@osfactory/otel-hook 0.13.2 → 0.14.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 (37) hide show
  1. package/README.md +43 -0
  2. package/dist/{adapter-DyCb7y1N.d.ts → adapter-D5R8lhfl.d.ts} +1 -1
  3. package/dist/cli.js +427 -37
  4. package/dist/cli.js.map +1 -1
  5. package/dist/config.d.ts +30 -4
  6. package/dist/config.js +161 -9
  7. package/dist/config.js.map +1 -1
  8. package/dist/{destinations-C4sSKjDO.d.ts → destinations-2KrcRslo.d.ts} +92 -2
  9. package/dist/{export-destinations-BjRXDots.d.ts → export-destinations-DvoH4QOe.d.ts} +101 -9
  10. package/dist/{hook-CKLpgrYP.d.ts → hook-DVK8Don-.d.ts} +4 -4
  11. package/dist/index.d.ts +10 -10
  12. package/dist/index.js +424 -36
  13. package/dist/index.js.map +1 -1
  14. package/dist/install.d.ts +3 -3
  15. package/dist/integration.d.ts +7 -7
  16. package/dist/integration.js +376 -34
  17. package/dist/integration.js.map +1 -1
  18. package/dist/lifecycle.js +1 -1
  19. package/dist/lifecycle.js.map +1 -1
  20. package/dist/{payload-DLK7QaBB.d.ts → payload-D4r71EL-.d.ts} +1 -1
  21. package/dist/privacy.d.ts +2 -2
  22. package/dist/privacy.js +42 -1
  23. package/dist/privacy.js.map +1 -1
  24. package/dist/providers.d.ts +8 -8
  25. package/dist/{registry-DM-4YvIA.d.ts → registry-DOJh9mzB.d.ts} +2 -2
  26. package/dist/runtime.d.ts +5 -5
  27. package/dist/runtime.js +128 -2
  28. package/dist/runtime.js.map +1 -1
  29. package/dist/{schema-CD61uW99.d.ts → schema-oRsbo7WO.d.ts} +45 -0
  30. package/dist/{service-CbI9CObT.d.ts → service-DySC7KQM.d.ts} +6 -1
  31. package/dist/telemetry.d.ts +5 -4
  32. package/dist/telemetry.js +285 -15
  33. package/dist/telemetry.js.map +1 -1
  34. package/dist/testing.d.ts +5 -5
  35. package/dist/testing.js +128 -2
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/config/schema.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/resource-attributes.ts","../src/model/identity.ts","../src/privacy/service.ts","../src/model/extensions.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/errors/index.ts","../src/providers/builder.ts","../src/providers/registry.ts","../src/providers/claude/capabilities.ts","../src/providers/claude/schema.ts","../src/providers/claude/usage.ts","../src/providers/claude/payload-normalize.ts","../src/providers/claude/delivery.ts","../src/providers/claude/detect.ts","../src/privacy/workspace.ts","../src/providers/claude/identity.ts","../src/providers/claude/stop-content.ts","../src/providers/claude/target.ts","../src/providers/claude/tool-kind.ts","../src/providers/claude/events.ts","../src/providers/claude/adapter.ts","../src/providers/claude/transcript.ts","../src/providers/cursor/payload.ts","../src/providers/cursor/delivery.ts","../src/providers/cursor/target.ts","../src/providers/cursor/usage.ts","../src/providers/cursor/adapter.ts","../src/providers/codex/payload.ts","../src/providers/codex/delivery.ts","../src/providers/codex/target.ts","../src/providers/codex/tool-kind.ts","../src/providers/codex/usage.ts","../src/providers/codex/version.ts","../src/providers/codex/adapter.ts","../src/providers/codex/rollout-usage.ts","../src/providers/gemini/delivery.ts","../src/providers/gemini/identity.ts","../src/providers/gemini/schema.ts","../src/providers/gemini/tool-kind.ts","../src/providers/gemini/usage.ts","../src/providers/gemini/adapter.ts","../src/providers/antigravity/payload.ts","../src/providers/antigravity/delivery.ts","../src/providers/antigravity/adapter.ts","../src/providers/antigravity/maturity.ts","../src/providers/defaults.ts","../src/runtime/clock.ts","../src/runtime/hook.ts","../src/runtime/delivery.ts","../src/runtime/ids.ts","../src/runtime/ports.ts","../src/runtime/logger.ts","../src/runtime/target-resolution.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/session-context.ts","../src/runtime/memory.ts","../src/testing/fixture-adapter.ts","../src/testing/assertions.ts","../src/testing/index.ts"],"sourcesContent":["import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n /**\n * The most time one hook invocation spends trying to reach one endpoint, in\n * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup\n * included) and the exporter's own retries inside it. A batch that does not\n * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:\n * the host agent waits for its hooks, so a down collector must not stall it.\n */\n exportBudgetMillis: z.number().int().min(50).max(600_000).optional(),\n /**\n * After an endpoint was unreachable (refused, timed out, or answered a\n * retryable status), every hook spools for it without trying for this long,\n * in milliseconds; then one hook probes it again. 0 disables the window.\n * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.\n */\n endpointDownMillis: z.number().int().min(0).max(3_600_000).optional(),\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\n/** Default `exporter.exportBudgetMillis`. */\nexport const DEFAULT_EXPORT_BUDGET_MILLIS = 1_500;\n/** Default `exporter.endpointDownMillis`. */\nexport const DEFAULT_ENDPOINT_DOWN_MILLIS = 30_000;\n\n/** The per-request OTLP timeout a hook uses: `timeoutMillis`, capped by the export budget. */\nexport const effectiveExportTimeoutMillis = (exporter: ExporterPolicy): number =>\n Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it.\n *\n * `codex.readRolloutUsage` is the same exception for Codex, which puts no token\n * counters on any hook payload: at `Stop` the runtime reads the session's\n * rollout (`transcript_path`) from a per-session cursor, bounded, and attaches\n * the thread's running token total (docs/usage-semantics.md).\n *\n * Both off by default: without them, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n codex: z\n .strictObject({\n readRolloutUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n codex: z.strictObject({ readRolloutUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n codex: Object.freeze({ readRolloutUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** Whether the runtime may read Codex rollouts at `Stop` (default false). */\nexport const readsCodexRolloutUsage = (config: OtelHookConfig): boolean =>\n config.providers?.codex?.readRolloutUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport type { ContentDisclosure } from \"../model/content.js\";\n\n/**\n * How much content the library is permitted to disclose.\n *\n * `omit` is the default and the only mode that requires no trust in the\n * downstream collector.\n */\nexport const contentModeSchema = z.enum([\"omit\", \"mask\", \"redact\", \"raw\"]);\nexport type ContentMode = z.infer<typeof contentModeSchema>;\n\nexport const CONTENT_MODE_DISCLOSURE: Readonly<Record<ContentMode, ContentDisclosure>> =\n Object.freeze({\n omit: \"omitted\",\n mask: \"masked\",\n redact: \"redacted\",\n raw: \"raw\",\n });\n\n/**\n * Default secret-key patterns, matched case-insensitively against object keys at\n * every depth. A key matching any of these has its value replaced before the\n * value itself is ever inspected.\n */\nexport const DEFAULT_SECRET_KEY_PATTERNS: readonly string[] = Object.freeze([\n \"(^|[._-])(secret|secrets)([._-]|$)\",\n \"(^|[._-])(token|tokens)([._-]|$)\",\n \"(^|[._-])(password|passwd|pwd)([._-]|$)\",\n \"(^|[._-])(credential|credentials)([._-]|$)\",\n \"(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)\",\n \"(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)\",\n \"(^|[._-])(cookie|set[._-]?cookie)([._-]|$)\",\n \"(^|[._-])(signature|sig)([._-]|$)\",\n]);\n\n/**\n * Default secret-value patterns applied to disclosed text in `redact` mode.\n * These are heuristics; they reduce accidental disclosure but are not a\n * substitute for `omit`.\n */\nexport const DEFAULT_SECRET_VALUE_PATTERNS: readonly string[] = Object.freeze([\n \"AKIA[0-9A-Z]{16}\",\n \"sk-[A-Za-z0-9_-]{16,}\",\n \"gh[pousr]_[A-Za-z0-9]{16,}\",\n \"xox[abprs]-[A-Za-z0-9-]{10,}\",\n \"-----BEGIN[A-Z ]*PRIVATE KEY-----\",\n \"eyJ[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\",\n \"(?:Bearer|Basic)\\\\s+[A-Za-z0-9._~+/=-]{12,}\",\n]);\n\nexport const privacyLimitsSchema = z.strictObject({\n /** Maximum characters of disclosed text per content fact or string value. */\n maxStringLength: z.number().int().min(0).max(65_536),\n /** Maximum nesting depth walked when sanitizing structured values. */\n maxDepth: z.number().int().min(1).max(32),\n /** Maximum array entries retained when sanitizing structured values. */\n maxArrayLength: z.number().int().min(1).max(4096),\n /** Maximum canonical events emitted per invocation. */\n maxEventsPerInvocation: z.number().int().min(1).max(10_000),\n /** Maximum object keys retained per level when sanitizing. */\n maxObjectKeys: z.number().int().min(1).max(1024),\n});\nexport type PrivacyLimits = z.infer<typeof privacyLimitsSchema>;\n\nexport const privacyPolicySchema = z.strictObject({\n contentMode: contentModeSchema,\n /**\n * `raw` mode is refused unless this is also true, so a single mistyped\n * environment variable cannot start exporting prompts.\n */\n allowRawContent: z.boolean(),\n /**\n * Salt mixed into every hash. A per-deployment salt makes hashes\n * non-correlatable across deployments; an empty salt makes them globally\n * comparable. Both are legitimate; the choice is explicit.\n */\n hashSalt: z.string().max(256),\n maskCharacter: z.string().length(1),\n redactionPlaceholder: z.string().min(1).max(64),\n secretKeyPatterns: z.array(z.string().min(1)).max(128).readonly(),\n secretValuePatterns: z.array(z.string().min(1)).max(128).readonly(),\n limits: privacyLimitsSchema,\n});\nexport type PrivacyPolicy = z.infer<typeof privacyPolicySchema>;\n\nexport const DEFAULT_PRIVACY_LIMITS: PrivacyLimits = Object.freeze({\n maxStringLength: 1024,\n maxDepth: 6,\n maxArrayLength: 64,\n maxEventsPerInvocation: 512,\n maxObjectKeys: 128,\n});\n\nexport const DEFAULT_PRIVACY_POLICY: PrivacyPolicy = Object.freeze({\n contentMode: \"omit\",\n allowRawContent: false,\n hashSalt: \"\",\n maskCharacter: \"*\",\n redactionPlaceholder: \"[redacted]\",\n secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,\n secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,\n limits: DEFAULT_PRIVACY_LIMITS,\n});\n\nexport type PolicyResolution = {\n readonly policy: PrivacyPolicy;\n /** Non-sensitive notes about deterministic downgrades that were applied. */\n readonly notes: readonly string[];\n};\n\n/**\n * Validate a policy and apply the one deterministic downgrade the library\n * enforces: `raw` without `allowRawContent` becomes `omit`.\n */\nexport const resolvePrivacyPolicy = (policy: PrivacyPolicy): PolicyResolution => {\n const parsed = privacyPolicySchema.parse(policy);\n if (parsed.contentMode === \"raw\" && !parsed.allowRawContent) {\n return {\n policy: { ...parsed, contentMode: \"omit\" },\n notes: [\"contentMode=raw downgraded to omit because allowRawContent is false\"],\n };\n }\n return { policy: parsed, notes: [] };\n};\n","import { z } from \"zod\";\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n },\n headers: { ...(destination.headers ?? {}) },\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n};\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","import { z } from \"zod\";\n\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\nimport { DEFAULT_SECRET_KEY_PATTERNS } from \"../privacy/policy.js\";\n\n/**\n * Custom OTLP **resource** attributes: facts about the emitting deployment\n * (`deployment.environment`, `service.instance.id`, a tenant label) that belong\n * on every span this installation exports.\n *\n * These are deliberately *not* {@link ConsumerAttributes}. Consumer attributes\n * are opaque per-invocation metadata that travels with one observation's\n * identity and is sanitized by the privacy service; resource attributes are\n * per-process exporter policy, resolved from configuration layers, and describe\n * the producer rather than the observation. The two never share a field name, a\n * flag, or a code path — see ADR 0001 on keeping identity out of configuration.\n */\n\n/** Upper bound on how many custom resource attributes one installation may set. */\nexport const MAX_RESOURCE_ATTRIBUTES = 64;\n/** Upper bound on a resource attribute key, matching the OpenTelemetry guidance. */\nexport const MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;\n/** Upper bound on a resource attribute value; values are repeated on every export. */\nexport const MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;\n\n/**\n * Accepted shape of a resource attribute key.\n *\n * Deliberately narrower than \"any string\": a key becomes an attribute name on\n * the wire, so restricting it to the OpenTelemetry naming vocabulary keeps\n * newlines, control characters, and arbitrary binary out of the exported\n * resource by construction.\n */\nexport const RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;\n\n/**\n * Keys that resource attributes may never set directly.\n *\n * `service.name` and `service.namespace` are typed exporter policy with their\n * own precedence chain and their own diagnostics. If a resource-attribute map\n * could also write them, the winner would depend on merge order inside the\n * exporter rather than on the documented configuration precedence — which is\n * exactly the silent override this reservation prevents. Supplying either one\n * through `OTEL_RESOURCE_ATTRIBUTES` still works: the environment parser routes\n * it to the policy field at a defined precedence instead of smuggling it into\n * the resource map.\n */\nexport const RESERVED_RESOURCE_ATTRIBUTE_KEYS: readonly string[] = Object.freeze([\n \"service.name\",\n \"service.namespace\",\n]);\n\n/** Case-insensitive: `Service.Name` is the same reservation, spelled differently. */\nexport const isReservedResourceAttributeKey = (key: string): boolean =>\n RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());\n\nconst SECRET_KEY_MATCHERS: readonly RegExp[] = Object.freeze(\n DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {\n try {\n return [new RegExp(source, \"i\")];\n } catch {\n return [];\n }\n }),\n);\n\n/**\n * Whether a key names something that should never be exported.\n *\n * A resource attribute is attached to *every* span, so `api_key=...` in a\n * config file or a shell profile would be the most durable possible leak. The\n * central privacy policy's key patterns are reused rather than re-invented, so\n * one list governs both content sanitization and this boundary.\n */\nexport const isSecretResourceAttributeKey = (key: string): boolean =>\n SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));\n\nexport type ResourceAttributeKeyRejection =\n | \"empty\"\n | \"too-long\"\n | \"malformed\"\n | \"reserved\"\n | \"secret-like\";\n\n/** Non-sensitive explanations. None of these ever quotes an attribute *value*. */\nexport const RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL: Readonly<\n Record<ResourceAttributeKeyRejection, string>\n> = Object.freeze({\n empty: \"resource attribute key is empty\",\n \"too-long\": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,\n malformed:\n \"resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`\",\n reserved:\n \"service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes\",\n \"secret-like\":\n \"resource attribute key matches a secret-name pattern, so it is never exported\",\n});\n\n/** Returns why a key is unusable, or `undefined` when it is acceptable. */\nexport const checkResourceAttributeKey = (\n key: string,\n): ResourceAttributeKeyRejection | undefined => {\n if (key.length === 0) {\n return \"empty\";\n }\n if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {\n return \"too-long\";\n }\n if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {\n return \"malformed\";\n }\n if (isReservedResourceAttributeKey(key)) {\n return \"reserved\";\n }\n if (isSecretResourceAttributeKey(key)) {\n return \"secret-like\";\n }\n return undefined;\n};\n\n/**\n * Resource attribute values are single primitives, never arrays.\n *\n * `OTEL_RESOURCE_ATTRIBUTES` cannot express an array, and allowing one only in\n * the file layer would make per-key precedence depend on which layer supplied a\n * key. A single primitive keeps the merge total and order-independent.\n */\nexport const resourceAttributeValueSchema = z.union([\n z.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type ResourceAttributeValue = z.infer<typeof resourceAttributeValueSchema>;\n\nexport const resourceAttributesSchema = z\n .record(z.string(), resourceAttributeValueSchema)\n .superRefine((value, ctx) => {\n const keys = Object.keys(value);\n if (keys.length > MAX_RESOURCE_ATTRIBUTES) {\n ctx.addIssue({\n code: \"custom\",\n message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`,\n });\n }\n for (const key of keys) {\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [key],\n message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection],\n });\n }\n }\n })\n .readonly();\nexport type ResourceAttributes = z.infer<typeof resourceAttributesSchema>;\n\nexport const EMPTY_RESOURCE_ATTRIBUTES: ResourceAttributes = Object.freeze({});\n\nexport type ParsedResourceAttributes = {\n readonly attributes: Readonly<Record<string, string>>;\n /** `service.name`, routed to exporter policy rather than into `attributes`. */\n readonly serviceName?: string;\n /** `service.namespace`, routed the same way. */\n readonly serviceNamespace?: string;\n /**\n * Why entries were skipped. Every message identifies an entry by its\n * *position*, never by quoting the entry — an ambient environment variable\n * may hold anything, and a diagnostic that echoes it would publish it.\n */\n readonly warnings: readonly string[];\n};\n\nconst stripSurroundingQuotes = (value: string): string =>\n value.length >= 2 && value.startsWith('\"') && value.endsWith('\"') ? value.slice(1, -1) : value;\n\n/**\n * Parse the standard `OTEL_RESOURCE_ATTRIBUTES` variable.\n *\n * The OpenTelemetry specification defines this as W3C Baggage: comma-separated\n * `key=value` pairs, optional whitespace around each part, an optional\n * `;`-delimited metadata suffix that carries no attribute meaning, and\n * **percent-encoded values**. Escaping is the part naive parsers get wrong, and\n * it is load-bearing here: without it `deployment.note=a%2Cb` silently becomes\n * two malformed entries, and `region=eu%2Dwest` keeps a literal `%2D`.\n *\n * Every rejection is reported and skipped rather than failing the whole\n * variable: a stale entry in a shell profile must not cost an operator the\n * attributes they got right, and must never disable telemetry (ADR 0004).\n */\nexport const parseResourceAttributesValue = (raw: string): ParsedResourceAttributes => {\n const attributes: Record<string, string> = {};\n const warnings: string[] = [];\n let serviceName: string | undefined;\n let serviceNamespace: string | undefined;\n let overflowed = false;\n\n const entries = raw.split(\",\");\n for (const [index, rawEntry] of entries.entries()) {\n const position = index + 1;\n // Baggage metadata (`key=value;prop=1`) carries no attribute meaning.\n const entry = (rawEntry.split(\";\")[0] ?? \"\").trim();\n if (entry === \"\") {\n continue;\n }\n\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${String(position)} is not a key=value pair`);\n continue;\n }\n const key = entry.slice(0, equals).trim();\n // Split on the *first* `=` only: a percent-decoded value may legitimately\n // contain one, and re-joining would be lossy.\n const encoded = stripSurroundingQuotes(entry.slice(equals + 1).trim());\n let value: string;\n try {\n value = decodeURIComponent(encoded);\n } catch {\n warnings.push(`entry ${String(position)} has a malformed percent-encoded value`);\n continue;\n }\n\n if (isReservedResourceAttributeKey(key)) {\n if (value.length === 0 || value.length > MAX_IDENTIFIER_LENGTH) {\n warnings.push(\n `entry ${String(position)} sets ${key.toLowerCase()} to an empty or over-long value`,\n );\n continue;\n }\n if (key.toLowerCase() === \"service.name\") {\n serviceName = value;\n } else {\n serviceNamespace = value;\n }\n continue;\n }\n\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n warnings.push(\n `entry ${String(position)} was skipped: ${RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]}`,\n );\n continue;\n }\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n // Dropped rather than truncated: a silently shortened attribute value is\n // a wrong fact, which is worse than a missing one.\n warnings.push(\n `entry ${String(position)} has a value longer than ${String(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH)} characters`,\n );\n continue;\n }\n if (!(key in attributes) && Object.keys(attributes).length >= MAX_RESOURCE_ATTRIBUTES) {\n overflowed = true;\n continue;\n }\n // A repeated key takes its last value, matching every other layer here.\n attributes[key] = value;\n }\n\n if (overflowed) {\n warnings.push(\n `more than ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes were supplied; the excess was dropped`,\n );\n }\n\n return {\n attributes,\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n warnings,\n };\n};\n\n/**\n * Drop anything that must not reach the exported resource.\n *\n * The schema already refuses these keys, but a {@link ExporterPolicy} can also\n * be hand-built by a library caller who never ran it through the schema. This\n * is the last gate before the wire, so it filters rather than trusts.\n */\nexport const sanitizeResourceAttributes = (\n attributes: ResourceAttributes,\n): Readonly<Record<string, ResourceAttributeValue>> => {\n const safe: Record<string, ResourceAttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (checkResourceAttributeKey(key) !== undefined) {\n continue;\n }\n if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n safe[key] = value;\n }\n return safe;\n};\n\n/**\n * Attribute *names* only, for a logged or exported configuration snapshot.\n *\n * Names are safe to disclose because they are already part of every exported\n * resource; values are not disclosed, because a value is the half an operator\n * may have filled with something they would not want in a log line.\n */\nexport const describeResourceAttributeNames = (\n attributes: ResourceAttributes,\n): readonly string[] => Object.keys(attributes).sort();\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 { createHash } from \"node:crypto\";\n\nimport type { ContentFact, ContentKind, ContentRole } from \"../model/content.js\";\nimport { isValidExtensionKey } from \"../model/extensions.js\";\nimport {\n attributeValueSchema,\n MAX_ATTRIBUTE_ARRAY_LENGTH,\n MAX_ATTRIBUTE_STRING_LENGTH,\n type AttributePrimitive,\n type Attributes,\n type AttributeValue,\n} from \"../model/primitives.js\";\nimport {\n CONTENT_MODE_DISCLOSURE,\n resolvePrivacyPolicy,\n type PrivacyLimits,\n type PrivacyPolicy,\n} from \"./policy.js\";\n\nexport type SanitizedValue =\n | string\n | number\n | boolean\n | null\n | readonly SanitizedValue[]\n | { readonly [key: string]: SanitizedValue };\n\nexport type SanitizeStats = {\n readonly truncatedStrings: number;\n readonly truncatedArrays: number;\n readonly truncatedObjects: number;\n readonly redactedKeys: number;\n readonly depthExceeded: number;\n readonly droppedValues: number;\n readonly circularReferences: number;\n};\n\nexport type SanitizeResult = {\n readonly value: SanitizedValue;\n readonly stats: SanitizeStats;\n};\n\nexport type DescribeContentInput = {\n readonly kind: ContentKind;\n readonly text: string;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type DescribeStructuredInput = {\n readonly kind: ContentKind;\n readonly value: unknown;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type SanitizeExtensionsResult = {\n readonly extensions: Record<string, AttributeValue>;\n readonly droppedKeys: readonly string[];\n};\n\n/**\n * Single point through which every piece of potentially sensitive data passes.\n *\n * Provider adapters receive this service and are expected to describe content\n * with it rather than copying text into events themselves. That keeps the\n * disclosure decision in one auditable place.\n */\nexport interface PrivacyService {\n readonly policy: PrivacyPolicy;\n /** Notes about deterministic policy downgrades applied at construction. */\n readonly policyNotes: readonly string[];\n /** Stable salted digest, formatted `sha256:<hex>`. */\n hash(value: string): string;\n /** Opaque namespaced handle suitable for a workspace or resource id. */\n deriveOpaqueId(namespace: string, value: string): string;\n describeContent(input: DescribeContentInput): ContentFact;\n /**\n * A content fact for a kind the event can carry when the provider sent no\n * text. Distinct from describing an empty string: there is nothing to\n * disclose under any content mode, so the fact is always omitted.\n */\n describeUnavailableContent(input: Omit<DescribeContentInput, \"text\">): ContentFact;\n describeStructured(input: DescribeStructuredInput): ContentFact;\n isSecretKey(key: string): boolean;\n sanitizeStructured(value: unknown): SanitizeResult;\n /** Attribute-safe projection of a sanitized value, with dotted paths. */\n flattenToAttributes(value: SanitizedValue, prefix: string): Attributes;\n sanitizeAttributes(value: Readonly<Record<string, unknown>>): Attributes;\n sanitizeExtensions(value: Readonly<Record<string, unknown>>): SanitizeExtensionsResult;\n /** Bound a string to the policy limit, reporting whether it was cut. */\n boundString(value: string): { readonly text: string; readonly truncated: boolean };\n}\n\nconst compilePatterns = (sources: readonly string[], flags: string): readonly RegExp[] => {\n const compiled: RegExp[] = [];\n for (const source of sources) {\n try {\n compiled.push(new RegExp(source, flags));\n } catch {\n // An unusable pattern must not disable the whole privacy service; the\n // remaining patterns still apply. Skipping is the conservative choice for\n // key patterns only because a bad pattern would otherwise match nothing\n // anyway.\n continue;\n }\n }\n return compiled;\n};\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst isSanitizedArray = (value: SanitizedValue): value is readonly SanitizedValue[] =>\n Array.isArray(value);\n\nconst sliceCodePoints = (value: string, max: number): string => {\n if (max <= 0) {\n return \"\";\n }\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input === \"bigint\") {\n return JSON.stringify(input.toString());\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${walk(record[key])}`)\n .join(\",\")}}`;\n };\n return walk(value);\n};\n\ntype MutableStats = {\n truncatedStrings: number;\n truncatedArrays: number;\n truncatedObjects: number;\n redactedKeys: number;\n depthExceeded: number;\n droppedValues: number;\n circularReferences: number;\n};\n\nconst emptyStats = (): MutableStats => ({\n truncatedStrings: 0,\n truncatedArrays: 0,\n truncatedObjects: 0,\n redactedKeys: 0,\n depthExceeded: 0,\n droppedValues: 0,\n circularReferences: 0,\n});\n\nexport const createPrivacyService = (policyInput: PrivacyPolicy): PrivacyService => {\n const { policy, notes } = resolvePrivacyPolicy(policyInput);\n const limits: PrivacyLimits = policy.limits;\n const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, \"i\");\n const secretValuePatterns = compilePatterns(policy.secretValuePatterns, \"g\");\n\n const hash = (value: string): string =>\n `sha256:${createHash(\"sha256\").update(policy.hashSalt).update(\"\\0\").update(value, \"utf8\").digest(\"hex\")}`;\n\n const isSecretKey = (key: string): boolean =>\n secretKeyPatterns.some((pattern) => pattern.test(key));\n\n const boundString = (value: string): { text: string; truncated: boolean } => {\n const length = codePointLength(value);\n if (length <= limits.maxStringLength) {\n return { text: value, truncated: false };\n }\n return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };\n };\n\n const redactSecretSpans = (value: string): { text: string; count: number } => {\n let count = 0;\n let text = value;\n for (const pattern of secretValuePatterns) {\n text = text.replace(new RegExp(pattern.source, pattern.flags), () => {\n count += 1;\n return policy.redactionPlaceholder;\n });\n }\n return { text, count };\n };\n\n const maskText = (value: string): string =>\n Array.from(value, (char) => (/\\s/.test(char) ? char : policy.maskCharacter)).join(\"\");\n\n const disclose = (\n original: string,\n ): { text: string | undefined; truncated: boolean; secretsRedacted: number } => {\n switch (policy.contentMode) {\n case \"omit\":\n return { text: undefined, truncated: false, secretsRedacted: 0 };\n case \"mask\": {\n const bounded = boundString(original);\n return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };\n }\n case \"redact\": {\n const redacted = redactSecretSpans(original);\n const bounded = boundString(redacted.text);\n return {\n text: bounded.text,\n truncated: bounded.truncated,\n secretsRedacted: redacted.count,\n };\n }\n case \"raw\": {\n const bounded = boundString(original);\n return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };\n }\n }\n };\n\n const describeText = (input: DescribeContentInput): ContentFact => {\n const disclosed = disclose(input.text);\n return {\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: codePointLength(input.text),\n byteLength: Buffer.byteLength(input.text, \"utf8\"),\n contentHash: hash(input.text),\n disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted,\n ...(input.label === undefined ? {} : { label: input.label }),\n };\n };\n\n const sanitizeValue = (value: unknown, depth: number, stats: MutableStats, seen: WeakSet<object>): SanitizedValue => {\n if (value === null) {\n return null;\n }\n switch (typeof value) {\n case \"string\": {\n const bounded = boundString(value);\n if (bounded.truncated) {\n stats.truncatedStrings += 1;\n }\n return bounded.text;\n }\n case \"number\":\n if (!Number.isFinite(value)) {\n stats.droppedValues += 1;\n return null;\n }\n return value;\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n stats.droppedValues += 1;\n return null;\n default:\n break;\n }\n\n if (depth >= limits.maxDepth) {\n stats.depthExceeded += 1;\n return \"<depth-exceeded>\";\n }\n if (seen.has(value)) {\n stats.circularReferences += 1;\n return \"<circular>\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const entries = value.slice(0, limits.maxArrayLength);\n if (value.length > limits.maxArrayLength) {\n stats.truncatedArrays += 1;\n }\n return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const retained = keys.slice(0, limits.maxObjectKeys);\n if (keys.length > limits.maxObjectKeys) {\n stats.truncatedObjects += 1;\n }\n const result: Record<string, SanitizedValue> = {};\n for (const key of retained) {\n if (isSecretKey(key)) {\n stats.redactedKeys += 1;\n result[key] = policy.redactionPlaceholder;\n continue;\n }\n result[key] = sanitizeValue(record[key], depth + 1, stats, seen);\n }\n return result;\n };\n\n const sanitizeStructured = (value: unknown): SanitizeResult => {\n const stats = emptyStats();\n const sanitized = sanitizeValue(value, 0, stats, new WeakSet<object>());\n return { value: sanitized, stats };\n };\n\n const toAttributePrimitive = (value: SanitizedValue): AttributePrimitive | undefined => {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return undefined;\n };\n\n const flattenToAttributes = (value: SanitizedValue, prefix: string): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n const walk = (current: SanitizedValue, path: string): void => {\n if (\n typeof current === \"string\" ||\n typeof current === \"number\" ||\n typeof current === \"boolean\"\n ) {\n const primitive = toAttributePrimitive(current);\n if (primitive !== undefined) {\n attributes[path] = primitive;\n }\n return;\n }\n if (current === null) {\n return;\n }\n if (isSanitizedArray(current)) {\n const primitives: AttributePrimitive[] = [];\n let uniform = true;\n for (const entry of current) {\n const entryPrimitive = toAttributePrimitive(entry);\n if (entryPrimitive === undefined) {\n uniform = false;\n break;\n }\n primitives.push(entryPrimitive);\n }\n if (uniform) {\n attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);\n return;\n }\n for (const [index, entry] of current.entries()) {\n walk(entry, `${path}.${index}`);\n }\n return;\n }\n for (const [key, entry] of Object.entries(current)) {\n walk(entry, path === \"\" ? key : `${path}.${key}`);\n }\n };\n walk(value, prefix);\n return attributes;\n };\n\n const sanitizeAttributes = (value: Readonly<Record<string, unknown>>): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isSecretKey(key)) {\n attributes[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const primitive = toAttributePrimitive(sanitized);\n if (primitive !== undefined) {\n attributes[key] = primitive;\n continue;\n }\n const flattened = flattenToAttributes(sanitized, key);\n Object.assign(attributes, flattened);\n }\n return attributes;\n };\n\n const sanitizeExtensions = (\n value: Readonly<Record<string, unknown>>,\n ): SanitizeExtensionsResult => {\n const extensions: Record<string, AttributeValue> = {};\n const droppedKeys: string[] = [];\n for (const [key, entry] of Object.entries(value)) {\n if (!isValidExtensionKey(key)) {\n droppedKeys.push(key);\n continue;\n }\n if (isSecretKey(key)) {\n extensions[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const candidate = attributeValueSchema.safeParse(sanitized);\n if (candidate.success) {\n extensions[key] = candidate.data;\n } else {\n droppedKeys.push(key);\n }\n }\n return { extensions, droppedKeys };\n };\n\n return {\n policy,\n policyNotes: notes,\n hash,\n deriveOpaqueId: (namespace: string, value: string): string =>\n hash(`${namespace}\\0${value}`),\n describeContent: describeText,\n describeUnavailableContent: (input: Omit<DescribeContentInput, \"text\">): ContentFact => ({\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: 0,\n byteLength: 0,\n contentHash: hash(\"\"),\n disclosure: \"omitted\",\n truncated: false,\n secretsRedacted: 0,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n describeStructured: (input: DescribeStructuredInput): ContentFact => {\n const serialized = stableStringify(input.value);\n const sanitized = sanitizeStructured(input.value);\n const base = describeText({\n kind: input.kind,\n text: serialized,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.label === undefined ? {} : { label: input.label }),\n });\n if (base.text === undefined) {\n return base;\n }\n // Disclose the sanitized projection rather than the raw serialization, so\n // secret-keyed values never appear even in `raw` mode.\n const disclosed = disclose(stableStringify(sanitized.value));\n return {\n ...base,\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: base.truncated || disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys,\n };\n },\n isSecretKey,\n sanitizeStructured,\n flattenToAttributes,\n sanitizeAttributes,\n sanitizeExtensions,\n boundString,\n };\n};\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 type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n canonicalEventTypeSchema,\n type CanonicalEvent,\n type CanonicalEventType,\n type ModelDescriptor,\n} from \"../model/events.js\";\nimport type { IdentityClaim, InvocationIdentity } from \"../model/identity.js\";\nimport type { TargetHint } from \"../model/target.js\";\nimport {\n detectionConfidenceSchema,\n nonEmptyStringSchema,\n providerIdSchema,\n resolvedProviderIdSchema,\n type EventId,\n type ProviderId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport { cacheCreationAccountingSchema, usageTemporalitySchema, type UsageTemporality } from \"../model/usage.js\";\nimport type { PrivacyLimits } from \"../privacy/policy.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport type { Clock, IdGenerator, Logger } from \"../runtime/ports.js\";\n\n/** Raw input offered to adapters. `payload` is `unknown` on purpose. */\nexport type ProviderDetectionInput = {\n /** Decoded but uninterpreted provider payload. Must not escape the adapter. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n /** Caller's assertion of the provider, e.g. from a CLI flag. */\n readonly providerHint?: string;\n};\n\nexport const providerDetectionSchema = z.strictObject({\n providerId: resolvedProviderIdSchema,\n confidence: detectionConfidenceSchema,\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.hook_event_name present\"`.\n * Reasons are exported in diagnostics, so they must not quote payload values.\n */\n reasons: z.array(z.string().min(1).max(160)).max(8),\n providerVersion: nonEmptyStringSchema.optional(),\n /** The provider's own name for this event, when the payload states one. */\n sourceEventName: nonEmptyStringSchema.optional(),\n});\nexport type ProviderDetection = z.infer<typeof providerDetectionSchema>;\n\n/**\n * How much of a provider's hook traffic carries an identifier that survives a\n * redelivery.\n *\n * - `none`: no callback carries one. Redelivery is undetectable from the\n * payload, and deduplication needs a host-supplied delivery id.\n * - `partial`: some callbacks do and some do not — typically per-tool-call and\n * per-turn events do, while session and compaction edges do not.\n * - `all`: every callback the adapter recognizes carries one.\n *\n * Declared rather than probed for the same reason as the usage capabilities\n * below: \"this callback has no stable id\" and \"this adapter never looked\" are\n * indistinguishable downstream, and only the first is safe to build on.\n */\nexport const deliveryIdentifierSupportSchema = z.enum([\"none\", \"partial\", \"all\"]);\nexport type DeliveryIdentifierSupport = z.infer<typeof deliveryIdentifierSupportSchema>;\n\n/**\n * Shape a delivery-identity component must have.\n *\n * Deliberately narrow. Provider identifiers, integer counters, hook event\n * names, and ISO-8601 timestamps all satisfy it; prose and filesystem paths do\n * not, because neither spaces nor `/` are allowed. So an adapter that\n * accidentally seeds a delivery identity with a prompt, a tool response, or a\n * home directory produces a *rejected claim* rather than a privacy incident —\n * the guard is structural, not a review convention.\n */\nexport const DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\n\nexport const deliveryComponentSchema = z\n .string()\n .regex(\n DELIVERY_COMPONENT_PATTERN,\n \"delivery component must be identifier-shaped: no whitespace, no path separators\",\n );\n\n/** Most identifier-shaped fields one callback identity may be built from. */\nexport const MAX_DELIVERY_COMPONENTS = 8;\n\n/**\n * An adapter's assertion that this callback has a replay-stable identity.\n *\n * The adapter reports *components* rather than a finished id: it knows which\n * payload fields are trustworthy, and the runtime owns how they are combined,\n * scoped, and digested. That split is what keeps a raw provider identifier from\n * becoming an on-disk key or a diagnostic attribute (see\n * `resolveDeliveryIdentity`).\n *\n * Returning nothing is always safe. Claiming an identity that is not actually\n * stable is not: it makes the runtime suppress a *genuine* second callback as if\n * it were a redelivery, which silently loses telemetry.\n */\nexport const providerDeliveryClaimSchema = z.strictObject({\n /**\n * The provider's own session/conversation id. Scopes the callback identity, so\n * two sessions reusing one tool-call id never collide.\n */\n sessionId: nonEmptyStringSchema,\n /** The provider's own name for this callback, e.g. `PostToolUse`. */\n sourceEventName: deliveryComponentSchema,\n /**\n * Identifier-shaped payload fields that, together with `sourceEventName`,\n * name this callback within the session exactly once.\n */\n components: z.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.tool_use_id names one\n * tool call\"`. Evidence reaches diagnostics, so it must name fields, never\n * quote their values.\n */\n evidence: z.array(z.string().min(1).max(160)).min(1).max(4).readonly(),\n});\nexport type ProviderDeliveryClaim = z.infer<typeof providerDeliveryClaimSchema>;\n\n/**\n * Shape a per-callback delivery *gap* explanation must have.\n *\n * These strings reach a diagnostic, so the same reasoning that constrains\n * {@link deliveryComponentSchema} applies for the opposite purpose: a component\n * must be identifier-shaped, a gap reason must be prose that cannot smuggle a\n * filesystem path or a newline-delimited payload dump into stderr. Spaces are\n * allowed — it is a sentence — and `/`, `\\`, and control characters are not,\n * which is what keeps a home directory out of a message an adapter author writes\n * by hand.\n */\nexport const DELIVERY_GAP_REASON_PATTERN = /^[^\\n\\r\\t\\\\/]{1,240}$/;\n\nexport const deliveryGapReasonSchema = z\n .string()\n .regex(\n DELIVERY_GAP_REASON_PATTERN,\n \"delivery gap reason must be one line of prose: no path separators, no control characters\",\n );\n\n/** Most callbacks one adapter may document a delivery gap for. */\nexport const MAX_DELIVERY_GAPS = 48;\n\n/**\n * Why each of an adapter's callbacks carries no replay-stable identity.\n *\n * Keyed by the provider's *own* event name — the same value `detect` reports as\n * `sourceEventName` — so the runtime can look up the reason for the callback in\n * front of it without parsing the payload a second time.\n *\n * This exists because `callback-not-identifiable` on its own is a true statement\n * that helps nobody: an operator auditing coverage with `--require-callback-id`\n * needs to know *which* callback and *what field would have to exist*, and only\n * the adapter knows that. Keeping it declarative rather than computed means the\n * answer is reviewable next to the protocol it describes, and an exhaustiveness\n * test can insist that adding a hook event without deciding its delivery status\n * reads as an omission.\n */\nexport const providerDeliveryGapsSchema = z\n .record(deliveryComponentSchema, deliveryGapReasonSchema)\n .refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {\n message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`,\n });\nexport type ProviderDeliveryGaps = z.infer<typeof providerDeliveryGapsSchema>;\n\n/**\n * What an adapter can actually observe.\n *\n * Capabilities are declared rather than probed so consumers can distinguish\n * \"this provider reports no cached tokens\" from \"this session used no cache\" —\n * the two look identical in the data.\n */\nexport const providerCapabilitiesSchema = z.strictObject({\n /** Event types the adapter can produce. */\n lifecycleEvents: z.array(canonicalEventTypeSchema).max(32).readonly(),\n usageTemporality: usageTemporalitySchema,\n /**\n * Which accumulator series a `cumulative` report continues — that is, which\n * previous snapshot the next one should be diffed against.\n *\n * Only meaningful when `usageTemporality` is `cumulative`; omit otherwise.\n *\n * - `event-scope` (the default when omitted) — each event scope keeps its own\n * running total, so a `generation.end` snapshot is diffed against the\n * previous snapshot *for that same generation*.\n * - `session-lifetime` — the provider maintains **one** running total for the\n * whole session and stamps it onto whichever callback happens to report it.\n * Diffing such a snapshot per event scope would restart the baseline on\n * every new generation id and re-count the entire session total each turn,\n * so session-level and generation-level snapshots share one baseline.\n * Subagent snapshots keep their own series regardless: a delegated agent's\n * counter is not a point on the parent session's curve.\n */\n cumulativeUsageSeries: z.enum([\"event-scope\", \"session-lifetime\"]).optional(),\n reportsCachedInput: z.boolean(),\n reportsCacheCreation: z.boolean(),\n cacheCreationAccounting: cacheCreationAccountingSchema,\n reportsReasoningOutput: z.boolean(),\n reportsProviderTotal: z.boolean(),\n reportsCost: z.boolean(),\n emitsSubagentEvents: z.boolean(),\n emitsCompactionEvents: z.boolean(),\n /** True when the provider reads a structured response from stdout. */\n requiresHookResponse: z.boolean(),\n /** How much of this provider's hook traffic is replay-identifiable. */\n deliveryIdentifier: deliveryIdentifierSupportSchema,\n});\nexport type ProviderCapabilities = z.infer<typeof providerCapabilitiesSchema>;\n\n/** Services an adapter is given. Note the absence of a filesystem or network. */\nexport type ProviderContext = {\n readonly privacy: PrivacyService;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n readonly logger: Logger;\n readonly limits: PrivacyLimits;\n};\n\nexport type ProviderIdentityInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n};\n\nexport type ProviderParseInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n /** Resolved by the core; adapters never resolve identity themselves. */\n readonly identity: InvocationIdentity;\n /**\n * First sequence number the adapter may use. Sequences must be assigned\n * consecutively from here so event ids stay stable across replays.\n */\n readonly sequenceBase: number;\n /**\n * The model this session last reported, as the core remembers it across\n * invocations (`session.start` or a `generation.*` edge with a known model).\n *\n * Read from the state store by the core and handed in, because an adapter must\n * not hold cross-invocation state itself (ADR 0006). Absent when no earlier\n * invocation of this session named a model, or when the store is unreadable.\n * An adapter whose generation callbacks carry no model id (Claude Code's\n * `Stop`) uses it instead of the `unknown` sentinel; one whose callbacks carry\n * their own model can ignore it.\n */\n readonly sessionModel?: ModelDescriptor;\n};\n\nexport type ProviderParseResult =\n | {\n readonly status: \"parsed\";\n readonly events: readonly CanonicalEvent[];\n readonly warnings?: readonly string[];\n /**\n * Where tool events pointed, keyed by event id (ADR 0008). The one\n * canonical value that carries local paths: the core resolves each into\n * the event's `target` and discards it. Use `EventFactory.targetHints()`.\n */\n readonly targetHints?: ReadonlyMap<EventId, TargetHint>;\n }\n /** The input was recognized but carries no telemetry. Not an error. */\n | { readonly status: \"ignored\"; readonly reason: string }\n | { readonly status: \"failed\"; readonly error: OtelHookErrorInfo };\n\nexport const providerHookResponseSchema = z.strictObject({\n /**\n * Always 0. A telemetry hook that can fail the host agent is a liability, so\n * the type forbids expressing anything else (ADR 0004).\n */\n exitCode: z.literal(0),\n /** Protocol response text. Omit to write nothing at all. */\n stdout: z.string().max(8192).optional(),\n /** Non-sensitive diagnostic text for stderr. */\n stderr: z.string().max(8192).optional(),\n /** Declares which of the two stdout contracts this response follows. */\n contract: z.enum([\"silent\", \"provider-protocol\"]),\n});\nexport type ProviderHookResponse = z.infer<typeof providerHookResponseSchema>;\n\n/** The silent response: nothing on stdout, success to the host. */\nexport const SILENT_HOOK_RESPONSE: ProviderHookResponse = Object.freeze({\n exitCode: 0 as const,\n contract: \"silent\" as const,\n});\n\nexport type ProviderHookResponseInput = {\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly detection?: ProviderDetection;\n readonly emittedEvents: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Contract every provider adapter implements.\n *\n * The four methods are deliberately separate: detection must be cheap and\n * side-effect free, identity must be expressible as claims the core can\n * arbitrate, parsing must be the only place that reads the payload, and the hook\n * response must be derivable from the outcome alone.\n */\nexport interface ProviderAdapter {\n readonly id: ProviderId;\n readonly version: string;\n readonly capabilities: ProviderCapabilities;\n /**\n * Report whether this adapter recognizes the input. Must not throw; must not\n * read files or the network. Return `none` rather than guessing.\n */\n detect(input: ProviderDetectionInput, context: ProviderContext): ProviderDetection;\n /**\n * Contribute identity claims. Returning fewer claims is always safe;\n * fabricating a session id is not.\n */\n identify(input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[];\n /**\n * Report this callback's replay-stable identity, when the payload carries one.\n *\n * Called before `parse`, must be cheap and side-effect free, and must not\n * throw. Return `undefined` whenever the payload's identifying fields are\n * absent or would not survive a redelivery — under-reporting costs\n * deduplication, over-reporting loses real telemetry.\n */\n deliveryIdentity?(\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): ProviderDeliveryClaim | undefined;\n /**\n * Why each callback that {@link ProviderAdapter.deliveryIdentity} declines\n * carries no replay-stable identity, keyed by the provider's own event name.\n *\n * Static data, not control flow: it never decides whether a callback is\n * deduplicated, only what the runtime can *say* when it is not. An adapter that\n * declares `deliveryIdentifier: \"none\"` should still populate this — the gap is\n * then the whole story, and \"the protocol has no request id\" is a far more\n * actionable diagnostic than \"not identifiable\".\n */\n readonly deliveryGaps?: ProviderDeliveryGaps;\n /** Interpret the payload into canonical events. */\n parse(input: ProviderParseInput, context: ProviderContext): ProviderParseResult;\n /** Provider-specific hook response for the given outcome. */\n hookResponse(input: ProviderHookResponseInput, context: ProviderContext): ProviderHookResponse;\n}\n\nexport const adapterSupports = (\n adapter: ProviderAdapter,\n eventType: CanonicalEventType,\n): boolean => adapter.capabilities.lifecycleEvents.includes(eventType);\n\nexport type AdapterDescription = {\n readonly id: ResolvedProviderId;\n readonly version: string;\n readonly lifecycleEvents: readonly string[];\n readonly usageTemporality: UsageTemporality;\n readonly deliveryIdentifier: DeliveryIdentifierSupport;\n};\n\nexport const describeAdapter = (adapter: ProviderAdapter): AdapterDescription => ({\n id: adapter.id,\n version: adapter.version,\n lifecycleEvents: [...adapter.capabilities.lifecycleEvents],\n usageTemporality: adapter.capabilities.usageTemporality,\n deliveryIdentifier: adapter.capabilities.deliveryIdentifier,\n});\n\n/**\n * Ask an adapter for a delivery claim, containing anything it does wrong.\n *\n * A `deliveryIdentity` that throws, or that returns a claim the schema rejects\n * (a component carrying prose, more components than the cap), degrades to \"no\n * stable identity available\" rather than failing the invocation: deduplication\n * is an optimization, and the host's telemetry is not.\n */\nexport const readDeliveryClaim = (\n adapter: ProviderAdapter,\n input: ProviderIdentityInput,\n context: ProviderContext,\n): { readonly claim?: ProviderDeliveryClaim; readonly rejection?: string } => {\n if (adapter.deliveryIdentity === undefined) {\n return {};\n }\n let candidate: ProviderDeliveryClaim | undefined;\n try {\n candidate = adapter.deliveryIdentity(input, context);\n } catch {\n return { rejection: `adapter ${adapter.id} threw while reporting a delivery identity` };\n }\n if (candidate === undefined) {\n return {};\n }\n const parsed = providerDeliveryClaimSchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 240),\n };\n }\n return { claim: parsed.data };\n};\n\n/**\n * Look up why this callback has no replay-stable identity, containing anything\n * the adapter got wrong.\n *\n * Validated on the way out rather than trusted, for the same reason a claim is:\n * the string ends up in a diagnostic an operator reads, and an adapter that pasted\n * a path or a payload excerpt into its own gap table must produce *no detail*\n * rather than a disclosure. Returning `undefined` costs a sentence of explanation\n * and nothing else — the reason code is reported either way.\n */\nexport const readDeliveryGap = (\n adapter: ProviderAdapter,\n sourceEventName: string | undefined,\n): string | undefined => {\n if (sourceEventName === undefined || adapter.deliveryGaps === undefined) {\n return undefined;\n }\n // A prototype-polluting event name must not reach a bare property read: the\n // event name comes from a payload, and `__proto__` is a string like any other.\n if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {\n return undefined;\n }\n const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);\n return parsed.success ? parsed.data : undefined;\n};\n\nexport const asProviderId = (value: string): ProviderId => providerIdSchema.parse(value);\n\nexport const unknownDetection = (\n reasons: readonly string[] = [\"no adapter recognized the input\"],\n): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: reasons.slice(0, 8),\n });\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { z } from \"zod\";\n\nimport { attributesSchema, epochMillisSchema, type Attributes } from \"../model/primitives.js\";\nimport {\n describeErrorCode,\n errorPhaseSchema,\n errorSeveritySchema,\n failurePostureSchema,\n otelHookErrorCodeSchema,\n type ErrorPhase,\n type OtelHookErrorCode,\n} from \"./taxonomy.js\";\n\nexport * from \"./taxonomy.js\";\n\n/**\n * Serializable, privacy-safe description of a failure.\n *\n * `message` is a fixed-vocabulary summary derived from the code and phase, never\n * a provider or exception string, because exception messages routinely contain\n * prompt text, file paths, and credentials. `details` is restricted to attribute\n * primitives for the same reason.\n */\nexport const otelHookErrorInfoSchema = z.strictObject({\n code: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n posture: failurePostureSchema,\n retryable: z.boolean(),\n message: z.string().min(1).max(512),\n details: attributesSchema.optional(),\n occurredAt: epochMillisSchema.optional(),\n});\nexport type OtelHookErrorInfo = z.infer<typeof otelHookErrorInfoSchema>;\n\nexport type CreateErrorInfoInput = {\n readonly code: OtelHookErrorCode;\n readonly phase: ErrorPhase;\n /** Short, non-sensitive detail, e.g. `\"2 adapters matched\"`. */\n readonly detail?: string;\n readonly details?: Attributes;\n readonly occurredAt?: number;\n};\n\nexport const createErrorInfo = (input: CreateErrorInfoInput): OtelHookErrorInfo => {\n const descriptor = describeErrorCode(input.code);\n const message =\n input.detail === undefined\n ? `${input.code} during ${input.phase}: ${descriptor.summary}`\n : `${input.code} during ${input.phase}: ${input.detail}`;\n return otelHookErrorInfoSchema.parse({\n code: descriptor.code,\n severity: descriptor.severity,\n phase: input.phase,\n posture: descriptor.posture,\n retryable: descriptor.retryable,\n message: message.slice(0, 512),\n ...(input.details === undefined ? {} : { details: input.details }),\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n\nexport class OtelHookError extends Error {\n public readonly info: OtelHookErrorInfo;\n\n public constructor(info: OtelHookErrorInfo) {\n super(info.message);\n this.name = \"OtelHookError\";\n this.info = info;\n }\n\n public static of(input: CreateErrorInfoInput): OtelHookError {\n return new OtelHookError(createErrorInfo(input));\n }\n}\n\nexport const isOtelHookError = (value: unknown): value is OtelHookError =>\n value instanceof OtelHookError;\n\n/**\n * Describe an arbitrary thrown value without disclosing its message.\n *\n * Only the constructor name crosses the boundary; the presence of a message is\n * reported as a boolean so operators can tell \"threw nothing useful\" from\n * \"threw something we deliberately did not log\".\n */\nexport const describeThrown = (\n thrown: unknown,\n): { readonly errorName: string; readonly hasMessage: boolean } => {\n if (thrown instanceof Error) {\n return {\n errorName: thrown.name.slice(0, 64) || \"Error\",\n hasMessage: typeof thrown.message === \"string\" && thrown.message.length > 0,\n };\n }\n return { errorName: typeof thrown, hasMessage: false };\n};\n\n/** Convert an unexpected throw into privacy-safe error info. */\nexport const errorInfoFromThrown = (\n thrown: unknown,\n input: { readonly code?: OtelHookErrorCode; readonly phase: ErrorPhase; readonly occurredAt?: number },\n): OtelHookErrorInfo => {\n if (isOtelHookError(thrown)) {\n return thrown.info;\n }\n const described = describeThrown(thrown);\n return createErrorInfo({\n code: input.code ?? \"internal-error\",\n phase: input.phase,\n detail: `contained ${described.errorName}`,\n details: { \"error.name\": described.errorName, \"error.has_message\": described.hasMessage },\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n","import { OtelHookError } from \"../errors/index.js\";\nimport {\n canonicalEventSchema,\n isTargetedEvent,\n type CanonicalEvent,\n type CompactionPerformedEvent,\n type ErrorRaisedEvent,\n type GenerationEndEvent,\n type GenerationStartEvent,\n type PromptSubmittedEvent,\n type SessionEndEvent,\n type SessionStartEvent,\n type SubagentEndEvent,\n type SubagentStartEvent,\n type ToolEndEvent,\n type ToolStartEvent,\n} from \"../model/events.js\";\nimport type { InvocationIdentity } from \"../model/identity.js\";\nimport type { EventId } from \"../model/primitives.js\";\nimport { subagentIdSchema, targetHintSchema, type TargetHint } from \"../model/target.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport type { ProviderContext } from \"./adapter.js\";\n\n/** Fields the factory supplies; an adapter never sets them itself. */\ntype ManagedFields =\n | \"schemaVersion\"\n | \"eventId\"\n | \"invocationId\"\n | \"sessionId\"\n | \"sequence\"\n | \"provenance\"\n | \"workspace\"\n | \"extensions\"\n | \"subagentId\"\n | \"contextAttributes\"\n | \"target\"\n | \"occurredAt\";\n\ntype Draft<TEvent extends CanonicalEvent> = Omit<TEvent, ManagedFields> & {\n /** Defaults to the clock reading at build time. */\n readonly occurredAt?: number;\n /** Sanitized and namespace-checked before it is attached. */\n readonly extensions?: Readonly<Record<string, unknown>>;\n /** Mixed into the derived event id when one event type repeats. */\n readonly idDiscriminator?: string;\n /**\n * Where an event pointed, for the core to resolve into a `target`\n * (ADR 0008). Accepted on `TARGETED_EVENT_TYPES` drafts only; never placed\n * on the event itself.\n */\n readonly targetHint?: TargetHint;\n};\n\nexport type CanonicalEventDraft =\n | Draft<SessionStartEvent>\n | Draft<SessionEndEvent>\n | Draft<PromptSubmittedEvent>\n | Draft<GenerationStartEvent>\n | Draft<GenerationEndEvent>\n | Draft<ToolStartEvent>\n | Draft<ToolEndEvent>\n | Draft<SubagentStartEvent>\n | Draft<SubagentEndEvent>\n | Draft<CompactionPerformedEvent>\n | Draft<ErrorRaisedEvent>;\n\n/**\n * Helper adapters use to emit canonical events.\n *\n * It owns every field that must stay consistent across an invocation —\n * identity, provenance, sequence numbering, derived event ids — so an adapter\n * cannot accidentally renumber a sequence or attach the wrong session. Sequences\n * are consecutive from `sequenceBase`, which keeps derived ids stable on replay.\n */\nexport interface EventFactory {\n build(draft: CanonicalEventDraft): CanonicalEvent;\n /** Events built so far, in build order. */\n events(): readonly CanonicalEvent[];\n /** Next sequence number that will be assigned. */\n nextSequence(): number;\n /** Extension keys rejected during building, for diagnostics. */\n droppedExtensionKeys(): readonly string[];\n /**\n * Target hints attached to built targeted events, keyed by event id. In-process\n * only: hand this to the core through `ProviderParseResult.targetHints`.\n */\n targetHints(): ReadonlyMap<EventId, TargetHint>;\n}\n\nexport type EventFactoryInput = {\n readonly identity: InvocationIdentity;\n readonly sequenceBase: number;\n readonly context: ProviderContext;\n /**\n * The provider's own id for the subagent this invocation runs inside, stamped\n * on every event built. A value that is not identifier-shaped is dropped rather\n * than failing the event: the event is still true without it.\n */\n readonly subagentId?: string;\n};\n\nexport const createEventFactory = (input: EventFactoryInput): EventFactory => {\n const { identity, context } = input;\n const built: CanonicalEvent[] = [];\n const dropped: string[] = [];\n const hints = new Map<EventId, TargetHint>();\n let sequence = input.sequenceBase;\n const subagentId =\n input.subagentId !== undefined && subagentIdSchema.safeParse(input.subagentId).success\n ? input.subagentId\n : undefined;\n\n return {\n build: (draft: CanonicalEventDraft): CanonicalEvent => {\n const { occurredAt, extensions, idDiscriminator, targetHint, ...drafted } = draft;\n // Managed fields are stripped even if an untyped caller supplied them: a\n // target is only ever the core's resolution, never an adapter's claim.\n const rest: Omit<typeof drafted, \"target\" | \"subagentId\"> = { ...drafted };\n delete (rest as { target?: unknown }).target;\n delete (rest as { subagentId?: unknown }).subagentId;\n // Session context is stamped by the core after parsing, never by an adapter.\n delete (rest as { contextAttributes?: unknown }).contextAttributes;\n\n const sanitized =\n extensions === undefined\n ? { extensions: {}, droppedKeys: [] as readonly string[] }\n : context.privacy.sanitizeExtensions(extensions);\n dropped.push(...sanitized.droppedKeys);\n\n const currentSequence = sequence;\n sequence += 1;\n\n const candidate = {\n ...rest,\n schemaVersion: CANONICAL_SCHEMA_VERSION,\n eventId: context.ids.newEventId({\n invocationId: identity.invocationId,\n sequence: currentSequence,\n eventType: rest.type,\n ...(idDiscriminator === undefined ? {} : { discriminator: idDiscriminator }),\n }),\n invocationId: identity.invocationId,\n sessionId: identity.sessionId,\n sequence: currentSequence,\n occurredAt: occurredAt ?? context.clock.now(),\n provenance: identity.provenance,\n workspace: identity.workspace,\n ...(subagentId === undefined ? {} : { subagentId }),\n extensions: sanitized.extensions,\n };\n\n const parsed = canonicalEventSchema.safeParse(candidate);\n if (!parsed.success) {\n throw OtelHookError.of({\n code: \"schema-validation-failed\",\n phase: \"parsing\",\n detail: `event ${rest.type} rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: { \"event.type\": rest.type, \"event.sequence\": currentSequence },\n });\n }\n built.push(parsed.data);\n if (targetHint !== undefined && isTargetedEvent(parsed.data)) {\n const hint = targetHintSchema.safeParse(targetHint);\n if (hint.success) {\n hints.set(parsed.data.eventId, hint.data);\n }\n }\n return parsed.data;\n },\n events: (): readonly CanonicalEvent[] => [...built],\n nextSequence: (): number => sequence,\n droppedExtensionKeys: (): readonly string[] => [...dropped],\n targetHints: (): ReadonlyMap<EventId, TargetHint> => new Map(hints),\n };\n};\n","import type { DetectionPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n DETECTION_CONFIDENCE_RANK,\n type ProviderId,\n} from \"../model/primitives.js\";\nimport {\n providerDetectionSchema,\n unknownDetection,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"./adapter.js\";\n\nexport type DetectionCandidate = {\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n};\n\nexport type RegistryDetectionResult =\n | {\n readonly status: \"selected\";\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"unknown\";\n readonly reason:\n | \"no-adapters-registered\"\n | \"no-candidates\"\n | \"below-minimum-confidence\"\n | \"provider-not-allowed\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"ambiguous\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n };\n\n/**\n * Immutable set of adapters.\n *\n * A registry is a value passed to the runtime, not a mutable module-level\n * singleton: two hooks in one process may legitimately be configured with\n * different adapter sets, and a global would let one silently reconfigure the\n * other.\n */\nexport interface ProviderRegistry {\n readonly adapters: readonly ProviderAdapter[];\n get(id: string): ProviderAdapter | undefined;\n detect(\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult;\n}\n\nexport const createProviderRegistry = (\n adapters: readonly ProviderAdapter[],\n): ProviderRegistry => {\n const byId = new Map<string, ProviderAdapter>();\n for (const adapter of adapters) {\n if (byId.has(adapter.id)) {\n throw createDuplicateAdapterError(adapter.id);\n }\n byId.set(adapter.id, adapter);\n }\n const frozen = Object.freeze([...adapters]);\n\n return {\n adapters: frozen,\n get: (id: string): ProviderAdapter | undefined => byId.get(id),\n detect: (\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult => {\n const errors: OtelHookErrorInfo[] = [];\n const candidates: DetectionCandidate[] = [];\n\n if (frozen.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-adapters-registered\",\n detection: unknownDetection([\"no adapters registered\"]),\n candidates,\n errors,\n };\n }\n\n // Reasons from adapters that recognized the callback well enough to\n // explain why they declined it — as opposed to one that never looked at\n // this payload shape at all. Kept only for the \"no-candidates\" outcome\n // below: a payload every adapter genuinely ignores should still read as\n // the generic message, but a payload one adapter recognized and rejected\n // (e.g. Cursor's own envelope contract) must not be flattened into that\n // same generic message — that is the difference between \"provider\n // unknown\" and \"provider known, payload rejected for a stated reason\",\n // and only the raw per-adapter `detect()` result carries the latter.\n const nearMisses: string[] = [];\n\n for (const adapter of frozen) {\n let detection: ProviderDetection;\n try {\n detection = providerDetectionSchema.parse(adapter.detect(input, context));\n } catch (thrown) {\n // A misbehaving adapter must not suppress its peers.\n errors.push(errorInfoFromThrown(thrown, { code: \"provider-adapter-failure\", phase: \"detection\" }));\n continue;\n }\n if (detection.confidence === \"none\") {\n for (const reason of detection.reasons) {\n const prefixed = `${adapter.id}: ${reason}`;\n nearMisses.push(prefixed.length <= 160 ? prefixed : `${prefixed.slice(0, 159)}…`);\n }\n continue;\n }\n if (detection.providerId !== adapter.id) {\n errors.push(\n createErrorInfo({\n code: \"provider-adapter-failure\",\n phase: \"detection\",\n detail: `adapter ${adapter.id} claimed provider id ${detection.providerId}`,\n details: { \"adapter.id\": adapter.id, \"detection.provider_id\": detection.providerId },\n }),\n );\n continue;\n }\n candidates.push({ adapter, detection });\n }\n\n if (candidates.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(nearMisses.length === 0 ? undefined : nearMisses.slice(0, 8)),\n candidates,\n errors,\n };\n }\n\n const bestRank = Math.max(\n ...candidates.map((candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence]),\n );\n const best = candidates.filter(\n (candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence] === bestRank,\n );\n\n if (best.length > 1) {\n return {\n status: \"ambiguous\",\n detection: unknownDetection([\n `${best.length} adapters matched at equal confidence`,\n ...best.map((candidate) => `candidate ${candidate.adapter.id}`),\n ]),\n candidates,\n errors,\n };\n }\n\n const [winner] = best;\n if (winner === undefined) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(),\n candidates,\n errors,\n };\n }\n\n if (bestRank < DETECTION_CONFIDENCE_RANK[policy.minimumConfidence]) {\n return {\n status: \"unknown\",\n reason: \"below-minimum-confidence\",\n detection: unknownDetection([\n `best confidence ${winner.detection.confidence} is below required ${policy.minimumConfidence}`,\n ]),\n candidates,\n errors,\n };\n }\n\n if (\n policy.allowedProviderIds.length > 0 &&\n !policy.allowedProviderIds.includes(winner.adapter.id)\n ) {\n return {\n status: \"unknown\",\n reason: \"provider-not-allowed\",\n detection: unknownDetection([`provider ${winner.adapter.id} is not in the allow-list`]),\n candidates,\n errors,\n };\n }\n\n return {\n status: \"selected\",\n adapter: winner.adapter,\n detection: winner.detection,\n candidates,\n errors,\n };\n },\n };\n};\n\nconst createDuplicateAdapterError = (id: ProviderId): Error =>\n new Error(`duplicate provider adapter id: ${id}`);\n\n/**\n * Built-in adapters.\n *\n * Empty by design in the core package: provider support is added by dedicated\n * adapter modules, and the core must remain testable without any of them.\n */\nexport const BUILT_IN_PROVIDERS: readonly ProviderAdapter[] = Object.freeze([]);\n","import type { ProviderCapabilities } from \"../adapter.js\";\n\n/**\n * What this adapter can actually observe from Claude Code hooks.\n *\n * Every value here is confirmed against Claude Code 2.1.220 — the CLI's own\n * hook-input schemas for what a callback carries, and 4,999 real `usage` objects\n * for what the counters mean. docs/claude-code-usage-contract.md records the\n * observations; the summary:\n *\n * - `reportsCachedInput`/`reportsCacheCreation` are true because the payload\n * schema *accepts* Anthropic's `message.usage` shape when a wrapping harness\n * attaches it. No hook callback in the protocol carries a token counter, and\n * this adapter never reads the transcript to find them; `transcript.ts` is the\n * bounded helper a wrapper calls to attach them (issue #64).\n * - `cacheCreationAccounting` is `included-in-input` because `input_tokens` is\n * the fresh portion only, so the adapter folds all three input buckets into one\n * inclusive total (see `usage.ts`).\n * - `reportsReasoningOutput` and `reportsProviderTotal` are false as an\n * **explicit exclusion, not an unknown**: 0 of 4,999 real usage objects carried\n * any reasoning-token or total-token key. Anthropic bills thinking tokens\n * inside `output_tokens` with nothing distinguishing them, and reports no grand\n * total for a canonical total to agree or disagree with.\n *\n * `contextTokensBefore` is excluded on the same footing, and has no capability\n * flag of its own to say so: neither compaction callback reports a context size,\n * so there is no figure to carry across the `PreCompact`/`PostCompact` boundary.\n * `PreCompact` states the exclusion when a harness attaches one anyway\n * (`events.ts`), and `ADAPTER-NOTE-002` records it.\n */\nexport const CLAUDE_CODE_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\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 ] as const),\n usageTemporality: \"delta\",\n reportsCachedInput: true,\n reportsCacheCreation: true,\n cacheCreationAccounting: \"included-in-input\",\n reportsReasoningOutput: false,\n reportsProviderTotal: false,\n reportsCost: false,\n emitsSubagentEvents: true,\n emitsCompactionEvents: true,\n // The hook is telemetry-only and must never influence Claude Code's own\n // permission/continuation decisions (ADR 0004: fail-open).\n requiresHookResponse: false,\n // Tool, subagent, and prompt callbacks carry a replay-stable id, and so does\n // the once-per-prompt `Stop` (`stop_hook_active: false`). Session, compaction,\n // and continuation stops do not. See `./delivery.ts` for which and why.\n deliveryIdentifier: \"partial\",\n});\n","import { z } from \"zod\";\n\n/**\n * Raw Claude Code hook payload shapes.\n *\n * Field names and event names are taken from Claude Code's published hooks\n * reference (`code.claude.com/docs/en/hooks`). Objects are intentionally\n * non-strict: an unrecognized field is ignored rather than rejected, so a\n * protocol addition does not break detection or parsing. Discriminants\n * (`hook_event_name`, and the enum-shaped fields we do constrain) are strict.\n */\n\n/** Fields Claude Code includes on effectively every hook invocation. */\nconst commonFields = {\n session_id: z.string().min(1),\n transcript_path: z.string().min(1).optional(),\n cwd: z.string().min(1).optional(),\n permission_mode: z.string().min(1).optional(),\n /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */\n prompt_id: z.string().min(1).optional(),\n /** Present when the hook fired while running inside a subagent. */\n agent_id: z.string().min(1).optional(),\n agent_type: z.string().min(1).optional(),\n};\n\n/**\n * Cache-creation tokens split by cache TTL.\n *\n * A *breakdown* of `cache_creation_input_tokens`, not tokens beside it: the two\n * sub-buckets summed to that counter in 4,999 of 4,999 real usage objects. See\n * `usage.ts` for why they are verified and never added, and\n * docs/claude-code-usage-contract.md (finding 3) for the capture.\n */\nexport const claudeCacheCreationSchema = z.object({\n ephemeral_5m_input_tokens: z.number().int().min(0).optional(),\n ephemeral_1h_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * One model request inside a turn that took more than one.\n *\n * Also a breakdown: the per-iteration counters summed to the outer counters\n * exactly, for all four fields, in every capture (finding 4).\n */\nexport const claudeUsageIterationSchema = z.object({\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * Anthropic Messages API usage shape, as a wrapping harness may attach it\n * after correlating a hook firing with the transcript.\n *\n * **No Claude Code hook callback carries this object.** Confirmed against the\n * CLI's own hook-input schemas at 2.1.220: not `Stop`, not `SubagentStop`, not\n * `PostCompact` — no hook event in the protocol reports a token counter at all\n * (docs/claude-code-usage-contract.md, finding 1). The tokens exist only at\n * `message.usage` in the transcript, and this adapter never reads the transcript\n * itself (AGENTS.md and ADR 0003: an adapter has no filesystem handle). So the\n * field is accepted only when a caller has already placed it on the payload, and\n * the shape mirrors `message.usage` exactly so a harness can attach what it read\n * without reshaping it — `readClaudeTranscriptTurn` / `attachClaudeTranscriptTurn`\n * (`transcript.ts`) are the bounded helper a wrapper can call to do that.\n *\n * `input_tokens` is the **fresh** portion of the prompt only; cache reads and\n * cache writes are separate, additive buckets (finding 2). `usage.ts` documents\n * the fold that turns those three into the canonical inclusive total.\n */\nexport const claudeUsageSchema = z.object({\n input_tokens: z.number().int().min(0),\n output_tokens: z.number().int().min(0),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n cache_creation: claudeCacheCreationSchema.optional(),\n iterations: z.array(claudeUsageIterationSchema).optional(),\n /**\n * Counters the canonical model has a home for but Claude Code never reports:\n * 0 of 4,999 real usage objects carried either (finding 5).\n *\n * Named here rather than left to the object's forward-compatible looseness so\n * that a harness attaching one gets told it was excluded, instead of watching\n * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.\n */\n total_tokens: z.number().int().min(0).optional(),\n reasoning_output_tokens: z.number().int().min(0).optional(),\n});\nexport type ClaudeUsage = z.infer<typeof claudeUsageSchema>;\n\nexport const sessionStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionStart\"),\n /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */\n source: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n session_title: z.string().min(1).optional(),\n});\nexport type SessionStartPayload = z.infer<typeof sessionStartPayloadSchema>;\n\nexport const sessionEndPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionEnd\"),\n /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */\n reason: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n end_reason: z.string().min(1).optional(),\n});\nexport type SessionEndPayload = z.infer<typeof sessionEndPayloadSchema>;\n\nexport const userPromptSubmitPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"UserPromptSubmit\"),\n prompt: z.string(),\n});\nexport type UserPromptSubmitPayload = z.infer<typeof userPromptSubmitPayloadSchema>;\n\nexport const preToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PreToolUsePayload = z.infer<typeof preToolUsePayloadSchema>;\n\nexport const postToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_response: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUsePayload = z.infer<typeof postToolUsePayloadSchema>;\n\nexport const postToolUseFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUseFailure\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n // Optional: a failure that names no message still ends its tool call. The\n // `error` spelling Claude Code 2.1.x sends is folded onto it by\n // `normalizeClaudeHookPayload`.\n tool_error: z.unknown().optional(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUseFailurePayload = z.infer<typeof postToolUseFailurePayloadSchema>;\n\nexport const permissionRequestPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PermissionRequest\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().min(1),\n});\nexport type PermissionRequestPayload = z.infer<typeof permissionRequestPayloadSchema>;\n\nexport const subagentStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStart\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n});\nexport type SubagentStartPayload = z.infer<typeof subagentStartPayloadSchema>;\n\nexport const subagentStopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStop\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n last_assistant_message: z.string().optional(),\n /** True when this stop fired because a hook continued the subagent's turn. */\n stop_hook_active: z.boolean().optional(),\n /**\n * The subagent run's tokens since its previous stop — harness- or\n * enricher-supplied, never upstream. Reported on the subagent's own\n * generation, never on the parent turn (issue #68).\n */\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: the subagent's model, from its transcript. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type SubagentStopPayload = z.infer<typeof subagentStopPayloadSchema>;\n\n/**\n * Compaction callbacks.\n *\n * The upstream contract at 2.1.220 is `PreCompact { trigger, custom_instructions }`\n * and `PostCompact { trigger, compact_summary }`. **Neither reports a token\n * count** — no context size before or after, no dropped-message count\n * (docs/claude-code-usage-contract.md, finding 6). The counters below are\n * accepted for a wrapping harness that computed them; they are not a claim that\n * Claude Code sends them, and `capabilities.ts` excludes `contextTokensBefore`\n * accordingly.\n *\n * `custom_instructions` and `compact_summary` are deliberately absent. The\n * summary is a model-generated précis of the conversation — content — and\n * compaction telemetry needs the trigger and the sizes, not the text. Both are\n * ignored by the object's forward-compatible looseness rather than read and\n * screened, so there is no path by which they could reach an event.\n */\nexport const preCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreCompact\"),\n /** Upstream values: manual | auto. Forward-compatible: any string. */\n trigger: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n compact_trigger: z.string().min(1).optional(),\n /**\n * Harness-supplied, never upstream. Reported as an explicit exclusion rather\n * than carried across the process boundary: see `events.ts`.\n */\n context_tokens_before: z.number().int().min(0).optional(),\n estimated_tokens_removed: z.number().int().min(0).optional(),\n});\nexport type PreCompactPayload = z.infer<typeof preCompactPayloadSchema>;\n\nexport const postCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostCompact\"),\n trigger: z.string().min(1).optional(),\n compact_trigger: z.string().min(1).optional(),\n /** Harness-supplied, never upstream; accepted here because one callback carries both. */\n context_tokens_before: z.number().int().min(0).optional(),\n context_tokens_after: z.number().int().min(0).optional(),\n dropped_message_count: z.number().int().min(0).optional(),\n usage: claudeUsageSchema.optional(),\n});\nexport type PostCompactPayload = z.infer<typeof postCompactPayloadSchema>;\n\nexport const stopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"Stop\"),\n /**\n * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK\n * result messages use `result` instead; `events.ts` reads both (and camelCase\n * `lastAssistantMessage`) through `extractClaudeAssistantText`.\n */\n last_assistant_message: z.string().optional(),\n /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */\n result: z.string().optional(),\n /**\n * True when this stop fired because a hook continued the turn.\n *\n * Required upstream, optional here. It is what separates the once-per-prompt\n * stop from a continuation stop, which is what lets `delivery.ts` deduplicate\n * the former without suppressing the latter.\n */\n stop_hook_active: z.boolean().optional(),\n usage: claudeUsageSchema.optional(),\n /**\n * The model that answered this turn — harness-supplied, never upstream.\n *\n * Claude Code's `Stop` carries no model id; the per-turn model sits only at\n * `message.model` in the transcript, beside `message.usage`. A wrapping harness\n * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here\n * with `usage`, and it becomes the generation's response model. An unusable\n * value (empty, over 256 characters, not a string) is dropped rather than\n * failing the whole payload: the turn is still worth reporting without it.\n */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /**\n * Harness-supplied, never upstream: whether `usage` covers only part of the\n * turn. `true` when it is the last model request alone (the tail fallback),\n * `false` when it sums every request since the previous stop. Exported as\n * `otelhook.usage.partial`; absent means the attacher did not say.\n */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopPayload = z.infer<typeof stopPayloadSchema>;\n\nexport const stopFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"StopFailure\"),\n /**\n * Matcher values: rate_limit | overloaded | authentication_failed |\n * oauth_org_not_allowed | billing_error | invalid_request | model_not_found\n * | server_error | max_output_tokens | unknown.\n */\n error_type: z.string().min(1),\n error_message: z.string().optional(),\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopFailurePayload = z.infer<typeof stopFailurePayloadSchema>;\n\nexport const claudeHookPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n userPromptSubmitPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n permissionRequestPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n postCompactPayloadSchema,\n stopPayloadSchema,\n stopFailurePayloadSchema,\n]);\nexport type ClaudeHookPayload = z.infer<typeof claudeHookPayloadSchema>;\n\n/** Every `hook_event_name` this adapter recognizes. */\nexport const CLAUDE_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"SessionEnd\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"PermissionRequest\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"PreCompact\",\n \"PostCompact\",\n \"Stop\",\n \"StopFailure\",\n] as const;\nexport type ClaudeHookEventName = (typeof CLAUDE_HOOK_EVENT_NAMES)[number];\n\n/**\n * Minimal shape identity resolution needs. Deliberately looser than\n * {@link claudeHookPayloadSchema}: a payload that is missing an\n * event-specific field (e.g. `PreToolUse` without `tool_use_id`) can still be\n * attributed to a session, so the deeper failure surfaces from `parse`\n * instead of silently declining attribution.\n */\nexport const claudeIdentityFieldsSchema = z.object({\n session_id: z.string().min(1),\n hook_event_name: z.string().min(1),\n cwd: z.string().min(1).optional(),\n prompt_id: z.string().min(1).optional(),\n agent_id: z.string().min(1).optional(),\n tool_use_id: z.string().min(1).optional(),\n /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */\n stop_hook_active: z.boolean().optional(),\n});\nexport type ClaudeIdentityFields = z.infer<typeof claudeIdentityFieldsSchema>;\n","import { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\nimport { claudeUsageSchema, type ClaudeUsage } from \"./schema.js\";\n\nexport type ClaudeUsageNormalization = {\n readonly usage?: CanonicalUsage;\n readonly warnings: readonly string[];\n};\n\n/**\n * Counters this adapter deliberately does not read.\n *\n * Both are absent from Claude Code's usage shape — 0 of 4,999 real usage objects\n * carried either (docs/claude-code-usage-contract.md, finding 5) — and both have\n * a home in the canonical model, which is exactly why reading a\n * harness-supplied one would be wrong: `providerTotalAgreement` would start\n * reporting `agrees`/`disagrees` for a provider that reports no total, and\n * `reasoningOutputTokens` would carry a figure `reportsReasoningOutput: false`\n * says does not exist. A consumer's ability to tell \"not reported\" from \"zero\"\n * depends on the capability declaration staying true.\n *\n * So the field is excluded and *said out loud*, rather than silently dropped.\n */\nexport const CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({\n total_tokens:\n \"usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): \" +\n \"it is not read, so providerTotalAgreement stays \\\"unreported\\\"\",\n reasoning_output_tokens:\n \"usage.reasoning_output_tokens is outside Claude Code's usage contract (capability \" +\n \"reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate \" +\n \"counter, so it is not read and reasoningOutputTokens stays 0\",\n});\n\n/** The four counters `usage.iterations[]` itemizes, and the outer fields they must match. */\nconst ITERATION_COUNTERS = [\n \"input_tokens\",\n \"output_tokens\",\n \"cache_read_input_tokens\",\n \"cache_creation_input_tokens\",\n] as const;\n\n/**\n * Cache-creation tokens split by TTL, or `undefined` when the split is absent.\n *\n * The two sub-buckets summed to `cache_creation_input_tokens` in every capture,\n * so this is a *breakdown* to reconcile against, never an addend.\n */\nconst ttlSplitTotal = (raw: ClaudeUsage): number | undefined => {\n const split = raw.cache_creation;\n if (split === undefined) {\n return undefined;\n }\n return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);\n};\n\n/**\n * Settle on one cache-creation figure from the two places it can be stated.\n *\n * The explicit counter wins when both are present: it is the billed total, and\n * preferring a sum of parts over a stated whole would let a future third TTL\n * bucket silently deflate it. A disagreement is reported rather than resolved\n * quietly, because only one of the two numbers can be the billing story.\n */\nconst resolveCacheCreationTokens = (raw: ClaudeUsage, warnings: string[]): number => {\n const declared = raw.cache_creation_input_tokens;\n const split = ttlSplitTotal(raw);\n if (declared === undefined) {\n // Only the TTL split was attached. Deriving the total is the whole point of\n // accepting the sub-object: the tokens were reported, just itemized.\n return split ?? 0;\n }\n if (split !== undefined && split !== declared) {\n warnings.push(\n `usage.cache_creation TTL buckets sum to ${String(split)} but ` +\n `usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the ` +\n `buckets are never added to it`,\n );\n }\n return declared;\n};\n\n/**\n * Reconcile `usage.iterations[]` against the outer counters without adding it.\n *\n * A multi-request turn itemizes the same tokens per model request, and the\n * per-iteration figures summed to the outer ones exactly in every capture. Adding\n * a breakdown to its own total is the archetypal double-count — it would double\n * every counter of every turn — so the sums are *checked* and a disagreement is\n * reported, which is the only reading under which either number could be wrong.\n */\nconst auditIterations = (\n raw: ClaudeUsage,\n cacheCreationInputTokens: number,\n warnings: string[],\n): void => {\n const iterations = raw.iterations;\n if (iterations === undefined || iterations.length === 0) {\n return;\n }\n const outer: Readonly<Record<(typeof ITERATION_COUNTERS)[number], number>> = {\n input_tokens: raw.input_tokens,\n output_tokens: raw.output_tokens,\n cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,\n cache_creation_input_tokens: cacheCreationInputTokens,\n };\n for (const counter of ITERATION_COUNTERS) {\n const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);\n if (summed !== outer[counter]) {\n warnings.push(\n `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ` +\n `${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`,\n );\n }\n }\n};\n\nconst auditExcludedCounters = (raw: ClaudeUsage, warnings: string[]): void => {\n if (raw.total_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);\n }\n if (raw.reasoning_output_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);\n }\n};\n\n/**\n * `normalizeUsage` notes when a caller declared a cache-creation accounting mode\n * on a snapshot with zero cache-creation tokens. That note is aimed at a caller\n * choosing the mode per observation; this adapter's mode is a fixed property of\n * the provider, so on any turn that wrote nothing to cache the note restates the\n * design rather than reporting anything. It would fire on most turns and bury the\n * warnings that do mean something, so it is dropped here — by prefix, so a note\n * this adapter has not considered still reaches the caller.\n */\nconst ACCOUNTING_RETAINED_NOTE_PREFIX = \"cacheCreationAccounting=\";\n\nconst forwardableNotes = (notes: readonly string[]): readonly string[] =>\n notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));\n\n/**\n * Normalize Anthropic's on-wire usage shape into canonical usage.\n *\n * `input_tokens` is the *fresh* portion of the prompt only: cache reads and cache\n * writes are separate, additive buckets. Confirmed against real captures rather\n * than assumed — across 4,999 usage objects `input_tokens` stayed within\n * 1..5,656 while `cache_read_input_tokens` reached 713,543\n * (docs/claude-code-usage-contract.md, finding 2). The canonical model instead\n * wants an inclusive `inputTokens`, so this folds all three into one total and\n * marks cache creation `included-in-input` — `uncachedInputTokens` then falls out\n * to exactly Anthropic's own `input_tokens`.\n *\n * The fold is what makes the canonical buckets **non-overlapping by\n * construction**: each subset is one of the addends of the total it is a subset\n * of, so no subset can exceed its total and no bucket is counted twice. That\n * holds structurally, not by a range check a provider change could invalidate.\n * The two places tokens are *itemized* rather than reported — the cache-creation\n * TTL split and `iterations[]` — are reconciled against the totals and never\n * added, which is where a double-count would otherwise come from within a single\n * callback. Double-counting *across* callbacks is the delivery layer's job; see\n * `delivery.ts`.\n *\n * Each usage snapshot corresponds to a single turn, subagent invocation, or\n * compaction — never a running session total — so it is always reported as a\n * `delta` observation.\n */\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst asNonNegativeInt = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : undefined;\n\n/**\n * Coerce one usage-shaped object onto {@link claudeUsageSchema}.\n *\n * Accepts the Anthropic Messages API snake_case counters and the camelCase\n * aliases a print/`-p` result or wrapping harness may use. Both `input_tokens`\n * and `output_tokens` must be present — a lone counter is not a usage object,\n * and inventing the missing side as zero would report tokens the provider\n * never sent.\n */\nexport const coerceClaudeUsage = (value: unknown): ClaudeUsage | undefined => {\n const record = asRecord(value);\n if (record === undefined) {\n return undefined;\n }\n const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);\n const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);\n if (inputTokens === undefined || outputTokens === undefined) {\n return undefined;\n }\n const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);\n const parsed = claudeUsageSchema.safeParse({\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n ...(asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) ===\n undefined\n ? {}\n : {\n cache_creation_input_tokens: asNonNegativeInt(\n record.cache_creation_input_tokens ?? record.cacheCreationInputTokens,\n ),\n }),\n ...(asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === undefined\n ? {}\n : {\n cache_read_input_tokens: asNonNegativeInt(\n record.cache_read_input_tokens ?? record.cacheReadInputTokens,\n ),\n }),\n ...(cacheCreation === undefined\n ? {}\n : {\n cache_creation: {\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_5m_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ),\n }),\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_1h_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ),\n }),\n },\n }),\n ...(Array.isArray(record.iterations) ? { iterations: record.iterations } : {}),\n ...(asNonNegativeInt(record.total_tokens ?? record.totalTokens) === undefined\n ? {}\n : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) }),\n ...(asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) ===\n undefined\n ? {}\n : {\n reasoning_output_tokens: asNonNegativeInt(\n record.reasoning_output_tokens ?? record.reasoningOutputTokens,\n ),\n }),\n });\n return parsed.success ? parsed.data : undefined;\n};\n\n/**\n * Find a usage object on a Stop / print-result / SessionEnd payload.\n *\n * Looks at `usage`, `token_usage`, `message.usage`, and top-level token\n * counters. The first object that coerces to {@link ClaudeUsage} wins. Absence\n * is reported as `undefined` — never as a zeroed snapshot.\n */\nexport const extractClaudeUsage = (payload: unknown): ClaudeUsage | undefined => {\n const record = asRecord(payload);\n if (record === undefined) {\n return undefined;\n }\n const message = asRecord(record.message);\n const candidates: readonly unknown[] = [\n record.usage,\n record.token_usage,\n record.tokenUsage,\n message?.usage,\n record,\n ];\n for (const candidate of candidates) {\n const usage = coerceClaudeUsage(candidate);\n if (usage !== undefined) {\n return usage;\n }\n }\n return undefined;\n};\n\nexport const normalizeClaudeUsage = (raw: ClaudeUsage | undefined): ClaudeUsageNormalization => {\n if (raw === undefined) {\n return { warnings: [] };\n }\n\n const warnings: string[] = [];\n const cachedInputTokens = raw.cache_read_input_tokens ?? 0;\n const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);\n auditIterations(raw, cacheCreationInputTokens, warnings);\n auditExcludedCounters(raw, warnings);\n\n const result = normalizeUsage({\n temporality: \"delta\",\n inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: \"included-in-input\",\n outputTokens: raw.output_tokens,\n });\n\n if (result.status === \"invalid\") {\n return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };\n }\n return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };\n};\n","import { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Fold Claude Code hook and print/`-p` payload aliases onto the snake_case\n * shapes {@link claudeHookPayloadSchema} already accepts.\n *\n * Interactive Stop payloads document `last_assistant_message`. Print / `-p` /\n * Agent SDK result messages use `type: \"result\"` and `result` instead, and some\n * wrappers emit camelCase field names. None of these are invented: each alias\n * is a name Claude Code or its published result JSON has actually used. An\n * unrecognized shape is returned unchanged so detection can decline it.\n */\n\nconst FIELD_ALIASES = Object.freeze({\n hookEventName: \"hook_event_name\",\n sessionId: \"session_id\",\n lastAssistantMessage: \"last_assistant_message\",\n transcriptPath: \"transcript_path\",\n promptId: \"prompt_id\",\n toolUseId: \"tool_use_id\",\n toolName: \"tool_name\",\n toolInput: \"tool_input\",\n toolResponse: \"tool_response\",\n toolError: \"tool_error\",\n stopHookActive: \"stop_hook_active\",\n agentId: \"agent_id\",\n agentType: \"agent_type\",\n errorType: \"error_type\",\n errorMessage: \"error_message\",\n tokenUsage: \"token_usage\",\n} as const);\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/**\n * Copy documented camelCase aliases onto their snake_case names when the\n * snake_case field is absent. Existing snake_case values win, so a payload that\n * carries both is not rewritten.\n */\nconst applyFieldAliases = (record: Record<string, unknown>): Record<string, unknown> => {\n const normalized: Record<string, unknown> = { ...record };\n for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {\n if (normalized[canonical] === undefined && normalized[alias] !== undefined) {\n normalized[canonical] = normalized[alias];\n }\n }\n return normalized;\n};\n\n/**\n * Claude Code print / `-p` / Agent SDK result messages are not hook events, but\n * they are the stop/result payload a non-interactive session actually produces.\n * When one arrives with a session id and no `hook_event_name`, treat it as the\n * Stop (or StopFailure) the interactive protocol would have fired.\n */\nconst applyPrintResultShape = (record: Record<string, unknown>): Record<string, unknown> => {\n if (record.hook_event_name !== undefined || record.type !== \"result\") {\n return record;\n }\n if (typeof record.session_id !== \"string\" || record.session_id.length === 0) {\n return record;\n }\n\n const isError = record.subtype === \"error\" || record.is_error === true;\n const normalized: Record<string, unknown> = {\n ...record,\n hook_event_name: isError ? \"StopFailure\" : \"Stop\",\n };\n if (\n normalized.last_assistant_message === undefined &&\n typeof record.result === \"string\" &&\n record.result.length > 0\n ) {\n normalized.last_assistant_message = record.result;\n }\n if (isError && (typeof normalized.error_type !== \"string\" || normalized.error_type.length === 0)) {\n normalized.error_type = \"unknown\";\n }\n return normalized;\n};\n\n/**\n * Return a Claude-shaped payload with documented aliases folded onto canonical\n * field names, or the original value when it is not an object.\n */\nexport const normalizeClaudeHookPayload = (payload: unknown): unknown => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));\n};\n\n/**\n * Claude Code 2.1.x sends a failed tool's message as `error` on\n * `PostToolUseFailure` (observed in the agent lab), not the `tool_error` an\n * earlier contract named. Fold it onto `tool_error` for that event only, so the\n * failure still ends its tool span; `tool_error` wins when both are present.\n */\nconst applyToolFailureShape = (record: Record<string, unknown>): Record<string, unknown> => {\n if (\n record.hook_event_name !== \"PostToolUseFailure\" ||\n record.tool_error !== undefined ||\n record.error === undefined\n ) {\n return record;\n }\n return { ...record, tool_error: record.error };\n};\n\n/**\n * Coerce `usage` / `token_usage` onto the Anthropic snake_case object the\n * Stop schema accepts, so a camelCase print-result usage object is not\n * rejected as an invalid `usage` field.\n */\nconst applyUsageShape = (record: Record<string, unknown>): Record<string, unknown> => {\n const usage =\n coerceClaudeUsage(record.usage) ??\n coerceClaudeUsage(record.token_usage) ??\n coerceClaudeUsage(record.tokenUsage);\n if (usage === undefined) {\n return record;\n }\n return { ...record, usage };\n};\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { claudeIdentityFieldsSchema } from \"./schema.js\";\n\n/**\n * Which Claude Code callbacks carry an identifier that survives a redelivery.\n *\n * Grounded in the fields the hook payloads actually carry — the CLI's own\n * hook-input schemas at 2.1.220, recorded in\n * docs/claude-code-usage-contract.md:\n *\n * - `tool_use_id` is required on `PreToolUse`, `PostToolUse`,\n * `PostToolUseFailure`, and `PermissionRequest`. It names one tool call, and\n * the event name separates the pre-edge from the post-edge of that same call.\n * - `agent_id` is required on `SubagentStart`/`SubagentStop` and names one\n * subagent instance.\n * - `prompt_id` correlates a firing with the prompt that triggered it, and\n * exactly one `UserPromptSubmit` exists per prompt.\n * - `stop_hook_active` is required on `Stop` and `SubagentStop`, and is `false`\n * exactly on the once-per-turn stop (finding 7).\n *\n * ## Why `Stop` is claimable at all now\n *\n * `Stop` carries usage, so a redelivered one double-counts a turn's tokens —\n * the worst outcome on this list, because a corrupted total cannot be\n * reconstructed. But `prompt_id` alone cannot separate a redelivery from a\n * genuine second stop: Claude Code fires `Stop` again when a hook continues the\n * turn. `stop_hook_active` is precisely that distinction, so the once-per-prompt\n * stop (`stop_hook_active: false`) is claimed and every continuation stop stays\n * unidentifiable.\n *\n * The gate is deliberately one-sided. Two continuation stops both report\n * `stop_hook_active: true`, so claiming an identity for them would suppress a\n * real second firing and lose its tokens — a certain loss to avoid a possible\n * double-count, which is the wrong trade in this direction (see\n * `providerDeliveryClaimSchema`). A payload that omits the field predates the\n * flag or came from a wrapper, and is likewise declined rather than guessed at.\n *\n * The same reasoning fixes an inversion on `SubagentStop`, which was keyed on\n * `agent_id` alone: a hook-continued subagent stop repeats `agent_id`, so it\n * would have been suppressed as a redelivery and its usage lost. It now declines\n * when `stop_hook_active` is `true`, and keeps `agent_id` otherwise — including\n * when the field is absent, which is the pre-existing coverage and the case where\n * `agent_id` genuinely names one stop.\n *\n * Everything else is deliberately excluded. `StopFailure` reports no\n * `stop_hook_active` upstream at all. `SessionStart`, `SessionEnd`, `PreCompact`,\n * and `PostCompact` carry nothing that distinguishes a redelivery from a real\n * second firing.\n */\nconst TOOL_SCOPED_EVENTS: readonly string[] = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"PermissionRequest\",\n];\n\nexport const claudeDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));\n if (!parsed.success) {\n return undefined;\n }\n const fields = parsed.data;\n const base = { sessionId: fields.session_id, sourceEventName: fields.hook_event_name };\n\n if (TOOL_SCOPED_EVENTS.includes(fields.hook_event_name) && fields.tool_use_id !== undefined) {\n return {\n ...base,\n components: [fields.tool_use_id],\n evidence: [\"payload.tool_use_id names one tool call and repeats on redelivery\"],\n };\n }\n\n if (fields.hook_event_name === \"SubagentStart\" && fields.agent_id !== undefined) {\n return {\n ...base,\n components: [fields.agent_id],\n evidence: [\"payload.agent_id names one subagent instance\"],\n };\n }\n\n if (\n fields.hook_event_name === \"SubagentStop\" &&\n fields.agent_id !== undefined &&\n fields.stop_hook_active !== true\n ) {\n return {\n ...base,\n components: [fields.agent_id],\n evidence: [\n \"payload.agent_id names one subagent instance\",\n \"payload.stop_hook_active is not true, so this is not a hook-continued second stop\",\n ],\n };\n }\n\n if (fields.hook_event_name === \"UserPromptSubmit\" && fields.prompt_id !== undefined) {\n return {\n ...base,\n components: [fields.prompt_id],\n evidence: [\"payload.prompt_id names one prompt, submitted exactly once\"],\n };\n }\n\n if (\n fields.hook_event_name === \"Stop\" &&\n fields.prompt_id !== undefined &&\n fields.stop_hook_active === false\n ) {\n return {\n ...base,\n // `agent_id` is present when the stop fired inside a subagent, where the\n // prompt is shared with the main thread's own stop.\n components:\n fields.agent_id === undefined\n ? [fields.prompt_id]\n : [fields.prompt_id, fields.agent_id],\n evidence: [\n \"payload.prompt_id names one prompt\",\n \"payload.stop_hook_active is false, so this is the once-per-prompt stop rather than a continuation\",\n ],\n };\n }\n\n return undefined;\n};\n\n/**\n * Why each remaining Claude Code callback carries no delivery identity, and what\n * would have to exist for it to.\n *\n * Reported through `readDeliveryGap` when `requireCallbackId` is set, so an\n * operator auditing coverage reads the actual protocol reason instead of\n * \"callback-not-identifiable\". Kept exhaustive over\n * {@link CLAUDE_HOOK_EVENT_NAMES} — every event is either identified above or\n * explained here, so adding a hook event without deciding its delivery status\n * reads as an omission rather than passing silently.\n *\n * The four tool events and the two subagent events appear here too, because their\n * identifying field is *optional in practice*: a payload that omits `tool_use_id`\n * or `agent_id` reaches the same dead end as an event that never had one, and the\n * diagnostic should say which field is missing rather than blame the event.\n */\nexport const CLAUDE_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n SessionStart:\n \"no per-firing id; payload `source` (startup, resume, clear, compact, fork) means SessionStart fires repeatedly under one session_id\",\n SessionEnd: \"no per-firing id; a cleared and a resumed session end under the same session_id\",\n PreCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n PostCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n Stop:\n \"prompt_id is not a delivery identity here: Claude Code can fire Stop more than once per prompt when a hook continues the turn (stop_hook_active)\",\n StopFailure:\n \"prompt_id is not a delivery identity here: one prompt can fail more than once, and error_type names a class rather than a firing\",\n PreToolUse: \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n PostToolUse: \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n PostToolUseFailure:\n \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n PermissionRequest:\n \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n SubagentStart: \"payload.agent_id absent; agent_type names a class of subagents, not an instance\",\n SubagentStop: \"payload.agent_id absent; agent_type names a class of subagents, not an instance\",\n UserPromptSubmit: \"payload.prompt_id absent; requires Claude Code v2.1.196 or later\",\n});\n","import {\n asProviderId,\n providerDetectionSchema,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"../adapter.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { CLAUDE_HOOK_EVENT_NAMES } from \"./schema.js\";\n\n/** Stable, hyphenated provider id for Claude Code. */\nexport const CLAUDE_CODE_PROVIDER_ID = asProviderId(\"claude-code\");\n\nconst KNOWN_EVENT_NAMES: ReadonlySet<string> = new Set(CLAUDE_HOOK_EVENT_NAMES);\n\nconst none = (reason: string): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: [reason],\n });\n\n/**\n * Recognize a Claude Code hook payload.\n *\n * Confidence is never `exact` from shape alone: Claude Code hook JSON has no\n * self-identifying `provider` field, so `hook_event_name` plus `session_id`\n * is the strongest evidence a shape check can offer. A caller-supplied\n * `providerHint` naming this adapter is treated as the stronger claim.\n */\nexport const detectClaudeCode = (input: ProviderDetectionInput): ProviderDetection => {\n const payload = normalizeClaudeHookPayload(input.payload);\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return none(\"payload is not a JSON object\");\n }\n\n const record = payload as Record<string, unknown>;\n const hookEventName = record.hook_event_name;\n if (typeof hookEventName !== \"string\" || !KNOWN_EVENT_NAMES.has(hookEventName)) {\n return none(\"hook_event_name is missing or not a recognized Claude Code hook event\");\n }\n\n const sessionId = record.session_id;\n if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n return none(\"session_id is missing\");\n }\n\n const hasTranscriptPath =\n typeof record.transcript_path === \"string\" && record.transcript_path.length > 0;\n const isPrintResult = record.type === \"result\";\n const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;\n\n return providerDetectionSchema.parse({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n confidence: hinted ? \"exact\" : hasTranscriptPath || isPrintResult ? \"strong\" : \"weak\",\n reasons: [\n `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,\n \"session_id present\",\n ...(hasTranscriptPath ? [\"transcript_path present\"] : []),\n ...(isPrintResult ? [\"type=result print/SDK result message\"] : []),\n ...(hinted ? [\"caller asserted providerHint=claude-code\"] : []),\n ],\n sourceEventName: hookEventName,\n });\n};\n","import {\n workspaceIdentitySchema,\n type WorkspaceIdentity,\n type WorkspaceKeySource,\n} from \"../model/identity.js\";\nimport type { PrivacyService } from \"./service.js\";\n\n/**\n * Raw material a caller can offer for workspace identification.\n *\n * Paths and remote URLs are accepted here and immediately hashed. Neither is\n * retained, so a home directory cannot reach an exporter through this path.\n */\nexport type WorkspaceKeyInput =\n | { readonly kind: \"git-remote\"; readonly remoteUrl: string }\n | { readonly kind: \"git-root\"; readonly absolutePath: string }\n | { readonly kind: \"working-directory\"; readonly absolutePath: string }\n | { readonly kind: \"explicit\"; readonly value: string }\n | { readonly kind: \"unknown\" };\n\nexport type WorkspaceLabels = {\n /** Bare repository name, e.g. `otel-hook`. Never an owner path or URL. */\n readonly repositoryName?: string;\n readonly vcsBranchName?: string;\n /** Revision identifier; hashed before it is stored. */\n readonly vcsRevisionId?: string;\n};\n\n/**\n * Canonicalize a git remote so equivalent spellings hash identically:\n * scheme, credentials, port, trailing `.git`, and case are removed.\n */\nexport const canonicalizeGitRemote = (remoteUrl: string): string => {\n const trimmed = remoteUrl.trim();\n const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);\n const withoutScheme = scpLike\n ? `${scpLike[2] ?? \"\"}/${scpLike[3] ?? \"\"}`\n : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//, \"\").replace(/^[^@/]+@/, \"\");\n return withoutScheme\n .replace(/:\\d+\\//, \"/\")\n .replace(/\\/+$/, \"\")\n .replace(/\\.git$/i, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n};\n\nconst keySourceOf = (input: WorkspaceKeyInput): WorkspaceKeySource => {\n switch (input.kind) {\n case \"git-remote\":\n return \"git-remote\";\n case \"git-root\":\n return \"git-root\";\n case \"working-directory\":\n return \"working-directory\";\n case \"explicit\":\n return \"explicit\";\n case \"unknown\":\n return \"unknown\";\n }\n};\n\nconst keyMaterialOf = (input: WorkspaceKeyInput): string | undefined => {\n switch (input.kind) {\n case \"git-remote\":\n return canonicalizeGitRemote(input.remoteUrl);\n case \"git-root\":\n case \"working-directory\":\n return input.absolutePath.replace(/[/\\\\]+$/, \"\");\n case \"explicit\":\n return input.value;\n case \"unknown\":\n return undefined;\n }\n};\n\n/**\n * Derive privacy-safe workspace identity.\n *\n * The identifier is a salted hash namespaced by key source, so a directory-keyed\n * workspace and a remote-keyed workspace never collide even if the underlying\n * strings match.\n */\nexport const deriveWorkspaceIdentity = (\n privacy: PrivacyService,\n input: WorkspaceKeyInput,\n labels: WorkspaceLabels = {},\n): WorkspaceIdentity => {\n const keySource = keySourceOf(input);\n const material = keyMaterialOf(input);\n const workspaceId =\n material === undefined || material === \"\"\n ? \"unknown:0000000000000000\"\n : privacy.deriveOpaqueId(`workspace/${keySource}`, material);\n\n return workspaceIdentitySchema.parse({\n workspaceId,\n keySource: material === undefined || material === \"\" ? \"unknown\" : keySource,\n ...(labels.repositoryName === undefined\n ? {}\n : { repositoryName: labels.repositoryName.slice(0, 128) }),\n ...(labels.vcsBranchName === undefined\n ? {}\n : { vcsBranchName: labels.vcsBranchName.slice(0, 128) }),\n ...(labels.vcsRevisionId === undefined\n ? {}\n : { vcsRevisionId: privacy.deriveOpaqueId(\"workspace/revision\", labels.vcsRevisionId) }),\n });\n};\n","import { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport { invocationIdSchema, sessionIdSchema, type InvocationId } from \"../../model/primitives.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport type { ProviderContext, ProviderIdentityInput } from \"../adapter.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./detect.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { claudeIdentityFieldsSchema } from \"./schema.js\";\n\n/**\n * Deterministic, cross-invocation-stable id for a subagent.\n *\n * Derived from only `sessionId` and `agentId` (never a timestamp), so any\n * hook firing that carries the same `agent_id` — the subagent's own\n * `SubagentStart`/`SubagentStop`, or a tool call made from inside it —\n * recomputes the identical id and can link back to it, without the adapter\n * ever persisting state between invocations.\n */\nexport const subagentInvocationIdFor = (\n context: ProviderContext,\n sessionId: string,\n agentId: string,\n): InvocationId =>\n invocationIdSchema.parse(`subagent_${context.ids.newOpaqueId([\"claude-subagent\", sessionId, agentId])}`);\n\n/**\n * Contribute identity claims for one Claude Code hook invocation.\n *\n * `sessionId` is Claude Code's own `session_id`, stable for the life of the\n * session. `invocationId` identifies this single hook firing and is\n * intentionally allowed to differ between firings in the same session —\n * continuity across firings is carried by `sessionId`, sequence numbers, and\n * (for subagents) `parentInvocationId`, not by a stable `invocationId`.\n */\nexport const identifyClaudeCode = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n): readonly IdentityClaim[] => {\n const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));\n if (!parsed.success) {\n return [];\n }\n const fields = parsed.data;\n const sessionId = sessionIdSchema.parse(fields.session_id);\n const occurredAt = context.clock.now();\n const discriminator = fields.tool_use_id ?? fields.prompt_id ?? fields.agent_id;\n\n const invocationId = context.ids.newInvocationId({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n sessionId,\n sourceEventName: fields.hook_event_name,\n occurredAt,\n ...(discriminator === undefined ? {} : { discriminator }),\n });\n\n const isSubagentLifecycleEvent =\n fields.hook_event_name === \"SubagentStart\" || fields.hook_event_name === \"SubagentStop\";\n const parentInvocationId =\n fields.agent_id !== undefined && !isSubagentLifecycleEvent\n ? subagentInvocationIdFor(context, sessionId, fields.agent_id)\n : undefined;\n\n const claim = identityClaimSchema.parse({\n source: `adapter:${CLAUDE_CODE_PROVIDER_ID}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt: occurredAt,\n ...(fields.cwd === undefined\n ? {}\n : { workspace: deriveWorkspaceIdentity(context.privacy, { kind: \"working-directory\", absolutePath: fields.cwd }) }),\n ...(parentInvocationId === undefined ? {} : { parentInvocationId }),\n ...(fields.agent_id === undefined ? {} : { agentInstanceId: fields.agent_id }),\n },\n });\n\n return [claim];\n};\n","/**\n * Locate assistant text on a Claude Code Stop / print-result payload.\n *\n * Field names are the ones Claude Code and its published `-p` / Agent SDK\n * result JSON have used. The first non-empty string wins. Empty strings and\n * missing fields are treated as \"the provider sent nothing\" — this module\n * never invents text.\n */\n\nconst TOP_LEVEL_TEXT_FIELDS = [\n \"last_assistant_message\",\n \"lastAssistantMessage\",\n \"result\",\n \"assistant_message\",\n \"final_message\",\n] as const;\n\nconst MESSAGE_TEXT_FIELDS = [\"content\", \"text\", \"result\"] as const;\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst nonEmptyString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\nconst textFromContentBlocks = (value: unknown): string | undefined => {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const parts: string[] = [];\n for (const block of value) {\n const record = asRecord(block);\n if (record === undefined) {\n continue;\n }\n const text = nonEmptyString(record.text);\n if (text !== undefined && (record.type === undefined || record.type === \"text\")) {\n parts.push(text);\n }\n }\n return parts.length === 0 ? undefined : parts.join(\"\");\n};\n\n/**\n * Return the assistant text Claude sent on this stop/result payload, or\n * `undefined` when no non-empty string was present.\n */\nexport const extractClaudeAssistantText = (payload: unknown): string | undefined => {\n const record = asRecord(payload);\n if (record === undefined) {\n return undefined;\n }\n\n for (const field of TOP_LEVEL_TEXT_FIELDS) {\n const text = nonEmptyString(record[field]);\n if (text !== undefined) {\n return text;\n }\n }\n\n const messageText = nonEmptyString(record.message);\n if (messageText !== undefined) {\n return messageText;\n }\n\n const message = asRecord(record.message);\n if (message === undefined) {\n return undefined;\n }\n for (const field of MESSAGE_TEXT_FIELDS) {\n const text = nonEmptyString(message[field]) ?? textFromContentBlocks(message[field]);\n if (text !== undefined) {\n return text;\n }\n }\n return undefined;\n};\n","import { sessionCwdHint, type TargetHint } from \"../../model/target.js\";\n\n/**\n * Where a Claude Code tool call pointed, as a target hint (ADR 0008).\n *\n * Claude Code's file tools name their file in `tool_input`; that is the\n * strongest evidence a hook payload carries, and is reported as `tool-path`.\n * The hook's `cwd` is the *session's* directory, not the tool's — Claude Code's\n * `Bash` reports no working directory of its own — so it is used only as the\n * `session-cwd` fallback for a call that names no path.\n *\n * Only built-in tools whose input field is documented as a path are read. An\n * MCP tool's `path` argument means whatever its server says it means, and is\n * not evidence of a local file.\n */\nconst PATH_FIELDS: Readonly<Record<string, readonly string[]>> = Object.freeze({\n Read: [\"file_path\"],\n Write: [\"file_path\"],\n Edit: [\"file_path\"],\n MultiEdit: [\"file_path\"],\n NotebookEdit: [\"notebook_path\"],\n NotebookRead: [\"notebook_path\"],\n // Optional on both: absent means \"search the session's directory\".\n Glob: [\"path\"],\n Grep: [\"path\"],\n});\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nexport const claudeTargetHint = (\n toolName: string,\n toolInput: unknown,\n cwd: string | undefined,\n): TargetHint | undefined => {\n // `hasOwn`: a tool name is payload data, and `__proto__` is a string like any other.\n const fields = Object.hasOwn(PATH_FIELDS, toolName) ? PATH_FIELDS[toolName] : undefined;\n const input = asRecord(toolInput);\n if (fields !== undefined && input !== undefined) {\n for (const field of fields) {\n const candidate = input[field];\n if (typeof candidate === \"string\" && candidate.length > 0) {\n return {\n source: \"tool-path\",\n paths: [candidate],\n ...(cwd === undefined ? {} : { baseDirectory: cwd }),\n };\n }\n }\n }\n return sessionCwdHint(cwd);\n};\n","import type { ToolKind } from \"../../model/index.js\";\n\n/**\n * Best-effort classification of Claude Code's built-in tool names.\n *\n * Unrecognized names (including every `mcp__*` tool, whose behavior is\n * defined by the connected MCP server rather than Claude Code itself) map to\n * `unknown` rather than a guess.\n */\nconst BUILT_IN_TOOL_KIND: Readonly<Record<string, ToolKind>> = Object.freeze({\n Bash: \"execute\",\n BashOutput: \"execute\",\n KillShell: \"execute\",\n Read: \"read\",\n NotebookRead: \"read\",\n Write: \"write\",\n Edit: \"write\",\n MultiEdit: \"write\",\n NotebookEdit: \"write\",\n Glob: \"search\",\n Grep: \"search\",\n WebFetch: \"network\",\n WebSearch: \"network\",\n Task: \"delegate\",\n // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.\n Agent: \"delegate\",\n TodoWrite: \"other\",\n ExitPlanMode: \"other\",\n AskUserQuestion: \"other\",\n SlashCommand: \"other\",\n});\n\nexport const inferToolKind = (toolName: string): ToolKind => {\n if (toolName.startsWith(\"mcp__\")) {\n return \"unknown\";\n }\n return BUILT_IN_TOOL_KIND[toolName] ?? \"unknown\";\n};\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { ModelDescriptor } from \"../../model/index.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport type { ProviderContext, ProviderParseInput, ProviderParseResult } from \"../adapter.js\";\nimport { subagentInvocationIdFor } from \"./identity.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { claudeHookPayloadSchema, type ClaudeUsage } from \"./schema.js\";\nimport { extractClaudeAssistantText } from \"./stop-content.js\";\nimport { sessionCwdHint } from \"../../model/target.js\";\nimport { claudeTargetHint } from \"./target.js\";\nimport { inferToolKind } from \"./tool-kind.js\";\nimport { extractClaudeUsage, normalizeClaudeUsage } from \"./usage.js\";\n\n/**\n * Claude Code hooks never report a model identifier on the events this\n * adapter turns into `generation.start`/`generation.end` (`Stop`,\n * `StopFailure`). Only `SessionStart` names one.\n *\n * So a generation's model comes from, in order:\n *\n * 1. a `model` a wrapping harness attached to the stop payload — the per-turn\n * model it read from the transcript's last assistant message, the only\n * source that follows a `/model` switch exactly;\n * 2. the session's model, which the core remembers from `SessionStart` (or the\n * last turn that named one) and hands in as `sessionModel` (ADR 0006: the\n * adapter itself holds no cross-invocation state);\n * 3. `unknown`, when nothing in this session ever named a model. Using a\n * real-looking model id here would assert something no payload said;\n * `unknown` is the same honest-absence sentinel the core model uses for\n * provider and workspace identity.\n *\n * The request model (`generation.start`) prefers the session's model, since that\n * is what the turn was sent to; the response model (`generation.end`) prefers the\n * attached per-turn one, since that is what answered.\n */\nconst UNKNOWN_MODEL: ModelDescriptor = { modelId: \"unknown\" };\n\nconst generationModels = (\n attached: string | undefined,\n sessionModel: ModelDescriptor | undefined,\n): { readonly request: ModelDescriptor; readonly response: ModelDescriptor } => {\n const turnModel: ModelDescriptor | undefined = attached === undefined ? undefined : { modelId: attached };\n return {\n request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,\n response: turnModel ?? sessionModel ?? UNKNOWN_MODEL,\n };\n};\n\ntype SessionEndReason = \"completed\" | \"aborted\" | \"error\" | \"timeout\" | \"unknown\";\n\nconst SESSION_END_REASON: Readonly<Record<string, SessionEndReason>> = Object.freeze({\n completed: \"completed\",\n aborted: \"aborted\",\n error: \"error\",\n timeout: \"timeout\",\n clear: \"completed\",\n resume: \"completed\",\n prompt_input_exit: \"completed\",\n logout: \"aborted\",\n bypass_permissions_disabled: \"aborted\",\n other: \"unknown\",\n});\n\nconst mapSessionEndReason = (raw: string | undefined): SessionEndReason =>\n raw === undefined ? \"unknown\" : (SESSION_END_REASON[raw] ?? \"unknown\");\n\ntype CompactionTrigger = \"automatic\" | \"manual\" | \"unknown\";\n\nconst mapCompactTrigger = (raw: string | undefined): CompactionTrigger => {\n if (raw === \"auto\" || raw === \"automatic\") {\n return \"automatic\";\n }\n if (raw === \"manual\") {\n return \"manual\";\n }\n return \"unknown\";\n};\n\ntype GenerationOutcome = \"ok\" | \"error\" | \"cancelled\" | \"timeout\" | \"denied\" | \"unknown\";\n\n/** `StopFailure` error categories that represent the request being refused rather than failing. */\nconst DENIED_STOP_FAILURE_TYPES: ReadonlySet<string> = new Set([\n \"authentication_failed\",\n \"oauth_org_not_allowed\",\n \"billing_error\",\n]);\n\nconst mapStopFailureOutcome = (errorType: string): GenerationOutcome =>\n DENIED_STOP_FAILURE_TYPES.has(errorType) ? \"denied\" : \"error\";\n\nconst applyUsage = (normalized: ReturnType<typeof normalizeClaudeUsage>): { usage?: ReturnType<typeof normalizeClaudeUsage>[\"usage\"] } =>\n normalized.usage === undefined ? {} : { usage: normalized.usage };\n\nexport const parseClaudeCode = (\n input: ProviderParseInput,\n context: ProviderContext,\n): ProviderParseResult => {\n const normalizedPayload = normalizeClaudeHookPayload(input.payload);\n const parsed = claudeHookPayloadSchema.safeParse(normalizedPayload);\n if (!parsed.success) {\n const rawEventName =\n typeof input.payload === \"object\" && input.payload !== null\n ? (input.payload as Record<string, unknown>).hook_event_name\n : undefined;\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: `payload failed Claude Code schema validation: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: { \"hook.event_name\": typeof rawEventName === \"string\" ? rawEventName : \"\" },\n }),\n };\n }\n const payload = parsed.data;\n const extractedUsage = extractClaudeUsage(normalizedPayload);\n\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n // Present exactly when the hook fired inside a subagent (or describes one,\n // on SubagentStart/SubagentStop).\n ...(payload.agent_id === undefined ? {} : { subagentId: payload.agent_id }),\n });\n const warnings: string[] = [];\n const targetHintFor = (toolName: string, toolInput: unknown) => {\n const hint = claudeTargetHint(toolName, toolInput, payload.cwd);\n return hint === undefined ? {} : { targetHint: hint };\n };\n // The session's own directory: where it runs before any tool names a path.\n const sessionHint = sessionCwdHint(payload.cwd);\n const sessionTarget = sessionHint === undefined ? {} : { targetHint: sessionHint };\n const withUsage = (usage: ClaudeUsage | undefined) => {\n const normalized = normalizeClaudeUsage(usage);\n warnings.push(...normalized.warnings);\n return applyUsage(normalized);\n };\n\n /** Usage plus the attacher's statement of whether it covers the whole turn. */\n const withPartialUsage = (usage: ClaudeUsage | undefined, partial: boolean | undefined) => {\n const applied = withUsage(usage);\n return applied.usage === undefined || partial === undefined ? applied : { ...applied, usagePartial: partial };\n };\n\n switch (payload.hook_event_name) {\n case \"SessionStart\":\n factory.build({\n type: \"session.start\",\n sessionKind: \"unknown\",\n agentName: \"claude-code\",\n ...(payload.model === undefined ? {} : { model: { modelId: payload.model } }),\n ...sessionTarget,\n });\n break;\n\n case \"SessionEnd\":\n factory.build({\n type: \"session.end\",\n reason: mapSessionEndReason(payload.reason ?? payload.end_reason),\n ...withUsage(extractedUsage),\n });\n break;\n\n case \"UserPromptSubmit\":\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n content: context.privacy.describeContent({ kind: \"prompt\", role: \"user\", text: payload.prompt }),\n ...sessionTarget,\n });\n break;\n\n case \"PreToolUse\":\n factory.build({\n type: \"tool.start\",\n toolCallId: payload.tool_use_id,\n toolName: payload.tool_name,\n toolKind: inferToolKind(payload.tool_name),\n ...targetHintFor(payload.tool_name, payload.tool_input),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"PostToolUse\":\n factory.build({\n type: \"tool.end\",\n toolCallId: payload.tool_use_id,\n toolName: payload.tool_name,\n outcome: \"ok\",\n ...targetHintFor(payload.tool_name, payload.tool_input),\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_response,\n label: payload.tool_name,\n }),\n });\n break;\n\n case \"PostToolUseFailure\":\n factory.build({\n type: \"tool.end\",\n toolCallId: payload.tool_use_id,\n toolName: payload.tool_name,\n outcome: \"error\",\n ...targetHintFor(payload.tool_name, payload.tool_input),\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_error,\n label: payload.tool_name,\n }),\n });\n break;\n\n case \"PermissionRequest\":\n // The canonical model has no dedicated \"permission requested\" event: a\n // decision here either becomes a normal PreToolUse/PostToolUse pair (if\n // allowed) or the tool call never happens at all (if denied), so there\n // is nothing distinct to telemeter yet.\n return {\n status: \"ignored\",\n reason: \"permission requests carry no telemetry independent of the tool call they gate\",\n };\n\n case \"SubagentStart\":\n factory.build({\n type: \"subagent.start\",\n subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),\n subagentType: payload.agent_type,\n delegationDepth: 1,\n });\n break;\n\n case \"SubagentStop\": {\n // The subagent's tokens (attached from its own transcript, issue #68) are\n // reported on a generation inside the subagent, where metrics and receivers\n // count generation spend, and nowhere else: not on the subagent span, which\n // would restate them, and not on the parent turn, which never sums sidechain\n // requests. The model is the subagent's own; the session's would be a guess.\n const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);\n if (usage.usage !== undefined || payload.model !== undefined) {\n // Replay-stable for the once-per-run stop, which is also what delivery\n // deduplicates on (`delivery.ts`): a reclaimed delivery folds into the\n // same generation instead of opening a second one. A hook-continued stop\n // repeats `agent_id`, so it needs the sequence to be a generation of its own.\n const generationId = context.ids.newOpaqueId([\n \"claude-subagent-generation\",\n payload.session_id,\n payload.agent_id,\n ...(payload.stop_hook_active === true ? [String(input.sequenceBase)] : []),\n ]);\n const models = generationModels(payload.model, undefined);\n factory.build({ type: \"generation.start\", generationId, model: models.request });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: models.response,\n outcome: \"ok\",\n outputContent: [\n payload.last_assistant_message === undefined\n ? context.privacy.describeUnavailableContent({ kind: \"response\", role: \"assistant\" })\n : context.privacy.describeContent({\n kind: \"response\",\n role: \"assistant\",\n text: payload.last_assistant_message,\n }),\n ],\n ...usage,\n });\n }\n factory.build({\n type: \"subagent.end\",\n subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),\n outcome: \"ok\",\n });\n break;\n }\n\n case \"PreCompact\":\n // Fires before compaction runs; the completed operation is reported once at\n // PostCompact instead. Claude Code reports no token count on either\n // compaction callback (docs/claude-code-usage-contract.md, finding 6), so\n // nothing is lost by ignoring this edge — but a *harness* may have attached\n // a before-figure here, and dropping that silently is what made\n // ADAPTER-NOTE-002 look like a plumbing gap. It is an exclusion, so it says\n // so: carrying the figure to PostCompact would need cross-invocation state\n // an adapter must not hold (ADR 0006), and the same harness can attach it to\n // PostCompact, where one callback carries both ends.\n // Kept inside the 160 characters an ignore reason survives at the log\n // boundary, so the remedy is not the part that gets truncated away.\n return {\n status: \"ignored\",\n reason:\n payload.context_tokens_before === undefined\n ? \"compaction is reported once it completes, at PostCompact\"\n : \"contextTokensBefore is an explicit exclusion for this provider: attach \" +\n \"context_tokens_before to PostCompact, which carries both ends in one callback\",\n };\n\n case \"PostCompact\":\n factory.build({\n type: \"compaction.performed\",\n trigger: mapCompactTrigger(payload.trigger ?? payload.compact_trigger),\n ...(payload.context_tokens_before === undefined ? {} : { contextTokensBefore: payload.context_tokens_before }),\n ...(payload.context_tokens_after === undefined ? {} : { contextTokensAfter: payload.context_tokens_after }),\n ...(payload.dropped_message_count === undefined ? {} : { droppedMessageCount: payload.dropped_message_count }),\n ...withUsage(payload.usage),\n });\n break;\n\n case \"Stop\": {\n const generationId = context.ids.newOpaqueId([\n \"claude-generation\",\n payload.session_id,\n payload.prompt_id ?? String(input.sequenceBase),\n ]);\n const assistantText = extractClaudeAssistantText(normalizedPayload);\n const models = generationModels(payload.model, input.sessionModel);\n factory.build({ type: \"generation.start\", generationId, model: models.request });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: models.response,\n outcome: \"ok\",\n // Always a response fact: a body when Claude sent text, otherwise a\n // zero-length omitted fact so the log mapping can emit metadata_only\n // instead of a generation.end with no content.kind.\n outputContent: [\n assistantText === undefined\n ? context.privacy.describeUnavailableContent({ kind: \"response\", role: \"assistant\" })\n : context.privacy.describeContent({\n kind: \"response\",\n role: \"assistant\",\n text: assistantText,\n }),\n ],\n ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial),\n });\n break;\n }\n\n case \"StopFailure\": {\n const generationId = context.ids.newOpaqueId([\n \"claude-generation\",\n payload.session_id,\n payload.prompt_id ?? String(input.sequenceBase),\n ]);\n const assistantText = extractClaudeAssistantText(normalizedPayload);\n const models = generationModels(payload.model, input.sessionModel);\n factory.build({ type: \"generation.start\", generationId, model: models.request });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: models.response,\n outcome: mapStopFailureOutcome(payload.error_type),\n stopReason: payload.error_type,\n ...(assistantText === undefined\n ? {}\n : {\n outputContent: [\n context.privacy.describeContent({\n kind: \"response\",\n role: \"assistant\",\n text: assistantText,\n }),\n ],\n }),\n ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial),\n });\n break;\n }\n }\n\n const targetHints = factory.targetHints();\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n ...(targetHints.size === 0 ? {} : { targetHints }),\n };\n};\n","import { SILENT_HOOK_RESPONSE, type ProviderAdapter, type ProviderHookResponse } from \"../adapter.js\";\nimport { CLAUDE_CODE_CAPABILITIES } from \"./capabilities.js\";\nimport { CLAUDE_DELIVERY_GAPS, claudeDeliveryIdentity } from \"./delivery.js\";\nimport { CLAUDE_CODE_PROVIDER_ID, detectClaudeCode } from \"./detect.js\";\nimport { parseClaudeCode } from \"./events.js\";\nimport { identifyClaudeCode } from \"./identity.js\";\n\nexport type ClaudeCodeAdapterOptions = {\n /** Adapter version reported in provenance; defaults to `1.0.0`. */\n readonly version?: string;\n};\n\n/**\n * Provider adapter for Claude Code's hook protocol.\n *\n * Always answers hook invocations silently: this adapter is a telemetry\n * sidecar, not the hook that governs permissions or turn continuation, and\n * must never be able to block the host agent (ADR 0004).\n */\nexport const createClaudeCodeAdapter = (options: ClaudeCodeAdapterOptions = {}): ProviderAdapter => ({\n id: CLAUDE_CODE_PROVIDER_ID,\n version: options.version ?? \"1.0.0\",\n capabilities: CLAUDE_CODE_CAPABILITIES,\n detect: (input) => detectClaudeCode(input),\n identify: (input, context) => identifyClaudeCode(input, context),\n deliveryIdentity: (input) => claudeDeliveryIdentity(input),\n deliveryGaps: CLAUDE_DELIVERY_GAPS,\n parse: (input, context) => parseClaudeCode(input, context),\n hookResponse: (): ProviderHookResponse => SILENT_HOOK_RESPONSE,\n});\n","import { createHash } from \"node:crypto\";\nimport { open, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { PayloadEnricher, PayloadEnrichment, ReadCursor } from \"../../runtime/ports.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./detect.js\";\nimport type { ClaudeUsage } from \"./schema.js\";\nimport { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Bounded readers for one Claude Code session transcript, and the enricher that\n * uses them to attach a turn's model and token usage to a `Stop` payload.\n *\n * None of this is part of the Claude Code adapter, and the adapter never calls\n * it: `ProviderContext` gives adapters no filesystem handle (ADR 0003). Two\n * callers use it instead:\n *\n * - a wrapping harness, through {@link attachClaudeTranscriptTurn}, which reads\n * the last assistant message only;\n * - the hook runtime, through {@link createClaudeTranscriptUsageEnricher}, when\n * the host turns on `providers.claudeCode.readTranscriptUsage` — the one\n * sanctioned exception to \"no transcript reads in the hook\". It sums the whole\n * turn, from a byte cursor the runtime keeps in the state store.\n *\n * Why the transcript at all: no Claude Code hook callback carries a token\n * counter, and only `SessionStart` names a model. The per-turn model\n * (`message.model`, which follows `/model`) and the Anthropic usage object\n * (`message.usage`) exist only on assistant transcript records, one record per\n * content block, each repeating its request's `message.id`.\n *\n * Every bound is hard, and nothing here throws:\n * - only regular `.jsonl` files at an absolute path are opened, so a FIFO or a\n * device cannot stall the hook, and no directory is ever listed;\n * - a read is capped in bytes and raced against a time budget;\n * - a malformed or truncated line is skipped, never fatal.\n *\n * Nothing but model ids and numeric counters leaves this module: a record's\n * content (prompt, response, thinking, tool input) is parsed only to be dropped.\n */\n\nexport type ClaudeTranscriptUnavailableReason =\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n | \"no-assistant-message\";\n\nexport type ClaudeTranscriptTurn =\n | {\n readonly status: \"found\";\n /** `message.model`; absent when the record named none. */\n readonly model?: string;\n /** `message.usage`, coerced onto the shape the `Stop` schema accepts. */\n readonly usage?: ClaudeUsage;\n }\n | { readonly status: \"unavailable\"; readonly reason: ClaudeTranscriptUnavailableReason };\n\nexport type ReadClaudeTranscriptTurnOptions = {\n /** Bytes read from the end of the file. Default 1 MiB, clamped to 64 KiB..16 MiB. */\n readonly maxTailBytes?: number;\n /** Budget for the whole read. Default 250 ms, clamped to 10 ms..5 s. */\n readonly timeoutMillis?: number;\n};\n\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1_048_576;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8_388_608;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;\n\nconst MIN_TAIL_BYTES = 65_536;\nconst MAX_TAIL_BYTES = 16_777_216;\nconst MAX_RANGE_BYTES = 67_108_864;\nconst MIN_TIMEOUT_MILLIS = 10;\nconst MAX_TIMEOUT_MILLIS = 5_000;\n/** Longer than any real model id; a longer value is not one. */\nconst MAX_MODEL_ID_LENGTH = 256;\n/** Bounds the request ids held while summing one range. */\nconst MAX_REQUESTS_PER_RANGE = 10_000;\n/**\n * Claude Code writes `<synthetic>` as the model of assistant records it made up\n * itself (an API error, an interrupted turn). Those name no real model and carry\n * zeroed usage, so they are skipped.\n */\nconst SYNTHETIC_MODEL = \"<synthetic>\";\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nconst clamp = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (value === undefined || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(max, Math.max(min, Math.floor(value)));\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst isTranscriptPath = (transcriptPath: unknown): transcriptPath is string =>\n typeof transcriptPath === \"string\" &&\n transcriptPath.length > 0 &&\n !transcriptPath.includes(\"\\0\") &&\n path.isAbsolute(transcriptPath) &&\n path.extname(transcriptPath) === \".jsonl\";\n\n/**\n * A record of subagent `agentId`: a sidechain record naming that agent, or\n * naming none (the file is the agent's own; only a different name excludes it).\n */\nconst isRecordOfAgent = (record: Record<string, unknown>, agentId: string): boolean =>\n record.isSidechain === true && (typeof record.agentId !== \"string\" || record.agentId === agentId);\n\ntype AssistantRecord = { readonly id?: string; readonly model?: string; readonly usage?: ClaudeUsage };\n\n/**\n * The request id, model and usage of one transcript line, or `undefined` when\n * it is not a usable assistant record of the thread being read.\n *\n * Without `agentId` that thread is the main one: sidechain records are a\n * subagent's conversation, and the parent's `Stop` is not about them. With\n * `agentId` it is that subagent's, read from its own transcript\n * (`agent_transcript_path`), where every record is a sidechain record; a record\n * naming another agent is skipped.\n */\nconst assistantRecordOf = (line: string, agentId?: string): AssistantRecord | undefined => {\n // Cheap pre-filter: most lines are user, tool-result, or summary records, and\n // parsing every one of them would spend the budget on records never used.\n if (!line.includes('\"assistant\"')) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n const record = asRecord(parsed);\n if (record === undefined || record.type !== \"assistant\") {\n return undefined;\n }\n if (agentId === undefined ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {\n return undefined;\n }\n const message = asRecord(record.message);\n if (message === undefined || message.model === SYNTHETIC_MODEL) {\n return undefined;\n }\n const model =\n typeof message.model === \"string\" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH\n ? message.model\n : undefined;\n const usage = coerceClaudeUsage(message.usage);\n if (model === undefined && usage === undefined) {\n return undefined;\n }\n const id =\n typeof message.id === \"string\" && message.id.length > 0 && message.id.length <= 256 ? message.id : undefined;\n return {\n ...(id === undefined ? {} : { id }),\n ...(model === undefined ? {} : { model }),\n ...(usage === undefined ? {} : { usage }),\n };\n};\n\nconst cacheCreationOf = (usage: ClaudeUsage): number =>\n usage.cache_creation_input_tokens ??\n (usage.cache_creation === undefined\n ? 0\n : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));\n\n/**\n * Sum per-request usage into one turn total.\n *\n * Only the four counters are summed. The TTL split and `iterations[]` are\n * breakdowns of one request's counters (docs/claude-code-usage-contract.md,\n * findings 3 and 4); carrying them across requests would add nothing a consumer\n * reads, and the adapter would only audit them against the sums.\n */\nconst sumUsage = (usages: readonly ClaudeUsage[]): ClaudeUsage => {\n let input = 0;\n let output = 0;\n let cacheRead = 0;\n let cacheCreation = 0;\n for (const usage of usages) {\n input += usage.input_tokens;\n output += usage.output_tokens;\n cacheRead += usage.cache_read_input_tokens ?? 0;\n cacheCreation += cacheCreationOf(usage);\n }\n return {\n input_tokens: input,\n output_tokens: output,\n cache_read_input_tokens: cacheRead,\n cache_creation_input_tokens: cacheCreation,\n };\n};\n\n/** Race `work` against a budget; a rejection becomes `onError`. */\nconst withTimeout = async <T>(\n work: Promise<T>,\n timeoutMillis: number,\n onError: T,\n): Promise<T | typeof TIMED_OUT> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => {\n resolve(TIMED_OUT);\n }, timeoutMillis);\n // A hook process must be free to exit the moment its real work is done.\n timer.unref();\n });\n try {\n return await Promise.race([work.catch(() => onError), timeout]);\n } finally {\n clearTimeout(timer);\n }\n};\n\ntype FileUnavailable = { readonly status: \"unavailable\"; readonly reason: \"not-a-file\" | \"unreadable\" };\n\ntype FileHandle = Awaited<ReturnType<typeof open>>;\n\n/** Open a regular file and run `body` with its handle and size; always closes. */\nconst withRegularFile = async <T>(\n transcriptPath: string,\n body: (handle: FileHandle, size: number) => Promise<T>,\n): Promise<T | FileUnavailable> => {\n let info;\n try {\n info = await stat(transcriptPath);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n if (!info.isFile()) {\n return { status: \"unavailable\", reason: \"not-a-file\" };\n }\n let handle;\n try {\n handle = await open(transcriptPath, \"r\");\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n try {\n const { size } = await handle.stat();\n return await body(handle, size);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\nconst readBytes = async (handle: FileHandle, start: number, length: number): Promise<Buffer> => {\n const buffer = Buffer.alloc(length);\n let filled = 0;\n while (filled < length) {\n const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);\n if (bytesRead === 0) {\n break;\n }\n filled += bytesRead;\n }\n return buffer.subarray(0, filled);\n};\n\n/** Offset just past the last complete line of `bytes`, read from `start`. */\nconst completeLinesEnd = (bytes: Buffer, start: number): number => {\n const lastNewline = bytes.lastIndexOf(0x0a);\n return lastNewline < 0 ? start : start + lastNewline + 1;\n};\n\ntype TailRead = { readonly turn: ClaudeTranscriptTurn; readonly endOffset: number };\n\nconst readTail = (\n transcriptPath: string,\n maxTailBytes: number,\n agentId: string | undefined,\n): Promise<TailRead | FileUnavailable> =>\n withRegularFile(transcriptPath, async (handle, size): Promise<TailRead> => {\n const length = Math.min(size, maxTailBytes);\n const start = size - length;\n const bytes = await readBytes(handle, start, length);\n const endOffset = completeLinesEnd(bytes, start);\n const lines = bytes.toString(\"utf8\").split(\"\\n\");\n // A tail that starts mid-file starts mid-line: that first fragment is not a\n // record, and parsing it could only fail or, worse, half-succeed.\n if (start > 0) {\n lines.shift();\n }\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n const record = assistantRecordOf((lines[index] ?? \"\").trim(), agentId);\n if (record !== undefined) {\n return {\n turn: {\n status: \"found\",\n ...(record.model === undefined ? {} : { model: record.model }),\n ...(record.usage === undefined ? {} : { usage: record.usage }),\n },\n endOffset,\n };\n }\n }\n return { turn: { status: \"unavailable\", reason: \"no-assistant-message\" }, endOffset };\n });\n\nconst boundedTail = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions,\n agentId?: string,\n): Promise<TailRead | FileUnavailable | typeof TIMED_OUT> =>\n withTimeout<TailRead | FileUnavailable>(\n readTail(\n transcriptPath,\n clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),\n agentId,\n ),\n clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),\n { status: \"unavailable\", reason: \"unreadable\" },\n );\n\n/**\n * Read the model and usage of the last main-thread assistant message in a\n * Claude Code transcript. Never throws, never rejects.\n *\n * The usage is that **one message's** — the final model request of the turn. A\n * turn that called tools made several requests, and the earlier ones are not\n * summed in; {@link readClaudeTranscriptRange} sums a whole turn.\n */\nexport const readClaudeTranscriptTurn = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<ClaudeTranscriptTurn> => {\n if (!isTranscriptPath(transcriptPath)) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const read = await boundedTail(transcriptPath, options);\n if (read === TIMED_OUT) {\n return { status: \"unavailable\", reason: \"timeout\" };\n }\n return \"turn\" in read ? read.turn : read;\n};\n\nexport type ClaudeTranscriptRange =\n | {\n readonly status: \"found\";\n /** Model of the last main-thread assistant record in the range. */\n readonly model?: string;\n /** Summed usage of every distinct request; absent when none reported usage. */\n readonly usage?: ClaudeUsage;\n /** Distinct main-thread requests (by `message.id`) in the range. */\n readonly requestCount: number;\n /** Offset just past the last complete line read: the next range starts here. */\n readonly endOffset: number;\n }\n | {\n readonly status: \"unavailable\";\n readonly reason:\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n /** The file is shorter than the offset: it was replaced or truncated. */\n | \"truncated\"\n /** More than the range cap was written since the offset. */\n | \"over-cap\";\n };\n\nexport type ReadClaudeTranscriptRangeOptions = {\n /** Most bytes a range may span. Default 8 MiB, clamped to 64 KiB..64 MiB. */\n readonly maxRangeBytes?: number;\n /** Budget for the whole range read. Default 500 ms, clamped to 10 ms..5 s. */\n readonly rangeTimeoutMillis?: number;\n /**\n * Read subagent `agentId`'s requests (its sidechain records) instead of the\n * main thread's. For a subagent's own transcript, `agent_transcript_path`.\n */\n readonly agentId?: string;\n};\n\n/**\n * Sum every main-thread model request (or, with `agentId`, every request of that\n * subagent) written between `fromOffset` and the end of the transcript. Never\n * throws, never rejects.\n *\n * Records of one request share a `message.id` and each repeats its usage, so the\n * last record per id is the one counted; a record without an id counts alone.\n * A trailing partial line is left for the next range.\n */\nexport const readClaudeTranscriptRange = async (\n transcriptPath: string,\n fromOffset: number,\n options: ReadClaudeTranscriptRangeOptions = {},\n): Promise<ClaudeTranscriptRange> => {\n if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);\n const timeoutMillis = clamp(\n options.rangeTimeoutMillis,\n DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,\n MIN_TIMEOUT_MILLIS,\n MAX_TIMEOUT_MILLIS,\n );\n const work = withRegularFile(transcriptPath, async (handle, size): Promise<ClaudeTranscriptRange> => {\n if (size < fromOffset) {\n return { status: \"unavailable\", reason: \"truncated\" };\n }\n if (size - fromOffset > maxRangeBytes) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n const bytes = await readBytes(handle, fromOffset, size - fromOffset);\n const endOffset = completeLinesEnd(bytes, fromOffset);\n const complete = bytes.subarray(0, endOffset - fromOffset).toString(\"utf8\");\n const requests = new Map<string, AssistantRecord>();\n let anonymous = 0;\n let model: string | undefined;\n for (const line of complete.split(\"\\n\")) {\n const record = assistantRecordOf(line.trim(), options.agentId);\n if (record === undefined) {\n continue;\n }\n if (record.model !== undefined) {\n model = record.model;\n }\n anonymous += record.id === undefined ? 1 : 0;\n // The last record of a request carries its final usage, so it replaces the earlier ones.\n requests.set(record.id ?? `#${String(anonymous)}`, record);\n if (requests.size > MAX_REQUESTS_PER_RANGE) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n }\n const usages = [...requests.values()].flatMap((record) => (record.usage === undefined ? [] : [record.usage]));\n return {\n status: \"found\",\n ...(model === undefined ? {} : { model }),\n ...(usages.length === 0 ? {} : { usage: sumUsage(usages) }),\n requestCount: requests.size,\n endOffset,\n };\n });\n const result = await withTimeout<ClaudeTranscriptRange | FileUnavailable>(work, timeoutMillis, {\n status: \"unavailable\",\n reason: \"unreadable\",\n });\n return result === TIMED_OUT ? { status: \"unavailable\", reason: \"timeout\" } : result;\n};\n\nconst STOP_EVENTS: ReadonlySet<string> = new Set([\"Stop\", \"StopFailure\"]);\n\nconst hasUsage = (record: Record<string, unknown>): boolean =>\n record.usage !== undefined || record.token_usage !== undefined || record.tokenUsage !== undefined;\n\nconst eventNameOf = (record: Record<string, unknown>): unknown => record.hook_event_name ?? record.hookEventName;\nconst transcriptPathOf = (record: Record<string, unknown>): unknown =>\n record.transcript_path ?? record.transcriptPath;\n\n/**\n * Attach the last assistant message's `{ model, usage }` to a Claude Code\n * `Stop` / `StopFailure` payload, for a wrapper to hand to otel-hook.\n *\n * The usage is one request's, so it is attached with `usage_partial: true`,\n * which the exported generation reports as `otelhook.usage.partial`. For whole\n * turn totals, turn on `providers.claudeCode.readTranscriptUsage` instead.\n *\n * Returns the payload unchanged when it is not a stop, names no\n * `transcript_path`, already carries both fields, or the transcript yields\n * nothing — so a wrapper can call it unconditionally. A field the payload\n * already carries is never overwritten. Never throws, never rejects.\n */\nexport const attachClaudeTranscriptTurn = async (\n payload: unknown,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<unknown> => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n const eventName = eventNameOf(record);\n if (typeof eventName !== \"string\" || !STOP_EVENTS.has(eventName)) {\n return payload;\n }\n const transcriptPath = transcriptPathOf(record);\n if (typeof transcriptPath !== \"string\") {\n return payload;\n }\n const needsModel = record.model === undefined;\n const needsUsage = !hasUsage(record);\n if (!needsModel && !needsUsage) {\n return payload;\n }\n const turn = await readClaudeTranscriptTurn(transcriptPath, options);\n if (turn.status !== \"found\") {\n return payload;\n }\n return {\n ...record,\n ...(needsModel && turn.model !== undefined ? { model: turn.model } : {}),\n ...(needsUsage && turn.usage !== undefined ? { usage: turn.usage, usage_partial: true } : {}),\n };\n};\n\nexport type ClaudeTranscriptUsageEnricherOptions = ReadClaudeTranscriptTurnOptions &\n Omit<ReadClaudeTranscriptRangeOptions, \"agentId\">;\n\nexport const CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = \"claude-transcript-usage\";\n\n/** Opaque, path-free name for a transcript, stored beside its cursor. */\nconst sourceDigest = (transcriptPath: string): string =>\n createHash(\"sha256\").update(transcriptPath, \"utf8\").digest(\"hex\").slice(0, 32);\n\nconst SUBAGENT_STOP = \"SubagentStop\";\n\nconst agentIdOf = (record: Record<string, unknown>): string | undefined => {\n const agentId = record.agent_id ?? record.agentId;\n return typeof agentId === \"string\" && agentId.length > 0 && agentId.length <= 256 ? agentId : undefined;\n};\n\nconst agentTranscriptPathOf = (record: Record<string, unknown>): unknown =>\n record.agent_transcript_path ?? record.agentTranscriptPath;\n\n/**\n * The cursor scope of a `SubagentStop`: one cursor per subagent, beside the\n * session's own. An opaque digest of the agent id, never the id or a path.\n */\nconst subagentCursorScope = (payload: unknown): string | undefined => {\n const record = asRecord(payload);\n if (record === undefined || eventNameOf(record) !== SUBAGENT_STOP) {\n return undefined;\n }\n const agentId = agentIdOf(record);\n return agentId === undefined\n ? undefined\n : `agent-${createHash(\"sha256\").update(agentId, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/**\n * The hook-runtime side of `providers.claudeCode.readTranscriptUsage`: attach\n * each turn's model and **summed** usage to its `Stop` / `StopFailure`, and each\n * subagent run's to its `SubagentStop`.\n *\n * The runtime keeps a byte cursor per session (state value `read-cursor`):\n *\n * - `SessionStart` records where the transcript ends now (0 when it does not\n * exist yet), unless a cursor for the same transcript is already stored — a\n * compaction restart must not skip the turn it interrupted.\n * - `Stop` sums every main-thread request from the cursor to the end, and moves\n * the cursor there. That is the exact turn total: `usage_partial: false`.\n * - With no usable cursor (enabled mid-session, an expired or lost store, a\n * different transcript), a range over the cap, or a transcript that shrank, it\n * falls back to the last request in the bounded tail, attaches it with\n * `usage_partial: true`, and moves the cursor to the end so the next turn is\n * exact again.\n * - A timeout or an unreadable file attaches nothing and keeps the cursor, so\n * the next turn's range includes this one: tokens are counted late, never\n * twice and never lost.\n *\n * `SubagentStop` does the same over the subagent's own transcript\n * (`agent_transcript_path`), with a cursor of its own per subagent (see\n * {@link PayloadEnricher.cursorScope}), summing that agent's sidechain records.\n * A subagent with no cursor yet is read from the start of its file: the file is\n * that subagent's alone, so the first stop is its exact total, not a fallback.\n * The parent's cursor is never touched, and the parent's `Stop` never counts\n * sidechain records, so a subagent's requests are counted once, on its own\n * generation (issue #68).\n *\n * A payload that already carries `usage` (a wrapper attached it) is left as it\n * is, and the cursor moves past it so those tokens are not counted again.\n */\nexport const createClaudeTranscriptUsageEnricher = (\n options: ClaudeTranscriptUsageEnricherOptions = {},\n): PayloadEnricher => {\n const fileSize = async (transcriptPath: string): Promise<number | \"absent\" | undefined> => {\n try {\n const info = await stat(transcriptPath);\n return info.isFile() ? info.size : undefined;\n } catch (thrown) {\n return (thrown as { code?: unknown } | undefined)?.code === \"ENOENT\" ? \"absent\" : undefined;\n }\n };\n\n const readOptions = (agentId: string | undefined): ReadClaudeTranscriptRangeOptions => ({\n ...(options.maxRangeBytes === undefined ? {} : { maxRangeBytes: options.maxRangeBytes }),\n ...(options.rangeTimeoutMillis === undefined ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis }),\n ...(agentId === undefined ? {} : { agentId }),\n });\n\n /**\n * Sum one transcript since `fromOffset` and attach the result, or fall back to\n * the bounded tail. `fromOffset` undefined means there is no usable cursor.\n */\n const attachSince = async (\n record: Record<string, unknown>,\n transcriptPath: string,\n fromOffset: number | undefined,\n agentId: string | undefined,\n ): Promise<PayloadEnrichment> => {\n const source = sourceDigest(transcriptPath);\n const attach = (\n model: string | undefined,\n usage: ClaudeUsage | undefined,\n partial: boolean,\n ): Record<string, unknown> => ({\n ...record,\n ...(record.model === undefined && model !== undefined ? { model } : {}),\n ...(usage === undefined ? {} : { usage, usage_partial: partial }),\n });\n\n if (fromOffset !== undefined) {\n const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));\n if (range.status === \"found\") {\n return {\n payload: attach(range.model, range.usage, false),\n cursor: { source, offset: range.endOffset },\n notes: [`summed ${String(range.requestCount)} request(s) since the last stop`],\n };\n }\n if (range.reason !== \"truncated\" && range.reason !== \"over-cap\") {\n return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };\n }\n }\n\n // No usable cursor, or a range that cannot be summed within bounds.\n const tail = await boundedTail(transcriptPath, options, agentId);\n if (tail === TIMED_OUT || !(\"turn\" in tail)) {\n return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? \"timeout\" : tail.reason})`] };\n }\n const why = fromOffset === undefined ? \"no cursor for this transcript\" : \"range not summable within bounds\";\n return {\n payload: tail.turn.status === \"found\" ? attach(tail.turn.model, tail.turn.usage, true) : record,\n cursor: { source, offset: tail.endOffset },\n notes: [`${why}; attached the last request only (usage_partial)`],\n };\n };\n\n /** A wrapper attached usage: keep it, and move the cursor past what it covered. */\n const skipAttached = async (payload: unknown, transcriptPath: string): Promise<PayloadEnrichment> => {\n const size = await fileSize(transcriptPath);\n return typeof size === \"number\"\n ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } }\n : { payload };\n };\n\n const enrich = async (input: {\n readonly payload: unknown;\n readonly cursor?: ReadCursor;\n }): Promise<PayloadEnrichment> => {\n const unchanged: PayloadEnrichment = { payload: input.payload };\n const record = asRecord(input.payload);\n if (record === undefined) {\n return unchanged;\n }\n const eventName = eventNameOf(record);\n\n if (eventName === SUBAGENT_STOP) {\n const agentTranscriptPath = agentTranscriptPathOf(record);\n const agentId = agentIdOf(record);\n if (agentId === undefined || !isTranscriptPath(agentTranscriptPath)) {\n return unchanged;\n }\n if (hasUsage(record)) {\n return skipAttached(input.payload, agentTranscriptPath);\n }\n const cursor = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : undefined;\n return attachSince(record, agentTranscriptPath, cursor?.offset ?? 0, agentId);\n }\n\n const transcriptPath = transcriptPathOf(record);\n if (typeof eventName !== \"string\" || !isTranscriptPath(transcriptPath)) {\n return unchanged;\n }\n const source = sourceDigest(transcriptPath);\n const cursor = input.cursor?.source === source ? input.cursor : undefined;\n\n if (eventName === \"SessionStart\") {\n if (cursor !== undefined) {\n return unchanged;\n }\n const size = await fileSize(transcriptPath);\n if (size === undefined) {\n return { ...unchanged, notes: [\"transcript is not a readable regular file; no cursor recorded\"] };\n }\n return { payload: input.payload, cursor: { source, offset: size === \"absent\" ? 0 : size } };\n }\n\n if (!STOP_EVENTS.has(eventName)) {\n return unchanged;\n }\n if (hasUsage(record)) {\n return skipAttached(input.payload, transcriptPath);\n }\n return attachSince(record, transcriptPath, cursor?.offset, undefined);\n };\n\n return Object.freeze({\n id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,\n providerId: CLAUDE_CODE_PROVIDER_ID,\n cursorScope: subagentCursorScope,\n enrich,\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Cursor agent-hook payload contract.\n *\n * ## Provenance\n *\n * Nothing in this module is invented. Every field, spelling, and unit below is\n * established by one or both of:\n *\n * 1. **Cursor's published hooks reference** — `cursor.com/docs/agent/hooks` and\n * `cursor.com/docs/hooks.md` (two URLs serving the same reference; both read\n * 2026-07-29). Source of the event-name list, the shared envelope, each\n * event's input fields, each event's stdout response, the `hooks.json`\n * schema, exit-code semantics, and the statement that `duration` and\n * `duration_ms` are milliseconds while `timeout` is seconds.\n * 2. **Real redacted captures** — `colinsurprenant/director`, under\n * `hack/canary/cursor-cli/findings/`: two Cursor CLI runs (`2026.07.17-3e2a980`,\n * captured 2026-07-21 and 2026-07-22) and two Cursor IDE runs (`3.12.17`,\n * captured 2026-07-21), each registering the full agent-hook set and recording\n * the exact key list of all 54 payload files it saved. Source of the fields\n * the reference omits, of which keys are actually optional, and of the two\n * lifecycle facts in \"Surface dependence\" below.\n *\n * The redacted fixtures under `fixtures/parity/cursor/` restate those captured\n * shapes with synthetic values; their provenance sidecars name this capture set.\n * No real path, email, transcript, prompt, or credential is copied into this\n * repository — see `CLAUDE.md`.\n *\n * ## Envelope\n *\n * Keys are snake_case throughout, and there is exactly one generation of the\n * shape: no camelCase variant and no legacy alias table is documented or\n * observed, so none is modelled. **There is no timestamp field anywhere** — not\n * in the reference, and not in any captured payload's key list — so the adapter\n * reads `occurredAt` from the injected clock, as the Claude Code adapter does.\n *\n * ## Surface dependence (captured, not documented)\n *\n * The same `hooks.json` produces different event subsets on Cursor's two\n * surfaces, which is why the registration planner's default set is chosen the\n * way it is:\n *\n * - `stop` and `afterAgentResponse` fired in the IDE runs and in neither CLI\n * run; `sessionEnd` fired in both CLI runs and in neither IDE run.\n * - One shell invocation fires **four** hooks. The CLI capture's `fired.log`\n * records `preToolUse`, `beforeShellExecution`, `afterShellExecution`,\n * `postToolUse` in that order for a single `printenv` call, with\n * `afterShellExecution` and `postToolUse` reporting the identical\n * `duration` of 169.812. Registering both pairs would report one tool call\n * twice.\n *\n * ## Forward compatibility\n *\n * Event objects are `z.object` (unknown keys stripped), not `z.strictObject`:\n * Cursor adds payload fields between releases — the reference already documents\n * a `preToolUse.agent_message` that no captured payload carries — and a\n * telemetry hook that rejects a payload for gaining a field fails closed on the\n * one thing it should tolerate.\n */\n\nexport const CURSOR_PROVIDER_ID = \"cursor\" as const;\n\n/**\n * Agent-session hook events this adapter interprets, in Cursor's own spelling.\n *\n * The reference groups its hooks as \"agent\", \"tab\", and \"app lifecycle\". Only\n * the agent group is here; see {@link CURSOR_UNMODELLED_HOOK_EVENT_NAMES}.\n */\nexport const CURSOR_HOOK_EVENT_NAMES = [\n \"sessionStart\",\n \"sessionEnd\",\n \"beforeSubmitPrompt\",\n \"afterAgentResponse\",\n \"afterAgentThought\",\n \"preToolUse\",\n \"postToolUse\",\n \"postToolUseFailure\",\n \"beforeShellExecution\",\n \"afterShellExecution\",\n \"beforeMCPExecution\",\n \"afterMCPExecution\",\n \"beforeReadFile\",\n \"afterFileEdit\",\n \"subagentStart\",\n \"subagentStop\",\n \"preCompact\",\n \"stop\",\n] as const;\nexport type CursorHookEventName = (typeof CURSOR_HOOK_EVENT_NAMES)[number];\n\n/**\n * Event names Cursor documents that this adapter deliberately does not model,\n * each with the reason. Recognized by name so a payload carrying one is\n * reported as \"known, unmodelled\" rather than as an unrecognized provider.\n */\nexport const CURSOR_UNMODELLED_HOOK_EVENT_NAMES: Readonly<Record<string, string>> = Object.freeze({\n beforeTabFileRead:\n \"a Tab (inline-completion) hook, not an agent-session hook; it belongs to no generation or tool lifecycle this model expresses\",\n afterTabFileEdit: \"a Tab (inline-completion) hook, as above\",\n workspaceOpen:\n \"an app-lifecycle hook that the reference states omits conversation_id, generation_id, model, session_id, and transcript_path, so it carries no session to attribute telemetry to\",\n});\n\n/**\n * Events whose stdout Cursor reads a decision from, and the field it reads.\n *\n * Taken from the reference's per-event \"Output\" sections. `beforeSubmitPrompt`\n * is the one event keyed `continue` rather than `permission`; the shell and MCP\n * gates additionally accept `\"ask\"`, which this tool never emits.\n */\nexport const CURSOR_DECISION_EVENTS: Readonly<Record<string, \"permission\" | \"continue\">> =\n Object.freeze({\n preToolUse: \"permission\",\n beforeShellExecution: \"permission\",\n beforeMCPExecution: \"permission\",\n beforeReadFile: \"permission\",\n subagentStart: \"permission\",\n beforeSubmitPrompt: \"continue\",\n });\n\n/** `[{ id, value }]`, per the reference's shared envelope. */\nconst modelParamSchema = z.object({\n id: z.string(),\n value: z.string(),\n});\nexport type CursorModelParam = z.infer<typeof modelParamSchema>;\n\nconst attachmentSchema = z.object({\n type: z.string().optional(),\n file_path: z.string().optional(),\n});\n\n/** `{ old_string, new_string }` pairs. Content, never exported — see the adapter. */\nconst fileEditSchema = z.object({\n old_string: z.string().optional(),\n new_string: z.string().optional(),\n});\n\n/**\n * Token counters observed on `afterAgentResponse` and `stop` in the IDE\n * captures. Absent from the published reference, which is why they are all\n * optional and why {@link CURSOR_USAGE_INCLUSIVITY_NOTE} states the one reading\n * the captures do not settle.\n */\nconst usageFields = {\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_read_tokens: z.number().int().min(0).optional(),\n cache_write_tokens: z.number().int().min(0).optional(),\n};\n\nexport const CURSOR_USAGE_INCLUSIVITY_NOTE =\n \"Cursor does not document its token counters, so whether input_tokens already includes cache_read_tokens \" +\n \"cannot be settled from the reference. Every captured sample has cache_read_tokens strictly below \" +\n \"input_tokens (28384/43859, 7040/21033, 77920/94622) with a stable ~15-17k remainder as the cached prefix \" +\n \"grows, which is what an inclusive counter looks like; the adapter therefore reads input_tokens as the \" +\n \"canonical inclusive total and cache_read_tokens as a subset of it. Where a payload contradicts that \" +\n \"reading, the adapter drops the breakdown rather than reporting a total it cannot justify.\";\n\n/**\n * Fields the reference lists as present on every agent hook.\n *\n * `conversation_id` is the session identity every captured agent payload\n * carries, and `session_id` repeats it in every capture — see\n * {@link cursorSessionId} for why the schema no longer hard-requires the\n * former by itself. `cwd` is *not* `.min(1)` — the CLI captures report\n * `\"cwd\": \"\"` for a workspace-rooted call, and rejecting an empty string would\n * drop the whole event over a field the adapter never reads for identity.\n *\n * `user_email` and `transcript_path` are declared so they parse rather than\n * being silently stripped, and are then never read by any code path. They are a\n * real address and a real filesystem path; `tests/providers/cursor` asserts\n * neither reaches a sink.\n */\nconst envelopeShape = {\n // Not `.min(1)`: see `cursorSessionId`. A payload naming neither\n // `conversation_id` nor `session_id` is still rejected — by\n // `recognizeCursorPayload`'s post-parse check — but rejecting it here would\n // fail the whole discriminated union on a field the adapter can source from\n // either name.\n conversation_id: z.string().optional(),\n generation_id: z.string().optional(),\n session_id: z.string().optional(),\n model: z.string().optional(),\n model_id: z.string().optional(),\n model_params: z.array(modelParamSchema).max(64).optional(),\n cursor_version: z.string().optional(),\n workspace_roots: z.array(z.string()).max(64).optional(),\n cwd: z.string().optional(),\n /** Never propagated. */\n user_email: z.string().nullish(),\n /** Never propagated. */\n transcript_path: z.string().nullish(),\n};\n\nconst event = <TName extends CursorHookEventName, TShape extends z.ZodRawShape>(\n name: TName,\n shape: TShape,\n) => z.object({ ...envelopeShape, hook_event_name: z.literal(name), ...shape });\n\nconst sessionStartPayloadSchema = event(\"sessionStart\", {\n is_background_agent: z.boolean().optional(),\n composer_mode: z.string().optional(),\n});\n\n/**\n * `reason` and `final_status` are free strings rather than enums on purpose.\n * The reference lists five reasons (`completed`, `aborted`, `error`,\n * `window_close`, `user_close`) and the adapter maps exactly those; a sixth\n * Cursor adds later must degrade to `unknown`, not reject the event.\n */\nconst sessionEndPayloadSchema = event(\"sessionEnd\", {\n reason: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n is_background_agent: z.boolean().optional(),\n final_status: z.string().optional(),\n error_message: z.string().optional(),\n});\n\nconst beforeSubmitPromptPayloadSchema = event(\"beforeSubmitPrompt\", {\n prompt: z.string().optional(),\n attachments: z.array(attachmentSchema).max(256).optional(),\n composer_mode: z.string().optional(),\n});\n\nconst afterAgentResponsePayloadSchema = event(\"afterAgentResponse\", {\n text: z.string().optional(),\n ...usageFields,\n});\n\nconst afterAgentThoughtPayloadSchema = event(\"afterAgentThought\", {\n text: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n});\n\nconst preToolUsePayloadSchema = event(\"preToolUse\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n agent_message: z.string().optional(),\n});\n\n/**\n * `tool_output` is `z.unknown()` because both shapes occur: the CLI capture\n * reports an object (`{ output, exitCode }`), the IDE capture a JSON-encoded\n * string, and the reference documents the string. Neither is parsed for meaning.\n */\nconst postToolUsePayloadSchema = event(\"postToolUse\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_output: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n duration: z.number().min(0).optional(),\n});\n\nconst postToolUseFailurePayloadSchema = event(\"postToolUseFailure\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n error_message: z.string().optional(),\n failure_type: z.string().optional(),\n duration: z.number().min(0).optional(),\n is_interrupt: z.boolean().optional(),\n});\n\nconst beforeShellExecutionPayloadSchema = event(\"beforeShellExecution\", {\n command: z.string(),\n sandbox: z.boolean().optional(),\n});\n\n/**\n * No exit status. The reference lists `command`, `output`, `duration`, and\n * `sandbox`, the captures confirm exactly those, and neither carries an exit\n * code — so the adapter reports this tool end with outcome `unknown` rather\n * than assuming success.\n */\nconst afterShellExecutionPayloadSchema = event(\"afterShellExecution\", {\n command: z.string(),\n output: z.string().optional(),\n duration: z.number().min(0).optional(),\n sandbox: z.boolean().optional(),\n});\n\nconst beforeMcpExecutionPayloadSchema = event(\"beforeMCPExecution\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n url: z.string().optional(),\n command: z.string().optional(),\n});\n\n/** As with the shell pair: `result_json` is opaque, and there is no status field. */\nconst afterMcpExecutionPayloadSchema = event(\"afterMCPExecution\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n result_json: z.string().optional(),\n duration: z.number().min(0).optional(),\n});\n\nconst beforeReadFilePayloadSchema = event(\"beforeReadFile\", {\n file_path: z.string(),\n content: z.string().optional(),\n attachments: z.array(attachmentSchema).max(256).optional(),\n});\n\nconst afterFileEditPayloadSchema = event(\"afterFileEdit\", {\n file_path: z.string(),\n edits: z.array(fileEditSchema).max(1024).optional(),\n});\n\nconst subagentStartPayloadSchema = event(\"subagentStart\", {\n subagent_id: z.string().optional(),\n subagent_type: z.string().optional(),\n task: z.string().optional(),\n parent_conversation_id: z.string().optional(),\n tool_call_id: z.string().optional(),\n subagent_model: z.string().optional(),\n is_parallel_worker: z.boolean().optional(),\n git_branch: z.string().optional(),\n});\n\n/**\n * Carries no subagent identifier. The reference gives `subagentStart` a\n * `subagent_id` and gives `subagentStop` only `subagent_type`, so the two\n * cannot be paired — which is why the adapter ignores both rather than emitting\n * a `subagent.start` that nothing can close. No capture contains either event.\n */\nconst subagentStopPayloadSchema = event(\"subagentStop\", {\n subagent_type: z.string().optional(),\n status: z.string().optional(),\n task: z.string().optional(),\n description: z.string().optional(),\n summary: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n message_count: z.number().int().min(0).optional(),\n tool_call_count: z.number().int().min(0).optional(),\n loop_count: z.number().int().min(0).optional(),\n modified_files: z.array(z.string()).max(1024).optional(),\n agent_transcript_path: z.string().nullish(),\n});\n\n/** `trigger` is `auto | manual` per the reference; mapped in the adapter. */\nconst preCompactPayloadSchema = event(\"preCompact\", {\n trigger: z.string().optional(),\n context_usage_percent: z.number().optional(),\n context_tokens: z.number().int().min(0).optional(),\n context_window_size: z.number().int().min(0).optional(),\n message_count: z.number().int().min(0).optional(),\n messages_to_compact: z.number().int().min(0).optional(),\n is_first_compaction: z.boolean().optional(),\n});\n\nconst stopPayloadSchema = event(\"stop\", {\n status: z.string().optional(),\n loop_count: z.number().int().min(0).optional(),\n ...usageFields,\n});\n\nexport const cursorPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n beforeSubmitPromptPayloadSchema,\n afterAgentResponsePayloadSchema,\n afterAgentThoughtPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n beforeShellExecutionPayloadSchema,\n afterShellExecutionPayloadSchema,\n beforeMcpExecutionPayloadSchema,\n afterMcpExecutionPayloadSchema,\n beforeReadFilePayloadSchema,\n afterFileEditPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n stopPayloadSchema,\n]);\nexport type CursorPayload = z.infer<typeof cursorPayloadSchema>;\n\nexport type CursorPayloadOf<TName extends CursorHookEventName> = Extract<\n CursorPayload,\n { hook_event_name: TName }\n>;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type CursorRecognition =\n /** A modelled agent hook that validated against its schema. */\n | { readonly status: \"modelled\"; readonly payload: CursorPayload }\n /** A documented Cursor event this adapter does not model, with the reason. */\n | { readonly status: \"unmodelled\"; readonly eventName: string; readonly reason: string }\n /** A modelled event name whose payload does not satisfy its schema. */\n | { readonly status: \"invalid\"; readonly eventName: string; readonly detail: string };\n\n/**\n * Recognize a raw Cursor hook payload.\n *\n * Three outcomes rather than two, so the adapter can tell \"not Cursor at all\"\n * (undefined) from \"Cursor, but nothing this adapter turns into telemetry\"\n * (`unmodelled`) from \"Cursor, and malformed\" (`invalid`) — the middle case must\n * not be reported as a parse failure, and the last must not be reported as a\n * foreign payload.\n */\nexport const recognizeCursorPayload = (payload: unknown): CursorRecognition | undefined => {\n if (!isPlainObject(payload)) {\n return undefined;\n }\n const eventName = payload.hook_event_name;\n if (typeof eventName !== \"string\") {\n return undefined;\n }\n\n const unmodelled = CURSOR_UNMODELLED_HOOK_EVENT_NAMES[eventName];\n if (unmodelled !== undefined) {\n return { status: \"unmodelled\", eventName, reason: unmodelled };\n }\n if (!(CURSOR_HOOK_EVENT_NAMES as readonly string[]).includes(eventName)) {\n return undefined;\n }\n\n const parsed = cursorPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n const [issue] = parsed.error.issues;\n return {\n status: \"invalid\",\n eventName,\n detail:\n issue === undefined\n ? \"payload does not satisfy the cursor hook schema\"\n : `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n };\n }\n if (cursorSessionId(parsed.data) === undefined) {\n return {\n status: \"invalid\",\n eventName,\n detail: \"payload names neither conversation_id nor session_id, so it carries no session to attribute telemetry to\",\n };\n }\n return { status: \"modelled\", payload: parsed.data };\n};\n\n/** Validated payload, or `undefined` for anything else. Convenience for callers. */\nexport const normalizeCursorPayload = (payload: unknown): CursorPayload | undefined => {\n const recognized = recognizeCursorPayload(payload);\n return recognized?.status === \"modelled\" ? recognized.payload : undefined;\n};\n\n/**\n * The session identity to attribute a modelled payload to.\n *\n * `conversation_id` is preferred, but some live Cursor Agent-surface\n * `beforeSubmitPrompt` deliveries have been observed missing it while still\n * carrying `session_id` — which every capture in `./payload.ts`'s provenance\n * note shows repeating `conversation_id` exactly. Previously the schema\n * required `conversation_id` unconditionally, so any callback missing it —\n * this one included — failed detection outright and was silently declined as\n * `provider-unknown`, with no `prompt.submitted` ever emitted for that\n * conversation. Falling back to `session_id` is not a guess: it is reading the\n * same identity from the field Cursor's own envelope repeats it in, and\n * `recognizeCursorPayload` still rejects a payload naming neither.\n */\nexport const cursorSessionId = (payload: CursorPayload): string | undefined => {\n if (payload.conversation_id !== undefined && payload.conversation_id.length > 0) {\n return payload.conversation_id;\n }\n return payload.session_id !== undefined && payload.session_id.length > 0\n ? payload.session_id\n : undefined;\n};\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { cursorSessionId, normalizeCursorPayload, type CursorPayload } from \"./payload.js\";\n\n/**\n * Which Cursor callbacks carry an identifier that survives a redelivery.\n *\n * Cursor's envelope scopes the identity by `conversation_id`, or by\n * `session_id` on the live deliveries observed missing it — see\n * `cursorSessionId` in `./payload.ts`. On top of it:\n *\n * - `tool_use_id` names one tool call, and the event name separates its\n * before-edge from its after-edge and from its failure edge.\n * - `generation_id` names one generation, and `beforeSubmitPrompt` and `stop`\n * each fire once per generation.\n * - `sessionStart`/`sessionEnd` fire once per conversation, so the event name\n * alone identifies them.\n *\n * Excluded on purpose:\n *\n * - The dedicated shell, MCP, and file callbacks carry no `tool_use_id` at all —\n * neither the reference nor any capture shows one. What distinguishes two of\n * them is the command line or the file path, which are content, not\n * identifiers; the contract's component guard rejects both (no whitespace, no\n * path separators), and it is right to. `generation_id` alone would be wrong\n * in the other direction: one generation runs many shell commands, so it would\n * suppress genuine second calls as redeliveries.\n * - `preCompact` carries nothing that separates two genuine compactions.\n * - `subagentStart`/`subagentStop` produce no events at all (see `adapter.ts`),\n * so there is nothing to deduplicate.\n * - There is no timestamp field to mix in, and Cursor sends none — so the usual\n * temptation to make two same-millisecond callbacks distinguishable does not\n * even arise here.\n */\nconst deliveryComponents = (\n payload: CursorPayload,\n): { readonly components: readonly string[]; readonly evidence: readonly string[] } | undefined => {\n switch (payload.hook_event_name) {\n case \"sessionStart\":\n case \"sessionEnd\":\n return {\n components: [payload.hook_event_name],\n evidence: [`cursor fires ${payload.hook_event_name} once per conversation`],\n };\n case \"beforeSubmitPrompt\":\n case \"stop\":\n return payload.generation_id === undefined || payload.generation_id.length === 0\n ? undefined\n : {\n components: [payload.generation_id],\n evidence: [\n `payload.generation_id names one generation, which fires ${payload.hook_event_name} once`,\n ],\n };\n case \"preToolUse\":\n case \"postToolUse\":\n case \"postToolUseFailure\":\n return payload.tool_use_id === undefined || payload.tool_use_id.length === 0\n ? undefined\n : {\n components: [payload.tool_use_id],\n evidence: [\"payload.tool_use_id names one tool call and repeats on redelivery\"],\n };\n case \"afterAgentResponse\":\n case \"afterAgentThought\":\n case \"beforeShellExecution\":\n case \"afterShellExecution\":\n case \"beforeMCPExecution\":\n case \"afterMCPExecution\":\n case \"beforeReadFile\":\n case \"afterFileEdit\":\n case \"subagentStart\":\n case \"subagentStop\":\n case \"preCompact\":\n return undefined;\n }\n};\n\n/**\n * Why each Cursor callback that {@link cursorDeliveryIdentity} declines carries no\n * delivery identity.\n *\n * Exhaustive over the hook event names in `./payload.ts`. Only `preCompact` is\n * unconditionally unidentifiable; the rest appear here for the case where their\n * optional `toolCallId` is absent, which is the whole of Cursor's coverage gap.\n */\nexport const CURSOR_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n preCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n afterAgentResponse:\n \"generation_id alone would collide with stop for the same generation; Cursor fires both with the same token snapshot\",\n afterAgentThought:\n \"payload.thoughtIndex absent; generationId alone names the generation, not one thought within it\",\n subagentStart:\n \"subagentStop carries no subagent id, so the pair cannot be correlated and neither edge is identified\",\n subagentStop:\n \"subagentStop carries no subagent id, so the pair cannot be correlated and neither edge is identified\",\n beforeShellExecution:\n \"payload.toolCallId absent; the only remaining field is the command line, which is content and may not become an id\",\n afterShellExecution:\n \"payload.toolCallId absent; the only remaining field is the command line, which is content and may not become an id\",\n beforeMCPExecution:\n \"payload.toolCallId absent; the only remaining fields are the tool name and its arguments, which are content\",\n afterMCPExecution:\n \"payload.toolCallId absent; the only remaining fields are the tool name and its arguments, which are content\",\n afterFileEdit:\n \"payload.toolCallId absent; the only remaining field is the file path, which is content and may not become an id\",\n beforeReadFile:\n \"payload.toolCallId absent; the only remaining field is the file path, which is content and may not become an id\",\n});\n\nexport const cursorDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const payload = normalizeCursorPayload(input.payload);\n if (payload === undefined) {\n return undefined;\n }\n const sessionId = cursorSessionId(payload);\n if (sessionId === undefined) {\n return undefined;\n }\n const identified = deliveryComponents(payload);\n if (identified === undefined) {\n return undefined;\n }\n return {\n sessionId,\n sourceEventName: payload.hook_event_name,\n components: identified.components,\n evidence: identified.evidence,\n };\n};\n","import { sessionCwdHint, type TargetHint } from \"../../model/target.js\";\nimport type { CursorPayload } from \"./payload.js\";\n\n/**\n * Where a Cursor tool callback pointed, as a target hint (ADR 0008).\n *\n * - **`tool-path`** — `afterFileEdit.file_path` and `beforeReadFile.file_path`\n * (the reference: \"Absolute path to the file being read\").\n * - **`shell-cwd`** — the `cwd` Cursor reports on `beforeShellExecution` (the\n * reference lists it there and not on `afterShellExecution`; read on the\n * latter only if a payload carries it).\n * - **`session-cwd`** — the workspace root, when the workspace has exactly one;\n * also the only hint on `sessionStart` and `beforeSubmitPrompt`.\n * A multi-root workspace has no single session directory, so it gives none.\n *\n * The CLI captures report `cwd: \"\"` for a call rooted at the workspace; an\n * empty `cwd` is therefore \"no shell directory stated\", and falls back to the\n * workspace root rather than being read as the filesystem root.\n */\n\nconst singleWorkspaceRoot = (payload: CursorPayload): string | undefined => {\n const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);\n return roots.length === 1 ? roots[0] : undefined;\n};\n\n\nexport const cursorTargetHint = (payload: CursorPayload): TargetHint | undefined => {\n const root = singleWorkspaceRoot(payload);\n const base = root === undefined ? {} : { baseDirectory: root };\n switch (payload.hook_event_name) {\n case \"afterFileEdit\":\n case \"beforeReadFile\":\n return payload.file_path.length === 0\n ? sessionCwdHint(root)\n : { source: \"tool-path\", paths: [payload.file_path], ...base };\n case \"beforeShellExecution\":\n case \"afterShellExecution\":\n return payload.cwd !== undefined && payload.cwd.length > 0\n ? { source: \"shell-cwd\", paths: [payload.cwd], ...base }\n : sessionCwdHint(root);\n case \"sessionStart\":\n case \"beforeSubmitPrompt\":\n case \"preToolUse\":\n case \"postToolUse\":\n case \"postToolUseFailure\":\n case \"beforeMCPExecution\":\n case \"afterMCPExecution\":\n return sessionCwdHint(root);\n default:\n return undefined;\n }\n};\n","import { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\n\nexport type CursorTokenCounters = {\n readonly input_tokens?: number | undefined;\n readonly output_tokens?: number | undefined;\n readonly cache_read_tokens?: number | undefined;\n readonly cache_write_tokens?: number | undefined;\n};\n\nexport type CursorUsageNormalization = {\n readonly usage?: CanonicalUsage;\n readonly warnings: readonly string[];\n};\n\n/**\n * Normalize Cursor's token counters into canonical usage.\n *\n * These four counters appear on `afterAgentResponse` and `stop` in the IDE\n * captures and are absent from Cursor's published reference, so the mapping is\n * deliberately narrow:\n *\n * - `input_tokens` is read as the canonical *inclusive* input total and\n * `cache_read_tokens` as a subset of it. `CURSOR_USAGE_INCLUSIVITY_NOTE` in\n * `./payload.ts` records the captured evidence for that reading, and the fact\n * that Cursor does not document it.\n * - A payload where `cache_read_tokens` exceeds `input_tokens` contradicts the\n * inclusive reading. Rather than clamp — which would invent a billing story —\n * the cache breakdown is dropped, the input and output totals are kept, and a\n * warning names the contradiction.\n * - `cache_write_tokens` is **not** reported at all. Canonical usage requires an\n * explicit `cacheCreationAccounting` whenever `cacheCreationInputTokens` is\n * non-zero, and whether Cursor bills cache writes inside or beside\n * `input_tokens` is exactly what no source establishes: the reference does not\n * mention the field, and every captured sample reports 0, so there is not even\n * an arithmetic hint. `included-in-input` would understate the total and\n * `disjoint-from-input` would inflate it, so a non-zero value produces a\n * warning naming the dropped field rather than either guess.\n *\n * Each snapshot covers one generation, never a running session total, so it is\n * always reported as a `delta` observation.\n */\nexport const normalizeCursorUsage = (raw: CursorTokenCounters): CursorUsageNormalization => {\n const inputTokens = raw.input_tokens;\n const outputTokens = raw.output_tokens;\n const cacheReadTokens = raw.cache_read_tokens;\n const cacheWriteTokens = raw.cache_write_tokens;\n\n const dropped: string[] =\n cacheWriteTokens === undefined || cacheWriteTokens === 0\n ? []\n : [\n `cursor reported cache_write_tokens (${String(cacheWriteTokens)}), whose accounting relative to ` +\n \"input_tokens is undocumented, so it was not folded into canonical usage\",\n ];\n\n if (inputTokens === undefined && outputTokens === undefined && cacheReadTokens === undefined) {\n return { warnings: dropped };\n }\n\n const warnings: string[] = [...dropped];\n const contradictsInclusive =\n cacheReadTokens !== undefined && inputTokens !== undefined && cacheReadTokens > inputTokens;\n if (contradictsInclusive) {\n warnings.push(\n `cursor reported cache_read_tokens (${String(cacheReadTokens)}) above input_tokens ` +\n `(${String(inputTokens)}); the cache breakdown was dropped rather than reinterpreted`,\n );\n }\n\n const result = normalizeUsage({\n temporality: \"delta\",\n ...(inputTokens === undefined ? {} : { inputTokens }),\n ...(outputTokens === undefined ? {} : { outputTokens }),\n ...(cacheReadTokens === undefined || contradictsInclusive\n ? {}\n : { cachedInputTokens: cacheReadTokens }),\n });\n\n if (result.status === \"invalid\") {\n return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };\n }\n return { usage: result.usage, warnings: [...warnings, ...result.notes] };\n};\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { EventOutcome, ModelDescriptor } from \"../../model/events.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport {\n asProviderId,\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderHookResponseInput,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport { CURSOR_DELIVERY_GAPS, cursorDeliveryIdentity } from \"./delivery.js\";\nimport {\n CURSOR_DECISION_EVENTS,\n CURSOR_PROVIDER_ID,\n cursorSessionId,\n recognizeCursorPayload,\n type CursorPayload,\n} from \"./payload.js\";\nimport { cursorTargetHint } from \"./target.js\";\nimport { normalizeCursorUsage } from \"./usage.js\";\n\n/**\n * Provider adapter for Cursor's agent hooks.\n *\n * `./payload.ts` carries the full provenance note: the contract is derived from\n * Cursor's published hooks reference plus four real redacted capture runs, and\n * this module maps only what those establish. Three lifecycle decisions follow\n * from that evidence rather than from convenience, and each is stated where it\n * is made below:\n *\n * - `generation.end` comes from `stop`, not `afterAgentResponse`.\n * - The shell and MCP tool ends report outcome `unknown`, because Cursor sends\n * no exit status on those callbacks.\n * - Both subagent callbacks are ignored, because `subagentStop` carries no\n * subagent identifier to pair with `subagentStart`.\n */\n\nexport const CURSOR_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"compaction.performed\",\n ] as const),\n usageTemporality: \"delta\",\n // Cursor's `cache_read_tokens` is read as a subset of `input_tokens`; see\n // `./usage.ts` for the captured evidence and the guard when a payload\n // contradicts it.\n reportsCachedInput: true,\n // `cache_write_tokens` is reported by Cursor but its accounting is\n // undocumented, so it is surfaced as an extension rather than folded into a\n // canonical total. See `./usage.ts`.\n reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\n reportsReasoningOutput: false,\n reportsProviderTotal: false,\n reportsCost: false,\n // `subagentStop` carries no subagent id, so no pairable subagent lifecycle can\n // be produced. See the `ignored` branch below.\n emitsSubagentEvents: false,\n emitsCompactionEvents: true,\n requiresHookResponse: true,\n // Tool and generation callbacks carry a replay-stable id; the dedicated\n // shell/MCP/file callbacks and `preCompact` do not. See `./delivery.ts`.\n deliveryIdentifier: \"partial\",\n});\n\n/** Sentinel used when a payload names no model at all. */\nconst UNKNOWN_MODEL: ModelDescriptor = Object.freeze({ modelId: \"unknown\" });\n\n/**\n * Cursor reports a model *variant* in `model` and its base in `model_id` — the\n * captures show `model: \"composer-2.5-fast\"` beside `model_id: \"composer-2.5\"`.\n * The variant is the identifier of what ran, so it becomes `modelId`; the base\n * becomes `family`, and is dropped when it merely repeats the variant. Vendor is\n * never guessed: Cursor names no vendor anywhere in the payload.\n */\nconst toModelDescriptor = (payload: CursorPayload): ModelDescriptor => {\n const modelId = payload.model;\n if (modelId === undefined || modelId.length === 0) {\n return UNKNOWN_MODEL;\n }\n const family = payload.model_id;\n return {\n modelId,\n ...(family === undefined || family.length === 0 || family === modelId ? {} : { family }),\n };\n};\n\nconst SESSION_END_REASONS: Readonly<\n Record<string, \"completed\" | \"aborted\" | \"error\" | \"timeout\" | \"unknown\">\n> = Object.freeze({\n completed: \"completed\",\n aborted: \"aborted\",\n error: \"error\",\n // Both documented \"the window/user closed it\" reasons are an abort from the\n // agent's point of view: work stopped without finishing.\n window_close: \"aborted\",\n user_close: \"aborted\",\n});\n\n/** `stop.status` and `subagentStop.status` share this vocabulary. */\nconst STOP_STATUS_TO_OUTCOME: Readonly<Record<string, EventOutcome>> = Object.freeze({\n completed: \"ok\",\n aborted: \"cancelled\",\n error: \"error\",\n});\n\nconst COMPACT_TRIGGERS: Readonly<Record<string, \"automatic\" | \"manual\">> = Object.freeze({\n auto: \"automatic\",\n manual: \"manual\",\n});\n\n/**\n * Derive privacy-safe workspace identity from the payload's own directory facts.\n *\n * `workspace_roots` first, `cwd` only as a fallback — and never a process cwd:\n * an absent or empty list simply contributes no workspace claim, letting the\n * core's `unknown` fallback apply. The CLI captures report `cwd: \"\"`, which is\n * treated as absent rather than as the filesystem root.\n */\nconst deriveWorkspace = (\n context: ProviderContext,\n payload: CursorPayload,\n): ReturnType<typeof deriveWorkspaceIdentity> | undefined => {\n const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);\n if (roots.length === 1) {\n return deriveWorkspaceIdentity(context.privacy, {\n kind: \"working-directory\",\n absolutePath: roots[0] ?? \"\",\n });\n }\n if (roots.length > 1) {\n return deriveWorkspaceIdentity(context.privacy, {\n kind: \"explicit\",\n value: [...roots].sort().join(\"\\n\"),\n });\n }\n if (payload.cwd !== undefined && payload.cwd.length > 0) {\n return deriveWorkspaceIdentity(context.privacy, {\n kind: \"working-directory\",\n absolutePath: payload.cwd,\n });\n }\n return undefined;\n};\n\n/**\n * Stable per-call uniqueness fed into the invocation id hash. Every value comes\n * from the payload itself, never from process state, so replaying a payload\n * reproduces the same id.\n */\nconst invocationDiscriminator = (payload: CursorPayload): string | undefined => {\n switch (payload.hook_event_name) {\n case \"sessionStart\":\n case \"sessionEnd\":\n return undefined;\n case \"preToolUse\":\n case \"postToolUse\":\n case \"postToolUseFailure\":\n return payload.tool_use_id ?? payload.tool_name;\n case \"beforeShellExecution\":\n case \"afterShellExecution\":\n return payload.generation_id;\n case \"beforeMCPExecution\":\n case \"afterMCPExecution\":\n return payload.tool_name;\n case \"beforeReadFile\":\n case \"afterFileEdit\":\n return payload.generation_id;\n case \"subagentStart\":\n return payload.subagent_id;\n case \"subagentStop\":\n return payload.subagent_type;\n case \"preCompact\":\n return payload.trigger;\n default:\n return payload.generation_id;\n }\n};\n\n/**\n * A tool call id for a callback that carries none.\n *\n * `beforeShellExecution`/`afterShellExecution` and the MCP pair report no\n * `tool_use_id`, so the pair is joined on the fields that *are* stable across\n * it: the generation and the command (or server-qualified tool name). Both\n * halves of a pair derive the same id from the same payload facts, which is what\n * lets the span correlator match them — and none of it is a clock or process\n * read, so a replay derives the same id again.\n */\nconst derivedToolCallId = (\n context: ProviderContext,\n sessionId: string,\n parts: readonly string[],\n): string => context.ids.newOpaqueId([sessionId, ...parts]);\n\n/** The validated payload, or `undefined` for anything this adapter cannot map. */\nconst asModelled = (payload: unknown): CursorPayload | undefined => {\n const recognized = recognizeCursorPayload(payload);\n return recognized?.status === \"modelled\" ? recognized.payload : undefined;\n};\n\n/** Longest detection reason the contract accepts. */\nconst MAX_DETECTION_REASON_LENGTH = 160;\n\nconst bounded = (reason: string): string =>\n reason.length <= MAX_DETECTION_REASON_LENGTH\n ? reason\n : `${reason.slice(0, MAX_DETECTION_REASON_LENGTH - 1)}…`;\n\nexport type CursorAdapterOptions = {\n readonly version?: string;\n};\n\nexport const CURSOR_ADAPTER_VERSION = \"2.0.0\";\n\nexport const createCursorAdapter = (options: CursorAdapterOptions = {}): ProviderAdapter => {\n const id = asProviderId(CURSOR_PROVIDER_ID);\n const version = options.version ?? CURSOR_ADAPTER_VERSION;\n const capabilities = CURSOR_CAPABILITIES;\n\n const detect = (input: ProviderDetectionInput): ProviderDetection => {\n const recognized = recognizeCursorPayload(input.payload);\n if (recognized === undefined) {\n return unknownDetection([\"payload does not match the cursor hook contract\"]);\n }\n // Detection reasons are bounded at 160 characters, and both branches below\n // interpolate a provider-supplied string, so each is trimmed to fit rather\n // than thrown away by the schema.\n if (recognized.status === \"unmodelled\") {\n return unknownDetection([\n bounded(`cursor documents \"${recognized.eventName}\" but this adapter does not model it`),\n ]);\n }\n if (recognized.status === \"invalid\") {\n return unknownDetection([\n bounded(\n `cursor \"${recognized.eventName}\" payload does not satisfy its contract: ${recognized.detail}`,\n ),\n ]);\n }\n const { payload } = recognized;\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"exact\",\n reasons: [`payload.hook_event_name \"${payload.hook_event_name}\" recognized`],\n ...(payload.cursor_version === undefined || payload.cursor_version.length === 0\n ? {}\n : { providerVersion: payload.cursor_version }),\n sourceEventName: payload.hook_event_name,\n });\n };\n\n const identify = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): readonly IdentityClaim[] => {\n const payload = asModelled(input.payload);\n if (payload === undefined) {\n return [];\n }\n const workspace = deriveWorkspace(context, payload);\n const discriminator = invocationDiscriminator(payload);\n // Cursor's own conversation id, used exactly as reported: never\n // normalized, parent/child matched, or substituted for a derived value.\n // `session_id` repeats it in every capture, and is the fallback\n // `recognizeCursorPayload` guarantees is present when `conversation_id`\n // is not — see `cursorSessionId`.\n const sessionId = cursorSessionId(payload);\n if (sessionId === undefined) {\n return [];\n }\n // Cursor sends no timestamp on any hook — see `./payload.ts`. The clock is\n // the only available reading, as it is for Claude Code.\n const occurredAt = context.clock.now();\n const invocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId,\n sourceEventName: payload.hook_event_name,\n occurredAt,\n ...(discriminator === undefined ? {} : { discriminator }),\n });\n const claim = identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt: occurredAt,\n ...(workspace === undefined ? {} : { workspace }),\n },\n });\n return [claim];\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const recognized = recognizeCursorPayload(input.payload);\n if (recognized === undefined) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the cursor hook contract\",\n }),\n };\n }\n if (recognized.status === \"unmodelled\") {\n return {\n status: \"ignored\",\n reason: `cursor \"${recognized.eventName}\" is not modelled: ${recognized.reason}`,\n };\n }\n if (recognized.status === \"invalid\") {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: `cursor \"${recognized.eventName}\" payload is malformed (${recognized.detail})`,\n }),\n };\n }\n\n const { payload } = recognized;\n\n if (payload.hook_event_name === \"afterAgentResponse\") {\n return {\n status: \"ignored\",\n reason:\n \"the generation's terminal outcome is reported from stop, which carries a status field and the \" +\n \"identical token snapshot (captured: 43859/1076/28384/0 on both callbacks of one generation); \" +\n \"emitting generation.end from both would double-count usage, and this adapter holds no \" +\n \"cross-invocation state to deduplicate them\",\n };\n }\n\n if (payload.hook_event_name === \"afterAgentThought\") {\n return {\n status: \"ignored\",\n reason:\n \"afterAgentThought is a reasoning notification, not a generation lifecycle event; no canonical \" +\n \"event type represents it and thought text is never exported\",\n };\n }\n\n if (payload.hook_event_name === \"subagentStart\" || payload.hook_event_name === \"subagentStop\") {\n return {\n status: \"ignored\",\n reason:\n \"cursor's subagentStop payload carries no subagent identifier — the reference gives subagent_id to \" +\n \"subagentStart only — so the two callbacks cannot be paired; emitting subagent.start alone would \" +\n \"leave a delegation that never closes, and minting an id for the end would produce an unpairable one\",\n };\n }\n\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n const sessionId = input.identity.sessionId;\n const model = toModelDescriptor(payload);\n const targetHint = cursorTargetHint(payload);\n const targetHintField = targetHint === undefined ? {} : { targetHint };\n\n switch (payload.hook_event_name) {\n case \"sessionStart\":\n factory.build({\n type: \"session.start\",\n // A background agent runs unattended; an interactive session is the\n // only other state Cursor reports here.\n sessionKind:\n payload.is_background_agent === undefined\n ? \"unknown\"\n : payload.is_background_agent\n ? \"non-interactive\"\n : \"interactive\",\n agentName: \"cursor\",\n ...(payload.cursor_version === undefined || payload.cursor_version.length === 0\n ? {}\n : { agentVersion: payload.cursor_version }),\n ...(model === UNKNOWN_MODEL ? {} : { model }),\n ...(payload.composer_mode === undefined\n ? {}\n : { extensions: { \"cursor.composer_mode\": payload.composer_mode } }),\n ...targetHintField,\n });\n break;\n\n case \"sessionEnd\":\n factory.build({\n type: \"session.end\",\n reason:\n payload.reason === undefined ? \"unknown\" : (SESSION_END_REASONS[payload.reason] ?? \"unknown\"),\n ...(payload.duration_ms === undefined ? {} : { durationMillis: payload.duration_ms }),\n ...(payload.final_status === undefined\n ? {}\n : { extensions: { \"cursor.final_status\": payload.final_status } }),\n });\n break;\n\n case \"beforeSubmitPrompt\": {\n factory.build({\n type: \"prompt.submitted\",\n // Cursor reports no prompt provenance. `user` would be a guess: this\n // hook also fires for an automation-driven or resumed turn.\n promptSource: \"unknown\",\n ...targetHintField,\n ...(payload.prompt === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.prompt,\n }),\n }),\n ...(payload.attachments === undefined\n ? {}\n : { extensions: { \"cursor.attachment_count\": payload.attachments.length } }),\n });\n // `generation_id` is present on every captured agent payload, but the\n // reference does not mark it required, so an absent one degrades to a\n // prompt with no generation rather than to a fabricated id.\n if (payload.generation_id !== undefined && payload.generation_id.length > 0) {\n factory.build({\n type: \"generation.start\",\n generationId: payload.generation_id,\n model,\n });\n } else {\n warnings.push(\n \"beforeSubmitPrompt carried no generation_id, so no generation.start was emitted\",\n );\n }\n break;\n }\n\n case \"preToolUse\":\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId:\n payload.tool_use_id ??\n derivedToolCallId(context, sessionId, [\n \"tool\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n // Cursor names its tools but does not classify them, and the names are\n // not a closed set. `unknown` says so; `other` would claim a lookup\n // happened and found nothing.\n toolKind: \"unknown\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"postToolUse\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId:\n payload.tool_use_id ??\n derivedToolCallId(context, sessionId, [\n \"tool\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n // Cursor routes failures to the separate postToolUseFailure callback,\n // so reaching this one *is* the success signal.\n outcome: \"ok\",\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.tool_output === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_output,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"postToolUseFailure\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId:\n payload.tool_use_id ??\n derivedToolCallId(context, sessionId, [\n \"tool\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n outcome:\n payload.failure_type === \"timeout\"\n ? \"timeout\"\n : payload.failure_type === \"permission_denied\"\n ? \"denied\"\n : payload.is_interrupt === true\n ? \"cancelled\"\n : \"error\",\n ...(payload.failure_type === \"permission_denied\"\n ? { permissionDecision: \"denied\" as const }\n : {}),\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.error_message === undefined\n ? {}\n : {\n output: context.privacy.describeContent({\n kind: \"error-message\",\n text: payload.error_message,\n }),\n }),\n });\n break;\n\n case \"beforeShellExecution\":\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"shell\",\n payload.generation_id ?? \"\",\n payload.command,\n ]),\n toolName: \"shell\",\n toolKind: \"execute\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n input: context.privacy.describeContent({\n kind: \"tool-input\",\n text: payload.command,\n label: \"shell\",\n }),\n ...(payload.sandbox === undefined ? {} : { extensions: { \"cursor.sandbox\": payload.sandbox } }),\n });\n break;\n\n case \"afterShellExecution\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"shell\",\n payload.generation_id ?? \"\",\n payload.command,\n ]),\n toolName: \"shell\",\n // No exit code and no status field on this callback, in the reference\n // or in the captures. Reporting `ok` would assert a success Cursor\n // never claimed.\n outcome: \"unknown\",\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.output === undefined\n ? {}\n : {\n output: context.privacy.describeContent({\n kind: \"tool-output\",\n text: payload.output,\n label: \"shell\",\n }),\n }),\n ...(payload.sandbox === undefined ? {} : { extensions: { \"cursor.sandbox\": payload.sandbox } }),\n });\n break;\n\n case \"beforeMCPExecution\":\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"mcp\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n toolKind: \"network\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"afterMCPExecution\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"mcp\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n // As with the shell pair: `result_json` is opaque and there is no\n // status field to read an outcome from.\n outcome: \"unknown\",\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.result_json === undefined\n ? {}\n : {\n output: context.privacy.describeContent({\n kind: \"tool-output\",\n text: payload.result_json,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"afterFileEdit\": {\n const toolCallId = derivedToolCallId(context, sessionId, [\n \"file-edit\",\n payload.generation_id ?? \"\",\n payload.file_path,\n ]);\n // Cursor exposes no \"before edit\" callback, so the pair is emitted from\n // this one firing: an edit that reached this hook has completed.\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId,\n toolName: \"edit_file\",\n toolKind: \"write\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n input: context.privacy.describeContent({\n kind: \"tool-input\",\n text: payload.file_path,\n label: \"edit_file\",\n }),\n });\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId,\n toolName: \"edit_file\",\n outcome: \"ok\",\n // `edits[].old_string`/`new_string` are file content and are never\n // exported, in described form or otherwise. Only how many edits landed.\n ...(payload.edits === undefined\n ? {}\n : { extensions: { \"cursor.edit_count\": payload.edits.length } }),\n });\n break;\n }\n\n case \"beforeReadFile\": {\n // The protocol has no \"after read\" callback, so — as with afterFileEdit —\n // the pair is emitted from this one firing. Unlike an edit, a read that\n // reached this hook has not happened yet and may still be refused by\n // another hook, so its outcome is `unknown`, not `ok`. `content` is the\n // file's text and is never read.\n const toolCallId = derivedToolCallId(context, sessionId, [\n \"read-file\",\n payload.generation_id ?? \"\",\n payload.file_path,\n ]);\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId,\n toolName: \"read_file\",\n toolKind: \"read\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n input: context.privacy.describeContent({\n kind: \"tool-input\",\n text: payload.file_path,\n label: \"read_file\",\n }),\n });\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId,\n toolName: \"read_file\",\n outcome: \"unknown\",\n });\n break;\n }\n\n case \"preCompact\":\n factory.build({\n type: \"compaction.performed\",\n trigger:\n payload.trigger === undefined ? \"unknown\" : (COMPACT_TRIGGERS[payload.trigger] ?? \"unknown\"),\n // Cursor exposes no post-compaction callback, so `contextTokensAfter`\n // is structurally unavailable and is never estimated.\n ...(payload.context_tokens === undefined\n ? {}\n : { contextTokensBefore: payload.context_tokens }),\n ...(payload.messages_to_compact === undefined\n ? {}\n : { droppedMessageCount: payload.messages_to_compact }),\n extensions: {\n ...(payload.context_window_size === undefined\n ? {}\n : { \"cursor.context_window_size\": payload.context_window_size }),\n ...(payload.message_count === undefined\n ? {}\n : { \"cursor.message_count\": payload.message_count }),\n ...(payload.is_first_compaction === undefined\n ? {}\n : { \"cursor.is_first_compaction\": payload.is_first_compaction }),\n },\n });\n break;\n\n case \"stop\": {\n const usage = normalizeCursorUsage(payload);\n warnings.push(...usage.warnings);\n const generationId = payload.generation_id;\n if (generationId === undefined || generationId.length === 0) {\n return {\n status: \"ignored\",\n reason:\n \"stop carried no generation_id, so the generation it ends cannot be named; \" +\n \"generation.end requires one and this adapter will not mint it\",\n };\n }\n factory.build({\n type: \"generation.end\",\n generationId,\n model,\n outcome:\n payload.status === undefined ? \"unknown\" : (STOP_STATUS_TO_OUTCOME[payload.status] ?? \"unknown\"),\n ...(payload.status === undefined ? {} : { stopReason: payload.status }),\n ...(usage.usage === undefined ? {} : { usage: usage.usage }),\n ...(payload.loop_count === undefined\n ? {}\n : { extensions: { \"cursor.loop_count\": payload.loop_count } }),\n });\n break;\n }\n\n // Every remaining event name returned early above.\n }\n\n const targetHints = factory.targetHints();\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n ...(targetHints.size === 0 ? {} : { targetHints }),\n };\n };\n\n /**\n * Answer the decision callbacks in their own vocabulary.\n *\n * Cursor reads a JSON object from stdout for six events, keyed `permission`\n * for five of them and `continue` for `beforeSubmitPrompt`. Writing nothing\n * would rely on Cursor's default; writing the wrong key would be silently\n * ignored, which is the same thing while looking deliberate. So the answer is\n * always \"proceed\", spelled the way each event spells it. Never `\"ask\"` — a\n * telemetry hook must not open a prompt — and never `\"deny\"`: ADR 0004 forbids\n * this hook from being able to block the host agent, and the response type\n * pins `exitCode` to 0 for the same reason.\n */\n const hookResponse = (input: ProviderHookResponseInput): ProviderHookResponse => {\n const sourceEventName = input.detection?.sourceEventName;\n const decisionKey =\n sourceEventName === undefined ? undefined : CURSOR_DECISION_EVENTS[sourceEventName];\n if (decisionKey === undefined) {\n return SILENT_HOOK_RESPONSE;\n }\n return {\n exitCode: 0,\n contract: \"provider-protocol\",\n stdout: JSON.stringify(\n decisionKey === \"continue\" ? { continue: true } : { permission: \"allow\" },\n ),\n };\n };\n\n return {\n id,\n version,\n capabilities,\n detect,\n identify,\n deliveryIdentity: cursorDeliveryIdentity,\n deliveryGaps: CURSOR_DELIVERY_GAPS,\n parse,\n hookResponse,\n };\n};\n","import { z } from \"zod\";\n\n/**\n * Codex CLI hook stdin payloads.\n *\n * Shape is drawn from the public Codex hooks reference (developers.openai.com\n * /codex/hooks, mirrored at learn.chatgpt.com/docs/hooks) as of 2026-07. Codex\n * has no dependable `SessionEnd`, so it is deliberately not modelled here; see\n * `adapter.ts` for how `Stop` and a state-store TTL substitute for it.\n *\n * Field names Codex does not document precisely (`tool_call_id`,\n * `subagent_id`, `occurred_at`) are this adapter's own choice of a stable\n * correlation key; see the provenance note in `tests/fixtures/codex/PROVENANCE.md`.\n */\n\nconst permissionModeSchema = z.enum([\n \"default\",\n \"acceptEdits\",\n \"plan\",\n \"dontAsk\",\n \"bypassPermissions\",\n]);\nexport type CodexPermissionMode = z.infer<typeof permissionModeSchema>;\n\n/**\n * Mirrors the rollout/exec `total_token_usage` / `last_token_usage` shape.\n *\n * Codex copies the Responses API counters verbatim: `input_tokens` is the whole\n * prompt, and `cached_input_tokens` (cache reads) and `cache_write_input_tokens`\n * (cache writes, Codex 0.163+) are subsets of it. See docs/usage-semantics.md.\n */\nexport const codexUsageSchema = z.object({\n input_tokens: z.number().int().min(0).optional(),\n cached_input_tokens: z.number().int().min(0).optional(),\n cache_write_input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n reasoning_output_tokens: z.number().int().min(0).optional(),\n total_tokens: z.number().int().min(0).optional(),\n});\nexport type CodexUsage = z.infer<typeof codexUsageSchema>;\n\nconst baseFields = {\n session_id: z.string().min(1).max(256),\n cwd: z.string().min(1).max(4096).optional(),\n model: z.string().min(1).max(256).optional(),\n permission_mode: permissionModeSchema.optional(),\n transcript_path: z.string().min(1).max(4096).optional(),\n codex_version: z.string().min(1).max(64).optional(),\n /** Not part of the documented protocol; lets tests and replay stay deterministic. */\n occurred_at: z.number().int().min(0).optional(),\n};\n\nexport const codexSessionStartPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"SessionStart\"),\n source: z.enum([\"startup\", \"resume\", \"clear\", \"compact\"]).optional(),\n});\nexport type CodexSessionStartPayload = z.infer<typeof codexSessionStartPayloadSchema>;\n\nexport const codexUserPromptSubmitPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"UserPromptSubmit\"),\n turn_id: z.string().min(1).max(256).optional(),\n prompt: z.string().max(1_000_000).optional(),\n});\nexport type CodexUserPromptSubmitPayload = z.infer<typeof codexUserPromptSubmitPayloadSchema>;\n\nexport const codexPreToolUsePayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PreToolUse\"),\n turn_id: z.string().min(1).max(256).optional(),\n tool_name: z.string().min(1).max(256),\n tool_call_id: z.string().min(1).max(256).optional(),\n tool_input: z.unknown().optional(),\n});\nexport type CodexPreToolUsePayload = z.infer<typeof codexPreToolUsePayloadSchema>;\n\nexport const codexPermissionRequestPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PermissionRequest\"),\n turn_id: z.string().min(1).max(256).optional(),\n tool_name: z.string().min(1).max(256).optional(),\n tool_call_id: z.string().min(1).max(256).optional(),\n tool_input: z.unknown().optional(),\n});\nexport type CodexPermissionRequestPayload = z.infer<typeof codexPermissionRequestPayloadSchema>;\n\nexport const codexPostToolUsePayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PostToolUse\"),\n turn_id: z.string().min(1).max(256).optional(),\n tool_name: z.string().min(1).max(256),\n tool_call_id: z.string().min(1).max(256).optional(),\n tool_input: z.unknown().optional(),\n tool_response: z.unknown().optional(),\n permission_decision: z.enum([\"allowed\", \"denied\", \"deferred\"]).optional(),\n duration_ms: z.number().min(0).optional(),\n});\nexport type CodexPostToolUsePayload = z.infer<typeof codexPostToolUsePayloadSchema>;\n\nexport const codexPreCompactPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PreCompact\"),\n trigger: z.enum([\"auto\", \"manual\"]).optional(),\n context_tokens_before: z.number().int().min(0).optional(),\n});\nexport type CodexPreCompactPayload = z.infer<typeof codexPreCompactPayloadSchema>;\n\nexport const codexPostCompactPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PostCompact\"),\n trigger: z.enum([\"auto\", \"manual\"]).optional(),\n context_tokens_after: z.number().int().min(0).optional(),\n dropped_message_count: z.number().int().min(0).optional(),\n usage: codexUsageSchema.optional(),\n});\nexport type CodexPostCompactPayload = z.infer<typeof codexPostCompactPayloadSchema>;\n\nexport const codexSubagentStartPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"SubagentStart\"),\n turn_id: z.string().min(1).max(256).optional(),\n subagent_id: z.string().min(1).max(256),\n subagent_type: z.string().min(1).max(256).optional(),\n});\nexport type CodexSubagentStartPayload = z.infer<typeof codexSubagentStartPayloadSchema>;\n\nexport const codexSubagentStopPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"SubagentStop\"),\n turn_id: z.string().min(1).max(256).optional(),\n subagent_id: z.string().min(1).max(256),\n status: z.enum([\"completed\", \"failed\", \"cancelled\"]).optional(),\n usage: codexUsageSchema.optional(),\n});\nexport type CodexSubagentStopPayload = z.infer<typeof codexSubagentStopPayloadSchema>;\n\nexport const codexStopPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"Stop\"),\n turn_id: z.string().min(1).max(256).optional(),\n stop_reason: z.string().min(1).max(256).optional(),\n usage: codexUsageSchema.optional(),\n duration_ms: z.number().min(0).optional(),\n});\nexport type CodexStopPayload = z.infer<typeof codexStopPayloadSchema>;\n\nexport const CODEX_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PermissionRequest\",\n \"PostToolUse\",\n \"PreCompact\",\n \"PostCompact\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"Stop\",\n] as const;\nexport type CodexHookEventName = (typeof CODEX_HOOK_EVENT_NAMES)[number];\n\nexport const codexHookPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n codexSessionStartPayloadSchema,\n codexUserPromptSubmitPayloadSchema,\n codexPreToolUsePayloadSchema,\n codexPermissionRequestPayloadSchema,\n codexPostToolUsePayloadSchema,\n codexPreCompactPayloadSchema,\n codexPostCompactPayloadSchema,\n codexSubagentStartPayloadSchema,\n codexSubagentStopPayloadSchema,\n codexStopPayloadSchema,\n]);\nexport type CodexHookPayload = z.infer<typeof codexHookPayloadSchema>;\n\n/** Loose shape check used to award `weak` confidence to a recognizable-but-malformed payload. */\nexport const codexHookEnvelopeSchema = z.object({\n session_id: z.string().min(1),\n hook_event_name: z.enum(CODEX_HOOK_EVENT_NAMES),\n});\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { codexHookPayloadSchema, type CodexHookPayload } from \"./payload.js\";\n\n/**\n * Which Codex callbacks carry an identifier that survives a redelivery.\n *\n * - `tool_call_id` names one tool call. The event name separates the pre-edge,\n * the permission prompt, and the post-edge of that same call.\n * - `subagent_id` is required on `SubagentStart`/`SubagentStop`.\n * - `turn_id` names one turn, and Codex fires `UserPromptSubmit` and `Stop`\n * exactly once per turn — `Stop` is documented as the reliable end-of-turn\n * callback, which is what makes it safe to key on here even though Claude\n * Code's `Stop` is not.\n *\n * Excluded: `SessionStart`, `PreCompact`, and `PostCompact` carry no per-callback\n * field at all, and `tool_name` alone is not one — the same tool called twice in\n * a turn would collapse into a single delivery. `occurred_at` is not used either:\n * it is this adapter's own optional convenience field, not part of the documented\n * protocol, so a real Codex payload would not carry it.\n */\nconst deliveryComponents = (\n payload: CodexHookPayload,\n): { readonly components: readonly string[]; readonly evidence: readonly string[] } | undefined => {\n switch (payload.hook_event_name) {\n case \"PreToolUse\":\n case \"PermissionRequest\":\n case \"PostToolUse\":\n return payload.tool_call_id === undefined\n ? undefined\n : {\n components: [payload.tool_call_id],\n evidence: [\"payload.tool_call_id names one tool call and repeats on redelivery\"],\n };\n case \"SubagentStart\":\n case \"SubagentStop\":\n return {\n components: [payload.subagent_id],\n evidence: [\"payload.subagent_id names one subagent instance\"],\n };\n case \"UserPromptSubmit\":\n case \"Stop\":\n return payload.turn_id === undefined\n ? undefined\n : {\n components: [payload.turn_id],\n evidence: [`payload.turn_id names one turn, which fires ${payload.hook_event_name} once`],\n };\n case \"SessionStart\":\n case \"PreCompact\":\n case \"PostCompact\":\n return undefined;\n }\n};\n\n/**\n * Why each Codex callback that {@link codexDeliveryIdentity} declines carries no\n * delivery identity.\n *\n * Exhaustive over {@link CODEX_HOOK_EVENT_NAMES}. The tool and turn events appear\n * here because their identifying field is optional in the documented protocol:\n * `tool_call_id` and `turn_id` are this adapter's chosen correlation keys, and a\n * payload that omits one reaches the same dead end as an event that never had it.\n * Naming the absent field is the point — that is the one thing a host can fix.\n */\nexport const CODEX_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n SessionStart:\n \"no per-firing id; payload `source` (startup, resume, clear, compact) means SessionStart fires repeatedly under one session_id\",\n PreCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n PostCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n PreToolUse:\n \"payload.tool_call_id absent; tool_name is not a substitute because one turn can call the same tool twice\",\n PostToolUse:\n \"payload.tool_call_id absent; tool_name is not a substitute because one turn can call the same tool twice\",\n PermissionRequest:\n \"payload.tool_call_id absent; tool_name is not a substitute because one turn can prompt for the same tool twice\",\n UserPromptSubmit: \"payload.turn_id absent; nothing else in this callback names one turn\",\n Stop: \"payload.turn_id absent; nothing else in this callback names one turn\",\n SubagentStart: \"payload.subagent_id absent, so no subagent instance is named\",\n SubagentStop: \"payload.subagent_id absent, so no subagent instance is named\",\n});\n\nexport const codexDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return undefined;\n }\n const payload = parsed.data;\n const identified = deliveryComponents(payload);\n if (identified === undefined) {\n return undefined;\n }\n return {\n sessionId: payload.session_id,\n sourceEventName: payload.hook_event_name,\n components: identified.components,\n evidence: identified.evidence,\n };\n};\n","import type { TargetHint } from \"../../model/target.js\";\nimport { MAX_TARGET_HINT_PATHS, sessionCwdHint } from \"../../model/target.js\";\n\n/**\n * Where a Codex tool call pointed, as a target hint (ADR 0008).\n *\n * ## What the payload actually carries\n *\n * Observed against Codex CLI 0.163.0 driving a mock Responses server (the agent\n * lab, `har-plugins/agent-lab`), with the model's `exec_command` call setting\n * `workdir` to a directory *different* from the session's:\n *\n * - `PreToolUse`/`PostToolUse` for a shell call report `tool_name: \"Bash\"` and\n * `tool_input: { command: \"<string>\" }` — the `workdir` the model asked for is\n * **not** forwarded, and the envelope `cwd` stays the session's directory.\n * - An `apply_patch` invocation through the shell arrives the same way, as a\n * `Bash` call whose command starts with `apply_patch`.\n *\n * So, in order:\n *\n * 1. **`tool-path`** — patch headers (`*** Add File:`, `*** Update File:`,\n * `*** Delete File:`, `*** Move to:`) from an `apply_patch` tool's input, or\n * from a shell command that invokes `apply_patch` (Codex intercepts exactly\n * that form). Header paths are relative to the patch's working directory.\n * 2. **`shell-cwd`** — `tool_input.workdir`, which is the shell tool's own\n * argument name and what older Codex builds forwarded verbatim (the\n * `command: [argv]` shape). Read when present; current builds omit it.\n * 3. **`session-cwd`** — the envelope `cwd`, for everything else.\n */\n\nconst PATCH_HEADER = /^\\*\\*\\* (?:Add File|Update File|Delete File|Move to): (.+)$/;\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst nonEmptyString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/** The shell command as one string: Codex sends a string today, an argv array before. */\nconst commandText = (input: Record<string, unknown> | undefined): string | undefined => {\n const command = input?.command ?? input?.cmd;\n if (typeof command === \"string\") {\n return command;\n }\n if (Array.isArray(command) && command.every((part) => typeof part === \"string\")) {\n return command.join(\" \");\n }\n return undefined;\n};\n\n/** Every distinct file a patch names, or `undefined` when it names none or too many. */\nexport const patchHeaderPaths = (patch: string): readonly string[] | undefined => {\n const paths = new Set<string>();\n for (const line of patch.split(/\\r?\\n/)) {\n const match = PATCH_HEADER.exec(line.trimEnd());\n const named = match?.[1]?.trim();\n if (named !== undefined && named.length > 0) {\n paths.add(named);\n }\n }\n // Too many files to check within bounds is not a reason to check some of\n // them: a target must hold for the whole call.\n return paths.size === 0 || paths.size > MAX_TARGET_HINT_PATHS ? undefined : [...paths];\n};\n\nconst patchTextOf = (toolName: string, input: unknown): string | undefined => {\n if (typeof input === \"string\") {\n return /^apply[_-]?patch$/i.test(toolName) ? input : undefined;\n }\n const record = asRecord(input);\n if (/^apply[_-]?patch$/i.test(toolName)) {\n return (\n nonEmptyString(record?.patch) ?? nonEmptyString(record?.input) ?? commandText(record)\n );\n }\n const command = commandText(record);\n return command !== undefined && /^\\s*apply_patch\\b/.test(command) ? command : undefined;\n};\n\nexport const codexTargetHint = (\n toolName: string,\n toolInput: unknown,\n cwd: string | undefined,\n): TargetHint | undefined => {\n const record = asRecord(toolInput);\n const workdir = nonEmptyString(record?.workdir);\n const base = workdir ?? cwd;\n\n const patch = patchTextOf(toolName, toolInput);\n if (patch !== undefined) {\n const paths = patchHeaderPaths(patch);\n // A patch whose files cannot all be named is not evidence of anything\n // weaker either: the call did touch files, just not ones we can see.\n return paths === undefined\n ? undefined\n : { source: \"tool-path\", paths, ...(base === undefined ? {} : { baseDirectory: base }) };\n }\n if (workdir !== undefined) {\n return {\n source: \"shell-cwd\",\n paths: [workdir],\n ...(cwd === undefined ? {} : { baseDirectory: cwd }),\n };\n }\n return sessionCwdHint(cwd);\n};\n","import type { ToolKind } from \"../../model/events.js\";\n\nconst PATTERNS: readonly (readonly [RegExp, ToolKind])[] = [\n [/^(apply[_-]?patch|patch)$/i, \"write\"],\n [/(write|edit|create[_-]?file|delete)/i, \"write\"],\n [/^(shell|bash|exec|local[_-]?shell|run[_-]?command|terminal)$/i, \"execute\"],\n [/(read|cat|view|get[_-]?file|open[_-]?file)/i, \"read\"],\n [/(web[_-]?search|browser|fetch|http)/i, \"network\"],\n [/(search|grep|find|glob)/i, \"search\"],\n [/(subagent|delegate|task)/i, \"delegate\"],\n];\n\n/**\n * Best-effort classification from a Codex tool name.\n *\n * Codex does not publish a closed enum of tool names (built-ins like\n * `apply_patch` and `shell` are documented; MCP tool names are arbitrary), so\n * this is a heuristic rather than a lookup table. Unmatched names fall back to\n * `other`, never `unknown`, because the tool name itself is always known.\n */\nexport const classifyCodexToolKind = (toolName: string): ToolKind => {\n for (const [pattern, kind] of PATTERNS) {\n if (pattern.test(toolName)) {\n return kind;\n }\n }\n return \"other\";\n};\n","import type { UsageReport, UsageTemporality } from \"../../model/usage.js\";\nimport type { CodexUsage } from \"./payload.js\";\n\n/**\n * Project a Codex usage snapshot onto a canonical usage report.\n *\n * Codex copies the Responses API usage verbatim, so `input_tokens` is the whole\n * prompt: `cached_input_tokens` (cache reads) and, from Codex 0.163,\n * `cache_write_input_tokens` (cache writes) are subsets of it, and\n * `reasoning_output_tokens` is a subset of `output_tokens`. That is the\n * canonical shape already (`cacheCreationAccounting: \"included-in-input\"`), the\n * same one Claude Code's disjoint buckets are folded into: no arithmetic here.\n * A Codex that reports no cache-write counter leaves the field absent, which\n * normalizes to zero with `not-reported`.\n */\nexport const codexUsageToReport = (\n usage: CodexUsage,\n temporality: UsageTemporality,\n): UsageReport => ({\n temporality,\n ...(usage.input_tokens === undefined ? {} : { inputTokens: usage.input_tokens }),\n ...(usage.cached_input_tokens === undefined\n ? {}\n : { cachedInputTokens: usage.cached_input_tokens }),\n ...(usage.cache_write_input_tokens === undefined\n ? {}\n : {\n cacheCreationInputTokens: usage.cache_write_input_tokens,\n cacheCreationAccounting: \"included-in-input\" as const,\n }),\n ...(usage.output_tokens === undefined ? {} : { outputTokens: usage.output_tokens }),\n ...(usage.reasoning_output_tokens === undefined\n ? {}\n : { reasoningOutputTokens: usage.reasoning_output_tokens }),\n ...(usage.total_tokens === undefined ? {} : { providerTotalTokens: usage.total_tokens }),\n});\n\nexport type CodexTokenCountObservation = {\n readonly totalTokenUsage?: CodexUsage;\n readonly lastTokenUsage?: CodexUsage;\n};\n\n/**\n * Prefer the cumulative session snapshot over a per-turn delta.\n *\n * Codex's rollout JSONL reports both a cumulative `total_token_usage` and a\n * per-turn `last_token_usage` on the same `token_count` event. The cumulative\n * figure is the authoritative running total (never sum repeats of it across\n * events); `last_token_usage` is only used, and only marked `delta`\n * explicitly, when no cumulative figure is present.\n */\nexport const codexTokenCountToReport = (\n observation: CodexTokenCountObservation,\n): UsageReport | undefined => {\n if (observation.totalTokenUsage !== undefined) {\n return codexUsageToReport(observation.totalTokenUsage, \"cumulative\");\n }\n if (observation.lastTokenUsage !== undefined) {\n return codexUsageToReport(observation.lastTokenUsage, \"delta\");\n }\n return undefined;\n};\n","import { providerIdSchema, type ProviderId } from \"../../model/primitives.js\";\n\n/** Stable identifier for this adapter across releases. */\nexport const CODEX_PROVIDER_ID: ProviderId = providerIdSchema.parse(\"codex\");\n\n/** Adapter package version, independent of the Codex CLI's own version. */\nexport const CODEX_ADAPTER_VERSION = \"0.1.0\";\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { EventOutcome } from \"../../model/events.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport {\n invocationIdSchema,\n sessionIdSchema,\n type InvocationId,\n type SessionId,\n} from \"../../model/primitives.js\";\nimport { normalizeUsage, type CanonicalUsage } from \"../../model/usage.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport {\n codexHookEnvelopeSchema,\n codexHookPayloadSchema,\n type CodexHookPayload,\n type CodexUsage,\n} from \"./payload.js\";\nimport { CODEX_DELIVERY_GAPS, codexDeliveryIdentity } from \"./delivery.js\";\nimport { sessionCwdHint } from \"../../model/target.js\";\nimport { codexTargetHint } from \"./target.js\";\nimport { classifyCodexToolKind } from \"./tool-kind.js\";\nimport { codexUsageToReport } from \"./usage.js\";\nimport { CODEX_ADAPTER_VERSION, CODEX_PROVIDER_ID } from \"./version.js\";\n\n/**\n * Codex has no dependable `SessionEnd` (see AGENT.md task scope), so\n * `session.end` is deliberately absent from {@link CODEX_CAPABILITIES}.\n * `Stop` — fired reliably at the end of every turn — is mapped to\n * `generation.end` instead, giving a host's state store a steady stream of\n * per-session activity it can use for TTL-based session finalization.\n */\nexport const CODEX_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\n \"session.start\",\n \"prompt.submitted\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n ] as const),\n usageTemporality: \"cumulative\",\n // Every usage-bearing Codex callback stamps the *session-wide* running total\n // (`total_token_usage`), not a per-turn figure, so all of them are points on\n // one series. Diffing per `turn_id` would re-count the whole session each\n // turn; see docs/usage-semantics.md.\n cumulativeUsageSeries: \"session-lifetime\",\n reportsCachedInput: true,\n // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.\n reportsCacheCreation: true,\n cacheCreationAccounting: \"included-in-input\",\n reportsReasoningOutput: true,\n reportsProviderTotal: true,\n reportsCost: false,\n emitsSubagentEvents: true,\n emitsCompactionEvents: true,\n requiresHookResponse: false,\n // Tool, subagent, and per-turn callbacks carry a replay-stable id; session and\n // compaction callbacks do not. See `./delivery.ts` for which and why.\n deliveryIdentifier: \"partial\",\n});\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/** A Codex-specific marker strong enough to resolve a `strong` match to `exact`. */\nconst hasExactMarker = (payload: CodexHookPayload): boolean => {\n if (payload.codex_version !== undefined) {\n return true;\n }\n if (payload.permission_mode === \"dontAsk\") {\n return true;\n }\n return \"tool_name\" in payload && payload.tool_name === \"apply_patch\";\n};\n\nconst detect = (input: ProviderDetectionInput): ProviderDetection => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (parsed.success) {\n const payload = parsed.data;\n const exact = hasExactMarker(payload);\n return providerDetectionSchema.parse({\n providerId: CODEX_PROVIDER_ID,\n confidence: exact ? \"exact\" : \"strong\",\n reasons: [\n \"payload.hook_event_name matches the Codex hook protocol\",\n ...(exact ? [\"payload carries a Codex-specific marker\"] : []),\n ],\n ...(payload.codex_version === undefined ? {} : { providerVersion: payload.codex_version }),\n sourceEventName: payload.hook_event_name,\n });\n }\n\n const envelope = codexHookEnvelopeSchema.safeParse(input.payload);\n if (envelope.success) {\n return providerDetectionSchema.parse({\n providerId: CODEX_PROVIDER_ID,\n confidence: \"weak\",\n reasons: [\n \"payload.hook_event_name is a known Codex event but failed schema validation for it\",\n ],\n sourceEventName: envelope.data.hook_event_name,\n });\n }\n\n return unknownDetection([\"payload does not match the Codex hook protocol\"]);\n};\n\n/** Per-event field that distinguishes concurrent hook calls in one session. */\nconst eventDiscriminator = (payload: CodexHookPayload): string | undefined => {\n switch (payload.hook_event_name) {\n case \"PreToolUse\":\n case \"PermissionRequest\":\n case \"PostToolUse\":\n return payload.tool_call_id ?? payload.tool_name;\n case \"SubagentStart\":\n case \"SubagentStop\":\n return payload.subagent_id;\n case \"UserPromptSubmit\":\n case \"Stop\":\n return payload.turn_id;\n case \"SessionStart\":\n case \"PreCompact\":\n case \"PostCompact\":\n return undefined;\n }\n};\n\nconst identify = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n): readonly IdentityClaim[] => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return [];\n }\n const payload = parsed.data;\n const occurredAt = payload.occurred_at ?? context.clock.now();\n const sessionId = sessionIdSchema.parse(payload.session_id);\n const discriminator = eventDiscriminator(payload);\n const invocationId = context.ids.newInvocationId({\n providerId: CODEX_PROVIDER_ID,\n sessionId,\n sourceEventName: payload.hook_event_name,\n occurredAt,\n ...(discriminator === undefined ? {} : { discriminator }),\n });\n const workspace =\n payload.cwd === undefined\n ? undefined\n : deriveWorkspaceIdentity(context.privacy, { kind: \"working-directory\", absolutePath: payload.cwd });\n\n const claim = identityClaimSchema.parse({\n source: `adapter:${CODEX_PROVIDER_ID}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt: occurredAt,\n ...(workspace === undefined ? {} : { workspace }),\n },\n });\n return [claim];\n};\n\n/**\n * Time-independent correlation key for a subagent, so `SubagentStart` and\n * `SubagentStop` — two separate hook process invocations — agree on the same\n * `subagentInvocationId` even though they occur at different times.\n */\nconst deriveSubagentInvocationId = (\n context: ProviderContext,\n sessionId: SessionId,\n subagentId: string,\n): InvocationId =>\n invocationIdSchema.parse(\n `subinv_${context.ids.newOpaqueId([\"codex\", \"subagent\", sessionId, subagentId])}`,\n );\n\nconst outcomeFromToolResponse = (toolResponse: unknown): EventOutcome => {\n if (toolResponse === undefined) {\n return \"unknown\";\n }\n const record = asRecord(toolResponse);\n if (record === undefined) {\n return \"ok\";\n }\n if (typeof record.success === \"boolean\") {\n return record.success ? \"ok\" : \"error\";\n }\n if (typeof record.exit_code === \"number\" && record.exit_code !== 0) {\n return \"error\";\n }\n if (record.error !== undefined && record.error !== null && record.error !== false) {\n return \"error\";\n }\n return \"ok\";\n};\n\nconst mapTrigger = (trigger: \"auto\" | \"manual\" | undefined): \"automatic\" | \"manual\" | \"unknown\" => {\n if (trigger === \"auto\") {\n return \"automatic\";\n }\n if (trigger === \"manual\") {\n return \"manual\";\n }\n return \"unknown\";\n};\n\nconst mapSubagentOutcome = (\n status: \"completed\" | \"failed\" | \"cancelled\" | undefined,\n): EventOutcome => {\n switch (status) {\n case \"completed\":\n return \"ok\";\n case \"failed\":\n return \"error\";\n case \"cancelled\":\n return \"cancelled\";\n default:\n return \"unknown\";\n }\n};\n\nconst mapStopOutcome = (stopReason: string | undefined): EventOutcome => {\n if (stopReason === undefined) {\n return \"ok\";\n }\n const normalized = stopReason.toLowerCase();\n if (normalized.includes(\"cancel\")) {\n return \"cancelled\";\n }\n if (normalized.includes(\"timeout\")) {\n return \"timeout\";\n }\n if (normalized.includes(\"error\") || normalized.includes(\"fail\")) {\n return \"error\";\n }\n return \"ok\";\n};\n\nconst parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the Codex hook protocol\",\n }),\n };\n }\n const payload = parsed.data;\n const occurredAt = payload.occurred_at ?? context.clock.now();\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n const targetHintFor = (toolName: string, toolInput: unknown) => {\n const hint = codexTargetHint(toolName, toolInput, payload.cwd);\n return hint === undefined ? {} : { targetHint: hint };\n };\n // The session's own directory: where it runs before any tool names a path.\n const sessionHint = sessionCwdHint(payload.cwd);\n const sessionTarget = sessionHint === undefined ? {} : { targetHint: sessionHint };\n\n const buildUsage = (usage: CodexUsage | undefined): CanonicalUsage | undefined => {\n if (usage === undefined) {\n return undefined;\n }\n // Codex's hook-carried usage mirrors the rollout's cumulative\n // `total_token_usage`; see docs/usage-semantics.md.\n const normalized = normalizeUsage(codexUsageToReport(usage, \"cumulative\"));\n if (normalized.status === \"invalid\") {\n warnings.push(...normalized.issues.map((issue) => issue.message));\n return undefined;\n }\n return normalized.usage;\n };\n\n switch (payload.hook_event_name) {\n case \"SessionStart\":\n factory.build({\n type: \"session.start\",\n sessionKind: \"unknown\",\n agentName: \"codex\",\n occurredAt,\n ...(payload.codex_version === undefined ? {} : { agentVersion: payload.codex_version }),\n ...(payload.model === undefined ? {} : { model: { modelId: payload.model, vendor: \"openai\" } }),\n ...sessionTarget,\n });\n break;\n\n case \"UserPromptSubmit\":\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n occurredAt,\n ...sessionTarget,\n ...(payload.prompt === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.prompt,\n }),\n }),\n });\n break;\n\n case \"PreToolUse\": {\n const toolCallId =\n payload.tool_call_id ??\n context.ids.newOpaqueId([input.identity.sessionId, payload.turn_id ?? \"\", payload.tool_name]);\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName: payload.tool_name,\n toolKind: classifyCodexToolKind(payload.tool_name),\n occurredAt,\n ...targetHintFor(payload.tool_name, payload.tool_input),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"PermissionRequest\":\n // No canonical event type represents an in-flight approval decision;\n // it surfaces as `permissionDecision` on the paired `tool.end`. This\n // hook is only ever a silent observer here (see `hookResponse`), never\n // a party to the actual allow/deny decision.\n return {\n status: \"ignored\",\n reason: \"permission requests carry no telemetry of their own; the decision surfaces on tool.end\",\n };\n\n case \"PostToolUse\": {\n const toolCallId =\n payload.tool_call_id ??\n context.ids.newOpaqueId([input.identity.sessionId, payload.turn_id ?? \"\", payload.tool_name]);\n const permissionDecision = payload.permission_decision ?? \"not-required\";\n const outcome =\n permissionDecision === \"denied\" ? \"denied\" : outcomeFromToolResponse(payload.tool_response);\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName: payload.tool_name,\n outcome,\n permissionDecision,\n occurredAt,\n ...targetHintFor(payload.tool_name, payload.tool_input),\n ...(payload.duration_ms === undefined ? {} : { durationMillis: payload.duration_ms }),\n ...(payload.tool_response === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_response,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"PreCompact\":\n factory.build({\n type: \"compaction.performed\",\n trigger: mapTrigger(payload.trigger),\n occurredAt,\n ...(payload.context_tokens_before === undefined\n ? {}\n : { contextTokensBefore: payload.context_tokens_before }),\n });\n break;\n\n case \"PostCompact\": {\n const usage = buildUsage(payload.usage);\n factory.build({\n type: \"compaction.performed\",\n trigger: mapTrigger(payload.trigger),\n occurredAt,\n ...(payload.context_tokens_after === undefined\n ? {}\n : { contextTokensAfter: payload.context_tokens_after }),\n ...(payload.dropped_message_count === undefined\n ? {}\n : { droppedMessageCount: payload.dropped_message_count }),\n ...(usage === undefined ? {} : { usage }),\n });\n break;\n }\n\n case \"SubagentStart\": {\n const subagentInvocationId = deriveSubagentInvocationId(\n context,\n input.identity.sessionId,\n payload.subagent_id,\n );\n factory.build({\n type: \"subagent.start\",\n subagentInvocationId,\n delegationDepth: 1,\n occurredAt,\n ...(payload.subagent_type === undefined ? {} : { subagentType: payload.subagent_type }),\n ...(payload.model === undefined ? {} : { model: { modelId: payload.model, vendor: \"openai\" } }),\n });\n break;\n }\n\n case \"SubagentStop\": {\n const subagentInvocationId = deriveSubagentInvocationId(\n context,\n input.identity.sessionId,\n payload.subagent_id,\n );\n const usage = buildUsage(payload.usage);\n factory.build({\n type: \"subagent.end\",\n subagentInvocationId,\n outcome: mapSubagentOutcome(payload.status),\n occurredAt,\n ...(usage === undefined ? {} : { usage }),\n });\n break;\n }\n\n case \"Stop\": {\n const generationId =\n payload.turn_id ?? context.ids.newOpaqueId([input.identity.sessionId, \"stop\", String(occurredAt)]);\n const usage = buildUsage(payload.usage);\n factory.build({\n type: \"generation.end\",\n generationId,\n model: {\n modelId: payload.model ?? \"unknown\",\n ...(payload.model === undefined ? {} : { vendor: \"openai\" }),\n },\n outcome: mapStopOutcome(payload.stop_reason),\n occurredAt,\n ...(payload.stop_reason === undefined ? {} : { stopReason: payload.stop_reason }),\n ...(payload.duration_ms === undefined ? {} : { durationMillis: payload.duration_ms }),\n ...(usage === undefined ? {} : { usage }),\n });\n break;\n }\n }\n\n const targetHints = factory.targetHints();\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n ...(targetHints.size === 0 ? {} : { targetHints }),\n };\n};\n\n/**\n * A telemetry sidecar must never become a policy hook. Regardless of event\n * type or attribution outcome, this adapter answers every hook call silently\n * (ADR 0004): it never emits a `permissionDecision`, `continue: false`, or any\n * other field that could influence Codex's own control flow.\n */\nconst hookResponse = (): ProviderHookResponse => SILENT_HOOK_RESPONSE;\n\nexport const createCodexAdapter = (): ProviderAdapter => ({\n id: CODEX_PROVIDER_ID,\n version: CODEX_ADAPTER_VERSION,\n capabilities: CODEX_CAPABILITIES,\n detect,\n identify,\n deliveryIdentity: codexDeliveryIdentity,\n deliveryGaps: CODEX_DELIVERY_GAPS,\n parse,\n hookResponse,\n});\n","import { createHash } from \"node:crypto\";\nimport { open, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { PayloadEnricher, PayloadEnrichment, ReadCursor } from \"../../runtime/ports.js\";\nimport { CODEX_PROVIDER_ID } from \"./version.js\";\nimport { codexUsageSchema, type CodexUsage } from \"./payload.js\";\n\n/**\n * The hook-runtime side of `providers.codex.readRolloutUsage`: attach the\n * session's token usage, read from Codex's own rollout file, to a Codex `Stop`.\n *\n * Why: Codex (observed on 0.163) puts no `usage` on any hook payload. The\n * counters exist only in the rollout JSONL Codex writes for every thread\n * (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<time>-<session-id>.jsonl`), on\n * `event_msg` records of `payload.type === \"token_count\"`:\n *\n * ```text\n * { \"type\": \"event_msg\", \"payload\": { \"type\": \"token_count\", \"info\": {\n * \"total_token_usage\": { input_tokens, cached_input_tokens,\n * cache_write_input_tokens, output_tokens, reasoning_output_tokens, total_tokens },\n * \"last_token_usage\": { ...same keys, the last request only } } } }\n * ```\n *\n * and, from 0.163, on `token_usage_record` records (`payload.thread_token_usage`,\n * the same running total). `total_token_usage` is the thread's running total:\n * exactly what the Codex adapter already takes `Stop.usage` to be (cumulative,\n * one series per session, diffed against the previous snapshot downstream). So\n * the enricher attaches the **last** snapshot, never a sum, which makes every\n * read exact on its own: a late read counts late, a missed read is caught up by\n * the next `Stop`, and nothing can be counted twice. That is also why no\n * `usage_partial` exists here.\n *\n * Not part of the Codex adapter, which gets no filesystem handle (ADR 0003). The\n * runtime keeps a byte cursor per session (`read-cursor` state value):\n *\n * - `SessionStart` records where the rollout ends now (0 when it does not exist\n * yet), unless a cursor for the same file is stored already.\n * - `Stop` reads from the cursor to the end (bounded in bytes and time) and\n * attaches the last snapshot found there; the cursor moves to the end. With no\n * new snapshot since the cursor (no model request this turn, or Codex has not\n * flushed it yet) it waits once, briefly, then attaches nothing: the next\n * `Stop` carries the running total that includes it.\n * - No usable cursor, a range over the cap, or a file that shrank: the last\n * snapshot in the bounded tail is attached instead (still exact, see above).\n * - A timeout or an unreadable file attaches nothing and keeps the cursor.\n *\n * The rollout is the one named by the payload's `transcript_path`. Only when a\n * payload names none, and the host gave a sessions root, is it looked up by\n * session id — in at most {@link ROLLOUT_LOOKUP_DAYS} date directories, by an\n * exact file-name match, never recursively.\n *\n * Nothing but numeric counters and a model id leaves this module.\n */\n\nexport const CODEX_ROLLOUT_USAGE_ENRICHER_ID = \"codex-rollout-usage\";\n\nexport const DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8_388_608;\nexport const DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1_048_576;\nexport const DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;\n/** How long a `Stop` waits once for a snapshot Codex has not flushed yet. */\nexport const DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;\n/** Date directories (today and earlier, local time) searched by session id. */\nexport const ROLLOUT_LOOKUP_DAYS = 7;\n\nconst MIN_BYTES = 65_536;\nconst MAX_RANGE_BYTES = 67_108_864;\nconst MAX_TAIL_BYTES = 16_777_216;\nconst MIN_TIMEOUT_MILLIS = 10;\nconst MAX_TIMEOUT_MILLIS = 5_000;\nconst MAX_SETTLE_MILLIS = 1_000;\nconst MAX_MODEL_ID_LENGTH = 256;\n/** A date directory with more entries than this is not searched. */\nconst MAX_LOOKUP_DIR_ENTRIES = 20_000;\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;\n\nexport type CodexRolloutUsageEnricherOptions = {\n /** Most bytes one `Stop` reads from its cursor. Default 8 MiB, clamped to 64 KiB..64 MiB. */\n readonly maxRangeBytes?: number;\n /** Bytes read from the end when no cursor applies. Default 1 MiB, clamped to 64 KiB..16 MiB. */\n readonly maxTailBytes?: number;\n /** Budget for one enrichment, lookup and settle wait included. Default 500 ms, clamped to 10 ms..5 s. */\n readonly timeoutMillis?: number;\n /** Wait before the one re-read when no snapshot is found yet. Default 150 ms, 0 disables. */\n readonly settleMillis?: number;\n /**\n * `$CODEX_HOME/sessions`, for payloads that name no `transcript_path`. Absent,\n * such payloads are left alone. Supplied by the host, never read from the\n * environment here.\n */\n readonly sessionsRoot?: string;\n /** Clock for the date directories of the session-id lookup. */\n readonly now?: () => Date;\n};\n\nconst clamp = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (value === undefined || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(max, Math.max(min, Math.floor(value)));\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst isRolloutPath = (value: unknown): value is string =>\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= 4096 &&\n !value.includes(\"\\0\") &&\n path.isAbsolute(value) &&\n path.extname(value) === \".jsonl\";\n\nconst sourceDigest = (rolloutPath: string): string =>\n createHash(\"sha256\").update(rolloutPath, \"utf8\").digest(\"hex\").slice(0, 32);\n\n/** One running-total snapshot, with the model in force when it was written. */\nexport type CodexRolloutSnapshot = {\n readonly usage: CodexUsage;\n readonly model?: string;\n};\n\nconst parseUsage = (value: unknown): CodexUsage | undefined => {\n const parsed = codexUsageSchema.safeParse(value);\n if (!parsed.success) {\n return undefined;\n }\n const usage = parsed.data;\n // A snapshot must at least say how many tokens went in and out.\n return usage.input_tokens === undefined || usage.output_tokens === undefined ? undefined : usage;\n};\n\nconst modelOf = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH ? value : undefined;\n\ntype LineFacts = { readonly usage?: CodexUsage; readonly model?: string };\n\n/**\n * The running total or the model one rollout line carries, if any.\n *\n * Pre-filtered on substrings: most lines are messages, tool calls and their\n * output, and parsing them would spend the budget on records never used.\n */\nconst factsOf = (line: string): LineFacts | undefined => {\n const usageLine = line.includes('\"token_count\"') || line.includes('\"token_usage_record\"');\n const contextLine = line.includes('\"turn_context\"');\n if (!usageLine && !contextLine) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n const record = asRecord(parsed);\n const payload = asRecord(record?.payload);\n if (record === undefined || payload === undefined) {\n return undefined;\n }\n if (record.type === \"turn_context\") {\n const model = modelOf(payload.model);\n return model === undefined ? undefined : { model };\n }\n if (record.type === \"event_msg\" && payload.type === \"token_count\") {\n // 0.163 nests the counters under `info`; earlier releases put them on the payload.\n const info = asRecord(payload.info) ?? payload;\n const usage = parseUsage(info.total_token_usage);\n return usage === undefined ? undefined : { usage };\n }\n if (record.type === \"token_usage_record\") {\n const usage = parseUsage(payload.thread_token_usage);\n return usage === undefined ? undefined : { usage };\n }\n return undefined;\n};\n\n/** The last snapshot (and the last model named before or after it) in `lines`. */\nconst lastSnapshotIn = (lines: readonly string[]): CodexRolloutSnapshot | undefined => {\n let usage: CodexUsage | undefined;\n let model: string | undefined;\n for (const line of lines) {\n const facts = factsOf(line.trim());\n if (facts === undefined) {\n continue;\n }\n if (facts.model !== undefined) {\n model = facts.model;\n }\n if (facts.usage !== undefined) {\n usage = facts.usage;\n }\n }\n return usage === undefined ? undefined : { usage, ...(model === undefined ? {} : { model }) };\n};\n\ntype FileHandle = Awaited<ReturnType<typeof open>>;\n\nconst readBytes = async (handle: FileHandle, start: number, length: number): Promise<Buffer> => {\n const buffer = Buffer.alloc(length);\n let filled = 0;\n while (filled < length) {\n const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);\n if (bytesRead === 0) {\n break;\n }\n filled += bytesRead;\n }\n return buffer.subarray(0, filled);\n};\n\ntype ReadOutcome =\n | { readonly status: \"found\"; readonly snapshot?: CodexRolloutSnapshot; readonly endOffset: number }\n | { readonly status: \"unavailable\"; readonly reason: \"not-a-file\" | \"unreadable\" | \"truncated\" | \"over-cap\" };\n\n/**\n * Read `[fromOffset, end)` (or the last `tailBytes` when `fromOffset` is\n * undefined) and return the last snapshot in its complete lines.\n */\nconst readRollout = async (\n rolloutPath: string,\n fromOffset: number | undefined,\n maxRangeBytes: number,\n tailBytes: number,\n): Promise<ReadOutcome> => {\n let handle: FileHandle;\n try {\n const info = await stat(rolloutPath);\n if (!info.isFile()) {\n return { status: \"unavailable\", reason: \"not-a-file\" };\n }\n handle = await open(rolloutPath, \"r\");\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n try {\n const { size } = await handle.stat();\n let start: number;\n if (fromOffset === undefined) {\n start = Math.max(0, size - tailBytes);\n } else if (size < fromOffset) {\n return { status: \"unavailable\", reason: \"truncated\" };\n } else if (size - fromOffset > maxRangeBytes) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n } else {\n start = fromOffset;\n }\n const bytes = await readBytes(handle, start, size - start);\n const lastNewline = bytes.lastIndexOf(0x0a);\n const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;\n const lines = bytes.subarray(0, endOffset - start).toString(\"utf8\").split(\"\\n\");\n // A tail that starts mid-file starts mid-line; that fragment is not a record.\n if (fromOffset === undefined && start > 0) {\n lines.shift();\n }\n const snapshot = lastSnapshotIn(lines);\n return { status: \"found\", ...(snapshot === undefined ? {} : { snapshot }), endOffset };\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\nconst pad = (value: number): string => String(value).padStart(2, \"0\");\n\n/**\n * Find `rollout-*-<sessionId>.jsonl` in the last {@link ROLLOUT_LOOKUP_DAYS}\n * local date directories below `sessionsRoot`. Never recursive.\n */\nconst findRolloutBySessionId = async (\n sessionsRoot: string,\n sessionId: string,\n now: Date,\n): Promise<string | undefined> => {\n if (!SESSION_ID_PATTERN.test(sessionId) || !path.isAbsolute(sessionsRoot)) {\n return undefined;\n }\n const suffix = `-${sessionId}.jsonl`;\n for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {\n const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);\n const dir = path.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));\n let names: string[];\n try {\n names = await readdir(dir);\n } catch {\n continue;\n }\n if (names.length > MAX_LOOKUP_DIR_ENTRIES) {\n continue;\n }\n const match = names.find((name) => name.startsWith(\"rollout-\") && name.endsWith(suffix));\n if (match !== undefined) {\n return path.join(dir, match);\n }\n }\n return undefined;\n};\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nconst withTimeout = async <T>(work: Promise<T>, timeoutMillis: number): Promise<T | typeof TIMED_OUT> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => {\n resolve(TIMED_OUT);\n }, timeoutMillis);\n timer.unref();\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n clearTimeout(timer);\n }\n};\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, millis).unref();\n });\n\nconst hasUsage = (record: Record<string, unknown>): boolean => record.usage !== undefined;\n\nexport const createCodexRolloutUsageEnricher = (options: CodexRolloutUsageEnricherOptions = {}): PayloadEnricher => {\n const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES);\n const maxTailBytes = clamp(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES);\n const timeoutMillis = clamp(\n options.timeoutMillis,\n DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,\n MIN_TIMEOUT_MILLIS,\n MAX_TIMEOUT_MILLIS,\n );\n const settleMillis = clamp(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);\n const now = options.now ?? ((): Date => new Date());\n\n const fileSize = async (rolloutPath: string): Promise<number | \"absent\" | undefined> => {\n try {\n const info = await stat(rolloutPath);\n return info.isFile() ? info.size : undefined;\n } catch (thrown) {\n return (thrown as { code?: unknown } | undefined)?.code === \"ENOENT\" ? \"absent\" : undefined;\n }\n };\n\n const resolveRollout = async (record: Record<string, unknown>): Promise<string | undefined> => {\n const named = record.transcript_path;\n if (named !== undefined && named !== null) {\n return isRolloutPath(named) ? named : undefined;\n }\n const sessionId = record.session_id;\n if (options.sessionsRoot === undefined || typeof sessionId !== \"string\") {\n return undefined;\n }\n return findRolloutBySessionId(options.sessionsRoot, sessionId, now());\n };\n\n const enrichWithin = async (input: {\n readonly payload: unknown;\n readonly cursor?: ReadCursor;\n }): Promise<PayloadEnrichment> => {\n const unchanged: PayloadEnrichment = { payload: input.payload };\n const record = asRecord(input.payload);\n const eventName = record?.hook_event_name;\n if (record === undefined || (eventName !== \"SessionStart\" && eventName !== \"Stop\")) {\n return unchanged;\n }\n const rolloutPath = await resolveRollout(record);\n if (rolloutPath === undefined) {\n return { ...unchanged, notes: [\"no rollout named or found for this session\"] };\n }\n const source = sourceDigest(rolloutPath);\n const cursor = input.cursor?.source === source ? input.cursor : undefined;\n\n if (eventName === \"SessionStart\") {\n if (cursor !== undefined) {\n return unchanged;\n }\n const size = await fileSize(rolloutPath);\n if (size === undefined) {\n return { ...unchanged, notes: [\"rollout is not a readable regular file; no cursor recorded\"] };\n }\n return { payload: input.payload, cursor: { source, offset: size === \"absent\" ? 0 : size } };\n }\n\n if (hasUsage(record)) {\n // Codex (or a wrapper) attached usage itself: keep it, move past it.\n const size = await fileSize(rolloutPath);\n return typeof size === \"number\" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;\n }\n\n const attach = (snapshot: CodexRolloutSnapshot): Record<string, unknown> => ({\n ...record,\n ...(record.model === undefined && snapshot.model !== undefined ? { model: snapshot.model } : {}),\n usage: snapshot.usage,\n });\n\n let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);\n if (read.status === \"found\" && read.snapshot === undefined && cursor !== undefined && settleMillis > 0) {\n // Codex writes the rollout from its own task; the turn's last `token_count`\n // can land a moment after `Stop` fires. One short wait, then give up: the\n // next `Stop`'s running total includes whatever this one missed.\n await sleep(settleMillis);\n read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);\n }\n if (read.status === \"unavailable\") {\n if (read.reason !== \"truncated\" && read.reason !== \"over-cap\") {\n return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };\n }\n read = await readRollout(rolloutPath, undefined, maxRangeBytes, maxTailBytes);\n if (read.status === \"unavailable\") {\n return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };\n }\n }\n const next = { source, offset: read.endOffset };\n if (read.snapshot === undefined) {\n return { payload: input.payload, cursor: next, notes: [\"no token_count since the last stop\"] };\n }\n return {\n payload: attach(read.snapshot),\n cursor: next,\n notes: [cursor === undefined ? \"no cursor; attached the last running total in the tail\" : \"attached the running total\"],\n };\n };\n\n const enrich = async (input: { readonly payload: unknown; readonly cursor?: ReadCursor }): Promise<PayloadEnrichment> => {\n try {\n const result = await withTimeout(enrichWithin(input), timeoutMillis);\n return result === TIMED_OUT ? { payload: input.payload, notes: [\"rollout read timed out; cursor kept\"] } : result;\n } catch {\n return { payload: input.payload, notes: [\"rollout read failed; cursor kept\"] };\n }\n };\n\n return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });\n};\n\n/**\n * The last running-total snapshot in a Codex rollout, for a wrapping harness\n * that wants to attach `usage` itself. Bounded to the last `maxTailBytes`.\n * Never throws.\n */\nexport const readCodexRolloutUsage = async (\n rolloutPath: string,\n options: { readonly maxTailBytes?: number } = {},\n): Promise<CodexRolloutSnapshot | undefined> => {\n if (!isRolloutPath(rolloutPath)) {\n return undefined;\n }\n const tail = clamp(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES);\n const read = await readRollout(rolloutPath, undefined, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, tail).catch(() => undefined);\n return read?.status === \"found\" ? read.snapshot : undefined;\n};\n","/**\n * Why no Gemini CLI callback carries a delivery identity.\n *\n * This file deliberately exports no `deliveryIdentity` function. The adapter\n * declares `deliveryIdentifier: \"none\"`, and this is the record of the field-by-\n * field reasoning behind that, so a future protocol version can be checked against\n * it rather than re-litigated from scratch.\n *\n * ## What the protocol provides\n *\n * Every Gemini hook input carries exactly three things that could bear on identity\n * (see `schema.ts`): `session_id`, `hook_event_name`, and an optional `timestamp`.\n * There is no request id, no turn id, and no tool-call id anywhere in the\n * vocabulary.\n *\n * The tool-call gap is a projection, not an absence: the CLI's own\n * `ToolCallRequestInfo` carries a `callId`, but `HookEventHandler`'s\n * `fireBeforeToolEvent` / `fireAfterToolEvent` build their inputs from\n * `tool_name`, `tool_input`, `mcp_context`, and `original_request_name` only, so\n * the id never crosses into the hook. Exposing it is what would unblock\n * deduplication for the two highest-volume events.\n *\n * ## Why a timestamp is not an identity\n *\n * `timestamp` is provider-recorded rather than read from a clock when the hook\n * runs, so it does repeat on redelivery. But repeating is only half of what an\n * identity needs: it must also *separate* two genuine firings, and a millisecond\n * reading does not. Two `BeforeTool` firings for the same tool inside one\n * millisecond — a loop issuing the same call, a parallel fan-out, a fast local\n * tool — produce byte-identical `(timestamp, tool_name)` pairs. Keying on that pair\n * makes the runtime suppress the *second real call* as though it were a\n * redelivery, which silently loses a span and its usage.\n *\n * ## Why `session_id` is not an identity either\n *\n * This is the subtler one, and it is why even the once-per-session events are\n * refused. `SessionStart` carries `source: \"startup\" | \"resume\" | \"clear\"`, so the\n * Gemini CLI fires it **again within the same `session_id`** when a session is\n * resumed or cleared. `(session_id, \"SessionStart\")` therefore names a *class* of\n * firings, not one firing. Treating it as an identity would suppress every resume\n * and every clear after the first — the user's session would appear to start once\n * and never restart, and the same argument applies to `SessionEnd` on the closing\n * side.\n *\n * A constant component would have made that worse rather than better: it looks\n * like a deliberate identity while being the least discriminating value possible.\n *\n * ## Consequence\n *\n * Deduplication for the Gemini CLI is available only against a host-supplied\n * `--callback-id`. `requireCallbackId` reports every callback as\n * `provider-declares-none`, which is the honest diagnostic: the gap is in the\n * protocol, not in this adapter's reading of it. Under-reporting coverage is\n * recoverable at a collector; suppressing a real observation is not.\n *\n * **To unblock:** a per-firing identifier in the Gemini hook payload — a request,\n * turn, or invocation id, or a `session_start_id` that changes on resume and clear.\n */\n\n/**\n * Every callback, and the field that would have to exist to identify it.\n *\n * Documentation rather than control flow. Kept exhaustive so that adding a hook\n * event without revisiting delivery identity is visibly an omission.\n */\nexport const GEMINI_UNIDENTIFIABLE_CALLBACKS: Readonly<Record<string, string>> = Object.freeze({\n SessionStart:\n \"fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one\",\n SessionEnd: \"the closing side of the same problem: a cleared session ends under the same session_id\",\n BeforeTool:\n \"ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call\",\n AfterTool:\n \"ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call\",\n BeforeAgent: \"no turn id; fires once per turn with only a millisecond separating turns\",\n AfterAgent: \"no turn id; fires once per turn with only a millisecond separating turns\",\n PreCompress: \"no compaction id; can fire repeatedly within one session\",\n BeforeModel: \"no request id\",\n AfterModel:\n \"fires per streaming chunk with the same llm_request each time, so several genuine firings share one request and often one millisecond\",\n BeforeToolSelection: \"no request id\",\n Notification: \"produces no canonical event\",\n});\n","import { sessionIdSchema, type SessionId } from \"../../model/primitives.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport type { WorkspaceIdentity } from \"../../model/identity.js\";\nimport type { ProviderContext } from \"../adapter.js\";\nimport type { GeminiHookInput } from \"./schema.js\";\n\n/** Deterministic, sorted-key serialization used to derive content-addressed ids. */\nexport const stableKey = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null || input === undefined) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${walk(record[key])}`).join(\",\")}}`;\n };\n return walk(value);\n};\n\nexport const geminiSessionId = (input: GeminiHookInput): SessionId => sessionIdSchema.parse(input.session_id);\n\n/** `undefined` when the timestamp is absent or unparsable; the caller supplies a fallback. */\nexport const parseGeminiTimestamp = (timestamp: string | undefined): number | undefined => {\n if (timestamp === undefined) {\n return undefined;\n }\n const parsed = Date.parse(timestamp);\n return Number.isNaN(parsed) ? undefined : parsed;\n};\n\nexport const geminiWorkspace = (\n context: ProviderContext,\n input: GeminiHookInput,\n): WorkspaceIdentity | undefined =>\n input.cwd === undefined\n ? undefined\n : deriveWorkspaceIdentity(context.privacy, { kind: \"working-directory\", absolutePath: input.cwd });\n\n/**\n * Stable content used to key a tool call across its `BeforeTool`/`AfterTool`\n * pair.\n *\n * **`tool_input` is deliberately excluded.** A `BeforeTool` hook may return\n * `hookSpecificOutput.tool_input`, which the CLI merges with\n * `Object.assign(invocation.params, modifiedInput)` — an in-place mutation of the\n * very object it later hands to `AfterTool`. So `BeforeTool` sees the model's\n * arguments and `AfterTool` sees the rewritten ones, for one and the same call.\n * Keying on the input would split that call into two unpaired halves.\n *\n * **`original_request_name` is a distinguisher, not a replacement.** It appears\n * only on a *tail tool call* — a tool the CLI runs in place of another because an\n * `AfterTool` hook returned `hookSpecificOutput.tailToolCallRequest` — and names\n * the tool the model originally asked for, while `tool_name` names the tool\n * actually running. Keying on `original_request_name` alone would hand the tail\n * call the *original* call's id, so two different tools would share one span.\n * Both names therefore go into the key, which keeps the tail call's own\n * before/after pair together and apart from the call it replaced.\n *\n * The residual gap: two calls to the same tool in a row within one turn are not\n * distinguishable from this protocol alone. The CLI has an internal\n * `ToolCallRequestInfo.callId`, but does not pass it to hooks (see\n * `./delivery.ts`).\n */\nexport const geminiToolCallKey = (input: {\n readonly tool_name: string;\n readonly original_request_name?: string | undefined;\n}): string =>\n input.original_request_name === undefined || input.original_request_name === input.tool_name\n ? input.tool_name\n : stableKey({ tail: input.tool_name, replacing: input.original_request_name });\n\nexport const geminiToolCallId = (\n context: ProviderContext,\n sessionId: string,\n toolKey: string,\n): string => context.ids.newOpaqueId([sessionId, \"gemini-cli\", \"tool\", toolKey]);\n\n/**\n * Stable content used to key a model call across its `BeforeModel` and\n * (possibly many, streaming) `AfterModel` firings: both carry `llm_request`\n * unchanged for the same call, so hashing it correlates them without needing an\n * explicit request id, which the protocol does not provide.\n */\nexport const geminiGenerationId = (\n context: ProviderContext,\n sessionId: string,\n llmRequest: unknown,\n): string => context.ids.newOpaqueId([sessionId, \"gemini-cli\", \"generation\", stableKey(llmRequest)]);\n\n/**\n * Content that distinguishes one hook firing from the next, mixed into the\n * derived `invocationId`. Re-delivering the exact same payload (a retried or\n * duplicated hook call) reproduces the same content and therefore the same\n * invocation id, which is what makes replay idempotent at the collector.\n */\nexport const geminiCorrelationSeed = (input: GeminiHookInput): string => {\n switch (input.hook_event_name) {\n case \"SessionStart\":\n return input.source ?? \"session-start\";\n case \"SessionEnd\":\n return input.reason ?? \"session-end\";\n case \"BeforeAgent\":\n return stableKey({ prompt: input.prompt });\n case \"AfterAgent\":\n return stableKey({ prompt: input.prompt, response: input.prompt_response });\n case \"BeforeModel\":\n return stableKey(input.llm_request);\n case \"AfterModel\":\n return stableKey({ request: input.llm_request, response: input.llm_response });\n case \"BeforeToolSelection\":\n return stableKey(input.llm_request);\n case \"BeforeTool\":\n return stableKey({ tool: geminiToolCallKey(input), input: input.tool_input });\n case \"AfterTool\":\n return stableKey({\n tool: geminiToolCallKey(input),\n input: input.tool_input,\n response: input.tool_response,\n });\n case \"PreCompress\":\n return input.trigger ?? \"compress\";\n case \"Notification\":\n return stableKey({ type: input.notification_type, message: input.message });\n }\n};\n","import { z } from \"zod\";\n\n/**\n * Zod schemas for the Gemini CLI command hook protocol.\n *\n * Shapes follow the public Gemini CLI hooks reference\n * (https://geminicli.com/docs/hooks/reference/,\n * https://github.com/google-gemini/gemini-cli/blob/main/docs/hooks/writing-hooks.md)\n * cross-checked field by field against the CLI source that *produces* these\n * payloads, pinned at `google-gemini/gemini-cli@3499c84`:\n *\n * - `packages/core/src/hooks/types.ts` — `HookEventName` and the per-event input\n * interfaces.\n * - `packages/core/src/hooks/hookTranslator.ts` — `LLMRequest` / `LLMResponse`,\n * the \"decoupled\", SDK-agnostic shapes the model events carry.\n * - `packages/core/src/hooks/hookEventHandler.ts` — how each input is assembled.\n *\n * Every hook receives the base fields below plus event-specific fields keyed by\n * `hook_event_name`. Unknown extra fields are stripped rather than rejected,\n * since the CLI is free to add fields the adapter does not yet model.\n */\n\nexport const GEMINI_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"SessionEnd\",\n \"BeforeAgent\",\n \"AfterAgent\",\n \"BeforeModel\",\n \"AfterModel\",\n \"BeforeToolSelection\",\n \"BeforeTool\",\n \"AfterTool\",\n \"PreCompress\",\n \"Notification\",\n] as const;\nexport type GeminiHookEventName = (typeof GEMINI_HOOK_EVENT_NAMES)[number];\n\nconst baseHookInputSchema = z.object({\n session_id: z.string().min(1),\n transcript_path: z.string().optional(),\n cwd: z.string().optional(),\n timestamp: z.string().min(1).optional(),\n});\n\nconst llmMessageSchema = z\n .object({\n role: z.enum([\"user\", \"model\", \"system\"]).optional(),\n content: z.union([z.string(), z.array(z.unknown())]).optional(),\n })\n .loose();\n\nconst llmRequestConfigSchema = z\n .object({\n temperature: z.number().optional(),\n maxOutputTokens: z.number().int().min(0).optional(),\n })\n .loose();\n\nexport const geminiLlmRequestSchema = z\n .object({\n model: z.string().min(1).optional(),\n messages: z.array(llmMessageSchema).optional(),\n config: llmRequestConfigSchema.optional(),\n toolConfig: z.unknown().optional(),\n })\n .loose();\nexport type GeminiLlmRequest = z.infer<typeof geminiLlmRequestSchema>;\n\n/**\n * `usageMetadata`, as the hook actually receives it.\n *\n * The hook does **not** see the Gemini API's `usageMetadata` verbatim.\n * `HookTranslatorGenAIv1.toHookLLMResponse` rebuilds the object with exactly\n * three counters — `promptTokenCount`, `candidatesTokenCount`, and\n * `totalTokenCount` — and the declared `LLMResponse['usageMetadata']` type lists\n * only those three. `cachedContentTokenCount` and `thoughtsTokenCount` exist on\n * the SDK response the CLI receives, but are dropped before any hook runs, which\n * is why {@link DEFAULT_GEMINI_CAPABILITIES} declares neither cached input nor\n * reasoning output as reported.\n *\n * They stay modelled here anyway, and `mapGeminiUsage` still honours them: the\n * translator is versioned (`HookTranslator` is an abstract base with a\n * `defaultHookTranslator` instance per SDK generation), so a later version may\n * widen the projection. Modelling a counter costs nothing; silently discarding\n * one the CLI started sending would understate every cache read.\n *\n * Inclusion semantics, when a counter *is* present, follow the Gemini API:\n * `promptTokenCount` is inclusive of `cachedContentTokenCount`, while\n * `candidatesTokenCount` and `thoughtsTokenCount` are separate counters that are\n * never merged before normalization.\n */\nexport const geminiUsageMetadataSchema = z\n .object({\n promptTokenCount: z.number().int().min(0).optional(),\n cachedContentTokenCount: z.number().int().min(0).optional(),\n candidatesTokenCount: z.number().int().min(0).optional(),\n thoughtsTokenCount: z.number().int().min(0).optional(),\n totalTokenCount: z.number().int().min(0).optional(),\n })\n .loose();\nexport type GeminiUsageMetadata = z.infer<typeof geminiUsageMetadataSchema>;\n\n/**\n * A candidate in the decoupled hook response format.\n *\n * `content.parts` is `string[]` here, not the SDK's `Part[]`: the translator\n * keeps only text parts and maps them to bare strings\n * (`parts: candidate.content?.parts?.filter(hasTextProperty).map((p) => p.text)`).\n * The element type stays `unknown` so that the `{ text }` spelling — which is\n * what a *hook* writes back in `hookSpecificOutput.llm_response`, and what the\n * SDK uses — is read rather than rejected.\n *\n * `finishReason`'s declared union is five values wide, but the translator casts\n * the SDK's own `FinishReason` through unchanged, so any value the API emits\n * (`BLOCKLIST`, `PROHIBITED_CONTENT`, `MALFORMED_FUNCTION_CALL`, …) reaches the\n * hook verbatim. It is therefore typed as a free string and classified by name.\n */\nconst geminiCandidateSchema = z\n .object({\n content: z\n .object({\n role: z.string().optional(),\n parts: z.array(z.unknown()).optional(),\n })\n .loose()\n .optional(),\n finishReason: z.string().optional(),\n index: z.number().int().min(0).optional(),\n })\n .loose();\n\nexport const geminiLlmResponseSchema = z\n .object({\n /** Whole-response text, set by the translator from `getResponseText`. */\n text: z.string().optional(),\n candidates: z.array(geminiCandidateSchema).optional(),\n usageMetadata: geminiUsageMetadataSchema.optional(),\n })\n .loose();\nexport type GeminiLlmResponse = z.infer<typeof geminiLlmResponseSchema>;\n\n/**\n * Connection identity for an MCP-backed tool call, present on `BeforeTool` and\n * `AfterTool` only when the tool came from an MCP server (`McpToolContext`).\n * Modelled to record the vocabulary; the adapter reads none of it, because the\n * `command`/`args`/`url` fields describe a server the operator configured.\n */\nconst geminiMcpContextSchema = z\n .object({\n server_name: z.string().optional(),\n tool_name: z.string().optional(),\n })\n .loose();\n\nconst geminiToolResponseSchema = z\n .object({\n llmContent: z.unknown().optional(),\n returnDisplay: z.unknown().optional(),\n error: z.unknown().optional(),\n })\n .loose();\n\nexport const sessionStartInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"SessionStart\"),\n source: z.enum([\"startup\", \"resume\", \"clear\"]).optional(),\n});\n\nexport const sessionEndInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"SessionEnd\"),\n reason: z.enum([\"exit\", \"clear\", \"logout\", \"prompt_input_exit\", \"other\"]).optional(),\n});\n\nexport const beforeAgentInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeAgent\"),\n prompt: z.string().optional(),\n});\n\nexport const afterAgentInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"AfterAgent\"),\n prompt: z.string().optional(),\n prompt_response: z.string().optional(),\n stop_hook_active: z.boolean().optional(),\n});\n\nexport const beforeModelInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeModel\"),\n llm_request: geminiLlmRequestSchema,\n});\n\n/**\n * Fires once per **streaming chunk**, not once per model call: `geminiChat.ts`\n * calls `fireAfterModelEvent(originalRequest, chunk)` from inside its\n * `for await (const chunk of streamResponse)` loop. `llm_request` is the same\n * object for every chunk of one call, which is what lets `geminiGenerationId`\n * correlate them; `llm_response` is that one chunk.\n */\nexport const afterModelInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"AfterModel\"),\n llm_request: geminiLlmRequestSchema,\n llm_response: geminiLlmResponseSchema,\n});\n\nexport const beforeToolSelectionInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeToolSelection\"),\n llm_request: geminiLlmRequestSchema,\n});\n\n/**\n * `original_request_name` is present only for a **tail tool call** — a second\n * tool the CLI runs in place of the first because an `AfterTool` hook returned\n * `hookSpecificOutput.tailToolCallRequest`. It names the tool the *model* asked\n * for, while `tool_name` names the tool actually executing\n * (`ToolCallRequestInfo.originalRequestName`). It is not a rewrite marker for\n * `tool_input`; see `identity.ts` for why that distinction changes correlation.\n */\nexport const beforeToolInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeTool\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n mcp_context: geminiMcpContextSchema.optional(),\n original_request_name: z.string().min(1).optional(),\n});\n\nexport const afterToolInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"AfterTool\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_response: geminiToolResponseSchema.optional(),\n mcp_context: geminiMcpContextSchema.optional(),\n original_request_name: z.string().min(1).optional(),\n});\n\nexport const preCompressInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"PreCompress\"),\n trigger: z.enum([\"auto\", \"manual\"]).optional(),\n});\n\nexport const notificationInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"Notification\"),\n notification_type: z.string().optional(),\n message: z.string().optional(),\n details: z.unknown().optional(),\n});\n\nexport const geminiHookInputSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartInputSchema,\n sessionEndInputSchema,\n beforeAgentInputSchema,\n afterAgentInputSchema,\n beforeModelInputSchema,\n afterModelInputSchema,\n beforeToolSelectionInputSchema,\n beforeToolInputSchema,\n afterToolInputSchema,\n preCompressInputSchema,\n notificationInputSchema,\n]);\nexport type GeminiHookInput = z.infer<typeof geminiHookInputSchema>;\n\nexport type GeminiHookInputOfType<TName extends GeminiHookEventName> = Extract<\n GeminiHookInput,\n { hook_event_name: TName }\n>;\n\n/** Cheap structural check used to distinguish \"not this protocol at all\" from a shape mismatch. */\nexport const looksLikeGeminiHookPayload = (payload: unknown): boolean => {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return false;\n }\n const record = payload as Record<string, unknown>;\n return (\n typeof record.session_id === \"string\" &&\n typeof record.hook_event_name === \"string\" &&\n (GEMINI_HOOK_EVENT_NAMES as readonly string[]).includes(record.hook_event_name)\n );\n};\n","import type { ToolKind } from \"../../model/events.js\";\n\n/**\n * Classify a Gemini CLI built-in tool name into a canonical {@link ToolKind}.\n *\n * The names are Gemini's own, taken from the tool declarations at\n * `google-gemini/gemini-cli@3499c84`\n * (`packages/core/src/tools/definitions/base-declarations.ts` and\n * `packages/core/src/tools/tool-names.ts`) rather than transliterated from\n * another agent's vocabulary. Several are near-misses for a name a different CLI\n * uses and would be wrong if guessed: the edit tool is `replace`, not `edit`;\n * content search is `grep_search`, not `grep` or `search_file_content`; the shell\n * is `run_shell_command`, not `shell`; web search is `google_web_search`. There\n * is no `save_memory` tool — the CLI's own prompt says so outright and points at\n * `replace`/`write_file` on `GEMINI.md` instead.\n *\n * Unrecognized names map to `unknown` rather than a guess.\n */\nconst BUILT_IN_TOOL_KIND: Readonly<Record<string, ToolKind>> = Object.freeze({\n read_file: \"read\",\n read_many_files: \"read\",\n list_directory: \"read\",\n get_internal_docs: \"read\",\n read_mcp_resource: \"read\",\n list_mcp_resources: \"read\",\n write_file: \"write\",\n replace: \"write\",\n run_shell_command: \"execute\",\n glob: \"search\",\n grep_search: \"search\",\n web_fetch: \"network\",\n google_web_search: \"network\",\n // Gemini's subagent entry point. The CLI has no subagent hook events, so a\n // delegated run is observable only as this tool's BeforeTool/AfterTool pair.\n invoke_agent: \"delegate\",\n activate_skill: \"other\",\n ask_user: \"other\",\n write_todos: \"other\",\n enter_plan_mode: \"other\",\n exit_plan_mode: \"other\",\n update_topic: \"other\",\n complete_task: \"other\",\n tracker_create_task: \"other\",\n tracker_update_task: \"other\",\n tracker_get_task: \"other\",\n tracker_list_tasks: \"other\",\n tracker_add_dependency: \"other\",\n tracker_visualize: \"other\",\n});\n\n/**\n * MCP tools are named `mcp_<server>_<tool>` — a single underscore separator and\n * an `mcp_` prefix that `generateValidName` enforces. What such a tool does is\n * defined by the connected server, not by the Gemini CLI, so it stays `unknown`.\n * The prefix is checked before the table so that a server whose generated name\n * happens to collide with a built-in is not misclassified.\n */\nconst MCP_TOOL_PREFIX = \"mcp_\";\n\n/** Tools the CLI discovers from a project command; likewise server-defined. */\nconst DISCOVERED_TOOL_PREFIX = \"discovered_tool_\";\n\nexport const classifyGeminiToolKind = (toolName: string): ToolKind => {\n if (toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(DISCOVERED_TOOL_PREFIX)) {\n return \"unknown\";\n }\n return BUILT_IN_TOOL_KIND[toolName] ?? \"unknown\";\n};\n","import { usageReportSchema, type UsageReport } from \"../../model/usage.js\";\nimport type { GeminiUsageMetadata } from \"./schema.js\";\n\n/**\n * Map Gemini's `usageMetadata` onto a canonical {@link UsageReport}.\n *\n * ## Why `cumulative`\n *\n * `AfterModel` fires per streaming chunk, and a chunk's `usageMetadata` is a\n * snapshot of the response so far, not that chunk's own increment. Two places in\n * the Gemini CLI state this by construction: `loggingContentGenerator`'s\n * `loggingStreamWrapper` keeps `lastUsageMetadata` across the stream and reports\n * that single value as the call's usage, and `chatRecordingService`\n * `recordMessageTokens` *replaces* the recorded token counts rather than adding\n * to them. Neither sums, so a later snapshot must already contain the earlier\n * one.\n *\n * Reporting these as `delta` would therefore add every snapshot together: a\n * stream that carries usage on three chunks would bill roughly three times the\n * true prompt. Declaring `cumulative` hands the composition to the runtime,\n * which diffs each snapshot against the baseline stored at\n * `usage:<sessionId>:generation:<generationId>` — so N usage-bearing chunks\n * contribute the final total exactly once, and a redelivered chunk yields a zero\n * delta rather than a second charge.\n *\n * This holds whether the API emits usage on one chunk or on many: a lone\n * snapshot with no baseline is emitted as its own first delta, which is the same\n * number `delta` would have produced.\n *\n * ## Counters\n *\n * `promptTokenCount` is inclusive of `cachedContentTokenCount` (a subset).\n * `candidatesTokenCount` and `thoughtsTokenCount` are separate, explicit\n * counters, so canonical `outputTokens` is their sum (inclusive, per core usage\n * semantics) and `reasoningOutputTokens` carries `thoughtsTokenCount` unchanged.\n * `totalTokenCount` is passed through as `providerTotalTokens` and validated by\n * `normalizeUsage`, never reconstructed here. Gemini reports no cache-creation\n * counter, so that field is always left absent. Any counter the provider did not\n * report stays absent rather than being defaulted to zero.\n *\n * Today the CLI's hook translator strips `cachedContentTokenCount` and\n * `thoughtsTokenCount` before a hook sees them (see\n * {@link GeminiUsageMetadata}), so on current payloads the cache and reasoning\n * branches below are dormant. They are kept because the translator is versioned\n * and dropping a counter the CLI started sending is the worse failure.\n */\nexport const mapGeminiUsage = (usage: GeminiUsageMetadata | undefined): UsageReport | undefined => {\n if (usage === undefined) {\n return undefined;\n }\n const {\n promptTokenCount,\n cachedContentTokenCount,\n candidatesTokenCount,\n thoughtsTokenCount,\n totalTokenCount,\n } = usage;\n\n const reportsNothing =\n promptTokenCount === undefined &&\n cachedContentTokenCount === undefined &&\n candidatesTokenCount === undefined &&\n thoughtsTokenCount === undefined &&\n totalTokenCount === undefined;\n if (reportsNothing) {\n return undefined;\n }\n\n const hasOutput = candidatesTokenCount !== undefined || thoughtsTokenCount !== undefined;\n\n return usageReportSchema.parse({\n temporality: \"cumulative\",\n ...(promptTokenCount === undefined ? {} : { inputTokens: promptTokenCount }),\n ...(cachedContentTokenCount === undefined ? {} : { cachedInputTokens: cachedContentTokenCount }),\n ...(hasOutput\n ? { outputTokens: (candidatesTokenCount ?? 0) + (thoughtsTokenCount ?? 0) }\n : {}),\n ...(thoughtsTokenCount === undefined ? {} : { reasoningOutputTokens: thoughtsTokenCount }),\n ...(totalTokenCount === undefined ? {} : { providerTotalTokens: totalTokenCount }),\n });\n};\n\n/**\n * Whether a chunk carries a usage snapshot at all.\n *\n * Most chunks of a stream do not. Those carry no billable observation, so the\n * adapter ignores them rather than closing a generation with no usage.\n */\nexport const hasGeminiUsageSnapshot = (usage: GeminiUsageMetadata | undefined): boolean =>\n mapGeminiUsage(usage) !== undefined;\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { EventOutcome, ToolKind } from \"../../model/events.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport { providerIdSchema, type ProviderId } from \"../../model/primitives.js\";\nimport { normalizeUsage, type CanonicalUsage } from \"../../model/usage.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport { GEMINI_UNIDENTIFIABLE_CALLBACKS } from \"./delivery.js\";\nimport {\n geminiCorrelationSeed,\n geminiGenerationId,\n geminiSessionId,\n geminiToolCallId,\n geminiToolCallKey,\n geminiWorkspace,\n parseGeminiTimestamp,\n} from \"./identity.js\";\nimport { geminiHookInputSchema, looksLikeGeminiHookPayload, type GeminiHookInput } from \"./schema.js\";\nimport { classifyGeminiToolKind } from \"./tool-kind.js\";\nimport { mapGeminiUsage } from \"./usage.js\";\n\nexport const GEMINI_PROVIDER_ID = \"gemini-cli\" as const;\nexport const GEMINI_ADAPTER_VERSION = \"0.1.0\";\n\nexport const DEFAULT_GEMINI_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"compaction.performed\",\n ] as const),\n // `AfterModel` fires per streaming chunk and a chunk's `usageMetadata` is a\n // snapshot of the response so far, not that chunk's increment. See\n // `./usage.ts` for the evidence; `delta` here would bill a multi-snapshot\n // stream several times over.\n usageTemporality: \"cumulative\",\n // Both false because the CLI's hook translator strips the counters before any\n // hook runs: `toHookLLMResponse` rebuilds `usageMetadata` as exactly\n // `{ promptTokenCount, candidatesTokenCount, totalTokenCount }`. The SDK\n // response it reads does carry `cachedContentTokenCount` and\n // `thoughtsTokenCount`, so this is a gap in the hook projection rather than in\n // the model — but a consumer must be able to tell \"this provider reports no\n // cache reads\" from \"this session had none\", and today it is the former.\n reportsCachedInput: false,\n reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\n reportsReasoningOutput: false,\n reportsProviderTotal: true,\n reportsCost: false,\n // The Gemini CLI has no subagent hook events. Delegation happens through the\n // `invoke_agent` tool, so a subagent run is observable only as that tool's\n // BeforeTool/AfterTool pair — never as a distinct subagent lifecycle.\n emitsSubagentEvents: false,\n emitsCompactionEvents: true,\n requiresHookResponse: false,\n // Nothing in this protocol identifies a callback across a redelivery: there is\n // no request, turn, or tool-call id, and `session_id` repeats across resume and\n // clear. See `./delivery.ts` for the field-by-field reasoning.\n deliveryIdentifier: \"none\",\n});\n\nexport type GeminiAdapterOptions = {\n readonly id?: string;\n readonly version?: string;\n readonly capabilities?: Partial<ProviderCapabilities>;\n};\n\nconst SESSION_END_REASON_OUTCOME: Readonly<Record<string, \"completed\" | \"unknown\">> = Object.freeze({\n exit: \"completed\",\n clear: \"completed\",\n logout: \"completed\",\n prompt_input_exit: \"completed\",\n other: \"unknown\",\n});\n\nconst FINISH_REASON_OUTCOME: Readonly<Record<string, EventOutcome>> = Object.freeze({\n STOP: \"ok\",\n MAX_TOKENS: \"ok\",\n SAFETY: \"denied\",\n RECITATION: \"denied\",\n BLOCKLIST: \"denied\",\n PROHIBITED_CONTENT: \"denied\",\n SPII: \"denied\",\n LANGUAGE: \"denied\",\n MALFORMED_FUNCTION_CALL: \"error\",\n OTHER: \"unknown\",\n});\n\nconst finishReasonOutcome = (finishReason: string | undefined): EventOutcome =>\n finishReason === undefined ? \"unknown\" : (FINISH_REASON_OUTCOME[finishReason] ?? \"unknown\");\n\nconst partText = (part: unknown): string | undefined => {\n if (typeof part === \"string\") {\n return part;\n }\n if (typeof part === \"object\" && part !== null && \"text\" in part) {\n const { text } = part;\n return typeof text === \"string\" ? text : undefined;\n }\n return undefined;\n};\n\n/**\n * The hook's `content.parts` is `string[]` — the CLI's translator keeps text\n * parts only and flattens them to bare strings. The `{ text }` spelling is read\n * too, because that is what a hook writes back in\n * `hookSpecificOutput.llm_response` and what the SDK response uses.\n */\nconst joinResponseText = (parts: readonly unknown[] | undefined): string | undefined => {\n if (parts === undefined || parts.length === 0) {\n return undefined;\n }\n const texts = parts.map(partText).filter((text): text is string => text !== undefined);\n const joined = texts.join(\"\");\n return joined === \"\" ? undefined : joined;\n};\n\nconst nonEmpty = (text: string | undefined): string | undefined =>\n text === undefined || text === \"\" ? undefined : text;\n\nconst messageText = (content: string | readonly unknown[] | undefined): string | undefined => {\n if (content === undefined) {\n return undefined;\n }\n if (typeof content === \"string\") {\n return content;\n }\n return joinResponseText(content);\n};\n\n/**\n * Provider adapter for the Gemini CLI's command hooks.\n *\n * Detection is purely structural (the protocol carries no provider tag), so\n * confidence is `exact` only when the full event-specific shape validates, and\n * `weak` when the payload merely looks like this protocol. All eleven hook events\n * in the CLI's `HookEventName` enum are recognized; `AfterAgent`,\n * `BeforeToolSelection`, and `Notification` carry no canonical telemetry and are\n * parsed as `ignored`.\n *\n * `AfterModel` fires once per streaming chunk. A chunk that carries no\n * `usageMetadata` is ignored; a chunk that carries one completes a\n * `generation.end` for the generation its `llm_request` identifies. Several\n * chunks of one stream may each carry a snapshot, and each closes the *same*\n * generation: the snapshots are cumulative, so the runtime diffs them against the\n * generation's stored baseline and the stream is billed once in total rather than\n * once per chunk. See `./usage.ts` for why that is the correct reading, and\n * `./delivery.ts` for the identity trade-offs this protocol imposes.\n */\nexport const createGeminiCliAdapter = (options: GeminiAdapterOptions = {}): ProviderAdapter => {\n const id: ProviderId = providerIdSchema.parse(options.id ?? GEMINI_PROVIDER_ID);\n const version = options.version ?? GEMINI_ADAPTER_VERSION;\n const capabilities: ProviderCapabilities = {\n ...DEFAULT_GEMINI_CAPABILITIES,\n ...options.capabilities,\n };\n\n const detect = (input: ProviderDetectionInput): ProviderDetection => {\n const parsed = geminiHookInputSchema.safeParse(input.payload);\n if (parsed.success) {\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"exact\",\n reasons: [\n \"payload matches the Gemini CLI command hook schema\",\n `hook_event_name=${parsed.data.hook_event_name}`,\n ],\n sourceEventName: parsed.data.hook_event_name,\n });\n }\n if (looksLikeGeminiHookPayload(input.payload)) {\n const record = input.payload as { hook_event_name: string };\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"weak\",\n reasons: [\n \"payload has session_id and a recognized hook_event_name but failed event-specific validation\",\n ],\n sourceEventName: record.hook_event_name,\n });\n }\n return unknownDetection([\"payload does not match the Gemini CLI command hook protocol\"]);\n };\n\n const identify = (input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[] => {\n const parsed = geminiHookInputSchema.safeParse(input.payload);\n if (!parsed.success) {\n return [];\n }\n const payload = parsed.data;\n const sessionId = geminiSessionId(payload);\n const startedAt = parseGeminiTimestamp(payload.timestamp) ?? context.clock.now();\n const workspace = geminiWorkspace(context, payload);\n const invocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId,\n sourceEventName: payload.hook_event_name,\n occurredAt: startedAt,\n discriminator: geminiCorrelationSeed(payload),\n });\n\n return [\n identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt,\n ...(workspace === undefined ? {} : { workspace }),\n },\n }),\n ];\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const parsed = geminiHookInputSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the Gemini CLI command hook protocol\",\n }),\n };\n }\n const payload: GeminiHookInput = parsed.data;\n const sessionId = String(input.identity.sessionId);\n const occurredAt = input.identity.startedAt;\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n\n switch (payload.hook_event_name) {\n case \"SessionStart\": {\n factory.build({\n type: \"session.start\",\n sessionKind: \"unknown\",\n agentName: \"gemini-cli\",\n occurredAt,\n });\n break;\n }\n\n case \"SessionEnd\": {\n factory.build({\n type: \"session.end\",\n reason: SESSION_END_REASON_OUTCOME[payload.reason ?? \"other\"] ?? \"unknown\",\n occurredAt,\n });\n break;\n }\n\n case \"BeforeAgent\": {\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n occurredAt,\n ...(payload.prompt === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.prompt,\n }),\n }),\n });\n break;\n }\n\n case \"AfterAgent\": {\n return {\n status: \"ignored\",\n reason:\n \"AfterAgent marks turn completion; the canonical model has no turn-level event distinct from generation.end, so it carries no telemetry of its own\",\n };\n }\n\n case \"BeforeModel\": {\n const generationId = geminiGenerationId(context, sessionId, payload.llm_request);\n const model = { modelId: payload.llm_request.model ?? \"unknown\", vendor: \"google\" };\n const inputContent = (payload.llm_request.messages ?? [])\n .map((message) => {\n const text = messageText(message.content);\n return text === undefined\n ? undefined\n : context.privacy.describeContent({\n kind: \"prompt\",\n role: message.role === \"model\" ? \"assistant\" : (message.role ?? \"unknown\"),\n text,\n });\n })\n .filter((fact) => fact !== undefined);\n factory.build({\n type: \"generation.start\",\n generationId,\n model,\n occurredAt,\n ...(payload.llm_request.config?.maxOutputTokens === undefined\n ? {}\n : { requestedMaxOutputTokens: payload.llm_request.config.maxOutputTokens }),\n ...(inputContent.length === 0 ? {} : { inputContent }),\n });\n break;\n }\n\n case \"AfterModel\": {\n const usage = mapGeminiUsage(payload.llm_response.usageMetadata);\n if (usage === undefined) {\n return {\n status: \"ignored\",\n reason: \"AfterModel fired for a streaming chunk carrying no usageMetadata snapshot\",\n };\n }\n const generationId = geminiGenerationId(context, sessionId, payload.llm_request);\n const model = { modelId: payload.llm_request.model ?? \"unknown\", vendor: \"google\" };\n const candidate = payload.llm_response.candidates?.[0];\n // The translator also sets a whole-response `text`; fall back to it when\n // the chunk's candidate carries no text parts of its own.\n const outputText =\n joinResponseText(candidate?.content?.parts) ?? nonEmpty(payload.llm_response.text);\n const usageResult = normalizeUsageOrWarn(usage, warnings);\n factory.build({\n type: \"generation.end\",\n generationId,\n model,\n outcome: finishReasonOutcome(candidate?.finishReason),\n occurredAt,\n ...(candidate?.finishReason === undefined ? {} : { stopReason: candidate.finishReason }),\n ...(usageResult === undefined ? {} : { usage: usageResult }),\n ...(outputText === undefined\n ? {}\n : {\n outputContent: [\n context.privacy.describeContent({ kind: \"response\", role: \"assistant\", text: outputText }),\n ],\n }),\n });\n break;\n }\n\n case \"BeforeToolSelection\": {\n return {\n status: \"ignored\",\n reason: \"BeforeToolSelection carries tool-choice configuration only, not lifecycle telemetry\",\n };\n }\n\n case \"BeforeTool\": {\n const toolCallId = geminiToolCallId(context, sessionId, geminiToolCallKey(payload));\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName: payload.tool_name,\n toolKind: classifyGeminiToolKind(payload.tool_name) satisfies ToolKind,\n occurredAt,\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"AfterTool\": {\n const toolCallId = geminiToolCallId(context, sessionId, geminiToolCallKey(payload));\n const hasError = payload.tool_response?.error !== undefined;\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName: payload.tool_name,\n outcome: hasError ? \"error\" : \"ok\",\n occurredAt,\n ...(payload.tool_response === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_response,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"PreCompress\": {\n factory.build({\n type: \"compaction.performed\",\n trigger: payload.trigger === \"manual\" ? \"manual\" : payload.trigger === \"auto\" ? \"automatic\" : \"unknown\",\n occurredAt,\n });\n break;\n }\n\n case \"Notification\": {\n return {\n status: \"ignored\",\n reason: \"Notification is observability-only in the Gemini CLI protocol and has no canonical event type\",\n };\n }\n }\n\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n };\n\n const hookResponse = (): ProviderHookResponse => SILENT_HOOK_RESPONSE;\n\n return {\n id,\n version,\n capabilities,\n detect,\n identify,\n // No `deliveryIdentity`: the capability is `none`, and offering a resolver\n // that always declines would be a contradiction the runtime never consults.\n // The gap table is still worth carrying — \"the protocol has no request id\" is\n // the actionable half of that answer, and only this adapter can say it.\n deliveryGaps: GEMINI_UNIDENTIFIABLE_CALLBACKS,\n parse,\n hookResponse,\n };\n};\n\nconst normalizeUsageOrWarn = (\n usage: ReturnType<typeof mapGeminiUsage>,\n warnings: string[],\n): CanonicalUsage | undefined => {\n if (usage === undefined) {\n return undefined;\n }\n const normalized = normalizeUsage(usage);\n if (normalized.status === \"invalid\") {\n warnings.push(...normalized.issues.map((issue) => issue.message));\n return undefined;\n }\n return normalized.usage;\n};\n","import { z } from \"zod\";\n\n/**\n * Raw hook payload shapes for Google Antigravity.\n *\n * Provenance: synthetic, reconstructed from the documented camelCase command\n * hooks and field names the integration task specified as verified —\n * `conversationId`, `workspacePaths`, `stepIdx`, `invocationNum`,\n * `transcriptPath`, `artifactDirectoryPath` — plus the five hook names\n * (`PreInvocation`, `PostInvocation`, `PreToolUse`, `PostToolUse`, `Stop`).\n * Every other field below (`toolName`, `toolInput`, `toolResponse`, `isError`,\n * `fullyIdle`, `agentVersion`) is an inferred reconstruction needed for the\n * hook to carry any tool or lifecycle fact at all; none of it has been\n * confirmed against a real Antigravity capture. See `./maturity.ts` for the\n * promotion gates that require that confirmation. No fixture in this package\n * is a copy of a real transcript, path, or credential.\n */\n\nexport const ANTIGRAVITY_HOOK_EVENT_NAMES = [\n \"PreInvocation\",\n \"PostInvocation\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"Stop\",\n] as const;\nexport type AntigravityHookEventName = (typeof ANTIGRAVITY_HOOK_EVENT_NAMES)[number];\n\nconst hookEventNameSchema = z.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);\n\n/**\n * Loose shape check used only to recognize a malformed-but-clearly-Antigravity\n * payload: unknown keys pass through so additive fields degrade safely.\n */\nexport const antigravityWeakShapeSchema = z.object({ hookEventName: hookEventNameSchema }).passthrough();\n\nconst commonFields = {\n conversationId: z.string().min(1),\n workspacePaths: z.array(z.string().min(1)).max(64),\n invocationNum: z.number().int().min(0),\n /** Never disclosed: a real filesystem path. Accepted, never propagated. */\n transcriptPath: z.string().min(1).optional(),\n /** Never disclosed: a real filesystem path. Accepted, never propagated. */\n artifactDirectoryPath: z.string().min(1).optional(),\n};\n\nexport const preInvocationPayloadSchema = z.object({\n hookEventName: z.literal(\"PreInvocation\"),\n ...commonFields,\n agentVersion: z.string().min(1).optional(),\n});\nexport type PreInvocationPayload = z.infer<typeof preInvocationPayloadSchema>;\n\nexport const postInvocationPayloadSchema = z.object({\n hookEventName: z.literal(\"PostInvocation\"),\n ...commonFields,\n agentVersion: z.string().min(1).optional(),\n});\nexport type PostInvocationPayload = z.infer<typeof postInvocationPayloadSchema>;\n\nexport const preToolUsePayloadSchema = z.object({\n hookEventName: z.literal(\"PreToolUse\"),\n ...commonFields,\n stepIdx: z.number().int().min(0),\n toolName: z.string().min(1),\n toolInput: z.unknown().optional(),\n});\nexport type PreToolUsePayload = z.infer<typeof preToolUsePayloadSchema>;\n\nexport const postToolUsePayloadSchema = z.object({\n hookEventName: z.literal(\"PostToolUse\"),\n ...commonFields,\n stepIdx: z.number().int().min(0),\n toolName: z.string().min(1),\n toolResponse: z.unknown().optional(),\n isError: z.boolean().optional(),\n});\nexport type PostToolUsePayload = z.infer<typeof postToolUsePayloadSchema>;\n\nexport const stopPayloadSchema = z.object({\n hookEventName: z.literal(\"Stop\"),\n ...commonFields,\n fullyIdle: z.boolean(),\n});\nexport type StopPayload = z.infer<typeof stopPayloadSchema>;\n\nexport const antigravityHookPayloadSchema = z.discriminatedUnion(\"hookEventName\", [\n preInvocationPayloadSchema,\n postInvocationPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n stopPayloadSchema,\n]);\nexport type AntigravityHookPayload = z.infer<typeof antigravityHookPayloadSchema>;\n\n/** The tool name documented as the experimental subagent-delegation relationship. */\nexport const ANTIGRAVITY_SUBAGENT_TOOL_NAME = \"invoke_subagent\" as const;\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { antigravityHookPayloadSchema } from \"./payload.js\";\n\n/**\n * Which Antigravity callbacks carry an identifier that survives a redelivery.\n *\n * Everything here is built from `invocationNum` and `stepIdx` — the two counters\n * on the *verified* field list (see `./payload.ts`) — scoped by the equally\n * verified `conversationId`:\n *\n * - The tool pair takes both counters. Together they name one step of one\n * invocation, and the event name separates its before-edge from its after-edge.\n * - The invocation pair takes `invocationNum` alone. A counter named for the\n * invocation it numbers is what makes `PreInvocation` fire once per value of\n * it: a redelivery repeats the number, while a genuine second invocation\n * advances it. That is the same argument the tool pair rests on, applied to the\n * field that is present on *every* Antigravity payload rather than only the\n * tool ones.\n *\n * `Stop` remains excluded. It can fire more than once per invocation (idle, then\n * fully idle), and the only field that would separate those two firings —\n * `fullyIdle` — is a reconstruction this adapter has not confirmed against a real\n * capture, so it is not something to build an at-most-once guarantee on. Keying\n * `Stop` on `invocationNum` alone would be worse than not identifying it: it\n * would suppress the second, *real* firing.\n */\nconst INVOCATION_SCOPED_EVENTS: readonly string[] = [\"PreInvocation\", \"PostInvocation\"];\n\nexport const antigravityDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const parsed = antigravityHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return undefined;\n }\n const payload = parsed.data;\n\n if (payload.hookEventName === \"PreToolUse\" || payload.hookEventName === \"PostToolUse\") {\n return {\n sessionId: payload.conversationId,\n sourceEventName: payload.hookEventName,\n components: [String(payload.invocationNum), String(payload.stepIdx)],\n evidence: [\"payload.invocationNum with payload.stepIdx names one step of one invocation\"],\n };\n }\n\n if (INVOCATION_SCOPED_EVENTS.includes(payload.hookEventName)) {\n return {\n sessionId: payload.conversationId,\n sourceEventName: payload.hookEventName,\n components: [String(payload.invocationNum)],\n evidence: [\"payload.invocationNum names one invocation, whose edges fire once each\"],\n };\n }\n\n return undefined;\n};\n\n/**\n * Why the remaining Antigravity callback carries no delivery identity.\n *\n * Exhaustive over {@link ANTIGRAVITY_HOOK_EVENT_NAMES}: every other event is\n * identified above, so `Stop` is the whole of this adapter's coverage gap and the\n * reason names the field whose confirmation would close it.\n */\nexport const ANTIGRAVITY_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n Stop:\n \"Stop can fire twice per invocation (idle, then fully idle) and payload `fullyIdle` — the only field separating them — is an unconfirmed reconstruction, so invocationNum alone would suppress the second real firing\",\n});\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport { identityClaimSchema, unknownWorkspaceIdentity, type IdentityClaim } from \"../../model/identity.js\";\nimport { providerIdSchema, sessionIdSchema, type ProviderId } from \"../../model/primitives.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport { ANTIGRAVITY_DELIVERY_GAPS, antigravityDeliveryIdentity } from \"./delivery.js\";\nimport {\n ANTIGRAVITY_SUBAGENT_TOOL_NAME,\n antigravityHookPayloadSchema,\n antigravityWeakShapeSchema,\n} from \"./payload.js\";\n\nexport const ANTIGRAVITY_PROVIDER_ID = \"antigravity\" as const;\n\n/**\n * What this adapter can honestly observe from the five documented command\n * hooks. Only PreToolUse/PostToolUse carry a lifecycle fact the canonical\n * model can represent without inventing anything: PreInvocation,\n * PostInvocation, and Stop expose invocation/execution bookkeeping, not a\n * session or generation identity (no `modelId`, no genuine start/end\n * signal), so none of them produce an event — see `parse()` below and\n * `./maturity.ts` for what would need to change that.\n */\nexport const ANTIGRAVITY_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\"tool.start\", \"tool.end\"] as const),\n usageTemporality: \"delta\",\n reportsCachedInput: false,\n reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\n reportsReasoningOutput: false,\n reportsProviderTotal: false,\n reportsCost: false,\n emitsSubagentEvents: false,\n emitsCompactionEvents: false,\n requiresHookResponse: false,\n // Only the tool pair carries a replay-stable id, and only from the two\n // verified counters. See `./delivery.ts` for which and why.\n deliveryIdentifier: \"partial\",\n});\n\nexport type AntigravityAdapterOptions = {\n readonly id?: string;\n readonly version?: string;\n};\n\n/**\n * Experimental Google Antigravity adapter.\n *\n * Maps the five documented camelCase command hooks onto canonical events\n * conservatively: fields the hooks do not expose (model identifiers, usage,\n * a genuine session start/end signal) are never fabricated. PreInvocation,\n * PostInvocation, and Stop report invocation and execution-completion\n * bookkeeping only — none of it converts to a canonical event without\n * inventing a session or generation identity, so all three are ignored with\n * a diagnostic reason. See ADR 0003 for the adapter contract this implements\n * and `./maturity.ts` for what would need to be verified before this leaves\n * `experimental`.\n */\nexport const createAntigravityAdapter = (\n options: AntigravityAdapterOptions = {},\n): ProviderAdapter => {\n const id: ProviderId = providerIdSchema.parse(options.id ?? ANTIGRAVITY_PROVIDER_ID);\n const version = options.version ?? \"0.1.0\";\n\n const detect = (input: ProviderDetectionInput): ProviderDetection => {\n const full = antigravityHookPayloadSchema.safeParse(input.payload);\n if (full.success) {\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"exact\",\n reasons: [`payload matches the documented antigravity ${full.data.hookEventName} hook shape`],\n sourceEventName: full.data.hookEventName,\n });\n }\n const weak = antigravityWeakShapeSchema.safeParse(input.payload);\n if (weak.success) {\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"weak\",\n reasons: [\n `payload.hookEventName=${weak.data.hookEventName} matches antigravity but required fields are missing or invalid`,\n ],\n sourceEventName: weak.data.hookEventName,\n });\n }\n return unknownDetection([\"payload does not match any documented antigravity hook shape\"]);\n };\n\n const identify = (input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[] => {\n const parsed = antigravityHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return [];\n }\n const payload = parsed.data;\n const sessionId = sessionIdSchema.parse(payload.conversationId);\n // occurredAt is pinned to a constant: the seed is a hash namespace, not a\n // claimed timestamp, and invocationNum is what must stay stable across the\n // separate Pre/Post hook processes that share one Antigravity invocation.\n const invocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId,\n occurredAt: 0,\n discriminator: String(payload.invocationNum),\n });\n const [firstWorkspacePath] = payload.workspacePaths;\n const workspace =\n firstWorkspacePath === undefined\n ? unknownWorkspaceIdentity()\n : deriveWorkspaceIdentity(context.privacy, {\n kind: \"working-directory\",\n absolutePath: firstWorkspacePath,\n });\n\n return [\n identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: { sessionId, invocationId, workspace },\n }),\n ];\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const parsed = antigravityHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the documented antigravity hook contract\",\n }),\n };\n }\n const payload = parsed.data;\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n\n switch (payload.hookEventName) {\n case \"PreInvocation\":\n return {\n status: \"ignored\",\n reason:\n \"PreInvocation reports invocation bookkeeping only; it carries no modelId or usage, so it cannot \" +\n \"become a generation fact, and it is not a genuine session-start signal Antigravity documents\",\n };\n case \"PostInvocation\":\n return {\n status: \"ignored\",\n reason:\n \"PostInvocation reports invocation bookkeeping only; it carries no modelId, usage, or outcome that \" +\n \"the canonical model can represent without inventing a generation fact\",\n };\n case \"PreToolUse\": {\n const toolCallId = context.ids.newOpaqueId([\n payload.conversationId,\n \"step\",\n String(payload.stepIdx),\n ]);\n const toolKind = payload.toolName === ANTIGRAVITY_SUBAGENT_TOOL_NAME ? \"delegate\" : \"unknown\";\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName: payload.toolName,\n toolKind,\n ...(payload.toolInput === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.toolInput,\n label: payload.toolName,\n }),\n }),\n });\n break;\n }\n case \"PostToolUse\": {\n const toolCallId = context.ids.newOpaqueId([\n payload.conversationId,\n \"step\",\n String(payload.stepIdx),\n ]);\n const outcome = payload.isError === true ? \"error\" : payload.isError === false ? \"ok\" : \"unknown\";\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName: payload.toolName,\n outcome,\n ...(payload.toolResponse === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.toolResponse,\n label: payload.toolName,\n }),\n }),\n });\n break;\n }\n case \"Stop\":\n return {\n status: \"ignored\",\n reason: payload.fullyIdle\n ? \"Stop signals execution/turn completion (fullyIdle=true) but exposes no session or generation \" +\n \"identity, so it cannot become session.end or generation.end without inventing one\"\n : \"Stop received while the agent is not fully idle; the conversation continues and the hook exposes \" +\n \"no lifecycle fact the canonical model can represent\",\n };\n }\n\n return { status: \"parsed\", events: factory.events() };\n };\n\n const hookResponse = (): ProviderHookResponse => SILENT_HOOK_RESPONSE;\n\n return {\n id,\n version,\n capabilities: ANTIGRAVITY_CAPABILITIES,\n detect,\n identify,\n deliveryIdentity: antigravityDeliveryIdentity,\n deliveryGaps: ANTIGRAVITY_DELIVERY_GAPS,\n parse,\n hookResponse,\n };\n};\n","/**\n * Maturity of the Antigravity provider adapter.\n *\n * `experimental` means: the five hook names and the six field names this\n * adapter treats as verified (`conversationId`, `workspacePaths`, `stepIdx`,\n * `invocationNum`, `transcriptPath`, `artifactDirectoryPath`) came from the\n * integration task, not from a captured transcript this package has seen.\n * Every other field (`toolName`, `toolInput`, `toolResponse`, `isError`,\n * `fullyIdle`, `agentVersion`) and every mapping decision below is a\n * conservative reconstruction pending confirmation.\n */\nexport const ANTIGRAVITY_PROVIDER_MATURITY = \"experimental\" as const;\nexport type AntigravityProviderMaturity = typeof ANTIGRAVITY_PROVIDER_MATURITY;\n\n/**\n * What must be verified against real Antigravity hook captures before this\n * adapter can be promoted past `experimental`:\n *\n * 1. Whether `PreInvocation`/`PostInvocation` ever expose a model identifier\n * or usage figures. If they do, promote from the current ignored handling\n * to `generation.start`/`generation.end` — this adapter deliberately does\n * not fabricate a `modelId` to unlock that today, and does not treat\n * `invocationNum === 0` as a session-start signal: Antigravity documents\n * no such hook, and a genuine session-start fact requires more than an\n * invocation counter reaching zero.\n * 2. Whether Antigravity documents any hook that reports a real session or\n * conversation start/end (as opposed to per-invocation bookkeeping). If\n * one exists, add `session.start`/`session.end` handling for it instead of\n * inferring boundaries from `PreInvocation`/`Stop`.\n * 3. Whether `Stop` (or another hook) ever exposes enough to honestly close\n * out a `generation.end` — a model identifier, an outcome, or a\n * generation id correlating it to a prior invocation. Today `Stop` is\n * ignored regardless of `fullyIdle`, because turn/execution completion\n * alone does not map to any canonical event without inventing one.\n * 4. Whether Antigravity reports its own tool-call identifier. This adapter\n * derives `toolCallId` from `conversationId` + `stepIdx`; a native id\n * would be strictly more precise and should replace the derived one.\n * 5. Whether `invoke_subagent` warrants a dedicated subagent lifecycle\n * (`subagent.start`/`subagent.end` with parent/child invocation identity)\n * instead of being modeled as an ordinary delegated tool call.\n * 6. Whether `PostToolUse.isError` is really optional or always present.\n * 7. A captured, redacted end-to-end transcript replayed through this\n * adapter with zero `schema-validation-failed` or `privacy-policy-violation`\n * diagnostics.\n */\nexport const ANTIGRAVITY_PROMOTION_GATES: readonly string[] = Object.freeze([\n \"confirm whether PreInvocation/PostInvocation ever expose modelId or usage\",\n \"confirm whether any hook documents a genuine session/conversation start or end\",\n \"confirm whether Stop or another hook can honestly close out a generation.end\",\n \"confirm whether Antigravity reports a native tool-call identifier\",\n \"confirm whether invoke_subagent should have a dedicated subagent lifecycle\",\n \"confirm PostToolUse.isError against real payloads\",\n \"replay a captured, redacted transcript with zero validation/privacy diagnostics\",\n]);\n","import { ANTIGRAVITY_PROVIDER_ID, createAntigravityAdapter } from \"./antigravity/adapter.js\";\nimport { ANTIGRAVITY_PROMOTION_GATES, ANTIGRAVITY_PROVIDER_MATURITY } from \"./antigravity/maturity.js\";\nimport { createClaudeCodeAdapter } from \"./claude/adapter.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./claude/detect.js\";\nimport { createCodexAdapter } from \"./codex/adapter.js\";\nimport { CODEX_PROVIDER_ID } from \"./codex/version.js\";\nimport { createCursorAdapter } from \"./cursor/adapter.js\";\nimport { CURSOR_PROVIDER_ID } from \"./cursor/payload.js\";\nimport { createGeminiCliAdapter, GEMINI_PROVIDER_ID } from \"./gemini/adapter.js\";\nimport {\n describeAdapter,\n type AdapterDescription,\n type DeliveryIdentifierSupport,\n type ProviderAdapter,\n} from \"./adapter.js\";\nimport { createProviderRegistry, type ProviderRegistry } from \"./registry.js\";\n\n/**\n * How much of a provider adapter's behaviour is confirmed against the real\n * provider.\n *\n * `experimental` is not a quality grade — it states that some of the adapter's\n * field and lifecycle mapping is a reconstruction pending confirmation against\n * real captures. Consumers are expected to be able to see this before they\n * depend on the data, so it is part of the descriptor rather than a comment.\n */\nexport type ProviderMaturity = \"stable\" | \"experimental\";\n\nexport type ProviderDescriptor = {\n readonly id: string;\n readonly maturity: ProviderMaturity;\n /** Human-readable name of the coding agent this adapter targets. */\n readonly title: string;\n /** Constructs a fresh adapter instance. Adapters are values, never singletons. */\n readonly createAdapter: () => ProviderAdapter;\n /**\n * For an `experimental` adapter: what must be verified before promotion.\n * Empty for a `stable` one.\n */\n readonly promotionGates: readonly string[];\n};\n\n/**\n * Every provider adapter this package ships, with its maturity.\n *\n * Ordering is stable and alphabetical by id so `otel-hook providers` output and\n * detection candidate lists are reproducible.\n */\nexport const PROVIDER_DESCRIPTORS: readonly ProviderDescriptor[] = Object.freeze([\n Object.freeze({\n id: ANTIGRAVITY_PROVIDER_ID,\n maturity: ANTIGRAVITY_PROVIDER_MATURITY,\n title: \"Google Antigravity (experimental)\",\n createAdapter: (): ProviderAdapter => createAntigravityAdapter(),\n promotionGates: ANTIGRAVITY_PROMOTION_GATES,\n }),\n Object.freeze({\n id: CLAUDE_CODE_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"Claude Code\",\n createAdapter: (): ProviderAdapter => createClaudeCodeAdapter(),\n promotionGates: Object.freeze([]),\n }),\n Object.freeze({\n id: CODEX_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"OpenAI Codex CLI\",\n createAdapter: (): ProviderAdapter => createCodexAdapter(),\n promotionGates: Object.freeze([]),\n }),\n Object.freeze({\n id: CURSOR_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"Cursor\",\n createAdapter: (): ProviderAdapter => createCursorAdapter(),\n promotionGates: Object.freeze([]),\n }),\n Object.freeze({\n id: GEMINI_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"Gemini CLI\",\n createAdapter: (): ProviderAdapter => createGeminiCliAdapter(),\n promotionGates: Object.freeze([]),\n }),\n]);\n\n/** Ids of the adapters whose mapping is still a reconstruction. */\nexport const EXPERIMENTAL_PROVIDER_IDS: readonly string[] = Object.freeze(\n PROVIDER_DESCRIPTORS.filter((descriptor) => descriptor.maturity === \"experimental\").map(\n (descriptor) => descriptor.id,\n ),\n);\n\nexport const findProviderDescriptor = (id: string): ProviderDescriptor | undefined =>\n PROVIDER_DESCRIPTORS.find((descriptor) => descriptor.id === id);\n\nexport const isExperimentalProvider = (id: string): boolean =>\n findProviderDescriptor(id)?.maturity === \"experimental\";\n\nexport type DefaultRegistryOptions = {\n /**\n * Include adapters marked `experimental`. Default `true`: an experimental\n * adapter is registered but visibly labelled, so a host that wants only\n * confirmed mappings opts out explicitly rather than discovering the\n * distinction from telemetry that looks the same as the rest.\n */\n readonly includeExperimental?: boolean;\n /** Restrict to these provider ids, in descriptor order. Empty means \"all\". */\n readonly only?: readonly string[];\n /** Extra adapters — a host's own provider — appended after the built-ins. */\n readonly additional?: readonly ProviderAdapter[];\n};\n\n/**\n * Build a registry over this package's provider adapters.\n *\n * A factory rather than a shared constant: a registry is a value the runtime is\n * given, and two hooks in one process may legitimately be configured with\n * different adapter sets (see `createProviderRegistry`'s note and ADR 0001).\n */\nexport const createDefaultProviderRegistry = (\n options: DefaultRegistryOptions = {},\n): ProviderRegistry => {\n const includeExperimental = options.includeExperimental ?? true;\n const only = options.only ?? [];\n const selected = PROVIDER_DESCRIPTORS.filter((descriptor) => {\n if (only.length > 0 && !only.includes(descriptor.id)) {\n return false;\n }\n return includeExperimental || descriptor.maturity !== \"experimental\";\n });\n return createProviderRegistry([\n ...selected.map((descriptor) => descriptor.createAdapter()),\n ...(options.additional ?? []),\n ]);\n};\n\nexport type ProviderCatalogEntry = AdapterDescription & {\n readonly maturity: ProviderMaturity;\n readonly title: string;\n readonly promotionGates: readonly string[];\n /** True when the provider's protocol reads a structured response from stdout. */\n readonly requiresHookResponse: boolean;\n /**\n * Which series this provider's `cumulative` counters accumulate over, so a\n * consumer summing deltas knows whether a per-turn snapshot is a per-turn\n * figure or a session-wide one. Absent for `delta` providers.\n */\n readonly cumulativeUsageSeries?: string;\n readonly reportsCachedInput: boolean;\n readonly reportsCacheCreation: boolean;\n readonly cacheCreationAccounting: string;\n readonly reportsReasoningOutput: boolean;\n readonly reportsProviderTotal: boolean;\n readonly reportsCost: boolean;\n readonly emitsSubagentEvents: boolean;\n readonly emitsCompactionEvents: boolean;\n};\n\n/** How each adapter's declared delivery-identifier coverage reads to a human. */\nexport const DELIVERY_IDENTIFIER_SUMMARY: Readonly<Record<DeliveryIdentifierSupport, string>> =\n Object.freeze({\n none: \"no callback carries a replay-stable identifier\",\n partial: \"some callbacks carry a replay-stable identifier\",\n all: \"every recognized callback carries a replay-stable identifier\",\n });\n\n/**\n * Machine-readable capability catalog, for `otel-hook providers --json` and for\n * consumers deciding whether a metric is absent or merely unreported.\n */\nexport const describeProviderCatalog = (\n options: DefaultRegistryOptions = {},\n): readonly ProviderCatalogEntry[] => {\n const includeExperimental = options.includeExperimental ?? true;\n const only = options.only ?? [];\n const entries: ProviderCatalogEntry[] = [];\n for (const descriptor of PROVIDER_DESCRIPTORS) {\n if (only.length > 0 && !only.includes(descriptor.id)) {\n continue;\n }\n if (!includeExperimental && descriptor.maturity === \"experimental\") {\n continue;\n }\n const adapter = descriptor.createAdapter();\n const { capabilities } = adapter;\n entries.push({\n ...describeAdapter(adapter),\n maturity: descriptor.maturity,\n title: descriptor.title,\n promotionGates: [...descriptor.promotionGates],\n requiresHookResponse: capabilities.requiresHookResponse,\n ...(capabilities.cumulativeUsageSeries === undefined\n ? {}\n : { cumulativeUsageSeries: capabilities.cumulativeUsageSeries }),\n reportsCachedInput: capabilities.reportsCachedInput,\n reportsCacheCreation: capabilities.reportsCacheCreation,\n cacheCreationAccounting: capabilities.cacheCreationAccounting,\n reportsReasoningOutput: capabilities.reportsReasoningOutput,\n reportsProviderTotal: capabilities.reportsProviderTotal,\n reportsCost: capabilities.reportsCost,\n emitsSubagentEvents: capabilities.emitsSubagentEvents,\n emitsCompactionEvents: capabilities.emitsCompactionEvents,\n });\n }\n return entries;\n};\n","import { epochMillisSchema, type EpochMillis } from \"../model/primitives.js\";\nimport type { Clock } from \"./ports.js\";\n\n/** Clock backed by the host process. */\nexport const createSystemClock = (): Clock => ({\n now: (): EpochMillis => epochMillisSchema.parse(Date.now()),\n monotonicMillis: (): number => Number(process.hrtime.bigint() / 1_000_000n),\n});\n\nexport type FixedClockOptions = {\n readonly startMillis?: number;\n /** Milliseconds added to the wall clock on each `now()` call. */\n readonly tickMillis?: number;\n};\n\n/**\n * Deterministic clock for tests.\n *\n * `advance` moves both readings together so duration arithmetic stays coherent.\n */\nexport interface FixedClock extends Clock {\n advance(millis: number): void;\n set(millis: number): void;\n}\n\nexport const createFixedClock = (options: FixedClockOptions = {}): FixedClock => {\n let wall = options.startMillis ?? 1_700_000_000_000;\n let monotonic = 0;\n const tick = options.tickMillis ?? 0;\n\n return {\n now: (): EpochMillis => {\n const current = wall;\n wall += tick;\n monotonic += tick;\n return epochMillisSchema.parse(current);\n },\n monotonicMillis: (): number => monotonic,\n advance: (millis: number): void => {\n wall += millis;\n monotonic += millis;\n },\n set: (millis: number): void => {\n wall = millis;\n },\n };\n};\n","import { z } from \"zod\";\n\nimport { DEFAULT_CONFIG, type OtelHookConfig } from \"../config/schema.js\";\nimport {\n createErrorInfo,\n errorInfoFromThrown,\n type AttributionOutcome,\n type AttributionReason,\n type OtelHookErrorInfo,\n} from \"../errors/index.js\";\nimport {\n isContentFactConsistent,\n isUnavailableContentFact,\n type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent, ModelDescriptor } from \"../model/events.js\";\nimport {\n resolveInvocationIdentity,\n sourceProvenanceSchema,\n unknownWorkspaceIdentity,\n type IdentityClaim,\n type InvocationIdentity,\n type WorkspaceIdentity,\n} from \"../model/identity.js\";\nimport {\n type DetectionConfidence,\n type EventId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport {\n cumulativeToDelta,\n normalizeUsage,\n toReport,\n type CanonicalUsage,\n type UsageTemporality,\n} from \"../model/usage.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport { CONTENT_MODE_DISCLOSURE } from \"../privacy/policy.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport {\n readDeliveryClaim,\n readDeliveryGap,\n SILENT_HOOK_RESPONSE,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderHookResponse,\n} from \"../providers/adapter.js\";\nimport { createProviderRegistry, BUILT_IN_PROVIDERS, type ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"./clock.js\";\nimport { resolveDeliveryIdentity, type DeliveryResolution } from \"./delivery.js\";\nimport { createDeterministicIdGenerator } from \"./ids.js\";\nimport { createNullLogger } from \"./logger.js\";\nimport type {\n Clock,\n IdGenerator,\n Logger,\n PayloadEnricher,\n ReadCursor,\n SessionContextReader,\n StateStore,\n TelemetrySink,\n WorktreeLocator,\n} from \"./ports.js\";\nimport type { TargetHint } from \"../model/target.js\";\nimport {\n DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,\n resolveEventTargets,\n} from \"./target-resolution.js\";\nimport { isStateLockContention, withOptionalSessionLock } from \"../state/store.js\";\nimport { stampSessionContext } from \"./session-context.js\";\n\nexport const usageScopeSchema = z.enum([\"session\", \"generation\", \"subagent\"]);\nexport type UsageScope = z.infer<typeof usageScopeSchema>;\n\n/**\n * Which series a provider's cumulative counters accumulate over. Mirrors\n * `ProviderCapabilities.cumulativeUsageSeries`, defaulting to `event-scope`\n * for the adapters that do not declare one.\n */\nexport type CumulativeUsageSeries = \"event-scope\" | \"session-lifetime\";\n\n/**\n * Delta usage derived for one event.\n *\n * Events keep whatever the provider reported. Deltas are produced alongside them\n * rather than rewritten into them, so a cumulative report and its derived delta\n * are both auditable.\n */\nexport type UsageObservation = {\n readonly eventId: EventId;\n readonly sequence: number;\n readonly scope: UsageScope;\n readonly scopeKey: string;\n readonly reportedTemporality: UsageTemporality;\n readonly delta: CanonicalUsage;\n /** True when the cumulative series restarted; see `cumulativeToDelta`. */\n readonly resetDetected: boolean;\n};\n\nexport type HookIngestInput = {\n /** Decoded provider payload. Only the selected adapter interprets it. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n /** Caller-supplied identity claims, arbitrated with the adapter's claims. */\n readonly identityClaims?: readonly IdentityClaim[];\n /** Opaque consumer metadata; sanitized, then carried through unchanged. */\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n readonly workspace?: WorkspaceIdentity;\n};\n\n/**\n * The terminal fate of one callback's telemetry, and the only thing a caller\n * should base a commit-or-retry decision on.\n *\n * The distinction that matters is **any** versus **all**, not success versus\n * failure. A batch is chunked before export, so it can be part accepted and part\n * refused — and once a single span has reached a collector or the spool, retrying\n * the callback would re-export that span. So a partial result is *terminal*: the\n * callback is committed, the loss is reported, and nothing is retried. Only a\n * result where nothing at all survived is safe to retry, precisely because there\n * is nothing to duplicate.\n */\nexport type DeliveryDurability =\n /** Suppressed, or no events to export. There is nothing to lose or retry. */\n | \"nothing-to-deliver\"\n /** Every span reached the collector or the spool. */\n | \"delivered\"\n /**\n * Some spans survived and some did not. Terminal: committing loses the refused\n * spans, retrying duplicates the accepted ones, and duplicating an accepted\n * span silently corrupts a total while a reported loss can be acted on.\n */\n | \"partial\"\n /** Nothing survived, so a retry cannot duplicate anything. */\n | \"lost\";\n\nexport const classifyDurability = (input: {\n readonly attempted: boolean;\n readonly accepted: number;\n readonly rejected: number;\n}): DeliveryDurability => {\n if (!input.attempted) {\n return \"nothing-to-deliver\";\n }\n if (input.rejected === 0) {\n return input.accepted === 0 ? \"nothing-to-deliver\" : \"delivered\";\n }\n return input.accepted === 0 ? \"lost\" : \"partial\";\n};\n\n/** Whether this fate permits committing the callback and its accounting. */\nexport const isCommittable = (durability: DeliveryDurability): boolean =>\n durability !== \"lost\";\n\nexport type HookIngestOutcome = {\n /**\n * Always `true`. The hook cannot fail the host agent; look at `attribution`\n * and `diagnostics` to see what actually happened (ADR 0004).\n */\n readonly ok: true;\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly providerId: ResolvedProviderId;\n readonly detectionConfidence: DetectionConfidence;\n readonly identity?: InvocationIdentity;\n readonly events: readonly CanonicalEvent[];\n readonly usageObservations: readonly UsageObservation[];\n /**\n * OTLP records the sink accepted, summed over every wired signal.\n *\n * A count of *records*, never of canonical events: two edges of one lifecycle\n * scope produce one span, and one event carrying three content facts produces\n * three log records. With the logs signal enabled a batch therefore reports both\n * signals' records here — which is what makes {@link durability} correct across\n * them, and why nothing should read this as \"how many events were observed\".\n */\n readonly emitted: number;\n /**\n * Records the sink could neither export nor durably spool.\n *\n * The distinction `emitted` cannot make: a successful spool enqueue counts as\n * emitted, because the batch is safe on disk and a later invocation will retry\n * it. A non-zero value here means those observations are **gone** unless the\n * callback is delivered again — which is what lets a caller decide whether a\n * delivery claim may be committed or has to be released for retry.\n */\n readonly exportRejected: number;\n /**\n * The terminal fate of this callback's telemetry.\n *\n * The field a caller should branch on. `emitted` and `exportRejected` are the\n * raw counts behind it; this is the decision they add up to, computed in one\n * place so a caller cannot get the any-versus-all boundary wrong.\n */\n readonly durability: DeliveryDurability;\n readonly dropped: number;\n readonly hookResponse: ProviderHookResponse;\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type HookIngestOptions = {\n /**\n * Parse and answer the provider, but export nothing and mutate no canonical\n * state.\n *\n * For a callback that deduplication has already identified as a redelivery.\n * The adapter still runs, so the provider's protocol response comes from a real\n * parse of the real payload rather than a guess — but the session sequence\n * counter is not advanced and no cumulative usage baseline is rewritten,\n * because both are *canonical state* and a redelivery is by definition not a\n * new observation. Advancing the sequence would renumber every later event in\n * the session and change its derived event id, which is exactly the\n * replay-stability the dedup guard exists to protect.\n */\n readonly suppress?: boolean;\n};\n\n/** Public runtime surface. */\nexport interface OtelHook {\n /**\n * Report the replay-stable delivery identity of an input without ingesting it.\n *\n * Synchronous, side-effect free, and never throws. It exists as a separate\n * step because deduplication has to decide *before* anything is exported or\n * accounted, and `ingest` exports as part of its own work — a caller that\n * learned the identity afterwards could only ever suppress a duplicate it had\n * already sent. Only `detect` and `deliveryIdentity` run here; the payload is\n * never parsed.\n */\n resolveDelivery(input: HookIngestInput): DeliveryResolution;\n /** Process one provider observation. Never throws, never rejects. */\n ingest(input: HookIngestInput, options?: HookIngestOptions): Promise<HookIngestOutcome>;\n /** Best-effort delivery of buffered telemetry. Never throws. */\n flush(): Promise<void>;\n /** Flush, then release resources. Never throws; idempotent. */\n shutdown(): Promise<void>;\n /** Resolved configuration in force. Read-only. */\n readonly config: OtelHookConfig;\n}\n\nexport type OtelHookDependencies = {\n readonly sink: TelemetrySink;\n readonly stateStore: StateStore;\n readonly config?: OtelHookConfig;\n readonly registry?: ProviderRegistry;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Overrides `config.privacy` when supplied; must already be configured. */\n readonly privacy?: PrivacyService;\n readonly logger?: Logger;\n /**\n * Namespace separating one deployment's derived delivery identities from\n * another's. Not identity: it never reaches an event, and no session or\n * workspace is derived from it. Defaults to `\"default\"`.\n */\n readonly installationId?: string;\n /**\n * Resolves tool events' target hints to the git worktree they touched\n * (ADR 0008). Absent means no resolution: events carry no `target`. The\n * filesystem implementation is `createFilesystemWorktreeLocator`.\n */\n readonly worktreeLocator?: WorktreeLocator;\n /** Ceiling on target resolution per callback. Default 50ms. */\n readonly targetResolutionBudgetMillis?: number;\n /**\n * Host-configured payload enrichers (see {@link PayloadEnricher}). Empty by\n * default: nothing reads beyond the payload unless a host asks for it.\n */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /**\n * Reads the session context a harness wrote (`docs/session-context.md`). Absent\n * means none: no event carries `contextAttributes`. The filesystem\n * implementation is `createDirectorySessionContextReader`.\n */\n readonly sessionContext?: SessionContextReader;\n};\n\nconst MAX_ERROR_EVENTS = 8;\n\nconst collectContentFacts = (event: CanonicalEvent): readonly ContentFact[] => {\n const facts: ContentFact[] = [];\n const push = (fact: ContentFact | undefined): void => {\n if (fact !== undefined) {\n facts.push(fact);\n }\n };\n switch (event.type) {\n case \"prompt.submitted\":\n push(event.content);\n break;\n case \"generation.start\":\n facts.push(...(event.inputContent ?? []));\n break;\n case \"generation.end\":\n facts.push(...(event.outputContent ?? []));\n break;\n case \"tool.start\":\n push(event.input);\n break;\n case \"tool.end\":\n push(event.output);\n break;\n case \"error.raised\":\n push(event.message);\n break;\n default:\n break;\n }\n return facts;\n};\n\nconst usageScopeOf = (\n event: CanonicalEvent,\n): { readonly scope: UsageScope; readonly scopeKey: string; readonly usage: CanonicalUsage } | undefined => {\n switch (event.type) {\n case \"session.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"compaction.performed\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"generation.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"generation\", scopeKey: event.generationId, usage: event.usage };\n case \"subagent.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"subagent\", scopeKey: event.subagentInvocationId, usage: event.usage };\n default:\n return undefined;\n }\n};\n\nconst sequenceKey = (sessionId: string): string => `sequence:${sessionId}`;\nconst sessionModelKey = (sessionId: string): string => `model:${sessionId}`;\nconst readCursorKey = (enricherId: string, sessionId: string, scope: string | undefined): string =>\n scope === undefined ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;\n\n/**\n * The placeholder an adapter uses when its payload names no model. Never\n * remembered: storing it would overwrite a real model the session reported.\n */\nconst UNKNOWN_MODEL_ID = \"unknown\";\n\n/**\n * The last model a batch reports for the top-level agent, if any.\n *\n * `session.start` and `generation.*` edges count; a subagent's events do not,\n * because a subagent can run on a different model than the session it serves and\n * must not rename the session's own generations. The last such event wins, so a\n * turn that reports a model switch updates what the session remembers.\n */\nconst latestSessionModel = (events: readonly CanonicalEvent[]): ModelDescriptor | undefined => {\n let latest: ModelDescriptor | undefined;\n for (const event of events) {\n if (event.subagentId !== undefined) {\n continue;\n }\n if (\n (event.type === \"session.start\" || event.type === \"generation.start\" || event.type === \"generation.end\") &&\n event.model !== undefined &&\n event.model.modelId !== UNKNOWN_MODEL_ID\n ) {\n latest = event.model;\n }\n }\n return latest;\n};\n\nconst sameModel = (left: ModelDescriptor | undefined, right: ModelDescriptor): boolean =>\n left !== undefined &&\n left.modelId === right.modelId &&\n left.vendor === right.vendor &&\n left.family === right.family;\nconst usageKey = (sessionId: string, scope: UsageScope, scopeKey: string): string =>\n `usage:${sessionId}:${scope}:${scopeKey}`;\n\n/**\n * Where the cumulative baseline for an observation is stored.\n *\n * This is deliberately *not* the same thing as the observation's own scope. The\n * derived delta belongs to the event that reported it — a turn's token spend is\n * attributed to that turn — but the snapshot it must be diffed against belongs\n * to whichever series the provider is actually accumulating.\n *\n * For a `session-lifetime` provider (Codex: every hook carries the session-wide\n * `total_token_usage`), keying the baseline by `generationId` would mean every\n * turn's snapshot found no predecessor and was emitted whole, billing the entire\n * session again on each turn. Redirecting `generation` to the session series\n * makes successive turns diff against each other.\n */\nconst baselineScopeOf = (\n scope: UsageScope,\n scopeKey: string,\n sessionId: string,\n series: CumulativeUsageSeries,\n): { readonly scope: UsageScope; readonly scopeKey: string } =>\n series === \"session-lifetime\" && scope === \"generation\"\n ? { scope: \"session\", scopeKey: sessionId }\n : { scope, scopeKey };\n\n/**\n * Minimal orchestrator wiring detection, identity, parsing, privacy checks,\n * usage derivation, and export.\n *\n * Every step is contained: a throwing adapter, an unavailable state store, or a\n * rejecting sink degrades the telemetry, never the host agent.\n */\nexport const createOtelHook = (deps: OtelHookDependencies): OtelHook => {\n const config = deps.config ?? DEFAULT_CONFIG;\n const registry = deps.registry ?? createProviderRegistry(BUILT_IN_PROVIDERS);\n const clock = deps.clock ?? createSystemClock();\n const ids = deps.ids ?? createDeterministicIdGenerator();\n const privacy = deps.privacy ?? createPrivacyService(config.privacy);\n const logger = deps.logger ?? createNullLogger();\n const installationId = deps.installationId ?? \"default\";\n const limits = privacy.policy.limits;\n const expectedDisclosure = CONTENT_MODE_DISCLOSURE[privacy.policy.contentMode];\n\n const providerContext: ProviderContext = { privacy, clock, ids, logger, limits };\n let shutdownCompleted = false;\n\n const hookResponseFor = (\n adapter: ProviderAdapter | undefined,\n detection: ProviderDetection | undefined,\n attribution: AttributionOutcome,\n attributionReason: AttributionReason | undefined,\n emittedEvents: number,\n errors: readonly OtelHookErrorInfo[],\n ): ProviderHookResponse => {\n if (adapter === undefined) {\n return SILENT_HOOK_RESPONSE;\n }\n try {\n return adapter.hookResponse(\n {\n attribution,\n ...(attributionReason === undefined ? {} : { attributionReason }),\n ...(detection === undefined ? {} : { detection }),\n emittedEvents,\n errors,\n },\n providerContext,\n );\n } catch {\n // A provider that cannot describe its own response gets the silent one.\n return SILENT_HOOK_RESPONSE;\n }\n };\n\n const readSequenceBase = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<number> => {\n try {\n const record = await deps.stateStore.read(sequenceKey(sessionId));\n if (record?.value.kind === \"sequence\") {\n return record.value.next;\n }\n return 0;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return 0;\n }\n };\n\n /**\n * Run the configured enrichers for this provider over the payload.\n *\n * Inside the session lock, so a cursor is read, advanced, and written by one\n * process at a time. Every failure is contained: a throwing enricher or an\n * unusable store leaves the payload as it was, and a cursor write that fails\n * is a diagnostic — the next read then starts from the old cursor, which can\n * count a turn into the next one but never twice.\n */\n const enrichPayload = async (\n payload: unknown,\n providerId: string,\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<unknown> => {\n let current = payload;\n for (const enricher of deps.payloadEnrichers ?? []) {\n if (enricher.providerId !== providerId) {\n continue;\n }\n let scope: string | undefined;\n try {\n scope = enricher.cursorScope?.(current);\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n const key = readCursorKey(enricher.id, sessionId, scope);\n let cursor: ReadCursor | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"read-cursor\") {\n cursor = { source: record.value.source, offset: record.value.offset };\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n // Without the stored cursor a read would start from the wrong place.\n continue;\n }\n let result;\n try {\n result = await enricher.enrich({ payload: current, sessionId, ...(cursor === undefined ? {} : { cursor }) });\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n current = result.payload;\n if (result.notes !== undefined && result.notes.length > 0) {\n logger.debug(\"payload enricher notes\", {\n \"enricher.id\": enricher.id,\n \"enricher.notes\": result.notes.slice(0, 8).map((note) => note.slice(0, 200)),\n });\n }\n const next = result.cursor;\n if (next !== undefined && (next.source !== cursor?.source || next.offset !== cursor.offset)) {\n try {\n await deps.stateStore.write(key, { kind: \"read-cursor\", source: next.source, offset: next.offset });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n }\n }\n }\n return current;\n };\n\n /**\n * The model this session last reported, or `undefined`.\n *\n * Fails open: an unreadable store costs the model name, never the observation,\n * so a read failure is a diagnostic and the adapter falls back to `unknown`.\n */\n const readSessionModel = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<ModelDescriptor | undefined> => {\n try {\n const record = await deps.stateStore.read(sessionModelKey(sessionId));\n return record?.value.kind === \"session-model\" ? record.value.model : undefined;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return undefined;\n }\n };\n\n /**\n * Derive per-event deltas, advancing the stored cumulative baseline.\n *\n * `suppress` makes this read-only: a redelivered callback must still be able to\n * report what it *would* have counted, but rewriting the baseline would make\n * the next genuine observation diff against the wrong snapshot and report a\n * zero — or negative — delta. Callers run this inside the session lock.\n */\n const deriveUsage = async (\n events: readonly CanonicalEvent[],\n diagnostics: OtelHookErrorInfo[],\n suppress: boolean,\n series: CumulativeUsageSeries,\n ): Promise<readonly UsageObservation[]> => {\n const observations: UsageObservation[] = [];\n for (const event of events) {\n const scoped = usageScopeOf(event);\n if (scoped === undefined) {\n continue;\n }\n if (scoped.usage.temporality === \"delta\") {\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"delta\",\n delta: scoped.usage,\n resetDetected: false,\n });\n continue;\n }\n\n const baselineScope = baselineScopeOf(scoped.scope, scoped.scopeKey, event.sessionId, series);\n const key = usageKey(event.sessionId, baselineScope.scope, baselineScope.scopeKey);\n let baseline: CanonicalUsage | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"usage-cumulative\") {\n baseline = record.value.usage;\n }\n } catch (thrown) {\n // Without a baseline the difference is unknowable. Emitting the raw\n // snapshot as a delta would double-count, so the observation is dropped.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n\n let delta: CanonicalUsage;\n let resetDetected = false;\n if (baseline === undefined) {\n const normalized = normalizeUsage({ ...toReport(scoped.usage), temporality: \"delta\" });\n if (normalized.status === \"invalid\") {\n diagnostics.push(\n createErrorInfo({\n code: \"usage-invalid\",\n phase: \"normalization\",\n detail: normalized.issues.map((issue) => issue.message).join(\"; \").slice(0, 400),\n details: { \"event.id\": event.eventId, \"usage.scope\": scoped.scope },\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n delta = normalized.usage;\n } else {\n try {\n const diffed = cumulativeToDelta(baseline, scoped.usage);\n delta = diffed.usage;\n resetDetected = diffed.resetDetected;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n }\n\n try {\n if (!suppress) {\n await deps.stateStore.write(key, { kind: \"usage-cumulative\", usage: scoped.usage });\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"cumulative\",\n delta,\n resetDetected,\n });\n }\n return observations;\n };\n\n const screenEvents = (\n events: readonly CanonicalEvent[],\n identity: InvocationIdentity,\n sequenceBase: number,\n diagnostics: OtelHookErrorInfo[],\n ): { readonly kept: readonly CanonicalEvent[]; readonly dropped: number } => {\n const kept: CanonicalEvent[] = [];\n let dropped = 0;\n let expectedSequence = sequenceBase;\n\n for (const event of events) {\n const reject = (code: \"schema-validation-failed\" | \"privacy-policy-violation\" | \"limit-exceeded\", detail: string): void => {\n dropped += 1;\n diagnostics.push(\n createErrorInfo({\n code,\n phase: code === \"privacy-policy-violation\" ? \"privacy\" : \"parsing\",\n detail,\n details: { \"event.type\": event.type, \"event.sequence\": event.sequence },\n occurredAt: clock.now(),\n }),\n );\n };\n\n if (kept.length >= limits.maxEventsPerInvocation) {\n reject(\"limit-exceeded\", `event dropped: maxEventsPerInvocation=${limits.maxEventsPerInvocation}`);\n continue;\n }\n if (event.schemaVersion !== CANONICAL_SCHEMA_VERSION) {\n reject(\"schema-validation-failed\", \"event carries an unexpected schema version\");\n continue;\n }\n if (event.invocationId !== identity.invocationId || event.sessionId !== identity.sessionId) {\n // Fail closed: an adapter may only describe the invocation it was given.\n reject(\"schema-validation-failed\", \"event identity does not match the resolved invocation\");\n continue;\n }\n if (event.provenance.providerId !== identity.provenance.providerId) {\n reject(\"schema-validation-failed\", \"event provenance does not match the detected provider\");\n continue;\n }\n if (event.sequence !== expectedSequence) {\n reject(\n \"schema-validation-failed\",\n `event sequence ${event.sequence} is not consecutive from ${expectedSequence}`,\n );\n continue;\n }\n\n const facts = collectContentFacts(event);\n const offending = facts.find(\n (fact) =>\n !isUnavailableContentFact(fact) &&\n (fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact)),\n );\n if (offending !== undefined) {\n reject(\n \"privacy-policy-violation\",\n `content fact disclosure ${offending.disclosure} violates policy ${expectedDisclosure}`,\n );\n continue;\n }\n\n expectedSequence += 1;\n kept.push(event);\n }\n return { kept, dropped };\n };\n\n const detectionInputFor = (input: HookIngestInput): {\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n } => ({\n payload: input.payload,\n transport: input.transport,\n environment: input.environment ?? {},\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n });\n\n const resolveDelivery = (input: HookIngestInput): DeliveryResolution => {\n let detected;\n try {\n detected = registry.detect(detectionInputFor(input), providerContext, config.detection);\n } catch {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n if (detected.status !== \"selected\") {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n\n const { adapter, detection } = detected;\n const capability = adapter.capabilities.deliveryIdentifier;\n // Named once, then reused: an unavailable resolution says *which* callback it\n // is talking about, because \"not identifiable\" without a callback name leaves\n // an operator auditing coverage nowhere to go.\n const named = {\n providerId: detection.providerId,\n capability,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n };\n const gap = readDeliveryGap(adapter, detection.sourceEventName);\n\n if (capability === \"none\") {\n return {\n status: \"unavailable\",\n reason: \"provider-declares-none\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n\n const read = readDeliveryClaim(adapter, { ...detectionInputFor(input), detection }, providerContext);\n if (read.rejection !== undefined) {\n return {\n status: \"unavailable\",\n reason: \"claim-rejected\",\n ...named,\n detail: read.rejection,\n };\n }\n if (read.claim === undefined) {\n return {\n status: \"unavailable\",\n reason: \"callback-not-identifiable\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n return {\n status: \"resolved\",\n identity: resolveDeliveryIdentity({\n ids,\n providerId: detection.providerId,\n installationId,\n claim: read.claim,\n }),\n };\n };\n\n const ingest = async (\n input: HookIngestInput,\n ingestOptions?: HookIngestOptions,\n ): Promise<HookIngestOutcome> => {\n const suppress = ingestOptions?.suppress === true;\n const diagnostics: OtelHookErrorInfo[] = [];\n const environment = input.environment ?? {};\n const detectionInput = {\n payload: input.payload,\n transport: input.transport,\n environment,\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n };\n\n try {\n const detected = registry.detect(detectionInput, providerContext, config.detection);\n diagnostics.push(...detected.errors);\n\n if (detected.status !== \"selected\") {\n const reason: AttributionReason =\n detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\";\n diagnostics.push(\n createErrorInfo({\n code: detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\",\n phase: \"detection\",\n detail: detected.detection.reasons.join(\"; \").slice(0, 400),\n details: { \"detection.candidates\": detected.candidates.length },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"provider not attributed\", {\n \"detection.status\": detected.status,\n \"detection.candidates\": detected.candidates.length,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: \"unknown\",\n detectionConfidence: detected.detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n\n const { adapter, detection } = detected;\n const provenance = sourceProvenanceSchema.parse({\n providerId: detection.providerId,\n ...(detection.providerVersion === undefined\n ? {}\n : { providerVersion: detection.providerVersion }),\n adapterId: adapter.id,\n adapterVersion: adapter.version,\n detectionConfidence: detection.confidence,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n transport: input.transport,\n });\n\n let adapterClaims: readonly IdentityClaim[] = [];\n try {\n adapterClaims = adapter.identify({ ...detectionInput, detection }, providerContext);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"identity\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n const resolution = resolveInvocationIdentity({\n claims: [...adapterClaims, ...(input.identityClaims ?? [])],\n provenance,\n fallback: {\n startedAt: clock.now(),\n workspace: input.workspace ?? unknownWorkspaceIdentity(),\n },\n consumerAttributes: privacy.sanitizeAttributes(input.consumerAttributes ?? {}),\n });\n\n if (resolution.status !== \"resolved\") {\n const reason: AttributionReason =\n resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\";\n const detail =\n resolution.status === \"conflict\"\n ? `conflicting fields: ${resolution.conflicts.map((conflict) => conflict.field).join(\", \")}`\n : resolution.status === \"incomplete\"\n ? `missing fields: ${resolution.missing.join(\", \")}`\n : `invalid claims: ${resolution.issues.join(\"; \")}`;\n diagnostics.push(\n createErrorInfo({\n code: resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: { \"provider.id\": detection.providerId },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"attribution declined\", {\n \"identity.status\": resolution.status,\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"declined\", reason, 0, diagnostics),\n diagnostics,\n };\n }\n\n const identity = resolution.identity;\n\n /**\n * Result of the session-state critical section: either a finished outcome\n * (the adapter declined to produce events) or a batch ready to export.\n */\n type Prepared =\n | { readonly kind: \"early\"; readonly outcome: HookIngestOutcome }\n | {\n readonly kind: \"ready\";\n readonly batch: readonly CanonicalEvent[];\n readonly dropped: number;\n readonly targetHints?: ReadonlyMap<EventId, TargetHint>;\n };\n\n /**\n * Read this session's sequence, stamp a batch from it, derive usage against\n * the stored baselines, and commit the new sequence — as one unit.\n *\n * These are read-modify-write cycles on state shared by every process\n * handling the same session, and hook processes genuinely run concurrently\n * (a tool callback and a generation callback firing together). Unserialized,\n * two processes both read sequence *n*, both stamp events from *n*, and both\n * write *n + k*: the second batch reuses the first's sequence numbers, so\n * both derive the *same* event ids and a collector sees one event twice\n * while another is never numbered at all. The cumulative usage baseline\n * races the same way, and there the lost update is a wrong token delta\n * rather than a duplicate id.\n *\n * Export deliberately happens *after* this returns, outside the lock. Two\n * reasons, one correctness and one liveness: the span correlator takes this\n * same session lock from inside the sink, so exporting in here would be a\n * non-reentrant self-deadlock; and an unreachable collector must not hold a\n * session's state lock for the length of its timeout. Committing the\n * sequence before exporting means a failed export leaves a gap in the\n * numbering rather than a reused number — a gap is invisible to a\n * collector, a reused id is a corrupted trace.\n */\n const prepare = async (): Promise<Prepared> => {\n const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);\n const sessionModel = await readSessionModel(identity.sessionId, diagnostics);\n const payload = suppress\n ? detectionInput.payload\n : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);\n\n let parsed;\n try {\n parsed = adapter.parse(\n {\n ...detectionInput,\n payload,\n detection,\n identity,\n sequenceBase,\n ...(sessionModel === undefined ? {} : { sessionModel }),\n },\n providerContext,\n );\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"parsing\",\n occurredAt: clock.now(),\n });\n diagnostics.push(info);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"ignored\") {\n logger.debug(\"adapter ignored input\", {\n \"provider.id\": detection.providerId,\n \"adapter.reason\": parsed.reason.slice(0, 160),\n });\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"not-applicable\",\n attributionReason: \"adapter-ignored-input\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(\n adapter,\n detection,\n \"not-applicable\",\n \"adapter-ignored-input\",\n 0,\n diagnostics,\n ),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"failed\") {\n diagnostics.push(parsed.error);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.warnings !== undefined && parsed.warnings.length > 0) {\n // An adapter reports a warning when it understood the payload but had to\n // decline part of it — a counter outside its declared capabilities, a\n // breakdown that disagrees with the total it itemizes. Not a diagnostic:\n // the observation is intact and nothing failed, so raising an error-severity\n // code would misreport a healthy invocation. But not nothing either, which\n // is what these were before: a harness whose attached field is being ignored\n // has no other way to find out.\n logger.warn(\"adapter declined part of the payload it understood\", {\n \"provider.id\": detection.providerId,\n \"adapter.warnings\": parsed.warnings.slice(0, 8).map((warning) => warning.slice(0, 200)),\n });\n }\n\n const screened = screenEvents(parsed.events, identity, sequenceBase, diagnostics);\n\n let batch: readonly CanonicalEvent[] = screened.kept;\n if (config.diagnostics.emitErrorEvents && diagnostics.length > 0) {\n batch = [...batch, ...buildErrorEvents(diagnostics, identity, sequenceBase + batch.length, ids, privacy)];\n }\n\n if (!suppress) {\n try {\n await deps.stateStore.write(sequenceKey(identity.sessionId), {\n kind: \"sequence\",\n next: sequenceBase + batch.length,\n });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n // Remember the session's model for the invocations whose payload names\n // none. Written only when it changed, so a session costs one record and\n // a steady session no extra writes; never written for a redelivery,\n // which is not a new observation.\n const reportedModel = latestSessionModel(screened.kept);\n if (reportedModel !== undefined && !sameModel(sessionModel, reportedModel)) {\n try {\n await deps.stateStore.write(sessionModelKey(identity.sessionId), {\n kind: \"session-model\",\n model: reportedModel,\n });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n }\n\n return {\n kind: \"ready\",\n batch,\n dropped: screened.dropped,\n ...(parsed.targetHints === undefined ? {} : { targetHints: parsed.targetHints }),\n };\n };\n\n let prepared: Prepared;\n try {\n prepared = await withOptionalSessionLock(deps.stateStore, identity.sessionId, prepare);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n\n if (!isStateLockContention(thrown)) {\n // The store cannot lock because it cannot be used at all — an unwritable\n // directory, a full disk. There is no peer inside the critical section\n // and no state to lose an update to, so the lock protects nothing here\n // and fail-open wins: process unlocked and export. Each individual read\n // and write inside still degrades to its own diagnostic.\n logger.warn(\"state store unusable; processing without session serialization\", {\n \"provider.id\": detection.providerId,\n });\n prepared = await prepare();\n } else {\n // Genuine contention. Proceeding unlocked would reintroduce exactly the\n // interleaving the lock exists to prevent, so the observation is declined\n // and said out loud — the provider still gets its protocol response, and a\n // caller holding a delivery claim releases it, turning a lock collision\n // into a retry rather than a corrupted sequence.\n //\n // A contended acquisition *cancels* its queued critical section\n // (`AsyncLock.run`), so this is now a provable statement rather than a\n // hopeful one: nothing was read, reserved, or written, which is what makes\n // the retry safe rather than a second half-application.\n logger.warn(\"session state lock contended; observation declined for retry\", {\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n // Nothing was exported, nothing was reserved, and nothing is on disk,\n // so the caller must see this as a total loss and retry it.\n exportRejected: 1,\n durability: \"lost\",\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"internal-error\", 0, diagnostics),\n diagnostics,\n };\n }\n }\n\n if (prepared.kind === \"early\") {\n return prepared.outcome;\n }\n const { dropped } = prepared;\n let batch = prepared.batch;\n\n // Outside the session lock on purpose: this is filesystem I/O, bounded by\n // its own budget, and must not lengthen the critical section peers wait on.\n if (\n !suppress &&\n deps.worktreeLocator !== undefined &&\n prepared.targetHints !== undefined &&\n prepared.targetHints.size > 0\n ) {\n const targeted = await resolveEventTargets({\n events: batch,\n hints: prepared.targetHints,\n locator: deps.worktreeLocator,\n privacy,\n budgetMillis: deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,\n });\n batch = targeted.events;\n if (targeted.timedOut) {\n logger.debug(\"worktree target resolution exceeded its budget\", {\n \"provider.id\": detection.providerId,\n \"target.resolved\": targeted.resolved,\n });\n }\n }\n\n // Session context: a core step, never adapter code (ADR 0003), outside the\n // session lock like target resolution. One bounded read of the file for this\n // invocation's session — for a subagent event that is its parent's session,\n // because events carry the invocation's session id, never the subagent's.\n // Always run, so an event can only ever carry the core's stamp.\n batch = stampSessionContext(\n batch,\n !suppress && batch.length > 0 && deps.sessionContext !== undefined\n ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId)\n : undefined,\n );\n\n let emitted = 0;\n let exportRejected = 0;\n if (!suppress && batch.length > 0) {\n try {\n const result = await deps.sink.emit(batch);\n emitted = result.accepted;\n exportRejected = result.rejected;\n diagnostics.push(...result.errors);\n } catch (thrown) {\n // A throwing sink delivered nothing and spooled nothing.\n exportRejected = batch.length;\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"export\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n\n const durability = classifyDurability({\n attempted: !suppress && batch.length > 0,\n accepted: emitted,\n rejected: exportRejected,\n });\n\n /**\n * Usage accounting is the *commit* half of the transaction, so it runs here\n * and not in `prepare`.\n *\n * Deriving a delta advances the stored cumulative baseline, which is a\n * one-way move: once it points at this snapshot, the difference this callback\n * represented is no longer recoverable from state. Doing that before knowing\n * whether the telemetry survived means a fully rejected callback releases its\n * claim having *already* consumed its own usage — so the retry diffs against\n * the advanced baseline, reports roughly zero, and the tokens are gone. Delta\n * usage has the mirror-image failure: it needs no baseline, so a retry\n * accumulates the same delta a second time.\n *\n * Nothing exported depends on these numbers — a span carries the usage the\n * provider *reported*, never the derived delta — so deferring costs nothing\n * and buys exactly-once accounting. The read of the baseline, the diff, and\n * the write back all stay inside one critical section, so two concurrent\n * processes cannot both diff against the same snapshot.\n *\n * A suppressed redelivery and a fully rejected attempt both skip this\n * entirely, which is what leaves the baseline where the next real attempt\n * needs it.\n */\n let usageObservations: readonly UsageObservation[] = [];\n if (durability !== \"lost\" && !suppress && batch.length > 0) {\n try {\n usageObservations = await withOptionalSessionLock(\n deps.stateStore,\n identity.sessionId,\n () =>\n deriveUsage(\n batch,\n diagnostics,\n false,\n adapter.capabilities.cumulativeUsageSeries ?? \"event-scope\",\n ),\n );\n } catch (thrown) {\n // The accounting could not be committed. The telemetry is already out, so\n // this is a reporting gap rather than a lost observation: it is said out\n // loud and the callback stays committed, because retrying it would\n // re-export spans a collector has already accepted.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"usage accounting could not be committed for a delivered callback\", {\n \"provider.id\": detection.providerId,\n });\n }\n }\n\n return {\n ok: true,\n attribution: \"attributed\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: batch,\n usageObservations,\n emitted,\n exportRejected,\n durability,\n dropped,\n hookResponse: hookResponseFor(adapter, detection, \"attributed\", undefined, emitted, diagnostics),\n diagnostics,\n };\n } catch (thrown) {\n // Last line of defence: anything unanticipated becomes a diagnostic.\n const info = errorInfoFromThrown(thrown, { code: \"internal-error\", phase: \"parsing\" });\n diagnostics.push(info);\n logger.error(\"ingest contained an unexpected failure\", {\n \"error.code\": info.code,\n ...(info.details ?? {}),\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: \"unknown\",\n detectionConfidence: \"none\",\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n await deps.sink.flush();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" });\n logger.warn(\"flush failed\", { \"error.code\": info.code });\n }\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await deps.sink.shutdown();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"shutdown\",\n });\n logger.warn(\"shutdown failed\", { \"error.code\": info.code });\n }\n };\n\n return { resolveDelivery, ingest, flush, shutdown, config };\n};\n\n/** Fail-open wrapper: a reader that throws despite its contract stamps nothing. */\nconst readSessionContext = async (\n reader: SessionContextReader,\n providerId: string,\n sessionId: string,\n): Promise<Awaited<ReturnType<SessionContextReader[\"read\"]>>> => {\n try {\n return await reader.read({ providerId, sessionId });\n } catch {\n return undefined;\n }\n};\n\nconst buildErrorEvents = (\n diagnostics: readonly OtelHookErrorInfo[],\n identity: InvocationIdentity,\n sequenceBase: number,\n ids: IdGenerator,\n privacy: PrivacyService,\n): readonly CanonicalEvent[] => {\n const events: CanonicalEvent[] = [];\n for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {\n const sequence = sequenceBase + index;\n events.push({\n schemaVersion: CANONICAL_SCHEMA_VERSION,\n eventId: ids.newEventId({\n invocationId: identity.invocationId,\n sequence,\n eventType: \"error.raised\",\n discriminator: info.code,\n }),\n invocationId: identity.invocationId,\n sessionId: identity.sessionId,\n sequence,\n occurredAt: info.occurredAt ?? identity.startedAt,\n provenance: identity.provenance,\n workspace: identity.workspace,\n extensions: {},\n type: \"error.raised\",\n errorCode: info.code,\n severity: info.severity,\n phase: info.phase,\n retryable: info.retryable,\n // The message is already a fixed-vocabulary summary, but it still passes\n // through the privacy service so one policy governs every disclosure.\n message: privacy.describeContent({ kind: \"error-message\", text: info.message }),\n detail: info.code,\n });\n }\n return events;\n};\n","import type { DeliveryIdentifierSupport, ProviderDeliveryClaim } from \"../providers/adapter.js\";\nimport type { IdGenerator } from \"./ports.js\";\n\n/**\n * Where a delivery identity came from.\n *\n * `host` is an id the embedding host passed in; `provider` is one normalized\n * from payload fields the selected adapter vouched for. The two are kept\n * distinguishable because they carry different guarantees: a host id is unique\n * by construction, a provider-derived one is only as good as the adapter's\n * evidence.\n */\nexport type DeliveryOrigin = \"host\" | \"provider\";\n\n/**\n * A delivery identity reduced to the two opaque strings deduplication needs.\n *\n * Both are digests, never raw payload values. That matters because the pair\n * becomes a state-store key and a diagnostic attribute: a provider's session id,\n * tool-call id, or turn id would otherwise be written to disk and logged as a\n * side effect of deduplication, which is not a disclosure anybody asked for.\n */\nexport type ResolvedDeliveryIdentity = {\n /** Namespace the callback id is unique within. */\n readonly scope: string;\n /** Opaque identity of this callback within that scope. */\n readonly callbackId: string;\n readonly origin: DeliveryOrigin;\n /** Non-sensitive justifications, for diagnostics. Empty for a host id. */\n readonly evidence: readonly string[];\n};\n\n/** Why no replay-stable delivery identity could be established. */\nexport type DeliveryUnavailableReason =\n /** No adapter was selected, so nothing could vouch for an identifier. */\n | \"provider-unattributed\"\n /** The adapter declares that no callback of this provider carries one. */\n | \"provider-declares-none\"\n /** The adapter supports some callbacks, but not this one. */\n | \"callback-not-identifiable\"\n /** The adapter offered an identity that failed the contract's own guards. */\n | \"claim-rejected\"\n /**\n * An identity was established but the state store could not be read or written,\n * so nothing could be claimed against it.\n */\n | \"state-unavailable\";\n\nexport type DeliveryResolution =\n | { readonly status: \"resolved\"; readonly identity: ResolvedDeliveryIdentity }\n | {\n readonly status: \"unavailable\";\n readonly reason: DeliveryUnavailableReason;\n /** Present once a provider has been selected. */\n readonly providerId?: string;\n /** The adapter's declared coverage, when there is an adapter. */\n readonly capability?: DeliveryIdentifierSupport;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Taken from the detection, which already carries it into span attributes\n * and provenance, so it discloses nothing new — and it is the difference\n * between a diagnostic an operator can act on and one that only restates\n * that something is missing.\n */\n readonly sourceEventName?: string;\n /**\n * Why, in the adapter's own words: a rejected claim's failure, or the\n * per-callback gap the adapter documents. Never contains payload values.\n */\n readonly detail?: string;\n };\n\n/**\n * Scope prefix for provider-derived identities.\n *\n * Kept distinct from a host-chosen scope so the two id spaces cannot be\n * confused, and so a host that starts supplying `--callback-id` does not inherit\n * whatever the adapter had already recorded for the same callbacks.\n */\nconst PROVIDER_SCOPE_PREFIX = \"provider-session\";\n\n/**\n * Namespace a host-supplied delivery id.\n *\n * Deliberately *not* scoped by session or installation: the host documented its\n * id as unique between distinct callbacks, so narrowing the scope here would\n * make a host id that repeats across two sessions stop being recognized as the\n * redelivery the host said it was.\n */\nexport const hostDeliveryIdentity = (\n callbackId: string,\n scope?: string,\n): ResolvedDeliveryIdentity => ({\n scope: scope ?? \"delivery\",\n callbackId,\n origin: \"host\",\n evidence: [],\n});\n\n/**\n * Reduce an adapter's delivery claim to an opaque, replay-stable identity.\n *\n * Scoping runs provider id, installation, and the provider's own session id\n * through the digest, so the same tool-call id observed by two installations, two\n * providers, or two sessions is three different callbacks. The callback digest\n * covers the event name and the adapter's components, so a `PreToolUse` and a\n * `PostToolUse` sharing one `tool_use_id` stay distinct.\n *\n * The digest comes from the injected {@link IdGenerator}, which is\n * content-addressed by default — that is precisely what makes the identity\n * survive a process restart: a later process with the same namespace recomputes\n * the identical pair without reading any state.\n */\nexport const resolveDeliveryIdentity = (input: {\n readonly ids: IdGenerator;\n readonly providerId: string;\n readonly installationId: string;\n readonly claim: ProviderDeliveryClaim;\n}): ResolvedDeliveryIdentity => {\n const { ids, providerId, installationId, claim } = input;\n return {\n scope: `${PROVIDER_SCOPE_PREFIX}:${ids.newOpaqueId([\n \"delivery-scope\",\n providerId,\n installationId,\n claim.sessionId,\n ])}`,\n callbackId: ids.newOpaqueId([\n \"delivery-callback\",\n providerId,\n claim.sessionId,\n claim.sourceEventName,\n ...claim.components,\n ]),\n origin: \"provider\",\n evidence: [...claim.evidence],\n };\n};\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n eventIdSchema,\n invocationIdSchema,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { EventIdSeed, IdGenerator, InvocationIdSeed } from \"./ports.js\";\n\nconst digest = (namespace: string, parts: readonly (string | number | undefined)[]): string => {\n const hash = createHash(\"sha256\");\n hash.update(namespace);\n for (const part of parts) {\n hash.update(\"\\0\");\n hash.update(part === undefined ? \"\" : String(part));\n }\n return hash.digest(\"hex\");\n};\n\nexport type DeterministicIdOptions = {\n /**\n * Namespace mixed into every id. Two deployments using different namespaces\n * produce different ids for identical input, which prevents cross-tenant id\n * collisions in a shared collector.\n */\n readonly namespace?: string;\n /** Hex characters retained. 32 gives a 128-bit id. */\n readonly length?: number;\n};\n\n/**\n * Content-addressed id generator.\n *\n * Ids are a pure function of their seed, so re-running a hook on the same input\n * — a retry, a replayed transcript, a duplicated delivery — yields identical\n * ids. That makes the pipeline idempotent at the collector instead of relying on\n * exactly-once delivery, which hooks cannot provide.\n */\nexport const createDeterministicIdGenerator = (\n options: DeterministicIdOptions = {},\n): IdGenerator => {\n const namespace = options.namespace ?? \"otel-hook\";\n const length = Math.min(Math.max(options.length ?? 32, 16), 64);\n const truncate = (hex: string): string => hex.slice(0, length);\n\n return {\n newInvocationId: (seed: InvocationIdSeed): InvocationId =>\n invocationIdSchema.parse(\n `inv_${truncate(\n digest(`${namespace}/invocation`, [\n seed.providerId,\n seed.sessionId,\n seed.sourceEventName,\n seed.occurredAt,\n seed.discriminator,\n ]),\n )}`,\n ),\n newEventId: (seed: EventIdSeed): EventId =>\n eventIdSchema.parse(\n `evt_${truncate(\n digest(`${namespace}/event`, [\n seed.invocationId,\n seed.sequence,\n seed.eventType,\n seed.discriminator,\n ]),\n )}`,\n ),\n newOpaqueId: (parts: readonly string[]): string =>\n truncate(digest(`${namespace}/opaque`, parts)),\n };\n};\n\n/**\n * Random id generator.\n *\n * Use only when no stable seed exists; it is not replay-safe, so duplicate\n * deliveries become duplicate events.\n */\nexport const createRandomIdGenerator = (): IdGenerator => ({\n newInvocationId: (): InvocationId => invocationIdSchema.parse(`inv_${randomUUID()}`),\n newEventId: (): EventId => eventIdSchema.parse(`evt_${randomUUID()}`),\n newOpaqueId: (): string => randomUUID().replace(/-/g, \"\"),\n});\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport { modelDescriptorSchema, type CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { WorktreeKind } from \"../model/target.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n /**\n * The model a session last reported, so a later invocation whose payload names\n * none (Claude Code's `Stop`) can still say which model it was. A model id is\n * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,\n * bounded canonical shape, never a payload fragment.\n */\n z.strictObject({\n kind: z.literal(\"session-model\"),\n model: modelDescriptorSchema,\n }),\n /**\n * How far a {@link PayloadEnricher} has read a session's append-only source\n * (Claude Code's transcript), so the next read starts where the last ended.\n * `source` is an opaque digest of what was read, never a path.\n */\n /**\n * Running state of one metric series (issue #69), so a cumulative data point\n * exported by a later hook process continues the same total. Holds numbers and\n * a series digest only; the series' attributes are re-supplied by the caller\n * and never read back from disk.\n */\n z.strictObject({\n kind: z.literal(\"metric-series\"),\n /** Start of the cumulative interval. */\n startTimeMillis: epochMillisSchema,\n /** Counters: the running total. */\n value: z.number().finite().min(0).optional(),\n /** Histograms: the running aggregation. */\n histogram: z\n .strictObject({\n count: z.number().int().min(0),\n sum: z.number().finite().min(0),\n min: z.number().finite(),\n max: z.number().finite(),\n bucketCounts: z.array(z.number().int().min(0)).max(64),\n })\n .optional(),\n /** Opaque digest of the last delivery folded in; makes a replay a no-op. */\n appliedDelivery: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"read-cursor\"),\n source: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n\n/** A git worktree found on the local filesystem. Holds a path: never exported. */\nexport type LocatedWorktree = {\n /** Absolute path of the worktree's top-level directory (the one holding `.git`). */\n readonly root: string;\n /** Branch checked out there, from `HEAD`; absent when HEAD is detached. */\n readonly branch?: string;\n /** Main checkout or linked worktree; absent when the locator does not tell. */\n readonly kind?: WorktreeKind;\n /**\n * Absolute path of the repository's main worktree — `root` itself for a main\n * worktree. Absent when there is none to name: a bare repository, a main\n * checkout that is gone, or a layout the locator cannot read.\n */\n readonly mainRoot?: string;\n};\n\n/**\n * Finds the git worktree containing a local path (ADR 0008).\n *\n * The only port that reads the filesystem on behalf of event content, which is\n * why it is a port: the core decides *when* to ask and what of the answer may be\n * exported, the implementation only answers. Implementations must never throw or\n * reject — any failure is `undefined` — and must not spawn processes.\n */\nexport interface WorktreeLocator {\n locate(absolutePath: string): Promise<LocatedWorktree | undefined>;\n}\n\n/** Where an enricher stopped reading a session's source; see the `read-cursor` state value. */\nexport type ReadCursor = {\n /** Opaque digest naming the source, so a cursor never applies to another file. */\n readonly source: string;\n /** Byte offset the next read starts at. */\n readonly offset: number;\n};\n\nexport type PayloadEnrichmentInput = {\n readonly payload: unknown;\n readonly sessionId: string;\n /** The cursor this enricher stored for this session (and cursor scope) last time, if any. */\n readonly cursor?: ReadCursor;\n};\n\nexport type PayloadEnrichment = {\n /** The payload the adapter parses: the input, or a copy with fields attached. */\n readonly payload: unknown;\n /** A cursor to store for this session; absent leaves the stored one as it is. */\n readonly cursor?: ReadCursor;\n /** Short, non-sensitive notes for the debug log (why a read fell back, ...). */\n readonly notes?: readonly string[];\n};\n\n/**\n * Host-side step that attaches facts to a provider payload before its adapter\n * parses it — for facts the provider writes somewhere other than the hook\n * payload, such as Claude Code's transcript.\n *\n * Not an adapter capability, on purpose: adapters get no filesystem handle (ADR\n * 0003). An enricher is configured by the host, runs inside the session lock so\n * its cursor is read and written atomically, and must be bounded and never throw\n * (a throw is contained and the original payload is parsed). It never runs for a\n * redelivered callback, which is not a new observation.\n */\nexport interface PayloadEnricher {\n /** Stable id; namespaces the enricher's cursor in the state store. */\n readonly id: string;\n /** The provider whose payloads it enriches. Others are never passed to it. */\n readonly providerId: string;\n /**\n * Which of the session's cursors this payload reads, when a session has more\n * than one source (Claude Code writes each subagent to its own transcript).\n * `undefined`, or no function, selects the session's own cursor. A scope is\n * part of a state key, never exported; it must not hold a path.\n */\n cursorScope?(payload: unknown): string | undefined;\n enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;\n}\n\n/**\n * One window of a session's context: the attributes in force from `from`\n * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.\n * Attributes are already screened (see `sanitizeSessionContextAttributes`).\n */\nexport type SessionContextSegment = {\n readonly from: EpochMillis;\n readonly to: EpochMillis | null;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type SessionContextRequest = {\n /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */\n readonly providerId: string;\n /**\n * The session whose context applies: always the invocation's session, which\n * for a subagent event is its parent's — never the subagent's own id.\n */\n readonly sessionId: string;\n};\n\n/**\n * Reads the session context a harness wrote for one agent session.\n *\n * A port for the same reason {@link WorktreeLocator} is one: the core decides\n * when to ask and what of the answer reaches a record; the implementation only\n * reads. Adapters never see it (ADR 0003). Implementations must never throw or\n * reject: no file, an unreadable file, an invalid one, or one of an unknown\n * version are all `undefined`, and the core then stamps nothing.\n */\nexport interface SessionContextReader {\n read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | undefined>;\n}\n","import type { Attributes } from \"../model/primitives.js\";\nimport { LOG_LEVEL_RANK, type Logger, type LogLevel } from \"./ports.js\";\n\nexport const createNullLogger = (): Logger => ({\n error: (): void => undefined,\n warn: (): void => undefined,\n info: (): void => undefined,\n debug: (): void => undefined,\n});\n\nexport type StderrLoggerOptions = {\n readonly level?: LogLevel;\n /** Injected for tests; defaults to `process.stderr.write`. */\n readonly write?: (line: string) => void;\n};\n\n/**\n * Diagnostic logger that writes to stderr only.\n *\n * stdout belongs to the host agent's hook protocol: anything written there can\n * be parsed as a hook response and change the agent's behaviour (ADR 0004).\n */\nexport const createStderrLogger = (options: StderrLoggerOptions = {}): Logger => {\n const level = options.level ?? \"warn\";\n const write =\n options.write ??\n ((line: string): void => {\n process.stderr.write(line);\n });\n const threshold = LOG_LEVEL_RANK[level];\n\n const log = (entryLevel: LogLevel, message: string, fields?: Attributes): void => {\n if (LOG_LEVEL_RANK[entryLevel] > threshold || threshold === 0) {\n return;\n }\n const payload =\n fields === undefined || Object.keys(fields).length === 0\n ? { level: entryLevel, message }\n : { level: entryLevel, message, fields };\n write(`${JSON.stringify(payload)}\\n`);\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n log(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n log(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n log(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n log(\"debug\", message, fields);\n },\n };\n};\n","import * as path from \"node:path\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { EventId } from \"../model/primitives.js\";\nimport { workspaceTargetSchema, type TargetHint, type WorkspaceTarget } from \"../model/target.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport { deriveWorkspaceIdentity } from \"../privacy/workspace.js\";\nimport type { LocatedWorktree, WorktreeLocator } from \"./ports.js\";\n\n/**\n * Turns adapters' target hints into exported worktree targets (ADR 0008).\n *\n * This is where local paths stop. A hint's paths are resolved to a worktree\n * root, branch, and repository through the injected {@link WorktreeLocator};\n * only salted `git-root` handles of the root and of its repository's main\n * worktree, the worktree's kind, and the branch name survive onto the event.\n *\n * Fail-open in both directions that matter: a slow or failing filesystem costs\n * the event its target, never the event — and never the host more than the\n * time budget. Fail-closed on meaning: a hint whose paths land in two different\n * worktrees, or that names a relative path with nothing to resolve it against,\n * yields no target rather than a guess.\n */\n\n/** Default ceiling on target resolution per callback. */\nexport const DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;\n\nconst absolutePathsOf = (hint: TargetHint): readonly string[] | undefined => {\n const base =\n hint.baseDirectory !== undefined && path.isAbsolute(hint.baseDirectory)\n ? hint.baseDirectory\n : undefined;\n const resolved: string[] = [];\n for (const candidate of hint.paths) {\n if (path.isAbsolute(candidate)) {\n resolved.push(path.resolve(candidate));\n } else if (base !== undefined) {\n resolved.push(path.resolve(base, candidate));\n } else {\n return undefined;\n }\n }\n return resolved;\n};\n\nconst resolveHint = async (\n hint: TargetHint,\n locator: WorktreeLocator,\n privacy: PrivacyService,\n): Promise<WorkspaceTarget | undefined> => {\n const paths = absolutePathsOf(hint);\n if (paths === undefined) {\n return undefined;\n }\n const located: (LocatedWorktree | undefined)[] = await Promise.all(\n [...new Set(paths)].map((candidate) => locator.locate(candidate)),\n );\n const [first] = located;\n if (first === undefined || located.some((entry) => entry?.root !== first.root)) {\n return undefined;\n }\n const identity = deriveWorkspaceIdentity(\n privacy,\n { kind: \"git-root\", absolutePath: first.root },\n first.branch === undefined ? {} : { vcsBranchName: first.branch },\n );\n if (identity.keySource !== \"git-root\") {\n return undefined;\n }\n // The repository is named by its main worktree, as that worktree would name\n // itself — so a main worktree's repository id is its own workspace id.\n const repository =\n first.mainRoot === undefined\n ? undefined\n : deriveWorkspaceIdentity(privacy, { kind: \"git-root\", absolutePath: first.mainRoot });\n const parsed = workspaceTargetSchema.safeParse({\n workspaceId: identity.workspaceId,\n ...(identity.vcsBranchName === undefined ? {} : { vcsBranchName: identity.vcsBranchName }),\n source: hint.source,\n ...(repository?.keySource === \"git-root\" ? { repositoryId: repository.workspaceId } : {}),\n ...(first.kind === undefined ? {} : { worktreeKind: first.kind }),\n });\n return parsed.success ? parsed.data : undefined;\n};\n\nexport type ResolveEventTargetsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly hints: ReadonlyMap<EventId, TargetHint>;\n readonly locator: WorktreeLocator;\n readonly privacy: PrivacyService;\n readonly budgetMillis: number;\n};\n\nexport type ResolveEventTargetsResult = {\n readonly events: readonly CanonicalEvent[];\n /** Hints that produced a target. */\n readonly resolved: number;\n /** True when the time budget expired before every hint was answered. */\n readonly timedOut: boolean;\n};\n\n/**\n * Attach a `target` to each targeted event (`TARGETED_EVENT_TYPES`) that has a resolvable hint. Never\n * throws or rejects; events without a hint, or whose hint does not resolve,\n * are returned unchanged.\n */\nexport const resolveEventTargets = async (\n input: ResolveEventTargetsInput,\n): Promise<ResolveEventTargetsResult> => {\n const pending = input.events.filter((event) => isTargetedEvent(event) && input.hints.has(event.eventId));\n if (pending.length === 0) {\n return { events: input.events, resolved: 0, timedOut: false };\n }\n\n const targets = new Map<EventId, WorkspaceTarget>();\n const work = Promise.all(\n pending.map(async (event) => {\n const hint = input.hints.get(event.eventId);\n if (hint === undefined) {\n return;\n }\n try {\n const target = await resolveHint(hint, input.locator, input.privacy);\n if (target !== undefined) {\n targets.set(event.eventId, target);\n }\n } catch {\n // A locator that broke its no-throw contract costs this event its target.\n }\n }),\n ).then(() => \"done\" as const);\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), Math.max(0, input.budgetMillis));\n timer.unref?.();\n });\n const finished = await Promise.race([work, deadline]);\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n // Snapshot: a resolution landing after the deadline must not mutate a batch\n // that is already on its way out.\n const settled = new Map(targets);\n const events = input.events.map((event): CanonicalEvent => {\n const target = settled.get(event.eventId);\n if (target === undefined || !isTargetedEvent(event)) {\n return event;\n }\n return { ...event, target };\n });\n return { events, resolved: settled.size, timedOut: finished === \"timeout\" };\n};\n","/**\n * Per-key async mutex.\n *\n * Ordinary promises already serialize a single caller's `await`s, but two\n * concurrent callers racing a read-modify-write against the same key (two\n * hook invocations updating the same session, in the same process) are not\n * serialized by anything. This chains each key's operations through a promise\n * tail so they run one at a time, in arrival order, without blocking unrelated\n * keys.\n */\nexport interface AsyncLock {\n /**\n * `timeoutMillis` bounds how long the caller waits to *acquire* the key.\n *\n * Two guarantees, and the boundary between them is the whole contract:\n *\n * - **A timed-out caller's `fn` never runs.** Giving up on the wait cancels the\n * queued operation. It has to: a caller that has been told \"I could not take\n * the lock\" will report contention and move on, and if `fn` then ran anyway it\n * would mutate state after the caller had already declared that nothing\n * happened. That is worse than either outcome on its own — the state changes\n * and nobody is watching.\n * - **Work is never cancelled after acquisition.** Once `fn` has started the\n * timeout is irrelevant; interrupting a read-modify-write partway through is\n * exactly the corruption a mutex exists to prevent. So the timeout bounds\n * *waiting*, never *exclusivity* and never *completion*.\n *\n * Cancellation does not let a waiter skip the queue: the cancelled slot still\n * settles in order, so everyone behind it keeps its place. A cancelled call\n * rejects with {@link LockWaitTimeoutError}, the same error a timed-out wait\n * produces, because from the caller's side they are one condition.\n */\n run<T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T>;\n}\n\nexport class LockWaitTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`lock wait exceeded ${timeoutMillis}ms`);\n this.name = \"LockWaitTimeoutError\";\n this.lockKey = key;\n }\n}\n\nexport const createAsyncLock = (): AsyncLock => {\n const tail = new Map<string, Promise<void>>();\n\n const run = async <T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T> => {\n const previous = tail.get(key) ?? Promise.resolve();\n const queued = previous.then(\n () => undefined,\n () => undefined,\n );\n\n /**\n * `entered` flips synchronously, immediately before `fn` is invoked, and\n * `cancelled` is only ever set from the timer while `entered` is false.\n *\n * That ordering is what makes the two guarantees exclusive rather than racy.\n * Microtasks drain before timers, so if this slot's turn has arrived at all,\n * the callback below has already run and set `entered` before any timer\n * callback can observe it — there is no window in which the timer sees a\n * not-yet-entered slot that is in fact about to run.\n */\n let cancelled = false;\n let entered = false;\n\n const current = queued.then((): T | Promise<T> => {\n if (cancelled) {\n // The waiter gave up before its turn came, so `fn` is skipped entirely.\n // The slot still settles here, in order, so nothing behind it is reordered.\n throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);\n }\n entered = true;\n return fn();\n });\n\n const swallowed = current.then(\n () => undefined,\n () => undefined,\n );\n tail.set(key, swallowed);\n void swallowed.then(() => {\n if (tail.get(key) === swallowed) {\n tail.delete(key);\n }\n });\n\n if (timeoutMillis === undefined) {\n return current;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n if (!entered) {\n cancelled = true;\n }\n reject(new LockWaitTimeoutError(key, timeoutMillis));\n }, timeoutMillis);\n timer.unref?.();\n });\n try {\n // Raced against the queue gate, not against `current`: once the slot is\n // entered the caller waits for `fn` however long it takes.\n await Promise.race([queued, timeout]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n return current;\n };\n\n return { run };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","import { open } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n} from \"../config/resource-attributes.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { SessionContextReader, SessionContextSegment } from \"./ports.js\";\n\n/**\n * Session context: attributes a harness wants on every record of one agent\n * session, for a window of time.\n *\n * A harness (HAR, or anything else) writes one JSON file per agent session:\n *\n * ```text\n * <dir>/<agent-tool>/<session-id>.json\n * { \"version\": 1, \"agentTool\": \"claude_code\", \"sessionId\": \"…\",\n * \"segments\": [ { \"from\": \"<ISO-8601>\", \"to\": \"<ISO-8601>\" | null,\n * \"reason\": \"launch\", \"attributes\": { \"k\": \"v\" } } ] }\n * ```\n *\n * On every hook event the core reads the one file for the event's session,\n * picks the segment in force at each event's time, and stamps its attributes on\n * every record the event produces. otel-hook knows nothing about what the\n * attributes mean: it applies an attribute map. See `docs/session-context.md`.\n *\n * Fail-open throughout: a missing, unreadable, oversized, invalid, or\n * wrong-version file — or no segment in force — stamps nothing and never fails\n * the hook.\n */\n\n/** The only file format version this build reads. Any other is ignored whole. */\nexport const SESSION_CONTEXT_FILE_VERSION = 1 as const;\n\n/** Largest file read; anything bigger is ignored rather than truncated. */\nexport const DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;\n\n/** Ceiling on one read; a slow filesystem costs the stamp, never the hook. */\nexport const DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;\n\n/** Upper bound on segments considered in one file. */\nexport const MAX_SESSION_CONTEXT_SEGMENTS = 1024;\n\n/**\n * otel-hook provider id → the agent-tool directory a harness writes under.\n *\n * The names are the ones HAR derives from the agent process it finds\n * (`claude_code`, `codex`, `cursor`). A provider absent from this table has no\n * session context: nothing is read for it.\n */\nexport const SESSION_CONTEXT_AGENT_TOOLS: Readonly<Record<string, string>> = Object.freeze({\n \"claude-code\": \"claude_code\",\n codex: \"codex\",\n cursor: \"cursor\",\n \"gemini-cli\": \"gemini_cli\",\n antigravity: \"antigravity\",\n});\n\nexport const sessionContextAgentTool = (providerId: string): string | undefined =>\n Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : undefined;\n\n/**\n * A session id is used as a file name, so it must be one: no separators, no\n * `.`/`..`, nothing a path could be steered with. Real session ids (UUIDs) pass.\n */\nconst SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;\n\nexport const isSessionContextFileName = (sessionId: string): boolean =>\n SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes(\"..\");\n\n/**\n * Where the context of one session lives, or `undefined` when the provider has\n * no agent-tool directory or the session id cannot be a file name.\n */\nexport const sessionContextFilePath = (\n dir: string,\n providerId: string,\n sessionId: string,\n): string | undefined => {\n const tool = sessionContextAgentTool(providerId);\n if (tool === undefined || !isSessionContextFileName(sessionId) || !path.isAbsolute(dir)) {\n return undefined;\n }\n return path.join(dir, tool, `${sessionId}.json`);\n};\n\n/**\n * Keys a context may never set, whatever it says.\n *\n * - `factory.local.*`: the Factory Commits telemetry profile defines it as\n * local-only (paths and the like); it must never reach a record.\n * - otel-hook's own record identity (`session.id`, `otelhook.*`, the hex trace\n * ids, `gen_ai.conversation.id`): a context file describes the work a session\n * does, it does not get to rename the session or forge its trace.\n * - Everything `checkResourceAttributeKey` refuses: malformed keys, the\n * `service.*` exporter policy keys, and secret-like names.\n */\nconst RESERVED_CONTEXT_KEYS: ReadonlySet<string> = new Set([\n \"session.id\",\n \"trace_id\",\n \"span_id\",\n \"parent_span_id\",\n \"gen_ai.conversation.id\",\n \"factory.local\",\n]);\nconst RESERVED_CONTEXT_PREFIXES: readonly string[] = Object.freeze([\"factory.local.\", \"otelhook.\"]);\n\nexport const isReservedSessionContextKey = (key: string): boolean =>\n RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));\n\n/**\n * Screen one segment's attribute map: primitive values only, bounded, and no\n * reserved or unsafe key. Dropped entries are dropped silently, one by one; the\n * rest of the map still applies.\n */\nexport const sanitizeSessionContextAttributes = (\n attributes: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, string | number | boolean>> => {\n const kept: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (count >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n if (checkResourceAttributeKey(key) !== undefined || isReservedSessionContextKey(key)) {\n continue;\n }\n if (typeof value === \"string\") {\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n continue;\n }\n } else if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n continue;\n }\n } else if (typeof value !== \"boolean\") {\n continue;\n }\n kept[key] = value;\n count += 1;\n }\n return kept;\n};\n\nconst ISO_INSTANT_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nconst isoInstantSchema = z\n .string()\n .max(64)\n .regex(ISO_INSTANT_PATTERN)\n .transform((value, ctx) => {\n const millis = Date.parse(value);\n if (!Number.isFinite(millis)) {\n ctx.issues.push({ code: \"custom\", input: value, message: \"not a valid instant\" });\n return z.NEVER;\n }\n return millis;\n });\n\nconst segmentSchema = z.object({\n from: isoInstantSchema,\n to: isoInstantSchema.nullable(),\n reason: z.string().max(256).optional(),\n attributes: z.record(z.string(), z.unknown()),\n});\n\n/**\n * The file format. Unknown extra fields are tolerated (a later minor revision\n * may add some); a different `version` is not, because its fields may mean\n * something else.\n */\nconst sessionContextFileSchema = z.object({\n version: z.literal(SESSION_CONTEXT_FILE_VERSION),\n agentTool: z.string().max(64).optional(),\n sessionId: z.string().max(256).optional(),\n segments: z.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS),\n});\n\n/**\n * Parse a decoded context file into screened segments.\n *\n * `expected` guards against a file that names another session or tool than the\n * one it was read for (a copy, a misplaced write): such a file applies to\n * nobody. Returns `undefined` for anything invalid; never throws.\n */\nexport const parseSessionContextFile = (\n value: unknown,\n expected?: { readonly agentTool?: string; readonly sessionId?: string },\n): readonly SessionContextSegment[] | undefined => {\n const parsed = sessionContextFileSchema.safeParse(value);\n if (!parsed.success) {\n return undefined;\n }\n const file = parsed.data;\n if (\n (expected?.agentTool !== undefined && file.agentTool !== undefined && file.agentTool !== expected.agentTool) ||\n (expected?.sessionId !== undefined && file.sessionId !== undefined && file.sessionId !== expected.sessionId)\n ) {\n return undefined;\n }\n return file.segments.map((segment) => ({\n from: segment.from,\n to: segment.to,\n attributes: sanitizeSessionContextAttributes(segment.attributes),\n }));\n};\n\n/**\n * The segment in force at `at`: `from <= at` and (`to` is null or `at < to`).\n * Should a writer ever leave two overlapping, the one that started last wins,\n * because it is the more recent statement.\n */\nexport const segmentInForce = (\n segments: readonly SessionContextSegment[],\n at: number,\n): SessionContextSegment | undefined => {\n let best: SessionContextSegment | undefined;\n for (const segment of segments) {\n if (segment.from <= at && (segment.to === null || at < segment.to)) {\n if (best === undefined || segment.from >= best.from) {\n best = segment;\n }\n }\n }\n return best;\n};\n\n/**\n * Stamp each event with the attributes of the segment in force at its own\n * `occurredAt`, and strip any `contextAttributes` an event already carried: only\n * this core step may set them. An event with no segment in force, or one whose\n * segment has no usable attribute, carries none.\n */\nexport const stampSessionContext = (\n events: readonly CanonicalEvent[],\n segments: readonly SessionContextSegment[] | undefined,\n): readonly CanonicalEvent[] =>\n events.map((event) => {\n const { contextAttributes: _discarded, ...rest } = event;\n const segment = segments === undefined ? undefined : segmentInForce(segments, event.occurredAt);\n if (segment === undefined || Object.keys(segment.attributes).length === 0) {\n return _discarded === undefined ? event : (rest);\n }\n return { ...rest, contextAttributes: { ...segment.attributes } };\n });\n\nexport type DirectorySessionContextReaderOptions = {\n /** Absolute directory holding `<agent-tool>/<session-id>.json`. */\n readonly dir: string;\n readonly maxBytes?: number;\n readonly budgetMillis?: number;\n};\n\nconst readBounded = async (file: string, maxBytes: number): Promise<string | undefined> => {\n let handle;\n try {\n handle = await open(file, \"r\");\n } catch {\n return undefined;\n }\n try {\n const stats = await handle.stat();\n if (!stats.isFile() || stats.size > maxBytes) {\n return undefined;\n }\n const buffer = Buffer.alloc(maxBytes + 1);\n let length = 0;\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);\n if (bytesRead === 0) {\n break;\n }\n length += bytesRead;\n }\n if (length > maxBytes) {\n return undefined;\n }\n return buffer.subarray(0, length).toString(\"utf8\");\n } catch {\n return undefined;\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\n/**\n * The filesystem {@link SessionContextReader}: one bounded read of one file per\n * call, never a directory scan. Never throws.\n */\nexport const createDirectorySessionContextReader = (\n options: DirectorySessionContextReaderOptions,\n): SessionContextReader => {\n const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;\n const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;\n\n const readOnce = async (\n providerId: string,\n sessionId: string,\n ): Promise<readonly SessionContextSegment[] | undefined> => {\n const file = sessionContextFilePath(options.dir, providerId, sessionId);\n if (file === undefined) {\n return undefined;\n }\n const text = await readBounded(file, maxBytes);\n if (text === undefined) {\n return undefined;\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(text);\n } catch {\n return undefined;\n }\n const agentTool = sessionContextAgentTool(providerId);\n return parseSessionContextFile(decoded, {\n ...(agentTool === undefined ? {} : { agentTool }),\n sessionId,\n });\n };\n\n return {\n read: async (request) => {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), budgetMillis);\n timer.unref?.();\n });\n try {\n return await Promise.race([\n readOnce(request.providerId, request.sessionId).catch(() => undefined),\n timeout,\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n },\n };\n};\n","import { createErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, Logger, LogLevel, StateRecord, StateStore, StateValue, TelemetryEmitResult, TelemetrySink } from \"./ports.js\";\nimport { stateRecordSchema } from \"./ports.js\";\nimport { LOG_LEVEL_RANK } from \"./ports.js\";\n\nexport type InMemoryStateStoreOptions = {\n readonly clock: Clock;\n /**\n * Fail the next N operations. Used to prove the pipeline degrades instead of\n * throwing when state is unavailable.\n */\n readonly failOperations?: number;\n};\n\nexport interface InMemoryStateStore extends StateStore {\n /** Direct view of stored records, for assertions. */\n snapshot(): ReadonlyMap<string, StateRecord>;\n /** Make the next `count` operations reject. */\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createInMemoryStateStore = (\n options: InMemoryStateStoreOptions,\n): InMemoryStateStore => {\n const records = new Map<string, StateRecord>();\n let failures = options.failOperations ?? 0;\n\n const guard = (operation: string): void => {\n if (failures > 0) {\n failures -= 1;\n throw new Error(`in-memory state store failure injected during ${operation}`);\n }\n };\n\n return {\n read: (key: string): Promise<StateRecord | undefined> => {\n guard(\"read\");\n return Promise.resolve(records.get(key));\n },\n write: (key: string, value: StateValue): Promise<StateRecord> => {\n guard(\"write\");\n const previous = records.get(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n records.set(key, record);\n return Promise.resolve(record);\n },\n delete: (key: string): Promise<void> => {\n guard(\"delete\");\n records.delete(key);\n return Promise.resolve();\n },\n keys: (prefix: string): Promise<readonly string[]> => {\n guard(\"keys\");\n return Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort());\n },\n snapshot: (): ReadonlyMap<string, StateRecord> => new Map(records),\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n records.clear();\n },\n };\n};\n\nexport type RecordingTelemetrySinkOptions = {\n /** Reject the next N batches, reporting an export failure. */\n readonly failBatches?: number;\n};\n\nexport interface RecordingTelemetrySink extends TelemetrySink {\n /** Batches in emit order. */\n batches(): readonly (readonly CanonicalEvent[])[];\n /** All events, flattened. */\n events(): readonly CanonicalEvent[];\n flushCount(): number;\n shutdownCount(): number;\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createRecordingTelemetrySink = (\n options: RecordingTelemetrySinkOptions = {},\n): RecordingTelemetrySink => {\n const batches: (readonly CanonicalEvent[])[] = [];\n let failures = options.failBatches ?? 0;\n let flushes = 0;\n let shutdowns = 0;\n\n return {\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n if (failures > 0) {\n failures -= 1;\n return Promise.resolve({\n accepted: 0,\n rejected: events.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"recording sink rejected the batch\",\n details: { \"export.batch_size\": events.length },\n }),\n ],\n });\n }\n batches.push([...events]);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => {\n flushes += 1;\n return Promise.resolve();\n },\n shutdown: (): Promise<void> => {\n shutdowns += 1;\n return Promise.resolve();\n },\n batches: (): readonly (readonly CanonicalEvent[])[] => batches.map((batch) => [...batch]),\n events: (): readonly CanonicalEvent[] => batches.flat(),\n flushCount: (): number => flushes,\n shutdownCount: (): number => shutdowns,\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n batches.length = 0;\n },\n };\n};\n\n/** Sink that accepts and discards everything. */\nexport const createNullTelemetrySink = (): TelemetrySink => ({\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: events.length, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n});\n\nexport type LogRecord = {\n readonly level: Exclude<LogLevel, \"silent\">;\n readonly message: string;\n readonly fields?: Attributes;\n};\n\nexport interface RecordingLogger extends Logger {\n records(): readonly LogRecord[];\n clear(): void;\n}\n\nexport const createRecordingLogger = (level: LogLevel = \"debug\"): RecordingLogger => {\n const records: LogRecord[] = [];\n const threshold = LOG_LEVEL_RANK[level];\n const push = (\n entryLevel: Exclude<LogLevel, \"silent\">,\n message: string,\n fields?: Attributes,\n ): void => {\n if (threshold === 0 || LOG_LEVEL_RANK[entryLevel] > threshold) {\n return;\n }\n records.push({ level: entryLevel, message, ...(fields === undefined ? {} : { fields }) });\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n push(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n push(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n push(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n push(\"debug\", message, fields);\n },\n records: (): readonly LogRecord[] => [...records],\n clear: (): void => {\n records.length = 0;\n },\n };\n};\n","import { z } from \"zod\";\n\nimport { createErrorInfo } from \"../errors/index.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../model/identity.js\";\nimport { providerIdSchema, sessionIdSchema, type ProviderId } from \"../model/primitives.js\";\nimport { normalizeUsage, usageReportSchema } from \"../model/usage.js\";\nimport { deriveWorkspaceIdentity } from \"../privacy/workspace.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDeliveryClaim,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderHookResponseInput,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../providers/adapter.js\";\nimport { createEventFactory } from \"../providers/builder.js\";\n\n/**\n * Synthetic hook payload used by the reference adapter.\n *\n * Provenance: invented for this repository. It resembles no real provider's\n * protocol and contains no captured transcript, path, or credential.\n */\nexport const syntheticPayloadSchema = z.object({\n provider: z.string().min(1),\n sessionId: z.string().min(1),\n event: z.enum([\n \"session.start\",\n \"prompt\",\n \"generation\",\n \"tool\",\n \"subagent\",\n \"compaction\",\n \"session.end\",\n \"noop\",\n ]),\n requestId: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n promptText: z.string().optional(),\n toolName: z.string().min(1).optional(),\n toolInput: z.unknown().optional(),\n workspaceKey: z.string().min(1).optional(),\n occurredAt: z.number().int().min(0).optional(),\n usage: usageReportSchema.optional(),\n agentVersion: z.string().min(1).optional(),\n});\nexport type SyntheticPayload = z.infer<typeof syntheticPayloadSchema>;\n\nexport const SYNTHETIC_PROVIDER_ID = \"fixture\" as const;\n\nexport const DEFAULT_FIXTURE_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\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 ] as const),\n usageTemporality: \"delta\",\n reportsCachedInput: true,\n reportsCacheCreation: true,\n cacheCreationAccounting: \"disjoint-from-input\",\n reportsReasoningOutput: true,\n reportsProviderTotal: true,\n reportsCost: false,\n emitsSubagentEvents: true,\n emitsCompactionEvents: true,\n requiresHookResponse: false,\n // The synthetic protocol carries an optional `requestId`, so some payloads are\n // replay-identifiable and some are not — the mixed case a core test wants.\n deliveryIdentifier: \"partial\",\n});\n\nexport type FixtureAdapterOptions = {\n readonly id?: string;\n readonly version?: string;\n readonly capabilities?: Partial<ProviderCapabilities>;\n /** Confidence reported when the payload matches this adapter's provider id. */\n readonly confidence?: ProviderDetection[\"confidence\"];\n /** Replace detection entirely, e.g. to simulate an ambiguous registry. */\n readonly detect?: (input: ProviderDetectionInput, context: ProviderContext) => ProviderDetection;\n /** Extra claims merged after the adapter's own, e.g. to force a conflict. */\n readonly extraClaims?: readonly IdentityClaim[];\n /** Throw from the named method, to exercise containment. */\n readonly throwOn?: \"detect\" | \"identify\" | \"parse\" | \"hookResponse\" | \"deliveryIdentity\";\n /**\n * Replace the delivery claim entirely, e.g. to return one the contract's own\n * component guard must reject.\n */\n readonly deliveryIdentity?: (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ) => ProviderDeliveryClaim | undefined;\n /** Emit a provider-protocol stdout response instead of staying silent. */\n readonly hookResponse?: (\n input: ProviderHookResponseInput,\n context: ProviderContext,\n ) => ProviderHookResponse;\n};\n\n/**\n * Reference adapter over the synthetic payload above.\n *\n * Provider agents can use it to exercise the core contract — registry\n * arbitration, identity resolution, privacy screening, usage derivation — without\n * depending on any real provider protocol.\n */\nexport const createFixtureAdapter = (options: FixtureAdapterOptions = {}): ProviderAdapter => {\n const id: ProviderId = providerIdSchema.parse(options.id ?? SYNTHETIC_PROVIDER_ID);\n const version = options.version ?? \"1.0.0\";\n const capabilities: ProviderCapabilities = {\n ...DEFAULT_FIXTURE_CAPABILITIES,\n ...options.capabilities,\n };\n const confidence = options.confidence ?? \"exact\";\n\n const detect = (input: ProviderDetectionInput, context: ProviderContext): ProviderDetection => {\n if (options.throwOn === \"detect\") {\n throw new Error(\"fixture adapter detect failure\");\n }\n if (options.detect !== undefined) {\n return options.detect(input, context);\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success || parsed.data.provider !== id) {\n return providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: [\"payload does not match the synthetic fixture protocol\"],\n });\n }\n return providerDetectionSchema.parse({\n providerId: id,\n confidence,\n reasons: [\"payload.provider matches the fixture provider id\"],\n providerVersion: parsed.data.agentVersion ?? \"0.1.0\",\n sourceEventName: parsed.data.event,\n });\n };\n\n const identify = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): readonly IdentityClaim[] => {\n if (options.throwOn === \"identify\") {\n throw new Error(\"fixture adapter identify failure\");\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return options.extraClaims ?? [];\n }\n const payload = parsed.data;\n const occurredAt = payload.occurredAt ?? context.clock.now();\n const sessionId = sessionIdSchema.parse(payload.sessionId);\n const claim = identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId: context.ids.newInvocationId({\n providerId: id,\n sessionId,\n sourceEventName: payload.event,\n occurredAt,\n ...(payload.requestId === undefined ? {} : { discriminator: payload.requestId }),\n }),\n startedAt: occurredAt,\n ...(payload.workspaceKey === undefined\n ? {}\n : {\n workspace: deriveWorkspaceIdentity(context.privacy, {\n kind: \"explicit\",\n value: payload.workspaceKey,\n }),\n }),\n },\n });\n return [claim, ...(options.extraClaims ?? [])];\n };\n\n /**\n * The synthetic protocol's `requestId` names one request, so it identifies a\n * delivery; a payload without one is deliberately left unidentifiable, which is\n * what lets a core test exercise both branches with the same adapter.\n */\n const deliveryIdentity = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): ProviderDeliveryClaim | undefined => {\n if (options.throwOn === \"deliveryIdentity\") {\n throw new Error(\"fixture adapter deliveryIdentity failure\");\n }\n if (options.deliveryIdentity !== undefined) {\n return options.deliveryIdentity(input, context);\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success || parsed.data.requestId === undefined) {\n return undefined;\n }\n return {\n sessionId: parsed.data.sessionId,\n sourceEventName: parsed.data.event,\n components: [parsed.data.requestId],\n evidence: [\"payload.requestId names one synthetic request\"],\n };\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n if (options.throwOn === \"parse\") {\n throw new Error(\"fixture adapter parse failure\");\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the synthetic fixture protocol\",\n }),\n };\n }\n const payload = parsed.data;\n if (payload.event === \"noop\") {\n return { status: \"ignored\", reason: \"synthetic noop event carries no telemetry\" };\n }\n\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const occurredAt = payload.occurredAt ?? context.clock.now();\n const model = { modelId: payload.model ?? \"synthetic-model-1\" };\n const warnings: string[] = [];\n\n const usage = ((): ReturnType<typeof normalizeUsage> | undefined => {\n if (payload.usage === undefined) {\n return undefined;\n }\n const normalized = normalizeUsage(payload.usage);\n if (normalized.status === \"invalid\") {\n warnings.push(...normalized.issues.map((issue) => issue.message));\n }\n return normalized;\n })();\n const canonicalUsage = usage?.status === \"ok\" ? usage.usage : undefined;\n\n switch (payload.event) {\n case \"session.start\":\n factory.build({\n type: \"session.start\",\n sessionKind: \"non-interactive\",\n agentName: `fixture-${id}`,\n ...(payload.agentVersion === undefined ? {} : { agentVersion: payload.agentVersion }),\n model,\n occurredAt,\n });\n break;\n case \"prompt\":\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n occurredAt,\n ...(payload.promptText === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.promptText,\n }),\n }),\n });\n break;\n case \"generation\": {\n const generationId = payload.requestId ?? context.ids.newOpaqueId([payload.sessionId, \"generation\"]);\n factory.build({ type: \"generation.start\", generationId, model, occurredAt });\n factory.build({\n type: \"generation.end\",\n generationId,\n model,\n outcome: \"ok\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n }\n case \"tool\": {\n const toolCallId = payload.requestId ?? context.ids.newOpaqueId([payload.sessionId, \"tool\"]);\n const toolName = payload.toolName ?? \"synthetic-tool\";\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName,\n toolKind: \"other\",\n occurredAt,\n ...(payload.toolInput === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.toolInput,\n label: toolName,\n }),\n }),\n });\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName,\n outcome: \"ok\",\n occurredAt,\n });\n break;\n }\n case \"subagent\": {\n const subagentInvocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId: payload.sessionId,\n sourceEventName: \"subagent\",\n occurredAt,\n ...(payload.requestId === undefined ? {} : { discriminator: payload.requestId }),\n });\n factory.build({\n type: \"subagent.start\",\n subagentInvocationId,\n delegationDepth: 1,\n occurredAt,\n });\n factory.build({\n type: \"subagent.end\",\n subagentInvocationId,\n outcome: \"ok\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n }\n case \"compaction\":\n factory.build({\n type: \"compaction.performed\",\n trigger: \"automatic\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n case \"session.end\":\n factory.build({\n type: \"session.end\",\n reason: \"completed\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n }\n\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n };\n\n const hookResponse = (\n input: ProviderHookResponseInput,\n context: ProviderContext,\n ): ProviderHookResponse => {\n if (options.throwOn === \"hookResponse\") {\n throw new Error(\"fixture adapter hookResponse failure\");\n }\n if (options.hookResponse !== undefined) {\n return options.hookResponse(input, context);\n }\n return SILENT_HOOK_RESPONSE;\n };\n\n return { id, version, capabilities, detect, identify, deliveryIdentity, parse, hookResponse };\n};\n","import {\n isContentFactConsistent,\n isUnavailableContentFact,\n type ContentDisclosure,\n type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\n\n/** Every content fact attached to an event, regardless of field name. */\nexport const collectEventContentFacts = (event: CanonicalEvent): readonly ContentFact[] => {\n const facts: ContentFact[] = [];\n const push = (fact: ContentFact | undefined): void => {\n if (fact !== undefined) {\n facts.push(fact);\n }\n };\n switch (event.type) {\n case \"prompt.submitted\":\n push(event.content);\n break;\n case \"generation.start\":\n facts.push(...(event.inputContent ?? []));\n break;\n case \"generation.end\":\n facts.push(...(event.outputContent ?? []));\n break;\n case \"tool.start\":\n push(event.input);\n break;\n case \"tool.end\":\n push(event.output);\n break;\n case \"error.raised\":\n push(event.message);\n break;\n default:\n break;\n }\n return facts;\n};\n\n/** Disclosed text across a batch, for assertions about what escaped. */\nexport const collectContentText = (events: readonly CanonicalEvent[]): readonly string[] => {\n const texts: string[] = [];\n for (const event of events) {\n for (const fact of collectEventContentFacts(event)) {\n if (fact.text !== undefined) {\n texts.push(fact.text);\n }\n }\n }\n return texts;\n};\n\nexport type ContentDisclosureViolation = {\n readonly eventId: string;\n readonly eventType: string;\n readonly kind: string;\n readonly disclosure: ContentDisclosure;\n readonly reason: \"unexpected-disclosure\" | \"inconsistent-fact\";\n};\n\n/**\n * Find content facts that disclose more than the expected mode allows.\n *\n * Provider suites are expected to assert this returns nothing under the default\n * `omit` policy.\n */\nexport const findDisclosureViolations = (\n events: readonly CanonicalEvent[],\n expected: ContentDisclosure = \"omitted\",\n): readonly ContentDisclosureViolation[] => {\n const violations: ContentDisclosureViolation[] = [];\n for (const event of events) {\n for (const fact of collectEventContentFacts(event)) {\n if (isUnavailableContentFact(fact)) {\n continue;\n }\n if (fact.disclosure !== expected) {\n violations.push({\n eventId: event.eventId,\n eventType: event.type,\n kind: fact.kind,\n disclosure: fact.disclosure,\n reason: \"unexpected-disclosure\",\n });\n continue;\n }\n if (!isContentFactConsistent(fact)) {\n violations.push({\n eventId: event.eventId,\n eventType: event.type,\n kind: fact.kind,\n disclosure: fact.disclosure,\n reason: \"inconsistent-fact\",\n });\n }\n }\n }\n return violations;\n};\n\n/**\n * Search a serialized batch for a literal substring.\n *\n * Used to prove a secret or prompt fragment is absent from everything a sink\n * would receive, including attributes and extensions.\n */\nexport const batchContains = (events: readonly CanonicalEvent[], needle: string): boolean =>\n JSON.stringify(events).includes(needle);\n","import {\n DEFAULT_CONFIG,\n otelHookConfigSchema,\n type OtelHookConfig,\n type OtelHookConfigPatch,\n} from \"../config/schema.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n invocationIdentitySchema,\n sourceProvenanceSchema,\n unknownWorkspaceIdentity,\n type InvocationIdentity,\n type SourceProvenance,\n} from \"../model/identity.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport { createProviderRegistry, type ProviderAdapter, type ProviderRegistry } from \"../providers/index.js\";\nimport { createFixedClock, type FixedClock } from \"../runtime/clock.js\";\nimport { createOtelHook, type OtelHook } from \"../runtime/hook.js\";\nimport { createDeterministicIdGenerator } from \"../runtime/ids.js\";\nimport {\n createInMemoryStateStore,\n createRecordingLogger,\n createRecordingTelemetrySink,\n type InMemoryStateStore,\n type RecordingLogger,\n type RecordingTelemetrySink,\n} from \"../runtime/memory.js\";\nimport type { IdGenerator, PayloadEnricher, SessionContextReader, WorktreeLocator } from \"../runtime/ports.js\";\n\nexport * from \"./fixture-adapter.js\";\nexport * from \"./assertions.js\";\nexport {\n createFixedClock,\n createInMemoryStateStore,\n createRecordingLogger,\n createRecordingTelemetrySink,\n createDeterministicIdGenerator,\n};\nexport type { FixedClock, InMemoryStateStore, RecordingLogger, RecordingTelemetrySink };\n\n/** Deterministic provenance for hand-built events. */\nexport const createTestProvenance = (\n overrides: Partial<SourceProvenance> = {},\n): SourceProvenance =>\n sourceProvenanceSchema.parse({\n providerId: \"fixture\",\n adapterId: \"fixture\",\n adapterVersion: \"1.0.0\",\n detectionConfidence: \"exact\",\n transport: \"test-fixture\",\n ...overrides,\n });\n\n/** Deterministic identity for hand-built events. */\nexport const createTestIdentity = (\n overrides: Partial<InvocationIdentity> = {},\n): InvocationIdentity =>\n invocationIdentitySchema.parse({\n invocationId: \"inv_test_0000000000000001\",\n sessionId: \"ses_test_0000000000000001\",\n provenance: createTestProvenance(),\n workspace: unknownWorkspaceIdentity(),\n startedAt: 1_700_000_000_000,\n consumerAttributes: {},\n ...overrides,\n });\n\nexport const createTestPrivacyService = (\n patch: Partial<OtelHookConfig[\"privacy\"]> = {},\n): PrivacyService => createPrivacyService({ ...DEFAULT_CONFIG.privacy, ...patch });\n\nexport type TestHarnessOptions = {\n readonly adapters?: readonly ProviderAdapter[];\n readonly registry?: ProviderRegistry;\n /** Shallow-merged over {@link DEFAULT_CONFIG}, then validated. */\n readonly config?: OtelHookConfigPatch;\n readonly clock?: FixedClock;\n readonly ids?: IdGenerator;\n readonly startMillis?: number;\n readonly tickMillis?: number;\n /**\n * Worktree resolution for event targets (ADR 0008). Absent by default, so the\n * harness stays filesystem-free; pass a fake, or the filesystem locator over a\n * temporary directory.\n */\n readonly worktreeLocator?: WorktreeLocator;\n /**\n * Ceiling on target resolution per callback (runtime default 50ms). A test of\n * what a target says, over a real filesystem, raises it so a slow CI runner\n * cannot turn the assertion into a timing race.\n */\n readonly targetResolutionBudgetMillis?: number;\n /** Payload enrichers, as a host would configure them (none by default). */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /** Session context reader (none by default), e.g. a fake or the directory reader. */\n readonly sessionContext?: SessionContextReader;\n};\n\nexport type TestHarness = {\n readonly hook: OtelHook;\n readonly sink: RecordingTelemetrySink;\n readonly stateStore: InMemoryStateStore;\n readonly clock: FixedClock;\n readonly ids: IdGenerator;\n readonly privacy: PrivacyService;\n readonly logger: RecordingLogger;\n readonly registry: ProviderRegistry;\n readonly config: OtelHookConfig;\n};\n\nconst mergeConfig = (patch: OtelHookConfigPatch | undefined): OtelHookConfig => {\n if (patch === undefined) {\n return DEFAULT_CONFIG;\n }\n return otelHookConfigSchema.parse({\n exporter: { ...DEFAULT_CONFIG.exporter, ...patch.exporter },\n privacy: {\n ...DEFAULT_CONFIG.privacy,\n ...patch.privacy,\n limits: { ...DEFAULT_CONFIG.privacy.limits, ...patch.privacy?.limits },\n },\n detection: { ...DEFAULT_CONFIG.detection, ...patch.detection },\n diagnostics: { ...DEFAULT_CONFIG.diagnostics, ...patch.diagnostics },\n });\n};\n\n/**\n * Fully wired hook backed by in-memory doubles and a deterministic clock.\n *\n * Nothing here reads the process environment, the filesystem, or the wall clock,\n * so a provider test is reproducible on any machine.\n */\nexport const createTestHook = (options: TestHarnessOptions = {}): TestHarness => {\n const config = mergeConfig(options.config);\n const clock =\n options.clock ??\n createFixedClock({\n startMillis: options.startMillis ?? 1_700_000_000_000,\n tickMillis: options.tickMillis ?? 0,\n });\n const ids = options.ids ?? createDeterministicIdGenerator({ namespace: \"test\" });\n const privacy = createPrivacyService(config.privacy);\n const logger = createRecordingLogger(\"debug\");\n const sink = createRecordingTelemetrySink();\n const stateStore = createInMemoryStateStore({ clock });\n const registry = options.registry ?? createProviderRegistry(options.adapters ?? []);\n\n const hook = createOtelHook({\n sink,\n stateStore,\n config,\n registry,\n clock,\n ids,\n privacy,\n logger,\n ...(options.worktreeLocator === undefined ? {} : { worktreeLocator: options.worktreeLocator }),\n ...(options.targetResolutionBudgetMillis === undefined\n ? {}\n : { targetResolutionBudgetMillis: options.targetResolutionBudgetMillis }),\n ...(options.payloadEnrichers === undefined ? {} : { payloadEnrichers: options.payloadEnrichers }),\n ...(options.sessionContext === undefined ? {} : { sessionContext: options.sessionContext }),\n });\n\n return { hook, sink, stateStore, clock, ids, privacy, logger, registry, config };\n};\n\n/** Convenience re-export so provider suites can type their own helpers. */\nexport type { CanonicalEvent };\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,KAAAA,UAAS;;;ACFlB,SAAS,SAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI3E,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,OAAO;AAGtD,IAAM,mBAAmB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAG/C,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAE1D,IAAM,kBAAkB,MAAmB,EAAE,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,oBAAoB,EAC9B,OAAO,EACP,MAAM,sBAAsB,0DAA0D,EACtF,MAAqB;AAIjB,IAAM,sBAAsB;AAC5B,IAAM,mBAAmB,EAC7B,OAAO,EACP,IAAI,CAAC,EACL,IAAI,EAAE,EACN,MAAM,qBAAqB,8CAA8C,EACzE,MAAoB;AAIhB,IAAM,sBAAsB;AAG5B,IAAM,2BAA2B,EAAE,MAAM;AA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;AAAA,IACA,GAAI,QAAQ,oBAAoB,SAAY,CAAC,IAAI,EAAE,iBAAiB,QAAQ,gBAAgB;AAAA,IAC5F,GAAI,QAAQ,iCAAiC,SACzC,CAAC,IACD,EAAE,8BAA8B,QAAQ,6BAA6B;AAAA,IACzE,GAAI,QAAQ,qBAAqB,SAAY,CAAC,IAAI,EAAE,kBAAkB,QAAQ,iBAAiB;AAAA,IAC/F,GAAI,QAAQ,mBAAmB,SAAY,CAAC,IAAI,EAAE,gBAAgB,QAAQ,eAAe;AAAA,EAC3F,CAAC;AAED,SAAO,EAAE,MAAM,MAAM,YAAY,OAAO,KAAK,SAAS,QAAQ,UAAU,OAAO;AACjF;","names":["z","z","z","z","z","z","z","z","z","z","parsed","z","z","bounded","path","z","z","z","z","z","z","z","z","z","z","z","event","z","z","z","z","asRecord","asRecord","messageText","asRecord","createHash","z","z","event","sessionStartPayloadSchema","sessionEndPayloadSchema","preToolUsePayloadSchema","postToolUsePayloadSchema","postToolUseFailurePayloadSchema","subagentStartPayloadSchema","subagentStopPayloadSchema","preCompactPayloadSchema","stopPayloadSchema","UNKNOWN_MODEL","detect","identify","parse","hookResponse","z","deliveryComponents","asRecord","nonEmptyString","asRecord","createHash","open","stat","path","z","BUILT_IN_TOOL_KIND","detect","identify","parse","hookResponse","z","commonFields","preToolUsePayloadSchema","postToolUsePayloadSchema","stopPayloadSchema","detect","identify","parse","hookResponse","z","createHash","createHash","z","z","path","event","resolve","open","path","z","z","event","z","event","batch","z","z","detect","identify","parse","hookResponse","event"]}
1
+ {"version":3,"sources":["../src/config/schema.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/config/destinations.ts","../src/config/header-value.ts","../src/config/otlp-headers.ts","../src/config/repository-key.ts","../src/config/resource-attributes.ts","../src/model/identity.ts","../src/privacy/service.ts","../src/model/extensions.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/errors/taxonomy.ts","../src/model/content.ts","../src/model/target.ts","../src/model/usage.ts","../src/model/version.ts","../src/errors/index.ts","../src/providers/builder.ts","../src/providers/registry.ts","../src/providers/claude/capabilities.ts","../src/providers/claude/schema.ts","../src/providers/claude/usage.ts","../src/providers/claude/payload-normalize.ts","../src/providers/claude/delivery.ts","../src/providers/claude/detect.ts","../src/privacy/workspace.ts","../src/providers/claude/identity.ts","../src/providers/claude/stop-content.ts","../src/providers/claude/target.ts","../src/providers/claude/tool-kind.ts","../src/providers/claude/events.ts","../src/providers/claude/adapter.ts","../src/providers/claude/transcript.ts","../src/providers/cursor/payload.ts","../src/providers/cursor/delivery.ts","../src/providers/cursor/target.ts","../src/providers/cursor/usage.ts","../src/providers/cursor/adapter.ts","../src/providers/codex/payload.ts","../src/providers/codex/delivery.ts","../src/providers/codex/target.ts","../src/providers/codex/tool-kind.ts","../src/providers/codex/usage.ts","../src/providers/codex/version.ts","../src/providers/codex/adapter.ts","../src/providers/codex/rollout-usage.ts","../src/providers/gemini/delivery.ts","../src/providers/gemini/identity.ts","../src/providers/gemini/schema.ts","../src/providers/gemini/tool-kind.ts","../src/providers/gemini/usage.ts","../src/providers/gemini/adapter.ts","../src/providers/antigravity/payload.ts","../src/providers/antigravity/delivery.ts","../src/providers/antigravity/adapter.ts","../src/providers/antigravity/maturity.ts","../src/providers/defaults.ts","../src/runtime/clock.ts","../src/runtime/hook.ts","../src/runtime/delivery.ts","../src/runtime/ids.ts","../src/runtime/ports.ts","../src/runtime/logger.ts","../src/runtime/target-resolution.ts","../src/state/async-lock.ts","../src/state/store.ts","../src/runtime/session-context.ts","../src/runtime/memory.ts","../src/testing/fixture-adapter.ts","../src/testing/assertions.ts","../src/testing/index.ts"],"sourcesContent":["import { isAbsolute } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { detectionConfidenceSchema, nonEmptyStringSchema } from \"../model/primitives.js\";\nimport {\n contentModeSchema,\n DEFAULT_PRIVACY_POLICY,\n privacyPolicySchema,\n} from \"../privacy/policy.js\";\nimport { exportDestinationsSchema, spoolPolicySchema } from \"./destinations.js\";\nimport { EMPTY_RESOURCE_ATTRIBUTES, resourceAttributesSchema } from \"./resource-attributes.js\";\n\n/**\n * Policy for the OTLP logs signal.\n *\n * Two switches rather than one, because they answer different questions and an\n * operator needs to be able to answer them differently:\n *\n * - `enabled` — whether a second signal leaves this host at all. Off by default:\n * an installation that upgrades must not silently start sending a new stream to a\n * collector whose receivers, quotas, and retention were sized for traces.\n * - `includeContent` — whether *disclosed* text may appear in a log body. Also off\n * by default, and deliberately not the same knob as `privacy.contentMode`: spans\n * carry no content in any content mode, so an installation that set\n * `contentMode` to get a hash and a length has never had content on the wire.\n * Reusing that setting to also mean \"publish prompts\" would change what an\n * existing configuration discloses without anybody editing it.\n *\n * `raw` content additionally requires the pre-existing `privacy.allowRawContent`\n * opt-in, which the privacy service enforces before a fact is ever built and the\n * log mapping re-checks at the wire.\n */\nexport const logsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /**\n * Full URL for the logs signal.\n *\n * Absent, it is derived from `endpoint`: a trailing `/v1/traces` becomes\n * `/v1/logs`, and an endpoint with no signal path has `/v1/logs` appended.\n */\n endpoint: z.string().url().max(2048).optional(),\n includeContent: z.boolean(),\n maxBatchSize: z.number().int().min(1).max(4096),\n});\nexport type LogsPolicy = z.infer<typeof logsPolicySchema>;\n\nexport const DEFAULT_LOGS_POLICY: LogsPolicy = Object.freeze({\n enabled: false,\n includeContent: false,\n maxBatchSize: 128,\n});\n\n/**\n * Policy for hook-derived metrics (issue #69).\n *\n * Off by default, like logs: an upgrade must not start a new stream to a\n * collector nobody sized for it. `enabled` governs the `default` destination\n * (the single-endpoint settings); an `exporter.destinations[]` entry receives\n * metrics when its `signals` list names `metrics`. Metrics carry no content, so\n * listing the signal is the whole opt-in.\n *\n * - `temporality`: `cumulative` (default) exports running totals per series,\n * kept in the state store across hook processes, so a receiver that merges\n * counters by keeping the largest value stays correct. `delta` exports what one\n * callback observed and keeps no state.\n * - `includeSessionId`: put `session.id` on every data point (default true). Turn\n * it off where per-session series are too many for the backend.\n */\nexport const metricsPolicySchema = z.strictObject({\n enabled: z.boolean(),\n /** Full URL. Absent, derived from `endpoint` (`/v1/traces` becomes `/v1/metrics`). */\n endpoint: z.string().url().max(2048).optional(),\n temporality: z.enum([\"cumulative\", \"delta\"]),\n includeSessionId: z.boolean(),\n});\nexport type MetricsPolicy = z.infer<typeof metricsPolicySchema>;\n\nexport const DEFAULT_METRICS_POLICY: MetricsPolicy = Object.freeze({\n enabled: false,\n temporality: \"cumulative\",\n includeSessionId: true,\n});\n\n/**\n * Runtime exporter policy.\n *\n * This describes *where and how* telemetry goes. It deliberately contains no\n * session, invocation, or workspace field: see ADR 0001. Mixing the two would\n * make identity globally reachable through configuration.\n */\nexport const exporterPolicySchema = z.strictObject({\n enabled: z.boolean(),\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]),\n endpoint: z.string().url().max(2048).optional(),\n /**\n * Header names only. Values are supplied separately at construction time and\n * are never part of a resolved-config snapshot, which is logged and exported.\n */\n headerNames: z.array(nonEmptyStringSchema).max(32).readonly(),\n timeoutMillis: z.number().int().min(1).max(600_000),\n maxBatchSize: z.number().int().min(1).max(4096),\n maxQueueSize: z.number().int().min(1).max(65_536),\n maxRetryAttempts: z.number().int().min(0).max(10),\n serviceName: nonEmptyStringSchema,\n serviceNamespace: nonEmptyStringSchema.optional(),\n /**\n * Custom attributes merged into the exported OTLP Resource.\n *\n * Bounded and validated, and refusing `service.name`/`service.namespace`,\n * which are the two fields above. Distinct from an invocation's\n * `consumerAttributes`: this describes the emitting deployment, carries no\n * identity, and is the same for every span this process exports.\n */\n resourceAttributes: resourceAttributesSchema,\n /**\n * The logs signal. Nested under the exporter because it shares the endpoint,\n * headers, timeout, protocol, service identity, and resource attributes above —\n * a second top-level section would invite two of each to drift apart.\n */\n logs: logsPolicySchema,\n /**\n * Hook-derived metrics. Optional so an `ExporterPolicy` built by hand before\n * metrics existed stays valid; absent reads as {@link DEFAULT_METRICS_POLICY}.\n */\n metrics: metricsPolicySchema.optional(),\n /**\n * Additional OTLP destinations, each sent every batch in parallel.\n *\n * Absent (the default), the exporter has exactly one destination — the\n * single-endpoint settings above, named `default` — and behaves exactly as it\n * did before this list existed. See `destinations.ts`.\n *\n * Merged as one leaf: a higher layer that sets the list replaces it whole,\n * because \"the union of two partial lists\" has no answer an operator could\n * predict.\n */\n destinations: exportDestinationsSchema.optional(),\n /**\n * Per-destination retry spool bounds, each optional and merged per leaf; any\n * bound left unset takes its value from `DEFAULT_SPOOL_POLICY`.\n */\n spool: spoolPolicySchema.partial().optional(),\n /**\n * The most time one hook invocation spends trying to reach one endpoint, in\n * milliseconds: caps `timeoutMillis` for every OTLP request (connection setup\n * included) and the exporter's own retries inside it. A batch that does not\n * get through in time is spooled. Default {@link DEFAULT_EXPORT_BUDGET_MILLIS}:\n * the host agent waits for its hooks, so a down collector must not stall it.\n */\n exportBudgetMillis: z.number().int().min(50).max(600_000).optional(),\n /**\n * After an endpoint was unreachable (refused, timed out, or answered a\n * retryable status), every hook spools for it without trying for this long,\n * in milliseconds; then one hook probes it again. 0 disables the window.\n * Default {@link DEFAULT_ENDPOINT_DOWN_MILLIS}.\n */\n endpointDownMillis: z.number().int().min(0).max(3_600_000).optional(),\n});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\n\n/** Default `exporter.exportBudgetMillis`. */\nexport const DEFAULT_EXPORT_BUDGET_MILLIS = 1_500;\n/** Default `exporter.endpointDownMillis`. */\nexport const DEFAULT_ENDPOINT_DOWN_MILLIS = 30_000;\n\n/** The per-request OTLP timeout a hook uses: `timeoutMillis`, capped by the export budget. */\nexport const effectiveExportTimeoutMillis = (exporter: ExporterPolicy): number =>\n Math.min(exporter.timeoutMillis, exporter.exportBudgetMillis ?? DEFAULT_EXPORT_BUDGET_MILLIS);\n\nexport const detectionPolicySchema = z.strictObject({\n /** Detections below this confidence resolve to the unknown provider. */\n minimumConfidence: detectionConfidenceSchema,\n /** When false, an ambiguous detection is an error rather than unknown. */\n allowAmbiguousFallback: z.boolean(),\n /** Optional allow-list of provider ids; empty means \"any registered\". */\n allowedProviderIds: z.array(nonEmptyStringSchema).max(32).readonly(),\n});\nexport type DetectionPolicy = z.infer<typeof detectionPolicySchema>;\n\nexport const diagnosticsPolicySchema = z.strictObject({\n logLevel: z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]),\n /** Emit `error.raised` events for contained failures. */\n emitErrorEvents: z.boolean(),\n});\nexport type DiagnosticsPolicy = z.infer<typeof diagnosticsPolicySchema>;\n\n/**\n * Per-provider behaviour that is not part of an adapter's parse.\n *\n * `claudeCode.readTranscriptUsage` is the one sanctioned exception to \"no\n * transcript reads in the hook\" (docs/claude-code-usage-contract.md, finding 8).\n * When true, the hook runtime — never the adapter — reads the session transcript\n * named by a Claude Code `Stop` / `StopFailure` payload, bounded, and attaches the\n * turn's model and summed token usage before the adapter parses it.\n *\n * `codex.readRolloutUsage` is the same exception for Codex, which puts no token\n * counters on any hook payload: at `Stop` the runtime reads the session's\n * rollout (`transcript_path`) from a per-session cursor, bounded, and attaches\n * the thread's running token total (docs/usage-semantics.md).\n *\n * Both off by default: without them, otel-hook reads no file a hook payload names.\n */\nexport const providersPolicySchema = z.strictObject({\n claudeCode: z\n .strictObject({\n readTranscriptUsage: z.boolean(),\n })\n .optional(),\n codex: z\n .strictObject({\n readRolloutUsage: z.boolean(),\n })\n .optional(),\n});\nexport type ProvidersPolicy = z.infer<typeof providersPolicySchema>;\n\n/**\n * Session context (`docs/session-context.md`): a directory a harness writes one\n * JSON file per agent session into, laid out `<dir>/<agent-tool>/<session-id>.json`.\n * With `dir` set, the hook reads that one file on every event and stamps the\n * attributes of the segment in force on every span, log record and metric point.\n * Absent (the default), nothing is read.\n *\n * Set in the configuration file or with `--session-context-dir`, never through\n * the environment: some agents (Claude Code) strip `OTEL_*` variables from the\n * hook processes they start.\n */\nexport const sessionContextPolicySchema = z.strictObject({\n /** Absolute path of the context directory. */\n dir: z\n .string()\n .min(1)\n .max(4096)\n .refine((value) => isAbsolute(value), { message: \"must be an absolute path\" }),\n});\nexport type SessionContextPolicy = z.infer<typeof sessionContextPolicySchema>;\n\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\n /** Optional so a hand-built configuration from before it existed stays valid. */\n providers: providersPolicySchema.optional(),\n /** Optional: absent means no session context is read. */\n sessionContext: sessionContextPolicySchema.optional(),\n});\nexport type OtelHookConfig = z.infer<typeof otelHookConfigSchema>;\n\n/** Partial overlay accepted from a configuration layer. */\nexport const otelHookConfigPatchSchema = z.strictObject({\n // `logs` is unwrapped and re-partialled for the same reason `privacy.limits` is:\n // merging happens per leaf, so a layer must be able to set `logs.enabled` alone\n // without also restating the endpoint and the batch size.\n exporter: exporterPolicySchema\n .omit({ logs: true, metrics: true, spool: true })\n .partial()\n .extend({\n logs: logsPolicySchema.partial().optional(),\n metrics: metricsPolicySchema.partial().optional(),\n spool: spoolPolicySchema.partial().optional(),\n })\n .optional(),\n privacy: privacyPolicySchema\n .omit({ limits: true })\n .partial()\n .extend({ limits: privacyPolicySchema.shape.limits.partial().optional() })\n .optional(),\n detection: detectionPolicySchema.partial().optional(),\n diagnostics: diagnosticsPolicySchema.partial().optional(),\n providers: z\n .strictObject({\n claudeCode: z.strictObject({ readTranscriptUsage: z.boolean() }).partial().optional(),\n codex: z.strictObject({ readRolloutUsage: z.boolean() }).partial().optional(),\n })\n .partial()\n .optional(),\n sessionContext: sessionContextPolicySchema.partial().optional(),\n});\nexport type OtelHookConfigPatch = z.infer<typeof otelHookConfigPatchSchema>;\n\nexport const DEFAULT_EXPORTER_POLICY: ExporterPolicy = Object.freeze({\n enabled: true,\n protocol: \"http/protobuf\",\n headerNames: Object.freeze([]),\n timeoutMillis: 10_000,\n maxBatchSize: 128,\n maxQueueSize: 2048,\n maxRetryAttempts: 2,\n serviceName: \"coding-agent\",\n resourceAttributes: EMPTY_RESOURCE_ATTRIBUTES,\n logs: DEFAULT_LOGS_POLICY,\n metrics: DEFAULT_METRICS_POLICY,\n});\n\nexport const DEFAULT_DETECTION_POLICY: DetectionPolicy = Object.freeze({\n minimumConfidence: \"strong\",\n allowAmbiguousFallback: true,\n allowedProviderIds: Object.freeze([]),\n});\n\nexport const DEFAULT_DIAGNOSTICS_POLICY: DiagnosticsPolicy = Object.freeze({\n logLevel: \"warn\",\n emitErrorEvents: true,\n});\n\nexport const DEFAULT_PROVIDERS_POLICY: ProvidersPolicy = Object.freeze({\n claudeCode: Object.freeze({ readTranscriptUsage: false }),\n codex: Object.freeze({ readRolloutUsage: false }),\n});\n\nexport const DEFAULT_CONFIG: OtelHookConfig = Object.freeze({\n exporter: DEFAULT_EXPORTER_POLICY,\n privacy: DEFAULT_PRIVACY_POLICY,\n detection: DEFAULT_DETECTION_POLICY,\n diagnostics: DEFAULT_DIAGNOSTICS_POLICY,\n providers: DEFAULT_PROVIDERS_POLICY,\n});\n\n/** Whether the runtime may read Claude Code transcripts at `Stop` (default false). */\nexport const readsClaudeTranscriptUsage = (config: OtelHookConfig): boolean =>\n config.providers?.claudeCode?.readTranscriptUsage === true;\n\n/** Whether the runtime may read Codex rollouts at `Stop` (default false). */\nexport const readsCodexRolloutUsage = (config: OtelHookConfig): boolean =>\n config.providers?.codex?.readRolloutUsage === true;\n\n/** The session context directory in force, or `undefined` when none is configured. */\nexport const sessionContextDir = (config: OtelHookConfig): string | undefined => config.sessionContext?.dir;\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n\n/** The metrics policy in force, defaults filled in. */\nexport const effectiveMetricsPolicy = (exporter: ExporterPolicy): MetricsPolicy => ({\n ...DEFAULT_METRICS_POLICY,\n ...(exporter.metrics ?? {}),\n});\n","import { z } from \"zod\";\n\n/** Maximum length accepted for short identifier-like strings. */\nexport const MAX_IDENTIFIER_LENGTH = 256;\n\n/** Maximum length accepted for a single string attribute value. */\nexport const MAX_ATTRIBUTE_STRING_LENGTH = 4096;\n\n/** Maximum number of entries accepted in an attribute array value. */\nexport const MAX_ATTRIBUTE_ARRAY_LENGTH = 128;\n\nexport const nonEmptyStringSchema = z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\n/** Wall-clock time as whole milliseconds since the Unix epoch. */\nexport const epochMillisSchema = z.number().int().min(0).max(8_640_000_000_000_000);\nexport type EpochMillis = z.infer<typeof epochMillisSchema>;\n\n/** Non-negative duration in milliseconds; may be fractional. */\nexport const durationMillisSchema = z.number().min(0).finite();\n\n/** Token counts are always non-negative integers. */\nexport const tokenCountSchema = z.number().int().min(0);\n\n/** Monotonically increasing per-invocation ordering key. */\nexport const sequenceNumberSchema = z.number().int().min(0);\n\nconst brandedIdSchema = (): z.ZodString => z.string().min(1).max(MAX_IDENTIFIER_LENGTH);\n\nexport const invocationIdSchema = brandedIdSchema().brand<\"InvocationId\">();\nexport type InvocationId = z.infer<typeof invocationIdSchema>;\n\nexport const sessionIdSchema = brandedIdSchema().brand<\"SessionId\">();\nexport type SessionId = z.infer<typeof sessionIdSchema>;\n\nexport const eventIdSchema = brandedIdSchema().brand<\"EventId\">();\nexport type EventId = z.infer<typeof eventIdSchema>;\n\n/**\n * Workspace identifiers are opaque, privacy-safe handles of the form\n * `<scheme>:<token>`. Filesystem paths cannot satisfy this pattern, which keeps\n * home directories and repository paths out of telemetry by construction.\n */\nexport const WORKSPACE_ID_PATTERN = /^[a-z][a-z0-9]{0,15}:[A-Za-z0-9_-]{8,128}$/;\nexport const workspaceIdSchema = z\n .string()\n .regex(WORKSPACE_ID_PATTERN, \"workspace id must be an opaque `<scheme>:<token>` handle\")\n .brand<\"WorkspaceId\">();\nexport type WorkspaceId = z.infer<typeof workspaceIdSchema>;\n\n/** Provider ids are lowercase, hyphenated, and stable across releases. */\nexport const PROVIDER_ID_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\nexport const providerIdSchema = z\n .string()\n .min(1)\n .max(64)\n .regex(PROVIDER_ID_PATTERN, \"provider id must be lowercase and hyphenated\")\n .brand<\"ProviderId\">();\nexport type ProviderId = z.infer<typeof providerIdSchema>;\n\n/** Sentinel used whenever the source provider could not be established. */\nexport const UNKNOWN_PROVIDER_ID = \"unknown\" as const;\nexport type UnknownProviderId = typeof UNKNOWN_PROVIDER_ID;\n\nexport const resolvedProviderIdSchema = z.union([\n providerIdSchema,\n z.literal(UNKNOWN_PROVIDER_ID),\n]);\nexport type ResolvedProviderId = z.infer<typeof resolvedProviderIdSchema>;\n\nexport const isUnknownProvider = (value: ResolvedProviderId): value is UnknownProviderId =>\n value === UNKNOWN_PROVIDER_ID;\n\n/**\n * Attribute values are restricted to OpenTelemetry-compatible primitives.\n *\n * This restriction is a containment boundary, not a convenience: because no\n * nested object can be represented, a raw provider payload cannot be smuggled\n * out of an adapter through attributes or extensions.\n */\nexport const attributePrimitiveSchema = z.union([\n z.string().max(MAX_ATTRIBUTE_STRING_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type AttributePrimitive = z.infer<typeof attributePrimitiveSchema>;\n\nexport const attributeValueSchema = z.union([\n attributePrimitiveSchema,\n z.array(attributePrimitiveSchema).max(MAX_ATTRIBUTE_ARRAY_LENGTH),\n]);\nexport type AttributeValue = z.infer<typeof attributeValueSchema>;\n\nexport const attributesSchema = z.record(z.string().min(1).max(MAX_IDENTIFIER_LENGTH), attributeValueSchema);\nexport type Attributes = z.infer<typeof attributesSchema>;\n\n/** Ordered confidence ladder for provider detection. */\nexport const detectionConfidenceSchema = z.enum([\"none\", \"weak\", \"strong\", \"exact\"]);\nexport type DetectionConfidence = z.infer<typeof detectionConfidenceSchema>;\n\nexport const DETECTION_CONFIDENCE_RANK: Readonly<Record<DetectionConfidence, number>> =\n Object.freeze({\n none: 0,\n weak: 1,\n strong: 2,\n exact: 3,\n });\n\nexport const compareDetectionConfidence = (a: DetectionConfidence, b: DetectionConfidence): number =>\n DETECTION_CONFIDENCE_RANK[a] - DETECTION_CONFIDENCE_RANK[b];\n\n/** How the observed data reached this process. */\nexport const sourceTransportSchema = z.enum([\n \"hook-stdin\",\n \"cli-argument\",\n \"library-call\",\n \"test-fixture\",\n]);\nexport type SourceTransport = z.infer<typeof sourceTransportSchema>;\n","import { z } from \"zod\";\n\nimport type { ContentDisclosure } from \"../model/content.js\";\n\n/**\n * How much content the library is permitted to disclose.\n *\n * `omit` is the default and the only mode that requires no trust in the\n * downstream collector.\n */\nexport const contentModeSchema = z.enum([\"omit\", \"mask\", \"redact\", \"raw\"]);\nexport type ContentMode = z.infer<typeof contentModeSchema>;\n\nexport const CONTENT_MODE_DISCLOSURE: Readonly<Record<ContentMode, ContentDisclosure>> =\n Object.freeze({\n omit: \"omitted\",\n mask: \"masked\",\n redact: \"redacted\",\n raw: \"raw\",\n });\n\n/**\n * Default secret-key patterns, matched case-insensitively against object keys at\n * every depth. A key matching any of these has its value replaced before the\n * value itself is ever inspected.\n */\nexport const DEFAULT_SECRET_KEY_PATTERNS: readonly string[] = Object.freeze([\n \"(^|[._-])(secret|secrets)([._-]|$)\",\n \"(^|[._-])(token|tokens)([._-]|$)\",\n \"(^|[._-])(password|passwd|pwd)([._-]|$)\",\n \"(^|[._-])(credential|credentials)([._-]|$)\",\n \"(^|[._-])(api[._-]?key|apikey|access[._-]?key|secret[._-]?key|private[._-]?key)([._-]|$)\",\n \"(^|[._-])(authorization|auth[._-]?header|bearer)([._-]|$)\",\n \"(^|[._-])(cookie|set[._-]?cookie)([._-]|$)\",\n \"(^|[._-])(signature|sig)([._-]|$)\",\n]);\n\n/**\n * Default secret-value patterns applied to disclosed text in `redact` mode.\n * These are heuristics; they reduce accidental disclosure but are not a\n * substitute for `omit`.\n */\nexport const DEFAULT_SECRET_VALUE_PATTERNS: readonly string[] = Object.freeze([\n \"AKIA[0-9A-Z]{16}\",\n \"sk-[A-Za-z0-9_-]{16,}\",\n \"gh[pousr]_[A-Za-z0-9]{16,}\",\n \"xox[abprs]-[A-Za-z0-9-]{10,}\",\n \"-----BEGIN[A-Z ]*PRIVATE KEY-----\",\n \"eyJ[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\\\\.[A-Za-z0-9_-]{10,}\",\n \"(?:Bearer|Basic)\\\\s+[A-Za-z0-9._~+/=-]{12,}\",\n]);\n\nexport const privacyLimitsSchema = z.strictObject({\n /** Maximum characters of disclosed text per content fact or string value. */\n maxStringLength: z.number().int().min(0).max(65_536),\n /** Maximum nesting depth walked when sanitizing structured values. */\n maxDepth: z.number().int().min(1).max(32),\n /** Maximum array entries retained when sanitizing structured values. */\n maxArrayLength: z.number().int().min(1).max(4096),\n /** Maximum canonical events emitted per invocation. */\n maxEventsPerInvocation: z.number().int().min(1).max(10_000),\n /** Maximum object keys retained per level when sanitizing. */\n maxObjectKeys: z.number().int().min(1).max(1024),\n});\nexport type PrivacyLimits = z.infer<typeof privacyLimitsSchema>;\n\nexport const privacyPolicySchema = z.strictObject({\n contentMode: contentModeSchema,\n /**\n * `raw` mode is refused unless this is also true, so a single mistyped\n * environment variable cannot start exporting prompts.\n */\n allowRawContent: z.boolean(),\n /**\n * Salt mixed into every hash. A per-deployment salt makes hashes\n * non-correlatable across deployments; an empty salt makes them globally\n * comparable. Both are legitimate; the choice is explicit.\n */\n hashSalt: z.string().max(256),\n maskCharacter: z.string().length(1),\n redactionPlaceholder: z.string().min(1).max(64),\n secretKeyPatterns: z.array(z.string().min(1)).max(128).readonly(),\n secretValuePatterns: z.array(z.string().min(1)).max(128).readonly(),\n limits: privacyLimitsSchema,\n});\nexport type PrivacyPolicy = z.infer<typeof privacyPolicySchema>;\n\nexport const DEFAULT_PRIVACY_LIMITS: PrivacyLimits = Object.freeze({\n maxStringLength: 1024,\n maxDepth: 6,\n maxArrayLength: 64,\n maxEventsPerInvocation: 512,\n maxObjectKeys: 128,\n});\n\nexport const DEFAULT_PRIVACY_POLICY: PrivacyPolicy = Object.freeze({\n contentMode: \"omit\",\n allowRawContent: false,\n hashSalt: \"\",\n maskCharacter: \"*\",\n redactionPlaceholder: \"[redacted]\",\n secretKeyPatterns: DEFAULT_SECRET_KEY_PATTERNS,\n secretValuePatterns: DEFAULT_SECRET_VALUE_PATTERNS,\n limits: DEFAULT_PRIVACY_LIMITS,\n});\n\nexport type PolicyResolution = {\n readonly policy: PrivacyPolicy;\n /** Non-sensitive notes about deterministic downgrades that were applied. */\n readonly notes: readonly string[];\n};\n\n/**\n * Validate a policy and apply the one deterministic downgrade the library\n * enforces: `raw` without `allowRawContent` becomes `omit`.\n */\nexport const resolvePrivacyPolicy = (policy: PrivacyPolicy): PolicyResolution => {\n const parsed = privacyPolicySchema.parse(policy);\n if (parsed.contentMode === \"raw\" && !parsed.allowRawContent) {\n return {\n policy: { ...parsed, contentMode: \"omit\" },\n notes: [\"contentMode=raw downgraded to omit because allowRawContent is false\"],\n };\n }\n return { policy: parsed, notes: [] };\n};\n","import { z } from \"zod\";\n\nimport { contentModeSchema, type ContentMode } from \"../privacy/policy.js\";\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\nimport { MAX_OTLP_HEADERS } from \"./otlp-headers.js\";\nimport { MAX_REPOSITORY_REFERENCE_LENGTH, normalizeRepositoryKey } from \"./repository-key.js\";\nimport type { ExporterPolicy } from \"./schema.js\";\n\n/**\n * Export destinations: one batch, several OTLP endpoints.\n *\n * otel-hook is not a long-running process, so it cannot sit behind a proxy that\n * fans out for it. Instead every enabled destination is sent the same batch by the\n * same short-lived process, and what a destination could not take is kept in that\n * destination's own spool for the next invocation.\n *\n * ## The `default` destination\n *\n * The single-endpoint settings that predate this list — `exporter.endpoint`,\n * `exporter.logs.endpoint`, `exporter.protocol`, `--header`, and the standard\n * `OTEL_EXPORTER_OTLP_*` variables that feed them — describe one destination\n * named `default`. The name is therefore reserved: a `destinations[]` entry may\n * not take it, so there is exactly one place that destination is configured.\n *\n * A configuration with no `destinations` resolves to that one destination and\n * nothing else, exactly as before the list existed.\n */\n\nexport const DEFAULT_DESTINATION_NAME = \"default\";\n\n/**\n * Destination names become directory names (each destination spools on its own),\n * so they are held to a lowercase, filesystem-safe vocabulary rather than being\n * sanitized into something an operator would not recognize.\n */\nexport const DESTINATION_NAME_PATTERN = /^[a-z0-9][a-z0-9_-]{0,62}$/;\n\nexport const MAX_EXPORT_DESTINATIONS = 16;\n/** The same bound `OTEL_EXPORTER_OTLP_*HEADERS` and `exporter.headerNames` have. */\nexport const MAX_DESTINATION_HEADERS = MAX_OTLP_HEADERS;\n\n/** Prefix of a header value that names an environment variable instead of holding a value. */\nexport const HEADER_ENV_REFERENCE_PREFIX = \"env:\";\n\n/** RFC 9110 `token`: the characters a header field name may use. */\nconst HEADER_NAME_PATTERN = /^[A-Za-z0-9!#$%&'*+.^_`|~-]{1,128}$/;\nconst ENV_VARIABLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]{0,127}$/;\nconst MAX_HEADER_VALUE_LENGTH = 8_192;\n\nexport const exportSignalSchema = z.enum([\"traces\", \"logs\", \"metrics\"]);\nexport type ExportSignal = z.infer<typeof exportSignalSchema>;\n\nconst headerValueSchema = z\n .string()\n .min(1)\n .max(MAX_HEADER_VALUE_LENGTH)\n // The rule `OTEL_EXPORTER_OTLP_*HEADERS` values are held to: a line break is a\n // request-splitting vector, and other controls or non-Latin-1 characters would\n // only make Node's HTTP client throw at send time.\n .refine(\n (value) => !isUnsafeHeaderValue(value),\n \"header values may not contain line breaks, control characters, or characters beyond Latin-1\",\n )\n .refine(\n (value) =>\n !value.startsWith(HEADER_ENV_REFERENCE_PREFIX) ||\n ENV_VARIABLE_NAME_PATTERN.test(value.slice(HEADER_ENV_REFERENCE_PREFIX.length)),\n \"an env: header reference must name an environment variable, e.g. env:COLLECTOR_TOKEN\",\n );\n\nconst endpointSchema = z.string().url().max(2048);\n\nexport const MAX_DESTINATION_SCOPES = 64;\nexport const MAX_SCOPE_REPOSITORIES = 256;\n\n/** Every repository, as a scope's `repositories`. */\nexport const ALL_REPOSITORIES = \"*\";\n\nconst repositoryReferenceSchema = z\n .string()\n .min(1)\n .max(MAX_REPOSITORY_REFERENCE_LENGTH)\n .refine(\n (value) => normalizeRepositoryKey(value) !== undefined,\n \"not a repository URL: use https://host/owner/repo, git@host:owner/repo.git, or host/owner/repo\",\n );\n\n/**\n * What one destination receives for a set of repositories.\n *\n * A scope can only *restrict* what the destination would otherwise get: its\n * signals are intersected with the destination's, its content mode can only\n * lower the disclosure the installation's `privacy.contentMode` produced, and\n * `includeSessionId: false` only removes `session.id` from metric points.\n */\nexport const destinationScopeSchema = z.strictObject({\n /**\n * Repository URLs (any spelling of the remote; compared by host and path,\n * case-insensitively, without `.git`), or `\"*\"` for every record that names\n * a repository. A record that names none never matches a scope.\n */\n repositories: z.union([\n z.literal(ALL_REPOSITORIES),\n z.array(repositoryReferenceSchema).min(1).max(MAX_SCOPE_REPOSITORIES).readonly(),\n ]),\n /** Signals sent for these repositories. Default: every signal the destination takes. */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n /** Content disclosure for these repositories, never above `privacy.contentMode`. Default: unchanged. */\n contentMode: contentModeSchema.optional(),\n /** False leaves `session.id` off metric data points for these repositories. Default true. */\n includeSessionId: z.boolean().optional(),\n});\nexport type DestinationScopeConfig = z.infer<typeof destinationScopeSchema>;\n\nexport const exportDestinationSchema = z\n .strictObject({\n /** Unique, lowercase, filesystem-safe. `default` is reserved for the single-endpoint settings. */\n name: z\n .string()\n .regex(DESTINATION_NAME_PATTERN, \"destination names are lowercase letters, digits, _ and -\"),\n /** Default true. A disabled destination is neither sent to nor drained. */\n enabled: z.boolean().optional(),\n /**\n * Traces URL, with the same meaning as `exporter.endpoint`: the logs URL is\n * derived from it (`/v1/traces` becomes `/v1/logs`) unless `logsEndpoint` is set.\n */\n endpoint: endpointSchema.optional(),\n /** Per-signal override of `endpoint` for traces. */\n tracesEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived logs URL. */\n logsEndpoint: endpointSchema.optional(),\n /** Per-signal override of the derived metrics URL (`/v1/traces` becomes `/v1/metrics`). */\n metricsEndpoint: endpointSchema.optional(),\n /** Defaults to `exporter.protocol`. */\n protocol: z.enum([\"http/protobuf\", \"http/json\", \"none\"]).optional(),\n /**\n * Header name to value. A value of the form `env:NAME` is read from that\n * environment variable at send time, so a credential never has to be written\n * into the file. Values never appear in a snapshot, a diagnostic, or `doctor`.\n */\n headers: z\n .record(z.string().regex(HEADER_NAME_PATTERN, \"not a valid header name\"), headerValueSchema)\n .refine(\n (headers) => Object.keys(headers).length <= MAX_DESTINATION_HEADERS,\n `at most ${String(MAX_DESTINATION_HEADERS)} headers per destination`,\n )\n .optional(),\n /**\n * Which signals this destination receives. Default: traces and logs. The logs\n * signal is still governed by `exporter.logs.enabled`, which stays the one\n * opt-in for content-bearing records leaving the host. `metrics` is never on by\n * default: a destination receives hook-derived metrics only when it lists them.\n */\n signals: z.array(exportSignalSchema).min(1).max(3).readonly().optional(),\n /**\n * Per-repository filter. Absent: every record goes to this destination, as\n * before scopes existed. Present: a record goes only when its repository\n * (`vcs.repository.url.full`) matches a scope — the first matching scope\n * decides its signals, content mode, and session id — and a record that\n * names no repository is not sent here at all.\n */\n scopes: z.array(destinationScopeSchema).min(1).max(MAX_DESTINATION_SCOPES).readonly().optional(),\n })\n .refine(\n (destination) =>\n destination.endpoint !== undefined ||\n destination.tracesEndpoint !== undefined ||\n destination.logsEndpoint !== undefined ||\n destination.metricsEndpoint !== undefined,\n \"a destination needs an endpoint, or a tracesEndpoint / logsEndpoint / metricsEndpoint\",\n );\nexport type ExportDestinationConfig = z.infer<typeof exportDestinationSchema>;\n\n/** Signals a destination receives when it does not list any: never metrics. */\nexport const DEFAULT_DESTINATION_SIGNALS: readonly ExportSignal[] = Object.freeze([\"traces\", \"logs\"]);\n\nexport const exportDestinationsSchema = z\n .array(exportDestinationSchema)\n .max(MAX_EXPORT_DESTINATIONS)\n .readonly()\n .superRefine((destinations, context) => {\n const seen = new Set<string>();\n destinations.forEach((destination, index) => {\n if (destination.name === DEFAULT_DESTINATION_NAME) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message:\n 'the name \"default\" is reserved for exporter.endpoint and the OTEL_EXPORTER_OTLP_* variables',\n });\n }\n if (seen.has(destination.name)) {\n context.addIssue({\n code: \"custom\",\n path: [index, \"name\"],\n message: `duplicate destination name \"${destination.name}\"`,\n });\n }\n seen.add(destination.name);\n });\n });\n\n/**\n * Bounds on each destination's retry spool, per signal.\n *\n * Every destination spools independently, so one long outage can only ever cost\n * its own budget. When a bound is reached the *oldest* batches are dropped first —\n * a recent batch is the one a reader is still likely to look for — and every drop\n * is counted on disk so `doctor` can report it.\n */\nexport const spoolPolicySchema = z.strictObject({\n /** Total bytes of queued batches. Default 16 MiB. */\n maxBytes: z.number().int().min(1_024).max(1_073_741_824),\n /** A batch older than this is dropped instead of sent. Default 72 hours. */\n maxAgeMillis: z.number().int().min(1_000).max(30 * 24 * 60 * 60 * 1000),\n /** Number of queued batches. Default 500. */\n maxBatches: z.number().int().min(1).max(65_536),\n});\nexport type SpoolPolicy = z.infer<typeof spoolPolicySchema>;\n\nexport const DEFAULT_SPOOL_POLICY: SpoolPolicy = Object.freeze({\n maxBytes: 16 * 1024 * 1024,\n maxAgeMillis: 72 * 60 * 60 * 1000,\n maxBatches: 500,\n});\n\n/** The spool policy in force, with defaults filled in for any bound left unset. */\nexport const effectiveSpoolPolicy = (exporter: ExporterPolicy): SpoolPolicy => ({\n maxBytes: exporter.spool?.maxBytes ?? DEFAULT_SPOOL_POLICY.maxBytes,\n maxAgeMillis: exporter.spool?.maxAgeMillis ?? DEFAULT_SPOOL_POLICY.maxAgeMillis,\n maxBatches: exporter.spool?.maxBatches ?? DEFAULT_SPOOL_POLICY.maxBatches,\n});\n\n/**\n * One destination as the runtime sends to it.\n *\n * `headers` holds what the configuration holds — literal values and `env:`\n * references, unresolved. Resolution against an environment happens only at the\n * point of sending ({@link resolveDestinationHeaders}), and the `default`\n * destination's header values never pass through configuration at all: they are\n * handed to the runtime separately, as they always have been.\n */\nexport type ExportDestination = {\n readonly name: string;\n /** `exporter` for the `default` destination, `destinations` for a list entry. */\n readonly source: \"exporter\" | \"destinations\";\n readonly protocol: ExporterPolicy[\"protocol\"];\n /** Traces URL as configured; for `default` this is `exporter.endpoint`. */\n readonly endpoint?: string;\n readonly tracesEndpoint?: string;\n readonly logsEndpoint?: string;\n readonly metricsEndpoint?: string;\n readonly signals: { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n readonly headers: Readonly<Record<string, string>>;\n /** Per-repository filter; absent sends every record (see {@link destinationScopeSchema}). */\n readonly scopes?: readonly DestinationScope[];\n};\n\n/** Signal flags, as a destination or a scope holds them. */\nexport type SignalFlags = { readonly traces: boolean; readonly logs: boolean; readonly metrics: boolean };\n\n/** One scope as the runtime applies it: keys normalized, signals already intersected. */\nexport type DestinationScope = {\n /** Normalized repository keys, or every repository. */\n readonly repositories: typeof ALL_REPOSITORIES | ReadonlySet<string>;\n readonly signals: SignalFlags;\n readonly contentMode?: ContentMode;\n readonly includeSessionId: boolean;\n};\n\n/** Resolve configured scopes against the destination's own signals. */\nexport const resolveDestinationScopes = (\n scopes: readonly DestinationScopeConfig[],\n destinationSignals: SignalFlags,\n): readonly DestinationScope[] =>\n scopes.map((scope) => {\n const listed: readonly ExportSignal[] = scope.signals ?? exportSignalSchema.options;\n return {\n repositories:\n scope.repositories === ALL_REPOSITORIES\n ? ALL_REPOSITORIES\n : new Set(\n scope.repositories.flatMap((reference) => {\n const key = normalizeRepositoryKey(reference);\n return key === undefined ? [] : [key];\n }),\n ),\n signals: {\n traces: destinationSignals.traces && listed.includes(\"traces\"),\n logs: destinationSignals.logs && listed.includes(\"logs\"),\n metrics: destinationSignals.metrics && listed.includes(\"metrics\"),\n },\n ...(scope.contentMode === undefined ? {} : { contentMode: scope.contentMode }),\n includeSessionId: scope.includeSessionId ?? true,\n };\n });\n\n/**\n * The scope a repository key falls in: the first that lists it (or lists `*`).\n * `undefined` — not sent — for a record with no repository key, or one no scope lists.\n */\nexport const matchDestinationScope = (\n scopes: readonly DestinationScope[],\n repositoryKey: string | undefined,\n): DestinationScope | undefined => {\n if (repositoryKey === undefined) {\n return undefined;\n }\n return scopes.find(\n (scope) => scope.repositories === ALL_REPOSITORIES || scope.repositories.has(repositoryKey),\n );\n};\n\nconst legacyDestination = (exporter: ExporterPolicy): ExportDestination => ({\n name: DEFAULT_DESTINATION_NAME,\n source: \"exporter\",\n protocol: exporter.protocol,\n ...(exporter.endpoint === undefined ? {} : { endpoint: exporter.endpoint }),\n ...(exporter.logs.endpoint === undefined ? {} : { logsEndpoint: exporter.logs.endpoint }),\n ...(exporter.metrics?.endpoint === undefined ? {} : { metricsEndpoint: exporter.metrics.endpoint }),\n signals: { traces: true, logs: exporter.logs.enabled, metrics: exporter.metrics?.enabled === true },\n headers: {},\n});\n\n/** Whether a configuration uses the destination list at all. */\nexport const hasConfiguredDestinations = (exporter: ExporterPolicy): boolean =>\n exporter.destinations !== undefined && exporter.destinations.length > 0;\n\n/**\n * The destinations an exporter policy sends to, in a stable order: `default`\n * first when present, then the list in file order.\n *\n * - No `destinations`: exactly one `default` destination, even when it has no\n * endpoint — the sink then reports itself unconfigured, as it always has.\n * - With `destinations`: `default` is included only when a single-endpoint setting\n * actually names an endpoint, and disabled entries are left out.\n */\nexport const resolveExportDestinations = (\n exporter: ExporterPolicy,\n): readonly ExportDestination[] => {\n if (!hasConfiguredDestinations(exporter)) {\n return [legacyDestination(exporter)];\n }\n const resolved: ExportDestination[] = [];\n if (\n exporter.endpoint !== undefined ||\n exporter.logs.endpoint !== undefined ||\n exporter.metrics?.endpoint !== undefined\n ) {\n resolved.push(legacyDestination(exporter));\n }\n for (const destination of exporter.destinations ?? []) {\n if (destination.enabled === false) {\n continue;\n }\n const signals: readonly ExportSignal[] = destination.signals ?? DEFAULT_DESTINATION_SIGNALS;\n const flags: SignalFlags = {\n traces: signals.includes(\"traces\"),\n logs: exporter.logs.enabled && signals.includes(\"logs\"),\n metrics: signals.includes(\"metrics\"),\n };\n resolved.push({\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n ...(destination.tracesEndpoint === undefined\n ? {}\n : { tracesEndpoint: destination.tracesEndpoint }),\n ...(destination.logsEndpoint === undefined ? {} : { logsEndpoint: destination.logsEndpoint }),\n ...(destination.metricsEndpoint === undefined\n ? {}\n : { metricsEndpoint: destination.metricsEndpoint }),\n signals: flags,\n headers: { ...(destination.headers ?? {}) },\n ...(destination.scopes === undefined\n ? {}\n : { scopes: resolveDestinationScopes(destination.scopes, flags) }),\n });\n }\n return resolved;\n};\n\n/** A header value's meaning, without its content. */\nexport type HeaderValueReference =\n | { readonly kind: \"literal\" }\n | { readonly kind: \"env\"; readonly variable: string };\n\nexport const parseHeaderValueReference = (value: string): HeaderValueReference =>\n value.startsWith(HEADER_ENV_REFERENCE_PREFIX)\n ? { kind: \"env\", variable: value.slice(HEADER_ENV_REFERENCE_PREFIX.length) }\n : { kind: \"literal\" };\n\nexport type ResolvedDestinationHeaders = {\n /** Header values ready to send. Never logged, never reported. */\n readonly values: Readonly<Record<string, string>>;\n /** Names of referenced environment variables that are unset or empty. */\n readonly missingVariables: readonly string[];\n};\n\n/**\n * Resolve `env:` references against an explicitly supplied environment.\n *\n * Pure: the process environment is never read implicitly. An unset or empty\n * variable is reported by *name* — the only part of a reference that is safe to\n * say out loud — and its header is left out of `values`.\n */\nexport const resolveDestinationHeaders = (\n headers: Readonly<Record<string, string>>,\n environment: Readonly<Record<string, string | undefined>> | undefined,\n): ResolvedDestinationHeaders => {\n const values: Record<string, string> = {};\n const missing: string[] = [];\n for (const [name, value] of Object.entries(headers)) {\n const reference = parseHeaderValueReference(value);\n if (reference.kind === \"literal\") {\n values[name] = value;\n continue;\n }\n const resolved = environment?.[reference.variable];\n if (resolved === undefined || resolved === \"\") {\n missing.push(reference.variable);\n continue;\n }\n values[name] = resolved;\n }\n return { values, missingVariables: [...new Set(missing)].sort() };\n};\n\n/**\n * Attribute-safe description of one destination: names, origins, and variable\n * names. Never a header value, and never an endpoint beyond its origin.\n */\nexport type DestinationDescription = {\n readonly name: string;\n readonly enabled: boolean;\n readonly protocol: ExporterPolicy[\"protocol\"];\n readonly signals: readonly ExportSignal[];\n readonly tracesEndpointOrigin?: string;\n readonly logsEndpointOrigin?: string;\n readonly metricsEndpointOrigin?: string;\n readonly headerNames: readonly string[];\n /** Environment variables this destination's headers reference. */\n readonly headerVariables: readonly string[];\n /** Per-repository filter, as configured (repositories normalized); absent when unscoped. */\n readonly scopes?: readonly DestinationScopeDescription[];\n};\n\nexport type DestinationScopeDescription = {\n readonly repositories: typeof ALL_REPOSITORIES | readonly string[];\n readonly signals: readonly ExportSignal[];\n readonly contentMode?: ContentMode;\n readonly includeSessionId: boolean;\n};\n\nconst describeScope = (scope: DestinationScope): DestinationScopeDescription => ({\n repositories:\n scope.repositories === ALL_REPOSITORIES ? ALL_REPOSITORIES : [...scope.repositories].sort(),\n signals: exportSignalSchema.options.filter((signal) => scope.signals[signal]),\n ...(scope.contentMode === undefined ? {} : { contentMode: scope.contentMode }),\n includeSessionId: scope.includeSessionId,\n});\n\nexport const endpointOrigin = (endpoint: string | undefined): string | undefined => {\n if (endpoint === undefined) {\n return undefined;\n }\n try {\n return new URL(endpoint).origin;\n } catch {\n return \"<unparsable>\";\n }\n};\n\n/** Every configured destination, disabled ones included, for `doctor` and snapshots. */\nexport const describeExportDestinations = (\n exporter: ExporterPolicy,\n): readonly DestinationDescription[] => {\n const describe = (\n destination: ExportDestination,\n enabled: boolean,\n ): DestinationDescription => {\n const tracesOrigin = endpointOrigin(destination.tracesEndpoint ?? destination.endpoint);\n const logsOrigin = endpointOrigin(\n destination.logsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const metricsOrigin = endpointOrigin(\n destination.metricsEndpoint ?? destination.endpoint ?? destination.tracesEndpoint,\n );\n const variables = Object.values(destination.headers)\n .map(parseHeaderValueReference)\n .flatMap((reference) => (reference.kind === \"env\" ? [reference.variable] : []));\n return {\n name: destination.name,\n enabled,\n protocol: destination.protocol,\n signals: exportSignalSchema.options.filter((signal) => destination.signals[signal]),\n ...(tracesOrigin === undefined || !destination.signals.traces\n ? {}\n : { tracesEndpointOrigin: tracesOrigin }),\n ...(logsOrigin === undefined || !destination.signals.logs\n ? {}\n : { logsEndpointOrigin: logsOrigin }),\n ...(metricsOrigin === undefined || !destination.signals.metrics\n ? {}\n : { metricsEndpointOrigin: metricsOrigin }),\n headerNames:\n destination.source === \"exporter\"\n ? [...exporter.headerNames].sort()\n : Object.keys(destination.headers).sort(),\n headerVariables: [...new Set(variables)].sort(),\n ...(destination.scopes === undefined ? {} : { scopes: destination.scopes.map(describeScope) }),\n };\n };\n const enabled = resolveExportDestinations(exporter).map((destination) =>\n describe(destination, true),\n );\n const disabled = (exporter.destinations ?? [])\n .filter((destination) => destination.enabled === false)\n .map((destination) =>\n describe(\n {\n name: destination.name,\n source: \"destinations\",\n protocol: destination.protocol ?? exporter.protocol,\n ...(destination.endpoint === undefined ? {} : { endpoint: destination.endpoint }),\n signals: { traces: false, logs: false, metrics: false },\n headers: { ...(destination.headers ?? {}) },\n ...(destination.scopes === undefined\n ? {}\n : {\n scopes: resolveDestinationScopes(destination.scopes, {\n traces: true,\n logs: true,\n metrics: true,\n }),\n }),\n },\n false,\n ),\n );\n return [...enabled, ...disabled];\n};\n","/**\n * Internal: shared by `OTEL_EXPORTER_OTLP_*HEADERS` parsing and the\n * `exporter.destinations[].headers` schema. Not re-exported from the package.\n */\n\n/**\n * Characters an HTTP field value must not contain once decoded. CR and LF would\n * split the request; the other controls and anything beyond Latin-1 are refused\n * by Node's HTTP client anyway, and refusing them here turns a failed export into\n * a reported, skipped entry.\n */\nexport const isUnsafeHeaderValue = (value: string): boolean =>\n [...value].some((char) => {\n const code = char.codePointAt(0) ?? 0;\n return (code < 0x20 && code !== 0x09) || code === 0x7f || code > 0xff;\n });\n","/**\n * The standard OTLP exporter header variables.\n *\n * `OTEL_EXPORTER_OTLP_HEADERS` applies to every signal;\n * `OTEL_EXPORTER_OTLP_TRACES_HEADERS` and `OTEL_EXPORTER_OTLP_LOGS_HEADERS`\n * apply to one signal each. They exist so a credential (`authorization=Basic …`)\n * can reach the exporter without being written on a command line, where `ps` and\n * `/proc/<pid>/cmdline` would show it to every local user.\n *\n * Header *values* never enter configuration. Parsing returns them to the caller,\n * which hands them straight to the sink at construction; configuration carries\n * header *names* only (`exporter.headerNames`), because a resolved-config\n * snapshot is logged and exported. Every diagnostic here names an entry by its\n * position and the variable by its name — never a key, never a value — because a\n * malformed entry may be the secret itself (`Basic abc` with no `=`).\n */\n\nimport { isUnsafeHeaderValue } from \"./header-value.js\";\n\n/** Upper bound on headers per variable, matching `exporter.headerNames`. */\nexport const MAX_OTLP_HEADERS = 32;\n\nexport const OTLP_HEADER_VARIABLES = Object.freeze({\n generic: \"OTEL_EXPORTER_OTLP_HEADERS\",\n traces: \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n logs: \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n});\n\n/** RFC 9110 `token`: the characters an HTTP field name may contain. */\nconst HEADER_NAME_PATTERN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n\nexport type ParsedOtlpHeaders = {\n readonly headers: Readonly<Record<string, string>>;\n /** Position-only explanations; never a key or a value. */\n readonly warnings: readonly string[];\n};\n\nconst decode = (raw: string): string | undefined => {\n try {\n return decodeURIComponent(raw);\n } catch {\n return undefined;\n }\n};\n\n/**\n * Parse one `OTEL_EXPORTER_OTLP_*HEADERS` value.\n *\n * The OpenTelemetry exporter specification defines the format as W3C\n * Baggage-like: comma-separated `key=value` pairs, surrounding whitespace\n * trimmed, keys and values percent-decoded. So `authorization=Basic%20abc` is\n * the header `authorization: Basic abc`, and a `,` inside a value must be\n * written `%2C`. A malformed entry is skipped and reported; the rest of the\n * variable still applies. A repeated key takes its last value.\n */\nexport const parseOtlpHeadersValue = (raw: string): ParsedOtlpHeaders => {\n const headers: Record<string, string> = {};\n const warnings: string[] = [];\n let overflowed = false;\n\n for (const [index, rawEntry] of raw.split(\",\").entries()) {\n const position = String(index + 1);\n const entry = rawEntry.trim();\n if (entry === \"\") {\n continue;\n }\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${position} is not a key=value pair; ignored`);\n continue;\n }\n const key = decode(entry.slice(0, equals).trim());\n // Split on the first `=` only: a base64 credential ends in `=` padding.\n const value = decode(entry.slice(equals + 1).trim());\n if (key === undefined || value === undefined) {\n warnings.push(`entry ${position} has malformed percent-encoding; ignored`);\n continue;\n }\n const name = key.trim();\n const trimmedValue = value.trim();\n if (!HEADER_NAME_PATTERN.test(name)) {\n warnings.push(`entry ${position} does not name a valid HTTP header; ignored`);\n continue;\n }\n if (trimmedValue === \"\") {\n warnings.push(`entry ${position} has an empty value; ignored`);\n continue;\n }\n if (isUnsafeHeaderValue(trimmedValue)) {\n warnings.push(`entry ${position} has a character not allowed in an HTTP header value; ignored`);\n continue;\n }\n const existing = findHeaderName(headers, name);\n if (existing === undefined && Object.keys(headers).length >= MAX_OTLP_HEADERS) {\n overflowed = true;\n continue;\n }\n if (existing !== undefined) {\n delete headers[existing];\n }\n headers[name] = trimmedValue;\n }\n\n if (overflowed) {\n warnings.push(`more than ${String(MAX_OTLP_HEADERS)} headers were supplied; the excess was ignored`);\n }\n return { headers, warnings };\n};\n\n/** HTTP field names are case-insensitive: `Authorization` and `authorization` are one header. */\nconst findHeaderName = (headers: Readonly<Record<string, string>>, name: string): string | undefined => {\n const lower = name.toLowerCase();\n return Object.keys(headers).find((candidate) => candidate.toLowerCase() === lower);\n};\n\n/**\n * Overlay header maps, lowest precedence first, per header name.\n *\n * A higher source replaces only the names it sets (case-insensitively), so a\n * signal-specific variable can override `authorization` while a generic tenant\n * header still applies — the same per-key merge the OpenTelemetry SDKs apply.\n */\nexport const mergeOtlpHeaders = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): Readonly<Record<string, string>> => {\n const merged: Record<string, string> = {};\n for (const source of sources) {\n for (const [name, value] of Object.entries(source)) {\n const existing = findHeaderName(merged, name);\n if (existing !== undefined) {\n delete merged[existing];\n }\n merged[name] = value;\n }\n }\n return merged;\n};\n\nexport type ResolvedOtlpHeaders = {\n /** Headers for the traces exporter. */\n readonly traces: Readonly<Record<string, string>>;\n /** Headers for the logs exporter. */\n readonly logs: Readonly<Record<string, string>>;\n /** Variable-qualified, value-free explanations of skipped entries. */\n readonly warnings: readonly { readonly variable: string; readonly detail: string }[];\n};\n\n/**\n * Resolve exporter headers per signal.\n *\n * Precedence, per header name, highest first:\n *\n * ```\n * explicit headers (--header) > OTEL_EXPORTER_OTLP_{TRACES,LOGS}_HEADERS > OTEL_EXPORTER_OTLP_HEADERS\n * ```\n *\n * Pure: the environment is passed in, never read from `process.env`.\n */\nexport const resolveOtlpHeaders = (\n env: Readonly<Record<string, string | undefined>>,\n explicit: Readonly<Record<string, string>> = {},\n): ResolvedOtlpHeaders => {\n const warnings: { variable: string; detail: string }[] = [];\n const read = (variable: string): Readonly<Record<string, string>> => {\n const raw = env[variable];\n if (raw === undefined || raw.trim() === \"\") {\n return {};\n }\n const parsed = parseOtlpHeadersValue(raw);\n for (const detail of parsed.warnings) {\n warnings.push({ variable, detail });\n }\n return parsed.headers;\n };\n const generic = read(OTLP_HEADER_VARIABLES.generic);\n const traces = read(OTLP_HEADER_VARIABLES.traces);\n const logs = read(OTLP_HEADER_VARIABLES.logs);\n return {\n traces: mergeOtlpHeaders(generic, traces, explicit),\n logs: mergeOtlpHeaders(generic, logs, explicit),\n warnings,\n };\n};\n\n/**\n * Header names, deduplicated case-insensitively (first spelling kept), sorted\n * and bounded — the only part of a header that may enter configuration or a\n * diagnostic.\n */\nexport const unionOtlpHeaderNames = (...lists: readonly (readonly string[])[]): readonly string[] => {\n const names: string[] = [];\n const seen = new Set<string>();\n for (const name of lists.flat()) {\n if (!seen.has(name.toLowerCase())) {\n seen.add(name.toLowerCase());\n names.push(name);\n }\n }\n return names.sort().slice(0, MAX_OTLP_HEADERS);\n};\n\n/** {@link unionOtlpHeaderNames} over the names of header maps. */\nexport const describeOtlpHeaderNames = (\n ...sources: readonly Readonly<Record<string, string>>[]\n): readonly string[] => unionOtlpHeaderNames(...sources.map((source) => Object.keys(source)));\n","/**\n * Repository keys: how a destination scope names a repository, and how a record's\n * `vcs.repository.url.full` is compared against it.\n *\n * A key is the repository URL's host and path, lowercased, without scheme,\n * credentials, port, trailing slash, or `.git` suffix — `github.com/acme/widget`.\n * The same remote spelled as HTTPS, `git@host:path` or `ssh://` gives the same\n * key, so a scope written from `git remote get-url origin` matches a record\n * stamped with the browse URL and the other way around.\n *\n * Pure: no I/O, never throws.\n */\n\n/** OpenTelemetry VCS attribute a record's repository is read from. */\nexport const ATTR_VCS_REPOSITORY_URL_FULL = \"vcs.repository.url.full\";\n\n/** Longest repository reference accepted, in a scope or on a record. */\nexport const MAX_REPOSITORY_REFERENCE_LENGTH = 2048;\n\nconst SCHEME_PATTERN = /^[a-z][a-z0-9+.-]*:\\/\\//i;\n/** `user@host:path` (scp-like git syntax), never `C:\\...` or `host:port/...`. */\nconst SCP_LIKE_PATTERN = /^(?:[^@/\\s]+@)?([^:/\\s]+):(?!\\/\\/)(.+)$/;\n\n/** Drops trailing `/` with a linear scan (`/\\/+$/` backtracks quadratically). */\nconst trimTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) end -= 1;\n return value.slice(0, end);\n};\n\nconst keyOf = (host: string, pathname: string): string | undefined => {\n const withoutSlashes = trimTrailingSlashes(pathname);\n const cleanedPath = trimTrailingSlashes(\n withoutSlashes.toLowerCase().endsWith(\".git\") ? withoutSlashes.slice(0, -4) : withoutSlashes,\n );\n if (host.length === 0 || cleanedPath.length === 0 || cleanedPath === \"/\") {\n return undefined;\n }\n const withSlash = cleanedPath.startsWith(\"/\") ? cleanedPath : `/${cleanedPath}`;\n return `${host}${withSlash}`.toLowerCase();\n};\n\n/**\n * The key of a repository URL or remote, or `undefined` when it does not name\n * one (empty, unparsable, no path, or a local path).\n *\n * Accepted: `https://host/path(.git)`, `http://…`, `ssh://user@host[:port]/path`,\n * `git://…`, `user@host:path` (scp-like), and an already-normalized\n * `host/path`. Credentials and ports never reach the key.\n */\nexport const normalizeRepositoryKey = (reference: string): string | undefined => {\n const trimmed = reference.trim();\n if (trimmed.length === 0 || trimmed.length > MAX_REPOSITORY_REFERENCE_LENGTH) {\n return undefined;\n }\n if (SCHEME_PATTERN.test(trimmed)) {\n let url: URL;\n try {\n url = new URL(trimmed);\n } catch {\n return undefined;\n }\n if (url.protocol === \"file:\") {\n return undefined;\n }\n return keyOf(url.hostname, url.pathname);\n }\n if (trimmed.startsWith(\"/\") || trimmed.startsWith(\".\") || trimmed.includes(\"\\\\\")) {\n // A local path is not a repository identity a receiver could share.\n return undefined;\n }\n const scp = SCP_LIKE_PATTERN.exec(trimmed);\n if (scp !== null && !trimmed.split(\":\")[0]?.includes(\"/\")) {\n const [, host, pathPart] = scp;\n return host === undefined || pathPart === undefined ? undefined : keyOf(host, pathPart);\n }\n // `host/path`, already a key (or a browse URL without its scheme).\n try {\n const url = new URL(`https://${trimmed}`);\n return keyOf(url.hostname, url.pathname);\n } catch {\n return undefined;\n }\n};\n","import { z } from \"zod\";\n\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\nimport { DEFAULT_SECRET_KEY_PATTERNS } from \"../privacy/policy.js\";\n\n/**\n * Custom OTLP **resource** attributes: facts about the emitting deployment\n * (`deployment.environment`, `service.instance.id`, a tenant label) that belong\n * on every span this installation exports.\n *\n * These are deliberately *not* {@link ConsumerAttributes}. Consumer attributes\n * are opaque per-invocation metadata that travels with one observation's\n * identity and is sanitized by the privacy service; resource attributes are\n * per-process exporter policy, resolved from configuration layers, and describe\n * the producer rather than the observation. The two never share a field name, a\n * flag, or a code path — see ADR 0001 on keeping identity out of configuration.\n */\n\n/** Upper bound on how many custom resource attributes one installation may set. */\nexport const MAX_RESOURCE_ATTRIBUTES = 64;\n/** Upper bound on a resource attribute key, matching the OpenTelemetry guidance. */\nexport const MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH = 255;\n/** Upper bound on a resource attribute value; values are repeated on every export. */\nexport const MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH = 2048;\n\n/**\n * Accepted shape of a resource attribute key.\n *\n * Deliberately narrower than \"any string\": a key becomes an attribute name on\n * the wire, so restricting it to the OpenTelemetry naming vocabulary keeps\n * newlines, control characters, and arbitrary binary out of the exported\n * resource by construction.\n */\nexport const RESOURCE_ATTRIBUTE_KEY_PATTERN = /^[A-Za-z][A-Za-z0-9_./-]*$/;\n\n/**\n * Keys that resource attributes may never set directly.\n *\n * `service.name` and `service.namespace` are typed exporter policy with their\n * own precedence chain and their own diagnostics. If a resource-attribute map\n * could also write them, the winner would depend on merge order inside the\n * exporter rather than on the documented configuration precedence — which is\n * exactly the silent override this reservation prevents. Supplying either one\n * through `OTEL_RESOURCE_ATTRIBUTES` still works: the environment parser routes\n * it to the policy field at a defined precedence instead of smuggling it into\n * the resource map.\n */\nexport const RESERVED_RESOURCE_ATTRIBUTE_KEYS: readonly string[] = Object.freeze([\n \"service.name\",\n \"service.namespace\",\n]);\n\n/** Case-insensitive: `Service.Name` is the same reservation, spelled differently. */\nexport const isReservedResourceAttributeKey = (key: string): boolean =>\n RESERVED_RESOURCE_ATTRIBUTE_KEYS.includes(key.toLowerCase());\n\nconst SECRET_KEY_MATCHERS: readonly RegExp[] = Object.freeze(\n DEFAULT_SECRET_KEY_PATTERNS.flatMap((source) => {\n try {\n return [new RegExp(source, \"i\")];\n } catch {\n return [];\n }\n }),\n);\n\n/**\n * Whether a key names something that should never be exported.\n *\n * A resource attribute is attached to *every* span, so `api_key=...` in a\n * config file or a shell profile would be the most durable possible leak. The\n * central privacy policy's key patterns are reused rather than re-invented, so\n * one list governs both content sanitization and this boundary.\n */\nexport const isSecretResourceAttributeKey = (key: string): boolean =>\n SECRET_KEY_MATCHERS.some((pattern) => pattern.test(key));\n\nexport type ResourceAttributeKeyRejection =\n | \"empty\"\n | \"too-long\"\n | \"malformed\"\n | \"reserved\"\n | \"secret-like\";\n\n/** Non-sensitive explanations. None of these ever quotes an attribute *value*. */\nexport const RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL: Readonly<\n Record<ResourceAttributeKeyRejection, string>\n> = Object.freeze({\n empty: \"resource attribute key is empty\",\n \"too-long\": `resource attribute key exceeds ${String(MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH)} characters`,\n malformed:\n \"resource attribute key must start with a letter and use only letters, digits, and `_`, `.`, `-`, `/`\",\n reserved:\n \"service.name and service.namespace are exporter policy (--service-name / OTEL_HOOK_SERVICE_NAME), not resource attributes\",\n \"secret-like\":\n \"resource attribute key matches a secret-name pattern, so it is never exported\",\n});\n\n/** Returns why a key is unusable, or `undefined` when it is acceptable. */\nexport const checkResourceAttributeKey = (\n key: string,\n): ResourceAttributeKeyRejection | undefined => {\n if (key.length === 0) {\n return \"empty\";\n }\n if (key.length > MAX_RESOURCE_ATTRIBUTE_KEY_LENGTH) {\n return \"too-long\";\n }\n if (!RESOURCE_ATTRIBUTE_KEY_PATTERN.test(key)) {\n return \"malformed\";\n }\n if (isReservedResourceAttributeKey(key)) {\n return \"reserved\";\n }\n if (isSecretResourceAttributeKey(key)) {\n return \"secret-like\";\n }\n return undefined;\n};\n\n/**\n * Resource attribute values are single primitives, never arrays.\n *\n * `OTEL_RESOURCE_ATTRIBUTES` cannot express an array, and allowing one only in\n * the file layer would make per-key precedence depend on which layer supplied a\n * key. A single primitive keeps the merge total and order-independent.\n */\nexport const resourceAttributeValueSchema = z.union([\n z.string().max(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH),\n z.number().finite(),\n z.boolean(),\n]);\nexport type ResourceAttributeValue = z.infer<typeof resourceAttributeValueSchema>;\n\nexport const resourceAttributesSchema = z\n .record(z.string(), resourceAttributeValueSchema)\n .superRefine((value, ctx) => {\n const keys = Object.keys(value);\n if (keys.length > MAX_RESOURCE_ATTRIBUTES) {\n ctx.addIssue({\n code: \"custom\",\n message: `at most ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes are accepted`,\n });\n }\n for (const key of keys) {\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n ctx.addIssue({\n code: \"custom\",\n path: [key],\n message: RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection],\n });\n }\n }\n })\n .readonly();\nexport type ResourceAttributes = z.infer<typeof resourceAttributesSchema>;\n\nexport const EMPTY_RESOURCE_ATTRIBUTES: ResourceAttributes = Object.freeze({});\n\nexport type ParsedResourceAttributes = {\n readonly attributes: Readonly<Record<string, string>>;\n /** `service.name`, routed to exporter policy rather than into `attributes`. */\n readonly serviceName?: string;\n /** `service.namespace`, routed the same way. */\n readonly serviceNamespace?: string;\n /**\n * Why entries were skipped. Every message identifies an entry by its\n * *position*, never by quoting the entry — an ambient environment variable\n * may hold anything, and a diagnostic that echoes it would publish it.\n */\n readonly warnings: readonly string[];\n};\n\nconst stripSurroundingQuotes = (value: string): string =>\n value.length >= 2 && value.startsWith('\"') && value.endsWith('\"') ? value.slice(1, -1) : value;\n\n/**\n * Parse the standard `OTEL_RESOURCE_ATTRIBUTES` variable.\n *\n * The OpenTelemetry specification defines this as W3C Baggage: comma-separated\n * `key=value` pairs, optional whitespace around each part, an optional\n * `;`-delimited metadata suffix that carries no attribute meaning, and\n * **percent-encoded values**. Escaping is the part naive parsers get wrong, and\n * it is load-bearing here: without it `deployment.note=a%2Cb` silently becomes\n * two malformed entries, and `region=eu%2Dwest` keeps a literal `%2D`.\n *\n * Every rejection is reported and skipped rather than failing the whole\n * variable: a stale entry in a shell profile must not cost an operator the\n * attributes they got right, and must never disable telemetry (ADR 0004).\n */\nexport const parseResourceAttributesValue = (raw: string): ParsedResourceAttributes => {\n const attributes: Record<string, string> = {};\n const warnings: string[] = [];\n let serviceName: string | undefined;\n let serviceNamespace: string | undefined;\n let overflowed = false;\n\n const entries = raw.split(\",\");\n for (const [index, rawEntry] of entries.entries()) {\n const position = index + 1;\n // Baggage metadata (`key=value;prop=1`) carries no attribute meaning.\n const entry = (rawEntry.split(\";\")[0] ?? \"\").trim();\n if (entry === \"\") {\n continue;\n }\n\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n warnings.push(`entry ${String(position)} is not a key=value pair`);\n continue;\n }\n const key = entry.slice(0, equals).trim();\n // Split on the *first* `=` only: a percent-decoded value may legitimately\n // contain one, and re-joining would be lossy.\n const encoded = stripSurroundingQuotes(entry.slice(equals + 1).trim());\n let value: string;\n try {\n value = decodeURIComponent(encoded);\n } catch {\n warnings.push(`entry ${String(position)} has a malformed percent-encoded value`);\n continue;\n }\n\n if (isReservedResourceAttributeKey(key)) {\n if (value.length === 0 || value.length > MAX_IDENTIFIER_LENGTH) {\n warnings.push(\n `entry ${String(position)} sets ${key.toLowerCase()} to an empty or over-long value`,\n );\n continue;\n }\n if (key.toLowerCase() === \"service.name\") {\n serviceName = value;\n } else {\n serviceNamespace = value;\n }\n continue;\n }\n\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n warnings.push(\n `entry ${String(position)} was skipped: ${RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]}`,\n );\n continue;\n }\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n // Dropped rather than truncated: a silently shortened attribute value is\n // a wrong fact, which is worse than a missing one.\n warnings.push(\n `entry ${String(position)} has a value longer than ${String(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH)} characters`,\n );\n continue;\n }\n if (!(key in attributes) && Object.keys(attributes).length >= MAX_RESOURCE_ATTRIBUTES) {\n overflowed = true;\n continue;\n }\n // A repeated key takes its last value, matching every other layer here.\n attributes[key] = value;\n }\n\n if (overflowed) {\n warnings.push(\n `more than ${String(MAX_RESOURCE_ATTRIBUTES)} resource attributes were supplied; the excess was dropped`,\n );\n }\n\n return {\n attributes,\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n warnings,\n };\n};\n\n/**\n * Drop anything that must not reach the exported resource.\n *\n * The schema already refuses these keys, but a {@link ExporterPolicy} can also\n * be hand-built by a library caller who never ran it through the schema. This\n * is the last gate before the wire, so it filters rather than trusts.\n */\nexport const sanitizeResourceAttributes = (\n attributes: ResourceAttributes,\n): Readonly<Record<string, ResourceAttributeValue>> => {\n const safe: Record<string, ResourceAttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (checkResourceAttributeKey(key) !== undefined) {\n continue;\n }\n if (Object.keys(safe).length >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n safe[key] = value;\n }\n return safe;\n};\n\n/**\n * Attribute *names* only, for a logged or exported configuration snapshot.\n *\n * Names are safe to disclose because they are already part of every exported\n * resource; values are not disclosed, because a value is the half an operator\n * may have filled with something they would not want in a log line.\n */\nexport const describeResourceAttributeNames = (\n attributes: ResourceAttributes,\n): readonly string[] => Object.keys(attributes).sort();\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 { createHash } from \"node:crypto\";\n\nimport type { ContentFact, ContentKind, ContentRole } from \"../model/content.js\";\nimport { isValidExtensionKey } from \"../model/extensions.js\";\nimport {\n attributeValueSchema,\n MAX_ATTRIBUTE_ARRAY_LENGTH,\n MAX_ATTRIBUTE_STRING_LENGTH,\n type AttributePrimitive,\n type Attributes,\n type AttributeValue,\n} from \"../model/primitives.js\";\nimport {\n CONTENT_MODE_DISCLOSURE,\n resolvePrivacyPolicy,\n type ContentMode,\n type PrivacyLimits,\n type PrivacyPolicy,\n} from \"./policy.js\";\n\nexport type SanitizedValue =\n | string\n | number\n | boolean\n | null\n | readonly SanitizedValue[]\n | { readonly [key: string]: SanitizedValue };\n\nexport type SanitizeStats = {\n readonly truncatedStrings: number;\n readonly truncatedArrays: number;\n readonly truncatedObjects: number;\n readonly redactedKeys: number;\n readonly depthExceeded: number;\n readonly droppedValues: number;\n readonly circularReferences: number;\n};\n\nexport type SanitizeResult = {\n readonly value: SanitizedValue;\n readonly stats: SanitizeStats;\n};\n\nexport type DescribeContentInput = {\n readonly kind: ContentKind;\n readonly text: string;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type DescribeStructuredInput = {\n readonly kind: ContentKind;\n readonly value: unknown;\n readonly role?: ContentRole;\n readonly label?: string;\n};\n\nexport type SanitizeExtensionsResult = {\n readonly extensions: Record<string, AttributeValue>;\n readonly droppedKeys: readonly string[];\n};\n\n/**\n * Single point through which every piece of potentially sensitive data passes.\n *\n * Provider adapters receive this service and are expected to describe content\n * with it rather than copying text into events themselves. That keeps the\n * disclosure decision in one auditable place.\n */\nexport interface PrivacyService {\n readonly policy: PrivacyPolicy;\n /** Notes about deterministic policy downgrades applied at construction. */\n readonly policyNotes: readonly string[];\n /** Stable salted digest, formatted `sha256:<hex>`. */\n hash(value: string): string;\n /** Opaque namespaced handle suitable for a workspace or resource id. */\n deriveOpaqueId(namespace: string, value: string): string;\n describeContent(input: DescribeContentInput): ContentFact;\n /**\n * A content fact for a kind the event can carry when the provider sent no\n * text. Distinct from describing an empty string: there is nothing to\n * disclose under any content mode, so the fact is always omitted.\n */\n describeUnavailableContent(input: Omit<DescribeContentInput, \"text\">): ContentFact;\n describeStructured(input: DescribeStructuredInput): ContentFact;\n isSecretKey(key: string): boolean;\n sanitizeStructured(value: unknown): SanitizeResult;\n /** Attribute-safe projection of a sanitized value, with dotted paths. */\n flattenToAttributes(value: SanitizedValue, prefix: string): Attributes;\n sanitizeAttributes(value: Readonly<Record<string, unknown>>): Attributes;\n sanitizeExtensions(value: Readonly<Record<string, unknown>>): SanitizeExtensionsResult;\n /** Bound a string to the policy limit, reporting whether it was cut. */\n boundString(value: string): { readonly text: string; readonly truncated: boolean };\n /**\n * The same fact disclosed at most at `mode` (a per-destination restriction).\n * Never raises disclosure: a fact already at or below `mode` is returned as is.\n */\n restrictContent(fact: ContentFact, mode: ContentMode): ContentFact;\n}\n\n/** Disclosure levels from least to most revealing. */\nconst DISCLOSURE_RANK: Readonly<Record<ContentFact[\"disclosure\"], number>> = Object.freeze({\n omitted: 0,\n masked: 1,\n redacted: 2,\n raw: 3,\n});\n\n/**\n * Text cut by the length bound may end inside a secret that is now too short\n * for a value pattern to recognize. Before redacting such text, its trailing\n * run of non-whitespace — where a cut secret would sit — is dropped.\n */\nconst WHITESPACE = /\\s/u;\nconst withoutTrailingToken = (text: string): string => {\n // A linear scan, not `/\\S+$/`: that pattern backtracks quadratically on a long\n // run of non-whitespace that is not at the end (CodeQL js/polynomial-redos).\n let end = text.length;\n while (end > 0) {\n // Step back one code point, so a surrogate pair is never split.\n const low = text.charCodeAt(end - 1);\n const width = end >= 2 && low >= 0xdc00 && low <= 0xdfff ? 2 : 1;\n if (WHITESPACE.test(text.slice(end - width, end))) break;\n end -= width;\n }\n return text.slice(0, end);\n};\n\nconst compilePatterns = (sources: readonly string[], flags: string): readonly RegExp[] => {\n const compiled: RegExp[] = [];\n for (const source of sources) {\n try {\n compiled.push(new RegExp(source, flags));\n } catch {\n // An unusable pattern must not disable the whole privacy service; the\n // remaining patterns still apply. Skipping is the conservative choice for\n // key patterns only because a bad pattern would otherwise match nothing\n // anyway.\n continue;\n }\n }\n return compiled;\n};\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst isSanitizedArray = (value: SanitizedValue): value is readonly SanitizedValue[] =>\n Array.isArray(value);\n\nconst sliceCodePoints = (value: string, max: number): string => {\n if (max <= 0) {\n return \"\";\n }\n let result = \"\";\n let count = 0;\n for (const char of value) {\n if (count >= max) {\n break;\n }\n result += char;\n count += 1;\n }\n return result;\n};\n\nconst stableStringify = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input === \"bigint\") {\n return JSON.stringify(input.toString());\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys\n .map((key) => `${JSON.stringify(key)}:${walk(record[key])}`)\n .join(\",\")}}`;\n };\n return walk(value);\n};\n\ntype MutableStats = {\n truncatedStrings: number;\n truncatedArrays: number;\n truncatedObjects: number;\n redactedKeys: number;\n depthExceeded: number;\n droppedValues: number;\n circularReferences: number;\n};\n\nconst emptyStats = (): MutableStats => ({\n truncatedStrings: 0,\n truncatedArrays: 0,\n truncatedObjects: 0,\n redactedKeys: 0,\n depthExceeded: 0,\n droppedValues: 0,\n circularReferences: 0,\n});\n\nexport const createPrivacyService = (policyInput: PrivacyPolicy): PrivacyService => {\n const { policy, notes } = resolvePrivacyPolicy(policyInput);\n const limits: PrivacyLimits = policy.limits;\n const secretKeyPatterns = compilePatterns(policy.secretKeyPatterns, \"i\");\n const secretValuePatterns = compilePatterns(policy.secretValuePatterns, \"g\");\n\n const hash = (value: string): string =>\n `sha256:${createHash(\"sha256\").update(policy.hashSalt).update(\"\\0\").update(value, \"utf8\").digest(\"hex\")}`;\n\n const isSecretKey = (key: string): boolean =>\n secretKeyPatterns.some((pattern) => pattern.test(key));\n\n const boundString = (value: string): { text: string; truncated: boolean } => {\n const length = codePointLength(value);\n if (length <= limits.maxStringLength) {\n return { text: value, truncated: false };\n }\n return { text: sliceCodePoints(value, limits.maxStringLength), truncated: true };\n };\n\n const redactSecretSpans = (value: string): { text: string; count: number } => {\n let count = 0;\n let text = value;\n for (const pattern of secretValuePatterns) {\n text = text.replace(new RegExp(pattern.source, pattern.flags), () => {\n count += 1;\n return policy.redactionPlaceholder;\n });\n }\n return { text, count };\n };\n\n const maskText = (value: string): string =>\n Array.from(value, (char) => (/\\s/.test(char) ? char : policy.maskCharacter)).join(\"\");\n\n const disclose = (\n original: string,\n ): { text: string | undefined; truncated: boolean; secretsRedacted: number } => {\n switch (policy.contentMode) {\n case \"omit\":\n return { text: undefined, truncated: false, secretsRedacted: 0 };\n case \"mask\": {\n const bounded = boundString(original);\n return { text: maskText(bounded.text), truncated: bounded.truncated, secretsRedacted: 0 };\n }\n case \"redact\": {\n const redacted = redactSecretSpans(original);\n const bounded = boundString(redacted.text);\n return {\n text: bounded.text,\n truncated: bounded.truncated,\n secretsRedacted: redacted.count,\n };\n }\n case \"raw\": {\n const bounded = boundString(original);\n return { text: bounded.text, truncated: bounded.truncated, secretsRedacted: 0 };\n }\n }\n };\n\n const describeText = (input: DescribeContentInput): ContentFact => {\n const disclosed = disclose(input.text);\n return {\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: codePointLength(input.text),\n byteLength: Buffer.byteLength(input.text, \"utf8\"),\n contentHash: hash(input.text),\n disclosure: CONTENT_MODE_DISCLOSURE[policy.contentMode],\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted,\n ...(input.label === undefined ? {} : { label: input.label }),\n };\n };\n\n const sanitizeValue = (value: unknown, depth: number, stats: MutableStats, seen: WeakSet<object>): SanitizedValue => {\n if (value === null) {\n return null;\n }\n switch (typeof value) {\n case \"string\": {\n const bounded = boundString(value);\n if (bounded.truncated) {\n stats.truncatedStrings += 1;\n }\n return bounded.text;\n }\n case \"number\":\n if (!Number.isFinite(value)) {\n stats.droppedValues += 1;\n return null;\n }\n return value;\n case \"boolean\":\n return value;\n case \"bigint\":\n return value.toString();\n case \"undefined\":\n case \"function\":\n case \"symbol\":\n stats.droppedValues += 1;\n return null;\n default:\n break;\n }\n\n if (depth >= limits.maxDepth) {\n stats.depthExceeded += 1;\n return \"<depth-exceeded>\";\n }\n if (seen.has(value)) {\n stats.circularReferences += 1;\n return \"<circular>\";\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n const entries = value.slice(0, limits.maxArrayLength);\n if (value.length > limits.maxArrayLength) {\n stats.truncatedArrays += 1;\n }\n return entries.map((entry) => sanitizeValue(entry, depth + 1, stats, seen));\n }\n\n if (value instanceof Date) {\n return value.toISOString();\n }\n\n const record = value as Record<string, unknown>;\n const keys = Object.keys(record);\n const retained = keys.slice(0, limits.maxObjectKeys);\n if (keys.length > limits.maxObjectKeys) {\n stats.truncatedObjects += 1;\n }\n const result: Record<string, SanitizedValue> = {};\n for (const key of retained) {\n if (isSecretKey(key)) {\n stats.redactedKeys += 1;\n result[key] = policy.redactionPlaceholder;\n continue;\n }\n result[key] = sanitizeValue(record[key], depth + 1, stats, seen);\n }\n return result;\n };\n\n const sanitizeStructured = (value: unknown): SanitizeResult => {\n const stats = emptyStats();\n const sanitized = sanitizeValue(value, 0, stats, new WeakSet<object>());\n return { value: sanitized, stats };\n };\n\n const toAttributePrimitive = (value: SanitizedValue): AttributePrimitive | undefined => {\n if (typeof value === \"string\") {\n return value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return value;\n }\n return undefined;\n };\n\n const flattenToAttributes = (value: SanitizedValue, prefix: string): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n const walk = (current: SanitizedValue, path: string): void => {\n if (\n typeof current === \"string\" ||\n typeof current === \"number\" ||\n typeof current === \"boolean\"\n ) {\n const primitive = toAttributePrimitive(current);\n if (primitive !== undefined) {\n attributes[path] = primitive;\n }\n return;\n }\n if (current === null) {\n return;\n }\n if (isSanitizedArray(current)) {\n const primitives: AttributePrimitive[] = [];\n let uniform = true;\n for (const entry of current) {\n const entryPrimitive = toAttributePrimitive(entry);\n if (entryPrimitive === undefined) {\n uniform = false;\n break;\n }\n primitives.push(entryPrimitive);\n }\n if (uniform) {\n attributes[path] = primitives.slice(0, MAX_ATTRIBUTE_ARRAY_LENGTH);\n return;\n }\n for (const [index, entry] of current.entries()) {\n walk(entry, `${path}.${index}`);\n }\n return;\n }\n for (const [key, entry] of Object.entries(current)) {\n walk(entry, path === \"\" ? key : `${path}.${key}`);\n }\n };\n walk(value, prefix);\n return attributes;\n };\n\n const sanitizeAttributes = (value: Readonly<Record<string, unknown>>): Attributes => {\n const attributes: Record<string, AttributeValue> = {};\n for (const [key, entry] of Object.entries(value)) {\n if (isSecretKey(key)) {\n attributes[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const primitive = toAttributePrimitive(sanitized);\n if (primitive !== undefined) {\n attributes[key] = primitive;\n continue;\n }\n const flattened = flattenToAttributes(sanitized, key);\n Object.assign(attributes, flattened);\n }\n return attributes;\n };\n\n const sanitizeExtensions = (\n value: Readonly<Record<string, unknown>>,\n ): SanitizeExtensionsResult => {\n const extensions: Record<string, AttributeValue> = {};\n const droppedKeys: string[] = [];\n for (const [key, entry] of Object.entries(value)) {\n if (!isValidExtensionKey(key)) {\n droppedKeys.push(key);\n continue;\n }\n if (isSecretKey(key)) {\n extensions[key] = policy.redactionPlaceholder;\n continue;\n }\n const sanitized = sanitizeStructured(entry).value;\n const candidate = attributeValueSchema.safeParse(sanitized);\n if (candidate.success) {\n extensions[key] = candidate.data;\n } else {\n droppedKeys.push(key);\n }\n }\n return { extensions, droppedKeys };\n };\n\n return {\n policy,\n policyNotes: notes,\n hash,\n deriveOpaqueId: (namespace: string, value: string): string =>\n hash(`${namespace}\\0${value}`),\n describeContent: describeText,\n describeUnavailableContent: (input: Omit<DescribeContentInput, \"text\">): ContentFact => ({\n kind: input.kind,\n ...(input.role === undefined ? {} : { role: input.role }),\n characterLength: 0,\n byteLength: 0,\n contentHash: hash(\"\"),\n disclosure: \"omitted\",\n truncated: false,\n secretsRedacted: 0,\n ...(input.label === undefined ? {} : { label: input.label }),\n }),\n describeStructured: (input: DescribeStructuredInput): ContentFact => {\n const serialized = stableStringify(input.value);\n const sanitized = sanitizeStructured(input.value);\n const base = describeText({\n kind: input.kind,\n text: serialized,\n ...(input.role === undefined ? {} : { role: input.role }),\n ...(input.label === undefined ? {} : { label: input.label }),\n });\n if (base.text === undefined) {\n return base;\n }\n // Disclose the sanitized projection rather than the raw serialization, so\n // secret-keyed values never appear even in `raw` mode.\n const disclosed = disclose(stableStringify(sanitized.value));\n return {\n ...base,\n ...(disclosed.text === undefined ? {} : { text: disclosed.text }),\n truncated: base.truncated || disclosed.truncated,\n secretsRedacted: disclosed.secretsRedacted + sanitized.stats.redactedKeys,\n };\n },\n isSecretKey,\n sanitizeStructured,\n flattenToAttributes,\n sanitizeAttributes,\n sanitizeExtensions,\n boundString,\n restrictContent: (fact: ContentFact, mode: ContentMode): ContentFact => {\n const target = CONTENT_MODE_DISCLOSURE[mode];\n if (fact.text === undefined || DISCLOSURE_RANK[fact.disclosure] <= DISCLOSURE_RANK[target]) {\n return fact;\n }\n const { text, ...rest } = fact;\n switch (target) {\n case \"omitted\":\n return { ...rest, disclosure: \"omitted\", truncated: false };\n case \"masked\":\n return { ...rest, disclosure: \"masked\", text: maskText(text) };\n case \"redacted\": {\n const redacted = redactSecretSpans(fact.truncated ? withoutTrailingToken(text) : text);\n return {\n ...rest,\n disclosure: \"redacted\",\n text: redacted.text,\n secretsRedacted: fact.secretsRedacted + redacted.count,\n };\n }\n case \"raw\":\n // Unreachable: nothing ranks above raw.\n return fact;\n }\n },\n };\n};\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 type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n canonicalEventTypeSchema,\n type CanonicalEvent,\n type CanonicalEventType,\n type ModelDescriptor,\n} from \"../model/events.js\";\nimport type { IdentityClaim, InvocationIdentity } from \"../model/identity.js\";\nimport type { TargetHint } from \"../model/target.js\";\nimport {\n detectionConfidenceSchema,\n nonEmptyStringSchema,\n providerIdSchema,\n resolvedProviderIdSchema,\n type EventId,\n type ProviderId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport { cacheCreationAccountingSchema, usageTemporalitySchema, type UsageTemporality } from \"../model/usage.js\";\nimport type { PrivacyLimits } from \"../privacy/policy.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport type { Clock, IdGenerator, Logger } from \"../runtime/ports.js\";\n\n/** Raw input offered to adapters. `payload` is `unknown` on purpose. */\nexport type ProviderDetectionInput = {\n /** Decoded but uninterpreted provider payload. Must not escape the adapter. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n /** Caller's assertion of the provider, e.g. from a CLI flag. */\n readonly providerHint?: string;\n};\n\nexport const providerDetectionSchema = z.strictObject({\n providerId: resolvedProviderIdSchema,\n confidence: detectionConfidenceSchema,\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.hook_event_name present\"`.\n * Reasons are exported in diagnostics, so they must not quote payload values.\n */\n reasons: z.array(z.string().min(1).max(160)).max(8),\n providerVersion: nonEmptyStringSchema.optional(),\n /** The provider's own name for this event, when the payload states one. */\n sourceEventName: nonEmptyStringSchema.optional(),\n});\nexport type ProviderDetection = z.infer<typeof providerDetectionSchema>;\n\n/**\n * How much of a provider's hook traffic carries an identifier that survives a\n * redelivery.\n *\n * - `none`: no callback carries one. Redelivery is undetectable from the\n * payload, and deduplication needs a host-supplied delivery id.\n * - `partial`: some callbacks do and some do not — typically per-tool-call and\n * per-turn events do, while session and compaction edges do not.\n * - `all`: every callback the adapter recognizes carries one.\n *\n * Declared rather than probed for the same reason as the usage capabilities\n * below: \"this callback has no stable id\" and \"this adapter never looked\" are\n * indistinguishable downstream, and only the first is safe to build on.\n */\nexport const deliveryIdentifierSupportSchema = z.enum([\"none\", \"partial\", \"all\"]);\nexport type DeliveryIdentifierSupport = z.infer<typeof deliveryIdentifierSupportSchema>;\n\n/**\n * Shape a delivery-identity component must have.\n *\n * Deliberately narrow. Provider identifiers, integer counters, hook event\n * names, and ISO-8601 timestamps all satisfy it; prose and filesystem paths do\n * not, because neither spaces nor `/` are allowed. So an adapter that\n * accidentally seeds a delivery identity with a prompt, a tool response, or a\n * home directory produces a *rejected claim* rather than a privacy incident —\n * the guard is structural, not a review convention.\n */\nexport const DELIVERY_COMPONENT_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\n\nexport const deliveryComponentSchema = z\n .string()\n .regex(\n DELIVERY_COMPONENT_PATTERN,\n \"delivery component must be identifier-shaped: no whitespace, no path separators\",\n );\n\n/** Most identifier-shaped fields one callback identity may be built from. */\nexport const MAX_DELIVERY_COMPONENTS = 8;\n\n/**\n * An adapter's assertion that this callback has a replay-stable identity.\n *\n * The adapter reports *components* rather than a finished id: it knows which\n * payload fields are trustworthy, and the runtime owns how they are combined,\n * scoped, and digested. That split is what keeps a raw provider identifier from\n * becoming an on-disk key or a diagnostic attribute (see\n * `resolveDeliveryIdentity`).\n *\n * Returning nothing is always safe. Claiming an identity that is not actually\n * stable is not: it makes the runtime suppress a *genuine* second callback as if\n * it were a redelivery, which silently loses telemetry.\n */\nexport const providerDeliveryClaimSchema = z.strictObject({\n /**\n * The provider's own session/conversation id. Scopes the callback identity, so\n * two sessions reusing one tool-call id never collide.\n */\n sessionId: nonEmptyStringSchema,\n /** The provider's own name for this callback, e.g. `PostToolUse`. */\n sourceEventName: deliveryComponentSchema,\n /**\n * Identifier-shaped payload fields that, together with `sourceEventName`,\n * name this callback within the session exactly once.\n */\n components: z.array(deliveryComponentSchema).min(1).max(MAX_DELIVERY_COMPONENTS).readonly(),\n /**\n * Short, non-sensitive justifications, e.g. `\"payload.tool_use_id names one\n * tool call\"`. Evidence reaches diagnostics, so it must name fields, never\n * quote their values.\n */\n evidence: z.array(z.string().min(1).max(160)).min(1).max(4).readonly(),\n});\nexport type ProviderDeliveryClaim = z.infer<typeof providerDeliveryClaimSchema>;\n\n/**\n * Shape a per-callback delivery *gap* explanation must have.\n *\n * These strings reach a diagnostic, so the same reasoning that constrains\n * {@link deliveryComponentSchema} applies for the opposite purpose: a component\n * must be identifier-shaped, a gap reason must be prose that cannot smuggle a\n * filesystem path or a newline-delimited payload dump into stderr. Spaces are\n * allowed — it is a sentence — and `/`, `\\`, and control characters are not,\n * which is what keeps a home directory out of a message an adapter author writes\n * by hand.\n */\nexport const DELIVERY_GAP_REASON_PATTERN = /^[^\\n\\r\\t\\\\/]{1,240}$/;\n\nexport const deliveryGapReasonSchema = z\n .string()\n .regex(\n DELIVERY_GAP_REASON_PATTERN,\n \"delivery gap reason must be one line of prose: no path separators, no control characters\",\n );\n\n/** Most callbacks one adapter may document a delivery gap for. */\nexport const MAX_DELIVERY_GAPS = 48;\n\n/**\n * Why each of an adapter's callbacks carries no replay-stable identity.\n *\n * Keyed by the provider's *own* event name — the same value `detect` reports as\n * `sourceEventName` — so the runtime can look up the reason for the callback in\n * front of it without parsing the payload a second time.\n *\n * This exists because `callback-not-identifiable` on its own is a true statement\n * that helps nobody: an operator auditing coverage with `--require-callback-id`\n * needs to know *which* callback and *what field would have to exist*, and only\n * the adapter knows that. Keeping it declarative rather than computed means the\n * answer is reviewable next to the protocol it describes, and an exhaustiveness\n * test can insist that adding a hook event without deciding its delivery status\n * reads as an omission.\n */\nexport const providerDeliveryGapsSchema = z\n .record(deliveryComponentSchema, deliveryGapReasonSchema)\n .refine((gaps) => Object.keys(gaps).length <= MAX_DELIVERY_GAPS, {\n message: `at most ${String(MAX_DELIVERY_GAPS)} delivery gaps may be declared`,\n });\nexport type ProviderDeliveryGaps = z.infer<typeof providerDeliveryGapsSchema>;\n\n/**\n * What an adapter can actually observe.\n *\n * Capabilities are declared rather than probed so consumers can distinguish\n * \"this provider reports no cached tokens\" from \"this session used no cache\" —\n * the two look identical in the data.\n */\nexport const providerCapabilitiesSchema = z.strictObject({\n /** Event types the adapter can produce. */\n lifecycleEvents: z.array(canonicalEventTypeSchema).max(32).readonly(),\n usageTemporality: usageTemporalitySchema,\n /**\n * Which accumulator series a `cumulative` report continues — that is, which\n * previous snapshot the next one should be diffed against.\n *\n * Only meaningful when `usageTemporality` is `cumulative`; omit otherwise.\n *\n * - `event-scope` (the default when omitted) — each event scope keeps its own\n * running total, so a `generation.end` snapshot is diffed against the\n * previous snapshot *for that same generation*.\n * - `session-lifetime` — the provider maintains **one** running total for the\n * whole session and stamps it onto whichever callback happens to report it.\n * Diffing such a snapshot per event scope would restart the baseline on\n * every new generation id and re-count the entire session total each turn,\n * so session-level and generation-level snapshots share one baseline.\n * Subagent snapshots keep their own series regardless: a delegated agent's\n * counter is not a point on the parent session's curve.\n */\n cumulativeUsageSeries: z.enum([\"event-scope\", \"session-lifetime\"]).optional(),\n reportsCachedInput: z.boolean(),\n reportsCacheCreation: z.boolean(),\n cacheCreationAccounting: cacheCreationAccountingSchema,\n reportsReasoningOutput: z.boolean(),\n reportsProviderTotal: z.boolean(),\n reportsCost: z.boolean(),\n emitsSubagentEvents: z.boolean(),\n emitsCompactionEvents: z.boolean(),\n /** True when the provider reads a structured response from stdout. */\n requiresHookResponse: z.boolean(),\n /** How much of this provider's hook traffic is replay-identifiable. */\n deliveryIdentifier: deliveryIdentifierSupportSchema,\n});\nexport type ProviderCapabilities = z.infer<typeof providerCapabilitiesSchema>;\n\n/** Services an adapter is given. Note the absence of a filesystem or network. */\nexport type ProviderContext = {\n readonly privacy: PrivacyService;\n readonly clock: Clock;\n readonly ids: IdGenerator;\n readonly logger: Logger;\n readonly limits: PrivacyLimits;\n};\n\nexport type ProviderIdentityInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n};\n\nexport type ProviderParseInput = ProviderDetectionInput & {\n readonly detection: ProviderDetection;\n /** Resolved by the core; adapters never resolve identity themselves. */\n readonly identity: InvocationIdentity;\n /**\n * First sequence number the adapter may use. Sequences must be assigned\n * consecutively from here so event ids stay stable across replays.\n */\n readonly sequenceBase: number;\n /**\n * The model this session last reported, as the core remembers it across\n * invocations (`session.start` or a `generation.*` edge with a known model).\n *\n * Read from the state store by the core and handed in, because an adapter must\n * not hold cross-invocation state itself (ADR 0006). Absent when no earlier\n * invocation of this session named a model, or when the store is unreadable.\n * An adapter whose generation callbacks carry no model id (Claude Code's\n * `Stop`) uses it instead of the `unknown` sentinel; one whose callbacks carry\n * their own model can ignore it.\n */\n readonly sessionModel?: ModelDescriptor;\n};\n\nexport type ProviderParseResult =\n | {\n readonly status: \"parsed\";\n readonly events: readonly CanonicalEvent[];\n readonly warnings?: readonly string[];\n /**\n * Where tool events pointed, keyed by event id (ADR 0008). The one\n * canonical value that carries local paths: the core resolves each into\n * the event's `target` and discards it. Use `EventFactory.targetHints()`.\n */\n readonly targetHints?: ReadonlyMap<EventId, TargetHint>;\n }\n /** The input was recognized but carries no telemetry. Not an error. */\n | { readonly status: \"ignored\"; readonly reason: string }\n | { readonly status: \"failed\"; readonly error: OtelHookErrorInfo };\n\nexport const providerHookResponseSchema = z.strictObject({\n /**\n * Always 0. A telemetry hook that can fail the host agent is a liability, so\n * the type forbids expressing anything else (ADR 0004).\n */\n exitCode: z.literal(0),\n /** Protocol response text. Omit to write nothing at all. */\n stdout: z.string().max(8192).optional(),\n /** Non-sensitive diagnostic text for stderr. */\n stderr: z.string().max(8192).optional(),\n /** Declares which of the two stdout contracts this response follows. */\n contract: z.enum([\"silent\", \"provider-protocol\"]),\n});\nexport type ProviderHookResponse = z.infer<typeof providerHookResponseSchema>;\n\n/** The silent response: nothing on stdout, success to the host. */\nexport const SILENT_HOOK_RESPONSE: ProviderHookResponse = Object.freeze({\n exitCode: 0 as const,\n contract: \"silent\" as const,\n});\n\nexport type ProviderHookResponseInput = {\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly detection?: ProviderDetection;\n readonly emittedEvents: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Contract every provider adapter implements.\n *\n * The four methods are deliberately separate: detection must be cheap and\n * side-effect free, identity must be expressible as claims the core can\n * arbitrate, parsing must be the only place that reads the payload, and the hook\n * response must be derivable from the outcome alone.\n */\nexport interface ProviderAdapter {\n readonly id: ProviderId;\n readonly version: string;\n readonly capabilities: ProviderCapabilities;\n /**\n * Report whether this adapter recognizes the input. Must not throw; must not\n * read files or the network. Return `none` rather than guessing.\n */\n detect(input: ProviderDetectionInput, context: ProviderContext): ProviderDetection;\n /**\n * Contribute identity claims. Returning fewer claims is always safe;\n * fabricating a session id is not.\n */\n identify(input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[];\n /**\n * Report this callback's replay-stable identity, when the payload carries one.\n *\n * Called before `parse`, must be cheap and side-effect free, and must not\n * throw. Return `undefined` whenever the payload's identifying fields are\n * absent or would not survive a redelivery — under-reporting costs\n * deduplication, over-reporting loses real telemetry.\n */\n deliveryIdentity?(\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): ProviderDeliveryClaim | undefined;\n /**\n * Why each callback that {@link ProviderAdapter.deliveryIdentity} declines\n * carries no replay-stable identity, keyed by the provider's own event name.\n *\n * Static data, not control flow: it never decides whether a callback is\n * deduplicated, only what the runtime can *say* when it is not. An adapter that\n * declares `deliveryIdentifier: \"none\"` should still populate this — the gap is\n * then the whole story, and \"the protocol has no request id\" is a far more\n * actionable diagnostic than \"not identifiable\".\n */\n readonly deliveryGaps?: ProviderDeliveryGaps;\n /** Interpret the payload into canonical events. */\n parse(input: ProviderParseInput, context: ProviderContext): ProviderParseResult;\n /** Provider-specific hook response for the given outcome. */\n hookResponse(input: ProviderHookResponseInput, context: ProviderContext): ProviderHookResponse;\n}\n\nexport const adapterSupports = (\n adapter: ProviderAdapter,\n eventType: CanonicalEventType,\n): boolean => adapter.capabilities.lifecycleEvents.includes(eventType);\n\nexport type AdapterDescription = {\n readonly id: ResolvedProviderId;\n readonly version: string;\n readonly lifecycleEvents: readonly string[];\n readonly usageTemporality: UsageTemporality;\n readonly deliveryIdentifier: DeliveryIdentifierSupport;\n};\n\nexport const describeAdapter = (adapter: ProviderAdapter): AdapterDescription => ({\n id: adapter.id,\n version: adapter.version,\n lifecycleEvents: [...adapter.capabilities.lifecycleEvents],\n usageTemporality: adapter.capabilities.usageTemporality,\n deliveryIdentifier: adapter.capabilities.deliveryIdentifier,\n});\n\n/**\n * Ask an adapter for a delivery claim, containing anything it does wrong.\n *\n * A `deliveryIdentity` that throws, or that returns a claim the schema rejects\n * (a component carrying prose, more components than the cap), degrades to \"no\n * stable identity available\" rather than failing the invocation: deduplication\n * is an optimization, and the host's telemetry is not.\n */\nexport const readDeliveryClaim = (\n adapter: ProviderAdapter,\n input: ProviderIdentityInput,\n context: ProviderContext,\n): { readonly claim?: ProviderDeliveryClaim; readonly rejection?: string } => {\n if (adapter.deliveryIdentity === undefined) {\n return {};\n }\n let candidate: ProviderDeliveryClaim | undefined;\n try {\n candidate = adapter.deliveryIdentity(input, context);\n } catch {\n return { rejection: `adapter ${adapter.id} threw while reporting a delivery identity` };\n }\n if (candidate === undefined) {\n return {};\n }\n const parsed = providerDeliveryClaimSchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n rejection: `adapter ${adapter.id} reported a malformed delivery identity: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 240),\n };\n }\n return { claim: parsed.data };\n};\n\n/**\n * Look up why this callback has no replay-stable identity, containing anything\n * the adapter got wrong.\n *\n * Validated on the way out rather than trusted, for the same reason a claim is:\n * the string ends up in a diagnostic an operator reads, and an adapter that pasted\n * a path or a payload excerpt into its own gap table must produce *no detail*\n * rather than a disclosure. Returning `undefined` costs a sentence of explanation\n * and nothing else — the reason code is reported either way.\n */\nexport const readDeliveryGap = (\n adapter: ProviderAdapter,\n sourceEventName: string | undefined,\n): string | undefined => {\n if (sourceEventName === undefined || adapter.deliveryGaps === undefined) {\n return undefined;\n }\n // A prototype-polluting event name must not reach a bare property read: the\n // event name comes from a payload, and `__proto__` is a string like any other.\n if (!Object.prototype.hasOwnProperty.call(adapter.deliveryGaps, sourceEventName)) {\n return undefined;\n }\n const parsed = deliveryGapReasonSchema.safeParse(adapter.deliveryGaps[sourceEventName]);\n return parsed.success ? parsed.data : undefined;\n};\n\nexport const asProviderId = (value: string): ProviderId => providerIdSchema.parse(value);\n\nexport const unknownDetection = (\n reasons: readonly string[] = [\"no adapter recognized the input\"],\n): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: reasons.slice(0, 8),\n });\n","import { z } from \"zod\";\n\nimport {\n errorPhaseSchema,\n errorSeveritySchema,\n otelHookErrorCodeSchema,\n} from \"../errors/taxonomy.js\";\nimport { contentFactSchema, contentFactsSchema } from \"./content.js\";\nimport { extensionsSchema, emptyExtensions } from \"./extensions.js\";\nimport { sourceProvenanceSchema, workspaceIdentitySchema } from \"./identity.js\";\nimport { subagentIdSchema, workspaceTargetSchema } from \"./target.js\";\nimport {\n durationMillisSchema,\n epochMillisSchema,\n eventIdSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n sequenceNumberSchema,\n sessionIdSchema,\n tokenCountSchema,\n} from \"./primitives.js\";\nimport { canonicalUsageSchema, type CanonicalUsage } from \"./usage.js\";\nimport { canonicalSchemaVersionSchema } from \"./version.js\";\n\n/** Model being invoked. Model identifiers are not treated as sensitive. */\nexport const modelDescriptorSchema = z.strictObject({\n modelId: nonEmptyStringSchema,\n /** Vendor of the model, e.g. `anthropic`. Distinct from the agent provider. */\n vendor: nonEmptyStringSchema.optional(),\n family: nonEmptyStringSchema.optional(),\n});\nexport type ModelDescriptor = z.infer<typeof modelDescriptorSchema>;\n\nexport const costFactsSchema = z.strictObject({\n /** ISO 4217 code. */\n currency: z.string().length(3),\n amount: z.number().min(0).finite(),\n source: z.enum([\"provider-reported\", \"computed\"]),\n});\nexport type CostFacts = z.infer<typeof costFactsSchema>;\n\nexport const canonicalEventTypeSchema = z.enum([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n \"error.raised\",\n]);\nexport type CanonicalEventType = z.infer<typeof canonicalEventTypeSchema>;\n\nexport const CANONICAL_EVENT_TYPES = canonicalEventTypeSchema.options;\n\nconst outcomeSchema = z.enum([\"ok\", \"error\", \"cancelled\", \"timeout\", \"denied\", \"unknown\"]);\nexport type EventOutcome = z.infer<typeof outcomeSchema>;\n\n/**\n * Fields present on every canonical event.\n *\n * Identity fields are duplicated onto each event rather than referenced through\n * shared state, so an event is self-describing once it leaves the process.\n */\nconst baseEventFields = {\n schemaVersion: canonicalSchemaVersionSchema,\n eventId: eventIdSchema,\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Per-invocation ordering key. Stable across replays of the same input. */\n sequence: sequenceNumberSchema,\n occurredAt: epochMillisSchema,\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n /**\n * The provider's own id for the subagent this event was emitted inside (e.g.\n * Claude Code's `agent_id`). Absent for the top-level agent. Set by the event\n * factory, never by hand.\n */\n subagentId: subagentIdSchema.optional(),\n extensions: extensionsSchema.default(emptyExtensions),\n /**\n * Attributes of the session context segment in force when the event\n * occurred (`docs/session-context.md`), stamped by the core from a file a\n * harness wrote. Exported on every record of the event, over the same keys\n * from the Resource. Absent when no context applies. Set by the core only,\n * never by an adapter.\n */\n contextAttributes: z.record(z.string().min(1).max(255), z.union([z.string(), z.number(), z.boolean()])).optional(),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const sessionEndEventSchema = event({\n type: z.literal(\"session.end\"),\n reason: z.enum([\"completed\", \"aborted\", \"error\", \"timeout\", \"unknown\"]),\n durationMillis: durationMillisSchema.optional(),\n /** Session totals, typically cumulative. */\n usage: canonicalUsageSchema.optional(),\n cost: costFactsSchema.optional(),\n});\n\nexport const promptSubmittedEventSchema = event({\n type: z.literal(\"prompt.submitted\"),\n promptSource: z.enum([\"user\", \"automation\", \"resumed\", \"unknown\"]),\n content: contentFactSchema.optional(),\n turnIndex: z.number().int().min(0).optional(),\n /** The git worktree the session runs in, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const generationStartEventSchema = event({\n type: z.literal(\"generation.start\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n requestedMaxOutputTokens: tokenCountSchema.optional(),\n inputContent: contentFactsSchema.optional(),\n});\n\nexport const generationEndEventSchema = event({\n type: z.literal(\"generation.end\"),\n generationId: nonEmptyStringSchema,\n model: modelDescriptorSchema,\n outcome: outcomeSchema,\n stopReason: nonEmptyStringSchema.optional(),\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n /**\n * True when `usage` is known to cover only part of the generation (for\n * example the last model request of a multi-request turn); false when the\n * provider or harness said it is the whole. Absent: not stated. Meaningless\n * without `usage`.\n */\n usagePartial: z.boolean().optional(),\n cost: costFactsSchema.optional(),\n outputContent: contentFactsSchema.optional(),\n});\n\nexport const toolKindSchema = z.enum([\n \"read\",\n \"write\",\n \"execute\",\n \"search\",\n \"network\",\n \"delegate\",\n \"other\",\n \"unknown\",\n]);\nexport type ToolKind = z.infer<typeof toolKindSchema>;\n\nexport const toolStartEventSchema = event({\n type: z.literal(\"tool.start\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n toolKind: toolKindSchema,\n generationId: nonEmptyStringSchema.optional(),\n input: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const toolEndEventSchema = event({\n type: z.literal(\"tool.end\"),\n toolCallId: nonEmptyStringSchema,\n toolName: nonEmptyStringSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n /** Present when the host asked for or recorded a permission decision. */\n permissionDecision: z.enum([\"allowed\", \"denied\", \"deferred\", \"not-required\"]).optional(),\n output: contentFactSchema.optional(),\n /** The git worktree this call targeted, resolved by the core (ADR 0008). */\n target: workspaceTargetSchema.optional(),\n});\n\nexport const subagentStartEventSchema = event({\n type: z.literal(\"subagent.start\"),\n subagentInvocationId: invocationIdSchema,\n subagentType: nonEmptyStringSchema.optional(),\n /** 0 for the top-level agent; 1 for its direct children. */\n delegationDepth: z.number().int().min(0).max(64),\n model: modelDescriptorSchema.optional(),\n});\n\nexport const subagentEndEventSchema = event({\n type: z.literal(\"subagent.end\"),\n subagentInvocationId: invocationIdSchema,\n outcome: outcomeSchema,\n durationMillis: durationMillisSchema.optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const compactionPerformedEventSchema = event({\n type: z.literal(\"compaction.performed\"),\n trigger: z.enum([\"automatic\", \"manual\", \"unknown\"]),\n /** Provider-reported context size before and after compaction, if known. */\n contextTokensBefore: tokenCountSchema.optional(),\n contextTokensAfter: tokenCountSchema.optional(),\n droppedMessageCount: z.number().int().min(0).optional(),\n usage: canonicalUsageSchema.optional(),\n});\n\nexport const errorRaisedEventSchema = event({\n type: z.literal(\"error.raised\"),\n errorCode: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n retryable: z.boolean(),\n /** Error text is content: it is described, never embedded verbatim by default. */\n message: contentFactSchema.optional(),\n /** Non-sensitive, provider-agnostic short label. */\n detail: nonEmptyStringSchema.optional(),\n});\n\nexport const canonicalEventSchema = z.discriminatedUnion(\"type\", [\n sessionStartEventSchema,\n sessionEndEventSchema,\n promptSubmittedEventSchema,\n generationStartEventSchema,\n generationEndEventSchema,\n toolStartEventSchema,\n toolEndEventSchema,\n subagentStartEventSchema,\n subagentEndEventSchema,\n compactionPerformedEventSchema,\n errorRaisedEventSchema,\n]);\n\nexport type CanonicalEvent = z.infer<typeof canonicalEventSchema>;\nexport type CanonicalEventInput = z.input<typeof canonicalEventSchema>;\n\nexport type SessionStartEvent = z.infer<typeof sessionStartEventSchema>;\nexport type SessionEndEvent = z.infer<typeof sessionEndEventSchema>;\nexport type PromptSubmittedEvent = z.infer<typeof promptSubmittedEventSchema>;\nexport type GenerationStartEvent = z.infer<typeof generationStartEventSchema>;\nexport type GenerationEndEvent = z.infer<typeof generationEndEventSchema>;\nexport type ToolStartEvent = z.infer<typeof toolStartEventSchema>;\nexport type ToolEndEvent = z.infer<typeof toolEndEventSchema>;\nexport type SubagentStartEvent = z.infer<typeof subagentStartEventSchema>;\nexport type SubagentEndEvent = z.infer<typeof subagentEndEventSchema>;\nexport type CompactionPerformedEvent = z.infer<typeof compactionPerformedEventSchema>;\nexport type ErrorRaisedEvent = z.infer<typeof errorRaisedEventSchema>;\n\nexport type CanonicalEventOfType<TType extends CanonicalEventType> = Extract<\n CanonicalEvent,\n { type: TType }\n>;\n\n/**\n * The event types that may carry a resolved `target` (ADR 0008): a tool call\n * names the worktree it touched; a session start and a prompt name the one the\n * session runs in, so a consumer knows the session's place before its first\n * tool call.\n */\nexport const TARGETED_EVENT_TYPES = [\"session.start\", \"prompt.submitted\", \"tool.start\", \"tool.end\"] as const;\nexport type TargetedEventType = (typeof TARGETED_EVENT_TYPES)[number];\nexport type TargetedEvent = CanonicalEventOfType<TargetedEventType>;\n\nconst TARGETED: ReadonlySet<string> = new Set(TARGETED_EVENT_TYPES);\nexport const isTargetedEvent = (event: CanonicalEvent): event is TargetedEvent => TARGETED.has(event.type);\n\nexport type EventValidationResult =\n | { readonly status: \"ok\"; readonly event: CanonicalEvent }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nexport const validateCanonicalEvent = (value: unknown): EventValidationResult => {\n const parsed = canonicalEventSchema.safeParse(value);\n if (parsed.success) {\n return { status: \"ok\", event: parsed.data };\n }\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n};\n\n/** Parse or throw. Intended for fixtures and tests, not the hook path. */\nexport const parseCanonicalEvent = (value: unknown): CanonicalEvent =>\n canonicalEventSchema.parse(value);\n\n/** Usage carried by an event, if the event type can carry any. */\nexport const eventUsage = (event: CanonicalEvent): CanonicalUsage | undefined =>\n \"usage\" in event ? event.usage : undefined;\n\n/** Stable ordering: by sequence, then by timestamp, then by event id. */\nexport const compareEvents = (a: CanonicalEvent, b: CanonicalEvent): number =>\n a.sequence - b.sequence || a.occurredAt - b.occurredAt || a.eventId.localeCompare(b.eventId);\n","import { z } from \"zod\";\n\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema } from \"./primitives.js\";\n\n/** What kind of conversational or tool content a fact describes. */\nexport const contentKindSchema = z.enum([\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool-input\",\n \"tool-output\",\n \"error-message\",\n \"system-instruction\",\n \"attachment\",\n]);\nexport type ContentKind = z.infer<typeof contentKindSchema>;\n\nexport const contentRoleSchema = z.enum([\"user\", \"assistant\", \"system\", \"tool\", \"unknown\"]);\nexport type ContentRole = z.infer<typeof contentRoleSchema>;\n\n/**\n * How much of the original content this fact discloses.\n *\n * - `omitted`: no text at all (the default posture).\n * - `masked`: a shape-preserving mask; non-whitespace characters replaced.\n * - `redacted`: text with secret-looking spans replaced by a placeholder.\n * - `raw`: verbatim text. Only reachable through explicit opt-in.\n */\nexport const contentDisclosureSchema = z.enum([\"omitted\", \"masked\", \"redacted\", \"raw\"]);\nexport type ContentDisclosure = z.infer<typeof contentDisclosureSchema>;\n\nexport const CONTENT_HASH_PATTERN = /^sha256:[0-9a-f]{64}$/;\n\n/**\n * A privacy-safe description of content.\n *\n * Lengths and a stable hash are always present so consumers can measure and\n * correlate volume without receiving the content itself. `text` is present only\n * when the resolved privacy policy allows disclosure, and is produced solely by\n * the central privacy service.\n */\nexport const contentFactSchema = z.strictObject({\n kind: contentKindSchema,\n role: contentRoleSchema.optional(),\n /** Unicode code point count of the original content. */\n characterLength: z.number().int().min(0),\n /** UTF-8 byte length of the original content. */\n byteLength: z.number().int().min(0),\n /** Stable salted digest of the original content. */\n contentHash: z.string().regex(CONTENT_HASH_PATTERN),\n disclosure: contentDisclosureSchema,\n /** Disclosed text, bounded by the privacy policy. Absent when omitted. */\n text: z.string().optional(),\n /** True when `text` was cut short by the configured string bound. */\n truncated: z.boolean(),\n /** Number of secret-looking spans replaced while producing `text`. */\n secretsRedacted: z.number().int().min(0),\n /** Optional non-sensitive label, e.g. a MIME type or tool name. */\n label: nonEmptyStringSchema.optional(),\n});\nexport type ContentFact = z.infer<typeof contentFactSchema>;\n\nexport const contentFactsSchema = z.array(contentFactSchema).max(64);\n\n/**\n * Guard used in tests and at the sink boundary: an omitted fact must not carry\n * text, and a disclosing fact must carry it.\n */\nexport const isContentFactConsistent = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" ? fact.text === undefined : fact.text !== undefined;\n\n/**\n * A fact for a content kind the event can carry when the provider sent no text.\n *\n * Always `omitted` with zero length, regardless of the installation's content\n * mode: there is nothing to mask, redact, or export.\n */\nexport const isUnavailableContentFact = (fact: ContentFact): boolean =>\n fact.disclosure === \"omitted\" &&\n fact.text === undefined &&\n fact.characterLength === 0 &&\n fact.byteLength === 0;\n","import { z } from \"zod\";\n\nimport { nonEmptyStringSchema, workspaceIdSchema } from \"./primitives.js\";\n\n/**\n * Per-event workspace targeting (ADR 0008).\n *\n * A session's `workspace` is where the agent was *started*. An agent routinely\n * works somewhere else — in a linked git worktree beside the checkout it was\n * launched from — and the session-level identity cannot show that. A tool event\n * can: the file it edited, or the directory its shell command ran in, names the\n * worktree it actually touched.\n *\n * Two values model that, and the split between them is the privacy boundary:\n *\n * - {@link TargetHint} is what an adapter observed — local paths. It is an\n * in-process value only: it is never part of a {@link CanonicalEvent}, never\n * persisted, never exported. The core resolves it and drops it.\n * - {@link WorkspaceTarget} is what the core resolved — salted handles of the\n * worktree and its repository, the worktree's kind, the checked-out branch, and\n * what the evidence was. It travels on the event.\n */\n\n/**\n * What a target was derived from, strongest evidence first.\n *\n * - `tool-path` — a path the tool call itself named (an edited or read file, a\n * patch header).\n * - `shell-cwd` — the working directory the provider reports a shell command ran in.\n * - `session-cwd` — only the session's own directory was known; the event may\n * have reached elsewhere (e.g. a shell `cd`) without the provider saying so.\n */\nexport const targetSourceSchema = z.enum([\"tool-path\", \"shell-cwd\", \"session-cwd\"]);\nexport type TargetSource = z.infer<typeof targetSourceSchema>;\n\n/** Most paths one hint may name; a bound, not a sampling rule (all must agree). */\nexport const MAX_TARGET_HINT_PATHS = 8;\n\n/** Longest local path a hint may carry. Longer input is dropped, never truncated. */\nexport const MAX_TARGET_PATH_LENGTH = 4096;\n\nconst localPathSchema = z\n .string()\n .min(1)\n .max(MAX_TARGET_PATH_LENGTH)\n .refine((value) => !value.includes(\"\\u0000\"), \"path must not contain NUL\");\n\n/**\n * An adapter's observation of where a tool event pointed. **Carries local paths**\n * — in-process only, see the module note.\n *\n * Every path in one hint must resolve to the same worktree, or the event gets no\n * target at all: a patch touching two worktrees did not target either of them.\n */\nexport const targetHintSchema = z\n .strictObject({\n source: targetSourceSchema,\n paths: z.array(localPathSchema).min(1).max(MAX_TARGET_HINT_PATHS).readonly(),\n /** Absolute directory that relative `paths` resolve against. */\n baseDirectory: localPathSchema.optional(),\n })\n .readonly();\nexport type TargetHint = z.infer<typeof targetHintSchema>;\n\n/**\n * The weakest hint: the session's own directory. Every adapter gives it to a\n * session start and a prompt, and to a tool call that names no path.\n */\nexport const sessionCwdHint = (cwd: string | undefined): TargetHint | undefined =>\n cwd === undefined || cwd.length === 0 ? undefined : { source: \"session-cwd\", paths: [cwd] };\n\n/**\n * Whether a worktree is its repository's main checkout (`main`) or one added\n * beside it with `git worktree add` (`linked`).\n */\nexport const worktreeKindSchema = z.enum([\"main\", \"linked\"]);\nexport type WorktreeKind = z.infer<typeof worktreeKindSchema>;\n\n/**\n * The git worktree a tool event targeted. Exported; carries no path.\n *\n * `workspaceId` is derived exactly like a `git-root` workspace identity, so a\n * consumer holding the same salt can match it against one it derived itself.\n * `repositoryId` is the same derivation applied to the repository's main\n * worktree, so every worktree of one repository shares it — and for a main\n * worktree it equals `workspaceId`.\n */\nexport const workspaceTargetSchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n /** Branch checked out in that worktree; absent on a detached HEAD. */\n vcsBranchName: nonEmptyStringSchema.optional(),\n source: targetSourceSchema,\n /** `git-root` handle of the repository's main worktree; absent when there is none to name. */\n repositoryId: workspaceIdSchema.optional(),\n worktreeKind: worktreeKindSchema.optional(),\n })\n .readonly();\nexport type WorkspaceTarget = z.infer<typeof workspaceTargetSchema>;\n\n/**\n * Shape a provider's own subagent identifier must have to be exported.\n *\n * Identifier-shaped on purpose — no whitespace, no path separators — so a\n * malformed payload field cannot carry prose or a path onto the wire under an id\n * attribute. A value that does not fit is dropped, not repaired.\n */\nexport const SUBAGENT_ID_PATTERN = /^[A-Za-z0-9_.:@+=-]{1,256}$/;\nexport const subagentIdSchema = z.string().regex(SUBAGENT_ID_PATTERN);\nexport type SubagentId = z.infer<typeof subagentIdSchema>;\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import { z } from \"zod\";\n\nimport { attributesSchema, epochMillisSchema, type Attributes } from \"../model/primitives.js\";\nimport {\n describeErrorCode,\n errorPhaseSchema,\n errorSeveritySchema,\n failurePostureSchema,\n otelHookErrorCodeSchema,\n type ErrorPhase,\n type OtelHookErrorCode,\n} from \"./taxonomy.js\";\n\nexport * from \"./taxonomy.js\";\n\n/**\n * Serializable, privacy-safe description of a failure.\n *\n * `message` is a fixed-vocabulary summary derived from the code and phase, never\n * a provider or exception string, because exception messages routinely contain\n * prompt text, file paths, and credentials. `details` is restricted to attribute\n * primitives for the same reason.\n */\nexport const otelHookErrorInfoSchema = z.strictObject({\n code: otelHookErrorCodeSchema,\n severity: errorSeveritySchema,\n phase: errorPhaseSchema,\n posture: failurePostureSchema,\n retryable: z.boolean(),\n message: z.string().min(1).max(512),\n details: attributesSchema.optional(),\n occurredAt: epochMillisSchema.optional(),\n});\nexport type OtelHookErrorInfo = z.infer<typeof otelHookErrorInfoSchema>;\n\nexport type CreateErrorInfoInput = {\n readonly code: OtelHookErrorCode;\n readonly phase: ErrorPhase;\n /** Short, non-sensitive detail, e.g. `\"2 adapters matched\"`. */\n readonly detail?: string;\n readonly details?: Attributes;\n readonly occurredAt?: number;\n};\n\nexport const createErrorInfo = (input: CreateErrorInfoInput): OtelHookErrorInfo => {\n const descriptor = describeErrorCode(input.code);\n const message =\n input.detail === undefined\n ? `${input.code} during ${input.phase}: ${descriptor.summary}`\n : `${input.code} during ${input.phase}: ${input.detail}`;\n return otelHookErrorInfoSchema.parse({\n code: descriptor.code,\n severity: descriptor.severity,\n phase: input.phase,\n posture: descriptor.posture,\n retryable: descriptor.retryable,\n message: message.slice(0, 512),\n ...(input.details === undefined ? {} : { details: input.details }),\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n\nexport class OtelHookError extends Error {\n public readonly info: OtelHookErrorInfo;\n\n public constructor(info: OtelHookErrorInfo) {\n super(info.message);\n this.name = \"OtelHookError\";\n this.info = info;\n }\n\n public static of(input: CreateErrorInfoInput): OtelHookError {\n return new OtelHookError(createErrorInfo(input));\n }\n}\n\nexport const isOtelHookError = (value: unknown): value is OtelHookError =>\n value instanceof OtelHookError;\n\n/**\n * Describe an arbitrary thrown value without disclosing its message.\n *\n * Only the constructor name crosses the boundary; the presence of a message is\n * reported as a boolean so operators can tell \"threw nothing useful\" from\n * \"threw something we deliberately did not log\".\n */\nexport const describeThrown = (\n thrown: unknown,\n): { readonly errorName: string; readonly hasMessage: boolean } => {\n if (thrown instanceof Error) {\n return {\n errorName: thrown.name.slice(0, 64) || \"Error\",\n hasMessage: typeof thrown.message === \"string\" && thrown.message.length > 0,\n };\n }\n return { errorName: typeof thrown, hasMessage: false };\n};\n\n/** Convert an unexpected throw into privacy-safe error info. */\nexport const errorInfoFromThrown = (\n thrown: unknown,\n input: { readonly code?: OtelHookErrorCode; readonly phase: ErrorPhase; readonly occurredAt?: number },\n): OtelHookErrorInfo => {\n if (isOtelHookError(thrown)) {\n return thrown.info;\n }\n const described = describeThrown(thrown);\n return createErrorInfo({\n code: input.code ?? \"internal-error\",\n phase: input.phase,\n detail: `contained ${described.errorName}`,\n details: { \"error.name\": described.errorName, \"error.has_message\": described.hasMessage },\n ...(input.occurredAt === undefined ? {} : { occurredAt: input.occurredAt }),\n });\n};\n","import { OtelHookError } from \"../errors/index.js\";\nimport {\n canonicalEventSchema,\n isTargetedEvent,\n type CanonicalEvent,\n type CompactionPerformedEvent,\n type ErrorRaisedEvent,\n type GenerationEndEvent,\n type GenerationStartEvent,\n type PromptSubmittedEvent,\n type SessionEndEvent,\n type SessionStartEvent,\n type SubagentEndEvent,\n type SubagentStartEvent,\n type ToolEndEvent,\n type ToolStartEvent,\n} from \"../model/events.js\";\nimport type { InvocationIdentity } from \"../model/identity.js\";\nimport type { EventId } from \"../model/primitives.js\";\nimport { subagentIdSchema, targetHintSchema, type TargetHint } from \"../model/target.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport type { ProviderContext } from \"./adapter.js\";\n\n/** Fields the factory supplies; an adapter never sets them itself. */\ntype ManagedFields =\n | \"schemaVersion\"\n | \"eventId\"\n | \"invocationId\"\n | \"sessionId\"\n | \"sequence\"\n | \"provenance\"\n | \"workspace\"\n | \"extensions\"\n | \"subagentId\"\n | \"contextAttributes\"\n | \"target\"\n | \"occurredAt\";\n\ntype Draft<TEvent extends CanonicalEvent> = Omit<TEvent, ManagedFields> & {\n /** Defaults to the clock reading at build time. */\n readonly occurredAt?: number;\n /** Sanitized and namespace-checked before it is attached. */\n readonly extensions?: Readonly<Record<string, unknown>>;\n /** Mixed into the derived event id when one event type repeats. */\n readonly idDiscriminator?: string;\n /**\n * Where an event pointed, for the core to resolve into a `target`\n * (ADR 0008). Accepted on `TARGETED_EVENT_TYPES` drafts only; never placed\n * on the event itself.\n */\n readonly targetHint?: TargetHint;\n};\n\nexport type CanonicalEventDraft =\n | Draft<SessionStartEvent>\n | Draft<SessionEndEvent>\n | Draft<PromptSubmittedEvent>\n | Draft<GenerationStartEvent>\n | Draft<GenerationEndEvent>\n | Draft<ToolStartEvent>\n | Draft<ToolEndEvent>\n | Draft<SubagentStartEvent>\n | Draft<SubagentEndEvent>\n | Draft<CompactionPerformedEvent>\n | Draft<ErrorRaisedEvent>;\n\n/**\n * Helper adapters use to emit canonical events.\n *\n * It owns every field that must stay consistent across an invocation —\n * identity, provenance, sequence numbering, derived event ids — so an adapter\n * cannot accidentally renumber a sequence or attach the wrong session. Sequences\n * are consecutive from `sequenceBase`, which keeps derived ids stable on replay.\n */\nexport interface EventFactory {\n build(draft: CanonicalEventDraft): CanonicalEvent;\n /** Events built so far, in build order. */\n events(): readonly CanonicalEvent[];\n /** Next sequence number that will be assigned. */\n nextSequence(): number;\n /** Extension keys rejected during building, for diagnostics. */\n droppedExtensionKeys(): readonly string[];\n /**\n * Target hints attached to built targeted events, keyed by event id. In-process\n * only: hand this to the core through `ProviderParseResult.targetHints`.\n */\n targetHints(): ReadonlyMap<EventId, TargetHint>;\n}\n\nexport type EventFactoryInput = {\n readonly identity: InvocationIdentity;\n readonly sequenceBase: number;\n readonly context: ProviderContext;\n /**\n * The provider's own id for the subagent this invocation runs inside, stamped\n * on every event built. A value that is not identifier-shaped is dropped rather\n * than failing the event: the event is still true without it.\n */\n readonly subagentId?: string;\n};\n\nexport const createEventFactory = (input: EventFactoryInput): EventFactory => {\n const { identity, context } = input;\n const built: CanonicalEvent[] = [];\n const dropped: string[] = [];\n const hints = new Map<EventId, TargetHint>();\n let sequence = input.sequenceBase;\n const subagentId =\n input.subagentId !== undefined && subagentIdSchema.safeParse(input.subagentId).success\n ? input.subagentId\n : undefined;\n\n return {\n build: (draft: CanonicalEventDraft): CanonicalEvent => {\n const { occurredAt, extensions, idDiscriminator, targetHint, ...drafted } = draft;\n // Managed fields are stripped even if an untyped caller supplied them: a\n // target is only ever the core's resolution, never an adapter's claim.\n const rest: Omit<typeof drafted, \"target\" | \"subagentId\"> = { ...drafted };\n delete (rest as { target?: unknown }).target;\n delete (rest as { subagentId?: unknown }).subagentId;\n // Session context is stamped by the core after parsing, never by an adapter.\n delete (rest as { contextAttributes?: unknown }).contextAttributes;\n\n const sanitized =\n extensions === undefined\n ? { extensions: {}, droppedKeys: [] as readonly string[] }\n : context.privacy.sanitizeExtensions(extensions);\n dropped.push(...sanitized.droppedKeys);\n\n const currentSequence = sequence;\n sequence += 1;\n\n const candidate = {\n ...rest,\n schemaVersion: CANONICAL_SCHEMA_VERSION,\n eventId: context.ids.newEventId({\n invocationId: identity.invocationId,\n sequence: currentSequence,\n eventType: rest.type,\n ...(idDiscriminator === undefined ? {} : { discriminator: idDiscriminator }),\n }),\n invocationId: identity.invocationId,\n sessionId: identity.sessionId,\n sequence: currentSequence,\n occurredAt: occurredAt ?? context.clock.now(),\n provenance: identity.provenance,\n workspace: identity.workspace,\n ...(subagentId === undefined ? {} : { subagentId }),\n extensions: sanitized.extensions,\n };\n\n const parsed = canonicalEventSchema.safeParse(candidate);\n if (!parsed.success) {\n throw OtelHookError.of({\n code: \"schema-validation-failed\",\n phase: \"parsing\",\n detail: `event ${rest.type} rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: { \"event.type\": rest.type, \"event.sequence\": currentSequence },\n });\n }\n built.push(parsed.data);\n if (targetHint !== undefined && isTargetedEvent(parsed.data)) {\n const hint = targetHintSchema.safeParse(targetHint);\n if (hint.success) {\n hints.set(parsed.data.eventId, hint.data);\n }\n }\n return parsed.data;\n },\n events: (): readonly CanonicalEvent[] => [...built],\n nextSequence: (): number => sequence,\n droppedExtensionKeys: (): readonly string[] => [...dropped],\n targetHints: (): ReadonlyMap<EventId, TargetHint> => new Map(hints),\n };\n};\n","import type { DetectionPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport {\n DETECTION_CONFIDENCE_RANK,\n type ProviderId,\n} from \"../model/primitives.js\";\nimport {\n providerDetectionSchema,\n unknownDetection,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"./adapter.js\";\n\nexport type DetectionCandidate = {\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n};\n\nexport type RegistryDetectionResult =\n | {\n readonly status: \"selected\";\n readonly adapter: ProviderAdapter;\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"unknown\";\n readonly reason:\n | \"no-adapters-registered\"\n | \"no-candidates\"\n | \"below-minimum-confidence\"\n | \"provider-not-allowed\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n }\n | {\n readonly status: \"ambiguous\";\n readonly detection: ProviderDetection;\n readonly candidates: readonly DetectionCandidate[];\n readonly errors: readonly OtelHookErrorInfo[];\n };\n\n/**\n * Immutable set of adapters.\n *\n * A registry is a value passed to the runtime, not a mutable module-level\n * singleton: two hooks in one process may legitimately be configured with\n * different adapter sets, and a global would let one silently reconfigure the\n * other.\n */\nexport interface ProviderRegistry {\n readonly adapters: readonly ProviderAdapter[];\n get(id: string): ProviderAdapter | undefined;\n detect(\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult;\n}\n\nexport const createProviderRegistry = (\n adapters: readonly ProviderAdapter[],\n): ProviderRegistry => {\n const byId = new Map<string, ProviderAdapter>();\n for (const adapter of adapters) {\n if (byId.has(adapter.id)) {\n throw createDuplicateAdapterError(adapter.id);\n }\n byId.set(adapter.id, adapter);\n }\n const frozen = Object.freeze([...adapters]);\n\n return {\n adapters: frozen,\n get: (id: string): ProviderAdapter | undefined => byId.get(id),\n detect: (\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n ): RegistryDetectionResult => {\n const errors: OtelHookErrorInfo[] = [];\n const candidates: DetectionCandidate[] = [];\n\n if (frozen.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-adapters-registered\",\n detection: unknownDetection([\"no adapters registered\"]),\n candidates,\n errors,\n };\n }\n\n // Reasons from adapters that recognized the callback well enough to\n // explain why they declined it — as opposed to one that never looked at\n // this payload shape at all. Kept only for the \"no-candidates\" outcome\n // below: a payload every adapter genuinely ignores should still read as\n // the generic message, but a payload one adapter recognized and rejected\n // (e.g. Cursor's own envelope contract) must not be flattened into that\n // same generic message — that is the difference between \"provider\n // unknown\" and \"provider known, payload rejected for a stated reason\",\n // and only the raw per-adapter `detect()` result carries the latter.\n const nearMisses: string[] = [];\n\n for (const adapter of frozen) {\n let detection: ProviderDetection;\n try {\n detection = providerDetectionSchema.parse(adapter.detect(input, context));\n } catch (thrown) {\n // A misbehaving adapter must not suppress its peers.\n errors.push(errorInfoFromThrown(thrown, { code: \"provider-adapter-failure\", phase: \"detection\" }));\n continue;\n }\n if (detection.confidence === \"none\") {\n for (const reason of detection.reasons) {\n const prefixed = `${adapter.id}: ${reason}`;\n nearMisses.push(prefixed.length <= 160 ? prefixed : `${prefixed.slice(0, 159)}…`);\n }\n continue;\n }\n if (detection.providerId !== adapter.id) {\n errors.push(\n createErrorInfo({\n code: \"provider-adapter-failure\",\n phase: \"detection\",\n detail: `adapter ${adapter.id} claimed provider id ${detection.providerId}`,\n details: { \"adapter.id\": adapter.id, \"detection.provider_id\": detection.providerId },\n }),\n );\n continue;\n }\n candidates.push({ adapter, detection });\n }\n\n if (candidates.length === 0) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(nearMisses.length === 0 ? undefined : nearMisses.slice(0, 8)),\n candidates,\n errors,\n };\n }\n\n const bestRank = Math.max(\n ...candidates.map((candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence]),\n );\n const best = candidates.filter(\n (candidate) => DETECTION_CONFIDENCE_RANK[candidate.detection.confidence] === bestRank,\n );\n\n if (best.length > 1) {\n return {\n status: \"ambiguous\",\n detection: unknownDetection([\n `${best.length} adapters matched at equal confidence`,\n ...best.map((candidate) => `candidate ${candidate.adapter.id}`),\n ]),\n candidates,\n errors,\n };\n }\n\n const [winner] = best;\n if (winner === undefined) {\n return {\n status: \"unknown\",\n reason: \"no-candidates\",\n detection: unknownDetection(),\n candidates,\n errors,\n };\n }\n\n if (bestRank < DETECTION_CONFIDENCE_RANK[policy.minimumConfidence]) {\n return {\n status: \"unknown\",\n reason: \"below-minimum-confidence\",\n detection: unknownDetection([\n `best confidence ${winner.detection.confidence} is below required ${policy.minimumConfidence}`,\n ]),\n candidates,\n errors,\n };\n }\n\n if (\n policy.allowedProviderIds.length > 0 &&\n !policy.allowedProviderIds.includes(winner.adapter.id)\n ) {\n return {\n status: \"unknown\",\n reason: \"provider-not-allowed\",\n detection: unknownDetection([`provider ${winner.adapter.id} is not in the allow-list`]),\n candidates,\n errors,\n };\n }\n\n return {\n status: \"selected\",\n adapter: winner.adapter,\n detection: winner.detection,\n candidates,\n errors,\n };\n },\n };\n};\n\nconst createDuplicateAdapterError = (id: ProviderId): Error =>\n new Error(`duplicate provider adapter id: ${id}`);\n\n/**\n * Built-in adapters.\n *\n * Empty by design in the core package: provider support is added by dedicated\n * adapter modules, and the core must remain testable without any of them.\n */\nexport const BUILT_IN_PROVIDERS: readonly ProviderAdapter[] = Object.freeze([]);\n","import type { ProviderCapabilities } from \"../adapter.js\";\n\n/**\n * What this adapter can actually observe from Claude Code hooks.\n *\n * Every value here is confirmed against Claude Code 2.1.220 — the CLI's own\n * hook-input schemas for what a callback carries, and 4,999 real `usage` objects\n * for what the counters mean. docs/claude-code-usage-contract.md records the\n * observations; the summary:\n *\n * - `reportsCachedInput`/`reportsCacheCreation` are true because the payload\n * schema *accepts* Anthropic's `message.usage` shape when a wrapping harness\n * attaches it. No hook callback in the protocol carries a token counter, and\n * this adapter never reads the transcript to find them; `transcript.ts` is the\n * bounded helper a wrapper calls to attach them (issue #64).\n * - `cacheCreationAccounting` is `included-in-input` because `input_tokens` is\n * the fresh portion only, so the adapter folds all three input buckets into one\n * inclusive total (see `usage.ts`).\n * - `reportsReasoningOutput` and `reportsProviderTotal` are false as an\n * **explicit exclusion, not an unknown**: 0 of 4,999 real usage objects carried\n * any reasoning-token or total-token key. Anthropic bills thinking tokens\n * inside `output_tokens` with nothing distinguishing them, and reports no grand\n * total for a canonical total to agree or disagree with.\n *\n * `contextTokensBefore` is excluded on the same footing, and has no capability\n * flag of its own to say so: neither compaction callback reports a context size,\n * so there is no figure to carry across the `PreCompact`/`PostCompact` boundary.\n * `PreCompact` states the exclusion when a harness attaches one anyway\n * (`events.ts`), and `ADAPTER-NOTE-002` records it.\n */\nexport const CLAUDE_CODE_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\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 ] as const),\n usageTemporality: \"delta\",\n reportsCachedInput: true,\n reportsCacheCreation: true,\n cacheCreationAccounting: \"included-in-input\",\n reportsReasoningOutput: false,\n reportsProviderTotal: false,\n reportsCost: false,\n emitsSubagentEvents: true,\n emitsCompactionEvents: true,\n // The hook is telemetry-only and must never influence Claude Code's own\n // permission/continuation decisions (ADR 0004: fail-open).\n requiresHookResponse: false,\n // Tool, subagent, and prompt callbacks carry a replay-stable id, and so does\n // the once-per-prompt `Stop` (`stop_hook_active: false`). Session, compaction,\n // and continuation stops do not. See `./delivery.ts` for which and why.\n deliveryIdentifier: \"partial\",\n});\n","import { z } from \"zod\";\n\n/**\n * Raw Claude Code hook payload shapes.\n *\n * Field names and event names are taken from Claude Code's published hooks\n * reference (`code.claude.com/docs/en/hooks`). Objects are intentionally\n * non-strict: an unrecognized field is ignored rather than rejected, so a\n * protocol addition does not break detection or parsing. Discriminants\n * (`hook_event_name`, and the enum-shaped fields we do constrain) are strict.\n */\n\n/** Fields Claude Code includes on effectively every hook invocation. */\nconst commonFields = {\n session_id: z.string().min(1),\n transcript_path: z.string().min(1).optional(),\n cwd: z.string().min(1).optional(),\n permission_mode: z.string().min(1).optional(),\n /** Correlates a hook firing with the user prompt that triggered it (Claude Code v2.1.196+). */\n prompt_id: z.string().min(1).optional(),\n /** Present when the hook fired while running inside a subagent. */\n agent_id: z.string().min(1).optional(),\n agent_type: z.string().min(1).optional(),\n};\n\n/**\n * Cache-creation tokens split by cache TTL.\n *\n * A *breakdown* of `cache_creation_input_tokens`, not tokens beside it: the two\n * sub-buckets summed to that counter in 4,999 of 4,999 real usage objects. See\n * `usage.ts` for why they are verified and never added, and\n * docs/claude-code-usage-contract.md (finding 3) for the capture.\n */\nexport const claudeCacheCreationSchema = z.object({\n ephemeral_5m_input_tokens: z.number().int().min(0).optional(),\n ephemeral_1h_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * One model request inside a turn that took more than one.\n *\n * Also a breakdown: the per-iteration counters summed to the outer counters\n * exactly, for all four fields, in every capture (finding 4).\n */\nexport const claudeUsageIterationSchema = z.object({\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n});\n\n/**\n * Anthropic Messages API usage shape, as a wrapping harness may attach it\n * after correlating a hook firing with the transcript.\n *\n * **No Claude Code hook callback carries this object.** Confirmed against the\n * CLI's own hook-input schemas at 2.1.220: not `Stop`, not `SubagentStop`, not\n * `PostCompact` — no hook event in the protocol reports a token counter at all\n * (docs/claude-code-usage-contract.md, finding 1). The tokens exist only at\n * `message.usage` in the transcript, and this adapter never reads the transcript\n * itself (AGENTS.md and ADR 0003: an adapter has no filesystem handle). So the\n * field is accepted only when a caller has already placed it on the payload, and\n * the shape mirrors `message.usage` exactly so a harness can attach what it read\n * without reshaping it — `readClaudeTranscriptTurn` / `attachClaudeTranscriptTurn`\n * (`transcript.ts`) are the bounded helper a wrapper can call to do that.\n *\n * `input_tokens` is the **fresh** portion of the prompt only; cache reads and\n * cache writes are separate, additive buckets (finding 2). `usage.ts` documents\n * the fold that turns those three into the canonical inclusive total.\n */\nexport const claudeUsageSchema = z.object({\n input_tokens: z.number().int().min(0),\n output_tokens: z.number().int().min(0),\n cache_creation_input_tokens: z.number().int().min(0).optional(),\n cache_read_input_tokens: z.number().int().min(0).optional(),\n cache_creation: claudeCacheCreationSchema.optional(),\n iterations: z.array(claudeUsageIterationSchema).optional(),\n /**\n * Counters the canonical model has a home for but Claude Code never reports:\n * 0 of 4,999 real usage objects carried either (finding 5).\n *\n * Named here rather than left to the object's forward-compatible looseness so\n * that a harness attaching one gets told it was excluded, instead of watching\n * it vanish. See `CLAUDE_EXCLUDED_USAGE_COUNTERS`.\n */\n total_tokens: z.number().int().min(0).optional(),\n reasoning_output_tokens: z.number().int().min(0).optional(),\n});\nexport type ClaudeUsage = z.infer<typeof claudeUsageSchema>;\n\nexport const sessionStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionStart\"),\n /** Matcher values: startup | resume | clear | compact | fork. Forward-compatible: any string. */\n source: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n session_title: z.string().min(1).optional(),\n});\nexport type SessionStartPayload = z.infer<typeof sessionStartPayloadSchema>;\n\nexport const sessionEndPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SessionEnd\"),\n /** Current Claude Code field; values include clear, logout, prompt_input_exit, and other. */\n reason: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n end_reason: z.string().min(1).optional(),\n});\nexport type SessionEndPayload = z.infer<typeof sessionEndPayloadSchema>;\n\nexport const userPromptSubmitPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"UserPromptSubmit\"),\n prompt: z.string(),\n});\nexport type UserPromptSubmitPayload = z.infer<typeof userPromptSubmitPayloadSchema>;\n\nexport const preToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PreToolUsePayload = z.infer<typeof preToolUsePayloadSchema>;\n\nexport const postToolUsePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUse\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_response: z.unknown(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUsePayload = z.infer<typeof postToolUsePayloadSchema>;\n\nexport const postToolUseFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostToolUseFailure\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n // Optional: a failure that names no message still ends its tool call. The\n // `error` spelling Claude Code 2.1.x sends is folded onto it by\n // `normalizeClaudeHookPayload`.\n tool_error: z.unknown().optional(),\n tool_use_id: z.string().min(1),\n});\nexport type PostToolUseFailurePayload = z.infer<typeof postToolUseFailurePayloadSchema>;\n\nexport const permissionRequestPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PermissionRequest\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().min(1),\n});\nexport type PermissionRequestPayload = z.infer<typeof permissionRequestPayloadSchema>;\n\nexport const subagentStartPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStart\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n});\nexport type SubagentStartPayload = z.infer<typeof subagentStartPayloadSchema>;\n\nexport const subagentStopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"SubagentStop\"),\n agent_type: z.string().min(1),\n agent_id: z.string().min(1),\n last_assistant_message: z.string().optional(),\n /** True when this stop fired because a hook continued the subagent's turn. */\n stop_hook_active: z.boolean().optional(),\n /**\n * The subagent run's tokens since its previous stop — harness- or\n * enricher-supplied, never upstream. Reported on the subagent's own\n * generation, never on the parent turn (issue #68).\n */\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: the subagent's model, from its transcript. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type SubagentStopPayload = z.infer<typeof subagentStopPayloadSchema>;\n\n/**\n * Compaction callbacks.\n *\n * The upstream contract at 2.1.220 is `PreCompact { trigger, custom_instructions }`\n * and `PostCompact { trigger, compact_summary }`. **Neither reports a token\n * count** — no context size before or after, no dropped-message count\n * (docs/claude-code-usage-contract.md, finding 6). The counters below are\n * accepted for a wrapping harness that computed them; they are not a claim that\n * Claude Code sends them, and `capabilities.ts` excludes `contextTokensBefore`\n * accordingly.\n *\n * `custom_instructions` and `compact_summary` are deliberately absent. The\n * summary is a model-generated précis of the conversation — content — and\n * compaction telemetry needs the trigger and the sizes, not the text. Both are\n * ignored by the object's forward-compatible looseness rather than read and\n * screened, so there is no path by which they could reach an event.\n */\nexport const preCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PreCompact\"),\n /** Upstream values: manual | auto. Forward-compatible: any string. */\n trigger: z.string().min(1).optional(),\n /** Compatibility alias emitted by older wrappers and hook integrations. */\n compact_trigger: z.string().min(1).optional(),\n /**\n * Harness-supplied, never upstream. Reported as an explicit exclusion rather\n * than carried across the process boundary: see `events.ts`.\n */\n context_tokens_before: z.number().int().min(0).optional(),\n estimated_tokens_removed: z.number().int().min(0).optional(),\n});\nexport type PreCompactPayload = z.infer<typeof preCompactPayloadSchema>;\n\nexport const postCompactPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"PostCompact\"),\n trigger: z.string().min(1).optional(),\n compact_trigger: z.string().min(1).optional(),\n /** Harness-supplied, never upstream; accepted here because one callback carries both. */\n context_tokens_before: z.number().int().min(0).optional(),\n context_tokens_after: z.number().int().min(0).optional(),\n dropped_message_count: z.number().int().min(0).optional(),\n usage: claudeUsageSchema.optional(),\n});\nexport type PostCompactPayload = z.infer<typeof postCompactPayloadSchema>;\n\nexport const stopPayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"Stop\"),\n /**\n * Interactive Stop field (Claude Code ≥ 2.1.47). Print / `-p` / Agent SDK\n * result messages use `result` instead; `events.ts` reads both (and camelCase\n * `lastAssistantMessage`) through `extractClaudeAssistantText`.\n */\n last_assistant_message: z.string().optional(),\n /** Print / `-p` JSON result field; accepted so a harness can attach it as-is. */\n result: z.string().optional(),\n /**\n * True when this stop fired because a hook continued the turn.\n *\n * Required upstream, optional here. It is what separates the once-per-prompt\n * stop from a continuation stop, which is what lets `delivery.ts` deduplicate\n * the former without suppressing the latter.\n */\n stop_hook_active: z.boolean().optional(),\n usage: claudeUsageSchema.optional(),\n /**\n * The model that answered this turn — harness-supplied, never upstream.\n *\n * Claude Code's `Stop` carries no model id; the per-turn model sits only at\n * `message.model` in the transcript, beside `message.usage`. A wrapping harness\n * that read it (for instance with `readClaudeTranscriptTurn`) attaches it here\n * with `usage`, and it becomes the generation's response model. An unusable\n * value (empty, over 256 characters, not a string) is dropped rather than\n * failing the whole payload: the turn is still worth reporting without it.\n */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /**\n * Harness-supplied, never upstream: whether `usage` covers only part of the\n * turn. `true` when it is the last model request alone (the tail fallback),\n * `false` when it sums every request since the previous stop. Exported as\n * `otelhook.usage.partial`; absent means the attacher did not say.\n */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopPayload = z.infer<typeof stopPayloadSchema>;\n\nexport const stopFailurePayloadSchema = z.object({\n ...commonFields,\n hook_event_name: z.literal(\"StopFailure\"),\n /**\n * Matcher values: rate_limit | overloaded | authentication_failed |\n * oauth_org_not_allowed | billing_error | invalid_request | model_not_found\n * | server_error | max_output_tokens | unknown.\n */\n error_type: z.string().min(1),\n error_message: z.string().optional(),\n usage: claudeUsageSchema.optional(),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.model`. */\n model: z.string().min(1).max(256).optional().catch(undefined),\n /** Harness-supplied, never upstream: see `stopPayloadSchema.usage_partial`. */\n usage_partial: z.boolean().optional().catch(undefined),\n});\nexport type StopFailurePayload = z.infer<typeof stopFailurePayloadSchema>;\n\nexport const claudeHookPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n userPromptSubmitPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n permissionRequestPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n postCompactPayloadSchema,\n stopPayloadSchema,\n stopFailurePayloadSchema,\n]);\nexport type ClaudeHookPayload = z.infer<typeof claudeHookPayloadSchema>;\n\n/** Every `hook_event_name` this adapter recognizes. */\nexport const CLAUDE_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"SessionEnd\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"PermissionRequest\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"PreCompact\",\n \"PostCompact\",\n \"Stop\",\n \"StopFailure\",\n] as const;\nexport type ClaudeHookEventName = (typeof CLAUDE_HOOK_EVENT_NAMES)[number];\n\n/**\n * Minimal shape identity resolution needs. Deliberately looser than\n * {@link claudeHookPayloadSchema}: a payload that is missing an\n * event-specific field (e.g. `PreToolUse` without `tool_use_id`) can still be\n * attributed to a session, so the deeper failure surfaces from `parse`\n * instead of silently declining attribution.\n */\nexport const claudeIdentityFieldsSchema = z.object({\n session_id: z.string().min(1),\n hook_event_name: z.string().min(1),\n cwd: z.string().min(1).optional(),\n prompt_id: z.string().min(1).optional(),\n agent_id: z.string().min(1).optional(),\n tool_use_id: z.string().min(1).optional(),\n /** Read by `delivery.ts` to tell a once-per-prompt stop from a continuation. */\n stop_hook_active: z.boolean().optional(),\n});\nexport type ClaudeIdentityFields = z.infer<typeof claudeIdentityFieldsSchema>;\n","import { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\nimport { claudeUsageSchema, type ClaudeUsage } from \"./schema.js\";\n\nexport type ClaudeUsageNormalization = {\n readonly usage?: CanonicalUsage;\n readonly warnings: readonly string[];\n};\n\n/**\n * Counters this adapter deliberately does not read.\n *\n * Both are absent from Claude Code's usage shape — 0 of 4,999 real usage objects\n * carried either (docs/claude-code-usage-contract.md, finding 5) — and both have\n * a home in the canonical model, which is exactly why reading a\n * harness-supplied one would be wrong: `providerTotalAgreement` would start\n * reporting `agrees`/`disagrees` for a provider that reports no total, and\n * `reasoningOutputTokens` would carry a figure `reportsReasoningOutput: false`\n * says does not exist. A consumer's ability to tell \"not reported\" from \"zero\"\n * depends on the capability declaration staying true.\n *\n * So the field is excluded and *said out loud*, rather than silently dropped.\n */\nexport const CLAUDE_EXCLUDED_USAGE_COUNTERS = Object.freeze({\n total_tokens:\n \"usage.total_tokens is outside Claude Code's usage contract (capability reportsProviderTotal=false): \" +\n \"it is not read, so providerTotalAgreement stays \\\"unreported\\\"\",\n reasoning_output_tokens:\n \"usage.reasoning_output_tokens is outside Claude Code's usage contract (capability \" +\n \"reportsReasoningOutput=false): Anthropic bills thinking tokens inside output_tokens with no separate \" +\n \"counter, so it is not read and reasoningOutputTokens stays 0\",\n});\n\n/** The four counters `usage.iterations[]` itemizes, and the outer fields they must match. */\nconst ITERATION_COUNTERS = [\n \"input_tokens\",\n \"output_tokens\",\n \"cache_read_input_tokens\",\n \"cache_creation_input_tokens\",\n] as const;\n\n/**\n * Cache-creation tokens split by TTL, or `undefined` when the split is absent.\n *\n * The two sub-buckets summed to `cache_creation_input_tokens` in every capture,\n * so this is a *breakdown* to reconcile against, never an addend.\n */\nconst ttlSplitTotal = (raw: ClaudeUsage): number | undefined => {\n const split = raw.cache_creation;\n if (split === undefined) {\n return undefined;\n }\n return (split.ephemeral_5m_input_tokens ?? 0) + (split.ephemeral_1h_input_tokens ?? 0);\n};\n\n/**\n * Settle on one cache-creation figure from the two places it can be stated.\n *\n * The explicit counter wins when both are present: it is the billed total, and\n * preferring a sum of parts over a stated whole would let a future third TTL\n * bucket silently deflate it. A disagreement is reported rather than resolved\n * quietly, because only one of the two numbers can be the billing story.\n */\nconst resolveCacheCreationTokens = (raw: ClaudeUsage, warnings: string[]): number => {\n const declared = raw.cache_creation_input_tokens;\n const split = ttlSplitTotal(raw);\n if (declared === undefined) {\n // Only the TTL split was attached. Deriving the total is the whole point of\n // accepting the sub-object: the tokens were reported, just itemized.\n return split ?? 0;\n }\n if (split !== undefined && split !== declared) {\n warnings.push(\n `usage.cache_creation TTL buckets sum to ${String(split)} but ` +\n `usage.cache_creation_input_tokens reports ${String(declared)}; the explicit counter is used and the ` +\n `buckets are never added to it`,\n );\n }\n return declared;\n};\n\n/**\n * Reconcile `usage.iterations[]` against the outer counters without adding it.\n *\n * A multi-request turn itemizes the same tokens per model request, and the\n * per-iteration figures summed to the outer ones exactly in every capture. Adding\n * a breakdown to its own total is the archetypal double-count — it would double\n * every counter of every turn — so the sums are *checked* and a disagreement is\n * reported, which is the only reading under which either number could be wrong.\n */\nconst auditIterations = (\n raw: ClaudeUsage,\n cacheCreationInputTokens: number,\n warnings: string[],\n): void => {\n const iterations = raw.iterations;\n if (iterations === undefined || iterations.length === 0) {\n return;\n }\n const outer: Readonly<Record<(typeof ITERATION_COUNTERS)[number], number>> = {\n input_tokens: raw.input_tokens,\n output_tokens: raw.output_tokens,\n cache_read_input_tokens: raw.cache_read_input_tokens ?? 0,\n cache_creation_input_tokens: cacheCreationInputTokens,\n };\n for (const counter of ITERATION_COUNTERS) {\n const summed = iterations.reduce((total, iteration) => total + (iteration[counter] ?? 0), 0);\n if (summed !== outer[counter]) {\n warnings.push(\n `usage.iterations[].${counter} sums to ${String(summed)} but usage.${counter} reports ` +\n `${String(outer[counter])}; the outer counter is used and per-iteration figures are never added to it`,\n );\n }\n }\n};\n\nconst auditExcludedCounters = (raw: ClaudeUsage, warnings: string[]): void => {\n if (raw.total_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.total_tokens);\n }\n if (raw.reasoning_output_tokens !== undefined) {\n warnings.push(CLAUDE_EXCLUDED_USAGE_COUNTERS.reasoning_output_tokens);\n }\n};\n\n/**\n * `normalizeUsage` notes when a caller declared a cache-creation accounting mode\n * on a snapshot with zero cache-creation tokens. That note is aimed at a caller\n * choosing the mode per observation; this adapter's mode is a fixed property of\n * the provider, so on any turn that wrote nothing to cache the note restates the\n * design rather than reporting anything. It would fire on most turns and bury the\n * warnings that do mean something, so it is dropped here — by prefix, so a note\n * this adapter has not considered still reaches the caller.\n */\nconst ACCOUNTING_RETAINED_NOTE_PREFIX = \"cacheCreationAccounting=\";\n\nconst forwardableNotes = (notes: readonly string[]): readonly string[] =>\n notes.filter((note) => !note.startsWith(ACCOUNTING_RETAINED_NOTE_PREFIX));\n\n/**\n * Normalize Anthropic's on-wire usage shape into canonical usage.\n *\n * `input_tokens` is the *fresh* portion of the prompt only: cache reads and cache\n * writes are separate, additive buckets. Confirmed against real captures rather\n * than assumed — across 4,999 usage objects `input_tokens` stayed within\n * 1..5,656 while `cache_read_input_tokens` reached 713,543\n * (docs/claude-code-usage-contract.md, finding 2). The canonical model instead\n * wants an inclusive `inputTokens`, so this folds all three into one total and\n * marks cache creation `included-in-input` — `uncachedInputTokens` then falls out\n * to exactly Anthropic's own `input_tokens`.\n *\n * The fold is what makes the canonical buckets **non-overlapping by\n * construction**: each subset is one of the addends of the total it is a subset\n * of, so no subset can exceed its total and no bucket is counted twice. That\n * holds structurally, not by a range check a provider change could invalidate.\n * The two places tokens are *itemized* rather than reported — the cache-creation\n * TTL split and `iterations[]` — are reconciled against the totals and never\n * added, which is where a double-count would otherwise come from within a single\n * callback. Double-counting *across* callbacks is the delivery layer's job; see\n * `delivery.ts`.\n *\n * Each usage snapshot corresponds to a single turn, subagent invocation, or\n * compaction — never a running session total — so it is always reported as a\n * `delta` observation.\n */\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst asNonNegativeInt = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isInteger(value) && value >= 0 ? value : undefined;\n\n/**\n * Coerce one usage-shaped object onto {@link claudeUsageSchema}.\n *\n * Accepts the Anthropic Messages API snake_case counters and the camelCase\n * aliases a print/`-p` result or wrapping harness may use. Both `input_tokens`\n * and `output_tokens` must be present — a lone counter is not a usage object,\n * and inventing the missing side as zero would report tokens the provider\n * never sent.\n */\nexport const coerceClaudeUsage = (value: unknown): ClaudeUsage | undefined => {\n const record = asRecord(value);\n if (record === undefined) {\n return undefined;\n }\n const inputTokens = asNonNegativeInt(record.input_tokens ?? record.inputTokens);\n const outputTokens = asNonNegativeInt(record.output_tokens ?? record.outputTokens);\n if (inputTokens === undefined || outputTokens === undefined) {\n return undefined;\n }\n const cacheCreation = asRecord(record.cache_creation ?? record.cacheCreation);\n const parsed = claudeUsageSchema.safeParse({\n input_tokens: inputTokens,\n output_tokens: outputTokens,\n ...(asNonNegativeInt(record.cache_creation_input_tokens ?? record.cacheCreationInputTokens) ===\n undefined\n ? {}\n : {\n cache_creation_input_tokens: asNonNegativeInt(\n record.cache_creation_input_tokens ?? record.cacheCreationInputTokens,\n ),\n }),\n ...(asNonNegativeInt(record.cache_read_input_tokens ?? record.cacheReadInputTokens) === undefined\n ? {}\n : {\n cache_read_input_tokens: asNonNegativeInt(\n record.cache_read_input_tokens ?? record.cacheReadInputTokens,\n ),\n }),\n ...(cacheCreation === undefined\n ? {}\n : {\n cache_creation: {\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_5m_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_5m_input_tokens ?? cacheCreation.ephemeral5mInputTokens,\n ),\n }),\n ...(asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ) === undefined\n ? {}\n : {\n ephemeral_1h_input_tokens: asNonNegativeInt(\n cacheCreation.ephemeral_1h_input_tokens ?? cacheCreation.ephemeral1hInputTokens,\n ),\n }),\n },\n }),\n ...(Array.isArray(record.iterations) ? { iterations: record.iterations } : {}),\n ...(asNonNegativeInt(record.total_tokens ?? record.totalTokens) === undefined\n ? {}\n : { total_tokens: asNonNegativeInt(record.total_tokens ?? record.totalTokens) }),\n ...(asNonNegativeInt(record.reasoning_output_tokens ?? record.reasoningOutputTokens) ===\n undefined\n ? {}\n : {\n reasoning_output_tokens: asNonNegativeInt(\n record.reasoning_output_tokens ?? record.reasoningOutputTokens,\n ),\n }),\n });\n return parsed.success ? parsed.data : undefined;\n};\n\n/**\n * Find a usage object on a Stop / print-result / SessionEnd payload.\n *\n * Looks at `usage`, `token_usage`, `message.usage`, and top-level token\n * counters. The first object that coerces to {@link ClaudeUsage} wins. Absence\n * is reported as `undefined` — never as a zeroed snapshot.\n */\nexport const extractClaudeUsage = (payload: unknown): ClaudeUsage | undefined => {\n const record = asRecord(payload);\n if (record === undefined) {\n return undefined;\n }\n const message = asRecord(record.message);\n const candidates: readonly unknown[] = [\n record.usage,\n record.token_usage,\n record.tokenUsage,\n message?.usage,\n record,\n ];\n for (const candidate of candidates) {\n const usage = coerceClaudeUsage(candidate);\n if (usage !== undefined) {\n return usage;\n }\n }\n return undefined;\n};\n\nexport const normalizeClaudeUsage = (raw: ClaudeUsage | undefined): ClaudeUsageNormalization => {\n if (raw === undefined) {\n return { warnings: [] };\n }\n\n const warnings: string[] = [];\n const cachedInputTokens = raw.cache_read_input_tokens ?? 0;\n const cacheCreationInputTokens = resolveCacheCreationTokens(raw, warnings);\n auditIterations(raw, cacheCreationInputTokens, warnings);\n auditExcludedCounters(raw, warnings);\n\n const result = normalizeUsage({\n temporality: \"delta\",\n inputTokens: raw.input_tokens + cachedInputTokens + cacheCreationInputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: \"included-in-input\",\n outputTokens: raw.output_tokens,\n });\n\n if (result.status === \"invalid\") {\n return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };\n }\n return { usage: result.usage, warnings: [...warnings, ...forwardableNotes(result.notes)] };\n};\n","import { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Fold Claude Code hook and print/`-p` payload aliases onto the snake_case\n * shapes {@link claudeHookPayloadSchema} already accepts.\n *\n * Interactive Stop payloads document `last_assistant_message`. Print / `-p` /\n * Agent SDK result messages use `type: \"result\"` and `result` instead, and some\n * wrappers emit camelCase field names. None of these are invented: each alias\n * is a name Claude Code or its published result JSON has actually used. An\n * unrecognized shape is returned unchanged so detection can decline it.\n */\n\nconst FIELD_ALIASES = Object.freeze({\n hookEventName: \"hook_event_name\",\n sessionId: \"session_id\",\n lastAssistantMessage: \"last_assistant_message\",\n transcriptPath: \"transcript_path\",\n promptId: \"prompt_id\",\n toolUseId: \"tool_use_id\",\n toolName: \"tool_name\",\n toolInput: \"tool_input\",\n toolResponse: \"tool_response\",\n toolError: \"tool_error\",\n stopHookActive: \"stop_hook_active\",\n agentId: \"agent_id\",\n agentType: \"agent_type\",\n errorType: \"error_type\",\n errorMessage: \"error_message\",\n tokenUsage: \"token_usage\",\n} as const);\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/**\n * Copy documented camelCase aliases onto their snake_case names when the\n * snake_case field is absent. Existing snake_case values win, so a payload that\n * carries both is not rewritten.\n */\nconst applyFieldAliases = (record: Record<string, unknown>): Record<string, unknown> => {\n const normalized: Record<string, unknown> = { ...record };\n for (const [alias, canonical] of Object.entries(FIELD_ALIASES)) {\n if (normalized[canonical] === undefined && normalized[alias] !== undefined) {\n normalized[canonical] = normalized[alias];\n }\n }\n return normalized;\n};\n\n/**\n * Claude Code print / `-p` / Agent SDK result messages are not hook events, but\n * they are the stop/result payload a non-interactive session actually produces.\n * When one arrives with a session id and no `hook_event_name`, treat it as the\n * Stop (or StopFailure) the interactive protocol would have fired.\n */\nconst applyPrintResultShape = (record: Record<string, unknown>): Record<string, unknown> => {\n if (record.hook_event_name !== undefined || record.type !== \"result\") {\n return record;\n }\n if (typeof record.session_id !== \"string\" || record.session_id.length === 0) {\n return record;\n }\n\n const isError = record.subtype === \"error\" || record.is_error === true;\n const normalized: Record<string, unknown> = {\n ...record,\n hook_event_name: isError ? \"StopFailure\" : \"Stop\",\n };\n if (\n normalized.last_assistant_message === undefined &&\n typeof record.result === \"string\" &&\n record.result.length > 0\n ) {\n normalized.last_assistant_message = record.result;\n }\n if (isError && (typeof normalized.error_type !== \"string\" || normalized.error_type.length === 0)) {\n normalized.error_type = \"unknown\";\n }\n return normalized;\n};\n\n/**\n * Return a Claude-shaped payload with documented aliases folded onto canonical\n * field names, or the original value when it is not an object.\n */\nexport const normalizeClaudeHookPayload = (payload: unknown): unknown => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n return applyUsageShape(applyToolFailureShape(applyPrintResultShape(applyFieldAliases(record))));\n};\n\n/**\n * Claude Code 2.1.x sends a failed tool's message as `error` on\n * `PostToolUseFailure` (observed in the agent lab), not the `tool_error` an\n * earlier contract named. Fold it onto `tool_error` for that event only, so the\n * failure still ends its tool span; `tool_error` wins when both are present.\n */\nconst applyToolFailureShape = (record: Record<string, unknown>): Record<string, unknown> => {\n if (\n record.hook_event_name !== \"PostToolUseFailure\" ||\n record.tool_error !== undefined ||\n record.error === undefined\n ) {\n return record;\n }\n return { ...record, tool_error: record.error };\n};\n\n/**\n * Coerce `usage` / `token_usage` onto the Anthropic snake_case object the\n * Stop schema accepts, so a camelCase print-result usage object is not\n * rejected as an invalid `usage` field.\n */\nconst applyUsageShape = (record: Record<string, unknown>): Record<string, unknown> => {\n const usage =\n coerceClaudeUsage(record.usage) ??\n coerceClaudeUsage(record.token_usage) ??\n coerceClaudeUsage(record.tokenUsage);\n if (usage === undefined) {\n return record;\n }\n return { ...record, usage };\n};\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { claudeIdentityFieldsSchema } from \"./schema.js\";\n\n/**\n * Which Claude Code callbacks carry an identifier that survives a redelivery.\n *\n * Grounded in the fields the hook payloads actually carry — the CLI's own\n * hook-input schemas at 2.1.220, recorded in\n * docs/claude-code-usage-contract.md:\n *\n * - `tool_use_id` is required on `PreToolUse`, `PostToolUse`,\n * `PostToolUseFailure`, and `PermissionRequest`. It names one tool call, and\n * the event name separates the pre-edge from the post-edge of that same call.\n * - `agent_id` is required on `SubagentStart`/`SubagentStop` and names one\n * subagent instance.\n * - `prompt_id` correlates a firing with the prompt that triggered it, and\n * exactly one `UserPromptSubmit` exists per prompt.\n * - `stop_hook_active` is required on `Stop` and `SubagentStop`, and is `false`\n * exactly on the once-per-turn stop (finding 7).\n *\n * ## Why `Stop` is claimable at all now\n *\n * `Stop` carries usage, so a redelivered one double-counts a turn's tokens —\n * the worst outcome on this list, because a corrupted total cannot be\n * reconstructed. But `prompt_id` alone cannot separate a redelivery from a\n * genuine second stop: Claude Code fires `Stop` again when a hook continues the\n * turn. `stop_hook_active` is precisely that distinction, so the once-per-prompt\n * stop (`stop_hook_active: false`) is claimed and every continuation stop stays\n * unidentifiable.\n *\n * The gate is deliberately one-sided. Two continuation stops both report\n * `stop_hook_active: true`, so claiming an identity for them would suppress a\n * real second firing and lose its tokens — a certain loss to avoid a possible\n * double-count, which is the wrong trade in this direction (see\n * `providerDeliveryClaimSchema`). A payload that omits the field predates the\n * flag or came from a wrapper, and is likewise declined rather than guessed at.\n *\n * The same reasoning fixes an inversion on `SubagentStop`, which was keyed on\n * `agent_id` alone: a hook-continued subagent stop repeats `agent_id`, so it\n * would have been suppressed as a redelivery and its usage lost. It now declines\n * when `stop_hook_active` is `true`, and keeps `agent_id` otherwise — including\n * when the field is absent, which is the pre-existing coverage and the case where\n * `agent_id` genuinely names one stop.\n *\n * Everything else is deliberately excluded. `StopFailure` reports no\n * `stop_hook_active` upstream at all. `SessionStart`, `SessionEnd`, `PreCompact`,\n * and `PostCompact` carry nothing that distinguishes a redelivery from a real\n * second firing.\n */\nconst TOOL_SCOPED_EVENTS: readonly string[] = [\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"PermissionRequest\",\n];\n\nexport const claudeDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));\n if (!parsed.success) {\n return undefined;\n }\n const fields = parsed.data;\n const base = { sessionId: fields.session_id, sourceEventName: fields.hook_event_name };\n\n if (TOOL_SCOPED_EVENTS.includes(fields.hook_event_name) && fields.tool_use_id !== undefined) {\n return {\n ...base,\n components: [fields.tool_use_id],\n evidence: [\"payload.tool_use_id names one tool call and repeats on redelivery\"],\n };\n }\n\n if (fields.hook_event_name === \"SubagentStart\" && fields.agent_id !== undefined) {\n return {\n ...base,\n components: [fields.agent_id],\n evidence: [\"payload.agent_id names one subagent instance\"],\n };\n }\n\n if (\n fields.hook_event_name === \"SubagentStop\" &&\n fields.agent_id !== undefined &&\n fields.stop_hook_active !== true\n ) {\n return {\n ...base,\n components: [fields.agent_id],\n evidence: [\n \"payload.agent_id names one subagent instance\",\n \"payload.stop_hook_active is not true, so this is not a hook-continued second stop\",\n ],\n };\n }\n\n if (fields.hook_event_name === \"UserPromptSubmit\" && fields.prompt_id !== undefined) {\n return {\n ...base,\n components: [fields.prompt_id],\n evidence: [\"payload.prompt_id names one prompt, submitted exactly once\"],\n };\n }\n\n if (\n fields.hook_event_name === \"Stop\" &&\n fields.prompt_id !== undefined &&\n fields.stop_hook_active === false\n ) {\n return {\n ...base,\n // `agent_id` is present when the stop fired inside a subagent, where the\n // prompt is shared with the main thread's own stop.\n components:\n fields.agent_id === undefined\n ? [fields.prompt_id]\n : [fields.prompt_id, fields.agent_id],\n evidence: [\n \"payload.prompt_id names one prompt\",\n \"payload.stop_hook_active is false, so this is the once-per-prompt stop rather than a continuation\",\n ],\n };\n }\n\n return undefined;\n};\n\n/**\n * Why each remaining Claude Code callback carries no delivery identity, and what\n * would have to exist for it to.\n *\n * Reported through `readDeliveryGap` when `requireCallbackId` is set, so an\n * operator auditing coverage reads the actual protocol reason instead of\n * \"callback-not-identifiable\". Kept exhaustive over\n * {@link CLAUDE_HOOK_EVENT_NAMES} — every event is either identified above or\n * explained here, so adding a hook event without deciding its delivery status\n * reads as an omission rather than passing silently.\n *\n * The four tool events and the two subagent events appear here too, because their\n * identifying field is *optional in practice*: a payload that omits `tool_use_id`\n * or `agent_id` reaches the same dead end as an event that never had one, and the\n * diagnostic should say which field is missing rather than blame the event.\n */\nexport const CLAUDE_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n SessionStart:\n \"no per-firing id; payload `source` (startup, resume, clear, compact, fork) means SessionStart fires repeatedly under one session_id\",\n SessionEnd: \"no per-firing id; a cleared and a resumed session end under the same session_id\",\n PreCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n PostCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n Stop:\n \"prompt_id is not a delivery identity here: Claude Code can fire Stop more than once per prompt when a hook continues the turn (stop_hook_active)\",\n StopFailure:\n \"prompt_id is not a delivery identity here: one prompt can fail more than once, and error_type names a class rather than a firing\",\n PreToolUse: \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n PostToolUse: \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n PostToolUseFailure:\n \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n PermissionRequest:\n \"payload.tool_use_id absent; nothing else in this callback names one tool call\",\n SubagentStart: \"payload.agent_id absent; agent_type names a class of subagents, not an instance\",\n SubagentStop: \"payload.agent_id absent; agent_type names a class of subagents, not an instance\",\n UserPromptSubmit: \"payload.prompt_id absent; requires Claude Code v2.1.196 or later\",\n});\n","import {\n asProviderId,\n providerDetectionSchema,\n type ProviderDetection,\n type ProviderDetectionInput,\n} from \"../adapter.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { CLAUDE_HOOK_EVENT_NAMES } from \"./schema.js\";\n\n/** Stable, hyphenated provider id for Claude Code. */\nexport const CLAUDE_CODE_PROVIDER_ID = asProviderId(\"claude-code\");\n\nconst KNOWN_EVENT_NAMES: ReadonlySet<string> = new Set(CLAUDE_HOOK_EVENT_NAMES);\n\nconst none = (reason: string): ProviderDetection =>\n providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: [reason],\n });\n\n/**\n * Recognize a Claude Code hook payload.\n *\n * Confidence is never `exact` from shape alone: Claude Code hook JSON has no\n * self-identifying `provider` field, so `hook_event_name` plus `session_id`\n * is the strongest evidence a shape check can offer. A caller-supplied\n * `providerHint` naming this adapter is treated as the stronger claim.\n */\nexport const detectClaudeCode = (input: ProviderDetectionInput): ProviderDetection => {\n const payload = normalizeClaudeHookPayload(input.payload);\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return none(\"payload is not a JSON object\");\n }\n\n const record = payload as Record<string, unknown>;\n const hookEventName = record.hook_event_name;\n if (typeof hookEventName !== \"string\" || !KNOWN_EVENT_NAMES.has(hookEventName)) {\n return none(\"hook_event_name is missing or not a recognized Claude Code hook event\");\n }\n\n const sessionId = record.session_id;\n if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n return none(\"session_id is missing\");\n }\n\n const hasTranscriptPath =\n typeof record.transcript_path === \"string\" && record.transcript_path.length > 0;\n const isPrintResult = record.type === \"result\";\n const hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;\n\n return providerDetectionSchema.parse({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n confidence: hinted ? \"exact\" : hasTranscriptPath || isPrintResult ? \"strong\" : \"weak\",\n reasons: [\n `hook_event_name=${hookEventName} matches the Claude Code hooks protocol`,\n \"session_id present\",\n ...(hasTranscriptPath ? [\"transcript_path present\"] : []),\n ...(isPrintResult ? [\"type=result print/SDK result message\"] : []),\n ...(hinted ? [\"caller asserted providerHint=claude-code\"] : []),\n ],\n sourceEventName: hookEventName,\n });\n};\n","import {\n workspaceIdentitySchema,\n type WorkspaceIdentity,\n type WorkspaceKeySource,\n} from \"../model/identity.js\";\nimport type { PrivacyService } from \"./service.js\";\n\n/**\n * Raw material a caller can offer for workspace identification.\n *\n * Paths and remote URLs are accepted here and immediately hashed. Neither is\n * retained, so a home directory cannot reach an exporter through this path.\n */\nexport type WorkspaceKeyInput =\n | { readonly kind: \"git-remote\"; readonly remoteUrl: string }\n | { readonly kind: \"git-root\"; readonly absolutePath: string }\n | { readonly kind: \"working-directory\"; readonly absolutePath: string }\n | { readonly kind: \"explicit\"; readonly value: string }\n | { readonly kind: \"unknown\" };\n\nexport type WorkspaceLabels = {\n /** Bare repository name, e.g. `otel-hook`. Never an owner path or URL. */\n readonly repositoryName?: string;\n readonly vcsBranchName?: string;\n /** Revision identifier; hashed before it is stored. */\n readonly vcsRevisionId?: string;\n};\n\n/**\n * Canonicalize a git remote so equivalent spellings hash identically:\n * scheme, credentials, port, trailing `.git`, and case are removed.\n */\nexport const canonicalizeGitRemote = (remoteUrl: string): string => {\n const trimmed = remoteUrl.trim();\n const scpLike = /^([^@/]+)@([^:]+):(.+)$/.exec(trimmed);\n const withoutScheme = scpLike\n ? `${scpLike[2] ?? \"\"}/${scpLike[3] ?? \"\"}`\n : trimmed.replace(/^[a-zA-Z][a-zA-Z0-9+.-]*:\\/\\//, \"\").replace(/^[^@/]+@/, \"\");\n return withoutScheme\n .replace(/:\\d+\\//, \"/\")\n .replace(/\\/+$/, \"\")\n .replace(/\\.git$/i, \"\")\n .replace(/\\/+$/, \"\")\n .toLowerCase();\n};\n\nconst keySourceOf = (input: WorkspaceKeyInput): WorkspaceKeySource => {\n switch (input.kind) {\n case \"git-remote\":\n return \"git-remote\";\n case \"git-root\":\n return \"git-root\";\n case \"working-directory\":\n return \"working-directory\";\n case \"explicit\":\n return \"explicit\";\n case \"unknown\":\n return \"unknown\";\n }\n};\n\nconst keyMaterialOf = (input: WorkspaceKeyInput): string | undefined => {\n switch (input.kind) {\n case \"git-remote\":\n return canonicalizeGitRemote(input.remoteUrl);\n case \"git-root\":\n case \"working-directory\":\n return input.absolutePath.replace(/[/\\\\]+$/, \"\");\n case \"explicit\":\n return input.value;\n case \"unknown\":\n return undefined;\n }\n};\n\n/**\n * Derive privacy-safe workspace identity.\n *\n * The identifier is a salted hash namespaced by key source, so a directory-keyed\n * workspace and a remote-keyed workspace never collide even if the underlying\n * strings match.\n */\nexport const deriveWorkspaceIdentity = (\n privacy: PrivacyService,\n input: WorkspaceKeyInput,\n labels: WorkspaceLabels = {},\n): WorkspaceIdentity => {\n const keySource = keySourceOf(input);\n const material = keyMaterialOf(input);\n const workspaceId =\n material === undefined || material === \"\"\n ? \"unknown:0000000000000000\"\n : privacy.deriveOpaqueId(`workspace/${keySource}`, material);\n\n return workspaceIdentitySchema.parse({\n workspaceId,\n keySource: material === undefined || material === \"\" ? \"unknown\" : keySource,\n ...(labels.repositoryName === undefined\n ? {}\n : { repositoryName: labels.repositoryName.slice(0, 128) }),\n ...(labels.vcsBranchName === undefined\n ? {}\n : { vcsBranchName: labels.vcsBranchName.slice(0, 128) }),\n ...(labels.vcsRevisionId === undefined\n ? {}\n : { vcsRevisionId: privacy.deriveOpaqueId(\"workspace/revision\", labels.vcsRevisionId) }),\n });\n};\n","import { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport { invocationIdSchema, sessionIdSchema, type InvocationId } from \"../../model/primitives.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport type { ProviderContext, ProviderIdentityInput } from \"../adapter.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./detect.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { claudeIdentityFieldsSchema } from \"./schema.js\";\n\n/**\n * Deterministic, cross-invocation-stable id for a subagent.\n *\n * Derived from only `sessionId` and `agentId` (never a timestamp), so any\n * hook firing that carries the same `agent_id` — the subagent's own\n * `SubagentStart`/`SubagentStop`, or a tool call made from inside it —\n * recomputes the identical id and can link back to it, without the adapter\n * ever persisting state between invocations.\n */\nexport const subagentInvocationIdFor = (\n context: ProviderContext,\n sessionId: string,\n agentId: string,\n): InvocationId =>\n invocationIdSchema.parse(`subagent_${context.ids.newOpaqueId([\"claude-subagent\", sessionId, agentId])}`);\n\n/**\n * Contribute identity claims for one Claude Code hook invocation.\n *\n * `sessionId` is Claude Code's own `session_id`, stable for the life of the\n * session. `invocationId` identifies this single hook firing and is\n * intentionally allowed to differ between firings in the same session —\n * continuity across firings is carried by `sessionId`, sequence numbers, and\n * (for subagents) `parentInvocationId`, not by a stable `invocationId`.\n */\nexport const identifyClaudeCode = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n): readonly IdentityClaim[] => {\n const parsed = claudeIdentityFieldsSchema.safeParse(normalizeClaudeHookPayload(input.payload));\n if (!parsed.success) {\n return [];\n }\n const fields = parsed.data;\n const sessionId = sessionIdSchema.parse(fields.session_id);\n const occurredAt = context.clock.now();\n const discriminator = fields.tool_use_id ?? fields.prompt_id ?? fields.agent_id;\n\n const invocationId = context.ids.newInvocationId({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n sessionId,\n sourceEventName: fields.hook_event_name,\n occurredAt,\n ...(discriminator === undefined ? {} : { discriminator }),\n });\n\n const isSubagentLifecycleEvent =\n fields.hook_event_name === \"SubagentStart\" || fields.hook_event_name === \"SubagentStop\";\n const parentInvocationId =\n fields.agent_id !== undefined && !isSubagentLifecycleEvent\n ? subagentInvocationIdFor(context, sessionId, fields.agent_id)\n : undefined;\n\n const claim = identityClaimSchema.parse({\n source: `adapter:${CLAUDE_CODE_PROVIDER_ID}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt: occurredAt,\n ...(fields.cwd === undefined\n ? {}\n : { workspace: deriveWorkspaceIdentity(context.privacy, { kind: \"working-directory\", absolutePath: fields.cwd }) }),\n ...(parentInvocationId === undefined ? {} : { parentInvocationId }),\n ...(fields.agent_id === undefined ? {} : { agentInstanceId: fields.agent_id }),\n },\n });\n\n return [claim];\n};\n","/**\n * Locate assistant text on a Claude Code Stop / print-result payload.\n *\n * Field names are the ones Claude Code and its published `-p` / Agent SDK\n * result JSON have used. The first non-empty string wins. Empty strings and\n * missing fields are treated as \"the provider sent nothing\" — this module\n * never invents text.\n */\n\nconst TOP_LEVEL_TEXT_FIELDS = [\n \"last_assistant_message\",\n \"lastAssistantMessage\",\n \"result\",\n \"assistant_message\",\n \"final_message\",\n] as const;\n\nconst MESSAGE_TEXT_FIELDS = [\"content\", \"text\", \"result\"] as const;\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst nonEmptyString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\nconst textFromContentBlocks = (value: unknown): string | undefined => {\n if (!Array.isArray(value)) {\n return undefined;\n }\n const parts: string[] = [];\n for (const block of value) {\n const record = asRecord(block);\n if (record === undefined) {\n continue;\n }\n const text = nonEmptyString(record.text);\n if (text !== undefined && (record.type === undefined || record.type === \"text\")) {\n parts.push(text);\n }\n }\n return parts.length === 0 ? undefined : parts.join(\"\");\n};\n\n/**\n * Return the assistant text Claude sent on this stop/result payload, or\n * `undefined` when no non-empty string was present.\n */\nexport const extractClaudeAssistantText = (payload: unknown): string | undefined => {\n const record = asRecord(payload);\n if (record === undefined) {\n return undefined;\n }\n\n for (const field of TOP_LEVEL_TEXT_FIELDS) {\n const text = nonEmptyString(record[field]);\n if (text !== undefined) {\n return text;\n }\n }\n\n const messageText = nonEmptyString(record.message);\n if (messageText !== undefined) {\n return messageText;\n }\n\n const message = asRecord(record.message);\n if (message === undefined) {\n return undefined;\n }\n for (const field of MESSAGE_TEXT_FIELDS) {\n const text = nonEmptyString(message[field]) ?? textFromContentBlocks(message[field]);\n if (text !== undefined) {\n return text;\n }\n }\n return undefined;\n};\n","import { sessionCwdHint, type TargetHint } from \"../../model/target.js\";\n\n/**\n * Where a Claude Code tool call pointed, as a target hint (ADR 0008).\n *\n * Claude Code's file tools name their file in `tool_input`; that is the\n * strongest evidence a hook payload carries, and is reported as `tool-path`.\n * The hook's `cwd` is the *session's* directory, not the tool's — Claude Code's\n * `Bash` reports no working directory of its own — so it is used only as the\n * `session-cwd` fallback for a call that names no path.\n *\n * Only built-in tools whose input field is documented as a path are read. An\n * MCP tool's `path` argument means whatever its server says it means, and is\n * not evidence of a local file.\n */\nconst PATH_FIELDS: Readonly<Record<string, readonly string[]>> = Object.freeze({\n Read: [\"file_path\"],\n Write: [\"file_path\"],\n Edit: [\"file_path\"],\n MultiEdit: [\"file_path\"],\n NotebookEdit: [\"notebook_path\"],\n NotebookRead: [\"notebook_path\"],\n // Optional on both: absent means \"search the session's directory\".\n Glob: [\"path\"],\n Grep: [\"path\"],\n});\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nexport const claudeTargetHint = (\n toolName: string,\n toolInput: unknown,\n cwd: string | undefined,\n): TargetHint | undefined => {\n // `hasOwn`: a tool name is payload data, and `__proto__` is a string like any other.\n const fields = Object.hasOwn(PATH_FIELDS, toolName) ? PATH_FIELDS[toolName] : undefined;\n const input = asRecord(toolInput);\n if (fields !== undefined && input !== undefined) {\n for (const field of fields) {\n const candidate = input[field];\n if (typeof candidate === \"string\" && candidate.length > 0) {\n return {\n source: \"tool-path\",\n paths: [candidate],\n ...(cwd === undefined ? {} : { baseDirectory: cwd }),\n };\n }\n }\n }\n return sessionCwdHint(cwd);\n};\n","import type { ToolKind } from \"../../model/index.js\";\n\n/**\n * Best-effort classification of Claude Code's built-in tool names.\n *\n * Unrecognized names (including every `mcp__*` tool, whose behavior is\n * defined by the connected MCP server rather than Claude Code itself) map to\n * `unknown` rather than a guess.\n */\nconst BUILT_IN_TOOL_KIND: Readonly<Record<string, ToolKind>> = Object.freeze({\n Bash: \"execute\",\n BashOutput: \"execute\",\n KillShell: \"execute\",\n Read: \"read\",\n NotebookRead: \"read\",\n Write: \"write\",\n Edit: \"write\",\n MultiEdit: \"write\",\n NotebookEdit: \"write\",\n Glob: \"search\",\n Grep: \"search\",\n WebFetch: \"network\",\n WebSearch: \"network\",\n Task: \"delegate\",\n // Current Claude Code releases (observed on 2.1.332) name the subagent tool `Agent`.\n Agent: \"delegate\",\n TodoWrite: \"other\",\n ExitPlanMode: \"other\",\n AskUserQuestion: \"other\",\n SlashCommand: \"other\",\n});\n\nexport const inferToolKind = (toolName: string): ToolKind => {\n if (toolName.startsWith(\"mcp__\")) {\n return \"unknown\";\n }\n return BUILT_IN_TOOL_KIND[toolName] ?? \"unknown\";\n};\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { ModelDescriptor } from \"../../model/index.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport type { ProviderContext, ProviderParseInput, ProviderParseResult } from \"../adapter.js\";\nimport { subagentInvocationIdFor } from \"./identity.js\";\nimport { normalizeClaudeHookPayload } from \"./payload-normalize.js\";\nimport { claudeHookPayloadSchema, type ClaudeUsage } from \"./schema.js\";\nimport { extractClaudeAssistantText } from \"./stop-content.js\";\nimport { sessionCwdHint } from \"../../model/target.js\";\nimport { claudeTargetHint } from \"./target.js\";\nimport { inferToolKind } from \"./tool-kind.js\";\nimport { extractClaudeUsage, normalizeClaudeUsage } from \"./usage.js\";\n\n/**\n * Claude Code hooks never report a model identifier on the events this\n * adapter turns into `generation.start`/`generation.end` (`Stop`,\n * `StopFailure`). Only `SessionStart` names one.\n *\n * So a generation's model comes from, in order:\n *\n * 1. a `model` a wrapping harness attached to the stop payload — the per-turn\n * model it read from the transcript's last assistant message, the only\n * source that follows a `/model` switch exactly;\n * 2. the session's model, which the core remembers from `SessionStart` (or the\n * last turn that named one) and hands in as `sessionModel` (ADR 0006: the\n * adapter itself holds no cross-invocation state);\n * 3. `unknown`, when nothing in this session ever named a model. Using a\n * real-looking model id here would assert something no payload said;\n * `unknown` is the same honest-absence sentinel the core model uses for\n * provider and workspace identity.\n *\n * The request model (`generation.start`) prefers the session's model, since that\n * is what the turn was sent to; the response model (`generation.end`) prefers the\n * attached per-turn one, since that is what answered.\n */\nconst UNKNOWN_MODEL: ModelDescriptor = { modelId: \"unknown\" };\n\nconst generationModels = (\n attached: string | undefined,\n sessionModel: ModelDescriptor | undefined,\n): { readonly request: ModelDescriptor; readonly response: ModelDescriptor } => {\n const turnModel: ModelDescriptor | undefined = attached === undefined ? undefined : { modelId: attached };\n return {\n request: sessionModel ?? turnModel ?? UNKNOWN_MODEL,\n response: turnModel ?? sessionModel ?? UNKNOWN_MODEL,\n };\n};\n\ntype SessionEndReason = \"completed\" | \"aborted\" | \"error\" | \"timeout\" | \"unknown\";\n\nconst SESSION_END_REASON: Readonly<Record<string, SessionEndReason>> = Object.freeze({\n completed: \"completed\",\n aborted: \"aborted\",\n error: \"error\",\n timeout: \"timeout\",\n clear: \"completed\",\n resume: \"completed\",\n prompt_input_exit: \"completed\",\n logout: \"aborted\",\n bypass_permissions_disabled: \"aborted\",\n other: \"unknown\",\n});\n\nconst mapSessionEndReason = (raw: string | undefined): SessionEndReason =>\n raw === undefined ? \"unknown\" : (SESSION_END_REASON[raw] ?? \"unknown\");\n\ntype CompactionTrigger = \"automatic\" | \"manual\" | \"unknown\";\n\nconst mapCompactTrigger = (raw: string | undefined): CompactionTrigger => {\n if (raw === \"auto\" || raw === \"automatic\") {\n return \"automatic\";\n }\n if (raw === \"manual\") {\n return \"manual\";\n }\n return \"unknown\";\n};\n\ntype GenerationOutcome = \"ok\" | \"error\" | \"cancelled\" | \"timeout\" | \"denied\" | \"unknown\";\n\n/** `StopFailure` error categories that represent the request being refused rather than failing. */\nconst DENIED_STOP_FAILURE_TYPES: ReadonlySet<string> = new Set([\n \"authentication_failed\",\n \"oauth_org_not_allowed\",\n \"billing_error\",\n]);\n\nconst mapStopFailureOutcome = (errorType: string): GenerationOutcome =>\n DENIED_STOP_FAILURE_TYPES.has(errorType) ? \"denied\" : \"error\";\n\nconst applyUsage = (normalized: ReturnType<typeof normalizeClaudeUsage>): { usage?: ReturnType<typeof normalizeClaudeUsage>[\"usage\"] } =>\n normalized.usage === undefined ? {} : { usage: normalized.usage };\n\nexport const parseClaudeCode = (\n input: ProviderParseInput,\n context: ProviderContext,\n): ProviderParseResult => {\n const normalizedPayload = normalizeClaudeHookPayload(input.payload);\n const parsed = claudeHookPayloadSchema.safeParse(normalizedPayload);\n if (!parsed.success) {\n const rawEventName =\n typeof input.payload === \"object\" && input.payload !== null\n ? (input.payload as Record<string, unknown>).hook_event_name\n : undefined;\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: `payload failed Claude Code schema validation: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: { \"hook.event_name\": typeof rawEventName === \"string\" ? rawEventName : \"\" },\n }),\n };\n }\n const payload = parsed.data;\n const extractedUsage = extractClaudeUsage(normalizedPayload);\n\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n // Present exactly when the hook fired inside a subagent (or describes one,\n // on SubagentStart/SubagentStop).\n ...(payload.agent_id === undefined ? {} : { subagentId: payload.agent_id }),\n });\n const warnings: string[] = [];\n const targetHintFor = (toolName: string, toolInput: unknown) => {\n const hint = claudeTargetHint(toolName, toolInput, payload.cwd);\n return hint === undefined ? {} : { targetHint: hint };\n };\n // The session's own directory: where it runs before any tool names a path.\n const sessionHint = sessionCwdHint(payload.cwd);\n const sessionTarget = sessionHint === undefined ? {} : { targetHint: sessionHint };\n const withUsage = (usage: ClaudeUsage | undefined) => {\n const normalized = normalizeClaudeUsage(usage);\n warnings.push(...normalized.warnings);\n return applyUsage(normalized);\n };\n\n /** Usage plus the attacher's statement of whether it covers the whole turn. */\n const withPartialUsage = (usage: ClaudeUsage | undefined, partial: boolean | undefined) => {\n const applied = withUsage(usage);\n return applied.usage === undefined || partial === undefined ? applied : { ...applied, usagePartial: partial };\n };\n\n switch (payload.hook_event_name) {\n case \"SessionStart\":\n factory.build({\n type: \"session.start\",\n sessionKind: \"unknown\",\n agentName: \"claude-code\",\n ...(payload.model === undefined ? {} : { model: { modelId: payload.model } }),\n ...sessionTarget,\n });\n break;\n\n case \"SessionEnd\":\n factory.build({\n type: \"session.end\",\n reason: mapSessionEndReason(payload.reason ?? payload.end_reason),\n ...withUsage(extractedUsage),\n });\n break;\n\n case \"UserPromptSubmit\":\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n content: context.privacy.describeContent({ kind: \"prompt\", role: \"user\", text: payload.prompt }),\n ...sessionTarget,\n });\n break;\n\n case \"PreToolUse\":\n factory.build({\n type: \"tool.start\",\n toolCallId: payload.tool_use_id,\n toolName: payload.tool_name,\n toolKind: inferToolKind(payload.tool_name),\n ...targetHintFor(payload.tool_name, payload.tool_input),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"PostToolUse\":\n factory.build({\n type: \"tool.end\",\n toolCallId: payload.tool_use_id,\n toolName: payload.tool_name,\n outcome: \"ok\",\n ...targetHintFor(payload.tool_name, payload.tool_input),\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_response,\n label: payload.tool_name,\n }),\n });\n break;\n\n case \"PostToolUseFailure\":\n factory.build({\n type: \"tool.end\",\n toolCallId: payload.tool_use_id,\n toolName: payload.tool_name,\n outcome: \"error\",\n ...targetHintFor(payload.tool_name, payload.tool_input),\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_error,\n label: payload.tool_name,\n }),\n });\n break;\n\n case \"PermissionRequest\":\n // The canonical model has no dedicated \"permission requested\" event: a\n // decision here either becomes a normal PreToolUse/PostToolUse pair (if\n // allowed) or the tool call never happens at all (if denied), so there\n // is nothing distinct to telemeter yet.\n return {\n status: \"ignored\",\n reason: \"permission requests carry no telemetry independent of the tool call they gate\",\n };\n\n case \"SubagentStart\":\n factory.build({\n type: \"subagent.start\",\n subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),\n subagentType: payload.agent_type,\n delegationDepth: 1,\n });\n break;\n\n case \"SubagentStop\": {\n // The subagent's tokens (attached from its own transcript, issue #68) are\n // reported on a generation inside the subagent, where metrics and receivers\n // count generation spend, and nowhere else: not on the subagent span, which\n // would restate them, and not on the parent turn, which never sums sidechain\n // requests. The model is the subagent's own; the session's would be a guess.\n const usage = withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial);\n if (usage.usage !== undefined || payload.model !== undefined) {\n // Replay-stable for the once-per-run stop, which is also what delivery\n // deduplicates on (`delivery.ts`): a reclaimed delivery folds into the\n // same generation instead of opening a second one. A hook-continued stop\n // repeats `agent_id`, so it needs the sequence to be a generation of its own.\n const generationId = context.ids.newOpaqueId([\n \"claude-subagent-generation\",\n payload.session_id,\n payload.agent_id,\n ...(payload.stop_hook_active === true ? [String(input.sequenceBase)] : []),\n ]);\n const models = generationModels(payload.model, undefined);\n factory.build({ type: \"generation.start\", generationId, model: models.request });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: models.response,\n outcome: \"ok\",\n outputContent: [\n payload.last_assistant_message === undefined\n ? context.privacy.describeUnavailableContent({ kind: \"response\", role: \"assistant\" })\n : context.privacy.describeContent({\n kind: \"response\",\n role: \"assistant\",\n text: payload.last_assistant_message,\n }),\n ],\n ...usage,\n });\n }\n factory.build({\n type: \"subagent.end\",\n subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),\n outcome: \"ok\",\n });\n break;\n }\n\n case \"PreCompact\":\n // Fires before compaction runs; the completed operation is reported once at\n // PostCompact instead. Claude Code reports no token count on either\n // compaction callback (docs/claude-code-usage-contract.md, finding 6), so\n // nothing is lost by ignoring this edge — but a *harness* may have attached\n // a before-figure here, and dropping that silently is what made\n // ADAPTER-NOTE-002 look like a plumbing gap. It is an exclusion, so it says\n // so: carrying the figure to PostCompact would need cross-invocation state\n // an adapter must not hold (ADR 0006), and the same harness can attach it to\n // PostCompact, where one callback carries both ends.\n // Kept inside the 160 characters an ignore reason survives at the log\n // boundary, so the remedy is not the part that gets truncated away.\n return {\n status: \"ignored\",\n reason:\n payload.context_tokens_before === undefined\n ? \"compaction is reported once it completes, at PostCompact\"\n : \"contextTokensBefore is an explicit exclusion for this provider: attach \" +\n \"context_tokens_before to PostCompact, which carries both ends in one callback\",\n };\n\n case \"PostCompact\":\n factory.build({\n type: \"compaction.performed\",\n trigger: mapCompactTrigger(payload.trigger ?? payload.compact_trigger),\n ...(payload.context_tokens_before === undefined ? {} : { contextTokensBefore: payload.context_tokens_before }),\n ...(payload.context_tokens_after === undefined ? {} : { contextTokensAfter: payload.context_tokens_after }),\n ...(payload.dropped_message_count === undefined ? {} : { droppedMessageCount: payload.dropped_message_count }),\n ...withUsage(payload.usage),\n });\n break;\n\n case \"Stop\": {\n const generationId = context.ids.newOpaqueId([\n \"claude-generation\",\n payload.session_id,\n payload.prompt_id ?? String(input.sequenceBase),\n ]);\n const assistantText = extractClaudeAssistantText(normalizedPayload);\n const models = generationModels(payload.model, input.sessionModel);\n factory.build({ type: \"generation.start\", generationId, model: models.request });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: models.response,\n outcome: \"ok\",\n // Always a response fact: a body when Claude sent text, otherwise a\n // zero-length omitted fact so the log mapping can emit metadata_only\n // instead of a generation.end with no content.kind.\n outputContent: [\n assistantText === undefined\n ? context.privacy.describeUnavailableContent({ kind: \"response\", role: \"assistant\" })\n : context.privacy.describeContent({\n kind: \"response\",\n role: \"assistant\",\n text: assistantText,\n }),\n ],\n ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial),\n });\n break;\n }\n\n case \"StopFailure\": {\n const generationId = context.ids.newOpaqueId([\n \"claude-generation\",\n payload.session_id,\n payload.prompt_id ?? String(input.sequenceBase),\n ]);\n const assistantText = extractClaudeAssistantText(normalizedPayload);\n const models = generationModels(payload.model, input.sessionModel);\n factory.build({ type: \"generation.start\", generationId, model: models.request });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: models.response,\n outcome: mapStopFailureOutcome(payload.error_type),\n stopReason: payload.error_type,\n ...(assistantText === undefined\n ? {}\n : {\n outputContent: [\n context.privacy.describeContent({\n kind: \"response\",\n role: \"assistant\",\n text: assistantText,\n }),\n ],\n }),\n ...withPartialUsage(extractedUsage ?? payload.usage, payload.usage_partial),\n });\n break;\n }\n }\n\n const targetHints = factory.targetHints();\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n ...(targetHints.size === 0 ? {} : { targetHints }),\n };\n};\n","import { SILENT_HOOK_RESPONSE, type ProviderAdapter, type ProviderHookResponse } from \"../adapter.js\";\nimport { CLAUDE_CODE_CAPABILITIES } from \"./capabilities.js\";\nimport { CLAUDE_DELIVERY_GAPS, claudeDeliveryIdentity } from \"./delivery.js\";\nimport { CLAUDE_CODE_PROVIDER_ID, detectClaudeCode } from \"./detect.js\";\nimport { parseClaudeCode } from \"./events.js\";\nimport { identifyClaudeCode } from \"./identity.js\";\n\nexport type ClaudeCodeAdapterOptions = {\n /** Adapter version reported in provenance; defaults to `1.0.0`. */\n readonly version?: string;\n};\n\n/**\n * Provider adapter for Claude Code's hook protocol.\n *\n * Always answers hook invocations silently: this adapter is a telemetry\n * sidecar, not the hook that governs permissions or turn continuation, and\n * must never be able to block the host agent (ADR 0004).\n */\nexport const createClaudeCodeAdapter = (options: ClaudeCodeAdapterOptions = {}): ProviderAdapter => ({\n id: CLAUDE_CODE_PROVIDER_ID,\n version: options.version ?? \"1.0.0\",\n capabilities: CLAUDE_CODE_CAPABILITIES,\n detect: (input) => detectClaudeCode(input),\n identify: (input, context) => identifyClaudeCode(input, context),\n deliveryIdentity: (input) => claudeDeliveryIdentity(input),\n deliveryGaps: CLAUDE_DELIVERY_GAPS,\n parse: (input, context) => parseClaudeCode(input, context),\n hookResponse: (): ProviderHookResponse => SILENT_HOOK_RESPONSE,\n});\n","import { createHash } from \"node:crypto\";\nimport { open, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { PayloadEnricher, PayloadEnrichment, ReadCursor } from \"../../runtime/ports.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./detect.js\";\nimport type { ClaudeUsage } from \"./schema.js\";\nimport { coerceClaudeUsage } from \"./usage.js\";\n\n/**\n * Bounded readers for one Claude Code session transcript, and the enricher that\n * uses them to attach a turn's model and token usage to a `Stop` payload.\n *\n * None of this is part of the Claude Code adapter, and the adapter never calls\n * it: `ProviderContext` gives adapters no filesystem handle (ADR 0003). Two\n * callers use it instead:\n *\n * - a wrapping harness, through {@link attachClaudeTranscriptTurn}, which reads\n * the last assistant message only;\n * - the hook runtime, through {@link createClaudeTranscriptUsageEnricher}, when\n * the host turns on `providers.claudeCode.readTranscriptUsage` — the one\n * sanctioned exception to \"no transcript reads in the hook\". It sums the whole\n * turn, from a byte cursor the runtime keeps in the state store.\n *\n * Why the transcript at all: no Claude Code hook callback carries a token\n * counter, and only `SessionStart` names a model. The per-turn model\n * (`message.model`, which follows `/model`) and the Anthropic usage object\n * (`message.usage`) exist only on assistant transcript records, one record per\n * content block, each repeating its request's `message.id`.\n *\n * Every bound is hard, and nothing here throws:\n * - only regular `.jsonl` files at an absolute path are opened, so a FIFO or a\n * device cannot stall the hook, and no directory is ever listed;\n * - a read is capped in bytes and raced against a time budget;\n * - a malformed or truncated line is skipped, never fatal.\n *\n * Nothing but model ids and numeric counters leaves this module: a record's\n * content (prompt, response, thinking, tool input) is parsed only to be dropped.\n */\n\nexport type ClaudeTranscriptUnavailableReason =\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n | \"no-assistant-message\";\n\nexport type ClaudeTranscriptTurn =\n | {\n readonly status: \"found\";\n /** `message.model`; absent when the record named none. */\n readonly model?: string;\n /** `message.usage`, coerced onto the shape the `Stop` schema accepts. */\n readonly usage?: ClaudeUsage;\n }\n | { readonly status: \"unavailable\"; readonly reason: ClaudeTranscriptUnavailableReason };\n\nexport type ReadClaudeTranscriptTurnOptions = {\n /** Bytes read from the end of the file. Default 1 MiB, clamped to 64 KiB..16 MiB. */\n readonly maxTailBytes?: number;\n /** Budget for the whole read. Default 250 ms, clamped to 10 ms..5 s. */\n readonly timeoutMillis?: number;\n};\n\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES = 1_048_576;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS = 250;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES = 8_388_608;\nexport const DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS = 500;\n\nconst MIN_TAIL_BYTES = 65_536;\nconst MAX_TAIL_BYTES = 16_777_216;\nconst MAX_RANGE_BYTES = 67_108_864;\nconst MIN_TIMEOUT_MILLIS = 10;\nconst MAX_TIMEOUT_MILLIS = 5_000;\n/** Longer than any real model id; a longer value is not one. */\nconst MAX_MODEL_ID_LENGTH = 256;\n/** Bounds the request ids held while summing one range. */\nconst MAX_REQUESTS_PER_RANGE = 10_000;\n/**\n * Claude Code writes `<synthetic>` as the model of assistant records it made up\n * itself (an API error, an interrupted turn). Those name no real model and carry\n * zeroed usage, so they are skipped.\n */\nconst SYNTHETIC_MODEL = \"<synthetic>\";\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nconst clamp = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (value === undefined || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(max, Math.max(min, Math.floor(value)));\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst isTranscriptPath = (transcriptPath: unknown): transcriptPath is string =>\n typeof transcriptPath === \"string\" &&\n transcriptPath.length > 0 &&\n !transcriptPath.includes(\"\\0\") &&\n path.isAbsolute(transcriptPath) &&\n path.extname(transcriptPath) === \".jsonl\";\n\n/**\n * A record of subagent `agentId`: a sidechain record naming that agent, or\n * naming none (the file is the agent's own; only a different name excludes it).\n */\nconst isRecordOfAgent = (record: Record<string, unknown>, agentId: string): boolean =>\n record.isSidechain === true && (typeof record.agentId !== \"string\" || record.agentId === agentId);\n\ntype AssistantRecord = { readonly id?: string; readonly model?: string; readonly usage?: ClaudeUsage };\n\n/**\n * The request id, model and usage of one transcript line, or `undefined` when\n * it is not a usable assistant record of the thread being read.\n *\n * Without `agentId` that thread is the main one: sidechain records are a\n * subagent's conversation, and the parent's `Stop` is not about them. With\n * `agentId` it is that subagent's, read from its own transcript\n * (`agent_transcript_path`), where every record is a sidechain record; a record\n * naming another agent is skipped.\n */\nconst assistantRecordOf = (line: string, agentId?: string): AssistantRecord | undefined => {\n // Cheap pre-filter: most lines are user, tool-result, or summary records, and\n // parsing every one of them would spend the budget on records never used.\n if (!line.includes('\"assistant\"')) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n const record = asRecord(parsed);\n if (record === undefined || record.type !== \"assistant\") {\n return undefined;\n }\n if (agentId === undefined ? record.isSidechain === true : !isRecordOfAgent(record, agentId)) {\n return undefined;\n }\n const message = asRecord(record.message);\n if (message === undefined || message.model === SYNTHETIC_MODEL) {\n return undefined;\n }\n const model =\n typeof message.model === \"string\" && message.model.length > 0 && message.model.length <= MAX_MODEL_ID_LENGTH\n ? message.model\n : undefined;\n const usage = coerceClaudeUsage(message.usage);\n if (model === undefined && usage === undefined) {\n return undefined;\n }\n const id =\n typeof message.id === \"string\" && message.id.length > 0 && message.id.length <= 256 ? message.id : undefined;\n return {\n ...(id === undefined ? {} : { id }),\n ...(model === undefined ? {} : { model }),\n ...(usage === undefined ? {} : { usage }),\n };\n};\n\nconst cacheCreationOf = (usage: ClaudeUsage): number =>\n usage.cache_creation_input_tokens ??\n (usage.cache_creation === undefined\n ? 0\n : (usage.cache_creation.ephemeral_5m_input_tokens ?? 0) + (usage.cache_creation.ephemeral_1h_input_tokens ?? 0));\n\n/**\n * Sum per-request usage into one turn total.\n *\n * Only the four counters are summed. The TTL split and `iterations[]` are\n * breakdowns of one request's counters (docs/claude-code-usage-contract.md,\n * findings 3 and 4); carrying them across requests would add nothing a consumer\n * reads, and the adapter would only audit them against the sums.\n */\nconst sumUsage = (usages: readonly ClaudeUsage[]): ClaudeUsage => {\n let input = 0;\n let output = 0;\n let cacheRead = 0;\n let cacheCreation = 0;\n for (const usage of usages) {\n input += usage.input_tokens;\n output += usage.output_tokens;\n cacheRead += usage.cache_read_input_tokens ?? 0;\n cacheCreation += cacheCreationOf(usage);\n }\n return {\n input_tokens: input,\n output_tokens: output,\n cache_read_input_tokens: cacheRead,\n cache_creation_input_tokens: cacheCreation,\n };\n};\n\n/** Race `work` against a budget; a rejection becomes `onError`. */\nconst withTimeout = async <T>(\n work: Promise<T>,\n timeoutMillis: number,\n onError: T,\n): Promise<T | typeof TIMED_OUT> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => {\n resolve(TIMED_OUT);\n }, timeoutMillis);\n // A hook process must be free to exit the moment its real work is done.\n timer.unref();\n });\n try {\n return await Promise.race([work.catch(() => onError), timeout]);\n } finally {\n clearTimeout(timer);\n }\n};\n\ntype FileUnavailable = { readonly status: \"unavailable\"; readonly reason: \"not-a-file\" | \"unreadable\" };\n\ntype FileHandle = Awaited<ReturnType<typeof open>>;\n\n/** Open a regular file and run `body` with its handle and size; always closes. */\nconst withRegularFile = async <T>(\n transcriptPath: string,\n body: (handle: FileHandle, size: number) => Promise<T>,\n): Promise<T | FileUnavailable> => {\n let info;\n try {\n info = await stat(transcriptPath);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n if (!info.isFile()) {\n return { status: \"unavailable\", reason: \"not-a-file\" };\n }\n let handle;\n try {\n handle = await open(transcriptPath, \"r\");\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n try {\n const { size } = await handle.stat();\n return await body(handle, size);\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\nconst readBytes = async (handle: FileHandle, start: number, length: number): Promise<Buffer> => {\n const buffer = Buffer.alloc(length);\n let filled = 0;\n while (filled < length) {\n const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);\n if (bytesRead === 0) {\n break;\n }\n filled += bytesRead;\n }\n return buffer.subarray(0, filled);\n};\n\n/** Offset just past the last complete line of `bytes`, read from `start`. */\nconst completeLinesEnd = (bytes: Buffer, start: number): number => {\n const lastNewline = bytes.lastIndexOf(0x0a);\n return lastNewline < 0 ? start : start + lastNewline + 1;\n};\n\ntype TailRead = { readonly turn: ClaudeTranscriptTurn; readonly endOffset: number };\n\nconst readTail = (\n transcriptPath: string,\n maxTailBytes: number,\n agentId: string | undefined,\n): Promise<TailRead | FileUnavailable> =>\n withRegularFile(transcriptPath, async (handle, size): Promise<TailRead> => {\n const length = Math.min(size, maxTailBytes);\n const start = size - length;\n const bytes = await readBytes(handle, start, length);\n const endOffset = completeLinesEnd(bytes, start);\n const lines = bytes.toString(\"utf8\").split(\"\\n\");\n // A tail that starts mid-file starts mid-line: that first fragment is not a\n // record, and parsing it could only fail or, worse, half-succeed.\n if (start > 0) {\n lines.shift();\n }\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n const record = assistantRecordOf((lines[index] ?? \"\").trim(), agentId);\n if (record !== undefined) {\n return {\n turn: {\n status: \"found\",\n ...(record.model === undefined ? {} : { model: record.model }),\n ...(record.usage === undefined ? {} : { usage: record.usage }),\n },\n endOffset,\n };\n }\n }\n return { turn: { status: \"unavailable\", reason: \"no-assistant-message\" }, endOffset };\n });\n\nconst boundedTail = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions,\n agentId?: string,\n): Promise<TailRead | FileUnavailable | typeof TIMED_OUT> =>\n withTimeout<TailRead | FileUnavailable>(\n readTail(\n transcriptPath,\n clamp(options.maxTailBytes, DEFAULT_CLAUDE_TRANSCRIPT_TAIL_BYTES, MIN_TAIL_BYTES, MAX_TAIL_BYTES),\n agentId,\n ),\n clamp(options.timeoutMillis, DEFAULT_CLAUDE_TRANSCRIPT_TIMEOUT_MILLIS, MIN_TIMEOUT_MILLIS, MAX_TIMEOUT_MILLIS),\n { status: \"unavailable\", reason: \"unreadable\" },\n );\n\n/**\n * Read the model and usage of the last main-thread assistant message in a\n * Claude Code transcript. Never throws, never rejects.\n *\n * The usage is that **one message's** — the final model request of the turn. A\n * turn that called tools made several requests, and the earlier ones are not\n * summed in; {@link readClaudeTranscriptRange} sums a whole turn.\n */\nexport const readClaudeTranscriptTurn = async (\n transcriptPath: string,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<ClaudeTranscriptTurn> => {\n if (!isTranscriptPath(transcriptPath)) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const read = await boundedTail(transcriptPath, options);\n if (read === TIMED_OUT) {\n return { status: \"unavailable\", reason: \"timeout\" };\n }\n return \"turn\" in read ? read.turn : read;\n};\n\nexport type ClaudeTranscriptRange =\n | {\n readonly status: \"found\";\n /** Model of the last main-thread assistant record in the range. */\n readonly model?: string;\n /** Summed usage of every distinct request; absent when none reported usage. */\n readonly usage?: ClaudeUsage;\n /** Distinct main-thread requests (by `message.id`) in the range. */\n readonly requestCount: number;\n /** Offset just past the last complete line read: the next range starts here. */\n readonly endOffset: number;\n }\n | {\n readonly status: \"unavailable\";\n readonly reason:\n | \"invalid-path\"\n | \"not-a-file\"\n | \"unreadable\"\n | \"timeout\"\n /** The file is shorter than the offset: it was replaced or truncated. */\n | \"truncated\"\n /** More than the range cap was written since the offset. */\n | \"over-cap\";\n };\n\nexport type ReadClaudeTranscriptRangeOptions = {\n /** Most bytes a range may span. Default 8 MiB, clamped to 64 KiB..64 MiB. */\n readonly maxRangeBytes?: number;\n /** Budget for the whole range read. Default 500 ms, clamped to 10 ms..5 s. */\n readonly rangeTimeoutMillis?: number;\n /**\n * Read subagent `agentId`'s requests (its sidechain records) instead of the\n * main thread's. For a subagent's own transcript, `agent_transcript_path`.\n */\n readonly agentId?: string;\n};\n\n/**\n * Sum every main-thread model request (or, with `agentId`, every request of that\n * subagent) written between `fromOffset` and the end of the transcript. Never\n * throws, never rejects.\n *\n * Records of one request share a `message.id` and each repeats its usage, so the\n * last record per id is the one counted; a record without an id counts alone.\n * A trailing partial line is left for the next range.\n */\nexport const readClaudeTranscriptRange = async (\n transcriptPath: string,\n fromOffset: number,\n options: ReadClaudeTranscriptRangeOptions = {},\n): Promise<ClaudeTranscriptRange> => {\n if (!isTranscriptPath(transcriptPath) || !Number.isSafeInteger(fromOffset) || fromOffset < 0) {\n return { status: \"unavailable\", reason: \"invalid-path\" };\n }\n const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CLAUDE_TRANSCRIPT_RANGE_BYTES, MIN_TAIL_BYTES, MAX_RANGE_BYTES);\n const timeoutMillis = clamp(\n options.rangeTimeoutMillis,\n DEFAULT_CLAUDE_TRANSCRIPT_RANGE_TIMEOUT_MILLIS,\n MIN_TIMEOUT_MILLIS,\n MAX_TIMEOUT_MILLIS,\n );\n const work = withRegularFile(transcriptPath, async (handle, size): Promise<ClaudeTranscriptRange> => {\n if (size < fromOffset) {\n return { status: \"unavailable\", reason: \"truncated\" };\n }\n if (size - fromOffset > maxRangeBytes) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n const bytes = await readBytes(handle, fromOffset, size - fromOffset);\n const endOffset = completeLinesEnd(bytes, fromOffset);\n const complete = bytes.subarray(0, endOffset - fromOffset).toString(\"utf8\");\n const requests = new Map<string, AssistantRecord>();\n let anonymous = 0;\n let model: string | undefined;\n for (const line of complete.split(\"\\n\")) {\n const record = assistantRecordOf(line.trim(), options.agentId);\n if (record === undefined) {\n continue;\n }\n if (record.model !== undefined) {\n model = record.model;\n }\n anonymous += record.id === undefined ? 1 : 0;\n // The last record of a request carries its final usage, so it replaces the earlier ones.\n requests.set(record.id ?? `#${String(anonymous)}`, record);\n if (requests.size > MAX_REQUESTS_PER_RANGE) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n }\n }\n const usages = [...requests.values()].flatMap((record) => (record.usage === undefined ? [] : [record.usage]));\n return {\n status: \"found\",\n ...(model === undefined ? {} : { model }),\n ...(usages.length === 0 ? {} : { usage: sumUsage(usages) }),\n requestCount: requests.size,\n endOffset,\n };\n });\n const result = await withTimeout<ClaudeTranscriptRange | FileUnavailable>(work, timeoutMillis, {\n status: \"unavailable\",\n reason: \"unreadable\",\n });\n return result === TIMED_OUT ? { status: \"unavailable\", reason: \"timeout\" } : result;\n};\n\nconst STOP_EVENTS: ReadonlySet<string> = new Set([\"Stop\", \"StopFailure\"]);\n\nconst hasUsage = (record: Record<string, unknown>): boolean =>\n record.usage !== undefined || record.token_usage !== undefined || record.tokenUsage !== undefined;\n\nconst eventNameOf = (record: Record<string, unknown>): unknown => record.hook_event_name ?? record.hookEventName;\nconst transcriptPathOf = (record: Record<string, unknown>): unknown =>\n record.transcript_path ?? record.transcriptPath;\n\n/**\n * Attach the last assistant message's `{ model, usage }` to a Claude Code\n * `Stop` / `StopFailure` payload, for a wrapper to hand to otel-hook.\n *\n * The usage is one request's, so it is attached with `usage_partial: true`,\n * which the exported generation reports as `otelhook.usage.partial`. For whole\n * turn totals, turn on `providers.claudeCode.readTranscriptUsage` instead.\n *\n * Returns the payload unchanged when it is not a stop, names no\n * `transcript_path`, already carries both fields, or the transcript yields\n * nothing — so a wrapper can call it unconditionally. A field the payload\n * already carries is never overwritten. Never throws, never rejects.\n */\nexport const attachClaudeTranscriptTurn = async (\n payload: unknown,\n options: ReadClaudeTranscriptTurnOptions = {},\n): Promise<unknown> => {\n const record = asRecord(payload);\n if (record === undefined) {\n return payload;\n }\n const eventName = eventNameOf(record);\n if (typeof eventName !== \"string\" || !STOP_EVENTS.has(eventName)) {\n return payload;\n }\n const transcriptPath = transcriptPathOf(record);\n if (typeof transcriptPath !== \"string\") {\n return payload;\n }\n const needsModel = record.model === undefined;\n const needsUsage = !hasUsage(record);\n if (!needsModel && !needsUsage) {\n return payload;\n }\n const turn = await readClaudeTranscriptTurn(transcriptPath, options);\n if (turn.status !== \"found\") {\n return payload;\n }\n return {\n ...record,\n ...(needsModel && turn.model !== undefined ? { model: turn.model } : {}),\n ...(needsUsage && turn.usage !== undefined ? { usage: turn.usage, usage_partial: true } : {}),\n };\n};\n\nexport type ClaudeTranscriptUsageEnricherOptions = ReadClaudeTranscriptTurnOptions &\n Omit<ReadClaudeTranscriptRangeOptions, \"agentId\">;\n\nexport const CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID = \"claude-transcript-usage\";\n\n/** Opaque, path-free name for a transcript, stored beside its cursor. */\nconst sourceDigest = (transcriptPath: string): string =>\n createHash(\"sha256\").update(transcriptPath, \"utf8\").digest(\"hex\").slice(0, 32);\n\nconst SUBAGENT_STOP = \"SubagentStop\";\n\nconst agentIdOf = (record: Record<string, unknown>): string | undefined => {\n const agentId = record.agent_id ?? record.agentId;\n return typeof agentId === \"string\" && agentId.length > 0 && agentId.length <= 256 ? agentId : undefined;\n};\n\nconst agentTranscriptPathOf = (record: Record<string, unknown>): unknown =>\n record.agent_transcript_path ?? record.agentTranscriptPath;\n\n/**\n * The cursor scope of a `SubagentStop`: one cursor per subagent, beside the\n * session's own. An opaque digest of the agent id, never the id or a path.\n */\nconst subagentCursorScope = (payload: unknown): string | undefined => {\n const record = asRecord(payload);\n if (record === undefined || eventNameOf(record) !== SUBAGENT_STOP) {\n return undefined;\n }\n const agentId = agentIdOf(record);\n return agentId === undefined\n ? undefined\n : `agent-${createHash(\"sha256\").update(agentId, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/**\n * The hook-runtime side of `providers.claudeCode.readTranscriptUsage`: attach\n * each turn's model and **summed** usage to its `Stop` / `StopFailure`, and each\n * subagent run's to its `SubagentStop`.\n *\n * The runtime keeps a byte cursor per session (state value `read-cursor`):\n *\n * - `SessionStart` records where the transcript ends now (0 when it does not\n * exist yet), unless a cursor for the same transcript is already stored — a\n * compaction restart must not skip the turn it interrupted.\n * - `Stop` sums every main-thread request from the cursor to the end, and moves\n * the cursor there. That is the exact turn total: `usage_partial: false`.\n * - With no usable cursor (enabled mid-session, an expired or lost store, a\n * different transcript), a range over the cap, or a transcript that shrank, it\n * falls back to the last request in the bounded tail, attaches it with\n * `usage_partial: true`, and moves the cursor to the end so the next turn is\n * exact again.\n * - A timeout or an unreadable file attaches nothing and keeps the cursor, so\n * the next turn's range includes this one: tokens are counted late, never\n * twice and never lost.\n *\n * `SubagentStop` does the same over the subagent's own transcript\n * (`agent_transcript_path`), with a cursor of its own per subagent (see\n * {@link PayloadEnricher.cursorScope}), summing that agent's sidechain records.\n * A subagent with no cursor yet is read from the start of its file: the file is\n * that subagent's alone, so the first stop is its exact total, not a fallback.\n * The parent's cursor is never touched, and the parent's `Stop` never counts\n * sidechain records, so a subagent's requests are counted once, on its own\n * generation (issue #68).\n *\n * A payload that already carries `usage` (a wrapper attached it) is left as it\n * is, and the cursor moves past it so those tokens are not counted again.\n */\nexport const createClaudeTranscriptUsageEnricher = (\n options: ClaudeTranscriptUsageEnricherOptions = {},\n): PayloadEnricher => {\n const fileSize = async (transcriptPath: string): Promise<number | \"absent\" | undefined> => {\n try {\n const info = await stat(transcriptPath);\n return info.isFile() ? info.size : undefined;\n } catch (thrown) {\n return (thrown as { code?: unknown } | undefined)?.code === \"ENOENT\" ? \"absent\" : undefined;\n }\n };\n\n const readOptions = (agentId: string | undefined): ReadClaudeTranscriptRangeOptions => ({\n ...(options.maxRangeBytes === undefined ? {} : { maxRangeBytes: options.maxRangeBytes }),\n ...(options.rangeTimeoutMillis === undefined ? {} : { rangeTimeoutMillis: options.rangeTimeoutMillis }),\n ...(agentId === undefined ? {} : { agentId }),\n });\n\n /**\n * Sum one transcript since `fromOffset` and attach the result, or fall back to\n * the bounded tail. `fromOffset` undefined means there is no usable cursor.\n */\n const attachSince = async (\n record: Record<string, unknown>,\n transcriptPath: string,\n fromOffset: number | undefined,\n agentId: string | undefined,\n ): Promise<PayloadEnrichment> => {\n const source = sourceDigest(transcriptPath);\n const attach = (\n model: string | undefined,\n usage: ClaudeUsage | undefined,\n partial: boolean,\n ): Record<string, unknown> => ({\n ...record,\n ...(record.model === undefined && model !== undefined ? { model } : {}),\n ...(usage === undefined ? {} : { usage, usage_partial: partial }),\n });\n\n if (fromOffset !== undefined) {\n const range = await readClaudeTranscriptRange(transcriptPath, fromOffset, readOptions(agentId));\n if (range.status === \"found\") {\n return {\n payload: attach(range.model, range.usage, false),\n cursor: { source, offset: range.endOffset },\n notes: [`summed ${String(range.requestCount)} request(s) since the last stop`],\n };\n }\n if (range.reason !== \"truncated\" && range.reason !== \"over-cap\") {\n return { payload: record, notes: [`transcript range not read (${range.reason}); cursor kept`] };\n }\n }\n\n // No usable cursor, or a range that cannot be summed within bounds.\n const tail = await boundedTail(transcriptPath, options, agentId);\n if (tail === TIMED_OUT || !(\"turn\" in tail)) {\n return { payload: record, notes: [`transcript tail not read (${tail === TIMED_OUT ? \"timeout\" : tail.reason})`] };\n }\n const why = fromOffset === undefined ? \"no cursor for this transcript\" : \"range not summable within bounds\";\n return {\n payload: tail.turn.status === \"found\" ? attach(tail.turn.model, tail.turn.usage, true) : record,\n cursor: { source, offset: tail.endOffset },\n notes: [`${why}; attached the last request only (usage_partial)`],\n };\n };\n\n /** A wrapper attached usage: keep it, and move the cursor past what it covered. */\n const skipAttached = async (payload: unknown, transcriptPath: string): Promise<PayloadEnrichment> => {\n const size = await fileSize(transcriptPath);\n return typeof size === \"number\"\n ? { payload, cursor: { source: sourceDigest(transcriptPath), offset: size } }\n : { payload };\n };\n\n const enrich = async (input: {\n readonly payload: unknown;\n readonly cursor?: ReadCursor;\n }): Promise<PayloadEnrichment> => {\n const unchanged: PayloadEnrichment = { payload: input.payload };\n const record = asRecord(input.payload);\n if (record === undefined) {\n return unchanged;\n }\n const eventName = eventNameOf(record);\n\n if (eventName === SUBAGENT_STOP) {\n const agentTranscriptPath = agentTranscriptPathOf(record);\n const agentId = agentIdOf(record);\n if (agentId === undefined || !isTranscriptPath(agentTranscriptPath)) {\n return unchanged;\n }\n if (hasUsage(record)) {\n return skipAttached(input.payload, agentTranscriptPath);\n }\n const cursor = input.cursor?.source === sourceDigest(agentTranscriptPath) ? input.cursor : undefined;\n return attachSince(record, agentTranscriptPath, cursor?.offset ?? 0, agentId);\n }\n\n const transcriptPath = transcriptPathOf(record);\n if (typeof eventName !== \"string\" || !isTranscriptPath(transcriptPath)) {\n return unchanged;\n }\n const source = sourceDigest(transcriptPath);\n const cursor = input.cursor?.source === source ? input.cursor : undefined;\n\n if (eventName === \"SessionStart\") {\n if (cursor !== undefined) {\n return unchanged;\n }\n const size = await fileSize(transcriptPath);\n if (size === undefined) {\n return { ...unchanged, notes: [\"transcript is not a readable regular file; no cursor recorded\"] };\n }\n return { payload: input.payload, cursor: { source, offset: size === \"absent\" ? 0 : size } };\n }\n\n if (!STOP_EVENTS.has(eventName)) {\n return unchanged;\n }\n if (hasUsage(record)) {\n return skipAttached(input.payload, transcriptPath);\n }\n return attachSince(record, transcriptPath, cursor?.offset, undefined);\n };\n\n return Object.freeze({\n id: CLAUDE_TRANSCRIPT_USAGE_ENRICHER_ID,\n providerId: CLAUDE_CODE_PROVIDER_ID,\n cursorScope: subagentCursorScope,\n enrich,\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Cursor agent-hook payload contract.\n *\n * ## Provenance\n *\n * Nothing in this module is invented. Every field, spelling, and unit below is\n * established by one or both of:\n *\n * 1. **Cursor's published hooks reference** — `cursor.com/docs/agent/hooks` and\n * `cursor.com/docs/hooks.md` (two URLs serving the same reference; both read\n * 2026-07-29). Source of the event-name list, the shared envelope, each\n * event's input fields, each event's stdout response, the `hooks.json`\n * schema, exit-code semantics, and the statement that `duration` and\n * `duration_ms` are milliseconds while `timeout` is seconds.\n * 2. **Real redacted captures** — `colinsurprenant/director`, under\n * `hack/canary/cursor-cli/findings/`: two Cursor CLI runs (`2026.07.17-3e2a980`,\n * captured 2026-07-21 and 2026-07-22) and two Cursor IDE runs (`3.12.17`,\n * captured 2026-07-21), each registering the full agent-hook set and recording\n * the exact key list of all 54 payload files it saved. Source of the fields\n * the reference omits, of which keys are actually optional, and of the two\n * lifecycle facts in \"Surface dependence\" below.\n *\n * The redacted fixtures under `fixtures/parity/cursor/` restate those captured\n * shapes with synthetic values; their provenance sidecars name this capture set.\n * No real path, email, transcript, prompt, or credential is copied into this\n * repository — see `CLAUDE.md`.\n *\n * ## Envelope\n *\n * Keys are snake_case throughout, and there is exactly one generation of the\n * shape: no camelCase variant and no legacy alias table is documented or\n * observed, so none is modelled. **There is no timestamp field anywhere** — not\n * in the reference, and not in any captured payload's key list — so the adapter\n * reads `occurredAt` from the injected clock, as the Claude Code adapter does.\n *\n * ## Surface dependence (captured, not documented)\n *\n * The same `hooks.json` produces different event subsets on Cursor's two\n * surfaces, which is why the registration planner's default set is chosen the\n * way it is:\n *\n * - `stop` and `afterAgentResponse` fired in the IDE runs and in neither CLI\n * run; `sessionEnd` fired in both CLI runs and in neither IDE run.\n * - One shell invocation fires **four** hooks. The CLI capture's `fired.log`\n * records `preToolUse`, `beforeShellExecution`, `afterShellExecution`,\n * `postToolUse` in that order for a single `printenv` call, with\n * `afterShellExecution` and `postToolUse` reporting the identical\n * `duration` of 169.812. Registering both pairs would report one tool call\n * twice.\n *\n * ## Forward compatibility\n *\n * Event objects are `z.object` (unknown keys stripped), not `z.strictObject`:\n * Cursor adds payload fields between releases — the reference already documents\n * a `preToolUse.agent_message` that no captured payload carries — and a\n * telemetry hook that rejects a payload for gaining a field fails closed on the\n * one thing it should tolerate.\n */\n\nexport const CURSOR_PROVIDER_ID = \"cursor\" as const;\n\n/**\n * Agent-session hook events this adapter interprets, in Cursor's own spelling.\n *\n * The reference groups its hooks as \"agent\", \"tab\", and \"app lifecycle\". Only\n * the agent group is here; see {@link CURSOR_UNMODELLED_HOOK_EVENT_NAMES}.\n */\nexport const CURSOR_HOOK_EVENT_NAMES = [\n \"sessionStart\",\n \"sessionEnd\",\n \"beforeSubmitPrompt\",\n \"afterAgentResponse\",\n \"afterAgentThought\",\n \"preToolUse\",\n \"postToolUse\",\n \"postToolUseFailure\",\n \"beforeShellExecution\",\n \"afterShellExecution\",\n \"beforeMCPExecution\",\n \"afterMCPExecution\",\n \"beforeReadFile\",\n \"afterFileEdit\",\n \"subagentStart\",\n \"subagentStop\",\n \"preCompact\",\n \"stop\",\n] as const;\nexport type CursorHookEventName = (typeof CURSOR_HOOK_EVENT_NAMES)[number];\n\n/**\n * Event names Cursor documents that this adapter deliberately does not model,\n * each with the reason. Recognized by name so a payload carrying one is\n * reported as \"known, unmodelled\" rather than as an unrecognized provider.\n */\nexport const CURSOR_UNMODELLED_HOOK_EVENT_NAMES: Readonly<Record<string, string>> = Object.freeze({\n beforeTabFileRead:\n \"a Tab (inline-completion) hook, not an agent-session hook; it belongs to no generation or tool lifecycle this model expresses\",\n afterTabFileEdit: \"a Tab (inline-completion) hook, as above\",\n workspaceOpen:\n \"an app-lifecycle hook that the reference states omits conversation_id, generation_id, model, session_id, and transcript_path, so it carries no session to attribute telemetry to\",\n});\n\n/**\n * Events whose stdout Cursor reads a decision from, and the field it reads.\n *\n * Taken from the reference's per-event \"Output\" sections. `beforeSubmitPrompt`\n * is the one event keyed `continue` rather than `permission`; the shell and MCP\n * gates additionally accept `\"ask\"`, which this tool never emits.\n */\nexport const CURSOR_DECISION_EVENTS: Readonly<Record<string, \"permission\" | \"continue\">> =\n Object.freeze({\n preToolUse: \"permission\",\n beforeShellExecution: \"permission\",\n beforeMCPExecution: \"permission\",\n beforeReadFile: \"permission\",\n subagentStart: \"permission\",\n beforeSubmitPrompt: \"continue\",\n });\n\n/** `[{ id, value }]`, per the reference's shared envelope. */\nconst modelParamSchema = z.object({\n id: z.string(),\n value: z.string(),\n});\nexport type CursorModelParam = z.infer<typeof modelParamSchema>;\n\nconst attachmentSchema = z.object({\n type: z.string().optional(),\n file_path: z.string().optional(),\n});\n\n/** `{ old_string, new_string }` pairs. Content, never exported — see the adapter. */\nconst fileEditSchema = z.object({\n old_string: z.string().optional(),\n new_string: z.string().optional(),\n});\n\n/**\n * Token counters observed on `afterAgentResponse` and `stop` in the IDE\n * captures. Absent from the published reference, which is why they are all\n * optional and why {@link CURSOR_USAGE_INCLUSIVITY_NOTE} states the one reading\n * the captures do not settle.\n */\nconst usageFields = {\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_read_tokens: z.number().int().min(0).optional(),\n cache_write_tokens: z.number().int().min(0).optional(),\n};\n\nexport const CURSOR_USAGE_INCLUSIVITY_NOTE =\n \"Cursor does not document its token counters, so whether input_tokens already includes cache_read_tokens \" +\n \"cannot be settled from the reference. Every captured sample has cache_read_tokens strictly below \" +\n \"input_tokens (28384/43859, 7040/21033, 77920/94622) with a stable ~15-17k remainder as the cached prefix \" +\n \"grows, which is what an inclusive counter looks like; the adapter therefore reads input_tokens as the \" +\n \"canonical inclusive total and cache_read_tokens as a subset of it. Where a payload contradicts that \" +\n \"reading, the adapter drops the breakdown rather than reporting a total it cannot justify.\";\n\n/**\n * Fields the reference lists as present on every agent hook.\n *\n * `conversation_id` is the session identity every captured agent payload\n * carries, and `session_id` repeats it in every capture — see\n * {@link cursorSessionId} for why the schema no longer hard-requires the\n * former by itself. `cwd` is *not* `.min(1)` — the CLI captures report\n * `\"cwd\": \"\"` for a workspace-rooted call, and rejecting an empty string would\n * drop the whole event over a field the adapter never reads for identity.\n *\n * `user_email` and `transcript_path` are declared so they parse rather than\n * being silently stripped, and are then never read by any code path. They are a\n * real address and a real filesystem path; `tests/providers/cursor` asserts\n * neither reaches a sink.\n */\nconst envelopeShape = {\n // Not `.min(1)`: see `cursorSessionId`. A payload naming neither\n // `conversation_id` nor `session_id` is still rejected — by\n // `recognizeCursorPayload`'s post-parse check — but rejecting it here would\n // fail the whole discriminated union on a field the adapter can source from\n // either name.\n conversation_id: z.string().optional(),\n generation_id: z.string().optional(),\n session_id: z.string().optional(),\n model: z.string().optional(),\n model_id: z.string().optional(),\n model_params: z.array(modelParamSchema).max(64).optional(),\n cursor_version: z.string().optional(),\n workspace_roots: z.array(z.string()).max(64).optional(),\n cwd: z.string().optional(),\n /** Never propagated. */\n user_email: z.string().nullish(),\n /** Never propagated. */\n transcript_path: z.string().nullish(),\n};\n\nconst event = <TName extends CursorHookEventName, TShape extends z.ZodRawShape>(\n name: TName,\n shape: TShape,\n) => z.object({ ...envelopeShape, hook_event_name: z.literal(name), ...shape });\n\nconst sessionStartPayloadSchema = event(\"sessionStart\", {\n is_background_agent: z.boolean().optional(),\n composer_mode: z.string().optional(),\n});\n\n/**\n * `reason` and `final_status` are free strings rather than enums on purpose.\n * The reference lists five reasons (`completed`, `aborted`, `error`,\n * `window_close`, `user_close`) and the adapter maps exactly those; a sixth\n * Cursor adds later must degrade to `unknown`, not reject the event.\n */\nconst sessionEndPayloadSchema = event(\"sessionEnd\", {\n reason: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n is_background_agent: z.boolean().optional(),\n final_status: z.string().optional(),\n error_message: z.string().optional(),\n});\n\nconst beforeSubmitPromptPayloadSchema = event(\"beforeSubmitPrompt\", {\n prompt: z.string().optional(),\n attachments: z.array(attachmentSchema).max(256).optional(),\n composer_mode: z.string().optional(),\n});\n\nconst afterAgentResponsePayloadSchema = event(\"afterAgentResponse\", {\n text: z.string().optional(),\n ...usageFields,\n});\n\nconst afterAgentThoughtPayloadSchema = event(\"afterAgentThought\", {\n text: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n});\n\nconst preToolUsePayloadSchema = event(\"preToolUse\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n agent_message: z.string().optional(),\n});\n\n/**\n * `tool_output` is `z.unknown()` because both shapes occur: the CLI capture\n * reports an object (`{ output, exitCode }`), the IDE capture a JSON-encoded\n * string, and the reference documents the string. Neither is parsed for meaning.\n */\nconst postToolUsePayloadSchema = event(\"postToolUse\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_output: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n duration: z.number().min(0).optional(),\n});\n\nconst postToolUseFailurePayloadSchema = event(\"postToolUseFailure\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n error_message: z.string().optional(),\n failure_type: z.string().optional(),\n duration: z.number().min(0).optional(),\n is_interrupt: z.boolean().optional(),\n});\n\nconst beforeShellExecutionPayloadSchema = event(\"beforeShellExecution\", {\n command: z.string(),\n sandbox: z.boolean().optional(),\n});\n\n/**\n * No exit status. The reference lists `command`, `output`, `duration`, and\n * `sandbox`, the captures confirm exactly those, and neither carries an exit\n * code — so the adapter reports this tool end with outcome `unknown` rather\n * than assuming success.\n */\nconst afterShellExecutionPayloadSchema = event(\"afterShellExecution\", {\n command: z.string(),\n output: z.string().optional(),\n duration: z.number().min(0).optional(),\n sandbox: z.boolean().optional(),\n});\n\nconst beforeMcpExecutionPayloadSchema = event(\"beforeMCPExecution\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n url: z.string().optional(),\n command: z.string().optional(),\n});\n\n/** As with the shell pair: `result_json` is opaque, and there is no status field. */\nconst afterMcpExecutionPayloadSchema = event(\"afterMCPExecution\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n result_json: z.string().optional(),\n duration: z.number().min(0).optional(),\n});\n\nconst beforeReadFilePayloadSchema = event(\"beforeReadFile\", {\n file_path: z.string(),\n content: z.string().optional(),\n attachments: z.array(attachmentSchema).max(256).optional(),\n});\n\nconst afterFileEditPayloadSchema = event(\"afterFileEdit\", {\n file_path: z.string(),\n edits: z.array(fileEditSchema).max(1024).optional(),\n});\n\nconst subagentStartPayloadSchema = event(\"subagentStart\", {\n subagent_id: z.string().optional(),\n subagent_type: z.string().optional(),\n task: z.string().optional(),\n parent_conversation_id: z.string().optional(),\n tool_call_id: z.string().optional(),\n subagent_model: z.string().optional(),\n is_parallel_worker: z.boolean().optional(),\n git_branch: z.string().optional(),\n});\n\n/**\n * Carries no subagent identifier. The reference gives `subagentStart` a\n * `subagent_id` and gives `subagentStop` only `subagent_type`, so the two\n * cannot be paired — which is why the adapter ignores both rather than emitting\n * a `subagent.start` that nothing can close. No capture contains either event.\n */\nconst subagentStopPayloadSchema = event(\"subagentStop\", {\n subagent_type: z.string().optional(),\n status: z.string().optional(),\n task: z.string().optional(),\n description: z.string().optional(),\n summary: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n message_count: z.number().int().min(0).optional(),\n tool_call_count: z.number().int().min(0).optional(),\n loop_count: z.number().int().min(0).optional(),\n modified_files: z.array(z.string()).max(1024).optional(),\n agent_transcript_path: z.string().nullish(),\n});\n\n/** `trigger` is `auto | manual` per the reference; mapped in the adapter. */\nconst preCompactPayloadSchema = event(\"preCompact\", {\n trigger: z.string().optional(),\n context_usage_percent: z.number().optional(),\n context_tokens: z.number().int().min(0).optional(),\n context_window_size: z.number().int().min(0).optional(),\n message_count: z.number().int().min(0).optional(),\n messages_to_compact: z.number().int().min(0).optional(),\n is_first_compaction: z.boolean().optional(),\n});\n\nconst stopPayloadSchema = event(\"stop\", {\n status: z.string().optional(),\n loop_count: z.number().int().min(0).optional(),\n ...usageFields,\n});\n\nexport const cursorPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n beforeSubmitPromptPayloadSchema,\n afterAgentResponsePayloadSchema,\n afterAgentThoughtPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n beforeShellExecutionPayloadSchema,\n afterShellExecutionPayloadSchema,\n beforeMcpExecutionPayloadSchema,\n afterMcpExecutionPayloadSchema,\n beforeReadFilePayloadSchema,\n afterFileEditPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n stopPayloadSchema,\n]);\nexport type CursorPayload = z.infer<typeof cursorPayloadSchema>;\n\nexport type CursorPayloadOf<TName extends CursorHookEventName> = Extract<\n CursorPayload,\n { hook_event_name: TName }\n>;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type CursorRecognition =\n /** A modelled agent hook that validated against its schema. */\n | { readonly status: \"modelled\"; readonly payload: CursorPayload }\n /** A documented Cursor event this adapter does not model, with the reason. */\n | { readonly status: \"unmodelled\"; readonly eventName: string; readonly reason: string }\n /** A modelled event name whose payload does not satisfy its schema. */\n | { readonly status: \"invalid\"; readonly eventName: string; readonly detail: string };\n\n/**\n * Recognize a raw Cursor hook payload.\n *\n * Three outcomes rather than two, so the adapter can tell \"not Cursor at all\"\n * (undefined) from \"Cursor, but nothing this adapter turns into telemetry\"\n * (`unmodelled`) from \"Cursor, and malformed\" (`invalid`) — the middle case must\n * not be reported as a parse failure, and the last must not be reported as a\n * foreign payload.\n */\nexport const recognizeCursorPayload = (payload: unknown): CursorRecognition | undefined => {\n if (!isPlainObject(payload)) {\n return undefined;\n }\n const eventName = payload.hook_event_name;\n if (typeof eventName !== \"string\") {\n return undefined;\n }\n\n const unmodelled = CURSOR_UNMODELLED_HOOK_EVENT_NAMES[eventName];\n if (unmodelled !== undefined) {\n return { status: \"unmodelled\", eventName, reason: unmodelled };\n }\n if (!(CURSOR_HOOK_EVENT_NAMES as readonly string[]).includes(eventName)) {\n return undefined;\n }\n\n const parsed = cursorPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n const [issue] = parsed.error.issues;\n return {\n status: \"invalid\",\n eventName,\n detail:\n issue === undefined\n ? \"payload does not satisfy the cursor hook schema\"\n : `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n };\n }\n if (cursorSessionId(parsed.data) === undefined) {\n return {\n status: \"invalid\",\n eventName,\n detail: \"payload names neither conversation_id nor session_id, so it carries no session to attribute telemetry to\",\n };\n }\n return { status: \"modelled\", payload: parsed.data };\n};\n\n/** Validated payload, or `undefined` for anything else. Convenience for callers. */\nexport const normalizeCursorPayload = (payload: unknown): CursorPayload | undefined => {\n const recognized = recognizeCursorPayload(payload);\n return recognized?.status === \"modelled\" ? recognized.payload : undefined;\n};\n\n/**\n * The session identity to attribute a modelled payload to.\n *\n * `conversation_id` is preferred, but some live Cursor Agent-surface\n * `beforeSubmitPrompt` deliveries have been observed missing it while still\n * carrying `session_id` — which every capture in `./payload.ts`'s provenance\n * note shows repeating `conversation_id` exactly. Previously the schema\n * required `conversation_id` unconditionally, so any callback missing it —\n * this one included — failed detection outright and was silently declined as\n * `provider-unknown`, with no `prompt.submitted` ever emitted for that\n * conversation. Falling back to `session_id` is not a guess: it is reading the\n * same identity from the field Cursor's own envelope repeats it in, and\n * `recognizeCursorPayload` still rejects a payload naming neither.\n */\nexport const cursorSessionId = (payload: CursorPayload): string | undefined => {\n if (payload.conversation_id !== undefined && payload.conversation_id.length > 0) {\n return payload.conversation_id;\n }\n return payload.session_id !== undefined && payload.session_id.length > 0\n ? payload.session_id\n : undefined;\n};\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { cursorSessionId, normalizeCursorPayload, type CursorPayload } from \"./payload.js\";\n\n/**\n * Which Cursor callbacks carry an identifier that survives a redelivery.\n *\n * Cursor's envelope scopes the identity by `conversation_id`, or by\n * `session_id` on the live deliveries observed missing it — see\n * `cursorSessionId` in `./payload.ts`. On top of it:\n *\n * - `tool_use_id` names one tool call, and the event name separates its\n * before-edge from its after-edge and from its failure edge.\n * - `generation_id` names one generation, and `beforeSubmitPrompt` and `stop`\n * each fire once per generation.\n * - `sessionStart`/`sessionEnd` fire once per conversation, so the event name\n * alone identifies them.\n *\n * Excluded on purpose:\n *\n * - The dedicated shell, MCP, and file callbacks carry no `tool_use_id` at all —\n * neither the reference nor any capture shows one. What distinguishes two of\n * them is the command line or the file path, which are content, not\n * identifiers; the contract's component guard rejects both (no whitespace, no\n * path separators), and it is right to. `generation_id` alone would be wrong\n * in the other direction: one generation runs many shell commands, so it would\n * suppress genuine second calls as redeliveries.\n * - `preCompact` carries nothing that separates two genuine compactions.\n * - `subagentStart`/`subagentStop` produce no events at all (see `adapter.ts`),\n * so there is nothing to deduplicate.\n * - There is no timestamp field to mix in, and Cursor sends none — so the usual\n * temptation to make two same-millisecond callbacks distinguishable does not\n * even arise here.\n */\nconst deliveryComponents = (\n payload: CursorPayload,\n): { readonly components: readonly string[]; readonly evidence: readonly string[] } | undefined => {\n switch (payload.hook_event_name) {\n case \"sessionStart\":\n case \"sessionEnd\":\n return {\n components: [payload.hook_event_name],\n evidence: [`cursor fires ${payload.hook_event_name} once per conversation`],\n };\n case \"beforeSubmitPrompt\":\n case \"stop\":\n return payload.generation_id === undefined || payload.generation_id.length === 0\n ? undefined\n : {\n components: [payload.generation_id],\n evidence: [\n `payload.generation_id names one generation, which fires ${payload.hook_event_name} once`,\n ],\n };\n case \"preToolUse\":\n case \"postToolUse\":\n case \"postToolUseFailure\":\n return payload.tool_use_id === undefined || payload.tool_use_id.length === 0\n ? undefined\n : {\n components: [payload.tool_use_id],\n evidence: [\"payload.tool_use_id names one tool call and repeats on redelivery\"],\n };\n case \"afterAgentResponse\":\n case \"afterAgentThought\":\n case \"beforeShellExecution\":\n case \"afterShellExecution\":\n case \"beforeMCPExecution\":\n case \"afterMCPExecution\":\n case \"beforeReadFile\":\n case \"afterFileEdit\":\n case \"subagentStart\":\n case \"subagentStop\":\n case \"preCompact\":\n return undefined;\n }\n};\n\n/**\n * Why each Cursor callback that {@link cursorDeliveryIdentity} declines carries no\n * delivery identity.\n *\n * Exhaustive over the hook event names in `./payload.ts`. Only `preCompact` is\n * unconditionally unidentifiable; the rest appear here for the case where their\n * optional `toolCallId` is absent, which is the whole of Cursor's coverage gap.\n */\nexport const CURSOR_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n preCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n afterAgentResponse:\n \"generation_id alone would collide with stop for the same generation; Cursor fires both with the same token snapshot\",\n afterAgentThought:\n \"payload.thoughtIndex absent; generationId alone names the generation, not one thought within it\",\n subagentStart:\n \"subagentStop carries no subagent id, so the pair cannot be correlated and neither edge is identified\",\n subagentStop:\n \"subagentStop carries no subagent id, so the pair cannot be correlated and neither edge is identified\",\n beforeShellExecution:\n \"payload.toolCallId absent; the only remaining field is the command line, which is content and may not become an id\",\n afterShellExecution:\n \"payload.toolCallId absent; the only remaining field is the command line, which is content and may not become an id\",\n beforeMCPExecution:\n \"payload.toolCallId absent; the only remaining fields are the tool name and its arguments, which are content\",\n afterMCPExecution:\n \"payload.toolCallId absent; the only remaining fields are the tool name and its arguments, which are content\",\n afterFileEdit:\n \"payload.toolCallId absent; the only remaining field is the file path, which is content and may not become an id\",\n beforeReadFile:\n \"payload.toolCallId absent; the only remaining field is the file path, which is content and may not become an id\",\n});\n\nexport const cursorDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const payload = normalizeCursorPayload(input.payload);\n if (payload === undefined) {\n return undefined;\n }\n const sessionId = cursorSessionId(payload);\n if (sessionId === undefined) {\n return undefined;\n }\n const identified = deliveryComponents(payload);\n if (identified === undefined) {\n return undefined;\n }\n return {\n sessionId,\n sourceEventName: payload.hook_event_name,\n components: identified.components,\n evidence: identified.evidence,\n };\n};\n","import { sessionCwdHint, type TargetHint } from \"../../model/target.js\";\nimport type { CursorPayload } from \"./payload.js\";\n\n/**\n * Where a Cursor tool callback pointed, as a target hint (ADR 0008).\n *\n * - **`tool-path`** — `afterFileEdit.file_path` and `beforeReadFile.file_path`\n * (the reference: \"Absolute path to the file being read\").\n * - **`shell-cwd`** — the `cwd` Cursor reports on `beforeShellExecution` (the\n * reference lists it there and not on `afterShellExecution`; read on the\n * latter only if a payload carries it).\n * - **`session-cwd`** — the workspace root, when the workspace has exactly one;\n * also the only hint on `sessionStart` and `beforeSubmitPrompt`.\n * A multi-root workspace has no single session directory, so it gives none.\n *\n * The CLI captures report `cwd: \"\"` for a call rooted at the workspace; an\n * empty `cwd` is therefore \"no shell directory stated\", and falls back to the\n * workspace root rather than being read as the filesystem root.\n */\n\nconst singleWorkspaceRoot = (payload: CursorPayload): string | undefined => {\n const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);\n return roots.length === 1 ? roots[0] : undefined;\n};\n\n\nexport const cursorTargetHint = (payload: CursorPayload): TargetHint | undefined => {\n const root = singleWorkspaceRoot(payload);\n const base = root === undefined ? {} : { baseDirectory: root };\n switch (payload.hook_event_name) {\n case \"afterFileEdit\":\n case \"beforeReadFile\":\n return payload.file_path.length === 0\n ? sessionCwdHint(root)\n : { source: \"tool-path\", paths: [payload.file_path], ...base };\n case \"beforeShellExecution\":\n case \"afterShellExecution\":\n return payload.cwd !== undefined && payload.cwd.length > 0\n ? { source: \"shell-cwd\", paths: [payload.cwd], ...base }\n : sessionCwdHint(root);\n case \"sessionStart\":\n case \"beforeSubmitPrompt\":\n case \"preToolUse\":\n case \"postToolUse\":\n case \"postToolUseFailure\":\n case \"beforeMCPExecution\":\n case \"afterMCPExecution\":\n return sessionCwdHint(root);\n default:\n return undefined;\n }\n};\n","import { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\n\nexport type CursorTokenCounters = {\n readonly input_tokens?: number | undefined;\n readonly output_tokens?: number | undefined;\n readonly cache_read_tokens?: number | undefined;\n readonly cache_write_tokens?: number | undefined;\n};\n\nexport type CursorUsageNormalization = {\n readonly usage?: CanonicalUsage;\n readonly warnings: readonly string[];\n};\n\n/**\n * Normalize Cursor's token counters into canonical usage.\n *\n * These four counters appear on `afterAgentResponse` and `stop` in the IDE\n * captures and are absent from Cursor's published reference, so the mapping is\n * deliberately narrow:\n *\n * - `input_tokens` is read as the canonical *inclusive* input total and\n * `cache_read_tokens` as a subset of it. `CURSOR_USAGE_INCLUSIVITY_NOTE` in\n * `./payload.ts` records the captured evidence for that reading, and the fact\n * that Cursor does not document it.\n * - A payload where `cache_read_tokens` exceeds `input_tokens` contradicts the\n * inclusive reading. Rather than clamp — which would invent a billing story —\n * the cache breakdown is dropped, the input and output totals are kept, and a\n * warning names the contradiction.\n * - `cache_write_tokens` is **not** reported at all. Canonical usage requires an\n * explicit `cacheCreationAccounting` whenever `cacheCreationInputTokens` is\n * non-zero, and whether Cursor bills cache writes inside or beside\n * `input_tokens` is exactly what no source establishes: the reference does not\n * mention the field, and every captured sample reports 0, so there is not even\n * an arithmetic hint. `included-in-input` would understate the total and\n * `disjoint-from-input` would inflate it, so a non-zero value produces a\n * warning naming the dropped field rather than either guess.\n *\n * Each snapshot covers one generation, never a running session total, so it is\n * always reported as a `delta` observation.\n */\nexport const normalizeCursorUsage = (raw: CursorTokenCounters): CursorUsageNormalization => {\n const inputTokens = raw.input_tokens;\n const outputTokens = raw.output_tokens;\n const cacheReadTokens = raw.cache_read_tokens;\n const cacheWriteTokens = raw.cache_write_tokens;\n\n const dropped: string[] =\n cacheWriteTokens === undefined || cacheWriteTokens === 0\n ? []\n : [\n `cursor reported cache_write_tokens (${String(cacheWriteTokens)}), whose accounting relative to ` +\n \"input_tokens is undocumented, so it was not folded into canonical usage\",\n ];\n\n if (inputTokens === undefined && outputTokens === undefined && cacheReadTokens === undefined) {\n return { warnings: dropped };\n }\n\n const warnings: string[] = [...dropped];\n const contradictsInclusive =\n cacheReadTokens !== undefined && inputTokens !== undefined && cacheReadTokens > inputTokens;\n if (contradictsInclusive) {\n warnings.push(\n `cursor reported cache_read_tokens (${String(cacheReadTokens)}) above input_tokens ` +\n `(${String(inputTokens)}); the cache breakdown was dropped rather than reinterpreted`,\n );\n }\n\n const result = normalizeUsage({\n temporality: \"delta\",\n ...(inputTokens === undefined ? {} : { inputTokens }),\n ...(outputTokens === undefined ? {} : { outputTokens }),\n ...(cacheReadTokens === undefined || contradictsInclusive\n ? {}\n : { cachedInputTokens: cacheReadTokens }),\n });\n\n if (result.status === \"invalid\") {\n return { warnings: [...warnings, ...result.issues.map((issue) => issue.message)] };\n }\n return { usage: result.usage, warnings: [...warnings, ...result.notes] };\n};\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { EventOutcome, ModelDescriptor } from \"../../model/events.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport {\n asProviderId,\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderHookResponseInput,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport { CURSOR_DELIVERY_GAPS, cursorDeliveryIdentity } from \"./delivery.js\";\nimport {\n CURSOR_DECISION_EVENTS,\n CURSOR_PROVIDER_ID,\n cursorSessionId,\n recognizeCursorPayload,\n type CursorPayload,\n} from \"./payload.js\";\nimport { cursorTargetHint } from \"./target.js\";\nimport { normalizeCursorUsage } from \"./usage.js\";\n\n/**\n * Provider adapter for Cursor's agent hooks.\n *\n * `./payload.ts` carries the full provenance note: the contract is derived from\n * Cursor's published hooks reference plus four real redacted capture runs, and\n * this module maps only what those establish. Three lifecycle decisions follow\n * from that evidence rather than from convenience, and each is stated where it\n * is made below:\n *\n * - `generation.end` comes from `stop`, not `afterAgentResponse`.\n * - The shell and MCP tool ends report outcome `unknown`, because Cursor sends\n * no exit status on those callbacks.\n * - Both subagent callbacks are ignored, because `subagentStop` carries no\n * subagent identifier to pair with `subagentStart`.\n */\n\nexport const CURSOR_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"compaction.performed\",\n ] as const),\n usageTemporality: \"delta\",\n // Cursor's `cache_read_tokens` is read as a subset of `input_tokens`; see\n // `./usage.ts` for the captured evidence and the guard when a payload\n // contradicts it.\n reportsCachedInput: true,\n // `cache_write_tokens` is reported by Cursor but its accounting is\n // undocumented, so it is surfaced as an extension rather than folded into a\n // canonical total. See `./usage.ts`.\n reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\n reportsReasoningOutput: false,\n reportsProviderTotal: false,\n reportsCost: false,\n // `subagentStop` carries no subagent id, so no pairable subagent lifecycle can\n // be produced. See the `ignored` branch below.\n emitsSubagentEvents: false,\n emitsCompactionEvents: true,\n requiresHookResponse: true,\n // Tool and generation callbacks carry a replay-stable id; the dedicated\n // shell/MCP/file callbacks and `preCompact` do not. See `./delivery.ts`.\n deliveryIdentifier: \"partial\",\n});\n\n/** Sentinel used when a payload names no model at all. */\nconst UNKNOWN_MODEL: ModelDescriptor = Object.freeze({ modelId: \"unknown\" });\n\n/**\n * Cursor reports a model *variant* in `model` and its base in `model_id` — the\n * captures show `model: \"composer-2.5-fast\"` beside `model_id: \"composer-2.5\"`.\n * The variant is the identifier of what ran, so it becomes `modelId`; the base\n * becomes `family`, and is dropped when it merely repeats the variant. Vendor is\n * never guessed: Cursor names no vendor anywhere in the payload.\n */\nconst toModelDescriptor = (payload: CursorPayload): ModelDescriptor => {\n const modelId = payload.model;\n if (modelId === undefined || modelId.length === 0) {\n return UNKNOWN_MODEL;\n }\n const family = payload.model_id;\n return {\n modelId,\n ...(family === undefined || family.length === 0 || family === modelId ? {} : { family }),\n };\n};\n\nconst SESSION_END_REASONS: Readonly<\n Record<string, \"completed\" | \"aborted\" | \"error\" | \"timeout\" | \"unknown\">\n> = Object.freeze({\n completed: \"completed\",\n aborted: \"aborted\",\n error: \"error\",\n // Both documented \"the window/user closed it\" reasons are an abort from the\n // agent's point of view: work stopped without finishing.\n window_close: \"aborted\",\n user_close: \"aborted\",\n});\n\n/** `stop.status` and `subagentStop.status` share this vocabulary. */\nconst STOP_STATUS_TO_OUTCOME: Readonly<Record<string, EventOutcome>> = Object.freeze({\n completed: \"ok\",\n aborted: \"cancelled\",\n error: \"error\",\n});\n\nconst COMPACT_TRIGGERS: Readonly<Record<string, \"automatic\" | \"manual\">> = Object.freeze({\n auto: \"automatic\",\n manual: \"manual\",\n});\n\n/**\n * Derive privacy-safe workspace identity from the payload's own directory facts.\n *\n * `workspace_roots` first, `cwd` only as a fallback — and never a process cwd:\n * an absent or empty list simply contributes no workspace claim, letting the\n * core's `unknown` fallback apply. The CLI captures report `cwd: \"\"`, which is\n * treated as absent rather than as the filesystem root.\n */\nconst deriveWorkspace = (\n context: ProviderContext,\n payload: CursorPayload,\n): ReturnType<typeof deriveWorkspaceIdentity> | undefined => {\n const roots = (payload.workspace_roots ?? []).filter((root) => root.length > 0);\n if (roots.length === 1) {\n return deriveWorkspaceIdentity(context.privacy, {\n kind: \"working-directory\",\n absolutePath: roots[0] ?? \"\",\n });\n }\n if (roots.length > 1) {\n return deriveWorkspaceIdentity(context.privacy, {\n kind: \"explicit\",\n value: [...roots].sort().join(\"\\n\"),\n });\n }\n if (payload.cwd !== undefined && payload.cwd.length > 0) {\n return deriveWorkspaceIdentity(context.privacy, {\n kind: \"working-directory\",\n absolutePath: payload.cwd,\n });\n }\n return undefined;\n};\n\n/**\n * Stable per-call uniqueness fed into the invocation id hash. Every value comes\n * from the payload itself, never from process state, so replaying a payload\n * reproduces the same id.\n */\nconst invocationDiscriminator = (payload: CursorPayload): string | undefined => {\n switch (payload.hook_event_name) {\n case \"sessionStart\":\n case \"sessionEnd\":\n return undefined;\n case \"preToolUse\":\n case \"postToolUse\":\n case \"postToolUseFailure\":\n return payload.tool_use_id ?? payload.tool_name;\n case \"beforeShellExecution\":\n case \"afterShellExecution\":\n return payload.generation_id;\n case \"beforeMCPExecution\":\n case \"afterMCPExecution\":\n return payload.tool_name;\n case \"beforeReadFile\":\n case \"afterFileEdit\":\n return payload.generation_id;\n case \"subagentStart\":\n return payload.subagent_id;\n case \"subagentStop\":\n return payload.subagent_type;\n case \"preCompact\":\n return payload.trigger;\n default:\n return payload.generation_id;\n }\n};\n\n/**\n * A tool call id for a callback that carries none.\n *\n * `beforeShellExecution`/`afterShellExecution` and the MCP pair report no\n * `tool_use_id`, so the pair is joined on the fields that *are* stable across\n * it: the generation and the command (or server-qualified tool name). Both\n * halves of a pair derive the same id from the same payload facts, which is what\n * lets the span correlator match them — and none of it is a clock or process\n * read, so a replay derives the same id again.\n */\nconst derivedToolCallId = (\n context: ProviderContext,\n sessionId: string,\n parts: readonly string[],\n): string => context.ids.newOpaqueId([sessionId, ...parts]);\n\n/** The validated payload, or `undefined` for anything this adapter cannot map. */\nconst asModelled = (payload: unknown): CursorPayload | undefined => {\n const recognized = recognizeCursorPayload(payload);\n return recognized?.status === \"modelled\" ? recognized.payload : undefined;\n};\n\n/** Longest detection reason the contract accepts. */\nconst MAX_DETECTION_REASON_LENGTH = 160;\n\nconst bounded = (reason: string): string =>\n reason.length <= MAX_DETECTION_REASON_LENGTH\n ? reason\n : `${reason.slice(0, MAX_DETECTION_REASON_LENGTH - 1)}…`;\n\nexport type CursorAdapterOptions = {\n readonly version?: string;\n};\n\nexport const CURSOR_ADAPTER_VERSION = \"2.0.0\";\n\nexport const createCursorAdapter = (options: CursorAdapterOptions = {}): ProviderAdapter => {\n const id = asProviderId(CURSOR_PROVIDER_ID);\n const version = options.version ?? CURSOR_ADAPTER_VERSION;\n const capabilities = CURSOR_CAPABILITIES;\n\n const detect = (input: ProviderDetectionInput): ProviderDetection => {\n const recognized = recognizeCursorPayload(input.payload);\n if (recognized === undefined) {\n return unknownDetection([\"payload does not match the cursor hook contract\"]);\n }\n // Detection reasons are bounded at 160 characters, and both branches below\n // interpolate a provider-supplied string, so each is trimmed to fit rather\n // than thrown away by the schema.\n if (recognized.status === \"unmodelled\") {\n return unknownDetection([\n bounded(`cursor documents \"${recognized.eventName}\" but this adapter does not model it`),\n ]);\n }\n if (recognized.status === \"invalid\") {\n return unknownDetection([\n bounded(\n `cursor \"${recognized.eventName}\" payload does not satisfy its contract: ${recognized.detail}`,\n ),\n ]);\n }\n const { payload } = recognized;\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"exact\",\n reasons: [`payload.hook_event_name \"${payload.hook_event_name}\" recognized`],\n ...(payload.cursor_version === undefined || payload.cursor_version.length === 0\n ? {}\n : { providerVersion: payload.cursor_version }),\n sourceEventName: payload.hook_event_name,\n });\n };\n\n const identify = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): readonly IdentityClaim[] => {\n const payload = asModelled(input.payload);\n if (payload === undefined) {\n return [];\n }\n const workspace = deriveWorkspace(context, payload);\n const discriminator = invocationDiscriminator(payload);\n // Cursor's own conversation id, used exactly as reported: never\n // normalized, parent/child matched, or substituted for a derived value.\n // `session_id` repeats it in every capture, and is the fallback\n // `recognizeCursorPayload` guarantees is present when `conversation_id`\n // is not — see `cursorSessionId`.\n const sessionId = cursorSessionId(payload);\n if (sessionId === undefined) {\n return [];\n }\n // Cursor sends no timestamp on any hook — see `./payload.ts`. The clock is\n // the only available reading, as it is for Claude Code.\n const occurredAt = context.clock.now();\n const invocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId,\n sourceEventName: payload.hook_event_name,\n occurredAt,\n ...(discriminator === undefined ? {} : { discriminator }),\n });\n const claim = identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt: occurredAt,\n ...(workspace === undefined ? {} : { workspace }),\n },\n });\n return [claim];\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const recognized = recognizeCursorPayload(input.payload);\n if (recognized === undefined) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the cursor hook contract\",\n }),\n };\n }\n if (recognized.status === \"unmodelled\") {\n return {\n status: \"ignored\",\n reason: `cursor \"${recognized.eventName}\" is not modelled: ${recognized.reason}`,\n };\n }\n if (recognized.status === \"invalid\") {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: `cursor \"${recognized.eventName}\" payload is malformed (${recognized.detail})`,\n }),\n };\n }\n\n const { payload } = recognized;\n\n if (payload.hook_event_name === \"afterAgentResponse\") {\n return {\n status: \"ignored\",\n reason:\n \"the generation's terminal outcome is reported from stop, which carries a status field and the \" +\n \"identical token snapshot (captured: 43859/1076/28384/0 on both callbacks of one generation); \" +\n \"emitting generation.end from both would double-count usage, and this adapter holds no \" +\n \"cross-invocation state to deduplicate them\",\n };\n }\n\n if (payload.hook_event_name === \"afterAgentThought\") {\n return {\n status: \"ignored\",\n reason:\n \"afterAgentThought is a reasoning notification, not a generation lifecycle event; no canonical \" +\n \"event type represents it and thought text is never exported\",\n };\n }\n\n if (payload.hook_event_name === \"subagentStart\" || payload.hook_event_name === \"subagentStop\") {\n return {\n status: \"ignored\",\n reason:\n \"cursor's subagentStop payload carries no subagent identifier — the reference gives subagent_id to \" +\n \"subagentStart only — so the two callbacks cannot be paired; emitting subagent.start alone would \" +\n \"leave a delegation that never closes, and minting an id for the end would produce an unpairable one\",\n };\n }\n\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n const sessionId = input.identity.sessionId;\n const model = toModelDescriptor(payload);\n const targetHint = cursorTargetHint(payload);\n const targetHintField = targetHint === undefined ? {} : { targetHint };\n\n switch (payload.hook_event_name) {\n case \"sessionStart\":\n factory.build({\n type: \"session.start\",\n // A background agent runs unattended; an interactive session is the\n // only other state Cursor reports here.\n sessionKind:\n payload.is_background_agent === undefined\n ? \"unknown\"\n : payload.is_background_agent\n ? \"non-interactive\"\n : \"interactive\",\n agentName: \"cursor\",\n ...(payload.cursor_version === undefined || payload.cursor_version.length === 0\n ? {}\n : { agentVersion: payload.cursor_version }),\n ...(model === UNKNOWN_MODEL ? {} : { model }),\n ...(payload.composer_mode === undefined\n ? {}\n : { extensions: { \"cursor.composer_mode\": payload.composer_mode } }),\n ...targetHintField,\n });\n break;\n\n case \"sessionEnd\":\n factory.build({\n type: \"session.end\",\n reason:\n payload.reason === undefined ? \"unknown\" : (SESSION_END_REASONS[payload.reason] ?? \"unknown\"),\n ...(payload.duration_ms === undefined ? {} : { durationMillis: payload.duration_ms }),\n ...(payload.final_status === undefined\n ? {}\n : { extensions: { \"cursor.final_status\": payload.final_status } }),\n });\n break;\n\n case \"beforeSubmitPrompt\": {\n factory.build({\n type: \"prompt.submitted\",\n // Cursor reports no prompt provenance. `user` would be a guess: this\n // hook also fires for an automation-driven or resumed turn.\n promptSource: \"unknown\",\n ...targetHintField,\n ...(payload.prompt === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.prompt,\n }),\n }),\n ...(payload.attachments === undefined\n ? {}\n : { extensions: { \"cursor.attachment_count\": payload.attachments.length } }),\n });\n // `generation_id` is present on every captured agent payload, but the\n // reference does not mark it required, so an absent one degrades to a\n // prompt with no generation rather than to a fabricated id.\n if (payload.generation_id !== undefined && payload.generation_id.length > 0) {\n factory.build({\n type: \"generation.start\",\n generationId: payload.generation_id,\n model,\n });\n } else {\n warnings.push(\n \"beforeSubmitPrompt carried no generation_id, so no generation.start was emitted\",\n );\n }\n break;\n }\n\n case \"preToolUse\":\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId:\n payload.tool_use_id ??\n derivedToolCallId(context, sessionId, [\n \"tool\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n // Cursor names its tools but does not classify them, and the names are\n // not a closed set. `unknown` says so; `other` would claim a lookup\n // happened and found nothing.\n toolKind: \"unknown\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"postToolUse\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId:\n payload.tool_use_id ??\n derivedToolCallId(context, sessionId, [\n \"tool\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n // Cursor routes failures to the separate postToolUseFailure callback,\n // so reaching this one *is* the success signal.\n outcome: \"ok\",\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.tool_output === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_output,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"postToolUseFailure\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId:\n payload.tool_use_id ??\n derivedToolCallId(context, sessionId, [\n \"tool\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n outcome:\n payload.failure_type === \"timeout\"\n ? \"timeout\"\n : payload.failure_type === \"permission_denied\"\n ? \"denied\"\n : payload.is_interrupt === true\n ? \"cancelled\"\n : \"error\",\n ...(payload.failure_type === \"permission_denied\"\n ? { permissionDecision: \"denied\" as const }\n : {}),\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.error_message === undefined\n ? {}\n : {\n output: context.privacy.describeContent({\n kind: \"error-message\",\n text: payload.error_message,\n }),\n }),\n });\n break;\n\n case \"beforeShellExecution\":\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"shell\",\n payload.generation_id ?? \"\",\n payload.command,\n ]),\n toolName: \"shell\",\n toolKind: \"execute\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n input: context.privacy.describeContent({\n kind: \"tool-input\",\n text: payload.command,\n label: \"shell\",\n }),\n ...(payload.sandbox === undefined ? {} : { extensions: { \"cursor.sandbox\": payload.sandbox } }),\n });\n break;\n\n case \"afterShellExecution\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"shell\",\n payload.generation_id ?? \"\",\n payload.command,\n ]),\n toolName: \"shell\",\n // No exit code and no status field on this callback, in the reference\n // or in the captures. Reporting `ok` would assert a success Cursor\n // never claimed.\n outcome: \"unknown\",\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.output === undefined\n ? {}\n : {\n output: context.privacy.describeContent({\n kind: \"tool-output\",\n text: payload.output,\n label: \"shell\",\n }),\n }),\n ...(payload.sandbox === undefined ? {} : { extensions: { \"cursor.sandbox\": payload.sandbox } }),\n });\n break;\n\n case \"beforeMCPExecution\":\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"mcp\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n toolKind: \"network\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"afterMCPExecution\":\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId: derivedToolCallId(context, sessionId, [\n \"mcp\",\n payload.generation_id ?? \"\",\n payload.tool_name,\n ]),\n toolName: payload.tool_name,\n // As with the shell pair: `result_json` is opaque and there is no\n // status field to read an outcome from.\n outcome: \"unknown\",\n ...(payload.duration === undefined ? {} : { durationMillis: payload.duration }),\n ...(payload.result_json === undefined\n ? {}\n : {\n output: context.privacy.describeContent({\n kind: \"tool-output\",\n text: payload.result_json,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n\n case \"afterFileEdit\": {\n const toolCallId = derivedToolCallId(context, sessionId, [\n \"file-edit\",\n payload.generation_id ?? \"\",\n payload.file_path,\n ]);\n // Cursor exposes no \"before edit\" callback, so the pair is emitted from\n // this one firing: an edit that reached this hook has completed.\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId,\n toolName: \"edit_file\",\n toolKind: \"write\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n input: context.privacy.describeContent({\n kind: \"tool-input\",\n text: payload.file_path,\n label: \"edit_file\",\n }),\n });\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId,\n toolName: \"edit_file\",\n outcome: \"ok\",\n // `edits[].old_string`/`new_string` are file content and are never\n // exported, in described form or otherwise. Only how many edits landed.\n ...(payload.edits === undefined\n ? {}\n : { extensions: { \"cursor.edit_count\": payload.edits.length } }),\n });\n break;\n }\n\n case \"beforeReadFile\": {\n // The protocol has no \"after read\" callback, so — as with afterFileEdit —\n // the pair is emitted from this one firing. Unlike an edit, a read that\n // reached this hook has not happened yet and may still be refused by\n // another hook, so its outcome is `unknown`, not `ok`. `content` is the\n // file's text and is never read.\n const toolCallId = derivedToolCallId(context, sessionId, [\n \"read-file\",\n payload.generation_id ?? \"\",\n payload.file_path,\n ]);\n factory.build({\n type: \"tool.start\",\n ...targetHintField,\n toolCallId,\n toolName: \"read_file\",\n toolKind: \"read\",\n ...(payload.generation_id === undefined || payload.generation_id.length === 0\n ? {}\n : { generationId: payload.generation_id }),\n input: context.privacy.describeContent({\n kind: \"tool-input\",\n text: payload.file_path,\n label: \"read_file\",\n }),\n });\n factory.build({\n type: \"tool.end\",\n ...targetHintField,\n toolCallId,\n toolName: \"read_file\",\n outcome: \"unknown\",\n });\n break;\n }\n\n case \"preCompact\":\n factory.build({\n type: \"compaction.performed\",\n trigger:\n payload.trigger === undefined ? \"unknown\" : (COMPACT_TRIGGERS[payload.trigger] ?? \"unknown\"),\n // Cursor exposes no post-compaction callback, so `contextTokensAfter`\n // is structurally unavailable and is never estimated.\n ...(payload.context_tokens === undefined\n ? {}\n : { contextTokensBefore: payload.context_tokens }),\n ...(payload.messages_to_compact === undefined\n ? {}\n : { droppedMessageCount: payload.messages_to_compact }),\n extensions: {\n ...(payload.context_window_size === undefined\n ? {}\n : { \"cursor.context_window_size\": payload.context_window_size }),\n ...(payload.message_count === undefined\n ? {}\n : { \"cursor.message_count\": payload.message_count }),\n ...(payload.is_first_compaction === undefined\n ? {}\n : { \"cursor.is_first_compaction\": payload.is_first_compaction }),\n },\n });\n break;\n\n case \"stop\": {\n const usage = normalizeCursorUsage(payload);\n warnings.push(...usage.warnings);\n const generationId = payload.generation_id;\n if (generationId === undefined || generationId.length === 0) {\n return {\n status: \"ignored\",\n reason:\n \"stop carried no generation_id, so the generation it ends cannot be named; \" +\n \"generation.end requires one and this adapter will not mint it\",\n };\n }\n factory.build({\n type: \"generation.end\",\n generationId,\n model,\n outcome:\n payload.status === undefined ? \"unknown\" : (STOP_STATUS_TO_OUTCOME[payload.status] ?? \"unknown\"),\n ...(payload.status === undefined ? {} : { stopReason: payload.status }),\n ...(usage.usage === undefined ? {} : { usage: usage.usage }),\n ...(payload.loop_count === undefined\n ? {}\n : { extensions: { \"cursor.loop_count\": payload.loop_count } }),\n });\n break;\n }\n\n // Every remaining event name returned early above.\n }\n\n const targetHints = factory.targetHints();\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n ...(targetHints.size === 0 ? {} : { targetHints }),\n };\n };\n\n /**\n * Answer the decision callbacks in their own vocabulary.\n *\n * Cursor reads a JSON object from stdout for six events, keyed `permission`\n * for five of them and `continue` for `beforeSubmitPrompt`. Writing nothing\n * would rely on Cursor's default; writing the wrong key would be silently\n * ignored, which is the same thing while looking deliberate. So the answer is\n * always \"proceed\", spelled the way each event spells it. Never `\"ask\"` — a\n * telemetry hook must not open a prompt — and never `\"deny\"`: ADR 0004 forbids\n * this hook from being able to block the host agent, and the response type\n * pins `exitCode` to 0 for the same reason.\n */\n const hookResponse = (input: ProviderHookResponseInput): ProviderHookResponse => {\n const sourceEventName = input.detection?.sourceEventName;\n const decisionKey =\n sourceEventName === undefined ? undefined : CURSOR_DECISION_EVENTS[sourceEventName];\n if (decisionKey === undefined) {\n return SILENT_HOOK_RESPONSE;\n }\n return {\n exitCode: 0,\n contract: \"provider-protocol\",\n stdout: JSON.stringify(\n decisionKey === \"continue\" ? { continue: true } : { permission: \"allow\" },\n ),\n };\n };\n\n return {\n id,\n version,\n capabilities,\n detect,\n identify,\n deliveryIdentity: cursorDeliveryIdentity,\n deliveryGaps: CURSOR_DELIVERY_GAPS,\n parse,\n hookResponse,\n };\n};\n","import { z } from \"zod\";\n\n/**\n * Codex CLI hook stdin payloads.\n *\n * Shape is drawn from the public Codex hooks reference (developers.openai.com\n * /codex/hooks, mirrored at learn.chatgpt.com/docs/hooks) as of 2026-07. Codex\n * has no dependable `SessionEnd`, so it is deliberately not modelled here; see\n * `adapter.ts` for how `Stop` and a state-store TTL substitute for it.\n *\n * Field names Codex does not document precisely (`tool_call_id`,\n * `subagent_id`, `occurred_at`) are this adapter's own choice of a stable\n * correlation key; see the provenance note in `tests/fixtures/codex/PROVENANCE.md`.\n */\n\nconst permissionModeSchema = z.enum([\n \"default\",\n \"acceptEdits\",\n \"plan\",\n \"dontAsk\",\n \"bypassPermissions\",\n]);\nexport type CodexPermissionMode = z.infer<typeof permissionModeSchema>;\n\n/**\n * Mirrors the rollout/exec `total_token_usage` / `last_token_usage` shape.\n *\n * Codex copies the Responses API counters verbatim: `input_tokens` is the whole\n * prompt, and `cached_input_tokens` (cache reads) and `cache_write_input_tokens`\n * (cache writes, Codex 0.163+) are subsets of it. See docs/usage-semantics.md.\n */\nexport const codexUsageSchema = z.object({\n input_tokens: z.number().int().min(0).optional(),\n cached_input_tokens: z.number().int().min(0).optional(),\n cache_write_input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n reasoning_output_tokens: z.number().int().min(0).optional(),\n total_tokens: z.number().int().min(0).optional(),\n});\nexport type CodexUsage = z.infer<typeof codexUsageSchema>;\n\nconst baseFields = {\n session_id: z.string().min(1).max(256),\n cwd: z.string().min(1).max(4096).optional(),\n model: z.string().min(1).max(256).optional(),\n permission_mode: permissionModeSchema.optional(),\n transcript_path: z.string().min(1).max(4096).optional(),\n codex_version: z.string().min(1).max(64).optional(),\n /** Not part of the documented protocol; lets tests and replay stay deterministic. */\n occurred_at: z.number().int().min(0).optional(),\n};\n\nexport const codexSessionStartPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"SessionStart\"),\n source: z.enum([\"startup\", \"resume\", \"clear\", \"compact\"]).optional(),\n});\nexport type CodexSessionStartPayload = z.infer<typeof codexSessionStartPayloadSchema>;\n\nexport const codexUserPromptSubmitPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"UserPromptSubmit\"),\n turn_id: z.string().min(1).max(256).optional(),\n prompt: z.string().max(1_000_000).optional(),\n});\nexport type CodexUserPromptSubmitPayload = z.infer<typeof codexUserPromptSubmitPayloadSchema>;\n\nexport const codexPreToolUsePayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PreToolUse\"),\n turn_id: z.string().min(1).max(256).optional(),\n tool_name: z.string().min(1).max(256),\n tool_call_id: z.string().min(1).max(256).optional(),\n tool_input: z.unknown().optional(),\n});\nexport type CodexPreToolUsePayload = z.infer<typeof codexPreToolUsePayloadSchema>;\n\nexport const codexPermissionRequestPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PermissionRequest\"),\n turn_id: z.string().min(1).max(256).optional(),\n tool_name: z.string().min(1).max(256).optional(),\n tool_call_id: z.string().min(1).max(256).optional(),\n tool_input: z.unknown().optional(),\n});\nexport type CodexPermissionRequestPayload = z.infer<typeof codexPermissionRequestPayloadSchema>;\n\nexport const codexPostToolUsePayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PostToolUse\"),\n turn_id: z.string().min(1).max(256).optional(),\n tool_name: z.string().min(1).max(256),\n tool_call_id: z.string().min(1).max(256).optional(),\n tool_input: z.unknown().optional(),\n tool_response: z.unknown().optional(),\n permission_decision: z.enum([\"allowed\", \"denied\", \"deferred\"]).optional(),\n duration_ms: z.number().min(0).optional(),\n});\nexport type CodexPostToolUsePayload = z.infer<typeof codexPostToolUsePayloadSchema>;\n\nexport const codexPreCompactPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PreCompact\"),\n trigger: z.enum([\"auto\", \"manual\"]).optional(),\n context_tokens_before: z.number().int().min(0).optional(),\n});\nexport type CodexPreCompactPayload = z.infer<typeof codexPreCompactPayloadSchema>;\n\nexport const codexPostCompactPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"PostCompact\"),\n trigger: z.enum([\"auto\", \"manual\"]).optional(),\n context_tokens_after: z.number().int().min(0).optional(),\n dropped_message_count: z.number().int().min(0).optional(),\n usage: codexUsageSchema.optional(),\n});\nexport type CodexPostCompactPayload = z.infer<typeof codexPostCompactPayloadSchema>;\n\nexport const codexSubagentStartPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"SubagentStart\"),\n turn_id: z.string().min(1).max(256).optional(),\n subagent_id: z.string().min(1).max(256),\n subagent_type: z.string().min(1).max(256).optional(),\n});\nexport type CodexSubagentStartPayload = z.infer<typeof codexSubagentStartPayloadSchema>;\n\nexport const codexSubagentStopPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"SubagentStop\"),\n turn_id: z.string().min(1).max(256).optional(),\n subagent_id: z.string().min(1).max(256),\n status: z.enum([\"completed\", \"failed\", \"cancelled\"]).optional(),\n usage: codexUsageSchema.optional(),\n});\nexport type CodexSubagentStopPayload = z.infer<typeof codexSubagentStopPayloadSchema>;\n\nexport const codexStopPayloadSchema = z.object({\n ...baseFields,\n hook_event_name: z.literal(\"Stop\"),\n turn_id: z.string().min(1).max(256).optional(),\n stop_reason: z.string().min(1).max(256).optional(),\n usage: codexUsageSchema.optional(),\n duration_ms: z.number().min(0).optional(),\n});\nexport type CodexStopPayload = z.infer<typeof codexStopPayloadSchema>;\n\nexport const CODEX_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PermissionRequest\",\n \"PostToolUse\",\n \"PreCompact\",\n \"PostCompact\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"Stop\",\n] as const;\nexport type CodexHookEventName = (typeof CODEX_HOOK_EVENT_NAMES)[number];\n\nexport const codexHookPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n codexSessionStartPayloadSchema,\n codexUserPromptSubmitPayloadSchema,\n codexPreToolUsePayloadSchema,\n codexPermissionRequestPayloadSchema,\n codexPostToolUsePayloadSchema,\n codexPreCompactPayloadSchema,\n codexPostCompactPayloadSchema,\n codexSubagentStartPayloadSchema,\n codexSubagentStopPayloadSchema,\n codexStopPayloadSchema,\n]);\nexport type CodexHookPayload = z.infer<typeof codexHookPayloadSchema>;\n\n/** Loose shape check used to award `weak` confidence to a recognizable-but-malformed payload. */\nexport const codexHookEnvelopeSchema = z.object({\n session_id: z.string().min(1),\n hook_event_name: z.enum(CODEX_HOOK_EVENT_NAMES),\n});\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { codexHookPayloadSchema, type CodexHookPayload } from \"./payload.js\";\n\n/**\n * Which Codex callbacks carry an identifier that survives a redelivery.\n *\n * - `tool_call_id` names one tool call. The event name separates the pre-edge,\n * the permission prompt, and the post-edge of that same call.\n * - `subagent_id` is required on `SubagentStart`/`SubagentStop`.\n * - `turn_id` names one turn, and Codex fires `UserPromptSubmit` and `Stop`\n * exactly once per turn — `Stop` is documented as the reliable end-of-turn\n * callback, which is what makes it safe to key on here even though Claude\n * Code's `Stop` is not.\n *\n * Excluded: `SessionStart`, `PreCompact`, and `PostCompact` carry no per-callback\n * field at all, and `tool_name` alone is not one — the same tool called twice in\n * a turn would collapse into a single delivery. `occurred_at` is not used either:\n * it is this adapter's own optional convenience field, not part of the documented\n * protocol, so a real Codex payload would not carry it.\n */\nconst deliveryComponents = (\n payload: CodexHookPayload,\n): { readonly components: readonly string[]; readonly evidence: readonly string[] } | undefined => {\n switch (payload.hook_event_name) {\n case \"PreToolUse\":\n case \"PermissionRequest\":\n case \"PostToolUse\":\n return payload.tool_call_id === undefined\n ? undefined\n : {\n components: [payload.tool_call_id],\n evidence: [\"payload.tool_call_id names one tool call and repeats on redelivery\"],\n };\n case \"SubagentStart\":\n case \"SubagentStop\":\n return {\n components: [payload.subagent_id],\n evidence: [\"payload.subagent_id names one subagent instance\"],\n };\n case \"UserPromptSubmit\":\n case \"Stop\":\n return payload.turn_id === undefined\n ? undefined\n : {\n components: [payload.turn_id],\n evidence: [`payload.turn_id names one turn, which fires ${payload.hook_event_name} once`],\n };\n case \"SessionStart\":\n case \"PreCompact\":\n case \"PostCompact\":\n return undefined;\n }\n};\n\n/**\n * Why each Codex callback that {@link codexDeliveryIdentity} declines carries no\n * delivery identity.\n *\n * Exhaustive over {@link CODEX_HOOK_EVENT_NAMES}. The tool and turn events appear\n * here because their identifying field is optional in the documented protocol:\n * `tool_call_id` and `turn_id` are this adapter's chosen correlation keys, and a\n * payload that omits one reaches the same dead end as an event that never had it.\n * Naming the absent field is the point — that is the one thing a host can fix.\n */\nexport const CODEX_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n SessionStart:\n \"no per-firing id; payload `source` (startup, resume, clear, compact) means SessionStart fires repeatedly under one session_id\",\n PreCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n PostCompact: \"no compaction id; payload `trigger` does not separate two genuine compactions\",\n PreToolUse:\n \"payload.tool_call_id absent; tool_name is not a substitute because one turn can call the same tool twice\",\n PostToolUse:\n \"payload.tool_call_id absent; tool_name is not a substitute because one turn can call the same tool twice\",\n PermissionRequest:\n \"payload.tool_call_id absent; tool_name is not a substitute because one turn can prompt for the same tool twice\",\n UserPromptSubmit: \"payload.turn_id absent; nothing else in this callback names one turn\",\n Stop: \"payload.turn_id absent; nothing else in this callback names one turn\",\n SubagentStart: \"payload.subagent_id absent, so no subagent instance is named\",\n SubagentStop: \"payload.subagent_id absent, so no subagent instance is named\",\n});\n\nexport const codexDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return undefined;\n }\n const payload = parsed.data;\n const identified = deliveryComponents(payload);\n if (identified === undefined) {\n return undefined;\n }\n return {\n sessionId: payload.session_id,\n sourceEventName: payload.hook_event_name,\n components: identified.components,\n evidence: identified.evidence,\n };\n};\n","import type { TargetHint } from \"../../model/target.js\";\nimport { MAX_TARGET_HINT_PATHS, sessionCwdHint } from \"../../model/target.js\";\n\n/**\n * Where a Codex tool call pointed, as a target hint (ADR 0008).\n *\n * ## What the payload actually carries\n *\n * Observed against Codex CLI 0.163.0 driving a mock Responses server (the agent\n * lab, `har-plugins/agent-lab`), with the model's `exec_command` call setting\n * `workdir` to a directory *different* from the session's:\n *\n * - `PreToolUse`/`PostToolUse` for a shell call report `tool_name: \"Bash\"` and\n * `tool_input: { command: \"<string>\" }` — the `workdir` the model asked for is\n * **not** forwarded, and the envelope `cwd` stays the session's directory.\n * - An `apply_patch` invocation through the shell arrives the same way, as a\n * `Bash` call whose command starts with `apply_patch`.\n *\n * So, in order:\n *\n * 1. **`tool-path`** — patch headers (`*** Add File:`, `*** Update File:`,\n * `*** Delete File:`, `*** Move to:`) from an `apply_patch` tool's input, or\n * from a shell command that invokes `apply_patch` (Codex intercepts exactly\n * that form). Header paths are relative to the patch's working directory.\n * 2. **`shell-cwd`** — `tool_input.workdir`, which is the shell tool's own\n * argument name and what older Codex builds forwarded verbatim (the\n * `command: [argv]` shape). Read when present; current builds omit it.\n * 3. **`session-cwd`** — the envelope `cwd`, for everything else.\n */\n\nconst PATCH_HEADER = /^\\*\\*\\* (?:Add File|Update File|Delete File|Move to): (.+)$/;\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst nonEmptyString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/** The shell command as one string: Codex sends a string today, an argv array before. */\nconst commandText = (input: Record<string, unknown> | undefined): string | undefined => {\n const command = input?.command ?? input?.cmd;\n if (typeof command === \"string\") {\n return command;\n }\n if (Array.isArray(command) && command.every((part) => typeof part === \"string\")) {\n return command.join(\" \");\n }\n return undefined;\n};\n\n/** Every distinct file a patch names, or `undefined` when it names none or too many. */\nexport const patchHeaderPaths = (patch: string): readonly string[] | undefined => {\n const paths = new Set<string>();\n for (const line of patch.split(/\\r?\\n/)) {\n const match = PATCH_HEADER.exec(line.trimEnd());\n const named = match?.[1]?.trim();\n if (named !== undefined && named.length > 0) {\n paths.add(named);\n }\n }\n // Too many files to check within bounds is not a reason to check some of\n // them: a target must hold for the whole call.\n return paths.size === 0 || paths.size > MAX_TARGET_HINT_PATHS ? undefined : [...paths];\n};\n\nconst patchTextOf = (toolName: string, input: unknown): string | undefined => {\n if (typeof input === \"string\") {\n return /^apply[_-]?patch$/i.test(toolName) ? input : undefined;\n }\n const record = asRecord(input);\n if (/^apply[_-]?patch$/i.test(toolName)) {\n return (\n nonEmptyString(record?.patch) ?? nonEmptyString(record?.input) ?? commandText(record)\n );\n }\n const command = commandText(record);\n return command !== undefined && /^\\s*apply_patch\\b/.test(command) ? command : undefined;\n};\n\nexport const codexTargetHint = (\n toolName: string,\n toolInput: unknown,\n cwd: string | undefined,\n): TargetHint | undefined => {\n const record = asRecord(toolInput);\n const workdir = nonEmptyString(record?.workdir);\n const base = workdir ?? cwd;\n\n const patch = patchTextOf(toolName, toolInput);\n if (patch !== undefined) {\n const paths = patchHeaderPaths(patch);\n // A patch whose files cannot all be named is not evidence of anything\n // weaker either: the call did touch files, just not ones we can see.\n return paths === undefined\n ? undefined\n : { source: \"tool-path\", paths, ...(base === undefined ? {} : { baseDirectory: base }) };\n }\n if (workdir !== undefined) {\n return {\n source: \"shell-cwd\",\n paths: [workdir],\n ...(cwd === undefined ? {} : { baseDirectory: cwd }),\n };\n }\n return sessionCwdHint(cwd);\n};\n","import type { ToolKind } from \"../../model/events.js\";\n\nconst PATTERNS: readonly (readonly [RegExp, ToolKind])[] = [\n [/^(apply[_-]?patch|patch)$/i, \"write\"],\n [/(write|edit|create[_-]?file|delete)/i, \"write\"],\n [/^(shell|bash|exec|local[_-]?shell|run[_-]?command|terminal)$/i, \"execute\"],\n [/(read|cat|view|get[_-]?file|open[_-]?file)/i, \"read\"],\n [/(web[_-]?search|browser|fetch|http)/i, \"network\"],\n [/(search|grep|find|glob)/i, \"search\"],\n [/(subagent|delegate|task)/i, \"delegate\"],\n];\n\n/**\n * Best-effort classification from a Codex tool name.\n *\n * Codex does not publish a closed enum of tool names (built-ins like\n * `apply_patch` and `shell` are documented; MCP tool names are arbitrary), so\n * this is a heuristic rather than a lookup table. Unmatched names fall back to\n * `other`, never `unknown`, because the tool name itself is always known.\n */\nexport const classifyCodexToolKind = (toolName: string): ToolKind => {\n for (const [pattern, kind] of PATTERNS) {\n if (pattern.test(toolName)) {\n return kind;\n }\n }\n return \"other\";\n};\n","import type { UsageReport, UsageTemporality } from \"../../model/usage.js\";\nimport type { CodexUsage } from \"./payload.js\";\n\n/**\n * Project a Codex usage snapshot onto a canonical usage report.\n *\n * Codex copies the Responses API usage verbatim, so `input_tokens` is the whole\n * prompt: `cached_input_tokens` (cache reads) and, from Codex 0.163,\n * `cache_write_input_tokens` (cache writes) are subsets of it, and\n * `reasoning_output_tokens` is a subset of `output_tokens`. That is the\n * canonical shape already (`cacheCreationAccounting: \"included-in-input\"`), the\n * same one Claude Code's disjoint buckets are folded into: no arithmetic here.\n * A Codex that reports no cache-write counter leaves the field absent, which\n * normalizes to zero with `not-reported`.\n */\nexport const codexUsageToReport = (\n usage: CodexUsage,\n temporality: UsageTemporality,\n): UsageReport => ({\n temporality,\n ...(usage.input_tokens === undefined ? {} : { inputTokens: usage.input_tokens }),\n ...(usage.cached_input_tokens === undefined\n ? {}\n : { cachedInputTokens: usage.cached_input_tokens }),\n ...(usage.cache_write_input_tokens === undefined\n ? {}\n : {\n cacheCreationInputTokens: usage.cache_write_input_tokens,\n cacheCreationAccounting: \"included-in-input\" as const,\n }),\n ...(usage.output_tokens === undefined ? {} : { outputTokens: usage.output_tokens }),\n ...(usage.reasoning_output_tokens === undefined\n ? {}\n : { reasoningOutputTokens: usage.reasoning_output_tokens }),\n ...(usage.total_tokens === undefined ? {} : { providerTotalTokens: usage.total_tokens }),\n});\n\nexport type CodexTokenCountObservation = {\n readonly totalTokenUsage?: CodexUsage;\n readonly lastTokenUsage?: CodexUsage;\n};\n\n/**\n * Prefer the cumulative session snapshot over a per-turn delta.\n *\n * Codex's rollout JSONL reports both a cumulative `total_token_usage` and a\n * per-turn `last_token_usage` on the same `token_count` event. The cumulative\n * figure is the authoritative running total (never sum repeats of it across\n * events); `last_token_usage` is only used, and only marked `delta`\n * explicitly, when no cumulative figure is present.\n */\nexport const codexTokenCountToReport = (\n observation: CodexTokenCountObservation,\n): UsageReport | undefined => {\n if (observation.totalTokenUsage !== undefined) {\n return codexUsageToReport(observation.totalTokenUsage, \"cumulative\");\n }\n if (observation.lastTokenUsage !== undefined) {\n return codexUsageToReport(observation.lastTokenUsage, \"delta\");\n }\n return undefined;\n};\n","import { providerIdSchema, type ProviderId } from \"../../model/primitives.js\";\n\n/** Stable identifier for this adapter across releases. */\nexport const CODEX_PROVIDER_ID: ProviderId = providerIdSchema.parse(\"codex\");\n\n/** Adapter package version, independent of the Codex CLI's own version. */\nexport const CODEX_ADAPTER_VERSION = \"0.1.0\";\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { EventOutcome } from \"../../model/events.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport {\n invocationIdSchema,\n sessionIdSchema,\n type InvocationId,\n type SessionId,\n} from \"../../model/primitives.js\";\nimport { normalizeUsage, type CanonicalUsage } from \"../../model/usage.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport {\n codexHookEnvelopeSchema,\n codexHookPayloadSchema,\n type CodexHookPayload,\n type CodexUsage,\n} from \"./payload.js\";\nimport { CODEX_DELIVERY_GAPS, codexDeliveryIdentity } from \"./delivery.js\";\nimport { sessionCwdHint } from \"../../model/target.js\";\nimport { codexTargetHint } from \"./target.js\";\nimport { classifyCodexToolKind } from \"./tool-kind.js\";\nimport { codexUsageToReport } from \"./usage.js\";\nimport { CODEX_ADAPTER_VERSION, CODEX_PROVIDER_ID } from \"./version.js\";\n\n/**\n * Codex has no dependable `SessionEnd` (see AGENT.md task scope), so\n * `session.end` is deliberately absent from {@link CODEX_CAPABILITIES}.\n * `Stop` — fired reliably at the end of every turn — is mapped to\n * `generation.end` instead, giving a host's state store a steady stream of\n * per-session activity it can use for TTL-based session finalization.\n */\nexport const CODEX_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\n \"session.start\",\n \"prompt.submitted\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"subagent.start\",\n \"subagent.end\",\n \"compaction.performed\",\n ] as const),\n usageTemporality: \"cumulative\",\n // Every usage-bearing Codex callback stamps the *session-wide* running total\n // (`total_token_usage`), not a per-turn figure, so all of them are points on\n // one series. Diffing per `turn_id` would re-count the whole session each\n // turn; see docs/usage-semantics.md.\n cumulativeUsageSeries: \"session-lifetime\",\n reportsCachedInput: true,\n // Codex 0.163+ reports `cache_write_input_tokens`, a subset of `input_tokens`.\n reportsCacheCreation: true,\n cacheCreationAccounting: \"included-in-input\",\n reportsReasoningOutput: true,\n reportsProviderTotal: true,\n reportsCost: false,\n emitsSubagentEvents: true,\n emitsCompactionEvents: true,\n requiresHookResponse: false,\n // Tool, subagent, and per-turn callbacks carry a replay-stable id; session and\n // compaction callbacks do not. See `./delivery.ts` for which and why.\n deliveryIdentifier: \"partial\",\n});\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n value !== null && typeof value === \"object\" && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\n/** A Codex-specific marker strong enough to resolve a `strong` match to `exact`. */\nconst hasExactMarker = (payload: CodexHookPayload): boolean => {\n if (payload.codex_version !== undefined) {\n return true;\n }\n if (payload.permission_mode === \"dontAsk\") {\n return true;\n }\n return \"tool_name\" in payload && payload.tool_name === \"apply_patch\";\n};\n\nconst detect = (input: ProviderDetectionInput): ProviderDetection => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (parsed.success) {\n const payload = parsed.data;\n const exact = hasExactMarker(payload);\n return providerDetectionSchema.parse({\n providerId: CODEX_PROVIDER_ID,\n confidence: exact ? \"exact\" : \"strong\",\n reasons: [\n \"payload.hook_event_name matches the Codex hook protocol\",\n ...(exact ? [\"payload carries a Codex-specific marker\"] : []),\n ],\n ...(payload.codex_version === undefined ? {} : { providerVersion: payload.codex_version }),\n sourceEventName: payload.hook_event_name,\n });\n }\n\n const envelope = codexHookEnvelopeSchema.safeParse(input.payload);\n if (envelope.success) {\n return providerDetectionSchema.parse({\n providerId: CODEX_PROVIDER_ID,\n confidence: \"weak\",\n reasons: [\n \"payload.hook_event_name is a known Codex event but failed schema validation for it\",\n ],\n sourceEventName: envelope.data.hook_event_name,\n });\n }\n\n return unknownDetection([\"payload does not match the Codex hook protocol\"]);\n};\n\n/** Per-event field that distinguishes concurrent hook calls in one session. */\nconst eventDiscriminator = (payload: CodexHookPayload): string | undefined => {\n switch (payload.hook_event_name) {\n case \"PreToolUse\":\n case \"PermissionRequest\":\n case \"PostToolUse\":\n return payload.tool_call_id ?? payload.tool_name;\n case \"SubagentStart\":\n case \"SubagentStop\":\n return payload.subagent_id;\n case \"UserPromptSubmit\":\n case \"Stop\":\n return payload.turn_id;\n case \"SessionStart\":\n case \"PreCompact\":\n case \"PostCompact\":\n return undefined;\n }\n};\n\nconst identify = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n): readonly IdentityClaim[] => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return [];\n }\n const payload = parsed.data;\n const occurredAt = payload.occurred_at ?? context.clock.now();\n const sessionId = sessionIdSchema.parse(payload.session_id);\n const discriminator = eventDiscriminator(payload);\n const invocationId = context.ids.newInvocationId({\n providerId: CODEX_PROVIDER_ID,\n sessionId,\n sourceEventName: payload.hook_event_name,\n occurredAt,\n ...(discriminator === undefined ? {} : { discriminator }),\n });\n const workspace =\n payload.cwd === undefined\n ? undefined\n : deriveWorkspaceIdentity(context.privacy, { kind: \"working-directory\", absolutePath: payload.cwd });\n\n const claim = identityClaimSchema.parse({\n source: `adapter:${CODEX_PROVIDER_ID}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt: occurredAt,\n ...(workspace === undefined ? {} : { workspace }),\n },\n });\n return [claim];\n};\n\n/**\n * Time-independent correlation key for a subagent, so `SubagentStart` and\n * `SubagentStop` — two separate hook process invocations — agree on the same\n * `subagentInvocationId` even though they occur at different times.\n */\nconst deriveSubagentInvocationId = (\n context: ProviderContext,\n sessionId: SessionId,\n subagentId: string,\n): InvocationId =>\n invocationIdSchema.parse(\n `subinv_${context.ids.newOpaqueId([\"codex\", \"subagent\", sessionId, subagentId])}`,\n );\n\nconst outcomeFromToolResponse = (toolResponse: unknown): EventOutcome => {\n if (toolResponse === undefined) {\n return \"unknown\";\n }\n const record = asRecord(toolResponse);\n if (record === undefined) {\n return \"ok\";\n }\n if (typeof record.success === \"boolean\") {\n return record.success ? \"ok\" : \"error\";\n }\n if (typeof record.exit_code === \"number\" && record.exit_code !== 0) {\n return \"error\";\n }\n if (record.error !== undefined && record.error !== null && record.error !== false) {\n return \"error\";\n }\n return \"ok\";\n};\n\nconst mapTrigger = (trigger: \"auto\" | \"manual\" | undefined): \"automatic\" | \"manual\" | \"unknown\" => {\n if (trigger === \"auto\") {\n return \"automatic\";\n }\n if (trigger === \"manual\") {\n return \"manual\";\n }\n return \"unknown\";\n};\n\nconst mapSubagentOutcome = (\n status: \"completed\" | \"failed\" | \"cancelled\" | undefined,\n): EventOutcome => {\n switch (status) {\n case \"completed\":\n return \"ok\";\n case \"failed\":\n return \"error\";\n case \"cancelled\":\n return \"cancelled\";\n default:\n return \"unknown\";\n }\n};\n\nconst mapStopOutcome = (stopReason: string | undefined): EventOutcome => {\n if (stopReason === undefined) {\n return \"ok\";\n }\n const normalized = stopReason.toLowerCase();\n if (normalized.includes(\"cancel\")) {\n return \"cancelled\";\n }\n if (normalized.includes(\"timeout\")) {\n return \"timeout\";\n }\n if (normalized.includes(\"error\") || normalized.includes(\"fail\")) {\n return \"error\";\n }\n return \"ok\";\n};\n\nconst parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const parsed = codexHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the Codex hook protocol\",\n }),\n };\n }\n const payload = parsed.data;\n const occurredAt = payload.occurred_at ?? context.clock.now();\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n const targetHintFor = (toolName: string, toolInput: unknown) => {\n const hint = codexTargetHint(toolName, toolInput, payload.cwd);\n return hint === undefined ? {} : { targetHint: hint };\n };\n // The session's own directory: where it runs before any tool names a path.\n const sessionHint = sessionCwdHint(payload.cwd);\n const sessionTarget = sessionHint === undefined ? {} : { targetHint: sessionHint };\n\n const buildUsage = (usage: CodexUsage | undefined): CanonicalUsage | undefined => {\n if (usage === undefined) {\n return undefined;\n }\n // Codex's hook-carried usage mirrors the rollout's cumulative\n // `total_token_usage`; see docs/usage-semantics.md.\n const normalized = normalizeUsage(codexUsageToReport(usage, \"cumulative\"));\n if (normalized.status === \"invalid\") {\n warnings.push(...normalized.issues.map((issue) => issue.message));\n return undefined;\n }\n return normalized.usage;\n };\n\n switch (payload.hook_event_name) {\n case \"SessionStart\":\n factory.build({\n type: \"session.start\",\n sessionKind: \"unknown\",\n agentName: \"codex\",\n occurredAt,\n ...(payload.codex_version === undefined ? {} : { agentVersion: payload.codex_version }),\n ...(payload.model === undefined ? {} : { model: { modelId: payload.model, vendor: \"openai\" } }),\n ...sessionTarget,\n });\n break;\n\n case \"UserPromptSubmit\":\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n occurredAt,\n ...sessionTarget,\n ...(payload.prompt === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.prompt,\n }),\n }),\n });\n break;\n\n case \"PreToolUse\": {\n const toolCallId =\n payload.tool_call_id ??\n context.ids.newOpaqueId([input.identity.sessionId, payload.turn_id ?? \"\", payload.tool_name]);\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName: payload.tool_name,\n toolKind: classifyCodexToolKind(payload.tool_name),\n occurredAt,\n ...targetHintFor(payload.tool_name, payload.tool_input),\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"PermissionRequest\":\n // No canonical event type represents an in-flight approval decision;\n // it surfaces as `permissionDecision` on the paired `tool.end`. This\n // hook is only ever a silent observer here (see `hookResponse`), never\n // a party to the actual allow/deny decision.\n return {\n status: \"ignored\",\n reason: \"permission requests carry no telemetry of their own; the decision surfaces on tool.end\",\n };\n\n case \"PostToolUse\": {\n const toolCallId =\n payload.tool_call_id ??\n context.ids.newOpaqueId([input.identity.sessionId, payload.turn_id ?? \"\", payload.tool_name]);\n const permissionDecision = payload.permission_decision ?? \"not-required\";\n const outcome =\n permissionDecision === \"denied\" ? \"denied\" : outcomeFromToolResponse(payload.tool_response);\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName: payload.tool_name,\n outcome,\n permissionDecision,\n occurredAt,\n ...targetHintFor(payload.tool_name, payload.tool_input),\n ...(payload.duration_ms === undefined ? {} : { durationMillis: payload.duration_ms }),\n ...(payload.tool_response === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_response,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"PreCompact\":\n factory.build({\n type: \"compaction.performed\",\n trigger: mapTrigger(payload.trigger),\n occurredAt,\n ...(payload.context_tokens_before === undefined\n ? {}\n : { contextTokensBefore: payload.context_tokens_before }),\n });\n break;\n\n case \"PostCompact\": {\n const usage = buildUsage(payload.usage);\n factory.build({\n type: \"compaction.performed\",\n trigger: mapTrigger(payload.trigger),\n occurredAt,\n ...(payload.context_tokens_after === undefined\n ? {}\n : { contextTokensAfter: payload.context_tokens_after }),\n ...(payload.dropped_message_count === undefined\n ? {}\n : { droppedMessageCount: payload.dropped_message_count }),\n ...(usage === undefined ? {} : { usage }),\n });\n break;\n }\n\n case \"SubagentStart\": {\n const subagentInvocationId = deriveSubagentInvocationId(\n context,\n input.identity.sessionId,\n payload.subagent_id,\n );\n factory.build({\n type: \"subagent.start\",\n subagentInvocationId,\n delegationDepth: 1,\n occurredAt,\n ...(payload.subagent_type === undefined ? {} : { subagentType: payload.subagent_type }),\n ...(payload.model === undefined ? {} : { model: { modelId: payload.model, vendor: \"openai\" } }),\n });\n break;\n }\n\n case \"SubagentStop\": {\n const subagentInvocationId = deriveSubagentInvocationId(\n context,\n input.identity.sessionId,\n payload.subagent_id,\n );\n const usage = buildUsage(payload.usage);\n factory.build({\n type: \"subagent.end\",\n subagentInvocationId,\n outcome: mapSubagentOutcome(payload.status),\n occurredAt,\n ...(usage === undefined ? {} : { usage }),\n });\n break;\n }\n\n case \"Stop\": {\n const generationId =\n payload.turn_id ?? context.ids.newOpaqueId([input.identity.sessionId, \"stop\", String(occurredAt)]);\n const usage = buildUsage(payload.usage);\n factory.build({\n type: \"generation.end\",\n generationId,\n model: {\n modelId: payload.model ?? \"unknown\",\n ...(payload.model === undefined ? {} : { vendor: \"openai\" }),\n },\n outcome: mapStopOutcome(payload.stop_reason),\n occurredAt,\n ...(payload.stop_reason === undefined ? {} : { stopReason: payload.stop_reason }),\n ...(payload.duration_ms === undefined ? {} : { durationMillis: payload.duration_ms }),\n ...(usage === undefined ? {} : { usage }),\n });\n break;\n }\n }\n\n const targetHints = factory.targetHints();\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n ...(targetHints.size === 0 ? {} : { targetHints }),\n };\n};\n\n/**\n * A telemetry sidecar must never become a policy hook. Regardless of event\n * type or attribution outcome, this adapter answers every hook call silently\n * (ADR 0004): it never emits a `permissionDecision`, `continue: false`, or any\n * other field that could influence Codex's own control flow.\n */\nconst hookResponse = (): ProviderHookResponse => SILENT_HOOK_RESPONSE;\n\nexport const createCodexAdapter = (): ProviderAdapter => ({\n id: CODEX_PROVIDER_ID,\n version: CODEX_ADAPTER_VERSION,\n capabilities: CODEX_CAPABILITIES,\n detect,\n identify,\n deliveryIdentity: codexDeliveryIdentity,\n deliveryGaps: CODEX_DELIVERY_GAPS,\n parse,\n hookResponse,\n});\n","import { createHash } from \"node:crypto\";\nimport { open, readdir, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport type { PayloadEnricher, PayloadEnrichment, ReadCursor } from \"../../runtime/ports.js\";\nimport { CODEX_PROVIDER_ID } from \"./version.js\";\nimport { codexUsageSchema, type CodexUsage } from \"./payload.js\";\n\n/**\n * The hook-runtime side of `providers.codex.readRolloutUsage`: attach the\n * session's token usage, read from Codex's own rollout file, to a Codex `Stop`.\n *\n * Why: Codex (observed on 0.163) puts no `usage` on any hook payload. The\n * counters exist only in the rollout JSONL Codex writes for every thread\n * (`$CODEX_HOME/sessions/YYYY/MM/DD/rollout-<time>-<session-id>.jsonl`), on\n * `event_msg` records of `payload.type === \"token_count\"`:\n *\n * ```text\n * { \"type\": \"event_msg\", \"payload\": { \"type\": \"token_count\", \"info\": {\n * \"total_token_usage\": { input_tokens, cached_input_tokens,\n * cache_write_input_tokens, output_tokens, reasoning_output_tokens, total_tokens },\n * \"last_token_usage\": { ...same keys, the last request only } } } }\n * ```\n *\n * and, from 0.163, on `token_usage_record` records (`payload.thread_token_usage`,\n * the same running total). `total_token_usage` is the thread's running total:\n * exactly what the Codex adapter already takes `Stop.usage` to be (cumulative,\n * one series per session, diffed against the previous snapshot downstream). So\n * the enricher attaches the **last** snapshot, never a sum, which makes every\n * read exact on its own: a late read counts late, a missed read is caught up by\n * the next `Stop`, and nothing can be counted twice. That is also why no\n * `usage_partial` exists here.\n *\n * Not part of the Codex adapter, which gets no filesystem handle (ADR 0003). The\n * runtime keeps a byte cursor per session (`read-cursor` state value):\n *\n * - `SessionStart` records where the rollout ends now (0 when it does not exist\n * yet), unless a cursor for the same file is stored already.\n * - `Stop` reads from the cursor to the end (bounded in bytes and time) and\n * attaches the last snapshot found there; the cursor moves to the end. With no\n * new snapshot since the cursor (no model request this turn, or Codex has not\n * flushed it yet) it waits once, briefly, then attaches nothing: the next\n * `Stop` carries the running total that includes it.\n * - No usable cursor, a range over the cap, or a file that shrank: the last\n * snapshot in the bounded tail is attached instead (still exact, see above).\n * - A timeout or an unreadable file attaches nothing and keeps the cursor.\n *\n * The rollout is the one named by the payload's `transcript_path`. Only when a\n * payload names none, and the host gave a sessions root, is it looked up by\n * session id — in at most {@link ROLLOUT_LOOKUP_DAYS} date directories, by an\n * exact file-name match, never recursively.\n *\n * Nothing but numeric counters and a model id leaves this module.\n */\n\nexport const CODEX_ROLLOUT_USAGE_ENRICHER_ID = \"codex-rollout-usage\";\n\nexport const DEFAULT_CODEX_ROLLOUT_RANGE_BYTES = 8_388_608;\nexport const DEFAULT_CODEX_ROLLOUT_TAIL_BYTES = 1_048_576;\nexport const DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS = 500;\n/** How long a `Stop` waits once for a snapshot Codex has not flushed yet. */\nexport const DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS = 150;\n/** Date directories (today and earlier, local time) searched by session id. */\nexport const ROLLOUT_LOOKUP_DAYS = 7;\n\nconst MIN_BYTES = 65_536;\nconst MAX_RANGE_BYTES = 67_108_864;\nconst MAX_TAIL_BYTES = 16_777_216;\nconst MIN_TIMEOUT_MILLIS = 10;\nconst MAX_TIMEOUT_MILLIS = 5_000;\nconst MAX_SETTLE_MILLIS = 1_000;\nconst MAX_MODEL_ID_LENGTH = 256;\n/** A date directory with more entries than this is not searched. */\nconst MAX_LOOKUP_DIR_ENTRIES = 20_000;\nconst SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{7,127}$/;\n\nexport type CodexRolloutUsageEnricherOptions = {\n /** Most bytes one `Stop` reads from its cursor. Default 8 MiB, clamped to 64 KiB..64 MiB. */\n readonly maxRangeBytes?: number;\n /** Bytes read from the end when no cursor applies. Default 1 MiB, clamped to 64 KiB..16 MiB. */\n readonly maxTailBytes?: number;\n /** Budget for one enrichment, lookup and settle wait included. Default 500 ms, clamped to 10 ms..5 s. */\n readonly timeoutMillis?: number;\n /** Wait before the one re-read when no snapshot is found yet. Default 150 ms, 0 disables. */\n readonly settleMillis?: number;\n /**\n * `$CODEX_HOME/sessions`, for payloads that name no `transcript_path`. Absent,\n * such payloads are left alone. Supplied by the host, never read from the\n * environment here.\n */\n readonly sessionsRoot?: string;\n /** Clock for the date directories of the session-id lookup. */\n readonly now?: () => Date;\n};\n\nconst clamp = (value: number | undefined, fallback: number, min: number, max: number): number => {\n if (value === undefined || !Number.isFinite(value)) {\n return fallback;\n }\n return Math.min(max, Math.max(min, Math.floor(value)));\n};\n\nconst asRecord = (value: unknown): Record<string, unknown> | undefined =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : undefined;\n\nconst isRolloutPath = (value: unknown): value is string =>\n typeof value === \"string\" &&\n value.length > 0 &&\n value.length <= 4096 &&\n !value.includes(\"\\0\") &&\n path.isAbsolute(value) &&\n path.extname(value) === \".jsonl\";\n\nconst sourceDigest = (rolloutPath: string): string =>\n createHash(\"sha256\").update(rolloutPath, \"utf8\").digest(\"hex\").slice(0, 32);\n\n/** One running-total snapshot, with the model in force when it was written. */\nexport type CodexRolloutSnapshot = {\n readonly usage: CodexUsage;\n readonly model?: string;\n};\n\nconst parseUsage = (value: unknown): CodexUsage | undefined => {\n const parsed = codexUsageSchema.safeParse(value);\n if (!parsed.success) {\n return undefined;\n }\n const usage = parsed.data;\n // A snapshot must at least say how many tokens went in and out.\n return usage.input_tokens === undefined || usage.output_tokens === undefined ? undefined : usage;\n};\n\nconst modelOf = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_MODEL_ID_LENGTH ? value : undefined;\n\ntype LineFacts = { readonly usage?: CodexUsage; readonly model?: string };\n\n/**\n * The running total or the model one rollout line carries, if any.\n *\n * Pre-filtered on substrings: most lines are messages, tool calls and their\n * output, and parsing them would spend the budget on records never used.\n */\nconst factsOf = (line: string): LineFacts | undefined => {\n const usageLine = line.includes('\"token_count\"') || line.includes('\"token_usage_record\"');\n const contextLine = line.includes('\"turn_context\"');\n if (!usageLine && !contextLine) {\n return undefined;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(line);\n } catch {\n return undefined;\n }\n const record = asRecord(parsed);\n const payload = asRecord(record?.payload);\n if (record === undefined || payload === undefined) {\n return undefined;\n }\n if (record.type === \"turn_context\") {\n const model = modelOf(payload.model);\n return model === undefined ? undefined : { model };\n }\n if (record.type === \"event_msg\" && payload.type === \"token_count\") {\n // 0.163 nests the counters under `info`; earlier releases put them on the payload.\n const info = asRecord(payload.info) ?? payload;\n const usage = parseUsage(info.total_token_usage);\n return usage === undefined ? undefined : { usage };\n }\n if (record.type === \"token_usage_record\") {\n const usage = parseUsage(payload.thread_token_usage);\n return usage === undefined ? undefined : { usage };\n }\n return undefined;\n};\n\n/** The last snapshot (and the last model named before or after it) in `lines`. */\nconst lastSnapshotIn = (lines: readonly string[]): CodexRolloutSnapshot | undefined => {\n let usage: CodexUsage | undefined;\n let model: string | undefined;\n for (const line of lines) {\n const facts = factsOf(line.trim());\n if (facts === undefined) {\n continue;\n }\n if (facts.model !== undefined) {\n model = facts.model;\n }\n if (facts.usage !== undefined) {\n usage = facts.usage;\n }\n }\n return usage === undefined ? undefined : { usage, ...(model === undefined ? {} : { model }) };\n};\n\ntype FileHandle = Awaited<ReturnType<typeof open>>;\n\nconst readBytes = async (handle: FileHandle, start: number, length: number): Promise<Buffer> => {\n const buffer = Buffer.alloc(length);\n let filled = 0;\n while (filled < length) {\n const { bytesRead } = await handle.read(buffer, filled, length - filled, start + filled);\n if (bytesRead === 0) {\n break;\n }\n filled += bytesRead;\n }\n return buffer.subarray(0, filled);\n};\n\ntype ReadOutcome =\n | { readonly status: \"found\"; readonly snapshot?: CodexRolloutSnapshot; readonly endOffset: number }\n | { readonly status: \"unavailable\"; readonly reason: \"not-a-file\" | \"unreadable\" | \"truncated\" | \"over-cap\" };\n\n/**\n * Read `[fromOffset, end)` (or the last `tailBytes` when `fromOffset` is\n * undefined) and return the last snapshot in its complete lines.\n */\nconst readRollout = async (\n rolloutPath: string,\n fromOffset: number | undefined,\n maxRangeBytes: number,\n tailBytes: number,\n): Promise<ReadOutcome> => {\n let handle: FileHandle;\n try {\n const info = await stat(rolloutPath);\n if (!info.isFile()) {\n return { status: \"unavailable\", reason: \"not-a-file\" };\n }\n handle = await open(rolloutPath, \"r\");\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n }\n try {\n const { size } = await handle.stat();\n let start: number;\n if (fromOffset === undefined) {\n start = Math.max(0, size - tailBytes);\n } else if (size < fromOffset) {\n return { status: \"unavailable\", reason: \"truncated\" };\n } else if (size - fromOffset > maxRangeBytes) {\n return { status: \"unavailable\", reason: \"over-cap\" };\n } else {\n start = fromOffset;\n }\n const bytes = await readBytes(handle, start, size - start);\n const lastNewline = bytes.lastIndexOf(0x0a);\n const endOffset = lastNewline < 0 ? start : start + lastNewline + 1;\n const lines = bytes.subarray(0, endOffset - start).toString(\"utf8\").split(\"\\n\");\n // A tail that starts mid-file starts mid-line; that fragment is not a record.\n if (fromOffset === undefined && start > 0) {\n lines.shift();\n }\n const snapshot = lastSnapshotIn(lines);\n return { status: \"found\", ...(snapshot === undefined ? {} : { snapshot }), endOffset };\n } catch {\n return { status: \"unavailable\", reason: \"unreadable\" };\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\nconst pad = (value: number): string => String(value).padStart(2, \"0\");\n\n/**\n * Find `rollout-*-<sessionId>.jsonl` in the last {@link ROLLOUT_LOOKUP_DAYS}\n * local date directories below `sessionsRoot`. Never recursive.\n */\nconst findRolloutBySessionId = async (\n sessionsRoot: string,\n sessionId: string,\n now: Date,\n): Promise<string | undefined> => {\n if (!SESSION_ID_PATTERN.test(sessionId) || !path.isAbsolute(sessionsRoot)) {\n return undefined;\n }\n const suffix = `-${sessionId}.jsonl`;\n for (let back = 0; back < ROLLOUT_LOOKUP_DAYS; back += 1) {\n const day = new Date(now.getFullYear(), now.getMonth(), now.getDate() - back);\n const dir = path.join(sessionsRoot, String(day.getFullYear()), pad(day.getMonth() + 1), pad(day.getDate()));\n let names: string[];\n try {\n names = await readdir(dir);\n } catch {\n continue;\n }\n if (names.length > MAX_LOOKUP_DIR_ENTRIES) {\n continue;\n }\n const match = names.find((name) => name.startsWith(\"rollout-\") && name.endsWith(suffix));\n if (match !== undefined) {\n return path.join(dir, match);\n }\n }\n return undefined;\n};\n\nconst TIMED_OUT = Symbol(\"timed-out\");\n\nconst withTimeout = async <T>(work: Promise<T>, timeoutMillis: number): Promise<T | typeof TIMED_OUT> => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<typeof TIMED_OUT>((resolve) => {\n timer = setTimeout(() => {\n resolve(TIMED_OUT);\n }, timeoutMillis);\n timer.unref();\n });\n try {\n return await Promise.race([work, timeout]);\n } finally {\n clearTimeout(timer);\n }\n};\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, millis).unref();\n });\n\nconst hasUsage = (record: Record<string, unknown>): boolean => record.usage !== undefined;\n\nexport const createCodexRolloutUsageEnricher = (options: CodexRolloutUsageEnricherOptions = {}): PayloadEnricher => {\n const maxRangeBytes = clamp(options.maxRangeBytes, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, MIN_BYTES, MAX_RANGE_BYTES);\n const maxTailBytes = clamp(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES);\n const timeoutMillis = clamp(\n options.timeoutMillis,\n DEFAULT_CODEX_ROLLOUT_TIMEOUT_MILLIS,\n MIN_TIMEOUT_MILLIS,\n MAX_TIMEOUT_MILLIS,\n );\n const settleMillis = clamp(options.settleMillis, DEFAULT_CODEX_ROLLOUT_SETTLE_MILLIS, 0, MAX_SETTLE_MILLIS);\n const now = options.now ?? ((): Date => new Date());\n\n const fileSize = async (rolloutPath: string): Promise<number | \"absent\" | undefined> => {\n try {\n const info = await stat(rolloutPath);\n return info.isFile() ? info.size : undefined;\n } catch (thrown) {\n return (thrown as { code?: unknown } | undefined)?.code === \"ENOENT\" ? \"absent\" : undefined;\n }\n };\n\n const resolveRollout = async (record: Record<string, unknown>): Promise<string | undefined> => {\n const named = record.transcript_path;\n if (named !== undefined && named !== null) {\n return isRolloutPath(named) ? named : undefined;\n }\n const sessionId = record.session_id;\n if (options.sessionsRoot === undefined || typeof sessionId !== \"string\") {\n return undefined;\n }\n return findRolloutBySessionId(options.sessionsRoot, sessionId, now());\n };\n\n const enrichWithin = async (input: {\n readonly payload: unknown;\n readonly cursor?: ReadCursor;\n }): Promise<PayloadEnrichment> => {\n const unchanged: PayloadEnrichment = { payload: input.payload };\n const record = asRecord(input.payload);\n const eventName = record?.hook_event_name;\n if (record === undefined || (eventName !== \"SessionStart\" && eventName !== \"Stop\")) {\n return unchanged;\n }\n const rolloutPath = await resolveRollout(record);\n if (rolloutPath === undefined) {\n return { ...unchanged, notes: [\"no rollout named or found for this session\"] };\n }\n const source = sourceDigest(rolloutPath);\n const cursor = input.cursor?.source === source ? input.cursor : undefined;\n\n if (eventName === \"SessionStart\") {\n if (cursor !== undefined) {\n return unchanged;\n }\n const size = await fileSize(rolloutPath);\n if (size === undefined) {\n return { ...unchanged, notes: [\"rollout is not a readable regular file; no cursor recorded\"] };\n }\n return { payload: input.payload, cursor: { source, offset: size === \"absent\" ? 0 : size } };\n }\n\n if (hasUsage(record)) {\n // Codex (or a wrapper) attached usage itself: keep it, move past it.\n const size = await fileSize(rolloutPath);\n return typeof size === \"number\" ? { payload: input.payload, cursor: { source, offset: size } } : unchanged;\n }\n\n const attach = (snapshot: CodexRolloutSnapshot): Record<string, unknown> => ({\n ...record,\n ...(record.model === undefined && snapshot.model !== undefined ? { model: snapshot.model } : {}),\n usage: snapshot.usage,\n });\n\n let read = await readRollout(rolloutPath, cursor?.offset, maxRangeBytes, maxTailBytes);\n if (read.status === \"found\" && read.snapshot === undefined && cursor !== undefined && settleMillis > 0) {\n // Codex writes the rollout from its own task; the turn's last `token_count`\n // can land a moment after `Stop` fires. One short wait, then give up: the\n // next `Stop`'s running total includes whatever this one missed.\n await sleep(settleMillis);\n read = await readRollout(rolloutPath, cursor.offset, maxRangeBytes, maxTailBytes);\n }\n if (read.status === \"unavailable\") {\n if (read.reason !== \"truncated\" && read.reason !== \"over-cap\") {\n return { ...unchanged, notes: [`rollout not read (${read.reason}); cursor kept`] };\n }\n read = await readRollout(rolloutPath, undefined, maxRangeBytes, maxTailBytes);\n if (read.status === \"unavailable\") {\n return { ...unchanged, notes: [`rollout tail not read (${read.reason})`] };\n }\n }\n const next = { source, offset: read.endOffset };\n if (read.snapshot === undefined) {\n return { payload: input.payload, cursor: next, notes: [\"no token_count since the last stop\"] };\n }\n return {\n payload: attach(read.snapshot),\n cursor: next,\n notes: [cursor === undefined ? \"no cursor; attached the last running total in the tail\" : \"attached the running total\"],\n };\n };\n\n const enrich = async (input: { readonly payload: unknown; readonly cursor?: ReadCursor }): Promise<PayloadEnrichment> => {\n try {\n const result = await withTimeout(enrichWithin(input), timeoutMillis);\n return result === TIMED_OUT ? { payload: input.payload, notes: [\"rollout read timed out; cursor kept\"] } : result;\n } catch {\n return { payload: input.payload, notes: [\"rollout read failed; cursor kept\"] };\n }\n };\n\n return Object.freeze({ id: CODEX_ROLLOUT_USAGE_ENRICHER_ID, providerId: CODEX_PROVIDER_ID, enrich });\n};\n\n/**\n * The last running-total snapshot in a Codex rollout, for a wrapping harness\n * that wants to attach `usage` itself. Bounded to the last `maxTailBytes`.\n * Never throws.\n */\nexport const readCodexRolloutUsage = async (\n rolloutPath: string,\n options: { readonly maxTailBytes?: number } = {},\n): Promise<CodexRolloutSnapshot | undefined> => {\n if (!isRolloutPath(rolloutPath)) {\n return undefined;\n }\n const tail = clamp(options.maxTailBytes, DEFAULT_CODEX_ROLLOUT_TAIL_BYTES, MIN_BYTES, MAX_TAIL_BYTES);\n const read = await readRollout(rolloutPath, undefined, DEFAULT_CODEX_ROLLOUT_RANGE_BYTES, tail).catch(() => undefined);\n return read?.status === \"found\" ? read.snapshot : undefined;\n};\n","/**\n * Why no Gemini CLI callback carries a delivery identity.\n *\n * This file deliberately exports no `deliveryIdentity` function. The adapter\n * declares `deliveryIdentifier: \"none\"`, and this is the record of the field-by-\n * field reasoning behind that, so a future protocol version can be checked against\n * it rather than re-litigated from scratch.\n *\n * ## What the protocol provides\n *\n * Every Gemini hook input carries exactly three things that could bear on identity\n * (see `schema.ts`): `session_id`, `hook_event_name`, and an optional `timestamp`.\n * There is no request id, no turn id, and no tool-call id anywhere in the\n * vocabulary.\n *\n * The tool-call gap is a projection, not an absence: the CLI's own\n * `ToolCallRequestInfo` carries a `callId`, but `HookEventHandler`'s\n * `fireBeforeToolEvent` / `fireAfterToolEvent` build their inputs from\n * `tool_name`, `tool_input`, `mcp_context`, and `original_request_name` only, so\n * the id never crosses into the hook. Exposing it is what would unblock\n * deduplication for the two highest-volume events.\n *\n * ## Why a timestamp is not an identity\n *\n * `timestamp` is provider-recorded rather than read from a clock when the hook\n * runs, so it does repeat on redelivery. But repeating is only half of what an\n * identity needs: it must also *separate* two genuine firings, and a millisecond\n * reading does not. Two `BeforeTool` firings for the same tool inside one\n * millisecond — a loop issuing the same call, a parallel fan-out, a fast local\n * tool — produce byte-identical `(timestamp, tool_name)` pairs. Keying on that pair\n * makes the runtime suppress the *second real call* as though it were a\n * redelivery, which silently loses a span and its usage.\n *\n * ## Why `session_id` is not an identity either\n *\n * This is the subtler one, and it is why even the once-per-session events are\n * refused. `SessionStart` carries `source: \"startup\" | \"resume\" | \"clear\"`, so the\n * Gemini CLI fires it **again within the same `session_id`** when a session is\n * resumed or cleared. `(session_id, \"SessionStart\")` therefore names a *class* of\n * firings, not one firing. Treating it as an identity would suppress every resume\n * and every clear after the first — the user's session would appear to start once\n * and never restart, and the same argument applies to `SessionEnd` on the closing\n * side.\n *\n * A constant component would have made that worse rather than better: it looks\n * like a deliberate identity while being the least discriminating value possible.\n *\n * ## Consequence\n *\n * Deduplication for the Gemini CLI is available only against a host-supplied\n * `--callback-id`. `requireCallbackId` reports every callback as\n * `provider-declares-none`, which is the honest diagnostic: the gap is in the\n * protocol, not in this adapter's reading of it. Under-reporting coverage is\n * recoverable at a collector; suppressing a real observation is not.\n *\n * **To unblock:** a per-firing identifier in the Gemini hook payload — a request,\n * turn, or invocation id, or a `session_start_id` that changes on resume and clear.\n */\n\n/**\n * Every callback, and the field that would have to exist to identify it.\n *\n * Documentation rather than control flow. Kept exhaustive so that adding a hook\n * event without revisiting delivery identity is visibly an omission.\n */\nexport const GEMINI_UNIDENTIFIABLE_CALLBACKS: Readonly<Record<string, string>> = Object.freeze({\n SessionStart:\n \"fires again within the same session_id on resume and clear (payload `source`), so session_id names a class of firings rather than one\",\n SessionEnd: \"the closing side of the same problem: a cleared session ends under the same session_id\",\n BeforeTool:\n \"ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call\",\n AfterTool:\n \"ToolCallRequestInfo.callId exists but is not projected into the hook input; two calls to one tool can share a millisecond, so (timestamp, tool_name) would suppress a genuine second call\",\n BeforeAgent: \"no turn id; fires once per turn with only a millisecond separating turns\",\n AfterAgent: \"no turn id; fires once per turn with only a millisecond separating turns\",\n PreCompress: \"no compaction id; can fire repeatedly within one session\",\n BeforeModel: \"no request id\",\n AfterModel:\n \"fires per streaming chunk with the same llm_request each time, so several genuine firings share one request and often one millisecond\",\n BeforeToolSelection: \"no request id\",\n Notification: \"produces no canonical event\",\n});\n","import { sessionIdSchema, type SessionId } from \"../../model/primitives.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport type { WorkspaceIdentity } from \"../../model/identity.js\";\nimport type { ProviderContext } from \"../adapter.js\";\nimport type { GeminiHookInput } from \"./schema.js\";\n\n/** Deterministic, sorted-key serialization used to derive content-addressed ids. */\nexport const stableKey = (value: unknown): string => {\n const seen = new WeakSet<object>();\n const walk = (input: unknown): string => {\n if (input === null || input === undefined) {\n return \"null\";\n }\n if (typeof input === \"string\") {\n return JSON.stringify(input);\n }\n if (typeof input === \"number\") {\n return Number.isFinite(input) ? JSON.stringify(input) : \"null\";\n }\n if (typeof input === \"boolean\") {\n return input ? \"true\" : \"false\";\n }\n if (typeof input !== \"object\") {\n return \"null\";\n }\n if (seen.has(input)) {\n return '\"<circular>\"';\n }\n seen.add(input);\n if (Array.isArray(input)) {\n return `[${input.map((entry) => walk(entry)).join(\",\")}]`;\n }\n const record = input as Record<string, unknown>;\n const keys = Object.keys(record).sort();\n return `{${keys.map((key) => `${JSON.stringify(key)}:${walk(record[key])}`).join(\",\")}}`;\n };\n return walk(value);\n};\n\nexport const geminiSessionId = (input: GeminiHookInput): SessionId => sessionIdSchema.parse(input.session_id);\n\n/** `undefined` when the timestamp is absent or unparsable; the caller supplies a fallback. */\nexport const parseGeminiTimestamp = (timestamp: string | undefined): number | undefined => {\n if (timestamp === undefined) {\n return undefined;\n }\n const parsed = Date.parse(timestamp);\n return Number.isNaN(parsed) ? undefined : parsed;\n};\n\nexport const geminiWorkspace = (\n context: ProviderContext,\n input: GeminiHookInput,\n): WorkspaceIdentity | undefined =>\n input.cwd === undefined\n ? undefined\n : deriveWorkspaceIdentity(context.privacy, { kind: \"working-directory\", absolutePath: input.cwd });\n\n/**\n * Stable content used to key a tool call across its `BeforeTool`/`AfterTool`\n * pair.\n *\n * **`tool_input` is deliberately excluded.** A `BeforeTool` hook may return\n * `hookSpecificOutput.tool_input`, which the CLI merges with\n * `Object.assign(invocation.params, modifiedInput)` — an in-place mutation of the\n * very object it later hands to `AfterTool`. So `BeforeTool` sees the model's\n * arguments and `AfterTool` sees the rewritten ones, for one and the same call.\n * Keying on the input would split that call into two unpaired halves.\n *\n * **`original_request_name` is a distinguisher, not a replacement.** It appears\n * only on a *tail tool call* — a tool the CLI runs in place of another because an\n * `AfterTool` hook returned `hookSpecificOutput.tailToolCallRequest` — and names\n * the tool the model originally asked for, while `tool_name` names the tool\n * actually running. Keying on `original_request_name` alone would hand the tail\n * call the *original* call's id, so two different tools would share one span.\n * Both names therefore go into the key, which keeps the tail call's own\n * before/after pair together and apart from the call it replaced.\n *\n * The residual gap: two calls to the same tool in a row within one turn are not\n * distinguishable from this protocol alone. The CLI has an internal\n * `ToolCallRequestInfo.callId`, but does not pass it to hooks (see\n * `./delivery.ts`).\n */\nexport const geminiToolCallKey = (input: {\n readonly tool_name: string;\n readonly original_request_name?: string | undefined;\n}): string =>\n input.original_request_name === undefined || input.original_request_name === input.tool_name\n ? input.tool_name\n : stableKey({ tail: input.tool_name, replacing: input.original_request_name });\n\nexport const geminiToolCallId = (\n context: ProviderContext,\n sessionId: string,\n toolKey: string,\n): string => context.ids.newOpaqueId([sessionId, \"gemini-cli\", \"tool\", toolKey]);\n\n/**\n * Stable content used to key a model call across its `BeforeModel` and\n * (possibly many, streaming) `AfterModel` firings: both carry `llm_request`\n * unchanged for the same call, so hashing it correlates them without needing an\n * explicit request id, which the protocol does not provide.\n */\nexport const geminiGenerationId = (\n context: ProviderContext,\n sessionId: string,\n llmRequest: unknown,\n): string => context.ids.newOpaqueId([sessionId, \"gemini-cli\", \"generation\", stableKey(llmRequest)]);\n\n/**\n * Content that distinguishes one hook firing from the next, mixed into the\n * derived `invocationId`. Re-delivering the exact same payload (a retried or\n * duplicated hook call) reproduces the same content and therefore the same\n * invocation id, which is what makes replay idempotent at the collector.\n */\nexport const geminiCorrelationSeed = (input: GeminiHookInput): string => {\n switch (input.hook_event_name) {\n case \"SessionStart\":\n return input.source ?? \"session-start\";\n case \"SessionEnd\":\n return input.reason ?? \"session-end\";\n case \"BeforeAgent\":\n return stableKey({ prompt: input.prompt });\n case \"AfterAgent\":\n return stableKey({ prompt: input.prompt, response: input.prompt_response });\n case \"BeforeModel\":\n return stableKey(input.llm_request);\n case \"AfterModel\":\n return stableKey({ request: input.llm_request, response: input.llm_response });\n case \"BeforeToolSelection\":\n return stableKey(input.llm_request);\n case \"BeforeTool\":\n return stableKey({ tool: geminiToolCallKey(input), input: input.tool_input });\n case \"AfterTool\":\n return stableKey({\n tool: geminiToolCallKey(input),\n input: input.tool_input,\n response: input.tool_response,\n });\n case \"PreCompress\":\n return input.trigger ?? \"compress\";\n case \"Notification\":\n return stableKey({ type: input.notification_type, message: input.message });\n }\n};\n","import { z } from \"zod\";\n\n/**\n * Zod schemas for the Gemini CLI command hook protocol.\n *\n * Shapes follow the public Gemini CLI hooks reference\n * (https://geminicli.com/docs/hooks/reference/,\n * https://github.com/google-gemini/gemini-cli/blob/main/docs/hooks/writing-hooks.md)\n * cross-checked field by field against the CLI source that *produces* these\n * payloads, pinned at `google-gemini/gemini-cli@3499c84`:\n *\n * - `packages/core/src/hooks/types.ts` — `HookEventName` and the per-event input\n * interfaces.\n * - `packages/core/src/hooks/hookTranslator.ts` — `LLMRequest` / `LLMResponse`,\n * the \"decoupled\", SDK-agnostic shapes the model events carry.\n * - `packages/core/src/hooks/hookEventHandler.ts` — how each input is assembled.\n *\n * Every hook receives the base fields below plus event-specific fields keyed by\n * `hook_event_name`. Unknown extra fields are stripped rather than rejected,\n * since the CLI is free to add fields the adapter does not yet model.\n */\n\nexport const GEMINI_HOOK_EVENT_NAMES = [\n \"SessionStart\",\n \"SessionEnd\",\n \"BeforeAgent\",\n \"AfterAgent\",\n \"BeforeModel\",\n \"AfterModel\",\n \"BeforeToolSelection\",\n \"BeforeTool\",\n \"AfterTool\",\n \"PreCompress\",\n \"Notification\",\n] as const;\nexport type GeminiHookEventName = (typeof GEMINI_HOOK_EVENT_NAMES)[number];\n\nconst baseHookInputSchema = z.object({\n session_id: z.string().min(1),\n transcript_path: z.string().optional(),\n cwd: z.string().optional(),\n timestamp: z.string().min(1).optional(),\n});\n\nconst llmMessageSchema = z\n .object({\n role: z.enum([\"user\", \"model\", \"system\"]).optional(),\n content: z.union([z.string(), z.array(z.unknown())]).optional(),\n })\n .loose();\n\nconst llmRequestConfigSchema = z\n .object({\n temperature: z.number().optional(),\n maxOutputTokens: z.number().int().min(0).optional(),\n })\n .loose();\n\nexport const geminiLlmRequestSchema = z\n .object({\n model: z.string().min(1).optional(),\n messages: z.array(llmMessageSchema).optional(),\n config: llmRequestConfigSchema.optional(),\n toolConfig: z.unknown().optional(),\n })\n .loose();\nexport type GeminiLlmRequest = z.infer<typeof geminiLlmRequestSchema>;\n\n/**\n * `usageMetadata`, as the hook actually receives it.\n *\n * The hook does **not** see the Gemini API's `usageMetadata` verbatim.\n * `HookTranslatorGenAIv1.toHookLLMResponse` rebuilds the object with exactly\n * three counters — `promptTokenCount`, `candidatesTokenCount`, and\n * `totalTokenCount` — and the declared `LLMResponse['usageMetadata']` type lists\n * only those three. `cachedContentTokenCount` and `thoughtsTokenCount` exist on\n * the SDK response the CLI receives, but are dropped before any hook runs, which\n * is why {@link DEFAULT_GEMINI_CAPABILITIES} declares neither cached input nor\n * reasoning output as reported.\n *\n * They stay modelled here anyway, and `mapGeminiUsage` still honours them: the\n * translator is versioned (`HookTranslator` is an abstract base with a\n * `defaultHookTranslator` instance per SDK generation), so a later version may\n * widen the projection. Modelling a counter costs nothing; silently discarding\n * one the CLI started sending would understate every cache read.\n *\n * Inclusion semantics, when a counter *is* present, follow the Gemini API:\n * `promptTokenCount` is inclusive of `cachedContentTokenCount`, while\n * `candidatesTokenCount` and `thoughtsTokenCount` are separate counters that are\n * never merged before normalization.\n */\nexport const geminiUsageMetadataSchema = z\n .object({\n promptTokenCount: z.number().int().min(0).optional(),\n cachedContentTokenCount: z.number().int().min(0).optional(),\n candidatesTokenCount: z.number().int().min(0).optional(),\n thoughtsTokenCount: z.number().int().min(0).optional(),\n totalTokenCount: z.number().int().min(0).optional(),\n })\n .loose();\nexport type GeminiUsageMetadata = z.infer<typeof geminiUsageMetadataSchema>;\n\n/**\n * A candidate in the decoupled hook response format.\n *\n * `content.parts` is `string[]` here, not the SDK's `Part[]`: the translator\n * keeps only text parts and maps them to bare strings\n * (`parts: candidate.content?.parts?.filter(hasTextProperty).map((p) => p.text)`).\n * The element type stays `unknown` so that the `{ text }` spelling — which is\n * what a *hook* writes back in `hookSpecificOutput.llm_response`, and what the\n * SDK uses — is read rather than rejected.\n *\n * `finishReason`'s declared union is five values wide, but the translator casts\n * the SDK's own `FinishReason` through unchanged, so any value the API emits\n * (`BLOCKLIST`, `PROHIBITED_CONTENT`, `MALFORMED_FUNCTION_CALL`, …) reaches the\n * hook verbatim. It is therefore typed as a free string and classified by name.\n */\nconst geminiCandidateSchema = z\n .object({\n content: z\n .object({\n role: z.string().optional(),\n parts: z.array(z.unknown()).optional(),\n })\n .loose()\n .optional(),\n finishReason: z.string().optional(),\n index: z.number().int().min(0).optional(),\n })\n .loose();\n\nexport const geminiLlmResponseSchema = z\n .object({\n /** Whole-response text, set by the translator from `getResponseText`. */\n text: z.string().optional(),\n candidates: z.array(geminiCandidateSchema).optional(),\n usageMetadata: geminiUsageMetadataSchema.optional(),\n })\n .loose();\nexport type GeminiLlmResponse = z.infer<typeof geminiLlmResponseSchema>;\n\n/**\n * Connection identity for an MCP-backed tool call, present on `BeforeTool` and\n * `AfterTool` only when the tool came from an MCP server (`McpToolContext`).\n * Modelled to record the vocabulary; the adapter reads none of it, because the\n * `command`/`args`/`url` fields describe a server the operator configured.\n */\nconst geminiMcpContextSchema = z\n .object({\n server_name: z.string().optional(),\n tool_name: z.string().optional(),\n })\n .loose();\n\nconst geminiToolResponseSchema = z\n .object({\n llmContent: z.unknown().optional(),\n returnDisplay: z.unknown().optional(),\n error: z.unknown().optional(),\n })\n .loose();\n\nexport const sessionStartInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"SessionStart\"),\n source: z.enum([\"startup\", \"resume\", \"clear\"]).optional(),\n});\n\nexport const sessionEndInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"SessionEnd\"),\n reason: z.enum([\"exit\", \"clear\", \"logout\", \"prompt_input_exit\", \"other\"]).optional(),\n});\n\nexport const beforeAgentInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeAgent\"),\n prompt: z.string().optional(),\n});\n\nexport const afterAgentInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"AfterAgent\"),\n prompt: z.string().optional(),\n prompt_response: z.string().optional(),\n stop_hook_active: z.boolean().optional(),\n});\n\nexport const beforeModelInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeModel\"),\n llm_request: geminiLlmRequestSchema,\n});\n\n/**\n * Fires once per **streaming chunk**, not once per model call: `geminiChat.ts`\n * calls `fireAfterModelEvent(originalRequest, chunk)` from inside its\n * `for await (const chunk of streamResponse)` loop. `llm_request` is the same\n * object for every chunk of one call, which is what lets `geminiGenerationId`\n * correlate them; `llm_response` is that one chunk.\n */\nexport const afterModelInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"AfterModel\"),\n llm_request: geminiLlmRequestSchema,\n llm_response: geminiLlmResponseSchema,\n});\n\nexport const beforeToolSelectionInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeToolSelection\"),\n llm_request: geminiLlmRequestSchema,\n});\n\n/**\n * `original_request_name` is present only for a **tail tool call** — a second\n * tool the CLI runs in place of the first because an `AfterTool` hook returned\n * `hookSpecificOutput.tailToolCallRequest`. It names the tool the *model* asked\n * for, while `tool_name` names the tool actually executing\n * (`ToolCallRequestInfo.originalRequestName`). It is not a rewrite marker for\n * `tool_input`; see `identity.ts` for why that distinction changes correlation.\n */\nexport const beforeToolInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"BeforeTool\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n mcp_context: geminiMcpContextSchema.optional(),\n original_request_name: z.string().min(1).optional(),\n});\n\nexport const afterToolInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"AfterTool\"),\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_response: geminiToolResponseSchema.optional(),\n mcp_context: geminiMcpContextSchema.optional(),\n original_request_name: z.string().min(1).optional(),\n});\n\nexport const preCompressInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"PreCompress\"),\n trigger: z.enum([\"auto\", \"manual\"]).optional(),\n});\n\nexport const notificationInputSchema = baseHookInputSchema.extend({\n hook_event_name: z.literal(\"Notification\"),\n notification_type: z.string().optional(),\n message: z.string().optional(),\n details: z.unknown().optional(),\n});\n\nexport const geminiHookInputSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartInputSchema,\n sessionEndInputSchema,\n beforeAgentInputSchema,\n afterAgentInputSchema,\n beforeModelInputSchema,\n afterModelInputSchema,\n beforeToolSelectionInputSchema,\n beforeToolInputSchema,\n afterToolInputSchema,\n preCompressInputSchema,\n notificationInputSchema,\n]);\nexport type GeminiHookInput = z.infer<typeof geminiHookInputSchema>;\n\nexport type GeminiHookInputOfType<TName extends GeminiHookEventName> = Extract<\n GeminiHookInput,\n { hook_event_name: TName }\n>;\n\n/** Cheap structural check used to distinguish \"not this protocol at all\" from a shape mismatch. */\nexport const looksLikeGeminiHookPayload = (payload: unknown): boolean => {\n if (typeof payload !== \"object\" || payload === null || Array.isArray(payload)) {\n return false;\n }\n const record = payload as Record<string, unknown>;\n return (\n typeof record.session_id === \"string\" &&\n typeof record.hook_event_name === \"string\" &&\n (GEMINI_HOOK_EVENT_NAMES as readonly string[]).includes(record.hook_event_name)\n );\n};\n","import type { ToolKind } from \"../../model/events.js\";\n\n/**\n * Classify a Gemini CLI built-in tool name into a canonical {@link ToolKind}.\n *\n * The names are Gemini's own, taken from the tool declarations at\n * `google-gemini/gemini-cli@3499c84`\n * (`packages/core/src/tools/definitions/base-declarations.ts` and\n * `packages/core/src/tools/tool-names.ts`) rather than transliterated from\n * another agent's vocabulary. Several are near-misses for a name a different CLI\n * uses and would be wrong if guessed: the edit tool is `replace`, not `edit`;\n * content search is `grep_search`, not `grep` or `search_file_content`; the shell\n * is `run_shell_command`, not `shell`; web search is `google_web_search`. There\n * is no `save_memory` tool — the CLI's own prompt says so outright and points at\n * `replace`/`write_file` on `GEMINI.md` instead.\n *\n * Unrecognized names map to `unknown` rather than a guess.\n */\nconst BUILT_IN_TOOL_KIND: Readonly<Record<string, ToolKind>> = Object.freeze({\n read_file: \"read\",\n read_many_files: \"read\",\n list_directory: \"read\",\n get_internal_docs: \"read\",\n read_mcp_resource: \"read\",\n list_mcp_resources: \"read\",\n write_file: \"write\",\n replace: \"write\",\n run_shell_command: \"execute\",\n glob: \"search\",\n grep_search: \"search\",\n web_fetch: \"network\",\n google_web_search: \"network\",\n // Gemini's subagent entry point. The CLI has no subagent hook events, so a\n // delegated run is observable only as this tool's BeforeTool/AfterTool pair.\n invoke_agent: \"delegate\",\n activate_skill: \"other\",\n ask_user: \"other\",\n write_todos: \"other\",\n enter_plan_mode: \"other\",\n exit_plan_mode: \"other\",\n update_topic: \"other\",\n complete_task: \"other\",\n tracker_create_task: \"other\",\n tracker_update_task: \"other\",\n tracker_get_task: \"other\",\n tracker_list_tasks: \"other\",\n tracker_add_dependency: \"other\",\n tracker_visualize: \"other\",\n});\n\n/**\n * MCP tools are named `mcp_<server>_<tool>` — a single underscore separator and\n * an `mcp_` prefix that `generateValidName` enforces. What such a tool does is\n * defined by the connected server, not by the Gemini CLI, so it stays `unknown`.\n * The prefix is checked before the table so that a server whose generated name\n * happens to collide with a built-in is not misclassified.\n */\nconst MCP_TOOL_PREFIX = \"mcp_\";\n\n/** Tools the CLI discovers from a project command; likewise server-defined. */\nconst DISCOVERED_TOOL_PREFIX = \"discovered_tool_\";\n\nexport const classifyGeminiToolKind = (toolName: string): ToolKind => {\n if (toolName.startsWith(MCP_TOOL_PREFIX) || toolName.startsWith(DISCOVERED_TOOL_PREFIX)) {\n return \"unknown\";\n }\n return BUILT_IN_TOOL_KIND[toolName] ?? \"unknown\";\n};\n","import { usageReportSchema, type UsageReport } from \"../../model/usage.js\";\nimport type { GeminiUsageMetadata } from \"./schema.js\";\n\n/**\n * Map Gemini's `usageMetadata` onto a canonical {@link UsageReport}.\n *\n * ## Why `cumulative`\n *\n * `AfterModel` fires per streaming chunk, and a chunk's `usageMetadata` is a\n * snapshot of the response so far, not that chunk's own increment. Two places in\n * the Gemini CLI state this by construction: `loggingContentGenerator`'s\n * `loggingStreamWrapper` keeps `lastUsageMetadata` across the stream and reports\n * that single value as the call's usage, and `chatRecordingService`\n * `recordMessageTokens` *replaces* the recorded token counts rather than adding\n * to them. Neither sums, so a later snapshot must already contain the earlier\n * one.\n *\n * Reporting these as `delta` would therefore add every snapshot together: a\n * stream that carries usage on three chunks would bill roughly three times the\n * true prompt. Declaring `cumulative` hands the composition to the runtime,\n * which diffs each snapshot against the baseline stored at\n * `usage:<sessionId>:generation:<generationId>` — so N usage-bearing chunks\n * contribute the final total exactly once, and a redelivered chunk yields a zero\n * delta rather than a second charge.\n *\n * This holds whether the API emits usage on one chunk or on many: a lone\n * snapshot with no baseline is emitted as its own first delta, which is the same\n * number `delta` would have produced.\n *\n * ## Counters\n *\n * `promptTokenCount` is inclusive of `cachedContentTokenCount` (a subset).\n * `candidatesTokenCount` and `thoughtsTokenCount` are separate, explicit\n * counters, so canonical `outputTokens` is their sum (inclusive, per core usage\n * semantics) and `reasoningOutputTokens` carries `thoughtsTokenCount` unchanged.\n * `totalTokenCount` is passed through as `providerTotalTokens` and validated by\n * `normalizeUsage`, never reconstructed here. Gemini reports no cache-creation\n * counter, so that field is always left absent. Any counter the provider did not\n * report stays absent rather than being defaulted to zero.\n *\n * Today the CLI's hook translator strips `cachedContentTokenCount` and\n * `thoughtsTokenCount` before a hook sees them (see\n * {@link GeminiUsageMetadata}), so on current payloads the cache and reasoning\n * branches below are dormant. They are kept because the translator is versioned\n * and dropping a counter the CLI started sending is the worse failure.\n */\nexport const mapGeminiUsage = (usage: GeminiUsageMetadata | undefined): UsageReport | undefined => {\n if (usage === undefined) {\n return undefined;\n }\n const {\n promptTokenCount,\n cachedContentTokenCount,\n candidatesTokenCount,\n thoughtsTokenCount,\n totalTokenCount,\n } = usage;\n\n const reportsNothing =\n promptTokenCount === undefined &&\n cachedContentTokenCount === undefined &&\n candidatesTokenCount === undefined &&\n thoughtsTokenCount === undefined &&\n totalTokenCount === undefined;\n if (reportsNothing) {\n return undefined;\n }\n\n const hasOutput = candidatesTokenCount !== undefined || thoughtsTokenCount !== undefined;\n\n return usageReportSchema.parse({\n temporality: \"cumulative\",\n ...(promptTokenCount === undefined ? {} : { inputTokens: promptTokenCount }),\n ...(cachedContentTokenCount === undefined ? {} : { cachedInputTokens: cachedContentTokenCount }),\n ...(hasOutput\n ? { outputTokens: (candidatesTokenCount ?? 0) + (thoughtsTokenCount ?? 0) }\n : {}),\n ...(thoughtsTokenCount === undefined ? {} : { reasoningOutputTokens: thoughtsTokenCount }),\n ...(totalTokenCount === undefined ? {} : { providerTotalTokens: totalTokenCount }),\n });\n};\n\n/**\n * Whether a chunk carries a usage snapshot at all.\n *\n * Most chunks of a stream do not. Those carry no billable observation, so the\n * adapter ignores them rather than closing a generation with no usage.\n */\nexport const hasGeminiUsageSnapshot = (usage: GeminiUsageMetadata | undefined): boolean =>\n mapGeminiUsage(usage) !== undefined;\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport type { EventOutcome, ToolKind } from \"../../model/events.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../../model/identity.js\";\nimport { providerIdSchema, type ProviderId } from \"../../model/primitives.js\";\nimport { normalizeUsage, type CanonicalUsage } from \"../../model/usage.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport { GEMINI_UNIDENTIFIABLE_CALLBACKS } from \"./delivery.js\";\nimport {\n geminiCorrelationSeed,\n geminiGenerationId,\n geminiSessionId,\n geminiToolCallId,\n geminiToolCallKey,\n geminiWorkspace,\n parseGeminiTimestamp,\n} from \"./identity.js\";\nimport { geminiHookInputSchema, looksLikeGeminiHookPayload, type GeminiHookInput } from \"./schema.js\";\nimport { classifyGeminiToolKind } from \"./tool-kind.js\";\nimport { mapGeminiUsage } from \"./usage.js\";\n\nexport const GEMINI_PROVIDER_ID = \"gemini-cli\" as const;\nexport const GEMINI_ADAPTER_VERSION = \"0.1.0\";\n\nexport const DEFAULT_GEMINI_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\n \"session.start\",\n \"session.end\",\n \"prompt.submitted\",\n \"generation.start\",\n \"generation.end\",\n \"tool.start\",\n \"tool.end\",\n \"compaction.performed\",\n ] as const),\n // `AfterModel` fires per streaming chunk and a chunk's `usageMetadata` is a\n // snapshot of the response so far, not that chunk's increment. See\n // `./usage.ts` for the evidence; `delta` here would bill a multi-snapshot\n // stream several times over.\n usageTemporality: \"cumulative\",\n // Both false because the CLI's hook translator strips the counters before any\n // hook runs: `toHookLLMResponse` rebuilds `usageMetadata` as exactly\n // `{ promptTokenCount, candidatesTokenCount, totalTokenCount }`. The SDK\n // response it reads does carry `cachedContentTokenCount` and\n // `thoughtsTokenCount`, so this is a gap in the hook projection rather than in\n // the model — but a consumer must be able to tell \"this provider reports no\n // cache reads\" from \"this session had none\", and today it is the former.\n reportsCachedInput: false,\n reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\n reportsReasoningOutput: false,\n reportsProviderTotal: true,\n reportsCost: false,\n // The Gemini CLI has no subagent hook events. Delegation happens through the\n // `invoke_agent` tool, so a subagent run is observable only as that tool's\n // BeforeTool/AfterTool pair — never as a distinct subagent lifecycle.\n emitsSubagentEvents: false,\n emitsCompactionEvents: true,\n requiresHookResponse: false,\n // Nothing in this protocol identifies a callback across a redelivery: there is\n // no request, turn, or tool-call id, and `session_id` repeats across resume and\n // clear. See `./delivery.ts` for the field-by-field reasoning.\n deliveryIdentifier: \"none\",\n});\n\nexport type GeminiAdapterOptions = {\n readonly id?: string;\n readonly version?: string;\n readonly capabilities?: Partial<ProviderCapabilities>;\n};\n\nconst SESSION_END_REASON_OUTCOME: Readonly<Record<string, \"completed\" | \"unknown\">> = Object.freeze({\n exit: \"completed\",\n clear: \"completed\",\n logout: \"completed\",\n prompt_input_exit: \"completed\",\n other: \"unknown\",\n});\n\nconst FINISH_REASON_OUTCOME: Readonly<Record<string, EventOutcome>> = Object.freeze({\n STOP: \"ok\",\n MAX_TOKENS: \"ok\",\n SAFETY: \"denied\",\n RECITATION: \"denied\",\n BLOCKLIST: \"denied\",\n PROHIBITED_CONTENT: \"denied\",\n SPII: \"denied\",\n LANGUAGE: \"denied\",\n MALFORMED_FUNCTION_CALL: \"error\",\n OTHER: \"unknown\",\n});\n\nconst finishReasonOutcome = (finishReason: string | undefined): EventOutcome =>\n finishReason === undefined ? \"unknown\" : (FINISH_REASON_OUTCOME[finishReason] ?? \"unknown\");\n\nconst partText = (part: unknown): string | undefined => {\n if (typeof part === \"string\") {\n return part;\n }\n if (typeof part === \"object\" && part !== null && \"text\" in part) {\n const { text } = part;\n return typeof text === \"string\" ? text : undefined;\n }\n return undefined;\n};\n\n/**\n * The hook's `content.parts` is `string[]` — the CLI's translator keeps text\n * parts only and flattens them to bare strings. The `{ text }` spelling is read\n * too, because that is what a hook writes back in\n * `hookSpecificOutput.llm_response` and what the SDK response uses.\n */\nconst joinResponseText = (parts: readonly unknown[] | undefined): string | undefined => {\n if (parts === undefined || parts.length === 0) {\n return undefined;\n }\n const texts = parts.map(partText).filter((text): text is string => text !== undefined);\n const joined = texts.join(\"\");\n return joined === \"\" ? undefined : joined;\n};\n\nconst nonEmpty = (text: string | undefined): string | undefined =>\n text === undefined || text === \"\" ? undefined : text;\n\nconst messageText = (content: string | readonly unknown[] | undefined): string | undefined => {\n if (content === undefined) {\n return undefined;\n }\n if (typeof content === \"string\") {\n return content;\n }\n return joinResponseText(content);\n};\n\n/**\n * Provider adapter for the Gemini CLI's command hooks.\n *\n * Detection is purely structural (the protocol carries no provider tag), so\n * confidence is `exact` only when the full event-specific shape validates, and\n * `weak` when the payload merely looks like this protocol. All eleven hook events\n * in the CLI's `HookEventName` enum are recognized; `AfterAgent`,\n * `BeforeToolSelection`, and `Notification` carry no canonical telemetry and are\n * parsed as `ignored`.\n *\n * `AfterModel` fires once per streaming chunk. A chunk that carries no\n * `usageMetadata` is ignored; a chunk that carries one completes a\n * `generation.end` for the generation its `llm_request` identifies. Several\n * chunks of one stream may each carry a snapshot, and each closes the *same*\n * generation: the snapshots are cumulative, so the runtime diffs them against the\n * generation's stored baseline and the stream is billed once in total rather than\n * once per chunk. See `./usage.ts` for why that is the correct reading, and\n * `./delivery.ts` for the identity trade-offs this protocol imposes.\n */\nexport const createGeminiCliAdapter = (options: GeminiAdapterOptions = {}): ProviderAdapter => {\n const id: ProviderId = providerIdSchema.parse(options.id ?? GEMINI_PROVIDER_ID);\n const version = options.version ?? GEMINI_ADAPTER_VERSION;\n const capabilities: ProviderCapabilities = {\n ...DEFAULT_GEMINI_CAPABILITIES,\n ...options.capabilities,\n };\n\n const detect = (input: ProviderDetectionInput): ProviderDetection => {\n const parsed = geminiHookInputSchema.safeParse(input.payload);\n if (parsed.success) {\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"exact\",\n reasons: [\n \"payload matches the Gemini CLI command hook schema\",\n `hook_event_name=${parsed.data.hook_event_name}`,\n ],\n sourceEventName: parsed.data.hook_event_name,\n });\n }\n if (looksLikeGeminiHookPayload(input.payload)) {\n const record = input.payload as { hook_event_name: string };\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"weak\",\n reasons: [\n \"payload has session_id and a recognized hook_event_name but failed event-specific validation\",\n ],\n sourceEventName: record.hook_event_name,\n });\n }\n return unknownDetection([\"payload does not match the Gemini CLI command hook protocol\"]);\n };\n\n const identify = (input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[] => {\n const parsed = geminiHookInputSchema.safeParse(input.payload);\n if (!parsed.success) {\n return [];\n }\n const payload = parsed.data;\n const sessionId = geminiSessionId(payload);\n const startedAt = parseGeminiTimestamp(payload.timestamp) ?? context.clock.now();\n const workspace = geminiWorkspace(context, payload);\n const invocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId,\n sourceEventName: payload.hook_event_name,\n occurredAt: startedAt,\n discriminator: geminiCorrelationSeed(payload),\n });\n\n return [\n identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId,\n startedAt,\n ...(workspace === undefined ? {} : { workspace }),\n },\n }),\n ];\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const parsed = geminiHookInputSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the Gemini CLI command hook protocol\",\n }),\n };\n }\n const payload: GeminiHookInput = parsed.data;\n const sessionId = String(input.identity.sessionId);\n const occurredAt = input.identity.startedAt;\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n\n switch (payload.hook_event_name) {\n case \"SessionStart\": {\n factory.build({\n type: \"session.start\",\n sessionKind: \"unknown\",\n agentName: \"gemini-cli\",\n occurredAt,\n });\n break;\n }\n\n case \"SessionEnd\": {\n factory.build({\n type: \"session.end\",\n reason: SESSION_END_REASON_OUTCOME[payload.reason ?? \"other\"] ?? \"unknown\",\n occurredAt,\n });\n break;\n }\n\n case \"BeforeAgent\": {\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n occurredAt,\n ...(payload.prompt === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.prompt,\n }),\n }),\n });\n break;\n }\n\n case \"AfterAgent\": {\n return {\n status: \"ignored\",\n reason:\n \"AfterAgent marks turn completion; the canonical model has no turn-level event distinct from generation.end, so it carries no telemetry of its own\",\n };\n }\n\n case \"BeforeModel\": {\n const generationId = geminiGenerationId(context, sessionId, payload.llm_request);\n const model = { modelId: payload.llm_request.model ?? \"unknown\", vendor: \"google\" };\n const inputContent = (payload.llm_request.messages ?? [])\n .map((message) => {\n const text = messageText(message.content);\n return text === undefined\n ? undefined\n : context.privacy.describeContent({\n kind: \"prompt\",\n role: message.role === \"model\" ? \"assistant\" : (message.role ?? \"unknown\"),\n text,\n });\n })\n .filter((fact) => fact !== undefined);\n factory.build({\n type: \"generation.start\",\n generationId,\n model,\n occurredAt,\n ...(payload.llm_request.config?.maxOutputTokens === undefined\n ? {}\n : { requestedMaxOutputTokens: payload.llm_request.config.maxOutputTokens }),\n ...(inputContent.length === 0 ? {} : { inputContent }),\n });\n break;\n }\n\n case \"AfterModel\": {\n const usage = mapGeminiUsage(payload.llm_response.usageMetadata);\n if (usage === undefined) {\n return {\n status: \"ignored\",\n reason: \"AfterModel fired for a streaming chunk carrying no usageMetadata snapshot\",\n };\n }\n const generationId = geminiGenerationId(context, sessionId, payload.llm_request);\n const model = { modelId: payload.llm_request.model ?? \"unknown\", vendor: \"google\" };\n const candidate = payload.llm_response.candidates?.[0];\n // The translator also sets a whole-response `text`; fall back to it when\n // the chunk's candidate carries no text parts of its own.\n const outputText =\n joinResponseText(candidate?.content?.parts) ?? nonEmpty(payload.llm_response.text);\n const usageResult = normalizeUsageOrWarn(usage, warnings);\n factory.build({\n type: \"generation.end\",\n generationId,\n model,\n outcome: finishReasonOutcome(candidate?.finishReason),\n occurredAt,\n ...(candidate?.finishReason === undefined ? {} : { stopReason: candidate.finishReason }),\n ...(usageResult === undefined ? {} : { usage: usageResult }),\n ...(outputText === undefined\n ? {}\n : {\n outputContent: [\n context.privacy.describeContent({ kind: \"response\", role: \"assistant\", text: outputText }),\n ],\n }),\n });\n break;\n }\n\n case \"BeforeToolSelection\": {\n return {\n status: \"ignored\",\n reason: \"BeforeToolSelection carries tool-choice configuration only, not lifecycle telemetry\",\n };\n }\n\n case \"BeforeTool\": {\n const toolCallId = geminiToolCallId(context, sessionId, geminiToolCallKey(payload));\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName: payload.tool_name,\n toolKind: classifyGeminiToolKind(payload.tool_name) satisfies ToolKind,\n occurredAt,\n ...(payload.tool_input === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.tool_input,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"AfterTool\": {\n const toolCallId = geminiToolCallId(context, sessionId, geminiToolCallKey(payload));\n const hasError = payload.tool_response?.error !== undefined;\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName: payload.tool_name,\n outcome: hasError ? \"error\" : \"ok\",\n occurredAt,\n ...(payload.tool_response === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.tool_response,\n label: payload.tool_name,\n }),\n }),\n });\n break;\n }\n\n case \"PreCompress\": {\n factory.build({\n type: \"compaction.performed\",\n trigger: payload.trigger === \"manual\" ? \"manual\" : payload.trigger === \"auto\" ? \"automatic\" : \"unknown\",\n occurredAt,\n });\n break;\n }\n\n case \"Notification\": {\n return {\n status: \"ignored\",\n reason: \"Notification is observability-only in the Gemini CLI protocol and has no canonical event type\",\n };\n }\n }\n\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n };\n\n const hookResponse = (): ProviderHookResponse => SILENT_HOOK_RESPONSE;\n\n return {\n id,\n version,\n capabilities,\n detect,\n identify,\n // No `deliveryIdentity`: the capability is `none`, and offering a resolver\n // that always declines would be a contradiction the runtime never consults.\n // The gap table is still worth carrying — \"the protocol has no request id\" is\n // the actionable half of that answer, and only this adapter can say it.\n deliveryGaps: GEMINI_UNIDENTIFIABLE_CALLBACKS,\n parse,\n hookResponse,\n };\n};\n\nconst normalizeUsageOrWarn = (\n usage: ReturnType<typeof mapGeminiUsage>,\n warnings: string[],\n): CanonicalUsage | undefined => {\n if (usage === undefined) {\n return undefined;\n }\n const normalized = normalizeUsage(usage);\n if (normalized.status === \"invalid\") {\n warnings.push(...normalized.issues.map((issue) => issue.message));\n return undefined;\n }\n return normalized.usage;\n};\n","import { z } from \"zod\";\n\n/**\n * Raw hook payload shapes for Google Antigravity.\n *\n * Provenance: synthetic, reconstructed from the documented camelCase command\n * hooks and field names the integration task specified as verified —\n * `conversationId`, `workspacePaths`, `stepIdx`, `invocationNum`,\n * `transcriptPath`, `artifactDirectoryPath` — plus the five hook names\n * (`PreInvocation`, `PostInvocation`, `PreToolUse`, `PostToolUse`, `Stop`).\n * Every other field below (`toolName`, `toolInput`, `toolResponse`, `isError`,\n * `fullyIdle`, `agentVersion`) is an inferred reconstruction needed for the\n * hook to carry any tool or lifecycle fact at all; none of it has been\n * confirmed against a real Antigravity capture. See `./maturity.ts` for the\n * promotion gates that require that confirmation. No fixture in this package\n * is a copy of a real transcript, path, or credential.\n */\n\nexport const ANTIGRAVITY_HOOK_EVENT_NAMES = [\n \"PreInvocation\",\n \"PostInvocation\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"Stop\",\n] as const;\nexport type AntigravityHookEventName = (typeof ANTIGRAVITY_HOOK_EVENT_NAMES)[number];\n\nconst hookEventNameSchema = z.enum(ANTIGRAVITY_HOOK_EVENT_NAMES);\n\n/**\n * Loose shape check used only to recognize a malformed-but-clearly-Antigravity\n * payload: unknown keys pass through so additive fields degrade safely.\n */\nexport const antigravityWeakShapeSchema = z.object({ hookEventName: hookEventNameSchema }).passthrough();\n\nconst commonFields = {\n conversationId: z.string().min(1),\n workspacePaths: z.array(z.string().min(1)).max(64),\n invocationNum: z.number().int().min(0),\n /** Never disclosed: a real filesystem path. Accepted, never propagated. */\n transcriptPath: z.string().min(1).optional(),\n /** Never disclosed: a real filesystem path. Accepted, never propagated. */\n artifactDirectoryPath: z.string().min(1).optional(),\n};\n\nexport const preInvocationPayloadSchema = z.object({\n hookEventName: z.literal(\"PreInvocation\"),\n ...commonFields,\n agentVersion: z.string().min(1).optional(),\n});\nexport type PreInvocationPayload = z.infer<typeof preInvocationPayloadSchema>;\n\nexport const postInvocationPayloadSchema = z.object({\n hookEventName: z.literal(\"PostInvocation\"),\n ...commonFields,\n agentVersion: z.string().min(1).optional(),\n});\nexport type PostInvocationPayload = z.infer<typeof postInvocationPayloadSchema>;\n\nexport const preToolUsePayloadSchema = z.object({\n hookEventName: z.literal(\"PreToolUse\"),\n ...commonFields,\n stepIdx: z.number().int().min(0),\n toolName: z.string().min(1),\n toolInput: z.unknown().optional(),\n});\nexport type PreToolUsePayload = z.infer<typeof preToolUsePayloadSchema>;\n\nexport const postToolUsePayloadSchema = z.object({\n hookEventName: z.literal(\"PostToolUse\"),\n ...commonFields,\n stepIdx: z.number().int().min(0),\n toolName: z.string().min(1),\n toolResponse: z.unknown().optional(),\n isError: z.boolean().optional(),\n});\nexport type PostToolUsePayload = z.infer<typeof postToolUsePayloadSchema>;\n\nexport const stopPayloadSchema = z.object({\n hookEventName: z.literal(\"Stop\"),\n ...commonFields,\n fullyIdle: z.boolean(),\n});\nexport type StopPayload = z.infer<typeof stopPayloadSchema>;\n\nexport const antigravityHookPayloadSchema = z.discriminatedUnion(\"hookEventName\", [\n preInvocationPayloadSchema,\n postInvocationPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n stopPayloadSchema,\n]);\nexport type AntigravityHookPayload = z.infer<typeof antigravityHookPayloadSchema>;\n\n/** The tool name documented as the experimental subagent-delegation relationship. */\nexport const ANTIGRAVITY_SUBAGENT_TOOL_NAME = \"invoke_subagent\" as const;\n","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { antigravityHookPayloadSchema } from \"./payload.js\";\n\n/**\n * Which Antigravity callbacks carry an identifier that survives a redelivery.\n *\n * Everything here is built from `invocationNum` and `stepIdx` — the two counters\n * on the *verified* field list (see `./payload.ts`) — scoped by the equally\n * verified `conversationId`:\n *\n * - The tool pair takes both counters. Together they name one step of one\n * invocation, and the event name separates its before-edge from its after-edge.\n * - The invocation pair takes `invocationNum` alone. A counter named for the\n * invocation it numbers is what makes `PreInvocation` fire once per value of\n * it: a redelivery repeats the number, while a genuine second invocation\n * advances it. That is the same argument the tool pair rests on, applied to the\n * field that is present on *every* Antigravity payload rather than only the\n * tool ones.\n *\n * `Stop` remains excluded. It can fire more than once per invocation (idle, then\n * fully idle), and the only field that would separate those two firings —\n * `fullyIdle` — is a reconstruction this adapter has not confirmed against a real\n * capture, so it is not something to build an at-most-once guarantee on. Keying\n * `Stop` on `invocationNum` alone would be worse than not identifying it: it\n * would suppress the second, *real* firing.\n */\nconst INVOCATION_SCOPED_EVENTS: readonly string[] = [\"PreInvocation\", \"PostInvocation\"];\n\nexport const antigravityDeliveryIdentity = (\n input: ProviderIdentityInput,\n): ProviderDeliveryClaim | undefined => {\n const parsed = antigravityHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return undefined;\n }\n const payload = parsed.data;\n\n if (payload.hookEventName === \"PreToolUse\" || payload.hookEventName === \"PostToolUse\") {\n return {\n sessionId: payload.conversationId,\n sourceEventName: payload.hookEventName,\n components: [String(payload.invocationNum), String(payload.stepIdx)],\n evidence: [\"payload.invocationNum with payload.stepIdx names one step of one invocation\"],\n };\n }\n\n if (INVOCATION_SCOPED_EVENTS.includes(payload.hookEventName)) {\n return {\n sessionId: payload.conversationId,\n sourceEventName: payload.hookEventName,\n components: [String(payload.invocationNum)],\n evidence: [\"payload.invocationNum names one invocation, whose edges fire once each\"],\n };\n }\n\n return undefined;\n};\n\n/**\n * Why the remaining Antigravity callback carries no delivery identity.\n *\n * Exhaustive over {@link ANTIGRAVITY_HOOK_EVENT_NAMES}: every other event is\n * identified above, so `Stop` is the whole of this adapter's coverage gap and the\n * reason names the field whose confirmation would close it.\n */\nexport const ANTIGRAVITY_DELIVERY_GAPS: Readonly<Record<string, string>> = Object.freeze({\n Stop:\n \"Stop can fire twice per invocation (idle, then fully idle) and payload `fullyIdle` — the only field separating them — is an unconfirmed reconstruction, so invocationNum alone would suppress the second real firing\",\n});\n","import { createErrorInfo } from \"../../errors/index.js\";\nimport { identityClaimSchema, unknownWorkspaceIdentity, type IdentityClaim } from \"../../model/identity.js\";\nimport { providerIdSchema, sessionIdSchema, type ProviderId } from \"../../model/primitives.js\";\nimport { deriveWorkspaceIdentity } from \"../../privacy/workspace.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n unknownDetection,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../adapter.js\";\nimport { createEventFactory } from \"../builder.js\";\nimport { ANTIGRAVITY_DELIVERY_GAPS, antigravityDeliveryIdentity } from \"./delivery.js\";\nimport {\n ANTIGRAVITY_SUBAGENT_TOOL_NAME,\n antigravityHookPayloadSchema,\n antigravityWeakShapeSchema,\n} from \"./payload.js\";\n\nexport const ANTIGRAVITY_PROVIDER_ID = \"antigravity\" as const;\n\n/**\n * What this adapter can honestly observe from the five documented command\n * hooks. Only PreToolUse/PostToolUse carry a lifecycle fact the canonical\n * model can represent without inventing anything: PreInvocation,\n * PostInvocation, and Stop expose invocation/execution bookkeeping, not a\n * session or generation identity (no `modelId`, no genuine start/end\n * signal), so none of them produce an event — see `parse()` below and\n * `./maturity.ts` for what would need to change that.\n */\nexport const ANTIGRAVITY_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\"tool.start\", \"tool.end\"] as const),\n usageTemporality: \"delta\",\n reportsCachedInput: false,\n reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\n reportsReasoningOutput: false,\n reportsProviderTotal: false,\n reportsCost: false,\n emitsSubagentEvents: false,\n emitsCompactionEvents: false,\n requiresHookResponse: false,\n // Only the tool pair carries a replay-stable id, and only from the two\n // verified counters. See `./delivery.ts` for which and why.\n deliveryIdentifier: \"partial\",\n});\n\nexport type AntigravityAdapterOptions = {\n readonly id?: string;\n readonly version?: string;\n};\n\n/**\n * Experimental Google Antigravity adapter.\n *\n * Maps the five documented camelCase command hooks onto canonical events\n * conservatively: fields the hooks do not expose (model identifiers, usage,\n * a genuine session start/end signal) are never fabricated. PreInvocation,\n * PostInvocation, and Stop report invocation and execution-completion\n * bookkeeping only — none of it converts to a canonical event without\n * inventing a session or generation identity, so all three are ignored with\n * a diagnostic reason. See ADR 0003 for the adapter contract this implements\n * and `./maturity.ts` for what would need to be verified before this leaves\n * `experimental`.\n */\nexport const createAntigravityAdapter = (\n options: AntigravityAdapterOptions = {},\n): ProviderAdapter => {\n const id: ProviderId = providerIdSchema.parse(options.id ?? ANTIGRAVITY_PROVIDER_ID);\n const version = options.version ?? \"0.1.0\";\n\n const detect = (input: ProviderDetectionInput): ProviderDetection => {\n const full = antigravityHookPayloadSchema.safeParse(input.payload);\n if (full.success) {\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"exact\",\n reasons: [`payload matches the documented antigravity ${full.data.hookEventName} hook shape`],\n sourceEventName: full.data.hookEventName,\n });\n }\n const weak = antigravityWeakShapeSchema.safeParse(input.payload);\n if (weak.success) {\n return providerDetectionSchema.parse({\n providerId: id,\n confidence: \"weak\",\n reasons: [\n `payload.hookEventName=${weak.data.hookEventName} matches antigravity but required fields are missing or invalid`,\n ],\n sourceEventName: weak.data.hookEventName,\n });\n }\n return unknownDetection([\"payload does not match any documented antigravity hook shape\"]);\n };\n\n const identify = (input: ProviderIdentityInput, context: ProviderContext): readonly IdentityClaim[] => {\n const parsed = antigravityHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return [];\n }\n const payload = parsed.data;\n const sessionId = sessionIdSchema.parse(payload.conversationId);\n // occurredAt is pinned to a constant: the seed is a hash namespace, not a\n // claimed timestamp, and invocationNum is what must stay stable across the\n // separate Pre/Post hook processes that share one Antigravity invocation.\n const invocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId,\n occurredAt: 0,\n discriminator: String(payload.invocationNum),\n });\n const [firstWorkspacePath] = payload.workspacePaths;\n const workspace =\n firstWorkspacePath === undefined\n ? unknownWorkspaceIdentity()\n : deriveWorkspaceIdentity(context.privacy, {\n kind: \"working-directory\",\n absolutePath: firstWorkspacePath,\n });\n\n return [\n identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: { sessionId, invocationId, workspace },\n }),\n ];\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n const parsed = antigravityHookPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the documented antigravity hook contract\",\n }),\n };\n }\n const payload = parsed.data;\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n\n switch (payload.hookEventName) {\n case \"PreInvocation\":\n return {\n status: \"ignored\",\n reason:\n \"PreInvocation reports invocation bookkeeping only; it carries no modelId or usage, so it cannot \" +\n \"become a generation fact, and it is not a genuine session-start signal Antigravity documents\",\n };\n case \"PostInvocation\":\n return {\n status: \"ignored\",\n reason:\n \"PostInvocation reports invocation bookkeeping only; it carries no modelId, usage, or outcome that \" +\n \"the canonical model can represent without inventing a generation fact\",\n };\n case \"PreToolUse\": {\n const toolCallId = context.ids.newOpaqueId([\n payload.conversationId,\n \"step\",\n String(payload.stepIdx),\n ]);\n const toolKind = payload.toolName === ANTIGRAVITY_SUBAGENT_TOOL_NAME ? \"delegate\" : \"unknown\";\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName: payload.toolName,\n toolKind,\n ...(payload.toolInput === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.toolInput,\n label: payload.toolName,\n }),\n }),\n });\n break;\n }\n case \"PostToolUse\": {\n const toolCallId = context.ids.newOpaqueId([\n payload.conversationId,\n \"step\",\n String(payload.stepIdx),\n ]);\n const outcome = payload.isError === true ? \"error\" : payload.isError === false ? \"ok\" : \"unknown\";\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName: payload.toolName,\n outcome,\n ...(payload.toolResponse === undefined\n ? {}\n : {\n output: context.privacy.describeStructured({\n kind: \"tool-output\",\n value: payload.toolResponse,\n label: payload.toolName,\n }),\n }),\n });\n break;\n }\n case \"Stop\":\n return {\n status: \"ignored\",\n reason: payload.fullyIdle\n ? \"Stop signals execution/turn completion (fullyIdle=true) but exposes no session or generation \" +\n \"identity, so it cannot become session.end or generation.end without inventing one\"\n : \"Stop received while the agent is not fully idle; the conversation continues and the hook exposes \" +\n \"no lifecycle fact the canonical model can represent\",\n };\n }\n\n return { status: \"parsed\", events: factory.events() };\n };\n\n const hookResponse = (): ProviderHookResponse => SILENT_HOOK_RESPONSE;\n\n return {\n id,\n version,\n capabilities: ANTIGRAVITY_CAPABILITIES,\n detect,\n identify,\n deliveryIdentity: antigravityDeliveryIdentity,\n deliveryGaps: ANTIGRAVITY_DELIVERY_GAPS,\n parse,\n hookResponse,\n };\n};\n","/**\n * Maturity of the Antigravity provider adapter.\n *\n * `experimental` means: the five hook names and the six field names this\n * adapter treats as verified (`conversationId`, `workspacePaths`, `stepIdx`,\n * `invocationNum`, `transcriptPath`, `artifactDirectoryPath`) came from the\n * integration task, not from a captured transcript this package has seen.\n * Every other field (`toolName`, `toolInput`, `toolResponse`, `isError`,\n * `fullyIdle`, `agentVersion`) and every mapping decision below is a\n * conservative reconstruction pending confirmation.\n */\nexport const ANTIGRAVITY_PROVIDER_MATURITY = \"experimental\" as const;\nexport type AntigravityProviderMaturity = typeof ANTIGRAVITY_PROVIDER_MATURITY;\n\n/**\n * What must be verified against real Antigravity hook captures before this\n * adapter can be promoted past `experimental`:\n *\n * 1. Whether `PreInvocation`/`PostInvocation` ever expose a model identifier\n * or usage figures. If they do, promote from the current ignored handling\n * to `generation.start`/`generation.end` — this adapter deliberately does\n * not fabricate a `modelId` to unlock that today, and does not treat\n * `invocationNum === 0` as a session-start signal: Antigravity documents\n * no such hook, and a genuine session-start fact requires more than an\n * invocation counter reaching zero.\n * 2. Whether Antigravity documents any hook that reports a real session or\n * conversation start/end (as opposed to per-invocation bookkeeping). If\n * one exists, add `session.start`/`session.end` handling for it instead of\n * inferring boundaries from `PreInvocation`/`Stop`.\n * 3. Whether `Stop` (or another hook) ever exposes enough to honestly close\n * out a `generation.end` — a model identifier, an outcome, or a\n * generation id correlating it to a prior invocation. Today `Stop` is\n * ignored regardless of `fullyIdle`, because turn/execution completion\n * alone does not map to any canonical event without inventing one.\n * 4. Whether Antigravity reports its own tool-call identifier. This adapter\n * derives `toolCallId` from `conversationId` + `stepIdx`; a native id\n * would be strictly more precise and should replace the derived one.\n * 5. Whether `invoke_subagent` warrants a dedicated subagent lifecycle\n * (`subagent.start`/`subagent.end` with parent/child invocation identity)\n * instead of being modeled as an ordinary delegated tool call.\n * 6. Whether `PostToolUse.isError` is really optional or always present.\n * 7. A captured, redacted end-to-end transcript replayed through this\n * adapter with zero `schema-validation-failed` or `privacy-policy-violation`\n * diagnostics.\n */\nexport const ANTIGRAVITY_PROMOTION_GATES: readonly string[] = Object.freeze([\n \"confirm whether PreInvocation/PostInvocation ever expose modelId or usage\",\n \"confirm whether any hook documents a genuine session/conversation start or end\",\n \"confirm whether Stop or another hook can honestly close out a generation.end\",\n \"confirm whether Antigravity reports a native tool-call identifier\",\n \"confirm whether invoke_subagent should have a dedicated subagent lifecycle\",\n \"confirm PostToolUse.isError against real payloads\",\n \"replay a captured, redacted transcript with zero validation/privacy diagnostics\",\n]);\n","import { ANTIGRAVITY_PROVIDER_ID, createAntigravityAdapter } from \"./antigravity/adapter.js\";\nimport { ANTIGRAVITY_PROMOTION_GATES, ANTIGRAVITY_PROVIDER_MATURITY } from \"./antigravity/maturity.js\";\nimport { createClaudeCodeAdapter } from \"./claude/adapter.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"./claude/detect.js\";\nimport { createCodexAdapter } from \"./codex/adapter.js\";\nimport { CODEX_PROVIDER_ID } from \"./codex/version.js\";\nimport { createCursorAdapter } from \"./cursor/adapter.js\";\nimport { CURSOR_PROVIDER_ID } from \"./cursor/payload.js\";\nimport { createGeminiCliAdapter, GEMINI_PROVIDER_ID } from \"./gemini/adapter.js\";\nimport {\n describeAdapter,\n type AdapterDescription,\n type DeliveryIdentifierSupport,\n type ProviderAdapter,\n} from \"./adapter.js\";\nimport { createProviderRegistry, type ProviderRegistry } from \"./registry.js\";\n\n/**\n * How much of a provider adapter's behaviour is confirmed against the real\n * provider.\n *\n * `experimental` is not a quality grade — it states that some of the adapter's\n * field and lifecycle mapping is a reconstruction pending confirmation against\n * real captures. Consumers are expected to be able to see this before they\n * depend on the data, so it is part of the descriptor rather than a comment.\n */\nexport type ProviderMaturity = \"stable\" | \"experimental\";\n\nexport type ProviderDescriptor = {\n readonly id: string;\n readonly maturity: ProviderMaturity;\n /** Human-readable name of the coding agent this adapter targets. */\n readonly title: string;\n /** Constructs a fresh adapter instance. Adapters are values, never singletons. */\n readonly createAdapter: () => ProviderAdapter;\n /**\n * For an `experimental` adapter: what must be verified before promotion.\n * Empty for a `stable` one.\n */\n readonly promotionGates: readonly string[];\n};\n\n/**\n * Every provider adapter this package ships, with its maturity.\n *\n * Ordering is stable and alphabetical by id so `otel-hook providers` output and\n * detection candidate lists are reproducible.\n */\nexport const PROVIDER_DESCRIPTORS: readonly ProviderDescriptor[] = Object.freeze([\n Object.freeze({\n id: ANTIGRAVITY_PROVIDER_ID,\n maturity: ANTIGRAVITY_PROVIDER_MATURITY,\n title: \"Google Antigravity (experimental)\",\n createAdapter: (): ProviderAdapter => createAntigravityAdapter(),\n promotionGates: ANTIGRAVITY_PROMOTION_GATES,\n }),\n Object.freeze({\n id: CLAUDE_CODE_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"Claude Code\",\n createAdapter: (): ProviderAdapter => createClaudeCodeAdapter(),\n promotionGates: Object.freeze([]),\n }),\n Object.freeze({\n id: CODEX_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"OpenAI Codex CLI\",\n createAdapter: (): ProviderAdapter => createCodexAdapter(),\n promotionGates: Object.freeze([]),\n }),\n Object.freeze({\n id: CURSOR_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"Cursor\",\n createAdapter: (): ProviderAdapter => createCursorAdapter(),\n promotionGates: Object.freeze([]),\n }),\n Object.freeze({\n id: GEMINI_PROVIDER_ID,\n maturity: \"stable\" as const,\n title: \"Gemini CLI\",\n createAdapter: (): ProviderAdapter => createGeminiCliAdapter(),\n promotionGates: Object.freeze([]),\n }),\n]);\n\n/** Ids of the adapters whose mapping is still a reconstruction. */\nexport const EXPERIMENTAL_PROVIDER_IDS: readonly string[] = Object.freeze(\n PROVIDER_DESCRIPTORS.filter((descriptor) => descriptor.maturity === \"experimental\").map(\n (descriptor) => descriptor.id,\n ),\n);\n\nexport const findProviderDescriptor = (id: string): ProviderDescriptor | undefined =>\n PROVIDER_DESCRIPTORS.find((descriptor) => descriptor.id === id);\n\nexport const isExperimentalProvider = (id: string): boolean =>\n findProviderDescriptor(id)?.maturity === \"experimental\";\n\nexport type DefaultRegistryOptions = {\n /**\n * Include adapters marked `experimental`. Default `true`: an experimental\n * adapter is registered but visibly labelled, so a host that wants only\n * confirmed mappings opts out explicitly rather than discovering the\n * distinction from telemetry that looks the same as the rest.\n */\n readonly includeExperimental?: boolean;\n /** Restrict to these provider ids, in descriptor order. Empty means \"all\". */\n readonly only?: readonly string[];\n /** Extra adapters — a host's own provider — appended after the built-ins. */\n readonly additional?: readonly ProviderAdapter[];\n};\n\n/**\n * Build a registry over this package's provider adapters.\n *\n * A factory rather than a shared constant: a registry is a value the runtime is\n * given, and two hooks in one process may legitimately be configured with\n * different adapter sets (see `createProviderRegistry`'s note and ADR 0001).\n */\nexport const createDefaultProviderRegistry = (\n options: DefaultRegistryOptions = {},\n): ProviderRegistry => {\n const includeExperimental = options.includeExperimental ?? true;\n const only = options.only ?? [];\n const selected = PROVIDER_DESCRIPTORS.filter((descriptor) => {\n if (only.length > 0 && !only.includes(descriptor.id)) {\n return false;\n }\n return includeExperimental || descriptor.maturity !== \"experimental\";\n });\n return createProviderRegistry([\n ...selected.map((descriptor) => descriptor.createAdapter()),\n ...(options.additional ?? []),\n ]);\n};\n\nexport type ProviderCatalogEntry = AdapterDescription & {\n readonly maturity: ProviderMaturity;\n readonly title: string;\n readonly promotionGates: readonly string[];\n /** True when the provider's protocol reads a structured response from stdout. */\n readonly requiresHookResponse: boolean;\n /**\n * Which series this provider's `cumulative` counters accumulate over, so a\n * consumer summing deltas knows whether a per-turn snapshot is a per-turn\n * figure or a session-wide one. Absent for `delta` providers.\n */\n readonly cumulativeUsageSeries?: string;\n readonly reportsCachedInput: boolean;\n readonly reportsCacheCreation: boolean;\n readonly cacheCreationAccounting: string;\n readonly reportsReasoningOutput: boolean;\n readonly reportsProviderTotal: boolean;\n readonly reportsCost: boolean;\n readonly emitsSubagentEvents: boolean;\n readonly emitsCompactionEvents: boolean;\n};\n\n/** How each adapter's declared delivery-identifier coverage reads to a human. */\nexport const DELIVERY_IDENTIFIER_SUMMARY: Readonly<Record<DeliveryIdentifierSupport, string>> =\n Object.freeze({\n none: \"no callback carries a replay-stable identifier\",\n partial: \"some callbacks carry a replay-stable identifier\",\n all: \"every recognized callback carries a replay-stable identifier\",\n });\n\n/**\n * Machine-readable capability catalog, for `otel-hook providers --json` and for\n * consumers deciding whether a metric is absent or merely unreported.\n */\nexport const describeProviderCatalog = (\n options: DefaultRegistryOptions = {},\n): readonly ProviderCatalogEntry[] => {\n const includeExperimental = options.includeExperimental ?? true;\n const only = options.only ?? [];\n const entries: ProviderCatalogEntry[] = [];\n for (const descriptor of PROVIDER_DESCRIPTORS) {\n if (only.length > 0 && !only.includes(descriptor.id)) {\n continue;\n }\n if (!includeExperimental && descriptor.maturity === \"experimental\") {\n continue;\n }\n const adapter = descriptor.createAdapter();\n const { capabilities } = adapter;\n entries.push({\n ...describeAdapter(adapter),\n maturity: descriptor.maturity,\n title: descriptor.title,\n promotionGates: [...descriptor.promotionGates],\n requiresHookResponse: capabilities.requiresHookResponse,\n ...(capabilities.cumulativeUsageSeries === undefined\n ? {}\n : { cumulativeUsageSeries: capabilities.cumulativeUsageSeries }),\n reportsCachedInput: capabilities.reportsCachedInput,\n reportsCacheCreation: capabilities.reportsCacheCreation,\n cacheCreationAccounting: capabilities.cacheCreationAccounting,\n reportsReasoningOutput: capabilities.reportsReasoningOutput,\n reportsProviderTotal: capabilities.reportsProviderTotal,\n reportsCost: capabilities.reportsCost,\n emitsSubagentEvents: capabilities.emitsSubagentEvents,\n emitsCompactionEvents: capabilities.emitsCompactionEvents,\n });\n }\n return entries;\n};\n","import { epochMillisSchema, type EpochMillis } from \"../model/primitives.js\";\nimport type { Clock } from \"./ports.js\";\n\n/** Clock backed by the host process. */\nexport const createSystemClock = (): Clock => ({\n now: (): EpochMillis => epochMillisSchema.parse(Date.now()),\n monotonicMillis: (): number => Number(process.hrtime.bigint() / 1_000_000n),\n});\n\nexport type FixedClockOptions = {\n readonly startMillis?: number;\n /** Milliseconds added to the wall clock on each `now()` call. */\n readonly tickMillis?: number;\n};\n\n/**\n * Deterministic clock for tests.\n *\n * `advance` moves both readings together so duration arithmetic stays coherent.\n */\nexport interface FixedClock extends Clock {\n advance(millis: number): void;\n set(millis: number): void;\n}\n\nexport const createFixedClock = (options: FixedClockOptions = {}): FixedClock => {\n let wall = options.startMillis ?? 1_700_000_000_000;\n let monotonic = 0;\n const tick = options.tickMillis ?? 0;\n\n return {\n now: (): EpochMillis => {\n const current = wall;\n wall += tick;\n monotonic += tick;\n return epochMillisSchema.parse(current);\n },\n monotonicMillis: (): number => monotonic,\n advance: (millis: number): void => {\n wall += millis;\n monotonic += millis;\n },\n set: (millis: number): void => {\n wall = millis;\n },\n };\n};\n","import { z } from \"zod\";\n\nimport { DEFAULT_CONFIG, type OtelHookConfig } from \"../config/schema.js\";\nimport {\n createErrorInfo,\n errorInfoFromThrown,\n type AttributionOutcome,\n type AttributionReason,\n type OtelHookErrorInfo,\n} from \"../errors/index.js\";\nimport {\n isContentFactConsistent,\n isUnavailableContentFact,\n type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent, ModelDescriptor } from \"../model/events.js\";\nimport {\n resolveInvocationIdentity,\n sourceProvenanceSchema,\n unknownWorkspaceIdentity,\n type IdentityClaim,\n type InvocationIdentity,\n type WorkspaceIdentity,\n} from \"../model/identity.js\";\nimport {\n type DetectionConfidence,\n type EventId,\n type ResolvedProviderId,\n type SourceTransport,\n} from \"../model/primitives.js\";\nimport {\n cumulativeToDelta,\n normalizeUsage,\n toReport,\n type CanonicalUsage,\n type UsageTemporality,\n} from \"../model/usage.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport { CONTENT_MODE_DISCLOSURE } from \"../privacy/policy.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport {\n readDeliveryClaim,\n readDeliveryGap,\n SILENT_HOOK_RESPONSE,\n type ProviderAdapter,\n type ProviderContext,\n type ProviderDetection,\n type ProviderHookResponse,\n} from \"../providers/adapter.js\";\nimport { createProviderRegistry, BUILT_IN_PROVIDERS, type ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"./clock.js\";\nimport { resolveDeliveryIdentity, type DeliveryResolution } from \"./delivery.js\";\nimport { createDeterministicIdGenerator } from \"./ids.js\";\nimport { createNullLogger } from \"./logger.js\";\nimport type {\n Clock,\n IdGenerator,\n Logger,\n PayloadEnricher,\n ReadCursor,\n SessionContextReader,\n StateStore,\n TelemetrySink,\n WorktreeLocator,\n} from \"./ports.js\";\nimport type { TargetHint } from \"../model/target.js\";\nimport {\n DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,\n resolveEventTargets,\n} from \"./target-resolution.js\";\nimport { isStateLockContention, withOptionalSessionLock } from \"../state/store.js\";\nimport { stampSessionContext } from \"./session-context.js\";\n\nexport const usageScopeSchema = z.enum([\"session\", \"generation\", \"subagent\"]);\nexport type UsageScope = z.infer<typeof usageScopeSchema>;\n\n/**\n * Which series a provider's cumulative counters accumulate over. Mirrors\n * `ProviderCapabilities.cumulativeUsageSeries`, defaulting to `event-scope`\n * for the adapters that do not declare one.\n */\nexport type CumulativeUsageSeries = \"event-scope\" | \"session-lifetime\";\n\n/**\n * Delta usage derived for one event.\n *\n * Events keep whatever the provider reported. Deltas are produced alongside them\n * rather than rewritten into them, so a cumulative report and its derived delta\n * are both auditable.\n */\nexport type UsageObservation = {\n readonly eventId: EventId;\n readonly sequence: number;\n readonly scope: UsageScope;\n readonly scopeKey: string;\n readonly reportedTemporality: UsageTemporality;\n readonly delta: CanonicalUsage;\n /** True when the cumulative series restarted; see `cumulativeToDelta`. */\n readonly resetDetected: boolean;\n};\n\nexport type HookIngestInput = {\n /** Decoded provider payload. Only the selected adapter interprets it. */\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment?: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n /** Caller-supplied identity claims, arbitrated with the adapter's claims. */\n readonly identityClaims?: readonly IdentityClaim[];\n /** Opaque consumer metadata; sanitized, then carried through unchanged. */\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n readonly workspace?: WorkspaceIdentity;\n};\n\n/**\n * The terminal fate of one callback's telemetry, and the only thing a caller\n * should base a commit-or-retry decision on.\n *\n * The distinction that matters is **any** versus **all**, not success versus\n * failure. A batch is chunked before export, so it can be part accepted and part\n * refused — and once a single span has reached a collector or the spool, retrying\n * the callback would re-export that span. So a partial result is *terminal*: the\n * callback is committed, the loss is reported, and nothing is retried. Only a\n * result where nothing at all survived is safe to retry, precisely because there\n * is nothing to duplicate.\n */\nexport type DeliveryDurability =\n /** Suppressed, or no events to export. There is nothing to lose or retry. */\n | \"nothing-to-deliver\"\n /** Every span reached the collector or the spool. */\n | \"delivered\"\n /**\n * Some spans survived and some did not. Terminal: committing loses the refused\n * spans, retrying duplicates the accepted ones, and duplicating an accepted\n * span silently corrupts a total while a reported loss can be acted on.\n */\n | \"partial\"\n /** Nothing survived, so a retry cannot duplicate anything. */\n | \"lost\";\n\nexport const classifyDurability = (input: {\n readonly attempted: boolean;\n readonly accepted: number;\n readonly rejected: number;\n}): DeliveryDurability => {\n if (!input.attempted) {\n return \"nothing-to-deliver\";\n }\n if (input.rejected === 0) {\n return input.accepted === 0 ? \"nothing-to-deliver\" : \"delivered\";\n }\n return input.accepted === 0 ? \"lost\" : \"partial\";\n};\n\n/** Whether this fate permits committing the callback and its accounting. */\nexport const isCommittable = (durability: DeliveryDurability): boolean =>\n durability !== \"lost\";\n\nexport type HookIngestOutcome = {\n /**\n * Always `true`. The hook cannot fail the host agent; look at `attribution`\n * and `diagnostics` to see what actually happened (ADR 0004).\n */\n readonly ok: true;\n readonly attribution: AttributionOutcome;\n readonly attributionReason?: AttributionReason;\n readonly providerId: ResolvedProviderId;\n readonly detectionConfidence: DetectionConfidence;\n readonly identity?: InvocationIdentity;\n readonly events: readonly CanonicalEvent[];\n readonly usageObservations: readonly UsageObservation[];\n /**\n * OTLP records the sink accepted, summed over every wired signal.\n *\n * A count of *records*, never of canonical events: two edges of one lifecycle\n * scope produce one span, and one event carrying three content facts produces\n * three log records. With the logs signal enabled a batch therefore reports both\n * signals' records here — which is what makes {@link durability} correct across\n * them, and why nothing should read this as \"how many events were observed\".\n */\n readonly emitted: number;\n /**\n * Records the sink could neither export nor durably spool.\n *\n * The distinction `emitted` cannot make: a successful spool enqueue counts as\n * emitted, because the batch is safe on disk and a later invocation will retry\n * it. A non-zero value here means those observations are **gone** unless the\n * callback is delivered again — which is what lets a caller decide whether a\n * delivery claim may be committed or has to be released for retry.\n */\n readonly exportRejected: number;\n /**\n * The terminal fate of this callback's telemetry.\n *\n * The field a caller should branch on. `emitted` and `exportRejected` are the\n * raw counts behind it; this is the decision they add up to, computed in one\n * place so a caller cannot get the any-versus-all boundary wrong.\n */\n readonly durability: DeliveryDurability;\n readonly dropped: number;\n readonly hookResponse: ProviderHookResponse;\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type HookIngestOptions = {\n /**\n * Parse and answer the provider, but export nothing and mutate no canonical\n * state.\n *\n * For a callback that deduplication has already identified as a redelivery.\n * The adapter still runs, so the provider's protocol response comes from a real\n * parse of the real payload rather than a guess — but the session sequence\n * counter is not advanced and no cumulative usage baseline is rewritten,\n * because both are *canonical state* and a redelivery is by definition not a\n * new observation. Advancing the sequence would renumber every later event in\n * the session and change its derived event id, which is exactly the\n * replay-stability the dedup guard exists to protect.\n */\n readonly suppress?: boolean;\n};\n\n/** Public runtime surface. */\nexport interface OtelHook {\n /**\n * Report the replay-stable delivery identity of an input without ingesting it.\n *\n * Synchronous, side-effect free, and never throws. It exists as a separate\n * step because deduplication has to decide *before* anything is exported or\n * accounted, and `ingest` exports as part of its own work — a caller that\n * learned the identity afterwards could only ever suppress a duplicate it had\n * already sent. Only `detect` and `deliveryIdentity` run here; the payload is\n * never parsed.\n */\n resolveDelivery(input: HookIngestInput): DeliveryResolution;\n /** Process one provider observation. Never throws, never rejects. */\n ingest(input: HookIngestInput, options?: HookIngestOptions): Promise<HookIngestOutcome>;\n /** Best-effort delivery of buffered telemetry. Never throws. */\n flush(): Promise<void>;\n /** Flush, then release resources. Never throws; idempotent. */\n shutdown(): Promise<void>;\n /** Resolved configuration in force. Read-only. */\n readonly config: OtelHookConfig;\n}\n\nexport type OtelHookDependencies = {\n readonly sink: TelemetrySink;\n readonly stateStore: StateStore;\n readonly config?: OtelHookConfig;\n readonly registry?: ProviderRegistry;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n /** Overrides `config.privacy` when supplied; must already be configured. */\n readonly privacy?: PrivacyService;\n readonly logger?: Logger;\n /**\n * Namespace separating one deployment's derived delivery identities from\n * another's. Not identity: it never reaches an event, and no session or\n * workspace is derived from it. Defaults to `\"default\"`.\n */\n readonly installationId?: string;\n /**\n * Resolves tool events' target hints to the git worktree they touched\n * (ADR 0008). Absent means no resolution: events carry no `target`. The\n * filesystem implementation is `createFilesystemWorktreeLocator`.\n */\n readonly worktreeLocator?: WorktreeLocator;\n /** Ceiling on target resolution per callback. Default 50ms. */\n readonly targetResolutionBudgetMillis?: number;\n /**\n * Host-configured payload enrichers (see {@link PayloadEnricher}). Empty by\n * default: nothing reads beyond the payload unless a host asks for it.\n */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /**\n * Reads the session context a harness wrote (`docs/session-context.md`). Absent\n * means none: no event carries `contextAttributes`. The filesystem\n * implementation is `createDirectorySessionContextReader`.\n */\n readonly sessionContext?: SessionContextReader;\n};\n\nconst MAX_ERROR_EVENTS = 8;\n\nconst collectContentFacts = (event: CanonicalEvent): readonly ContentFact[] => {\n const facts: ContentFact[] = [];\n const push = (fact: ContentFact | undefined): void => {\n if (fact !== undefined) {\n facts.push(fact);\n }\n };\n switch (event.type) {\n case \"prompt.submitted\":\n push(event.content);\n break;\n case \"generation.start\":\n facts.push(...(event.inputContent ?? []));\n break;\n case \"generation.end\":\n facts.push(...(event.outputContent ?? []));\n break;\n case \"tool.start\":\n push(event.input);\n break;\n case \"tool.end\":\n push(event.output);\n break;\n case \"error.raised\":\n push(event.message);\n break;\n default:\n break;\n }\n return facts;\n};\n\nconst usageScopeOf = (\n event: CanonicalEvent,\n): { readonly scope: UsageScope; readonly scopeKey: string; readonly usage: CanonicalUsage } | undefined => {\n switch (event.type) {\n case \"session.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"compaction.performed\":\n return event.usage === undefined\n ? undefined\n : { scope: \"session\", scopeKey: event.sessionId, usage: event.usage };\n case \"generation.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"generation\", scopeKey: event.generationId, usage: event.usage };\n case \"subagent.end\":\n return event.usage === undefined\n ? undefined\n : { scope: \"subagent\", scopeKey: event.subagentInvocationId, usage: event.usage };\n default:\n return undefined;\n }\n};\n\nconst sequenceKey = (sessionId: string): string => `sequence:${sessionId}`;\nconst sessionModelKey = (sessionId: string): string => `model:${sessionId}`;\nconst readCursorKey = (enricherId: string, sessionId: string, scope: string | undefined): string =>\n scope === undefined ? `cursor:${enricherId}:${sessionId}` : `cursor:${enricherId}:${sessionId}:${scope}`;\n\n/**\n * The placeholder an adapter uses when its payload names no model. Never\n * remembered: storing it would overwrite a real model the session reported.\n */\nconst UNKNOWN_MODEL_ID = \"unknown\";\n\n/**\n * The last model a batch reports for the top-level agent, if any.\n *\n * `session.start` and `generation.*` edges count; a subagent's events do not,\n * because a subagent can run on a different model than the session it serves and\n * must not rename the session's own generations. The last such event wins, so a\n * turn that reports a model switch updates what the session remembers.\n */\nconst latestSessionModel = (events: readonly CanonicalEvent[]): ModelDescriptor | undefined => {\n let latest: ModelDescriptor | undefined;\n for (const event of events) {\n if (event.subagentId !== undefined) {\n continue;\n }\n if (\n (event.type === \"session.start\" || event.type === \"generation.start\" || event.type === \"generation.end\") &&\n event.model !== undefined &&\n event.model.modelId !== UNKNOWN_MODEL_ID\n ) {\n latest = event.model;\n }\n }\n return latest;\n};\n\nconst sameModel = (left: ModelDescriptor | undefined, right: ModelDescriptor): boolean =>\n left !== undefined &&\n left.modelId === right.modelId &&\n left.vendor === right.vendor &&\n left.family === right.family;\nconst usageKey = (sessionId: string, scope: UsageScope, scopeKey: string): string =>\n `usage:${sessionId}:${scope}:${scopeKey}`;\n\n/**\n * Where the cumulative baseline for an observation is stored.\n *\n * This is deliberately *not* the same thing as the observation's own scope. The\n * derived delta belongs to the event that reported it — a turn's token spend is\n * attributed to that turn — but the snapshot it must be diffed against belongs\n * to whichever series the provider is actually accumulating.\n *\n * For a `session-lifetime` provider (Codex: every hook carries the session-wide\n * `total_token_usage`), keying the baseline by `generationId` would mean every\n * turn's snapshot found no predecessor and was emitted whole, billing the entire\n * session again on each turn. Redirecting `generation` to the session series\n * makes successive turns diff against each other.\n */\nconst baselineScopeOf = (\n scope: UsageScope,\n scopeKey: string,\n sessionId: string,\n series: CumulativeUsageSeries,\n): { readonly scope: UsageScope; readonly scopeKey: string } =>\n series === \"session-lifetime\" && scope === \"generation\"\n ? { scope: \"session\", scopeKey: sessionId }\n : { scope, scopeKey };\n\n/**\n * Minimal orchestrator wiring detection, identity, parsing, privacy checks,\n * usage derivation, and export.\n *\n * Every step is contained: a throwing adapter, an unavailable state store, or a\n * rejecting sink degrades the telemetry, never the host agent.\n */\nexport const createOtelHook = (deps: OtelHookDependencies): OtelHook => {\n const config = deps.config ?? DEFAULT_CONFIG;\n const registry = deps.registry ?? createProviderRegistry(BUILT_IN_PROVIDERS);\n const clock = deps.clock ?? createSystemClock();\n const ids = deps.ids ?? createDeterministicIdGenerator();\n const privacy = deps.privacy ?? createPrivacyService(config.privacy);\n const logger = deps.logger ?? createNullLogger();\n const installationId = deps.installationId ?? \"default\";\n const limits = privacy.policy.limits;\n const expectedDisclosure = CONTENT_MODE_DISCLOSURE[privacy.policy.contentMode];\n\n const providerContext: ProviderContext = { privacy, clock, ids, logger, limits };\n let shutdownCompleted = false;\n\n const hookResponseFor = (\n adapter: ProviderAdapter | undefined,\n detection: ProviderDetection | undefined,\n attribution: AttributionOutcome,\n attributionReason: AttributionReason | undefined,\n emittedEvents: number,\n errors: readonly OtelHookErrorInfo[],\n ): ProviderHookResponse => {\n if (adapter === undefined) {\n return SILENT_HOOK_RESPONSE;\n }\n try {\n return adapter.hookResponse(\n {\n attribution,\n ...(attributionReason === undefined ? {} : { attributionReason }),\n ...(detection === undefined ? {} : { detection }),\n emittedEvents,\n errors,\n },\n providerContext,\n );\n } catch {\n // A provider that cannot describe its own response gets the silent one.\n return SILENT_HOOK_RESPONSE;\n }\n };\n\n const readSequenceBase = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<number> => {\n try {\n const record = await deps.stateStore.read(sequenceKey(sessionId));\n if (record?.value.kind === \"sequence\") {\n return record.value.next;\n }\n return 0;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return 0;\n }\n };\n\n /**\n * Run the configured enrichers for this provider over the payload.\n *\n * Inside the session lock, so a cursor is read, advanced, and written by one\n * process at a time. Every failure is contained: a throwing enricher or an\n * unusable store leaves the payload as it was, and a cursor write that fails\n * is a diagnostic — the next read then starts from the old cursor, which can\n * count a turn into the next one but never twice.\n */\n const enrichPayload = async (\n payload: unknown,\n providerId: string,\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<unknown> => {\n let current = payload;\n for (const enricher of deps.payloadEnrichers ?? []) {\n if (enricher.providerId !== providerId) {\n continue;\n }\n let scope: string | undefined;\n try {\n scope = enricher.cursorScope?.(current);\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n const key = readCursorKey(enricher.id, sessionId, scope);\n let cursor: ReadCursor | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"read-cursor\") {\n cursor = { source: record.value.source, offset: record.value.offset };\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n // Without the stored cursor a read would start from the wrong place.\n continue;\n }\n let result;\n try {\n result = await enricher.enrich({ payload: current, sessionId, ...(cursor === undefined ? {} : { cursor }) });\n } catch (thrown) {\n logger.warn(\"payload enricher failed; parsing the payload as delivered\", {\n \"enricher.id\": enricher.id,\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n continue;\n }\n current = result.payload;\n if (result.notes !== undefined && result.notes.length > 0) {\n logger.debug(\"payload enricher notes\", {\n \"enricher.id\": enricher.id,\n \"enricher.notes\": result.notes.slice(0, 8).map((note) => note.slice(0, 200)),\n });\n }\n const next = result.cursor;\n if (next !== undefined && (next.source !== cursor?.source || next.offset !== cursor.offset)) {\n try {\n await deps.stateStore.write(key, { kind: \"read-cursor\", source: next.source, offset: next.offset });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n }\n }\n }\n return current;\n };\n\n /**\n * The model this session last reported, or `undefined`.\n *\n * Fails open: an unreadable store costs the model name, never the observation,\n * so a read failure is a diagnostic and the adapter falls back to `unknown`.\n */\n const readSessionModel = async (\n sessionId: string,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<ModelDescriptor | undefined> => {\n try {\n const record = await deps.stateStore.read(sessionModelKey(sessionId));\n return record?.value.kind === \"session-model\" ? record.value.model : undefined;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() }),\n );\n return undefined;\n }\n };\n\n /**\n * Derive per-event deltas, advancing the stored cumulative baseline.\n *\n * `suppress` makes this read-only: a redelivered callback must still be able to\n * report what it *would* have counted, but rewriting the baseline would make\n * the next genuine observation diff against the wrong snapshot and report a\n * zero — or negative — delta. Callers run this inside the session lock.\n */\n const deriveUsage = async (\n events: readonly CanonicalEvent[],\n diagnostics: OtelHookErrorInfo[],\n suppress: boolean,\n series: CumulativeUsageSeries,\n ): Promise<readonly UsageObservation[]> => {\n const observations: UsageObservation[] = [];\n for (const event of events) {\n const scoped = usageScopeOf(event);\n if (scoped === undefined) {\n continue;\n }\n if (scoped.usage.temporality === \"delta\") {\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"delta\",\n delta: scoped.usage,\n resetDetected: false,\n });\n continue;\n }\n\n const baselineScope = baselineScopeOf(scoped.scope, scoped.scopeKey, event.sessionId, series);\n const key = usageKey(event.sessionId, baselineScope.scope, baselineScope.scopeKey);\n let baseline: CanonicalUsage | undefined;\n try {\n const record = await deps.stateStore.read(key);\n if (record?.value.kind === \"usage-cumulative\") {\n baseline = record.value.usage;\n }\n } catch (thrown) {\n // Without a baseline the difference is unknowable. Emitting the raw\n // snapshot as a delta would double-count, so the observation is dropped.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n\n let delta: CanonicalUsage;\n let resetDetected = false;\n if (baseline === undefined) {\n const normalized = normalizeUsage({ ...toReport(scoped.usage), temporality: \"delta\" });\n if (normalized.status === \"invalid\") {\n diagnostics.push(\n createErrorInfo({\n code: \"usage-invalid\",\n phase: \"normalization\",\n detail: normalized.issues.map((issue) => issue.message).join(\"; \").slice(0, 400),\n details: { \"event.id\": event.eventId, \"usage.scope\": scoped.scope },\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n delta = normalized.usage;\n } else {\n try {\n const diffed = cumulativeToDelta(baseline, scoped.usage);\n delta = diffed.usage;\n resetDetected = diffed.resetDetected;\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n continue;\n }\n }\n\n try {\n if (!suppress) {\n await deps.stateStore.write(key, { kind: \"usage-cumulative\", usage: scoped.usage });\n }\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n observations.push({\n eventId: event.eventId,\n sequence: event.sequence,\n scope: scoped.scope,\n scopeKey: scoped.scopeKey,\n reportedTemporality: \"cumulative\",\n delta,\n resetDetected,\n });\n }\n return observations;\n };\n\n const screenEvents = (\n events: readonly CanonicalEvent[],\n identity: InvocationIdentity,\n sequenceBase: number,\n diagnostics: OtelHookErrorInfo[],\n ): { readonly kept: readonly CanonicalEvent[]; readonly dropped: number } => {\n const kept: CanonicalEvent[] = [];\n let dropped = 0;\n let expectedSequence = sequenceBase;\n\n for (const event of events) {\n const reject = (code: \"schema-validation-failed\" | \"privacy-policy-violation\" | \"limit-exceeded\", detail: string): void => {\n dropped += 1;\n diagnostics.push(\n createErrorInfo({\n code,\n phase: code === \"privacy-policy-violation\" ? \"privacy\" : \"parsing\",\n detail,\n details: { \"event.type\": event.type, \"event.sequence\": event.sequence },\n occurredAt: clock.now(),\n }),\n );\n };\n\n if (kept.length >= limits.maxEventsPerInvocation) {\n reject(\"limit-exceeded\", `event dropped: maxEventsPerInvocation=${limits.maxEventsPerInvocation}`);\n continue;\n }\n if (event.schemaVersion !== CANONICAL_SCHEMA_VERSION) {\n reject(\"schema-validation-failed\", \"event carries an unexpected schema version\");\n continue;\n }\n if (event.invocationId !== identity.invocationId || event.sessionId !== identity.sessionId) {\n // Fail closed: an adapter may only describe the invocation it was given.\n reject(\"schema-validation-failed\", \"event identity does not match the resolved invocation\");\n continue;\n }\n if (event.provenance.providerId !== identity.provenance.providerId) {\n reject(\"schema-validation-failed\", \"event provenance does not match the detected provider\");\n continue;\n }\n if (event.sequence !== expectedSequence) {\n reject(\n \"schema-validation-failed\",\n `event sequence ${event.sequence} is not consecutive from ${expectedSequence}`,\n );\n continue;\n }\n\n const facts = collectContentFacts(event);\n const offending = facts.find(\n (fact) =>\n !isUnavailableContentFact(fact) &&\n (fact.disclosure !== expectedDisclosure || !isContentFactConsistent(fact)),\n );\n if (offending !== undefined) {\n reject(\n \"privacy-policy-violation\",\n `content fact disclosure ${offending.disclosure} violates policy ${expectedDisclosure}`,\n );\n continue;\n }\n\n expectedSequence += 1;\n kept.push(event);\n }\n return { kept, dropped };\n };\n\n const detectionInputFor = (input: HookIngestInput): {\n readonly payload: unknown;\n readonly transport: SourceTransport;\n readonly environment: Readonly<Record<string, string | undefined>>;\n readonly providerHint?: string;\n } => ({\n payload: input.payload,\n transport: input.transport,\n environment: input.environment ?? {},\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n });\n\n const resolveDelivery = (input: HookIngestInput): DeliveryResolution => {\n let detected;\n try {\n detected = registry.detect(detectionInputFor(input), providerContext, config.detection);\n } catch {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n if (detected.status !== \"selected\") {\n return { status: \"unavailable\", reason: \"provider-unattributed\" };\n }\n\n const { adapter, detection } = detected;\n const capability = adapter.capabilities.deliveryIdentifier;\n // Named once, then reused: an unavailable resolution says *which* callback it\n // is talking about, because \"not identifiable\" without a callback name leaves\n // an operator auditing coverage nowhere to go.\n const named = {\n providerId: detection.providerId,\n capability,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n };\n const gap = readDeliveryGap(adapter, detection.sourceEventName);\n\n if (capability === \"none\") {\n return {\n status: \"unavailable\",\n reason: \"provider-declares-none\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n\n const read = readDeliveryClaim(adapter, { ...detectionInputFor(input), detection }, providerContext);\n if (read.rejection !== undefined) {\n return {\n status: \"unavailable\",\n reason: \"claim-rejected\",\n ...named,\n detail: read.rejection,\n };\n }\n if (read.claim === undefined) {\n return {\n status: \"unavailable\",\n reason: \"callback-not-identifiable\",\n ...named,\n ...(gap === undefined ? {} : { detail: gap }),\n };\n }\n return {\n status: \"resolved\",\n identity: resolveDeliveryIdentity({\n ids,\n providerId: detection.providerId,\n installationId,\n claim: read.claim,\n }),\n };\n };\n\n const ingest = async (\n input: HookIngestInput,\n ingestOptions?: HookIngestOptions,\n ): Promise<HookIngestOutcome> => {\n const suppress = ingestOptions?.suppress === true;\n const diagnostics: OtelHookErrorInfo[] = [];\n const environment = input.environment ?? {};\n const detectionInput = {\n payload: input.payload,\n transport: input.transport,\n environment,\n ...(input.providerHint === undefined ? {} : { providerHint: input.providerHint }),\n };\n\n try {\n const detected = registry.detect(detectionInput, providerContext, config.detection);\n diagnostics.push(...detected.errors);\n\n if (detected.status !== \"selected\") {\n const reason: AttributionReason =\n detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\";\n diagnostics.push(\n createErrorInfo({\n code: detected.status === \"ambiguous\" ? \"provider-detection-ambiguous\" : \"provider-unknown\",\n phase: \"detection\",\n detail: detected.detection.reasons.join(\"; \").slice(0, 400),\n details: { \"detection.candidates\": detected.candidates.length },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"provider not attributed\", {\n \"detection.status\": detected.status,\n \"detection.candidates\": detected.candidates.length,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: \"unknown\",\n detectionConfidence: detected.detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n\n const { adapter, detection } = detected;\n const provenance = sourceProvenanceSchema.parse({\n providerId: detection.providerId,\n ...(detection.providerVersion === undefined\n ? {}\n : { providerVersion: detection.providerVersion }),\n adapterId: adapter.id,\n adapterVersion: adapter.version,\n detectionConfidence: detection.confidence,\n ...(detection.sourceEventName === undefined\n ? {}\n : { sourceEventName: detection.sourceEventName }),\n transport: input.transport,\n });\n\n let adapterClaims: readonly IdentityClaim[] = [];\n try {\n adapterClaims = adapter.identify({ ...detectionInput, detection }, providerContext);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"identity\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n const resolution = resolveInvocationIdentity({\n claims: [...adapterClaims, ...(input.identityClaims ?? [])],\n provenance,\n fallback: {\n startedAt: clock.now(),\n workspace: input.workspace ?? unknownWorkspaceIdentity(),\n },\n consumerAttributes: privacy.sanitizeAttributes(input.consumerAttributes ?? {}),\n });\n\n if (resolution.status !== \"resolved\") {\n const reason: AttributionReason =\n resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\";\n const detail =\n resolution.status === \"conflict\"\n ? `conflicting fields: ${resolution.conflicts.map((conflict) => conflict.field).join(\", \")}`\n : resolution.status === \"incomplete\"\n ? `missing fields: ${resolution.missing.join(\", \")}`\n : `invalid claims: ${resolution.issues.join(\"; \")}`;\n diagnostics.push(\n createErrorInfo({\n code: resolution.status === \"conflict\" ? \"identity-conflict\" : \"identity-incomplete\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: { \"provider.id\": detection.providerId },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"attribution declined\", {\n \"identity.status\": resolution.status,\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"declined\",\n attributionReason: reason,\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"declined\", reason, 0, diagnostics),\n diagnostics,\n };\n }\n\n const identity = resolution.identity;\n\n /**\n * Result of the session-state critical section: either a finished outcome\n * (the adapter declined to produce events) or a batch ready to export.\n */\n type Prepared =\n | { readonly kind: \"early\"; readonly outcome: HookIngestOutcome }\n | {\n readonly kind: \"ready\";\n readonly batch: readonly CanonicalEvent[];\n readonly dropped: number;\n readonly targetHints?: ReadonlyMap<EventId, TargetHint>;\n };\n\n /**\n * Read this session's sequence, stamp a batch from it, derive usage against\n * the stored baselines, and commit the new sequence — as one unit.\n *\n * These are read-modify-write cycles on state shared by every process\n * handling the same session, and hook processes genuinely run concurrently\n * (a tool callback and a generation callback firing together). Unserialized,\n * two processes both read sequence *n*, both stamp events from *n*, and both\n * write *n + k*: the second batch reuses the first's sequence numbers, so\n * both derive the *same* event ids and a collector sees one event twice\n * while another is never numbered at all. The cumulative usage baseline\n * races the same way, and there the lost update is a wrong token delta\n * rather than a duplicate id.\n *\n * Export deliberately happens *after* this returns, outside the lock. Two\n * reasons, one correctness and one liveness: the span correlator takes this\n * same session lock from inside the sink, so exporting in here would be a\n * non-reentrant self-deadlock; and an unreachable collector must not hold a\n * session's state lock for the length of its timeout. Committing the\n * sequence before exporting means a failed export leaves a gap in the\n * numbering rather than a reused number — a gap is invisible to a\n * collector, a reused id is a corrupted trace.\n */\n const prepare = async (): Promise<Prepared> => {\n const sequenceBase = await readSequenceBase(identity.sessionId, diagnostics);\n const sessionModel = await readSessionModel(identity.sessionId, diagnostics);\n const payload = suppress\n ? detectionInput.payload\n : await enrichPayload(detectionInput.payload, detection.providerId, identity.sessionId, diagnostics);\n\n let parsed;\n try {\n parsed = adapter.parse(\n {\n ...detectionInput,\n payload,\n detection,\n identity,\n sequenceBase,\n ...(sessionModel === undefined ? {} : { sessionModel }),\n },\n providerContext,\n );\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"provider-adapter-failure\",\n phase: \"parsing\",\n occurredAt: clock.now(),\n });\n diagnostics.push(info);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"ignored\") {\n logger.debug(\"adapter ignored input\", {\n \"provider.id\": detection.providerId,\n \"adapter.reason\": parsed.reason.slice(0, 160),\n });\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"not-applicable\",\n attributionReason: \"adapter-ignored-input\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(\n adapter,\n detection,\n \"not-applicable\",\n \"adapter-ignored-input\",\n 0,\n diagnostics,\n ),\n diagnostics,\n },\n };\n }\n\n if (parsed.status === \"failed\") {\n diagnostics.push(parsed.error);\n return {\n kind: \"early\",\n outcome: {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"adapter-failure\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"adapter-failure\", 0, diagnostics),\n diagnostics,\n },\n };\n }\n\n if (parsed.warnings !== undefined && parsed.warnings.length > 0) {\n // An adapter reports a warning when it understood the payload but had to\n // decline part of it — a counter outside its declared capabilities, a\n // breakdown that disagrees with the total it itemizes. Not a diagnostic:\n // the observation is intact and nothing failed, so raising an error-severity\n // code would misreport a healthy invocation. But not nothing either, which\n // is what these were before: a harness whose attached field is being ignored\n // has no other way to find out.\n logger.warn(\"adapter declined part of the payload it understood\", {\n \"provider.id\": detection.providerId,\n \"adapter.warnings\": parsed.warnings.slice(0, 8).map((warning) => warning.slice(0, 200)),\n });\n }\n\n const screened = screenEvents(parsed.events, identity, sequenceBase, diagnostics);\n\n let batch: readonly CanonicalEvent[] = screened.kept;\n if (config.diagnostics.emitErrorEvents && diagnostics.length > 0) {\n batch = [...batch, ...buildErrorEvents(diagnostics, identity, sequenceBase + batch.length, ids, privacy)];\n }\n\n if (!suppress) {\n try {\n await deps.stateStore.write(sequenceKey(identity.sessionId), {\n kind: \"sequence\",\n next: sequenceBase + batch.length,\n });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n\n // Remember the session's model for the invocations whose payload names\n // none. Written only when it changed, so a session costs one record and\n // a steady session no extra writes; never written for a redelivery,\n // which is not a new observation.\n const reportedModel = latestSessionModel(screened.kept);\n if (reportedModel !== undefined && !sameModel(sessionModel, reportedModel)) {\n try {\n await deps.stateStore.write(sessionModelKey(identity.sessionId), {\n kind: \"session-model\",\n model: reportedModel,\n });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n }\n\n return {\n kind: \"ready\",\n batch,\n dropped: screened.dropped,\n ...(parsed.targetHints === undefined ? {} : { targetHints: parsed.targetHints }),\n };\n };\n\n let prepared: Prepared;\n try {\n prepared = await withOptionalSessionLock(deps.stateStore, identity.sessionId, prepare);\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n\n if (!isStateLockContention(thrown)) {\n // The store cannot lock because it cannot be used at all — an unwritable\n // directory, a full disk. There is no peer inside the critical section\n // and no state to lose an update to, so the lock protects nothing here\n // and fail-open wins: process unlocked and export. Each individual read\n // and write inside still degrades to its own diagnostic.\n logger.warn(\"state store unusable; processing without session serialization\", {\n \"provider.id\": detection.providerId,\n });\n prepared = await prepare();\n } else {\n // Genuine contention. Proceeding unlocked would reintroduce exactly the\n // interleaving the lock exists to prevent, so the observation is declined\n // and said out loud — the provider still gets its protocol response, and a\n // caller holding a delivery claim releases it, turning a lock collision\n // into a retry rather than a corrupted sequence.\n //\n // A contended acquisition *cancels* its queued critical section\n // (`AsyncLock.run`), so this is now a provable statement rather than a\n // hopeful one: nothing was read, reserved, or written, which is what makes\n // the retry safe rather than a second half-application.\n logger.warn(\"session state lock contended; observation declined for retry\", {\n \"provider.id\": detection.providerId,\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: [],\n usageObservations: [],\n emitted: 0,\n // Nothing was exported, nothing was reserved, and nothing is on disk,\n // so the caller must see this as a total loss and retry it.\n exportRejected: 1,\n durability: \"lost\",\n dropped: 0,\n hookResponse: hookResponseFor(adapter, detection, \"failed\", \"internal-error\", 0, diagnostics),\n diagnostics,\n };\n }\n }\n\n if (prepared.kind === \"early\") {\n return prepared.outcome;\n }\n const { dropped } = prepared;\n let batch = prepared.batch;\n\n // Outside the session lock on purpose: this is filesystem I/O, bounded by\n // its own budget, and must not lengthen the critical section peers wait on.\n if (\n !suppress &&\n deps.worktreeLocator !== undefined &&\n prepared.targetHints !== undefined &&\n prepared.targetHints.size > 0\n ) {\n const targeted = await resolveEventTargets({\n events: batch,\n hints: prepared.targetHints,\n locator: deps.worktreeLocator,\n privacy,\n budgetMillis: deps.targetResolutionBudgetMillis ?? DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS,\n });\n batch = targeted.events;\n if (targeted.timedOut) {\n logger.debug(\"worktree target resolution exceeded its budget\", {\n \"provider.id\": detection.providerId,\n \"target.resolved\": targeted.resolved,\n });\n }\n }\n\n // Session context: a core step, never adapter code (ADR 0003), outside the\n // session lock like target resolution. One bounded read of the file for this\n // invocation's session — for a subagent event that is its parent's session,\n // because events carry the invocation's session id, never the subagent's.\n // Always run, so an event can only ever carry the core's stamp.\n batch = stampSessionContext(\n batch,\n !suppress && batch.length > 0 && deps.sessionContext !== undefined\n ? await readSessionContext(deps.sessionContext, detection.providerId, identity.sessionId)\n : undefined,\n );\n\n let emitted = 0;\n let exportRejected = 0;\n if (!suppress && batch.length > 0) {\n try {\n const result = await deps.sink.emit(batch);\n emitted = result.accepted;\n exportRejected = result.rejected;\n diagnostics.push(...result.errors);\n } catch (thrown) {\n // A throwing sink delivered nothing and spooled nothing.\n exportRejected = batch.length;\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"export\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n\n const durability = classifyDurability({\n attempted: !suppress && batch.length > 0,\n accepted: emitted,\n rejected: exportRejected,\n });\n\n /**\n * Usage accounting is the *commit* half of the transaction, so it runs here\n * and not in `prepare`.\n *\n * Deriving a delta advances the stored cumulative baseline, which is a\n * one-way move: once it points at this snapshot, the difference this callback\n * represented is no longer recoverable from state. Doing that before knowing\n * whether the telemetry survived means a fully rejected callback releases its\n * claim having *already* consumed its own usage — so the retry diffs against\n * the advanced baseline, reports roughly zero, and the tokens are gone. Delta\n * usage has the mirror-image failure: it needs no baseline, so a retry\n * accumulates the same delta a second time.\n *\n * Nothing exported depends on these numbers — a span carries the usage the\n * provider *reported*, never the derived delta — so deferring costs nothing\n * and buys exactly-once accounting. The read of the baseline, the diff, and\n * the write back all stay inside one critical section, so two concurrent\n * processes cannot both diff against the same snapshot.\n *\n * A suppressed redelivery and a fully rejected attempt both skip this\n * entirely, which is what leaves the baseline where the next real attempt\n * needs it.\n */\n let usageObservations: readonly UsageObservation[] = [];\n if (durability !== \"lost\" && !suppress && batch.length > 0) {\n try {\n usageObservations = await withOptionalSessionLock(\n deps.stateStore,\n identity.sessionId,\n () =>\n deriveUsage(\n batch,\n diagnostics,\n false,\n adapter.capabilities.cumulativeUsageSeries ?? \"event-scope\",\n ),\n );\n } catch (thrown) {\n // The accounting could not be committed. The telemetry is already out, so\n // this is a reporting gap rather than a lost observation: it is said out\n // loud and the callback stays committed, because retrying it would\n // re-export spans a collector has already accepted.\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"state-store-failure\",\n phase: \"state\",\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"usage accounting could not be committed for a delivered callback\", {\n \"provider.id\": detection.providerId,\n });\n }\n }\n\n return {\n ok: true,\n attribution: \"attributed\",\n providerId: detection.providerId,\n detectionConfidence: detection.confidence,\n identity,\n events: batch,\n usageObservations,\n emitted,\n exportRejected,\n durability,\n dropped,\n hookResponse: hookResponseFor(adapter, detection, \"attributed\", undefined, emitted, diagnostics),\n diagnostics,\n };\n } catch (thrown) {\n // Last line of defence: anything unanticipated becomes a diagnostic.\n const info = errorInfoFromThrown(thrown, { code: \"internal-error\", phase: \"parsing\" });\n diagnostics.push(info);\n logger.error(\"ingest contained an unexpected failure\", {\n \"error.code\": info.code,\n ...(info.details ?? {}),\n });\n return {\n ok: true,\n attribution: \"failed\",\n attributionReason: \"internal-error\",\n providerId: \"unknown\",\n detectionConfidence: \"none\",\n events: [],\n usageObservations: [],\n emitted: 0,\n exportRejected: 0,\n durability: \"nothing-to-deliver\" as const,\n dropped: 0,\n hookResponse: SILENT_HOOK_RESPONSE,\n diagnostics,\n };\n }\n };\n\n const flush = async (): Promise<void> => {\n try {\n await deps.sink.flush();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, { code: \"telemetry-export-failure\", phase: \"export\" });\n logger.warn(\"flush failed\", { \"error.code\": info.code });\n }\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await deps.sink.shutdown();\n } catch (thrown) {\n const info = errorInfoFromThrown(thrown, {\n code: \"telemetry-export-failure\",\n phase: \"shutdown\",\n });\n logger.warn(\"shutdown failed\", { \"error.code\": info.code });\n }\n };\n\n return { resolveDelivery, ingest, flush, shutdown, config };\n};\n\n/** Fail-open wrapper: a reader that throws despite its contract stamps nothing. */\nconst readSessionContext = async (\n reader: SessionContextReader,\n providerId: string,\n sessionId: string,\n): Promise<Awaited<ReturnType<SessionContextReader[\"read\"]>>> => {\n try {\n return await reader.read({ providerId, sessionId });\n } catch {\n return undefined;\n }\n};\n\nconst buildErrorEvents = (\n diagnostics: readonly OtelHookErrorInfo[],\n identity: InvocationIdentity,\n sequenceBase: number,\n ids: IdGenerator,\n privacy: PrivacyService,\n): readonly CanonicalEvent[] => {\n const events: CanonicalEvent[] = [];\n for (const [index, info] of diagnostics.slice(0, MAX_ERROR_EVENTS).entries()) {\n const sequence = sequenceBase + index;\n events.push({\n schemaVersion: CANONICAL_SCHEMA_VERSION,\n eventId: ids.newEventId({\n invocationId: identity.invocationId,\n sequence,\n eventType: \"error.raised\",\n discriminator: info.code,\n }),\n invocationId: identity.invocationId,\n sessionId: identity.sessionId,\n sequence,\n occurredAt: info.occurredAt ?? identity.startedAt,\n provenance: identity.provenance,\n workspace: identity.workspace,\n extensions: {},\n type: \"error.raised\",\n errorCode: info.code,\n severity: info.severity,\n phase: info.phase,\n retryable: info.retryable,\n // The message is already a fixed-vocabulary summary, but it still passes\n // through the privacy service so one policy governs every disclosure.\n message: privacy.describeContent({ kind: \"error-message\", text: info.message }),\n detail: info.code,\n });\n }\n return events;\n};\n","import type { DeliveryIdentifierSupport, ProviderDeliveryClaim } from \"../providers/adapter.js\";\nimport type { IdGenerator } from \"./ports.js\";\n\n/**\n * Where a delivery identity came from.\n *\n * `host` is an id the embedding host passed in; `provider` is one normalized\n * from payload fields the selected adapter vouched for. The two are kept\n * distinguishable because they carry different guarantees: a host id is unique\n * by construction, a provider-derived one is only as good as the adapter's\n * evidence.\n */\nexport type DeliveryOrigin = \"host\" | \"provider\";\n\n/**\n * A delivery identity reduced to the two opaque strings deduplication needs.\n *\n * Both are digests, never raw payload values. That matters because the pair\n * becomes a state-store key and a diagnostic attribute: a provider's session id,\n * tool-call id, or turn id would otherwise be written to disk and logged as a\n * side effect of deduplication, which is not a disclosure anybody asked for.\n */\nexport type ResolvedDeliveryIdentity = {\n /** Namespace the callback id is unique within. */\n readonly scope: string;\n /** Opaque identity of this callback within that scope. */\n readonly callbackId: string;\n readonly origin: DeliveryOrigin;\n /** Non-sensitive justifications, for diagnostics. Empty for a host id. */\n readonly evidence: readonly string[];\n};\n\n/** Why no replay-stable delivery identity could be established. */\nexport type DeliveryUnavailableReason =\n /** No adapter was selected, so nothing could vouch for an identifier. */\n | \"provider-unattributed\"\n /** The adapter declares that no callback of this provider carries one. */\n | \"provider-declares-none\"\n /** The adapter supports some callbacks, but not this one. */\n | \"callback-not-identifiable\"\n /** The adapter offered an identity that failed the contract's own guards. */\n | \"claim-rejected\"\n /**\n * An identity was established but the state store could not be read or written,\n * so nothing could be claimed against it.\n */\n | \"state-unavailable\";\n\nexport type DeliveryResolution =\n | { readonly status: \"resolved\"; readonly identity: ResolvedDeliveryIdentity }\n | {\n readonly status: \"unavailable\";\n readonly reason: DeliveryUnavailableReason;\n /** Present once a provider has been selected. */\n readonly providerId?: string;\n /** The adapter's declared coverage, when there is an adapter. */\n readonly capability?: DeliveryIdentifierSupport;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Taken from the detection, which already carries it into span attributes\n * and provenance, so it discloses nothing new — and it is the difference\n * between a diagnostic an operator can act on and one that only restates\n * that something is missing.\n */\n readonly sourceEventName?: string;\n /**\n * Why, in the adapter's own words: a rejected claim's failure, or the\n * per-callback gap the adapter documents. Never contains payload values.\n */\n readonly detail?: string;\n };\n\n/**\n * Scope prefix for provider-derived identities.\n *\n * Kept distinct from a host-chosen scope so the two id spaces cannot be\n * confused, and so a host that starts supplying `--callback-id` does not inherit\n * whatever the adapter had already recorded for the same callbacks.\n */\nconst PROVIDER_SCOPE_PREFIX = \"provider-session\";\n\n/**\n * Namespace a host-supplied delivery id.\n *\n * Deliberately *not* scoped by session or installation: the host documented its\n * id as unique between distinct callbacks, so narrowing the scope here would\n * make a host id that repeats across two sessions stop being recognized as the\n * redelivery the host said it was.\n */\nexport const hostDeliveryIdentity = (\n callbackId: string,\n scope?: string,\n): ResolvedDeliveryIdentity => ({\n scope: scope ?? \"delivery\",\n callbackId,\n origin: \"host\",\n evidence: [],\n});\n\n/**\n * Reduce an adapter's delivery claim to an opaque, replay-stable identity.\n *\n * Scoping runs provider id, installation, and the provider's own session id\n * through the digest, so the same tool-call id observed by two installations, two\n * providers, or two sessions is three different callbacks. The callback digest\n * covers the event name and the adapter's components, so a `PreToolUse` and a\n * `PostToolUse` sharing one `tool_use_id` stay distinct.\n *\n * The digest comes from the injected {@link IdGenerator}, which is\n * content-addressed by default — that is precisely what makes the identity\n * survive a process restart: a later process with the same namespace recomputes\n * the identical pair without reading any state.\n */\nexport const resolveDeliveryIdentity = (input: {\n readonly ids: IdGenerator;\n readonly providerId: string;\n readonly installationId: string;\n readonly claim: ProviderDeliveryClaim;\n}): ResolvedDeliveryIdentity => {\n const { ids, providerId, installationId, claim } = input;\n return {\n scope: `${PROVIDER_SCOPE_PREFIX}:${ids.newOpaqueId([\n \"delivery-scope\",\n providerId,\n installationId,\n claim.sessionId,\n ])}`,\n callbackId: ids.newOpaqueId([\n \"delivery-callback\",\n providerId,\n claim.sessionId,\n claim.sourceEventName,\n ...claim.components,\n ]),\n origin: \"provider\",\n evidence: [...claim.evidence],\n };\n};\n","import { createHash, randomUUID } from \"node:crypto\";\n\nimport {\n eventIdSchema,\n invocationIdSchema,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { EventIdSeed, IdGenerator, InvocationIdSeed } from \"./ports.js\";\n\nconst digest = (namespace: string, parts: readonly (string | number | undefined)[]): string => {\n const hash = createHash(\"sha256\");\n hash.update(namespace);\n for (const part of parts) {\n hash.update(\"\\0\");\n hash.update(part === undefined ? \"\" : String(part));\n }\n return hash.digest(\"hex\");\n};\n\nexport type DeterministicIdOptions = {\n /**\n * Namespace mixed into every id. Two deployments using different namespaces\n * produce different ids for identical input, which prevents cross-tenant id\n * collisions in a shared collector.\n */\n readonly namespace?: string;\n /** Hex characters retained. 32 gives a 128-bit id. */\n readonly length?: number;\n};\n\n/**\n * Content-addressed id generator.\n *\n * Ids are a pure function of their seed, so re-running a hook on the same input\n * — a retry, a replayed transcript, a duplicated delivery — yields identical\n * ids. That makes the pipeline idempotent at the collector instead of relying on\n * exactly-once delivery, which hooks cannot provide.\n */\nexport const createDeterministicIdGenerator = (\n options: DeterministicIdOptions = {},\n): IdGenerator => {\n const namespace = options.namespace ?? \"otel-hook\";\n const length = Math.min(Math.max(options.length ?? 32, 16), 64);\n const truncate = (hex: string): string => hex.slice(0, length);\n\n return {\n newInvocationId: (seed: InvocationIdSeed): InvocationId =>\n invocationIdSchema.parse(\n `inv_${truncate(\n digest(`${namespace}/invocation`, [\n seed.providerId,\n seed.sessionId,\n seed.sourceEventName,\n seed.occurredAt,\n seed.discriminator,\n ]),\n )}`,\n ),\n newEventId: (seed: EventIdSeed): EventId =>\n eventIdSchema.parse(\n `evt_${truncate(\n digest(`${namespace}/event`, [\n seed.invocationId,\n seed.sequence,\n seed.eventType,\n seed.discriminator,\n ]),\n )}`,\n ),\n newOpaqueId: (parts: readonly string[]): string =>\n truncate(digest(`${namespace}/opaque`, parts)),\n };\n};\n\n/**\n * Random id generator.\n *\n * Use only when no stable seed exists; it is not replay-safe, so duplicate\n * deliveries become duplicate events.\n */\nexport const createRandomIdGenerator = (): IdGenerator => ({\n newInvocationId: (): InvocationId => invocationIdSchema.parse(`inv_${randomUUID()}`),\n newEventId: (): EventId => eventIdSchema.parse(`evt_${randomUUID()}`),\n newOpaqueId: (): string => randomUUID().replace(/-/g, \"\"),\n});\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport { modelDescriptorSchema, type CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport type { WorktreeKind } from \"../model/target.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n /**\n * The model a session last reported, so a later invocation whose payload names\n * none (Claude Code's `Stop`) can still say which model it was. A model id is\n * not sensitive (`modelDescriptorSchema`), and the descriptor is the strict,\n * bounded canonical shape, never a payload fragment.\n */\n z.strictObject({\n kind: z.literal(\"session-model\"),\n model: modelDescriptorSchema,\n }),\n /**\n * How far a {@link PayloadEnricher} has read a session's append-only source\n * (Claude Code's transcript), so the next read starts where the last ended.\n * `source` is an opaque digest of what was read, never a path.\n */\n /**\n * Running state of one metric series (issue #69), so a cumulative data point\n * exported by a later hook process continues the same total. Holds numbers and\n * a series digest only; the series' attributes are re-supplied by the caller\n * and never read back from disk.\n */\n z.strictObject({\n kind: z.literal(\"metric-series\"),\n /** Start of the cumulative interval. */\n startTimeMillis: epochMillisSchema,\n /** Counters: the running total. */\n value: z.number().finite().min(0).optional(),\n /** Histograms: the running aggregation. */\n histogram: z\n .strictObject({\n count: z.number().int().min(0),\n sum: z.number().finite().min(0),\n min: z.number().finite(),\n max: z.number().finite(),\n bucketCounts: z.array(z.number().int().min(0)).max(64),\n })\n .optional(),\n /** Opaque digest of the last delivery folded in; makes a replay a no-op. */\n appliedDelivery: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/).optional(),\n }),\n z.strictObject({\n kind: z.literal(\"read-cursor\"),\n source: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n offset: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n\n/** A git worktree found on the local filesystem. Holds a path: never exported. */\nexport type LocatedWorktree = {\n /** Absolute path of the worktree's top-level directory (the one holding `.git`). */\n readonly root: string;\n /** Branch checked out there, from `HEAD`; absent when HEAD is detached. */\n readonly branch?: string;\n /** Main checkout or linked worktree; absent when the locator does not tell. */\n readonly kind?: WorktreeKind;\n /**\n * Absolute path of the repository's main worktree — `root` itself for a main\n * worktree. Absent when there is none to name: a bare repository, a main\n * checkout that is gone, or a layout the locator cannot read.\n */\n readonly mainRoot?: string;\n};\n\n/**\n * Finds the git worktree containing a local path (ADR 0008).\n *\n * The only port that reads the filesystem on behalf of event content, which is\n * why it is a port: the core decides *when* to ask and what of the answer may be\n * exported, the implementation only answers. Implementations must never throw or\n * reject — any failure is `undefined` — and must not spawn processes.\n */\nexport interface WorktreeLocator {\n locate(absolutePath: string): Promise<LocatedWorktree | undefined>;\n}\n\n/** Where an enricher stopped reading a session's source; see the `read-cursor` state value. */\nexport type ReadCursor = {\n /** Opaque digest naming the source, so a cursor never applies to another file. */\n readonly source: string;\n /** Byte offset the next read starts at. */\n readonly offset: number;\n};\n\nexport type PayloadEnrichmentInput = {\n readonly payload: unknown;\n readonly sessionId: string;\n /** The cursor this enricher stored for this session (and cursor scope) last time, if any. */\n readonly cursor?: ReadCursor;\n};\n\nexport type PayloadEnrichment = {\n /** The payload the adapter parses: the input, or a copy with fields attached. */\n readonly payload: unknown;\n /** A cursor to store for this session; absent leaves the stored one as it is. */\n readonly cursor?: ReadCursor;\n /** Short, non-sensitive notes for the debug log (why a read fell back, ...). */\n readonly notes?: readonly string[];\n};\n\n/**\n * Host-side step that attaches facts to a provider payload before its adapter\n * parses it — for facts the provider writes somewhere other than the hook\n * payload, such as Claude Code's transcript.\n *\n * Not an adapter capability, on purpose: adapters get no filesystem handle (ADR\n * 0003). An enricher is configured by the host, runs inside the session lock so\n * its cursor is read and written atomically, and must be bounded and never throw\n * (a throw is contained and the original payload is parsed). It never runs for a\n * redelivered callback, which is not a new observation.\n */\nexport interface PayloadEnricher {\n /** Stable id; namespaces the enricher's cursor in the state store. */\n readonly id: string;\n /** The provider whose payloads it enriches. Others are never passed to it. */\n readonly providerId: string;\n /**\n * Which of the session's cursors this payload reads, when a session has more\n * than one source (Claude Code writes each subagent to its own transcript).\n * `undefined`, or no function, selects the session's own cursor. A scope is\n * part of a state key, never exported; it must not hold a path.\n */\n cursorScope?(payload: unknown): string | undefined;\n enrich(input: PayloadEnrichmentInput): Promise<PayloadEnrichment>;\n}\n\n/**\n * One window of a session's context: the attributes in force from `from`\n * (inclusive) until `to` (exclusive), or open-ended when `to` is `null`.\n * Attributes are already screened (see `sanitizeSessionContextAttributes`).\n */\nexport type SessionContextSegment = {\n readonly from: EpochMillis;\n readonly to: EpochMillis | null;\n readonly attributes: Readonly<Record<string, string | number | boolean>>;\n};\n\nexport type SessionContextRequest = {\n /** The detected provider, e.g. `claude-code`. The reader maps it to its directory name. */\n readonly providerId: string;\n /**\n * The session whose context applies: always the invocation's session, which\n * for a subagent event is its parent's — never the subagent's own id.\n */\n readonly sessionId: string;\n};\n\n/**\n * Reads the session context a harness wrote for one agent session.\n *\n * A port for the same reason {@link WorktreeLocator} is one: the core decides\n * when to ask and what of the answer reaches a record; the implementation only\n * reads. Adapters never see it (ADR 0003). Implementations must never throw or\n * reject: no file, an unreadable file, an invalid one, or one of an unknown\n * version are all `undefined`, and the core then stamps nothing.\n */\nexport interface SessionContextReader {\n read(request: SessionContextRequest): Promise<readonly SessionContextSegment[] | undefined>;\n}\n","import type { Attributes } from \"../model/primitives.js\";\nimport { LOG_LEVEL_RANK, type Logger, type LogLevel } from \"./ports.js\";\n\nexport const createNullLogger = (): Logger => ({\n error: (): void => undefined,\n warn: (): void => undefined,\n info: (): void => undefined,\n debug: (): void => undefined,\n});\n\nexport type StderrLoggerOptions = {\n readonly level?: LogLevel;\n /** Injected for tests; defaults to `process.stderr.write`. */\n readonly write?: (line: string) => void;\n};\n\n/**\n * Diagnostic logger that writes to stderr only.\n *\n * stdout belongs to the host agent's hook protocol: anything written there can\n * be parsed as a hook response and change the agent's behaviour (ADR 0004).\n */\nexport const createStderrLogger = (options: StderrLoggerOptions = {}): Logger => {\n const level = options.level ?? \"warn\";\n const write =\n options.write ??\n ((line: string): void => {\n process.stderr.write(line);\n });\n const threshold = LOG_LEVEL_RANK[level];\n\n const log = (entryLevel: LogLevel, message: string, fields?: Attributes): void => {\n if (LOG_LEVEL_RANK[entryLevel] > threshold || threshold === 0) {\n return;\n }\n const payload =\n fields === undefined || Object.keys(fields).length === 0\n ? { level: entryLevel, message }\n : { level: entryLevel, message, fields };\n write(`${JSON.stringify(payload)}\\n`);\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n log(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n log(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n log(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n log(\"debug\", message, fields);\n },\n };\n};\n","import * as path from \"node:path\";\n\nimport { isTargetedEvent, type CanonicalEvent } from \"../model/events.js\";\nimport type { EventId } from \"../model/primitives.js\";\nimport { workspaceTargetSchema, type TargetHint, type WorkspaceTarget } from \"../model/target.js\";\nimport type { PrivacyService } from \"../privacy/service.js\";\nimport { deriveWorkspaceIdentity } from \"../privacy/workspace.js\";\nimport type { LocatedWorktree, WorktreeLocator } from \"./ports.js\";\n\n/**\n * Turns adapters' target hints into exported worktree targets (ADR 0008).\n *\n * This is where local paths stop. A hint's paths are resolved to a worktree\n * root, branch, and repository through the injected {@link WorktreeLocator};\n * only salted `git-root` handles of the root and of its repository's main\n * worktree, the worktree's kind, and the branch name survive onto the event.\n *\n * Fail-open in both directions that matter: a slow or failing filesystem costs\n * the event its target, never the event — and never the host more than the\n * time budget. Fail-closed on meaning: a hint whose paths land in two different\n * worktrees, or that names a relative path with nothing to resolve it against,\n * yields no target rather than a guess.\n */\n\n/** Default ceiling on target resolution per callback. */\nexport const DEFAULT_TARGET_RESOLUTION_BUDGET_MILLIS = 50;\n\nconst absolutePathsOf = (hint: TargetHint): readonly string[] | undefined => {\n const base =\n hint.baseDirectory !== undefined && path.isAbsolute(hint.baseDirectory)\n ? hint.baseDirectory\n : undefined;\n const resolved: string[] = [];\n for (const candidate of hint.paths) {\n if (path.isAbsolute(candidate)) {\n resolved.push(path.resolve(candidate));\n } else if (base !== undefined) {\n resolved.push(path.resolve(base, candidate));\n } else {\n return undefined;\n }\n }\n return resolved;\n};\n\nconst resolveHint = async (\n hint: TargetHint,\n locator: WorktreeLocator,\n privacy: PrivacyService,\n): Promise<WorkspaceTarget | undefined> => {\n const paths = absolutePathsOf(hint);\n if (paths === undefined) {\n return undefined;\n }\n const located: (LocatedWorktree | undefined)[] = await Promise.all(\n [...new Set(paths)].map((candidate) => locator.locate(candidate)),\n );\n const [first] = located;\n if (first === undefined || located.some((entry) => entry?.root !== first.root)) {\n return undefined;\n }\n const identity = deriveWorkspaceIdentity(\n privacy,\n { kind: \"git-root\", absolutePath: first.root },\n first.branch === undefined ? {} : { vcsBranchName: first.branch },\n );\n if (identity.keySource !== \"git-root\") {\n return undefined;\n }\n // The repository is named by its main worktree, as that worktree would name\n // itself — so a main worktree's repository id is its own workspace id.\n const repository =\n first.mainRoot === undefined\n ? undefined\n : deriveWorkspaceIdentity(privacy, { kind: \"git-root\", absolutePath: first.mainRoot });\n const parsed = workspaceTargetSchema.safeParse({\n workspaceId: identity.workspaceId,\n ...(identity.vcsBranchName === undefined ? {} : { vcsBranchName: identity.vcsBranchName }),\n source: hint.source,\n ...(repository?.keySource === \"git-root\" ? { repositoryId: repository.workspaceId } : {}),\n ...(first.kind === undefined ? {} : { worktreeKind: first.kind }),\n });\n return parsed.success ? parsed.data : undefined;\n};\n\nexport type ResolveEventTargetsInput = {\n readonly events: readonly CanonicalEvent[];\n readonly hints: ReadonlyMap<EventId, TargetHint>;\n readonly locator: WorktreeLocator;\n readonly privacy: PrivacyService;\n readonly budgetMillis: number;\n};\n\nexport type ResolveEventTargetsResult = {\n readonly events: readonly CanonicalEvent[];\n /** Hints that produced a target. */\n readonly resolved: number;\n /** True when the time budget expired before every hint was answered. */\n readonly timedOut: boolean;\n};\n\n/**\n * Attach a `target` to each targeted event (`TARGETED_EVENT_TYPES`) that has a resolvable hint. Never\n * throws or rejects; events without a hint, or whose hint does not resolve,\n * are returned unchanged.\n */\nexport const resolveEventTargets = async (\n input: ResolveEventTargetsInput,\n): Promise<ResolveEventTargetsResult> => {\n const pending = input.events.filter((event) => isTargetedEvent(event) && input.hints.has(event.eventId));\n if (pending.length === 0) {\n return { events: input.events, resolved: 0, timedOut: false };\n }\n\n const targets = new Map<EventId, WorkspaceTarget>();\n const work = Promise.all(\n pending.map(async (event) => {\n const hint = input.hints.get(event.eventId);\n if (hint === undefined) {\n return;\n }\n try {\n const target = await resolveHint(hint, input.locator, input.privacy);\n if (target !== undefined) {\n targets.set(event.eventId, target);\n }\n } catch {\n // A locator that broke its no-throw contract costs this event its target.\n }\n }),\n ).then(() => \"done\" as const);\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const deadline = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), Math.max(0, input.budgetMillis));\n timer.unref?.();\n });\n const finished = await Promise.race([work, deadline]);\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n\n // Snapshot: a resolution landing after the deadline must not mutate a batch\n // that is already on its way out.\n const settled = new Map(targets);\n const events = input.events.map((event): CanonicalEvent => {\n const target = settled.get(event.eventId);\n if (target === undefined || !isTargetedEvent(event)) {\n return event;\n }\n return { ...event, target };\n });\n return { events, resolved: settled.size, timedOut: finished === \"timeout\" };\n};\n","/**\n * Per-key async mutex.\n *\n * Ordinary promises already serialize a single caller's `await`s, but two\n * concurrent callers racing a read-modify-write against the same key (two\n * hook invocations updating the same session, in the same process) are not\n * serialized by anything. This chains each key's operations through a promise\n * tail so they run one at a time, in arrival order, without blocking unrelated\n * keys.\n */\nexport interface AsyncLock {\n /**\n * `timeoutMillis` bounds how long the caller waits to *acquire* the key.\n *\n * Two guarantees, and the boundary between them is the whole contract:\n *\n * - **A timed-out caller's `fn` never runs.** Giving up on the wait cancels the\n * queued operation. It has to: a caller that has been told \"I could not take\n * the lock\" will report contention and move on, and if `fn` then ran anyway it\n * would mutate state after the caller had already declared that nothing\n * happened. That is worse than either outcome on its own — the state changes\n * and nobody is watching.\n * - **Work is never cancelled after acquisition.** Once `fn` has started the\n * timeout is irrelevant; interrupting a read-modify-write partway through is\n * exactly the corruption a mutex exists to prevent. So the timeout bounds\n * *waiting*, never *exclusivity* and never *completion*.\n *\n * Cancellation does not let a waiter skip the queue: the cancelled slot still\n * settles in order, so everyone behind it keeps its place. A cancelled call\n * rejects with {@link LockWaitTimeoutError}, the same error a timed-out wait\n * produces, because from the caller's side they are one condition.\n */\n run<T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T>;\n}\n\nexport class LockWaitTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`lock wait exceeded ${timeoutMillis}ms`);\n this.name = \"LockWaitTimeoutError\";\n this.lockKey = key;\n }\n}\n\nexport const createAsyncLock = (): AsyncLock => {\n const tail = new Map<string, Promise<void>>();\n\n const run = async <T>(key: string, fn: () => Promise<T>, timeoutMillis?: number): Promise<T> => {\n const previous = tail.get(key) ?? Promise.resolve();\n const queued = previous.then(\n () => undefined,\n () => undefined,\n );\n\n /**\n * `entered` flips synchronously, immediately before `fn` is invoked, and\n * `cancelled` is only ever set from the timer while `entered` is false.\n *\n * That ordering is what makes the two guarantees exclusive rather than racy.\n * Microtasks drain before timers, so if this slot's turn has arrived at all,\n * the callback below has already run and set `entered` before any timer\n * callback can observe it — there is no window in which the timer sees a\n * not-yet-entered slot that is in fact about to run.\n */\n let cancelled = false;\n let entered = false;\n\n const current = queued.then((): T | Promise<T> => {\n if (cancelled) {\n // The waiter gave up before its turn came, so `fn` is skipped entirely.\n // The slot still settles here, in order, so nothing behind it is reordered.\n throw new LockWaitTimeoutError(key, timeoutMillis ?? 0);\n }\n entered = true;\n return fn();\n });\n\n const swallowed = current.then(\n () => undefined,\n () => undefined,\n );\n tail.set(key, swallowed);\n void swallowed.then(() => {\n if (tail.get(key) === swallowed) {\n tail.delete(key);\n }\n });\n\n if (timeoutMillis === undefined) {\n return current;\n }\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n if (!entered) {\n cancelled = true;\n }\n reject(new LockWaitTimeoutError(key, timeoutMillis));\n }, timeoutMillis);\n timer.unref?.();\n });\n try {\n // Raced against the queue gate, not against `current`: once the slot is\n // entered the caller waits for `fn` however long it takes.\n await Promise.race([queued, timeout]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n return current;\n };\n\n return { run };\n};\n","import type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { LockWaitTimeoutError } from \"./async-lock.js\";\n\n/**\n * A lock could not be acquired within its wait bound because somebody else holds\n * it.\n *\n * Distinct from \"the store is broken\" on purpose, and the distinction is\n * load-bearing for callers that guard a read-modify-write with it. Contention\n * means a peer is plausibly *inside* the critical section right now, so\n * proceeding unlocked would produce exactly the lost update the lock exists to\n * prevent. A store that cannot lock at all — an unwritable directory, a full\n * disk — protects nothing, because the state the lock guards is equally\n * unreachable; there proceeding is the fail-open answer and costs nothing.\n */\nexport class StateLockTimeoutError extends Error {\n public readonly lockKey: string;\n\n public constructor(key: string, timeoutMillis: number) {\n super(`state store lock wait for \"${key}\" exceeded ${String(timeoutMillis)}ms`);\n this.name = \"StateLockTimeoutError\";\n this.lockKey = key;\n }\n}\n\n/**\n * Whether a thrown value means \"somebody else holds the lock\".\n *\n * Also true for {@link LockWaitTimeoutError}, the in-process variant, which\n * carries a second warning for callers: a timed-out wait does not cancel the\n * queued critical section, so it may still run afterwards. A caller that treats\n * contention as \"retry unlocked\" would therefore risk running the section twice.\n */\nexport const isStateLockContention = (thrown: unknown): boolean =>\n thrown instanceof StateLockTimeoutError || thrown instanceof LockWaitTimeoutError;\n\n/**\n * Optional capability beyond the frozen {@link StateStore} contract: a\n * session-scoped lock a caller can use to make a multi-step read-modify-write\n * atomic across an entire session, not just a single key.\n *\n * Deliberately keyed by an explicit `sessionId` the caller already knows,\n * rather than derived by parsing the store's own keys, so a store never has\n * to understand any particular key scheme.\n */\nexport interface LockingStateStore extends StateStore {\n withSessionLock<T>(\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n ): Promise<T>;\n}\n\nexport const isLockingStateStore = (store: StateStore): store is LockingStateStore =>\n typeof (store as Partial<LockingStateStore>).withSessionLock === \"function\";\n\n/** Runs `fn` under the store's session lock when it has one; otherwise runs it directly. */\nexport const withOptionalSessionLock = async <T>(\n store: StateStore,\n sessionId: string,\n fn: () => Promise<T>,\n options?: { readonly timeoutMillis?: number },\n): Promise<T> => {\n if (isLockingStateStore(store)) {\n return store.withSessionLock(sessionId, fn, options);\n }\n return fn();\n};\n\nexport type StateStoreDependencies = {\n readonly clock: Clock;\n};\n","import { open } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n} from \"../config/resource-attributes.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { SessionContextReader, SessionContextSegment } from \"./ports.js\";\n\n/**\n * Session context: attributes a harness wants on every record of one agent\n * session, for a window of time.\n *\n * A harness (HAR, or anything else) writes one JSON file per agent session:\n *\n * ```text\n * <dir>/<agent-tool>/<session-id>.json\n * { \"version\": 1, \"agentTool\": \"claude_code\", \"sessionId\": \"…\",\n * \"segments\": [ { \"from\": \"<ISO-8601>\", \"to\": \"<ISO-8601>\" | null,\n * \"reason\": \"launch\", \"attributes\": { \"k\": \"v\" } } ] }\n * ```\n *\n * On every hook event the core reads the one file for the event's session,\n * picks the segment in force at each event's time, and stamps its attributes on\n * every record the event produces. otel-hook knows nothing about what the\n * attributes mean: it applies an attribute map. See `docs/session-context.md`.\n *\n * Fail-open throughout: a missing, unreadable, oversized, invalid, or\n * wrong-version file — or no segment in force — stamps nothing and never fails\n * the hook.\n */\n\n/** The only file format version this build reads. Any other is ignored whole. */\nexport const SESSION_CONTEXT_FILE_VERSION = 1 as const;\n\n/** Largest file read; anything bigger is ignored rather than truncated. */\nexport const DEFAULT_SESSION_CONTEXT_MAX_BYTES = 256 * 1024;\n\n/** Ceiling on one read; a slow filesystem costs the stamp, never the hook. */\nexport const DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS = 100;\n\n/** Upper bound on segments considered in one file. */\nexport const MAX_SESSION_CONTEXT_SEGMENTS = 1024;\n\n/**\n * otel-hook provider id → the agent-tool directory a harness writes under.\n *\n * The names are the ones HAR derives from the agent process it finds\n * (`claude_code`, `codex`, `cursor`). A provider absent from this table has no\n * session context: nothing is read for it.\n */\nexport const SESSION_CONTEXT_AGENT_TOOLS: Readonly<Record<string, string>> = Object.freeze({\n \"claude-code\": \"claude_code\",\n codex: \"codex\",\n cursor: \"cursor\",\n \"gemini-cli\": \"gemini_cli\",\n antigravity: \"antigravity\",\n});\n\nexport const sessionContextAgentTool = (providerId: string): string | undefined =>\n Object.hasOwn(SESSION_CONTEXT_AGENT_TOOLS, providerId) ? SESSION_CONTEXT_AGENT_TOOLS[providerId] : undefined;\n\n/**\n * A session id is used as a file name, so it must be one: no separators, no\n * `.`/`..`, nothing a path could be steered with. Real session ids (UUIDs) pass.\n */\nconst SESSION_FILE_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;\n\nexport const isSessionContextFileName = (sessionId: string): boolean =>\n SESSION_FILE_NAME_PATTERN.test(sessionId) && !sessionId.includes(\"..\");\n\n/**\n * Where the context of one session lives, or `undefined` when the provider has\n * no agent-tool directory or the session id cannot be a file name.\n */\nexport const sessionContextFilePath = (\n dir: string,\n providerId: string,\n sessionId: string,\n): string | undefined => {\n const tool = sessionContextAgentTool(providerId);\n if (tool === undefined || !isSessionContextFileName(sessionId) || !path.isAbsolute(dir)) {\n return undefined;\n }\n return path.join(dir, tool, `${sessionId}.json`);\n};\n\n/**\n * Keys a context may never set, whatever it says.\n *\n * - `factory.local.*`: the Factory Commits telemetry profile defines it as\n * local-only (paths and the like); it must never reach a record.\n * - otel-hook's own record identity (`session.id`, `otelhook.*`, the hex trace\n * ids, `gen_ai.conversation.id`): a context file describes the work a session\n * does, it does not get to rename the session or forge its trace.\n * - Everything `checkResourceAttributeKey` refuses: malformed keys, the\n * `service.*` exporter policy keys, and secret-like names.\n */\nconst RESERVED_CONTEXT_KEYS: ReadonlySet<string> = new Set([\n \"session.id\",\n \"trace_id\",\n \"span_id\",\n \"parent_span_id\",\n \"gen_ai.conversation.id\",\n \"factory.local\",\n]);\nconst RESERVED_CONTEXT_PREFIXES: readonly string[] = Object.freeze([\"factory.local.\", \"otelhook.\"]);\n\nexport const isReservedSessionContextKey = (key: string): boolean =>\n RESERVED_CONTEXT_KEYS.has(key) || RESERVED_CONTEXT_PREFIXES.some((prefix) => key.startsWith(prefix));\n\n/**\n * Screen one segment's attribute map: primitive values only, bounded, and no\n * reserved or unsafe key. Dropped entries are dropped silently, one by one; the\n * rest of the map still applies.\n */\nexport const sanitizeSessionContextAttributes = (\n attributes: Readonly<Record<string, unknown>>,\n): Readonly<Record<string, string | number | boolean>> => {\n const kept: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (count >= MAX_RESOURCE_ATTRIBUTES) {\n break;\n }\n if (checkResourceAttributeKey(key) !== undefined || isReservedSessionContextKey(key)) {\n continue;\n }\n if (typeof value === \"string\") {\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n continue;\n }\n } else if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n continue;\n }\n } else if (typeof value !== \"boolean\") {\n continue;\n }\n kept[key] = value;\n count += 1;\n }\n return kept;\n};\n\nconst ISO_INSTANT_PATTERN =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:Z|[+-]\\d{2}:\\d{2})$/;\n\nconst isoInstantSchema = z\n .string()\n .max(64)\n .regex(ISO_INSTANT_PATTERN)\n .transform((value, ctx) => {\n const millis = Date.parse(value);\n if (!Number.isFinite(millis)) {\n ctx.issues.push({ code: \"custom\", input: value, message: \"not a valid instant\" });\n return z.NEVER;\n }\n return millis;\n });\n\nconst segmentSchema = z.object({\n from: isoInstantSchema,\n to: isoInstantSchema.nullable(),\n reason: z.string().max(256).optional(),\n attributes: z.record(z.string(), z.unknown()),\n});\n\n/**\n * The file format. Unknown extra fields are tolerated (a later minor revision\n * may add some); a different `version` is not, because its fields may mean\n * something else.\n */\nconst sessionContextFileSchema = z.object({\n version: z.literal(SESSION_CONTEXT_FILE_VERSION),\n agentTool: z.string().max(64).optional(),\n sessionId: z.string().max(256).optional(),\n segments: z.array(segmentSchema).max(MAX_SESSION_CONTEXT_SEGMENTS),\n});\n\n/**\n * Parse a decoded context file into screened segments.\n *\n * `expected` guards against a file that names another session or tool than the\n * one it was read for (a copy, a misplaced write): such a file applies to\n * nobody. Returns `undefined` for anything invalid; never throws.\n */\nexport const parseSessionContextFile = (\n value: unknown,\n expected?: { readonly agentTool?: string; readonly sessionId?: string },\n): readonly SessionContextSegment[] | undefined => {\n const parsed = sessionContextFileSchema.safeParse(value);\n if (!parsed.success) {\n return undefined;\n }\n const file = parsed.data;\n if (\n (expected?.agentTool !== undefined && file.agentTool !== undefined && file.agentTool !== expected.agentTool) ||\n (expected?.sessionId !== undefined && file.sessionId !== undefined && file.sessionId !== expected.sessionId)\n ) {\n return undefined;\n }\n return file.segments.map((segment) => ({\n from: segment.from,\n to: segment.to,\n attributes: sanitizeSessionContextAttributes(segment.attributes),\n }));\n};\n\n/**\n * The segment in force at `at`: `from <= at` and (`to` is null or `at < to`).\n * Should a writer ever leave two overlapping, the one that started last wins,\n * because it is the more recent statement.\n */\nexport const segmentInForce = (\n segments: readonly SessionContextSegment[],\n at: number,\n): SessionContextSegment | undefined => {\n let best: SessionContextSegment | undefined;\n for (const segment of segments) {\n if (segment.from <= at && (segment.to === null || at < segment.to)) {\n if (best === undefined || segment.from >= best.from) {\n best = segment;\n }\n }\n }\n return best;\n};\n\n/**\n * Stamp each event with the attributes of the segment in force at its own\n * `occurredAt`, and strip any `contextAttributes` an event already carried: only\n * this core step may set them. An event with no segment in force, or one whose\n * segment has no usable attribute, carries none.\n */\nexport const stampSessionContext = (\n events: readonly CanonicalEvent[],\n segments: readonly SessionContextSegment[] | undefined,\n): readonly CanonicalEvent[] =>\n events.map((event) => {\n const { contextAttributes: _discarded, ...rest } = event;\n const segment = segments === undefined ? undefined : segmentInForce(segments, event.occurredAt);\n if (segment === undefined || Object.keys(segment.attributes).length === 0) {\n return _discarded === undefined ? event : (rest);\n }\n return { ...rest, contextAttributes: { ...segment.attributes } };\n });\n\nexport type DirectorySessionContextReaderOptions = {\n /** Absolute directory holding `<agent-tool>/<session-id>.json`. */\n readonly dir: string;\n readonly maxBytes?: number;\n readonly budgetMillis?: number;\n};\n\nconst readBounded = async (file: string, maxBytes: number): Promise<string | undefined> => {\n let handle;\n try {\n handle = await open(file, \"r\");\n } catch {\n return undefined;\n }\n try {\n const stats = await handle.stat();\n if (!stats.isFile() || stats.size > maxBytes) {\n return undefined;\n }\n const buffer = Buffer.alloc(maxBytes + 1);\n let length = 0;\n while (length < buffer.length) {\n const { bytesRead } = await handle.read(buffer, length, buffer.length - length, length);\n if (bytesRead === 0) {\n break;\n }\n length += bytesRead;\n }\n if (length > maxBytes) {\n return undefined;\n }\n return buffer.subarray(0, length).toString(\"utf8\");\n } catch {\n return undefined;\n } finally {\n await handle.close().catch(() => undefined);\n }\n};\n\n/**\n * The filesystem {@link SessionContextReader}: one bounded read of one file per\n * call, never a directory scan. Never throws.\n */\nexport const createDirectorySessionContextReader = (\n options: DirectorySessionContextReaderOptions,\n): SessionContextReader => {\n const maxBytes = options.maxBytes ?? DEFAULT_SESSION_CONTEXT_MAX_BYTES;\n const budgetMillis = options.budgetMillis ?? DEFAULT_SESSION_CONTEXT_BUDGET_MILLIS;\n\n const readOnce = async (\n providerId: string,\n sessionId: string,\n ): Promise<readonly SessionContextSegment[] | undefined> => {\n const file = sessionContextFilePath(options.dir, providerId, sessionId);\n if (file === undefined) {\n return undefined;\n }\n const text = await readBounded(file, maxBytes);\n if (text === undefined) {\n return undefined;\n }\n let decoded: unknown;\n try {\n decoded = JSON.parse(text);\n } catch {\n return undefined;\n }\n const agentTool = sessionContextAgentTool(providerId);\n return parseSessionContextFile(decoded, {\n ...(agentTool === undefined ? {} : { agentTool }),\n sessionId,\n });\n };\n\n return {\n read: async (request) => {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), budgetMillis);\n timer.unref?.();\n });\n try {\n return await Promise.race([\n readOnce(request.providerId, request.sessionId).catch(() => undefined),\n timeout,\n ]);\n } finally {\n if (timer !== undefined) {\n clearTimeout(timer);\n }\n }\n },\n };\n};\n","import { createErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, Logger, LogLevel, StateRecord, StateStore, StateValue, TelemetryEmitResult, TelemetrySink } from \"./ports.js\";\nimport { stateRecordSchema } from \"./ports.js\";\nimport { LOG_LEVEL_RANK } from \"./ports.js\";\n\nexport type InMemoryStateStoreOptions = {\n readonly clock: Clock;\n /**\n * Fail the next N operations. Used to prove the pipeline degrades instead of\n * throwing when state is unavailable.\n */\n readonly failOperations?: number;\n};\n\nexport interface InMemoryStateStore extends StateStore {\n /** Direct view of stored records, for assertions. */\n snapshot(): ReadonlyMap<string, StateRecord>;\n /** Make the next `count` operations reject. */\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createInMemoryStateStore = (\n options: InMemoryStateStoreOptions,\n): InMemoryStateStore => {\n const records = new Map<string, StateRecord>();\n let failures = options.failOperations ?? 0;\n\n const guard = (operation: string): void => {\n if (failures > 0) {\n failures -= 1;\n throw new Error(`in-memory state store failure injected during ${operation}`);\n }\n };\n\n return {\n read: (key: string): Promise<StateRecord | undefined> => {\n guard(\"read\");\n return Promise.resolve(records.get(key));\n },\n write: (key: string, value: StateValue): Promise<StateRecord> => {\n guard(\"write\");\n const previous = records.get(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n records.set(key, record);\n return Promise.resolve(record);\n },\n delete: (key: string): Promise<void> => {\n guard(\"delete\");\n records.delete(key);\n return Promise.resolve();\n },\n keys: (prefix: string): Promise<readonly string[]> => {\n guard(\"keys\");\n return Promise.resolve([...records.keys()].filter((key) => key.startsWith(prefix)).sort());\n },\n snapshot: (): ReadonlyMap<string, StateRecord> => new Map(records),\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n records.clear();\n },\n };\n};\n\nexport type RecordingTelemetrySinkOptions = {\n /** Reject the next N batches, reporting an export failure. */\n readonly failBatches?: number;\n};\n\nexport interface RecordingTelemetrySink extends TelemetrySink {\n /** Batches in emit order. */\n batches(): readonly (readonly CanonicalEvent[])[];\n /** All events, flattened. */\n events(): readonly CanonicalEvent[];\n flushCount(): number;\n shutdownCount(): number;\n failNext(count: number): void;\n clear(): void;\n}\n\nexport const createRecordingTelemetrySink = (\n options: RecordingTelemetrySinkOptions = {},\n): RecordingTelemetrySink => {\n const batches: (readonly CanonicalEvent[])[] = [];\n let failures = options.failBatches ?? 0;\n let flushes = 0;\n let shutdowns = 0;\n\n return {\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n if (failures > 0) {\n failures -= 1;\n return Promise.resolve({\n accepted: 0,\n rejected: events.length,\n errors: [\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"recording sink rejected the batch\",\n details: { \"export.batch_size\": events.length },\n }),\n ],\n });\n }\n batches.push([...events]);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => {\n flushes += 1;\n return Promise.resolve();\n },\n shutdown: (): Promise<void> => {\n shutdowns += 1;\n return Promise.resolve();\n },\n batches: (): readonly (readonly CanonicalEvent[])[] => batches.map((batch) => [...batch]),\n events: (): readonly CanonicalEvent[] => batches.flat(),\n flushCount: (): number => flushes,\n shutdownCount: (): number => shutdowns,\n failNext: (count: number): void => {\n failures += count;\n },\n clear: (): void => {\n batches.length = 0;\n },\n };\n};\n\n/** Sink that accepts and discards everything. */\nexport const createNullTelemetrySink = (): TelemetrySink => ({\n emit: (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> =>\n Promise.resolve({ accepted: events.length, rejected: 0, errors: [] }),\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n});\n\nexport type LogRecord = {\n readonly level: Exclude<LogLevel, \"silent\">;\n readonly message: string;\n readonly fields?: Attributes;\n};\n\nexport interface RecordingLogger extends Logger {\n records(): readonly LogRecord[];\n clear(): void;\n}\n\nexport const createRecordingLogger = (level: LogLevel = \"debug\"): RecordingLogger => {\n const records: LogRecord[] = [];\n const threshold = LOG_LEVEL_RANK[level];\n const push = (\n entryLevel: Exclude<LogLevel, \"silent\">,\n message: string,\n fields?: Attributes,\n ): void => {\n if (threshold === 0 || LOG_LEVEL_RANK[entryLevel] > threshold) {\n return;\n }\n records.push({ level: entryLevel, message, ...(fields === undefined ? {} : { fields }) });\n };\n\n return {\n error: (message: string, fields?: Attributes): void => {\n push(\"error\", message, fields);\n },\n warn: (message: string, fields?: Attributes): void => {\n push(\"warn\", message, fields);\n },\n info: (message: string, fields?: Attributes): void => {\n push(\"info\", message, fields);\n },\n debug: (message: string, fields?: Attributes): void => {\n push(\"debug\", message, fields);\n },\n records: (): readonly LogRecord[] => [...records],\n clear: (): void => {\n records.length = 0;\n },\n };\n};\n","import { z } from \"zod\";\n\nimport { createErrorInfo } from \"../errors/index.js\";\nimport { identityClaimSchema, type IdentityClaim } from \"../model/identity.js\";\nimport { providerIdSchema, sessionIdSchema, type ProviderId } from \"../model/primitives.js\";\nimport { normalizeUsage, usageReportSchema } from \"../model/usage.js\";\nimport { deriveWorkspaceIdentity } from \"../privacy/workspace.js\";\nimport {\n providerDetectionSchema,\n SILENT_HOOK_RESPONSE,\n type ProviderAdapter,\n type ProviderCapabilities,\n type ProviderContext,\n type ProviderDeliveryClaim,\n type ProviderDetection,\n type ProviderDetectionInput,\n type ProviderHookResponse,\n type ProviderHookResponseInput,\n type ProviderIdentityInput,\n type ProviderParseInput,\n type ProviderParseResult,\n} from \"../providers/adapter.js\";\nimport { createEventFactory } from \"../providers/builder.js\";\n\n/**\n * Synthetic hook payload used by the reference adapter.\n *\n * Provenance: invented for this repository. It resembles no real provider's\n * protocol and contains no captured transcript, path, or credential.\n */\nexport const syntheticPayloadSchema = z.object({\n provider: z.string().min(1),\n sessionId: z.string().min(1),\n event: z.enum([\n \"session.start\",\n \"prompt\",\n \"generation\",\n \"tool\",\n \"subagent\",\n \"compaction\",\n \"session.end\",\n \"noop\",\n ]),\n requestId: z.string().min(1).optional(),\n model: z.string().min(1).optional(),\n promptText: z.string().optional(),\n toolName: z.string().min(1).optional(),\n toolInput: z.unknown().optional(),\n workspaceKey: z.string().min(1).optional(),\n occurredAt: z.number().int().min(0).optional(),\n usage: usageReportSchema.optional(),\n agentVersion: z.string().min(1).optional(),\n});\nexport type SyntheticPayload = z.infer<typeof syntheticPayloadSchema>;\n\nexport const SYNTHETIC_PROVIDER_ID = \"fixture\" as const;\n\nexport const DEFAULT_FIXTURE_CAPABILITIES: ProviderCapabilities = Object.freeze({\n lifecycleEvents: Object.freeze([\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 ] as const),\n usageTemporality: \"delta\",\n reportsCachedInput: true,\n reportsCacheCreation: true,\n cacheCreationAccounting: \"disjoint-from-input\",\n reportsReasoningOutput: true,\n reportsProviderTotal: true,\n reportsCost: false,\n emitsSubagentEvents: true,\n emitsCompactionEvents: true,\n requiresHookResponse: false,\n // The synthetic protocol carries an optional `requestId`, so some payloads are\n // replay-identifiable and some are not — the mixed case a core test wants.\n deliveryIdentifier: \"partial\",\n});\n\nexport type FixtureAdapterOptions = {\n readonly id?: string;\n readonly version?: string;\n readonly capabilities?: Partial<ProviderCapabilities>;\n /** Confidence reported when the payload matches this adapter's provider id. */\n readonly confidence?: ProviderDetection[\"confidence\"];\n /** Replace detection entirely, e.g. to simulate an ambiguous registry. */\n readonly detect?: (input: ProviderDetectionInput, context: ProviderContext) => ProviderDetection;\n /** Extra claims merged after the adapter's own, e.g. to force a conflict. */\n readonly extraClaims?: readonly IdentityClaim[];\n /** Throw from the named method, to exercise containment. */\n readonly throwOn?: \"detect\" | \"identify\" | \"parse\" | \"hookResponse\" | \"deliveryIdentity\";\n /**\n * Replace the delivery claim entirely, e.g. to return one the contract's own\n * component guard must reject.\n */\n readonly deliveryIdentity?: (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ) => ProviderDeliveryClaim | undefined;\n /** Emit a provider-protocol stdout response instead of staying silent. */\n readonly hookResponse?: (\n input: ProviderHookResponseInput,\n context: ProviderContext,\n ) => ProviderHookResponse;\n};\n\n/**\n * Reference adapter over the synthetic payload above.\n *\n * Provider agents can use it to exercise the core contract — registry\n * arbitration, identity resolution, privacy screening, usage derivation — without\n * depending on any real provider protocol.\n */\nexport const createFixtureAdapter = (options: FixtureAdapterOptions = {}): ProviderAdapter => {\n const id: ProviderId = providerIdSchema.parse(options.id ?? SYNTHETIC_PROVIDER_ID);\n const version = options.version ?? \"1.0.0\";\n const capabilities: ProviderCapabilities = {\n ...DEFAULT_FIXTURE_CAPABILITIES,\n ...options.capabilities,\n };\n const confidence = options.confidence ?? \"exact\";\n\n const detect = (input: ProviderDetectionInput, context: ProviderContext): ProviderDetection => {\n if (options.throwOn === \"detect\") {\n throw new Error(\"fixture adapter detect failure\");\n }\n if (options.detect !== undefined) {\n return options.detect(input, context);\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success || parsed.data.provider !== id) {\n return providerDetectionSchema.parse({\n providerId: \"unknown\",\n confidence: \"none\",\n reasons: [\"payload does not match the synthetic fixture protocol\"],\n });\n }\n return providerDetectionSchema.parse({\n providerId: id,\n confidence,\n reasons: [\"payload.provider matches the fixture provider id\"],\n providerVersion: parsed.data.agentVersion ?? \"0.1.0\",\n sourceEventName: parsed.data.event,\n });\n };\n\n const identify = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): readonly IdentityClaim[] => {\n if (options.throwOn === \"identify\") {\n throw new Error(\"fixture adapter identify failure\");\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return options.extraClaims ?? [];\n }\n const payload = parsed.data;\n const occurredAt = payload.occurredAt ?? context.clock.now();\n const sessionId = sessionIdSchema.parse(payload.sessionId);\n const claim = identityClaimSchema.parse({\n source: `adapter:${id}`,\n confidence: input.detection.confidence,\n fields: {\n sessionId,\n invocationId: context.ids.newInvocationId({\n providerId: id,\n sessionId,\n sourceEventName: payload.event,\n occurredAt,\n ...(payload.requestId === undefined ? {} : { discriminator: payload.requestId }),\n }),\n startedAt: occurredAt,\n ...(payload.workspaceKey === undefined\n ? {}\n : {\n workspace: deriveWorkspaceIdentity(context.privacy, {\n kind: \"explicit\",\n value: payload.workspaceKey,\n }),\n }),\n },\n });\n return [claim, ...(options.extraClaims ?? [])];\n };\n\n /**\n * The synthetic protocol's `requestId` names one request, so it identifies a\n * delivery; a payload without one is deliberately left unidentifiable, which is\n * what lets a core test exercise both branches with the same adapter.\n */\n const deliveryIdentity = (\n input: ProviderIdentityInput,\n context: ProviderContext,\n ): ProviderDeliveryClaim | undefined => {\n if (options.throwOn === \"deliveryIdentity\") {\n throw new Error(\"fixture adapter deliveryIdentity failure\");\n }\n if (options.deliveryIdentity !== undefined) {\n return options.deliveryIdentity(input, context);\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success || parsed.data.requestId === undefined) {\n return undefined;\n }\n return {\n sessionId: parsed.data.sessionId,\n sourceEventName: parsed.data.event,\n components: [parsed.data.requestId],\n evidence: [\"payload.requestId names one synthetic request\"],\n };\n };\n\n const parse = (input: ProviderParseInput, context: ProviderContext): ProviderParseResult => {\n if (options.throwOn === \"parse\") {\n throw new Error(\"fixture adapter parse failure\");\n }\n const parsed = syntheticPayloadSchema.safeParse(input.payload);\n if (!parsed.success) {\n return {\n status: \"failed\",\n error: createErrorInfo({\n code: \"invalid-input\",\n phase: \"parsing\",\n detail: \"payload does not match the synthetic fixture protocol\",\n }),\n };\n }\n const payload = parsed.data;\n if (payload.event === \"noop\") {\n return { status: \"ignored\", reason: \"synthetic noop event carries no telemetry\" };\n }\n\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const occurredAt = payload.occurredAt ?? context.clock.now();\n const model = { modelId: payload.model ?? \"synthetic-model-1\" };\n const warnings: string[] = [];\n\n const usage = ((): ReturnType<typeof normalizeUsage> | undefined => {\n if (payload.usage === undefined) {\n return undefined;\n }\n const normalized = normalizeUsage(payload.usage);\n if (normalized.status === \"invalid\") {\n warnings.push(...normalized.issues.map((issue) => issue.message));\n }\n return normalized;\n })();\n const canonicalUsage = usage?.status === \"ok\" ? usage.usage : undefined;\n\n switch (payload.event) {\n case \"session.start\":\n factory.build({\n type: \"session.start\",\n sessionKind: \"non-interactive\",\n agentName: `fixture-${id}`,\n ...(payload.agentVersion === undefined ? {} : { agentVersion: payload.agentVersion }),\n model,\n occurredAt,\n });\n break;\n case \"prompt\":\n factory.build({\n type: \"prompt.submitted\",\n promptSource: \"user\",\n occurredAt,\n ...(payload.promptText === undefined\n ? {}\n : {\n content: context.privacy.describeContent({\n kind: \"prompt\",\n role: \"user\",\n text: payload.promptText,\n }),\n }),\n });\n break;\n case \"generation\": {\n const generationId = payload.requestId ?? context.ids.newOpaqueId([payload.sessionId, \"generation\"]);\n factory.build({ type: \"generation.start\", generationId, model, occurredAt });\n factory.build({\n type: \"generation.end\",\n generationId,\n model,\n outcome: \"ok\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n }\n case \"tool\": {\n const toolCallId = payload.requestId ?? context.ids.newOpaqueId([payload.sessionId, \"tool\"]);\n const toolName = payload.toolName ?? \"synthetic-tool\";\n factory.build({\n type: \"tool.start\",\n toolCallId,\n toolName,\n toolKind: \"other\",\n occurredAt,\n ...(payload.toolInput === undefined\n ? {}\n : {\n input: context.privacy.describeStructured({\n kind: \"tool-input\",\n value: payload.toolInput,\n label: toolName,\n }),\n }),\n });\n factory.build({\n type: \"tool.end\",\n toolCallId,\n toolName,\n outcome: \"ok\",\n occurredAt,\n });\n break;\n }\n case \"subagent\": {\n const subagentInvocationId = context.ids.newInvocationId({\n providerId: id,\n sessionId: payload.sessionId,\n sourceEventName: \"subagent\",\n occurredAt,\n ...(payload.requestId === undefined ? {} : { discriminator: payload.requestId }),\n });\n factory.build({\n type: \"subagent.start\",\n subagentInvocationId,\n delegationDepth: 1,\n occurredAt,\n });\n factory.build({\n type: \"subagent.end\",\n subagentInvocationId,\n outcome: \"ok\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n }\n case \"compaction\":\n factory.build({\n type: \"compaction.performed\",\n trigger: \"automatic\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n case \"session.end\":\n factory.build({\n type: \"session.end\",\n reason: \"completed\",\n occurredAt,\n ...(canonicalUsage === undefined ? {} : { usage: canonicalUsage }),\n });\n break;\n }\n\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\n };\n };\n\n const hookResponse = (\n input: ProviderHookResponseInput,\n context: ProviderContext,\n ): ProviderHookResponse => {\n if (options.throwOn === \"hookResponse\") {\n throw new Error(\"fixture adapter hookResponse failure\");\n }\n if (options.hookResponse !== undefined) {\n return options.hookResponse(input, context);\n }\n return SILENT_HOOK_RESPONSE;\n };\n\n return { id, version, capabilities, detect, identify, deliveryIdentity, parse, hookResponse };\n};\n","import {\n isContentFactConsistent,\n isUnavailableContentFact,\n type ContentDisclosure,\n type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\n\n/** Every content fact attached to an event, regardless of field name. */\nexport const collectEventContentFacts = (event: CanonicalEvent): readonly ContentFact[] => {\n const facts: ContentFact[] = [];\n const push = (fact: ContentFact | undefined): void => {\n if (fact !== undefined) {\n facts.push(fact);\n }\n };\n switch (event.type) {\n case \"prompt.submitted\":\n push(event.content);\n break;\n case \"generation.start\":\n facts.push(...(event.inputContent ?? []));\n break;\n case \"generation.end\":\n facts.push(...(event.outputContent ?? []));\n break;\n case \"tool.start\":\n push(event.input);\n break;\n case \"tool.end\":\n push(event.output);\n break;\n case \"error.raised\":\n push(event.message);\n break;\n default:\n break;\n }\n return facts;\n};\n\n/** Disclosed text across a batch, for assertions about what escaped. */\nexport const collectContentText = (events: readonly CanonicalEvent[]): readonly string[] => {\n const texts: string[] = [];\n for (const event of events) {\n for (const fact of collectEventContentFacts(event)) {\n if (fact.text !== undefined) {\n texts.push(fact.text);\n }\n }\n }\n return texts;\n};\n\nexport type ContentDisclosureViolation = {\n readonly eventId: string;\n readonly eventType: string;\n readonly kind: string;\n readonly disclosure: ContentDisclosure;\n readonly reason: \"unexpected-disclosure\" | \"inconsistent-fact\";\n};\n\n/**\n * Find content facts that disclose more than the expected mode allows.\n *\n * Provider suites are expected to assert this returns nothing under the default\n * `omit` policy.\n */\nexport const findDisclosureViolations = (\n events: readonly CanonicalEvent[],\n expected: ContentDisclosure = \"omitted\",\n): readonly ContentDisclosureViolation[] => {\n const violations: ContentDisclosureViolation[] = [];\n for (const event of events) {\n for (const fact of collectEventContentFacts(event)) {\n if (isUnavailableContentFact(fact)) {\n continue;\n }\n if (fact.disclosure !== expected) {\n violations.push({\n eventId: event.eventId,\n eventType: event.type,\n kind: fact.kind,\n disclosure: fact.disclosure,\n reason: \"unexpected-disclosure\",\n });\n continue;\n }\n if (!isContentFactConsistent(fact)) {\n violations.push({\n eventId: event.eventId,\n eventType: event.type,\n kind: fact.kind,\n disclosure: fact.disclosure,\n reason: \"inconsistent-fact\",\n });\n }\n }\n }\n return violations;\n};\n\n/**\n * Search a serialized batch for a literal substring.\n *\n * Used to prove a secret or prompt fragment is absent from everything a sink\n * would receive, including attributes and extensions.\n */\nexport const batchContains = (events: readonly CanonicalEvent[], needle: string): boolean =>\n JSON.stringify(events).includes(needle);\n","import {\n DEFAULT_CONFIG,\n otelHookConfigSchema,\n type OtelHookConfig,\n type OtelHookConfigPatch,\n} from \"../config/schema.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n invocationIdentitySchema,\n sourceProvenanceSchema,\n unknownWorkspaceIdentity,\n type InvocationIdentity,\n type SourceProvenance,\n} from \"../model/identity.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport { createProviderRegistry, type ProviderAdapter, type ProviderRegistry } from \"../providers/index.js\";\nimport { createFixedClock, type FixedClock } from \"../runtime/clock.js\";\nimport { createOtelHook, type OtelHook } from \"../runtime/hook.js\";\nimport { createDeterministicIdGenerator } from \"../runtime/ids.js\";\nimport {\n createInMemoryStateStore,\n createRecordingLogger,\n createRecordingTelemetrySink,\n type InMemoryStateStore,\n type RecordingLogger,\n type RecordingTelemetrySink,\n} from \"../runtime/memory.js\";\nimport type { IdGenerator, PayloadEnricher, SessionContextReader, WorktreeLocator } from \"../runtime/ports.js\";\n\nexport * from \"./fixture-adapter.js\";\nexport * from \"./assertions.js\";\nexport {\n createFixedClock,\n createInMemoryStateStore,\n createRecordingLogger,\n createRecordingTelemetrySink,\n createDeterministicIdGenerator,\n};\nexport type { FixedClock, InMemoryStateStore, RecordingLogger, RecordingTelemetrySink };\n\n/** Deterministic provenance for hand-built events. */\nexport const createTestProvenance = (\n overrides: Partial<SourceProvenance> = {},\n): SourceProvenance =>\n sourceProvenanceSchema.parse({\n providerId: \"fixture\",\n adapterId: \"fixture\",\n adapterVersion: \"1.0.0\",\n detectionConfidence: \"exact\",\n transport: \"test-fixture\",\n ...overrides,\n });\n\n/** Deterministic identity for hand-built events. */\nexport const createTestIdentity = (\n overrides: Partial<InvocationIdentity> = {},\n): InvocationIdentity =>\n invocationIdentitySchema.parse({\n invocationId: \"inv_test_0000000000000001\",\n sessionId: \"ses_test_0000000000000001\",\n provenance: createTestProvenance(),\n workspace: unknownWorkspaceIdentity(),\n startedAt: 1_700_000_000_000,\n consumerAttributes: {},\n ...overrides,\n });\n\nexport const createTestPrivacyService = (\n patch: Partial<OtelHookConfig[\"privacy\"]> = {},\n): PrivacyService => createPrivacyService({ ...DEFAULT_CONFIG.privacy, ...patch });\n\nexport type TestHarnessOptions = {\n readonly adapters?: readonly ProviderAdapter[];\n readonly registry?: ProviderRegistry;\n /** Shallow-merged over {@link DEFAULT_CONFIG}, then validated. */\n readonly config?: OtelHookConfigPatch;\n readonly clock?: FixedClock;\n readonly ids?: IdGenerator;\n readonly startMillis?: number;\n readonly tickMillis?: number;\n /**\n * Worktree resolution for event targets (ADR 0008). Absent by default, so the\n * harness stays filesystem-free; pass a fake, or the filesystem locator over a\n * temporary directory.\n */\n readonly worktreeLocator?: WorktreeLocator;\n /**\n * Ceiling on target resolution per callback (runtime default 50ms). A test of\n * what a target says, over a real filesystem, raises it so a slow CI runner\n * cannot turn the assertion into a timing race.\n */\n readonly targetResolutionBudgetMillis?: number;\n /** Payload enrichers, as a host would configure them (none by default). */\n readonly payloadEnrichers?: readonly PayloadEnricher[];\n /** Session context reader (none by default), e.g. a fake or the directory reader. */\n readonly sessionContext?: SessionContextReader;\n};\n\nexport type TestHarness = {\n readonly hook: OtelHook;\n readonly sink: RecordingTelemetrySink;\n readonly stateStore: InMemoryStateStore;\n readonly clock: FixedClock;\n readonly ids: IdGenerator;\n readonly privacy: PrivacyService;\n readonly logger: RecordingLogger;\n readonly registry: ProviderRegistry;\n readonly config: OtelHookConfig;\n};\n\nconst mergeConfig = (patch: OtelHookConfigPatch | undefined): OtelHookConfig => {\n if (patch === undefined) {\n return DEFAULT_CONFIG;\n }\n return otelHookConfigSchema.parse({\n exporter: { ...DEFAULT_CONFIG.exporter, ...patch.exporter },\n privacy: {\n ...DEFAULT_CONFIG.privacy,\n ...patch.privacy,\n limits: { ...DEFAULT_CONFIG.privacy.limits, ...patch.privacy?.limits },\n },\n detection: { ...DEFAULT_CONFIG.detection, ...patch.detection },\n diagnostics: { ...DEFAULT_CONFIG.diagnostics, ...patch.diagnostics },\n });\n};\n\n/**\n * Fully wired hook backed by in-memory doubles and a deterministic clock.\n *\n * Nothing here reads the process environment, the filesystem, or the wall clock,\n * so a provider test is reproducible on any machine.\n */\nexport const createTestHook = (options: TestHarnessOptions = {}): TestHarness => {\n const config = mergeConfig(options.config);\n const clock =\n options.clock ??\n createFixedClock({\n startMillis: options.startMillis ?? 1_700_000_000_000,\n tickMillis: options.tickMillis ?? 0,\n });\n const ids = options.ids ?? createDeterministicIdGenerator({ namespace: \"test\" });\n const privacy = createPrivacyService(config.privacy);\n const logger = createRecordingLogger(\"debug\");\n const sink = createRecordingTelemetrySink();\n const stateStore = createInMemoryStateStore({ clock });\n const registry = options.registry ?? createProviderRegistry(options.adapters ?? []);\n\n const hook = createOtelHook({\n sink,\n stateStore,\n config,\n registry,\n clock,\n ids,\n privacy,\n logger,\n ...(options.worktreeLocator === undefined ? {} : { worktreeLocator: options.worktreeLocator }),\n ...(options.targetResolutionBudgetMillis === undefined\n ? {}\n : { targetResolutionBudgetMillis: options.targetResolutionBudgetMillis }),\n ...(options.payloadEnrichers === undefined ? {} : { payloadEnrichers: options.payloadEnrichers }),\n ...(options.sessionContext === undefined ? {} : { sessionContext: options.sessionContext }),\n });\n\n return { hook, sink, stateStore, clock, ids, privacy, logger, registry, config };\n};\n\n/** Convenience re-export so provider suites can type their own helpers. */\nexport type { CanonicalEvent };\n"],"mappings":";AAAA,SAAS,kBAAkB;AAE3B,SAAS,KAAAA,UAAS;;;ACFlB,SAAS,SAAS;AAGX,IAAM,wBAAwB;AAG9B,IAAM,8BAA8B;AAGpC,IAAM,6BAA6B;AAEnC,IAAM,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,IAAI,qBAAqB;AAGxE,IAAM,oBAAoB,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC,EAAE,IAAI,MAAqB;AAI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A,EACpC,CAAC;AACH,QAAM,MAAM,QAAQ,OAAO,+BAA+B,EAAE,WAAW,OAAO,CAAC;AAC/E,QAAM,UAAU,qBAAqB,OAAO,OAAO;AACnD,QAAM,SAAS,sBAAsB,OAAO;AAC5C,QAAM,OAAO,6BAA6B;AAC1C,QAAM,aAAa,yBAAyB,EAAE,MAAM,CAAC;AACrD,QAAM,WAAW,QAAQ,YAAY,uBAAuB,QAAQ,YAAY,CAAC,CAAC;AAElF,QAAM,OAAO,eAAe;AAAA,IAC1B;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,GAAI,QAAQ,oBAAoB,SAAY,CAAC,IAAI,EAAE,iBAAiB,QAAQ,gBAAgB;AAAA,IAC5F,GAAI,QAAQ,iCAAiC,SACzC,CAAC,IACD,EAAE,8BAA8B,QAAQ,6BAA6B;AAAA,IACzE,GAAI,QAAQ,qBAAqB,SAAY,CAAC,IAAI,EAAE,kBAAkB,QAAQ,iBAAiB;AAAA,IAC/F,GAAI,QAAQ,mBAAmB,SAAY,CAAC,IAAI,EAAE,gBAAgB,QAAQ,eAAe;AAAA,EAC3F,CAAC;AAED,SAAO,EAAE,MAAM,MAAM,YAAY,OAAO,KAAK,SAAS,QAAQ,UAAU,OAAO;AACjF;","names":["z","z","z","z","z","z","z","z","z","z","parsed","z","z","bounded","path","z","z","z","z","z","z","z","z","z","z","z","event","z","z","z","z","asRecord","asRecord","messageText","asRecord","createHash","z","z","event","sessionStartPayloadSchema","sessionEndPayloadSchema","preToolUsePayloadSchema","postToolUsePayloadSchema","postToolUseFailurePayloadSchema","subagentStartPayloadSchema","subagentStopPayloadSchema","preCompactPayloadSchema","stopPayloadSchema","UNKNOWN_MODEL","detect","identify","parse","hookResponse","z","deliveryComponents","asRecord","nonEmptyString","asRecord","createHash","open","stat","path","z","BUILT_IN_TOOL_KIND","detect","identify","parse","hookResponse","z","commonFields","preToolUsePayloadSchema","postToolUsePayloadSchema","stopPayloadSchema","detect","identify","parse","hookResponse","z","createHash","createHash","z","z","path","event","resolve","open","path","z","z","event","z","event","batch","z","z","detect","identify","parse","hookResponse","event"]}