@osfactory/otel-hook 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1020 -0
  3. package/dist/adapter-DIgRACtL.d.ts +303 -0
  4. package/dist/cli.js +12607 -0
  5. package/dist/cli.js.map +1 -0
  6. package/dist/config.d.ts +233 -0
  7. package/dist/config.js +996 -0
  8. package/dist/config.js.map +1 -0
  9. package/dist/content-CoB7aNP1.d.ts +118 -0
  10. package/dist/diagnostics.d.ts +58 -0
  11. package/dist/diagnostics.js +46 -0
  12. package/dist/diagnostics.js.map +1 -0
  13. package/dist/errors.d.ts +91 -0
  14. package/dist/errors.js +322 -0
  15. package/dist/errors.js.map +1 -0
  16. package/dist/events-VxBnDFaO.d.ts +2044 -0
  17. package/dist/filesystem-store-J8jjDMTh.d.ts +65 -0
  18. package/dist/hook-CGpo-vks.d.ts +292 -0
  19. package/dist/identity-BrVBs901.d.ts +227 -0
  20. package/dist/index.d.ts +44 -0
  21. package/dist/index.js +11798 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/install.d.ts +1021 -0
  24. package/dist/install.js +3271 -0
  25. package/dist/install.js.map +1 -0
  26. package/dist/integration.d.ts +303 -0
  27. package/dist/integration.js +5942 -0
  28. package/dist/integration.js.map +1 -0
  29. package/dist/keys-Dej5bN3L.d.ts +7 -0
  30. package/dist/lifecycle.d.ts +428 -0
  31. package/dist/lifecycle.js +1077 -0
  32. package/dist/lifecycle.js.map +1 -0
  33. package/dist/memory-DXVBc8V9.d.ts +94 -0
  34. package/dist/model.d.ts +45 -0
  35. package/dist/model.js +1023 -0
  36. package/dist/model.js.map +1 -0
  37. package/dist/otlp-log-sink-CeIFDDpn.d.ts +457 -0
  38. package/dist/payload-CHr53E_v.d.ts +201 -0
  39. package/dist/policy-D1CrlYn3.d.ts +73 -0
  40. package/dist/ports-Q8x0ODhs.d.ts +200 -0
  41. package/dist/primitives-CJ8-rn-f.d.ts +75 -0
  42. package/dist/privacy.d.ts +51 -0
  43. package/dist/privacy.js +633 -0
  44. package/dist/privacy.js.map +1 -0
  45. package/dist/providers.d.ts +257 -0
  46. package/dist/providers.js +4398 -0
  47. package/dist/providers.js.map +1 -0
  48. package/dist/registry-BzYmC9OC.d.ts +49 -0
  49. package/dist/runtime.d.ts +32 -0
  50. package/dist/runtime.js +2907 -0
  51. package/dist/runtime.js.map +1 -0
  52. package/dist/schema-Cn0-xz8L.d.ts +224 -0
  53. package/dist/semconv-Baoz-0OI.d.ts +188 -0
  54. package/dist/service-j4jEO6cZ.d.ts +68 -0
  55. package/dist/state.d.ts +36 -0
  56. package/dist/state.js +710 -0
  57. package/dist/state.js.map +1 -0
  58. package/dist/taxonomy-DwhTtuWd.d.ts +87 -0
  59. package/dist/telemetry.d.ts +77 -0
  60. package/dist/telemetry.js +2294 -0
  61. package/dist/telemetry.js.map +1 -0
  62. package/dist/testing.d.ts +155 -0
  63. package/dist/testing.js +6513 -0
  64. package/dist/testing.js.map +1 -0
  65. package/package.json +124 -0
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/config/resource-attributes.ts","../src/model/primitives.ts","../src/privacy/policy.ts","../src/cli/args.ts","../src/cli/context.ts","../src/errors/index.ts","../src/errors/taxonomy.ts","../src/config/environment.ts","../src/config/resolve.ts","../src/config/schema.ts","../src/runtime/ports.ts","../src/model/usage.ts","../src/runtime/logger.ts","../src/diagnostics/health.ts","../src/model/version.ts","../src/privacy/service.ts","../src/model/extensions.ts","../src/model/identity.ts","../src/privacy/workspace.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/model/content.ts","../src/providers/builder.ts","../src/providers/antigravity/payload.ts","../src/providers/antigravity/delivery.ts","../src/providers/antigravity/adapter.ts","../src/providers/antigravity/maturity.ts","../src/providers/claude/capabilities.ts","../src/providers/claude/schema.ts","../src/providers/claude/delivery.ts","../src/providers/claude/detect.ts","../src/providers/claude/identity.ts","../src/providers/claude/tool-kind.ts","../src/providers/claude/usage.ts","../src/providers/claude/events.ts","../src/providers/claude/adapter.ts","../src/providers/codex/payload.ts","../src/providers/codex/delivery.ts","../src/providers/codex/tool-kind.ts","../src/providers/codex/usage.ts","../src/providers/codex/version.ts","../src/providers/codex/adapter.ts","../src/providers/cursor/payload.ts","../src/providers/cursor/delivery.ts","../src/providers/cursor/usage.ts","../src/providers/cursor/adapter.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/registry.ts","../src/providers/defaults.ts","../src/runtime/clock.ts","../src/state/filesystem-store.ts","../src/state/async-lock.ts","../src/state/keys.ts","../src/state/store.ts","../src/telemetry/spool-queue.ts","../src/telemetry/durable-log-spool.ts","../src/telemetry/durable-spool.ts","../src/telemetry/otlp-log-sink.ts","../node_modules/@opentelemetry/core/src/common/time.ts","../node_modules/@opentelemetry/core/src/ExportResult.ts","../src/telemetry/exporter-resource.ts","../src/telemetry/log-records.ts","../src/telemetry/semconv.ts","../src/telemetry/otlp-sink.ts","../src/version.ts","../src/cli/doctor.ts","../src/providers/antigravity/registration.ts","../src/providers/hook-document.ts","../src/providers/claude/registration.ts","../src/providers/codex/registration.ts","../src/providers/cursor/registration.ts","../src/providers/gemini/setup.ts","../src/install/planners.ts","../src/install/support.ts","../src/install/scopes.ts","../src/install/document.ts","../src/install/file-lock.ts","../src/install/lifecycle.ts","../src/cli/providers.ts","../src/cli/registration.ts","../src/cli/run.ts","../src/lifecycle/dedup.ts","../src/lifecycle/keys.ts","../src/lifecycle/janitor.ts","../src/lifecycle/span-correlator.ts","../src/lifecycle/usage-accumulator.ts","../src/runtime/hook.ts","../src/runtime/delivery.ts","../src/runtime/ids.ts","../src/telemetry/signal-fanout.ts","../src/integration/hook-runtime.ts","../src/cli/detection.ts","../src/cli/environment-view.ts","../src/cli/identity.ts","../src/cli/stdin.ts","../src/cli/main.ts","../src/cli.ts"],"sourcesContent":["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\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","/**\n * Pure command-line parser.\n *\n * Separated from every command implementation so argument handling can be\n * tested without a subprocess, a filesystem, or a collector, and so nothing in\n * the parser can reach `process` — the CLI is handed its argv, environment,\n * and streams (see ADR 0001 on ambient state).\n */\n\nimport {\n checkResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTES,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL,\n} from \"../config/resource-attributes.js\";\n\nexport const CLI_COMMANDS = [\n \"run\",\n \"doctor\",\n \"providers\",\n \"setup\",\n \"diagnose\",\n \"uninstall\",\n] as const;\nexport type CliCommandName = (typeof CLI_COMMANDS)[number];\n\n/** Which of a provider's two documented configuration files to act on. */\nexport type CliRegistrationScope = \"global\" | \"project\";\n\n/** Exporter and runtime policy. Deliberately holds no identity field (ADR 0001). */\nexport type CliPolicyFlags = {\n readonly configFile?: string;\n readonly endpoint?: string;\n readonly protocol?: \"http/protobuf\" | \"http/json\" | \"none\";\n readonly serviceName?: string;\n readonly serviceNamespace?: string;\n readonly timeoutMillis?: number;\n readonly exportDisabled?: boolean;\n readonly contentMode?: string;\n readonly logLevel?: string;\n /** Header *values*, kept out of any resolved-config snapshot. */\n readonly headers: Readonly<Record<string, string>>;\n /**\n * Custom OTLP resource attributes describing this deployment. Exporter\n * policy, not identity, and a different flag and field from a run command's\n * `consumerAttributes`.\n */\n readonly resourceAttributes: Readonly<Record<string, string>>;\n readonly stateDir?: string;\n readonly installationId?: string;\n readonly spoolDisabled?: boolean;\n readonly flushTimeoutMillis?: number;\n readonly includeExperimental?: boolean;\n /** Enable the OTLP logs signal alongside traces. Off unless asked for. */\n readonly logsEnabled?: boolean;\n /** Full logs URL. Derived from `endpoint` when absent. */\n readonly logsEndpoint?: string;\n /**\n * Permit disclosed content text in a log body.\n *\n * A separate flag from `--content-mode` because they answer different questions:\n * that one decides what the privacy service discloses at all, this one decides\n * whether the logs pipeline may carry it. Both are needed for a body to appear.\n */\n readonly logsIncludeContent?: boolean;\n};\n\n/**\n * Immutable invocation identity asserted by the caller. Separate type from\n * {@link CliPolicyFlags} with no shared field names, so no configuration path\n * can set identity and no identity path can set configuration.\n */\nexport type CliIdentityFlags = {\n readonly sessionId?: string;\n readonly invocationId?: string;\n readonly parentInvocationId?: string;\n readonly rootSessionId?: string;\n readonly agentInstanceId?: string;\n readonly identityFile?: string;\n};\n\nexport type CliRunCommand = {\n readonly name: \"run\";\n readonly providerId?: string;\n readonly transport: \"hook-stdin\" | \"cli-argument\" | \"library-call\";\n readonly identity: CliIdentityFlags;\n readonly policy: CliPolicyFlags;\n readonly callbackId?: string;\n readonly callbackScope?: string;\n /** Report every callback that could not be deduplicated, and why. */\n readonly requireCallbackId?: boolean;\n /** Do not normalize a delivery id from the payload when none is supplied. */\n readonly noDeriveCallbackId?: boolean;\n readonly consumerAttributes: Readonly<Record<string, string>>;\n readonly maxInputBytes: number;\n};\n\nexport type CliDoctorCommand = {\n readonly name: \"doctor\";\n readonly json: boolean;\n readonly policy: CliPolicyFlags;\n};\n\nexport type CliProvidersCommand = {\n readonly name: \"providers\";\n readonly json: boolean;\n readonly includeExperimental: boolean;\n};\n\n/**\n * `setup`, `diagnose`, and `uninstall` share one command type because they take\n * the same target selection and differ only in what they do once a target is\n * resolved — which is also how `install/lifecycle.ts` implements them.\n */\nexport type CliRegistrationCommand = {\n readonly name: \"setup\" | \"diagnose\" | \"uninstall\";\n readonly json: boolean;\n readonly dryRun: boolean;\n /** Empty means \"every provider with a verified configuration path\" (diagnose only). */\n readonly providerIds: readonly string[];\n readonly scopes: readonly CliRegistrationScope[];\n readonly projectDir?: string;\n readonly homeDir?: string;\n /** Overrides the provider's documented configuration path. */\n readonly settingsFile?: string;\n readonly hookCommand?: string;\n readonly events?: readonly string[];\n readonly matcher?: string;\n readonly timeoutSeconds?: number;\n readonly managedMarker?: string;\n};\n\nexport type CliCommand =\n | CliRunCommand\n | CliDoctorCommand\n | CliProvidersCommand\n | CliRegistrationCommand;\n\nexport type CliParseResult =\n | { readonly status: \"command\"; readonly command: CliCommand }\n | { readonly status: \"version\" }\n | { readonly status: \"help\"; readonly topic?: CliCommandName }\n | { readonly status: \"error\"; readonly errors: readonly string[] };\n\n/** Default cap on stdin. One hook payload is kilobytes; a megabyte is generous. */\nexport const DEFAULT_MAX_INPUT_BYTES = 1_048_576;\nexport const MAX_ALLOWED_INPUT_BYTES = 16 * 1_048_576;\n\nconst VALUE_FLAGS = new Set([\n \"--provider\",\n \"--transport\",\n \"--session-id\",\n \"--invocation-id\",\n \"--parent-invocation-id\",\n \"--root-session-id\",\n \"--agent-instance-id\",\n \"--identity-file\",\n \"--callback-id\",\n \"--callback-scope\",\n \"--config-file\",\n \"--endpoint\",\n \"--protocol\",\n \"--service-name\",\n \"--service-namespace\",\n \"--timeout-ms\",\n \"--content-mode\",\n \"--log-level\",\n \"--header\",\n \"--attr\",\n \"--resource-attr\",\n \"--state-dir\",\n \"--installation-id\",\n \"--flush-timeout-ms\",\n \"--logs-endpoint\",\n \"--max-input-bytes\",\n \"--scope\",\n \"--project-dir\",\n \"--home-dir\",\n \"--settings-file\",\n \"--hook-command\",\n \"--event\",\n \"--matcher\",\n \"--timeout-seconds\",\n \"--managed-marker\",\n]);\n\nconst BOOLEAN_FLAGS = new Set([\n \"--json\",\n \"--no-export\",\n \"--no-spool\",\n \"--logs\",\n \"--no-logs\",\n \"--logs-content\",\n \"--include-experimental\",\n \"--no-experimental\",\n \"--dry-run\",\n \"--require-callback-id\",\n \"--no-derive-callback-id\",\n]);\n\ntype Tokenized = {\n readonly values: ReadonlyMap<string, readonly string[]>;\n readonly booleans: ReadonlySet<string>;\n readonly errors: readonly string[];\n};\n\nconst tokenize = (argv: readonly string[]): Tokenized => {\n const values = new Map<string, string[]>();\n const booleans = new Set<string>();\n const errors: string[] = [];\n\n for (let index = 0; index < argv.length; index += 1) {\n const token = argv[index];\n if (token === undefined) {\n continue;\n }\n if (!token.startsWith(\"--\")) {\n errors.push(`unexpected positional argument \"${token}\"`);\n continue;\n }\n\n const equals = token.indexOf(\"=\");\n const flag = equals === -1 ? token : token.slice(0, equals);\n const inlineValue = equals === -1 ? undefined : token.slice(equals + 1);\n\n if (BOOLEAN_FLAGS.has(flag)) {\n if (inlineValue !== undefined) {\n errors.push(`flag ${flag} does not take a value`);\n continue;\n }\n booleans.add(flag);\n continue;\n }\n\n if (!VALUE_FLAGS.has(flag)) {\n errors.push(`unknown flag ${flag}`);\n continue;\n }\n\n let value = inlineValue;\n if (value === undefined) {\n const next = argv[index + 1];\n if (next === undefined || next.startsWith(\"--\")) {\n errors.push(`flag ${flag} requires a value`);\n continue;\n }\n value = next;\n index += 1;\n }\n const existing = values.get(flag) ?? [];\n existing.push(value);\n values.set(flag, existing);\n }\n\n return { values, booleans, errors };\n};\n\nconst single = (\n tokens: Tokenized,\n flag: string,\n errors: string[],\n): string | undefined => {\n const found = tokens.values.get(flag);\n if (found === undefined) {\n return undefined;\n }\n if (found.length > 1) {\n errors.push(`flag ${flag} was given ${String(found.length)} times; it accepts one value`);\n }\n return found[found.length - 1];\n};\n\nconst integer = (\n tokens: Tokenized,\n flag: string,\n errors: string[],\n bounds: { readonly min: number; readonly max: number },\n): number | undefined => {\n const raw = single(tokens, flag, errors);\n if (raw === undefined) {\n return undefined;\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < bounds.min || parsed > bounds.max) {\n errors.push(\n `flag ${flag} expects an integer between ${String(bounds.min)} and ${String(bounds.max)}, got \"${raw}\"`,\n );\n return undefined;\n }\n return parsed;\n};\n\nconst keyValuePairs = (\n tokens: Tokenized,\n flag: string,\n errors: string[],\n): Readonly<Record<string, string>> => {\n const pairs: Record<string, string> = {};\n for (const entry of tokens.values.get(flag) ?? []) {\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n errors.push(`flag ${flag} expects key=value, got \"${entry}\"`);\n continue;\n }\n pairs[entry.slice(0, equals)] = entry.slice(equals + 1);\n }\n return pairs;\n};\n\n/**\n * Parse repeated `--resource-attr key=value` flags.\n *\n * Separate from {@link keyValuePairs} because these pairs are validated: a\n * reserved, malformed, or secret-looking key is a usage error the operator can\n * fix now, rather than a silently dropped attribute discovered later in a\n * collector. Keys appear in the error text — the operator just typed them —\n * but values never do.\n */\nconst resourceAttributePairs = (\n tokens: Tokenized,\n errors: string[],\n): Readonly<Record<string, string>> => {\n const pairs: Record<string, string> = {};\n for (const entry of tokens.values.get(\"--resource-attr\") ?? []) {\n const equals = entry.indexOf(\"=\");\n if (equals <= 0) {\n errors.push(\"flag --resource-attr expects key=value\");\n continue;\n }\n const key = entry.slice(0, equals).trim();\n const value = entry.slice(equals + 1);\n const rejection = checkResourceAttributeKey(key);\n if (rejection !== undefined) {\n errors.push(\n `flag --resource-attr rejected key \"${key}\": ${RESOURCE_ATTRIBUTE_KEY_REJECTION_DETAIL[rejection]}`,\n );\n continue;\n }\n if (value.length > MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) {\n errors.push(\n `flag --resource-attr value for \"${key}\" exceeds ${String(MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH)} characters`,\n );\n continue;\n }\n pairs[key] = value;\n }\n if (Object.keys(pairs).length > MAX_RESOURCE_ATTRIBUTES) {\n errors.push(\n `flag --resource-attr accepts at most ${String(MAX_RESOURCE_ATTRIBUTES)} attributes`,\n );\n }\n return pairs;\n};\n\nconst parsePolicy = (tokens: Tokenized, errors: string[]): CliPolicyFlags => {\n const protocolRaw = single(tokens, \"--protocol\", errors);\n let protocol: CliPolicyFlags[\"protocol\"];\n if (protocolRaw !== undefined) {\n if (protocolRaw === \"http/protobuf\" || protocolRaw === \"http/json\" || protocolRaw === \"none\") {\n protocol = protocolRaw;\n } else {\n errors.push(`flag --protocol expects http/protobuf, http/json, or none, got \"${protocolRaw}\"`);\n }\n }\n\n const includeExperimental = tokens.booleans.has(\"--include-experimental\")\n ? true\n : tokens.booleans.has(\"--no-experimental\")\n ? false\n : undefined;\n if (tokens.booleans.has(\"--include-experimental\") && tokens.booleans.has(\"--no-experimental\")) {\n errors.push(\"flags --include-experimental and --no-experimental cannot both be given\");\n }\n\n const configFile = single(tokens, \"--config-file\", errors);\n const endpoint = single(tokens, \"--endpoint\", errors);\n const serviceName = single(tokens, \"--service-name\", errors);\n const serviceNamespace = single(tokens, \"--service-namespace\", errors);\n const contentMode = single(tokens, \"--content-mode\", errors);\n const logLevel = single(tokens, \"--log-level\", errors);\n const stateDir = single(tokens, \"--state-dir\", errors);\n const installationId = single(tokens, \"--installation-id\", errors);\n const timeoutMillis = integer(tokens, \"--timeout-ms\", errors, { min: 1, max: 600_000 });\n const flushTimeoutMillis = integer(tokens, \"--flush-timeout-ms\", errors, { min: 1, max: 60_000 });\n const logsEndpoint = single(tokens, \"--logs-endpoint\", errors);\n\n const logsEnabled = tokens.booleans.has(\"--logs\")\n ? true\n : tokens.booleans.has(\"--no-logs\")\n ? false\n : undefined;\n if (tokens.booleans.has(\"--logs\") && tokens.booleans.has(\"--no-logs\")) {\n errors.push(\"flags --logs and --no-logs cannot both be given\");\n }\n\n return {\n ...(configFile === undefined ? {} : { configFile }),\n ...(endpoint === undefined ? {} : { endpoint }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n ...(timeoutMillis === undefined ? {} : { timeoutMillis }),\n ...(tokens.booleans.has(\"--no-export\") ? { exportDisabled: true } : {}),\n ...(contentMode === undefined ? {} : { contentMode }),\n ...(logLevel === undefined ? {} : { logLevel }),\n headers: keyValuePairs(tokens, \"--header\", errors),\n resourceAttributes: resourceAttributePairs(tokens, errors),\n ...(stateDir === undefined ? {} : { stateDir }),\n ...(installationId === undefined ? {} : { installationId }),\n ...(tokens.booleans.has(\"--no-spool\") ? { spoolDisabled: true } : {}),\n ...(flushTimeoutMillis === undefined ? {} : { flushTimeoutMillis }),\n ...(includeExperimental === undefined ? {} : { includeExperimental }),\n ...(logsEnabled === undefined ? {} : { logsEnabled }),\n ...(logsEndpoint === undefined ? {} : { logsEndpoint }),\n ...(tokens.booleans.has(\"--logs-content\") ? { logsIncludeContent: true } : {}),\n };\n};\n\nconst parseIdentity = (tokens: Tokenized, errors: string[]): CliIdentityFlags => {\n const sessionId = single(tokens, \"--session-id\", errors);\n const invocationId = single(tokens, \"--invocation-id\", errors);\n const parentInvocationId = single(tokens, \"--parent-invocation-id\", errors);\n const rootSessionId = single(tokens, \"--root-session-id\", errors);\n const agentInstanceId = single(tokens, \"--agent-instance-id\", errors);\n const identityFile = single(tokens, \"--identity-file\", errors);\n return {\n ...(sessionId === undefined ? {} : { sessionId }),\n ...(invocationId === undefined ? {} : { invocationId }),\n ...(parentInvocationId === undefined ? {} : { parentInvocationId }),\n ...(rootSessionId === undefined ? {} : { rootSessionId }),\n ...(agentInstanceId === undefined ? {} : { agentInstanceId }),\n ...(identityFile === undefined ? {} : { identityFile }),\n };\n};\n\nconst rejectFlagsFor = (\n command: CliCommandName,\n tokens: Tokenized,\n allowed: ReadonlySet<string>,\n errors: string[],\n): void => {\n for (const flag of [...tokens.values.keys(), ...tokens.booleans]) {\n if (!allowed.has(flag)) {\n errors.push(`flag ${flag} is not accepted by \"${command}\"`);\n }\n }\n};\n\n/**\n * Listed explicitly rather than derived from {@link VALUE_FLAGS}: that set is\n * the tokenizer's vocabulary for *every* command, so deriving from it would\n * silently make each new command's flags acceptable to `run` too — including\n * the registration flags, which must never be accepted by `run`.\n */\nconst RUN_FLAGS: ReadonlySet<string> = new Set([\n \"--provider\",\n \"--transport\",\n \"--session-id\",\n \"--invocation-id\",\n \"--parent-invocation-id\",\n \"--root-session-id\",\n \"--agent-instance-id\",\n \"--identity-file\",\n \"--callback-id\",\n \"--callback-scope\",\n \"--config-file\",\n \"--endpoint\",\n \"--protocol\",\n \"--service-name\",\n \"--service-namespace\",\n \"--timeout-ms\",\n \"--content-mode\",\n \"--log-level\",\n \"--header\",\n \"--attr\",\n \"--resource-attr\",\n \"--state-dir\",\n \"--installation-id\",\n \"--flush-timeout-ms\",\n \"--logs\",\n \"--no-logs\",\n \"--logs-endpoint\",\n \"--logs-content\",\n \"--max-input-bytes\",\n \"--no-export\",\n \"--no-spool\",\n \"--include-experimental\",\n \"--no-experimental\",\n \"--require-callback-id\",\n \"--no-derive-callback-id\",\n]);\nconst DOCTOR_FLAGS: ReadonlySet<string> = new Set([\n \"--json\",\n \"--config-file\",\n \"--endpoint\",\n \"--protocol\",\n \"--service-name\",\n \"--service-namespace\",\n \"--timeout-ms\",\n \"--no-export\",\n \"--content-mode\",\n \"--log-level\",\n \"--header\",\n \"--resource-attr\",\n \"--state-dir\",\n \"--installation-id\",\n \"--no-spool\",\n \"--flush-timeout-ms\",\n \"--logs\",\n \"--no-logs\",\n \"--logs-endpoint\",\n \"--logs-content\",\n \"--include-experimental\",\n \"--no-experimental\",\n]);\nconst PROVIDERS_FLAGS: ReadonlySet<string> = new Set([\"--json\", \"--include-experimental\", \"--no-experimental\"]);\nconst REGISTRATION_FLAGS: ReadonlySet<string> = new Set([\n \"--json\",\n \"--dry-run\",\n \"--provider\",\n \"--scope\",\n \"--project-dir\",\n \"--home-dir\",\n \"--settings-file\",\n \"--hook-command\",\n \"--event\",\n \"--matcher\",\n \"--timeout-seconds\",\n \"--managed-marker\",\n]);\n\nconst REGISTRATION_COMMANDS: ReadonlySet<string> = new Set([\"setup\", \"diagnose\", \"uninstall\"]);\n\nconst multiple = (tokens: Tokenized, flag: string): readonly string[] =>\n tokens.values.get(flag) ?? [];\n\nconst parseScopes = (\n raw: string | undefined,\n fallback: readonly CliRegistrationScope[],\n errors: string[],\n): readonly CliRegistrationScope[] => {\n if (raw === undefined) {\n return fallback;\n }\n if (raw === \"global\" || raw === \"project\") {\n return [raw];\n }\n if (raw === \"all\") {\n return [\"global\", \"project\"];\n }\n errors.push(`flag --scope expects global, project, or all, got \"${raw}\"`);\n return fallback;\n};\n\nconst parseRegistrationCommand = (\n name: CliRegistrationCommand[\"name\"],\n tokens: Tokenized,\n errors: string[],\n): CliParseResult => {\n rejectFlagsFor(name, tokens, REGISTRATION_FLAGS, errors);\n\n const providerIds = multiple(tokens, \"--provider\");\n // `setup` and `uninstall` mutate a file, so they never guess which one:\n // \"every provider I could find\" is a reasonable default for a report and a\n // bad one for a write.\n if (name !== \"diagnose\" && providerIds.length === 0) {\n errors.push(`\"${name}\" requires --provider <id>`);\n }\n\n const events = multiple(tokens, \"--event\");\n if (events.length > 0 && name === \"diagnose\") {\n errors.push(\"flag --event is not accepted by \\\"diagnose\\\"; it reports the provider's own event set\");\n }\n\n // Project scope by default for the mutating commands: writing into a\n // developer's home directory is the surprising choice, so it is opt-in.\n const scopes = parseScopes(\n single(tokens, \"--scope\", errors),\n name === \"diagnose\" ? ([\"global\", \"project\"] as const) : ([\"project\"] as const),\n errors,\n );\n\n const projectDir = single(tokens, \"--project-dir\", errors);\n const homeDir = single(tokens, \"--home-dir\", errors);\n const settingsFile = single(tokens, \"--settings-file\", errors);\n const hookCommand = single(tokens, \"--hook-command\", errors);\n const matcher = single(tokens, \"--matcher\", errors);\n const managedMarker = single(tokens, \"--managed-marker\", errors);\n const timeoutSeconds = integer(tokens, \"--timeout-seconds\", errors, { min: 1, max: 3_600 });\n\n if (settingsFile !== undefined && scopes.length > 1) {\n errors.push(\"flag --settings-file names one document, so --scope all cannot be used with it\");\n }\n if (tokens.booleans.has(\"--dry-run\") && name === \"diagnose\") {\n errors.push('flag --dry-run is not accepted by \"diagnose\"; it never writes');\n }\n\n if (errors.length > 0) {\n return { status: \"error\", errors };\n }\n\n return {\n status: \"command\",\n command: {\n name,\n json: tokens.booleans.has(\"--json\"),\n dryRun: tokens.booleans.has(\"--dry-run\"),\n providerIds,\n scopes,\n ...(projectDir === undefined ? {} : { projectDir }),\n ...(homeDir === undefined ? {} : { homeDir }),\n ...(settingsFile === undefined ? {} : { settingsFile }),\n ...(hookCommand === undefined ? {} : { hookCommand }),\n ...(events.length === 0 ? {} : { events }),\n ...(matcher === undefined ? {} : { matcher }),\n ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),\n ...(managedMarker === undefined ? {} : { managedMarker }),\n },\n };\n};\n\nexport const parseCliArgs = (argv: readonly string[]): CliParseResult => {\n const [first, ...rest] = argv;\n\n if (first === undefined) {\n return { status: \"help\" };\n }\n if (first === \"--version\" || first === \"-v\") {\n return argv.length === 1\n ? { status: \"version\" }\n : { status: \"error\", errors: [\"--version takes no other arguments\"] };\n }\n if (first === \"--help\" || first === \"-h\") {\n return { status: \"help\" };\n }\n if (!CLI_COMMANDS.includes(first as CliCommandName)) {\n return {\n status: \"error\",\n errors: [`unknown command \"${first}\"; expected one of ${CLI_COMMANDS.join(\", \")}`],\n };\n }\n const command = first as CliCommandName;\n if (rest.includes(\"--help\") || rest.includes(\"-h\")) {\n return { status: \"help\", topic: command };\n }\n\n const tokens = tokenize(rest);\n const errors = [...tokens.errors];\n\n if (command === \"providers\") {\n rejectFlagsFor(command, tokens, PROVIDERS_FLAGS, errors);\n if (errors.length > 0) {\n return { status: \"error\", errors };\n }\n return {\n status: \"command\",\n command: {\n name: \"providers\",\n json: tokens.booleans.has(\"--json\"),\n includeExperimental: !tokens.booleans.has(\"--no-experimental\"),\n },\n };\n }\n\n if (REGISTRATION_COMMANDS.has(command)) {\n return parseRegistrationCommand(command as CliRegistrationCommand[\"name\"], tokens, errors);\n }\n\n if (command === \"doctor\") {\n rejectFlagsFor(command, tokens, DOCTOR_FLAGS, errors);\n const policy = parsePolicy(tokens, errors);\n if (errors.length > 0) {\n return { status: \"error\", errors };\n }\n return {\n status: \"command\",\n command: { name: \"doctor\", json: tokens.booleans.has(\"--json\"), policy },\n };\n }\n\n rejectFlagsFor(command, tokens, RUN_FLAGS, errors);\n const transportRaw = single(tokens, \"--transport\", errors) ?? \"hook-stdin\";\n if (\n transportRaw !== \"hook-stdin\" &&\n transportRaw !== \"cli-argument\" &&\n transportRaw !== \"library-call\"\n ) {\n errors.push(\n `flag --transport expects hook-stdin, cli-argument, or library-call, got \"${transportRaw}\"`,\n );\n }\n const providerId = single(tokens, \"--provider\", errors);\n const callbackId = single(tokens, \"--callback-id\", errors);\n const callbackScope = single(tokens, \"--callback-scope\", errors);\n if (callbackScope !== undefined && callbackId === undefined) {\n errors.push(\"flag --callback-scope requires --callback-id\");\n }\n const requireCallbackId = tokens.booleans.has(\"--require-callback-id\");\n const noDeriveCallbackId = tokens.booleans.has(\"--no-derive-callback-id\");\n const maxInputBytes =\n integer(tokens, \"--max-input-bytes\", errors, { min: 1, max: MAX_ALLOWED_INPUT_BYTES }) ??\n DEFAULT_MAX_INPUT_BYTES;\n const identity = parseIdentity(tokens, errors);\n const policy = parsePolicy(tokens, errors);\n const consumerAttributes = keyValuePairs(tokens, \"--attr\", errors);\n\n if (errors.length > 0) {\n return { status: \"error\", errors };\n }\n\n return {\n status: \"command\",\n command: {\n name: \"run\",\n ...(providerId === undefined ? {} : { providerId }),\n transport: transportRaw as CliRunCommand[\"transport\"],\n identity,\n policy,\n ...(callbackId === undefined ? {} : { callbackId }),\n ...(callbackScope === undefined ? {} : { callbackScope }),\n ...(requireCallbackId ? { requireCallbackId } : {}),\n ...(noDeriveCallbackId ? { noDeriveCallbackId } : {}),\n consumerAttributes,\n maxInputBytes,\n },\n };\n};\n\nexport const CLI_USAGE = `otel-hook — provider-neutral coding-agent telemetry\n\nUsage:\n otel-hook run [--provider <id>] [options] process one hook payload from stdin\n otel-hook doctor [--json] report configuration and delivery health\n otel-hook providers [--json] list adapters and their capabilities\n otel-hook setup --provider <id> [options] register this hook in a provider's config\n otel-hook diagnose [--json] report what is registered where\n otel-hook uninstall --provider <id> remove this hook from a provider's config\n otel-hook --version\n\n\"run\" reads exactly one JSON value from stdin, writes only what the selected\nprovider's protocol requires to stdout, sends every diagnostic to stderr, and\nalways exits 0 so telemetry can never fail the host agent.\n\nProvider selection:\n --provider <id> explicit provider; always preferred\n (without it, detection must be unambiguous and\n never falls back to a default provider)\n --no-experimental exclude experimental adapters from detection\n\nInvocation identity (immutable, per invocation, never from the environment):\n --session-id <id> assert the session this observation belongs to\n --invocation-id <id> assert this invocation's id\n --parent-invocation-id <id>\n --root-session-id <id>\n --agent-instance-id <id>\n --identity-file <path> JSON with any of the fields above, plus\n \"startedAt\" and a \"workspace\" identity\n A caller assertion that disagrees with the provider payload is a conflict:\n attribution is declined rather than guessed.\n\nDelivery deduplication (at most once per callback, across process restarts):\n --callback-id <id> host-supplied delivery id; a repeat of the same id\n suppresses duplicate telemetry\n --callback-scope <scope> namespace for --callback-id (default \"delivery\")\n Without --callback-id, the selected adapter is asked whether the payload\n carries a replay-stable identifier of its own (a tool-call id, a turn id, a\n provider-recorded timestamp); see \"providers\" for per-adapter coverage.\n --require-callback-id report every callback that could not be deduplicated,\n naming the provider and the missing capability\n --no-derive-callback-id never normalize an identifier from the payload;\n deduplicate only against --callback-id\n\nExporter and runtime policy (never identity):\n --config-file <path> JSON configuration patch\n --endpoint <url> OTLP HTTP/protobuf traces endpoint\n --protocol <p> http/protobuf | http/json | none\n --service-name <name> --service-namespace <ns>\n --timeout-ms <n> per-export timeout\n --no-export disable the exporter entirely\n --content-mode <mode> omit (default) | mask | redact | raw\n --log-level <level> silent | error | warn | info | debug\n --header <name=value> exporter header; only its name enters any snapshot\n --resource-attr <key=value>\n custom OTLP resource attribute for this deployment,\n merged per key over OTEL_RESOURCE_ATTRIBUTES and the\n config file. service.name and service.namespace are\n refused here; use --service-name/--service-namespace\n --state-dir <path> root for session state and the retry spool\n --installation-id <id> state namespace (not identity)\n --no-spool do not persist batches a collector refused\n --flush-timeout-ms <n> upper bound on flush before exiting (default 2000)\n --logs also export OTLP logs (off by default)\n --logs-endpoint <url> OTLP HTTP/protobuf logs endpoint; derived from\n --endpoint when omitted (/v1/traces -> /v1/logs)\n --logs-content permit disclosed content text in a log body. Needs\n --content-mode too: this decides whether the logs\n pipeline may carry what that one discloses\n --max-input-bytes <n> stdin bound (default 1048576)\n --attr <key=value> opaque consumer attribute for this invocation,\n carried unchanged (not a resource attribute)\n --transport <t> hook-stdin (default) | cli-argument | library-call\n\nRegistration lifecycle (setup / diagnose / uninstall):\n --provider <id> provider to act on; repeatable. Required for setup\n and uninstall; diagnose defaults to every provider\n whose configuration path this build has verified\n --scope <s> global | project | all. setup and uninstall default\n to project; diagnose defaults to all\n --project-dir <path> project root for project scope (default: cwd)\n --home-dir <path> home directory for global scope\n --settings-file <path> write this exact document instead of the provider's\n documented path; required for a provider whose\n planner is verified but whose path is not\n --hook-command <cmd> command to register\n (default \"otel-hook run --provider <id>\")\n --event <name> register only these events; repeatable\n --matcher <m> matcher for a newly created hook group\n --timeout-seconds <n> per-hook timeout written into the config\n --managed-marker <token> substring that identifies this tool's own entries\n across versions (default \"otel-hook\")\n --dry-run print the exact document that would be written\n --json machine-readable report\n\nsetup is idempotent, preserves unrelated configuration and file formatting,\nwrites atomically under a lock, and refuses rather than overwrites a document it\ncannot parse. uninstall removes exactly what setup added.\n`;\n","import { readFile } from \"node:fs/promises\";\nimport * as os from \"node:os\";\nimport * as path from \"node:path\";\nimport type { Readable, Writable } from \"node:stream\";\n\nimport { parseEnvironmentConfig } from \"../config/environment.js\";\nimport { resolveConfig, type ConfigLayer, type ConfigProvenance } from \"../config/resolve.js\";\nimport { DEFAULT_CONFIG, type OtelHookConfig, type OtelHookConfigPatch } from \"../config/schema.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createStderrLogger } from \"../runtime/logger.js\";\nimport type { LogLevel, Logger } from \"../runtime/ports.js\";\nimport type { CliPolicyFlags } from \"./args.js\";\n\n/**\n * Everything the CLI is allowed to touch, passed in rather than reached for.\n *\n * `env` is read-only and never written back: no command mutates the process\n * environment, and no environment variable carries identity (ADR 0001). Streams\n * are injected so the whole CLI is testable in-process, and so nothing can write\n * to stdout by accident — only the run command's provider response does.\n */\nexport type CliIo = {\n readonly argv: readonly string[];\n readonly env: Readonly<Record<string, string | undefined>>;\n readonly stdin: Readable;\n readonly stdout: Writable;\n readonly stderr: Writable;\n /** Used only for the default state directory; never exported. */\n readonly homeDir?: string;\n readonly tmpDir?: string;\n};\n\nexport const writeLine = (stream: Writable, text: string): void => {\n stream.write(`${text}\\n`);\n};\n\n/** Environment variables the CLI reads in addition to the library's own. */\nexport const CLI_ENVIRONMENT_VARIABLES = Object.freeze({\n stateDir: \"OTEL_HOOK_STATE_DIR\",\n installationId: \"OTEL_HOOK_INSTALLATION_ID\",\n xdgStateHome: \"XDG_STATE_HOME\",\n});\n\nexport const DEFAULT_INSTALLATION_ID = \"default\";\n\n/**\n * Where session state and the retry spool live.\n *\n * Resolution order is explicit flag, then `OTEL_HOOK_STATE_DIR`, then the XDG\n * state directory, then a temp-directory fallback. The path is used only to open\n * files: it never becomes a workspace id, an attribute, or part of an event.\n */\nexport const resolveStateRootDir = (policy: CliPolicyFlags, io: CliIo): string => {\n if (policy.stateDir !== undefined) {\n return path.resolve(policy.stateDir);\n }\n const fromEnv = io.env[CLI_ENVIRONMENT_VARIABLES.stateDir];\n if (fromEnv !== undefined && fromEnv.trim().length > 0) {\n return path.resolve(fromEnv.trim());\n }\n const xdg = io.env[CLI_ENVIRONMENT_VARIABLES.xdgStateHome];\n if (xdg !== undefined && xdg.trim().length > 0) {\n return path.join(path.resolve(xdg.trim()), \"otel-hook\");\n }\n const home = io.homeDir ?? os.homedir();\n if (home.length > 0) {\n return path.join(home, \".local\", \"state\", \"otel-hook\");\n }\n return path.join(io.tmpDir ?? os.tmpdir(), \"otel-hook-state\");\n};\n\nexport const resolveInstallationId = (policy: CliPolicyFlags, io: CliIo): string => {\n const explicit = policy.installationId ?? io.env[CLI_ENVIRONMENT_VARIABLES.installationId];\n const trimmed = explicit?.trim() ?? \"\";\n return trimmed.length > 0 ? trimmed : DEFAULT_INSTALLATION_ID;\n};\n\n/** Configuration patch expressed by CLI policy flags. Carries no identity field. */\nexport const policyFlagsToPatch = (policy: CliPolicyFlags): OtelHookConfigPatch => {\n const headerNames = Object.keys(policy.headers).sort();\n const logs = {\n ...(policy.logsEnabled === undefined ? {} : { enabled: policy.logsEnabled }),\n ...(policy.logsEndpoint === undefined ? {} : { endpoint: policy.logsEndpoint }),\n ...(policy.logsIncludeContent === undefined\n ? {}\n : { includeContent: policy.logsIncludeContent }),\n };\n const exporter = {\n ...(policy.exportDisabled === true ? { enabled: false } : {}),\n ...(policy.endpoint === undefined ? {} : { endpoint: policy.endpoint }),\n ...(policy.protocol === undefined ? {} : { protocol: policy.protocol }),\n ...(policy.serviceName === undefined ? {} : { serviceName: policy.serviceName }),\n ...(policy.serviceNamespace === undefined ? {} : { serviceNamespace: policy.serviceNamespace }),\n ...(policy.timeoutMillis === undefined ? {} : { timeoutMillis: policy.timeoutMillis }),\n // Only header *names* reach configuration; the values stay in CliPolicyFlags\n // and are handed straight to the sink, so a resolved-config snapshot (which\n // is logged and exported) cannot leak a credential.\n ...(headerNames.length === 0 ? {} : { headerNames }),\n // Resource attribute *values* do belong in configuration: unlike a header\n // value they are exported on every span by design, so there is nothing to\n // keep out of the snapshot. The snapshot still reports names only.\n ...(Object.keys(policy.resourceAttributes).length === 0\n ? {}\n : { resourceAttributes: policy.resourceAttributes }),\n ...(Object.keys(logs).length === 0 ? {} : { logs }),\n };\n const privacy = policy.contentMode === undefined ? {} : { contentMode: policy.contentMode };\n const diagnostics = policy.logLevel === undefined ? {} : { logLevel: policy.logLevel };\n return {\n ...(Object.keys(exporter).length === 0 ? {} : { exporter }),\n ...(Object.keys(privacy).length === 0 ? {} : { privacy }),\n ...(Object.keys(diagnostics).length === 0 ? {} : { diagnostics }),\n } as OtelHookConfigPatch;\n};\n\nexport type ResolvedCliConfig = {\n readonly config: OtelHookConfig;\n readonly provenance?: ConfigProvenance;\n readonly notes: readonly string[];\n /** Reported, never fatal: a bad layer falls back to DEFAULT_CONFIG. */\n readonly warnings: readonly OtelHookErrorInfo[];\n readonly usedDefaults: boolean;\n};\n\nconst readJsonFile = async (\n filePath: string,\n): Promise<{ readonly value: unknown } | { readonly error: OtelHookErrorInfo }> => {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n return {\n error: createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n // The basename is safe to name; the full path is not.\n detail: `could not read ${path.basename(filePath)}`,\n details: {\n \"config.origin\": path.basename(filePath),\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n },\n }),\n };\n }\n try {\n return { value: JSON.parse(raw) as unknown };\n } catch {\n return {\n error: createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `${path.basename(filePath)} is not well-formed JSON`,\n details: { \"config.origin\": path.basename(filePath) },\n }),\n };\n }\n};\n\n/**\n * Resolve configuration from file, environment, and flags.\n *\n * An unusable layer is reported and the whole resolution falls back to\n * `DEFAULT_CONFIG` rather than being partially applied: a half-applied privacy\n * policy is exactly what the configuration contract exists to prevent. Falling\n * back rather than exiting keeps the hook fail-open (ADR 0004).\n */\nexport const resolveCliConfig = async (\n policy: CliPolicyFlags,\n io: CliIo,\n): Promise<ResolvedCliConfig> => {\n const warnings: OtelHookErrorInfo[] = [];\n const layers: ConfigLayer[] = [];\n\n if (policy.configFile !== undefined) {\n const read = await readJsonFile(path.resolve(policy.configFile));\n if (\"error\" in read) {\n warnings.push(read.error);\n } else {\n layers.push({\n source: \"file\",\n patch: read.value as OtelHookConfigPatch,\n origin: path.basename(policy.configFile),\n });\n }\n }\n\n const environment = parseEnvironmentConfig(io.env);\n warnings.push(...environment.warnings);\n layers.push({ source: \"environment\", patch: environment.patch });\n layers.push({ source: \"inline-override\", patch: policyFlagsToPatch(policy) });\n\n const resolution = resolveConfig(layers);\n if (resolution.status !== \"ok\") {\n warnings.push(...resolution.errors);\n return { config: DEFAULT_CONFIG, notes: [], warnings, usedDefaults: true };\n }\n return {\n config: resolution.config,\n provenance: resolution.provenance,\n notes: resolution.notes,\n warnings,\n usedDefaults: false,\n };\n};\n\nexport const createCliLogger = (io: CliIo, level: LogLevel): Logger =>\n createStderrLogger({\n level,\n write: (line: string): void => {\n io.stderr.write(line);\n },\n });\n\nexport const readIdentityFile = readJsonFile;\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 { 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 { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { detectionConfidenceSchema } from \"../model/primitives.js\";\nimport { contentModeSchema } from \"../privacy/policy.js\";\nimport { parseResourceAttributesValue } from \"./resource-attributes.js\";\nimport type { OtelHookConfigPatch } from \"./schema.js\";\n\nexport type EnvironmentRecord = Readonly<Record<string, string | undefined>>;\n\nexport type EnvironmentConfigResult = {\n readonly patch: OtelHookConfigPatch;\n /**\n * Unusable variables are reported and skipped rather than failing resolution.\n * The environment is ambient: a stale variable in a shell profile must not\n * disable telemetry, and it must not silently change privacy either — hence\n * the warning.\n */\n readonly warnings: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Environment variables read by the library.\n *\n * No identity variable appears here by design: session, invocation, and\n * workspace identity are supplied per invocation as identity claims, never\n * through ambient configuration (ADR 0001).\n */\nexport const ENVIRONMENT_VARIABLES = Object.freeze({\n exporterEnabled: \"OTEL_HOOK_ENABLED\",\n exporterEndpoint: \"OTEL_HOOK_EXPORTER_ENDPOINT\",\n otlpEndpoint: \"OTEL_EXPORTER_OTLP_ENDPOINT\",\n exporterProtocol: \"OTEL_HOOK_EXPORTER_PROTOCOL\",\n exporterTimeoutMillis: \"OTEL_HOOK_EXPORTER_TIMEOUT_MS\",\n logsEnabled: \"OTEL_HOOK_LOGS_ENABLED\",\n logsEndpoint: \"OTEL_HOOK_LOGS_ENDPOINT\",\n /** Standard per-signal endpoint; the weaker source of the two. */\n otlpLogsEndpoint: \"OTEL_EXPORTER_OTLP_LOGS_ENDPOINT\",\n logsIncludeContent: \"OTEL_HOOK_LOGS_INCLUDE_CONTENT\",\n serviceName: \"OTEL_HOOK_SERVICE_NAME\",\n otlpServiceName: \"OTEL_SERVICE_NAME\",\n serviceNamespace: \"OTEL_HOOK_SERVICE_NAMESPACE\",\n /** Standard W3C-Baggage-encoded resource attributes (percent-encoded values). */\n resourceAttributes: \"OTEL_RESOURCE_ATTRIBUTES\",\n contentMode: \"OTEL_HOOK_CONTENT_MODE\",\n allowRawContent: \"OTEL_HOOK_ALLOW_RAW_CONTENT\",\n hashSalt: \"OTEL_HOOK_HASH_SALT\",\n maxStringLength: \"OTEL_HOOK_MAX_STRING_LENGTH\",\n maxDepth: \"OTEL_HOOK_MAX_DEPTH\",\n maxArrayLength: \"OTEL_HOOK_MAX_ARRAY_LENGTH\",\n maxEventsPerInvocation: \"OTEL_HOOK_MAX_EVENTS_PER_INVOCATION\",\n minimumConfidence: \"OTEL_HOOK_MIN_DETECTION_CONFIDENCE\",\n logLevel: \"OTEL_HOOK_LOG_LEVEL\",\n});\n\nconst BOOLEAN_TRUE = new Set([\"1\", \"true\", \"yes\", \"on\"]);\nconst BOOLEAN_FALSE = new Set([\"0\", \"false\", \"no\", \"off\"]);\n\n/**\n * Read configuration from an environment record.\n *\n * Pure: the process environment is never read implicitly, which keeps tests and\n * hosted embeddings from inheriting the developer's shell.\n */\nexport const parseEnvironmentConfig = (env: EnvironmentRecord): EnvironmentConfigResult => {\n const warnings: OtelHookErrorInfo[] = [];\n const warn = (variable: string, detail: string): void => {\n warnings.push(\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `${variable}: ${detail}`,\n details: { \"config.variable\": variable },\n }),\n );\n };\n\n const readBoolean = (variable: string): boolean | undefined => {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n const normalized = raw.trim().toLowerCase();\n if (BOOLEAN_TRUE.has(normalized)) {\n return true;\n }\n if (BOOLEAN_FALSE.has(normalized)) {\n return false;\n }\n warn(variable, \"expected a boolean\");\n return undefined;\n };\n\n const readInteger = (variable: string): number | undefined => {\n const raw = env[variable];\n if (raw === undefined || raw === \"\") {\n return undefined;\n }\n const value = Number(raw.trim());\n if (!Number.isInteger(value) || value < 0) {\n warn(variable, \"expected a non-negative integer\");\n return undefined;\n }\n return value;\n };\n\n const readString = (variable: string): string | undefined => {\n const raw = env[variable];\n if (raw === undefined) {\n return undefined;\n }\n const trimmed = raw.trim();\n return trimmed === \"\" ? undefined : trimmed;\n };\n\n const exporterEnabled = readBoolean(ENVIRONMENT_VARIABLES.exporterEnabled);\n const endpoint =\n readString(ENVIRONMENT_VARIABLES.exporterEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpEndpoint);\n const timeoutMillis = readInteger(ENVIRONMENT_VARIABLES.exporterTimeoutMillis);\n\n const resourceRaw = readString(ENVIRONMENT_VARIABLES.resourceAttributes);\n const resource =\n resourceRaw === undefined ? undefined : parseResourceAttributesValue(resourceRaw);\n for (const detail of resource?.warnings ?? []) {\n warn(ENVIRONMENT_VARIABLES.resourceAttributes, detail);\n }\n const resourceAttributes = resource?.attributes ?? {};\n\n /**\n * Resolve one service field from its sources, highest precedence first.\n *\n * `service.name` inside `OTEL_RESOURCE_ATTRIBUTES` is honoured — that is the\n * shape a migrating deployment already has — but it is the *weakest* source,\n * and a disagreement with a dedicated variable is reported rather than\n * applied silently. Only variable names are named; values are not, because\n * this warning is written to a log the operator may ship elsewhere.\n */\n const resolveServiceField = (\n sources: readonly { readonly variable: string; readonly value: string | undefined }[],\n ): string | undefined => {\n const present = sources.filter(\n (source): source is { variable: string; value: string } => source.value !== undefined,\n );\n const winner = present[0];\n if (winner === undefined) {\n return undefined;\n }\n for (const loser of present.slice(1)) {\n if (loser.value !== winner.value) {\n warn(loser.variable, `overridden by ${winner.variable}, which sets a different value`);\n }\n }\n return winner.value;\n };\n\n const serviceName = resolveServiceField([\n { variable: ENVIRONMENT_VARIABLES.serviceName, value: readString(ENVIRONMENT_VARIABLES.serviceName) },\n {\n variable: ENVIRONMENT_VARIABLES.otlpServiceName,\n value: readString(ENVIRONMENT_VARIABLES.otlpServiceName),\n },\n {\n variable: `service.name in ${ENVIRONMENT_VARIABLES.resourceAttributes}`,\n value: resource?.serviceName,\n },\n ]);\n const serviceNamespace = resolveServiceField([\n {\n variable: ENVIRONMENT_VARIABLES.serviceNamespace,\n value: readString(ENVIRONMENT_VARIABLES.serviceNamespace),\n },\n {\n variable: `service.namespace in ${ENVIRONMENT_VARIABLES.resourceAttributes}`,\n value: resource?.serviceNamespace,\n },\n ]);\n\n const protocolRaw = readString(ENVIRONMENT_VARIABLES.exporterProtocol);\n let protocol: \"http/protobuf\" | \"http/json\" | \"none\" | undefined;\n if (protocolRaw !== undefined) {\n if (protocolRaw === \"http/protobuf\" || protocolRaw === \"http/json\" || protocolRaw === \"none\") {\n protocol = protocolRaw;\n } else {\n warn(ENVIRONMENT_VARIABLES.exporterProtocol, \"expected http/protobuf, http/json, or none\");\n }\n }\n\n const contentModeRaw = readString(ENVIRONMENT_VARIABLES.contentMode);\n const contentModeParsed =\n contentModeRaw === undefined ? undefined : contentModeSchema.safeParse(contentModeRaw);\n if (contentModeParsed !== undefined && !contentModeParsed.success) {\n warn(ENVIRONMENT_VARIABLES.contentMode, \"expected omit, mask, redact, or raw\");\n }\n\n const confidenceRaw = readString(ENVIRONMENT_VARIABLES.minimumConfidence);\n const confidenceParsed =\n confidenceRaw === undefined ? undefined : detectionConfidenceSchema.safeParse(confidenceRaw);\n if (confidenceParsed !== undefined && !confidenceParsed.success) {\n warn(ENVIRONMENT_VARIABLES.minimumConfidence, \"expected none, weak, strong, or exact\");\n }\n\n const logLevelRaw = readString(ENVIRONMENT_VARIABLES.logLevel);\n const logLevels = [\"silent\", \"error\", \"warn\", \"info\", \"debug\"] as const;\n type LogLevel = (typeof logLevels)[number];\n let logLevel: LogLevel | undefined;\n if (logLevelRaw !== undefined) {\n const match = logLevels.find((level) => level === logLevelRaw);\n if (match === undefined) {\n warn(ENVIRONMENT_VARIABLES.logLevel, `expected one of ${logLevels.join(\", \")}`);\n } else {\n logLevel = match;\n }\n }\n\n const allowRawContent = readBoolean(ENVIRONMENT_VARIABLES.allowRawContent);\n const hashSalt = readString(ENVIRONMENT_VARIABLES.hashSalt);\n const maxStringLength = readInteger(ENVIRONMENT_VARIABLES.maxStringLength);\n const maxDepth = readInteger(ENVIRONMENT_VARIABLES.maxDepth);\n const maxArrayLength = readInteger(ENVIRONMENT_VARIABLES.maxArrayLength);\n const maxEventsPerInvocation = readInteger(ENVIRONMENT_VARIABLES.maxEventsPerInvocation);\n\n const logsEnabled = readBoolean(ENVIRONMENT_VARIABLES.logsEnabled);\n const logsIncludeContent = readBoolean(ENVIRONMENT_VARIABLES.logsIncludeContent);\n const logsEndpoint =\n readString(ENVIRONMENT_VARIABLES.logsEndpoint) ??\n readString(ENVIRONMENT_VARIABLES.otlpLogsEndpoint);\n\n const logs = {\n ...(logsEnabled === undefined ? {} : { enabled: logsEnabled }),\n ...(logsEndpoint === undefined ? {} : { endpoint: logsEndpoint }),\n ...(logsIncludeContent === undefined ? {} : { includeContent: logsIncludeContent }),\n };\n\n const exporter = {\n ...(exporterEnabled === undefined ? {} : { enabled: exporterEnabled }),\n ...(endpoint === undefined ? {} : { endpoint }),\n ...(protocol === undefined ? {} : { protocol }),\n ...(timeoutMillis === undefined ? {} : { timeoutMillis }),\n ...(serviceName === undefined ? {} : { serviceName }),\n ...(serviceNamespace === undefined ? {} : { serviceNamespace }),\n ...(Object.keys(resourceAttributes).length === 0 ? {} : { resourceAttributes }),\n ...(Object.keys(logs).length === 0 ? {} : { logs }),\n };\n\n const limits = {\n ...(maxStringLength === undefined ? {} : { maxStringLength }),\n ...(maxDepth === undefined ? {} : { maxDepth }),\n ...(maxArrayLength === undefined ? {} : { maxArrayLength }),\n ...(maxEventsPerInvocation === undefined ? {} : { maxEventsPerInvocation }),\n };\n\n const privacy = {\n ...(contentModeParsed?.success === true ? { contentMode: contentModeParsed.data } : {}),\n ...(allowRawContent === undefined ? {} : { allowRawContent }),\n ...(hashSalt === undefined ? {} : { hashSalt }),\n ...(Object.keys(limits).length === 0 ? {} : { limits }),\n };\n\n const detection =\n confidenceParsed?.success === true ? { minimumConfidence: confidenceParsed.data } : {};\n\n const diagnostics = logLevel === undefined ? {} : { logLevel };\n\n const patch: OtelHookConfigPatch = {\n ...(Object.keys(exporter).length === 0 ? {} : { exporter }),\n ...(Object.keys(privacy).length === 0 ? {} : { privacy }),\n ...(Object.keys(detection).length === 0 ? {} : { detection }),\n ...(Object.keys(diagnostics).length === 0 ? {} : { diagnostics }),\n };\n\n return { patch, warnings };\n};\n","import { z } from \"zod\";\n\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport { describeResourceAttributeNames } from \"./resource-attributes.js\";\nimport {\n DEFAULT_CONFIG,\n otelHookConfigPatchSchema,\n otelHookConfigSchema,\n type OtelHookConfig,\n type OtelHookConfigPatch,\n} from \"./schema.js\";\n\n/**\n * Configuration layers, lowest precedence first.\n *\n * Precedence is fixed and total: `inline-override` beats `environment`, which\n * beats `file`, which beats `defaults`. There is no partial-merge surprise —\n * merging happens per leaf field, so a file may set an endpoint while the\n * environment sets only a content mode.\n *\n * `exporter.resourceAttributes` follows the same rule one level deeper: each\n * *attribute key* is its own leaf. A file may set `deployment.environment`\n * while `OTEL_RESOURCE_ATTRIBUTES` adds `service.instance.id` and\n * `--resource-attr` overrides just one of them; the result is the union, with\n * the highest-precedence layer winning per key and provenance recorded per key.\n * A layer cannot *remove* a key a lower layer set — precedence is an override\n * relation, not a replacement one.\n */\nexport const CONFIG_SOURCE_PRECEDENCE = [\"defaults\", \"file\", \"environment\", \"inline-override\"] as const;\nexport type ConfigSource = (typeof CONFIG_SOURCE_PRECEDENCE)[number];\n\nexport const configSourceSchema = z.enum(CONFIG_SOURCE_PRECEDENCE);\n\nexport type ConfigLayer = {\n readonly source: Exclude<ConfigSource, \"defaults\">;\n readonly patch: OtelHookConfigPatch;\n /** Non-sensitive origin label, e.g. a file name without its directory. */\n readonly origin?: string;\n};\n\n/** Which layer supplied each resolved leaf, keyed by `section.field` path. */\nexport type ConfigProvenance = Readonly<Record<string, ConfigSource>>;\n\nexport type ConfigResolution =\n | {\n readonly status: \"ok\";\n readonly config: OtelHookConfig;\n readonly provenance: ConfigProvenance;\n readonly notes: readonly string[];\n }\n | { readonly status: \"invalid\"; readonly errors: readonly OtelHookErrorInfo[] };\n\ntype PlainRecord = Record<string, unknown>;\n\nconst isPlainObject = (value: unknown): value is PlainRecord =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst mergeLeaf = (\n target: PlainRecord,\n patch: PlainRecord,\n source: ConfigSource,\n provenance: Record<string, ConfigSource>,\n path: string,\n): void => {\n for (const [key, value] of Object.entries(patch)) {\n if (value === undefined) {\n continue;\n }\n const childPath = path === \"\" ? key : `${path}.${key}`;\n const existing = target[key];\n if (isPlainObject(value) && isPlainObject(existing)) {\n const child: PlainRecord = { ...existing };\n mergeLeaf(child, value, source, provenance, childPath);\n target[key] = child;\n continue;\n }\n target[key] = value;\n provenance[childPath] = source;\n }\n};\n\nconst initialProvenance = (config: OtelHookConfig): Record<string, ConfigSource> => {\n const provenance: Record<string, ConfigSource> = {};\n const walk = (value: unknown, path: string): void => {\n if (isPlainObject(value)) {\n for (const [key, child] of Object.entries(value)) {\n walk(child, path === \"\" ? key : `${path}.${key}`);\n }\n return;\n }\n provenance[path] = \"defaults\";\n };\n walk(config, \"\");\n return provenance;\n};\n\n/**\n * Resolve configuration from layered patches.\n *\n * Invalid layers are rejected rather than partially applied: a half-applied\n * privacy policy is exactly the failure mode this contract exists to prevent.\n * Callers that must not fail hard should fall back to {@link DEFAULT_CONFIG},\n * which is always valid.\n */\nexport const resolveConfig = (layers: readonly ConfigLayer[] = []): ConfigResolution => {\n const errors: OtelHookErrorInfo[] = [];\n const ordered = [...layers].sort(\n (a, b) =>\n CONFIG_SOURCE_PRECEDENCE.indexOf(a.source) - CONFIG_SOURCE_PRECEDENCE.indexOf(b.source),\n );\n\n const validated: { source: ConfigSource; patch: PlainRecord }[] = [];\n for (const layer of ordered) {\n const parsed = otelHookConfigPatchSchema.safeParse(layer.patch);\n if (!parsed.success) {\n errors.push(\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `layer ${layer.source} rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n details: {\n \"config.layer\": layer.source,\n ...(layer.origin === undefined ? {} : { \"config.origin\": layer.origin }),\n },\n }),\n );\n continue;\n }\n validated.push({ source: layer.source, patch: parsed.data });\n }\n\n if (errors.length > 0) {\n return { status: \"invalid\", errors };\n }\n\n const merged: PlainRecord = structuredClone(DEFAULT_CONFIG);\n const provenance = initialProvenance(DEFAULT_CONFIG);\n for (const layer of validated) {\n mergeLeaf(merged, layer.patch, layer.source, provenance, \"\");\n }\n\n const parsed = otelHookConfigSchema.safeParse(merged);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n errors: [\n createErrorInfo({\n code: \"configuration-invalid\",\n phase: \"configuration\",\n detail: `merged configuration rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`.slice(0, 480),\n }),\n ],\n };\n }\n\n const notes: string[] = [];\n if (parsed.data.privacy.contentMode === \"raw\" && !parsed.data.privacy.allowRawContent) {\n notes.push(\"privacy.contentMode=raw will be downgraded to omit: allowRawContent is false\");\n }\n if (parsed.data.exporter.enabled && parsed.data.exporter.protocol !== \"none\" && parsed.data.exporter.endpoint === undefined) {\n notes.push(\"exporter.enabled is true but no endpoint is configured\");\n }\n if (\n parsed.data.exporter.logs.enabled &&\n parsed.data.exporter.logs.endpoint === undefined &&\n parsed.data.exporter.endpoint === undefined\n ) {\n notes.push(\n \"exporter.logs.enabled is true but neither a logs endpoint nor a trace endpoint to derive one from is configured\",\n );\n }\n if (parsed.data.exporter.logs.includeContent && parsed.data.privacy.contentMode === \"omit\") {\n // Not an error: the two settings are independent by design, and this is the\n // combination somebody lands on when they enable one and forget the other. Said\n // out loud because the symptom — every log body withheld — looks like a bug.\n notes.push(\n \"exporter.logs.includeContent is true but privacy.contentMode is omit, so no content is disclosed to describe\",\n );\n }\n\n return { status: \"ok\", config: parsed.data, provenance, notes };\n};\n\n/**\n * Attribute-safe snapshot of resolved configuration, for logging and telemetry.\n *\n * Endpoints are reduced to origin form and header values never appear, because a\n * snapshot is exported to the very system whose credentials it would leak.\n */\nexport const describeResolvedConfig = (config: OtelHookConfig): Attributes => {\n const originOf = (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 const endpointOrigin = originOf(config.exporter.endpoint);\n const logsEndpointOrigin = originOf(config.exporter.logs.endpoint);\n return {\n \"exporter.enabled\": config.exporter.enabled,\n \"exporter.protocol\": config.exporter.protocol,\n ...(endpointOrigin === undefined ? {} : { \"exporter.endpoint_origin\": endpointOrigin }),\n \"exporter.logs_enabled\": config.exporter.logs.enabled,\n \"exporter.logs_include_content\": config.exporter.logs.includeContent,\n \"exporter.logs_max_batch_size\": config.exporter.logs.maxBatchSize,\n ...(logsEndpointOrigin === undefined\n ? {}\n : { \"exporter.logs_endpoint_origin\": logsEndpointOrigin }),\n \"exporter.header_names\": [...config.exporter.headerNames],\n // Names only. A resource attribute *name* is already on the wire in every\n // exported resource, so disclosing it here adds nothing; a *value* may hold\n // whatever an operator put in a shell profile, so it never appears.\n \"exporter.resource_attribute_names\": [\n ...describeResourceAttributeNames(config.exporter.resourceAttributes),\n ],\n \"exporter.timeout_millis\": config.exporter.timeoutMillis,\n \"exporter.max_batch_size\": config.exporter.maxBatchSize,\n \"exporter.service_name\": config.exporter.serviceName,\n \"privacy.content_mode\": config.privacy.contentMode,\n \"privacy.allow_raw_content\": config.privacy.allowRawContent,\n \"privacy.hash_salted\": config.privacy.hashSalt.length > 0,\n \"privacy.max_string_length\": config.privacy.limits.maxStringLength,\n \"privacy.max_depth\": config.privacy.limits.maxDepth,\n \"privacy.max_array_length\": config.privacy.limits.maxArrayLength,\n \"privacy.max_events_per_invocation\": config.privacy.limits.maxEventsPerInvocation,\n \"detection.minimum_confidence\": config.detection.minimumConfidence,\n \"detection.allow_ambiguous_fallback\": config.detection.allowAmbiguousFallback,\n \"diagnostics.log_level\": config.diagnostics.logLevel,\n \"diagnostics.emit_error_events\": config.diagnostics.emitErrorEvents,\n };\n};\n","import { 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 { 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 * 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});\nexport type ExporterPolicy = z.infer<typeof exporterPolicySchema>;\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\nexport const otelHookConfigSchema = z.strictObject({\n exporter: exporterPolicySchema,\n privacy: privacyPolicySchema,\n detection: detectionPolicySchema,\n diagnostics: diagnosticsPolicySchema,\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 })\n .partial()\n .extend({ logs: logsPolicySchema.partial().optional() })\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});\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});\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_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});\n\n/** Content mode is re-exported for callers building patches. */\nexport { contentModeSchema };\n","import { z } from \"zod\";\n\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n attributesSchema,\n epochMillisSchema,\n sequenceNumberSchema,\n type Attributes,\n type EpochMillis,\n type EventId,\n type InvocationId,\n} from \"../model/primitives.js\";\nimport { canonicalUsageSchema } from \"../model/usage.js\";\n\n/**\n * Time source.\n *\n * Injected rather than read from `Date.now()` so tests are deterministic and so\n * a host with its own time authority can supply it.\n */\nexport interface Clock {\n /** Wall-clock time in whole milliseconds since the Unix epoch. */\n now(): EpochMillis;\n /** Monotonic reading for durations; unrelated to wall clock. */\n monotonicMillis(): number;\n}\n\n/** Stable inputs from which an invocation id is derived. */\nexport type InvocationIdSeed = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly sourceEventName?: string;\n readonly occurredAt: number;\n /** Provider-supplied uniqueness, e.g. a request id. */\n readonly discriminator?: string;\n};\n\n/** Stable inputs from which an event id is derived. */\nexport type EventIdSeed = {\n readonly invocationId: string;\n readonly sequence: number;\n readonly eventType: string;\n readonly discriminator?: string;\n};\n\n/**\n * Identifier factory.\n *\n * Seeds are structured rather than free-form so the default implementation can\n * be a pure function of its inputs: replaying the same source data produces the\n * same ids, which lets a collector dedupe instead of double-counting.\n */\nexport interface IdGenerator {\n newInvocationId(seed: InvocationIdSeed): InvocationId;\n newEventId(seed: EventIdSeed): EventId;\n /** Short opaque id for spans and generations, derived from its parts. */\n newOpaqueId(parts: readonly string[]): string;\n}\n\n/**\n * Which delivery's observations are already folded into a stored total.\n *\n * The reason this rides *inside* the total's own record rather than beside it: the\n * store has no multi-key transaction, so a marker in a second key could be written\n * without the total or the other way round, and a marker that can disagree with\n * what it describes is worse than none. In one record the two move together under a\n * single write, which is what makes re-applying a redelivered callback's usage a\n * no-op instead of a double count.\n *\n * `callbackId` is an opaque digest supplied by the caller, never a host's raw\n * delivery id: a state record is somewhere a raw provider or host identifier must\n * not appear as a side effect of deduplicating on it.\n */\nexport const appliedDeliverySchema = z.strictObject({\n callbackId: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),\n /** How many of that delivery's observations are folded in, counted from one. */\n applications: z.number().int().min(1).max(4_096),\n});\nexport type AppliedDelivery = z.infer<typeof appliedDeliverySchema>;\n\n/** Values the state store may hold. Restricted so state stays inspectable. */\nexport const stateValueSchema = z.discriminatedUnion(\"kind\", [\n z.strictObject({\n kind: z.literal(\"usage-cumulative\"),\n usage: canonicalUsageSchema,\n /**\n * Optional: absent on every record written before this field existed, which\n * reads as \"unknown provenance\" and simply forgoes the idempotency check\n * rather than resetting a baseline to gain it.\n */\n appliedDelivery: appliedDeliverySchema.optional(),\n }),\n z.strictObject({\n kind: z.literal(\"sequence\"),\n next: sequenceNumberSchema,\n }),\n z.strictObject({\n kind: z.literal(\"attributes\"),\n attributes: attributesSchema,\n }),\n]);\nexport type StateValue = z.infer<typeof stateValueSchema>;\n\nexport const stateRecordSchema = z.strictObject({\n /** Incremented on each write; lets callers detect lost updates. */\n revision: z.number().int().min(0),\n updatedAt: epochMillisSchema,\n value: stateValueSchema,\n});\nexport type StateRecord = z.infer<typeof stateRecordSchema>;\n\n/**\n * Durable-ish key/value state.\n *\n * Needed because a hook process is short-lived but usage accounting spans an\n * entire session. The interface is intentionally minimal: no transactions, no\n * queries, nothing a file or a KV row cannot provide.\n */\nexport interface StateStore {\n read(key: string): Promise<StateRecord | undefined>;\n /** Writes unconditionally, returning the stored record. */\n write(key: string, value: StateValue): Promise<StateRecord>;\n delete(key: string): Promise<void>;\n keys(prefix: string): Promise<readonly string[]>;\n}\n\nexport type TelemetryEmitResult = {\n readonly accepted: number;\n readonly rejected: number;\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\n/**\n * Destination for canonical events.\n *\n * The sink receives canonical events only — never provider payloads — so an\n * exporter cannot become a second, unaudited disclosure path.\n */\nexport interface TelemetrySink {\n emit(events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult>;\n flush(): Promise<void>;\n shutdown(): Promise<void>;\n}\n\nexport const logLevelSchema = z.enum([\"silent\", \"error\", \"warn\", \"info\", \"debug\"]);\nexport type LogLevel = z.infer<typeof logLevelSchema>;\n\nexport const LOG_LEVEL_RANK: Readonly<Record<LogLevel, number>> = Object.freeze({\n silent: 0,\n error: 1,\n warn: 2,\n info: 3,\n debug: 4,\n});\n\n/**\n * Diagnostic logger.\n *\n * Fields are attribute values, not arbitrary objects, so a log line cannot\n * become a way to print a provider payload. Implementations must never write to\n * stdout (ADR 0004).\n */\nexport interface Logger {\n error(message: string, fields?: Attributes): void;\n warn(message: string, fields?: Attributes): void;\n info(message: string, fields?: Attributes): void;\n debug(message: string, fields?: Attributes): void;\n}\n","import { z } from \"zod\";\n\nimport { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import type { 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 type { OtelHookErrorCode } from \"../errors/index.js\";\nimport type { EpochMillis } from \"../model/primitives.js\";\n\n/**\n * One tracked delivery path.\n *\n * The two telemetry signals are separate subsystems because they fail\n * independently — a collector with no logs receiver leaves traces perfectly\n * healthy — and a single combined verdict would make an operator bisect which one\n * is broken. `telemetry-sink` remains the traces signal, unrenamed, so an existing\n * `doctor --json` consumer keeps reading the same field.\n */\nexport type DeliverySubsystem =\n | \"state-store\"\n | \"telemetry-sink\"\n | \"telemetry-log-sink\"\n | \"lifecycle\";\n\n/**\n * Sanitized delivery health.\n *\n * Every field is a count, a timestamp, a boolean, or a closed-vocabulary error\n * code — the same restriction the privacy service applies to everything else\n * that might reach a sink, so a health snapshot is itself safe to export or log\n * without a second review.\n */\nexport type DeliveryHealthSnapshot = {\n readonly subsystem: DeliverySubsystem;\n readonly healthy: boolean;\n readonly totalAccepted: number;\n readonly totalRejected: number;\n readonly consecutiveFailures: number;\n readonly lastSuccessAt?: EpochMillis;\n readonly lastFailureAt?: EpochMillis;\n readonly lastErrorCode?: OtelHookErrorCode;\n};\n\nexport type HealthTrackerOptions = {\n /** Consecutive failures at or beyond this count flip `healthy` to false. Default 3. */\n readonly unhealthyAfterConsecutiveFailures?: number;\n};\n\n/**\n * Accumulates success/failure counts for one subsystem instance.\n *\n * Deliberately per-instance rather than a module-level registry: a store or\n * sink constructs its own tracker and exposes a `health()` accessor, so two\n * instances in one process never share counters (see ADR 0001 on module-level\n * identity).\n */\nexport interface HealthTracker {\n recordSuccess(count?: number, at?: number): void;\n recordFailure(code: OtelHookErrorCode, count?: number, at?: number): void;\n snapshot(): DeliveryHealthSnapshot;\n}\n\nexport const createHealthTracker = (\n subsystem: DeliverySubsystem,\n options: HealthTrackerOptions = {},\n): HealthTracker => {\n const unhealthyThreshold = options.unhealthyAfterConsecutiveFailures ?? 3;\n let totalAccepted = 0;\n let totalRejected = 0;\n let consecutiveFailures = 0;\n let lastSuccessAt: number | undefined;\n let lastFailureAt: number | undefined;\n let lastErrorCode: OtelHookErrorCode | undefined;\n\n return {\n recordSuccess: (count = 1, at?: number): void => {\n totalAccepted += count;\n consecutiveFailures = 0;\n if (at !== undefined) {\n lastSuccessAt = at;\n }\n },\n recordFailure: (code: OtelHookErrorCode, count = 1, at?: number): void => {\n totalRejected += count;\n consecutiveFailures += 1;\n lastErrorCode = code;\n if (at !== undefined) {\n lastFailureAt = at;\n }\n },\n snapshot: (): DeliveryHealthSnapshot => ({\n subsystem,\n healthy: consecutiveFailures < unhealthyThreshold,\n totalAccepted,\n totalRejected,\n consecutiveFailures,\n ...(lastSuccessAt === undefined ? {} : { lastSuccessAt }),\n ...(lastFailureAt === undefined ? {} : { lastFailureAt }),\n ...(lastErrorCode === undefined ? {} : { lastErrorCode }),\n }),\n };\n};\n\nexport type OverallHealth = {\n readonly healthy: boolean;\n readonly subsystems: readonly DeliveryHealthSnapshot[];\n};\n\n/** Combines snapshots from every configured subsystem into one overall verdict. */\nexport const summarizeHealth = (snapshots: readonly DeliveryHealthSnapshot[]): OverallHealth => ({\n healthy: snapshots.every((snapshot) => snapshot.healthy),\n subsystems: [...snapshots],\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 { 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 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 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 {\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 {\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 { z } from \"zod\";\n\nimport type { AttributionOutcome, AttributionReason, OtelHookErrorInfo } from \"../errors/index.js\";\nimport { canonicalEventTypeSchema, type CanonicalEvent, type CanonicalEventType } from \"../model/events.js\";\nimport type { IdentityClaim, InvocationIdentity } from \"../model/identity.js\";\nimport {\n detectionConfidenceSchema,\n nonEmptyStringSchema,\n providerIdSchema,\n resolvedProviderIdSchema,\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\nexport type ProviderParseResult =\n | {\n readonly status: \"parsed\";\n readonly events: readonly CanonicalEvent[];\n readonly warnings?: readonly string[];\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 {\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 extensions: extensionsSchema.default(emptyExtensions),\n} as const;\n\nconst event = <TShape extends z.ZodRawShape>(shape: TShape) =>\n z.strictObject({ ...baseEventFields, ...shape });\n\nexport const sessionStartEventSchema = event({\n type: z.literal(\"session.start\"),\n sessionKind: z.enum([\"interactive\", \"non-interactive\", \"unknown\"]),\n agentName: nonEmptyStringSchema.optional(),\n agentVersion: nonEmptyStringSchema.optional(),\n model: modelDescriptorSchema.optional(),\n});\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});\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 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});\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});\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\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\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","import { OtelHookError } from \"../errors/index.js\";\nimport {\n canonicalEventSchema,\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 { 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 | \"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\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\nexport type EventFactoryInput = {\n readonly identity: InvocationIdentity;\n readonly sequenceBase: number;\n readonly context: ProviderContext;\n};\n\nexport const createEventFactory = (input: EventFactoryInput): EventFactory => {\n const { identity, context } = input;\n const built: CanonicalEvent[] = [];\n const dropped: string[] = [];\n let sequence = input.sequenceBase;\n\n return {\n build: (draft: CanonicalEventDraft): CanonicalEvent => {\n const { occurredAt, extensions, idDiscriminator, ...rest } = draft;\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 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 return parsed.data;\n },\n events: (): readonly CanonicalEvent[] => [...built],\n nextSequence: (): number => sequence,\n droppedExtensionKeys: (): readonly string[] => [...dropped],\n };\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 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.\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 (AGENT.md forbids scanning transcript directories from provider\n * adapters). So the field is accepted only when a caller has already placed it\n * on the payload, and the shape mirrors `message.usage` exactly so a harness can\n * attach what it read without reshaping it.\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 tool_error: z.unknown(),\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 usage: claudeUsageSchema.optional(),\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 last_assistant_message: 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});\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});\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 type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.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(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 { 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 } = input;\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 hinted = input.providerHint === CLAUDE_CODE_PROVIDER_ID;\n\n return providerDetectionSchema.parse({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n confidence: hinted ? \"exact\" : hasTranscriptPath ? \"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 ...(hinted ? [\"caller asserted providerHint=claude-code\"] : []),\n ],\n sourceEventName: hookEventName,\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 { 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(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","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 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 { normalizeUsage, type CanonicalUsage } from \"../../model/index.js\";\nimport 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 */\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 { 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 { claudeHookPayloadSchema, type ClaudeUsage } from \"./schema.js\";\nimport { inferToolKind } from \"./tool-kind.js\";\nimport { 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`). Using a real-looking model id here would assert something\n * the payload never said; `unknown` is the same honest-absence sentinel the\n * core model uses for provider and workspace identity.\n */\nconst UNKNOWN_MODEL: ModelDescriptor = { modelId: \"unknown\" };\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 parsed = claudeHookPayloadSchema.safeParse(input.payload);\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\n const factory = createEventFactory({\n identity: input.identity,\n sequenceBase: input.sequenceBase,\n context,\n });\n const warnings: string[] = [];\n const withUsage = (usage: ClaudeUsage | undefined) => {\n const normalized = normalizeClaudeUsage(usage);\n warnings.push(...normalized.warnings);\n return applyUsage(normalized);\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 });\n break;\n\n case \"SessionEnd\":\n factory.build({\n type: \"session.end\",\n reason: mapSessionEndReason(payload.reason ?? payload.end_reason),\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 });\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 ...(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 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 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 factory.build({\n type: \"subagent.end\",\n subagentInvocationId: subagentInvocationIdFor(context, payload.session_id, payload.agent_id),\n outcome: \"ok\",\n ...withUsage(payload.usage),\n });\n break;\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 factory.build({ type: \"generation.start\", generationId, model: UNKNOWN_MODEL });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: UNKNOWN_MODEL,\n outcome: \"ok\",\n ...withUsage(payload.usage),\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 factory.build({ type: \"generation.start\", generationId, model: UNKNOWN_MODEL });\n factory.build({\n type: \"generation.end\",\n generationId,\n model: UNKNOWN_MODEL,\n outcome: mapStopFailureOutcome(payload.error_type),\n stopReason: payload.error_type,\n ...withUsage(payload.usage),\n });\n break;\n }\n }\n\n return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\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 { 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/** Mirrors the rollout/exec `total_token_usage` / `last_token_usage` shape. */\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 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 { 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 does not report a distinct cache-*creation* counter (only cache\n * *reads*, `cached_input_tokens`), so `cacheCreationInputTokens` is always\n * omitted here and the adapter declares `cacheCreationAccounting:\n * \"not-reported\"` in its capabilities. `cached_input_tokens` and\n * `reasoning_output_tokens` are always subsets of the inclusive\n * `input_tokens` / `output_tokens` totals, matching Codex's own accounting.\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.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 { 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 reportsCacheCreation: false,\n cacheCreationAccounting: \"not-reported\",\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\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 });\n break;\n\n case \"UserPromptSubmit\":\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 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 ...(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 ...(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 return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\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 { 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 only one this adapter requires: it is the session\n * identity, and every captured agent payload carries it. `cwd` is *not*\n * `.min(1)` — the CLI captures report `\"cwd\": \"\"` for a workspace-rooted call,\n * and rejecting an empty string would drop the whole event over a field the\n * 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 conversation_id: z.string().min(1),\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 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","import type { ProviderDeliveryClaim, ProviderIdentityInput } from \"../adapter.js\";\nimport { normalizeCursorPayload, type CursorPayload } from \"./payload.js\";\n\n/**\n * Which Cursor callbacks carry an identifier that survives a redelivery.\n *\n * Cursor's envelope always carries `conversation_id`, which scopes the identity.\n * 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 identified = deliveryComponents(payload);\n if (identified === undefined) {\n return undefined;\n }\n return {\n sessionId: payload.conversation_id,\n sourceEventName: payload.hook_event_name,\n components: identified.components,\n evidence: identified.evidence,\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 recognizeCursorPayload,\n type CursorPayload,\n} from \"./payload.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 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: payload.conversation_id,\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 // 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 not preferred over it.\n sessionId: payload.conversation_id,\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 === \"beforeReadFile\") {\n return {\n status: \"ignored\",\n reason:\n \"beforeReadFile has no completion callback in the cursor hook protocol, so emitting tool.start \" +\n \"here would leave a tool lifecycle that never closes\",\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\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 });\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 ...(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 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 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 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 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 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 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 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 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 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 \"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 return {\n status: \"parsed\",\n events: factory.events(),\n ...(warnings.length === 0 ? {} : { warnings }),\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","/**\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 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 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 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(),\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 { 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 { randomBytes } from \"node:crypto\";\nimport { mkdir, open, readFile, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger, StateRecord, StateValue } from \"../runtime/ports.js\";\nimport { stateRecordSchema } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"./async-lock.js\";\nimport { keyDigest, namespaceSegments, sanitizeSegment, type StoreNamespace } from \"./keys.js\";\nimport { StateLockTimeoutError, type LockingStateStore } from \"./store.js\";\n\nexport type FilesystemStateStoreOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Bounds how long a write, read, or session lock waits. Default 5,000ms. */\n readonly lockTimeoutMillis?: number;\n /** A lock file older than this is assumed to belong to a crashed process and is reclaimed. Default 30,000ms. */\n readonly lockStaleMillis?: number;\n /** Delay between lock acquisition attempts. Default 25ms. */\n readonly lockPollIntervalMillis?: number;\n};\n\nexport interface FilesystemStateStore extends LockingStateStore {\n readonly recordsDir: string;\n readonly quarantineDir: string;\n /** Bounded sweep: removes records untouched for longer than `maxAgeMillis`. */\n pruneStale(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }>;\n}\n\ntype Envelope = { readonly key: string; readonly record: StateRecord };\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nconst sleep = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n const timer = setTimeout(resolve, millis);\n timer.unref?.();\n });\n\nconst wrapFsError = (thrown: unknown, operation: string): Error => {\n if (thrown instanceof Error) {\n return new Error(`filesystem state store ${operation} failed: ${thrown.name}`, { cause: thrown });\n }\n return new Error(`filesystem state store ${operation} failed`);\n};\n\n/**\n * Crash-safe filesystem {@link StateStore}.\n *\n * Every write lands via a temp file plus `rename`, which POSIX guarantees is\n * atomic within one directory: a reader never observes a half-written record,\n * and a process killed mid-write leaves only an orphaned temp file, never a\n * corrupt one. A record that still fails to parse (disk corruption, a manual\n * edit, a future incompatible version) is quarantined rather than thrown from\n * `read`, so a single bad file degrades one key instead of the whole store.\n *\n * Locking is layered: an in-process {@link createAsyncLock} orders same-process\n * callers, and a lock file with a staleness timeout orders across processes\n * and recovers automatically if the holder crashed while holding it.\n */\nexport const createFilesystemStateStore = (\n options: FilesystemStateStoreOptions,\n): FilesystemStateStore => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const baseDir = path.join(options.rootDir, providerSegment, installationSegment);\n const recordsDir = path.join(baseDir, \"records\");\n const quarantineDir = path.join(baseDir, \"quarantine\");\n const locksDir = path.join(baseDir, \"locks\");\n\n const lockTimeoutMillis = options.lockTimeoutMillis ?? 5_000;\n const lockStaleMillis = options.lockStaleMillis ?? 30_000;\n const lockPollIntervalMillis = options.lockPollIntervalMillis ?? 25;\n\n const keyLock = createAsyncLock();\n const sessionLock = createAsyncLock();\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(recordsDir, { recursive: true });\n await mkdir(quarantineDir, { recursive: true });\n await mkdir(locksDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw wrapFsError(thrown, \"ensure-dirs\");\n }\n };\n\n const recordPath = (key: string): string => path.join(recordsDir, `${keyDigest(key)}.json`);\n const tempPath = (key: string): string =>\n path.join(recordsDir, `.tmp-${keyDigest(key)}-${randomBytes(6).toString(\"hex\")}.json`);\n const lockPath = (sessionId: string): string =>\n path.join(locksDir, `${sanitizeSegment(sessionId)}.lock`);\n\n const quarantine = async (filePath: string, key: string, reason: string): Promise<void> => {\n const dest = path.join(quarantineDir, `${options.clock.now()}-${keyDigest(key)}-${reason}.json`);\n try {\n await rename(filePath, dest);\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n options.logger?.warn(\"filesystem state record quarantined\", { \"state.reason\": reason });\n };\n\n const readUnlocked = async (key: string): Promise<StateRecord | undefined> => {\n await ensureDirs();\n const filePath = recordPath(key);\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return undefined;\n }\n throw wrapFsError(thrown, \"read\");\n }\n\n let parsedJson: unknown;\n try {\n parsedJson = JSON.parse(raw);\n } catch {\n await quarantine(filePath, key, \"invalid-json\");\n return undefined;\n }\n\n const envelope = parsedJson as Partial<Envelope>;\n if (envelope.key !== key) {\n await quarantine(filePath, key, \"key-mismatch\");\n return undefined;\n }\n const parsed = stateRecordSchema.safeParse(envelope.record);\n if (!parsed.success) {\n await quarantine(filePath, key, \"schema-invalid\");\n return undefined;\n }\n return parsed.data;\n };\n\n const writeUnlocked = async (key: string, value: StateValue): Promise<StateRecord> => {\n await ensureDirs();\n const previous = await readUnlocked(key);\n const record = stateRecordSchema.parse({\n revision: (previous?.revision ?? 0) + 1,\n updatedAt: options.clock.now(),\n value,\n });\n const envelope: Envelope = { key, record };\n const tmp = tempPath(key);\n try {\n await writeFile(tmp, JSON.stringify(envelope), \"utf8\");\n await rename(tmp, recordPath(key));\n } catch (thrown) {\n await unlink(tmp).catch(() => undefined);\n throw wrapFsError(thrown, \"write\");\n }\n return record;\n };\n\n const acquireFileLock = async (\n sessionId: string,\n timeoutMillis: number,\n ): Promise<() => Promise<void>> => {\n await ensureDirs();\n const filePath = lockPath(sessionId);\n const startedAt = options.clock.monotonicMillis();\n\n for (;;) {\n try {\n const handle = await open(filePath, \"wx\");\n try {\n await handle.writeFile(JSON.stringify({ pid: process.pid, acquiredAt: options.clock.now() }));\n } finally {\n await handle.close();\n }\n return async (): Promise<void> => {\n await unlink(filePath).catch(() => undefined);\n };\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw wrapFsError(thrown, \"lock\");\n }\n }\n\n const stale = await (async (): Promise<boolean> => {\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n return (\n typeof parsed.acquiredAt !== \"number\" ||\n options.clock.now() - parsed.acquiredAt > lockStaleMillis\n );\n } catch {\n return true;\n }\n })();\n if (stale) {\n await unlink(filePath).catch(() => undefined);\n continue;\n }\n\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n // A typed error, so a caller can tell \"a peer holds this\" apart from \"the\n // store is unusable\" — the two demand opposite responses.\n throw new StateLockTimeoutError(sessionId, timeoutMillis);\n }\n await sleep(lockPollIntervalMillis);\n }\n };\n\n return {\n recordsDir,\n quarantineDir,\n read: (key: string): Promise<StateRecord | undefined> =>\n keyLock.run(key, () => readUnlocked(key), lockTimeoutMillis),\n write: (key: string, value: StateValue): Promise<StateRecord> =>\n keyLock.run(key, () => writeUnlocked(key, value), lockTimeoutMillis),\n delete: (key: string): Promise<void> =>\n keyLock.run(\n key,\n async (): Promise<void> => {\n await ensureDirs();\n await unlink(recordPath(key)).catch((thrown: unknown) => {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"delete\");\n }\n });\n },\n lockTimeoutMillis,\n ),\n keys: async (prefix: string): Promise<readonly string[]> => {\n await ensureDirs();\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw wrapFsError(thrown, \"keys\");\n }\n const found: string[] = [];\n for (const entry of entries) {\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n let raw: string;\n try {\n raw = await readFile(path.join(recordsDir, entry), \"utf8\");\n } catch {\n continue;\n }\n try {\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n if (typeof envelope.key === \"string\" && envelope.key.startsWith(prefix)) {\n found.push(envelope.key);\n }\n } catch {\n continue;\n }\n }\n return found.sort();\n },\n withSessionLock: async <T>(\n sessionId: string,\n fn: () => Promise<T>,\n lockOptions?: { readonly timeoutMillis?: number },\n ): Promise<T> => {\n const timeoutMillis = lockOptions?.timeoutMillis ?? lockTimeoutMillis;\n return sessionLock.run(\n sessionId,\n async (): Promise<T> => {\n const release = await acquireFileLock(sessionId, timeoutMillis);\n try {\n return await fn();\n } finally {\n await release();\n }\n },\n timeoutMillis,\n );\n },\n pruneStale: async (\n maxAgeMillis: number,\n pruneOptions?: { readonly maxEntries?: number },\n ): Promise<{ readonly removed: number; readonly scanned: number }> => {\n await ensureDirs();\n const cap = pruneOptions?.maxEntries ?? 5_000;\n const now = options.clock.now();\n let removed = 0;\n let scanned = 0;\n\n let entries: string[];\n try {\n entries = await readdir(recordsDir);\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw wrapFsError(thrown, \"prune\");\n }\n entries = [];\n }\n for (const entry of entries) {\n if (scanned >= cap) {\n break;\n }\n if (!entry.endsWith(\".json\") || entry.startsWith(\".tmp-\")) {\n continue;\n }\n scanned += 1;\n const filePath = path.join(recordsDir, entry);\n try {\n // Ages are measured against the record's own `updatedAt`, taken from\n // the injected clock at write time, never the OS mtime: a test (or a\n // host) using a clock other than the wall clock would otherwise be\n // compared against a completely unrelated time source.\n const raw = await readFile(filePath, \"utf8\");\n const envelope = JSON.parse(raw) as Partial<Envelope>;\n const updatedAt = envelope.record?.updatedAt;\n if (typeof updatedAt === \"number\" && now - updatedAt > maxAgeMillis) {\n await unlink(filePath).catch(() => undefined);\n removed += 1;\n }\n } catch {\n continue;\n }\n }\n\n let lockEntries: string[];\n try {\n lockEntries = await readdir(locksDir);\n } catch {\n lockEntries = [];\n }\n for (const entry of lockEntries) {\n const filePath = path.join(locksDir, entry);\n try {\n const raw = await readFile(filePath, \"utf8\");\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown };\n if (typeof parsed.acquiredAt === \"number\" && now - parsed.acquiredAt > lockStaleMillis) {\n await unlink(filePath).catch(() => undefined);\n }\n } catch {\n continue;\n }\n }\n\n return { removed, scanned };\n },\n };\n};\n","/**\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 { createHash } from \"node:crypto\";\n\n/**\n * Segments derived from arbitrary strings must be safe path components on any\n * filesystem: no separators, no traversal, no reserved characters. Anything\n * that already looks safe is kept as-is (for readable directory names);\n * anything else is replaced by a stable hash so no input can escape its\n * namespace directory or collide with a sibling by accident.\n */\nconst SAFE_SEGMENT_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\nexport const isSafeSegment = (segment: string): boolean => SAFE_SEGMENT_PATTERN.test(segment);\n\nexport const sanitizeSegment = (segment: string): string => {\n if (isSafeSegment(segment)) {\n return segment;\n }\n return `h_${createHash(\"sha256\").update(segment, \"utf8\").digest(\"hex\").slice(0, 32)}`;\n};\n\n/** Scopes a state store to one provider deployed under one installation. */\nexport type StoreNamespace = {\n readonly providerId: string;\n readonly installationId: string;\n};\n\nexport const namespaceSegments = (namespace: StoreNamespace): readonly [string, string] => [\n sanitizeSegment(namespace.providerId),\n sanitizeSegment(namespace.installationId),\n];\n\n/** Stable, collision-resistant digest of a logical state key. */\nexport const keyDigest = (key: string): string =>\n createHash(\"sha256\").update(key, \"utf8\").digest(\"hex\");\n","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 { randomBytes } from \"node:crypto\";\nimport { mkdir, readFile, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport { namespaceSegments, type StoreNamespace } from \"../state/keys.js\";\n\nexport type SpoolEnqueueResult =\n | { readonly spooled: true }\n | { readonly spooled: false; readonly reason: \"capacity-exceeded\" };\n\nexport type SpoolDrainResult = {\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n /**\n * Batches removed from the queue because they were unusable rather than\n * undeliverable.\n *\n * Distinct from `failed`, which means \"the collector would not take it, try\n * later\". A quarantined batch will never become deliverable, so counting it\n * separately is what stops a permanent problem from reading as transient.\n */\n readonly quarantined: number;\n};\n\n/** Outcome of validating one batch read back from a queue file. */\nexport type SpoolValidation<TBatch> =\n | { readonly batch: TBatch }\n | { readonly rejection: string };\n\nexport type SpoolQueueOptions<TBatch> = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued, rather than growing without bound. */\n readonly maxFiles: number;\n /**\n * Directory holding the queue, under the identity namespace. One name per\n * signal, so a batch of one signal can never be drained by the other's sender —\n * the two encode different payloads and a mixed queue would quarantine\n * perfectly good batches.\n */\n readonly queueName: string;\n /** Re-validates a batch read back from disk, before any of it reaches a sender. */\n readonly validate: (value: unknown, identity: StoreNamespace) => SpoolValidation<TBatch>;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a later\n * invocation retry\" rather than an in-process backoff loop. Each instance is\n * rooted at `<rootDir>/<providerId>/<installationId>/<queueName>`; two queues for\n * different providers, installations, or signals never share a directory, so a\n * batch from one identity cannot physically land in another's drain — batches\n * cannot mix identities by construction, not by a runtime check alone (the check\n * inside {@link SpoolQueue.drain} is defense in depth for a hand-edited or\n * misplaced file).\n *\n * Shared by the trace and log spools rather than written twice: the drain's\n * quarantine-and-continue behavior is the subtle part, and a second copy of it is\n * a second place for the head-of-queue-blocking bug to come back.\n */\nexport interface SpoolQueue<TBatch> {\n enqueue(batch: TBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: TBatch) => Promise<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n}\n\n/** Default bound on a single drain pass, so one invocation's flush stays short. */\nexport const DEFAULT_DRAIN_MAX_BATCHES = 20;\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nexport const createSpoolQueue = <TBatch>(\n options: SpoolQueueOptions<TBatch>,\n): SpoolQueue<TBatch> => {\n const [providerSegment, installationSegment] = namespaceSegments(options);\n const queueDir = path.join(options.rootDir, providerSegment, installationSegment, options.queueName);\n const corruptDir = path.join(\n options.rootDir,\n providerSegment,\n installationSegment,\n `${options.queueName}-corrupt`,\n );\n\n let dirsReady: Promise<void> | undefined;\n const ensureDirs = async (): Promise<void> => {\n if (dirsReady !== undefined) {\n return dirsReady;\n }\n const promise = (async (): Promise<void> => {\n await mkdir(queueDir, { recursive: true });\n await mkdir(corruptDir, { recursive: true });\n })();\n dirsReady = promise;\n try {\n await promise;\n } catch (thrown) {\n dirsReady = undefined;\n throw thrown;\n }\n };\n\n const listSorted = async (): Promise<readonly string[]> => {\n let entries: string[];\n try {\n entries = await readdir(queueDir);\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return [];\n }\n throw thrown;\n }\n return entries.filter((entry) => entry.endsWith(\".json\") && !entry.startsWith(\".tmp-\")).sort();\n };\n\n const enqueue = async (batch: TBatch): Promise<SpoolEnqueueResult> => {\n await ensureDirs();\n const existing = await listSorted();\n if (existing.length >= options.maxFiles) {\n options.logger?.warn(\"durable spool at capacity; batch dropped\", {\n \"spool.max_files\": options.maxFiles,\n \"spool.queue\": options.queueName,\n });\n return { spooled: false, reason: \"capacity-exceeded\" };\n }\n const fileName = `${String(options.clock.now()).padStart(16, \"0\")}-${randomBytes(6).toString(\"hex\")}.json`;\n const target = path.join(queueDir, fileName);\n const tmp = path.join(queueDir, `.tmp-${randomBytes(6).toString(\"hex\")}.json`);\n await writeFile(tmp, JSON.stringify(batch), \"utf8\");\n await rename(tmp, target);\n return { spooled: true };\n };\n\n const drain = async (\n send: (batch: TBatch) => Promise<boolean>,\n drainOptions?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult> => {\n await ensureDirs();\n const cap = drainOptions?.maxBatches ?? DEFAULT_DRAIN_MAX_BATCHES;\n const files = await listSorted();\n let drained = 0;\n let failed = 0;\n let quarantined = 0;\n let index = 0;\n\n for (; index < files.length && index < cap; index += 1) {\n const fileName = files[index];\n if (fileName === undefined) {\n break;\n }\n const filePath = path.join(queueDir, fileName);\n\n /**\n * Move a file out of the queue, or delete it if quarantine is unavailable.\n *\n * Getting it *out of the queue* is the part that matters. A file the drain\n * cannot use and cannot move would be re-read on every pass, and because the\n * head is processed first it would block every healthy batch behind it — the\n * one failure mode a retry queue must not have. So a failed quarantine falls\n * back to deleting: losing one unusable batch beats losing all the usable\n * ones queued behind it.\n */\n const quarantine = async (rejection: string): Promise<void> => {\n quarantined += 1;\n options.logger?.error(\"durable spool quarantined an unusable batch\", {\n \"spool.rejection\": rejection,\n \"spool.file\": fileName,\n \"spool.queue\": options.queueName,\n });\n try {\n await rename(filePath, path.join(corruptDir, fileName));\n } catch {\n await unlink(filePath).catch(() => undefined);\n }\n };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(await readFile(filePath, \"utf8\")) as unknown;\n } catch {\n await quarantine(\"unparseable-json\");\n continue;\n }\n\n const validation = options.validate(parsed, {\n providerId: options.providerId,\n installationId: options.installationId,\n });\n if (\"rejection\" in validation) {\n await quarantine(validation.rejection);\n continue;\n }\n\n let delivered: boolean;\n try {\n delivered = await send(validation.batch);\n } catch {\n delivered = false;\n }\n if (delivered) {\n await unlink(filePath).catch(() => undefined);\n drained += 1;\n } else {\n failed += 1;\n break;\n }\n }\n\n const remaining = (await listSorted()).length;\n return { drained, remaining, failed, quarantined };\n };\n\n return {\n enqueue,\n drain,\n size: async (): Promise<number> => {\n await ensureDirs();\n return (await listSorted()).length;\n },\n };\n};\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n type SpoolValidation,\n} from \"./spool-queue.js\";\n\n/**\n * One log record, flattened to plain JSON so it survives a process exit.\n *\n * `body` is a string or absent, never a nested value: the mapping only ever\n * produces a disclosed text body, and admitting anything richer here would make a\n * spool file a route for a structure the live path would have refused.\n */\nexport type SerializedLogRecord = {\n readonly eventName: string;\n readonly severityNumber: number;\n readonly severityText?: string;\n readonly body?: string;\n readonly timeMillis: number;\n readonly observedTimeMillis: number;\n /** Absent only on a record that was mapped without trace correlation. */\n readonly traceId?: string;\n readonly spanId?: string;\n readonly attributes: Attributes;\n};\n\nexport type LogSpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly records: readonly SerializedLogRecord[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_LOG_RECORDS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_LOG_STRING_LENGTH = 8_192;\n/**\n * Longest replayed body.\n *\n * Matches the live mapping's `MAX_LOG_BODY_CHARACTERS`, because \"what the mapping\n * would have put on the wire\" and \"what is accepted back off disk\" diverging is\n * the whole vulnerability — a hand-edited spool file must not be able to export a\n * body the live path would have cut.\n */\nexport const MAX_SPOOLED_LOG_BODY_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_RECORD = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_LOG_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst isReplayableAttributeValue = (value: unknown): boolean => {\n if (Array.isArray(value)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not an\n // attribute and would fail encoding.\n return value.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof value === \"string\" && value.length <= MAX_SPOOLED_LOG_STRING_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\" ||\n value === undefined\n );\n};\n\n/**\n * Whether one recorded log record can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. The rebuilt record\n * goes straight to the OTLP encoder, which assumes the shapes the type declares —\n * so a `severityNumber` of `null`, a nested object in `attributes`, or a trace id\n * of the wrong width becomes an encoder error deep inside the exporter rather than\n * a rejected file here. Trace and span ids are held to their hex forms because a\n * malformed id is not a correlation a collector can resolve.\n */\nconst isReplayableLogRecord = (value: unknown): value is SerializedLogRecord => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.eventName)) {\n return false;\n }\n if (!isFiniteNonNegative(value.severityNumber)) {\n return false;\n }\n if (value.severityText !== undefined && typeof value.severityText !== \"string\") {\n return false;\n }\n if (\n value.body !== undefined &&\n (typeof value.body !== \"string\" || value.body.length > MAX_SPOOLED_LOG_BODY_LENGTH)\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.timeMillis) || !isFiniteNonNegative(value.observedTimeMillis)) {\n return false;\n }\n // Correlation is all-or-nothing: a trace id without a span id (or the reverse)\n // is not a span reference, and half of one would export as a record pointing at\n // span `0000000000000000`.\n const hasTrace = value.traceId !== undefined;\n const hasSpan = value.spanId !== undefined;\n if (hasTrace !== hasSpan) {\n return false;\n }\n if (hasTrace && (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId))) {\n return false;\n }\n if (hasSpan && (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId))) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_RECORD) {\n return false;\n }\n return entries.every(([, attribute]) => isReplayableAttributeValue(attribute));\n};\n\nexport type LogSpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"records-invalid\"\n | \"record-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `records` being anything other than an\n * array makes the sender's `records.map(...)` throw, and a throwing send is\n * indistinguishable from an unreachable collector — so the drain would treat a\n * permanently poisoned file as a transient failure and stop at it on every pass,\n * wedging the queue head and every batch behind it forever. Validation is what\n * turns that into a single quarantined file.\n */\nexport const validateLogSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): SpoolValidation<LogSpoolBatch> => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" satisfies LogSpoolBatchRejection };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: the resource is rebuilt by iterating it, and a string or\n // an array would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n !isPlainObject(value.instrumentationScope) ||\n !isBoundedString(value.instrumentationScope.name)\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!Array.isArray(value.records) || value.records.length === 0) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (value.records.length > MAX_SPOOLED_LOG_RECORDS_PER_BATCH) {\n return { rejection: \"records-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!value.records.every(isReplayableLogRecord)) {\n return { rejection: \"record-field-invalid\" satisfies LogSpoolBatchRejection };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" satisfies LogSpoolBatchRejection };\n }\n return { batch: value as unknown as LogSpoolBatch };\n};\n\nexport type DurableLogSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued. Default 500. */\n readonly maxSpoolFiles?: number;\n};\n\n/**\n * Durable filesystem queue for log batches a collector could not accept.\n *\n * Rooted at `<rootDir>/<providerId>/<installationId>/spool-logs`, deliberately a\n * different directory from the trace spool: the two hold different encodings, so a\n * single mixed queue would have each signal's sender quarantining the other's\n * perfectly deliverable batches. Separate directories also mean a logs outage\n * cannot consume the trace spool's capacity, which is what keeps the primary\n * signal unaffected by a misconfigured logs endpoint.\n */\nexport interface DurableLogSpool {\n enqueue(batch: LogSpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: LogSpoolBatch) => Promise<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n}\n\nexport const DEFAULT_MAX_LOG_SPOOL_FILES = 500;\n\nexport const createFileDurableLogSpool = (options: DurableLogSpoolOptions): DurableLogSpool =>\n createSpoolQueue<LogSpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_LOG_SPOOL_FILES,\n queueName: \"spool-logs\",\n validate: validateLogSpoolBatch,\n });\n","import type { Attributes } from \"@opentelemetry/api\";\n\nimport type { Clock, Logger } from \"../runtime/ports.js\";\nimport type { StoreNamespace } from \"../state/keys.js\";\n// Deliberately not re-exported: `spool-queue.js` is their one home, and a second\n// `export *` path to the same names makes them ambiguous in the barrel below.\nimport {\n createSpoolQueue,\n type SpoolDrainResult,\n type SpoolEnqueueResult,\n} from \"./spool-queue.js\";\n\nexport type SerializedSpan = {\n readonly name: string;\n readonly kind: number;\n readonly traceId: string;\n readonly spanId: string;\n /** Absent on batches spooled before cross-process parenting existed, and on root spans. */\n readonly parentSpanId?: string;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly statusCode: number;\n readonly statusMessage?: string;\n};\n\nexport type SpoolBatch = {\n readonly providerId: string;\n readonly installationId: string;\n readonly resourceAttributes: Attributes;\n readonly instrumentationScope: { readonly name: string; readonly version?: string };\n readonly spans: readonly SerializedSpan[];\n readonly enqueuedAt: number;\n};\n\n/** Upper bounds on a replayed batch. A spool file is untrusted input. */\nexport const MAX_SPOOLED_SPANS_PER_BATCH = 4_096;\nexport const MAX_SPOOLED_STRING_LENGTH = 8_192;\nconst MAX_SPOOLED_ATTRIBUTES_PER_SPAN = 256;\nconst TRACE_ID_PATTERN = /^[0-9a-f]{32}$/;\nconst SPAN_ID_PATTERN = /^[0-9a-f]{16}$/;\n\nconst isFiniteNonNegative = (value: unknown): value is number =>\n typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n\nconst isBoundedString = (value: unknown, maxLength = MAX_SPOOLED_STRING_LENGTH): value is string =>\n typeof value === \"string\" && value.length > 0 && value.length <= maxLength;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Whether one recorded span can be replayed.\n *\n * Every field is checked, not just the ones a happy path reads. `assembleReadableSpan`\n * hands its output straight to the OTLP encoder, which assumes the shapes the type\n * declares — so a `spanId` of the wrong length, a `startMillis` of `null`, or an\n * `attributes` value holding a nested object becomes an encoder error deep inside\n * the exporter rather than a rejected file here. Trace and span ids are further held\n * to their hex forms, because a malformed id is not a span a collector can place.\n */\nconst isReplayableSpan = (value: unknown): value is SerializedSpan => {\n if (!isPlainObject(value)) {\n return false;\n }\n if (!isBoundedString(value.name) || !isFiniteNonNegative(value.kind)) {\n return false;\n }\n if (typeof value.traceId !== \"string\" || !TRACE_ID_PATTERN.test(value.traceId)) {\n return false;\n }\n if (typeof value.spanId !== \"string\" || !SPAN_ID_PATTERN.test(value.spanId)) {\n return false;\n }\n if (\n value.parentSpanId !== undefined &&\n (typeof value.parentSpanId !== \"string\" || !SPAN_ID_PATTERN.test(value.parentSpanId))\n ) {\n return false;\n }\n if (!isFiniteNonNegative(value.startMillis) || !isFiniteNonNegative(value.endMillis)) {\n return false;\n }\n if (!isFiniteNonNegative(value.statusCode)) {\n return false;\n }\n if (\n value.statusMessage !== undefined &&\n typeof value.statusMessage !== \"string\"\n ) {\n return false;\n }\n if (!isPlainObject(value.attributes)) {\n return false;\n }\n const entries = Object.entries(value.attributes);\n if (entries.length > MAX_SPOOLED_ATTRIBUTES_PER_SPAN) {\n return false;\n }\n return entries.every(([, attribute]) => {\n if (Array.isArray(attribute)) {\n // OTLP permits homogeneous primitive arrays; anything nested is not a span\n // attribute and would fail encoding.\n return attribute.every(\n (item) =>\n (typeof item === \"string\" && item.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof item === \"number\" && Number.isFinite(item)) ||\n typeof item === \"boolean\" ||\n item === null,\n );\n }\n return (\n (typeof attribute === \"string\" && attribute.length <= MAX_SPOOLED_STRING_LENGTH) ||\n (typeof attribute === \"number\" && Number.isFinite(attribute)) ||\n typeof attribute === \"boolean\" ||\n attribute === undefined\n );\n });\n};\n\nexport type SpoolBatchRejection =\n | \"not-an-object\"\n | \"identity-mismatch\"\n | \"resource-attributes-invalid\"\n | \"instrumentation-scope-invalid\"\n | \"spans-invalid\"\n | \"span-field-invalid\";\n\n/**\n * Validate a whole batch read back from disk, before any of it reaches an exporter.\n *\n * The identity check alone is not enough. `spans` being anything other than an array\n * makes the sink's `spans.map(...)` throw, and a throwing send is indistinguishable\n * from an unreachable collector — so the drain would treat a permanently poisoned\n * file as a transient failure and stop at it on every pass, wedging the queue head\n * and every batch behind it forever. Validation is what turns that into a single\n * quarantined file.\n */\nexport const validateSpoolBatch = (\n value: unknown,\n identity: StoreNamespace,\n): { readonly batch: SpoolBatch } | { readonly rejection: SpoolBatchRejection } => {\n if (!isPlainObject(value)) {\n return { rejection: \"not-an-object\" };\n }\n if (\n value.providerId !== identity.providerId ||\n value.installationId !== identity.installationId\n ) {\n return { rejection: \"identity-mismatch\" };\n }\n if (!isPlainObject(value.resourceAttributes)) {\n // Not merely absent: `replayResource` iterates it, and a string or an array\n // would silently produce a resource built from its indices.\n return { rejection: \"resource-attributes-invalid\" };\n }\n if (!isPlainObject(value.instrumentationScope) || !isBoundedString(value.instrumentationScope.name)) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (\n value.instrumentationScope.version !== undefined &&\n typeof value.instrumentationScope.version !== \"string\"\n ) {\n return { rejection: \"instrumentation-scope-invalid\" };\n }\n if (!Array.isArray(value.spans) || value.spans.length === 0) {\n return { rejection: \"spans-invalid\" };\n }\n if (value.spans.length > MAX_SPOOLED_SPANS_PER_BATCH) {\n return { rejection: \"spans-invalid\" };\n }\n if (!value.spans.every(isReplayableSpan)) {\n return { rejection: \"span-field-invalid\" };\n }\n if (!isFiniteNonNegative(value.enqueuedAt)) {\n return { rejection: \"not-an-object\" };\n }\n return { batch: value as unknown as SpoolBatch };\n};\n\nexport type DurableSpoolOptions = StoreNamespace & {\n readonly rootDir: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Refuses new entries once this many are queued, rather than growing without bound. Default 500. */\n readonly maxSpoolFiles?: number;\n};\n\n/**\n * Durable filesystem queue for export batches a collector could not accept.\n *\n * A hook process is short-lived, so \"retry later\" means \"persist and let a\n * later invocation retry\" rather than an in-process backoff loop. Each\n * instance is rooted at `<rootDir>/<providerId>/<installationId>/spool`; two\n * spools for different providers or installations never share a directory,\n * so a batch from one identity cannot physically land in another's drain —\n * batches cannot mix identities by construction, not by a runtime check\n * alone (the check in {@link DurableSpool.drain} is defense in depth for a\n * hand-edited or misplaced file).\n */\nexport interface DurableSpool {\n enqueue(batch: SpoolBatch): Promise<SpoolEnqueueResult>;\n /** Sequential, bounded drain: stops after the first failed send, or after `maxBatches`. */\n drain(\n send: (batch: SpoolBatch) => Promise<boolean>,\n options?: { readonly maxBatches?: number },\n ): Promise<SpoolDrainResult>;\n size(): Promise<number>;\n}\n\n/** Default bound on queued trace batches, so the spool cannot grow without limit. */\nexport const DEFAULT_MAX_SPOOL_FILES = 500;\n\nexport const createFileDurableSpool = (options: DurableSpoolOptions): DurableSpool =>\n createSpoolQueue<SpoolBatch>({\n rootDir: options.rootDir,\n providerId: options.providerId,\n installationId: options.installationId,\n clock: options.clock,\n ...(options.logger === undefined ? {} : { logger: options.logger }),\n maxFiles: options.maxSpoolFiles ?? DEFAULT_MAX_SPOOL_FILES,\n queueName: \"spool\",\n validate: validateSpoolBatch,\n });\n","import { TraceFlags, type AttributeValue, type Attributes, type SpanContext } from \"@opentelemetry/api\";\nimport type { LogAttributes } from \"@opentelemetry/api-logs\";\nimport { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport { OTLPLogExporter } from \"@opentelemetry/exporter-logs-otlp-proto\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\n\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableLogSpool, LogSpoolBatch, SerializedLogRecord } from \"./durable-log-spool.js\";\nimport { replayResource, resourceFromExporterPolicy } from \"./exporter-resource.js\";\nimport {\n canonicalEventsToLogRecords,\n NO_LOG_CONTENT,\n type LogContentPolicy,\n} from \"./log-records.js\";\nimport {\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\n/**\n * OTLP HTTP/protobuf log sink.\n *\n * The logs counterpart of `otlp-sink.ts`, and deliberately its mirror image:\n * semantic mapping lives entirely in `log-records.ts`, and this module owns only\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a spool\n * is configured — persisting what a down collector rejected. Every failure mode\n * (disabled config, missing or underivable endpoint, export failure, timeout,\n * spool write failure) degrades to a reported diagnostic rather than a thrown\n * error, preserving the hook's fail-open contract.\n *\n * The two sinks are separate objects rather than one exporter with two encoders\n * because they fail independently: a collector that has no logs receiver, or an\n * operator who pointed logs at the wrong port, must cost the logs signal and\n * nothing else. The trace pipeline is the one an installation already depends on.\n */\n\nconst OTLP_TRACES_PATH = \"/v1/traces\";\nconst OTLP_LOGS_PATH = \"/v1/logs\";\n\n/**\n * Strip trailing slashes, by scan rather than by regex.\n *\n * `/\\/+$/` is a polynomial-ReDoS on this input: an endpoint of many `/` followed by\n * anything else makes the engine retry the `+` from every position. The endpoint is\n * operator-supplied configuration bounded to 2048 characters, so the practical cost\n * is small — but a linear scan is just as short, and the bound is not the guarantee.\n */\nconst withoutTrailingSlashes = (value: string): string => {\n let end = value.length;\n while (end > 0 && value.charCodeAt(end - 1) === 0x2f) {\n end -= 1;\n }\n return value.slice(0, end);\n};\n\n/**\n * Where log records are posted.\n *\n * Resolution order, highest first:\n *\n * 1. `logs.endpoint` — stated outright, used verbatim.\n * 2. the trace endpoint with a trailing `/v1/traces` swapped for `/v1/logs`, which\n * is the shape a collector configured for both signals actually has.\n * 3. the trace endpoint treated as a base URL, with `/v1/logs` appended — the\n * convention the OTLP specification defines for a signal-less endpoint.\n *\n * Returned as a discriminated result rather than a bare string because \"no logs\n * endpoint could be derived\" has to be reportable: silently posting an\n * `ExportLogsServiceRequest` to a traces receiver produces a rejection whose cause\n * is a configuration mistake, and an operator reading \"collector rejected a batch\"\n * would go looking at the collector.\n */\nexport const resolveLogsEndpoint = (\n exporter: ExporterPolicy,\n): { readonly endpoint: string; readonly derived: boolean } | { readonly unresolvable: \"no-endpoint\" } => {\n if (exporter.logs.endpoint !== undefined) {\n return { endpoint: exporter.logs.endpoint, derived: false };\n }\n if (exporter.endpoint === undefined) {\n return { unresolvable: \"no-endpoint\" };\n }\n const trimmed = withoutTrailingSlashes(exporter.endpoint);\n if (trimmed.endsWith(OTLP_LOGS_PATH)) {\n return { endpoint: trimmed, derived: true };\n }\n if (trimmed.endsWith(OTLP_TRACES_PATH)) {\n return {\n endpoint: `${trimmed.slice(0, trimmed.length - OTLP_TRACES_PATH.length)}${OTLP_LOGS_PATH}`,\n derived: true,\n };\n }\n return { endpoint: `${trimmed}${OTLP_LOGS_PATH}`, derived: true };\n};\n\n/**\n * Narrow a log record's attributes to what a spool file can hold.\n *\n * `LogAttributes` admits nested maps and byte strings; the spool's own validator\n * does not, and neither does `assembleReadableSpan`'s sibling contract for traces.\n * This mapping only ever produces primitives, so the filter is unreachable in\n * practice — it is here so that \"what the live path emits\" and \"what survives a\n * spool round-trip\" cannot silently diverge if a future attribute is richer than\n * the queue's schema.\n */\nconst toSpoolAttributes = (attributes: LogAttributes): Attributes => {\n const safe: Record<string, AttributeValue> = {};\n for (const [key, value] of Object.entries(attributes)) {\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n safe[key] = value;\n continue;\n }\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) {\n safe[key] = value;\n }\n }\n return safe;\n};\n\nconst serializeRecord = (record: ReadableLogRecord): SerializedLogRecord => {\n const context = record.spanContext;\n return {\n eventName: record.eventName ?? \"otelhook.record\",\n severityNumber: record.severityNumber ?? 0,\n ...(record.severityText === undefined ? {} : { severityText: record.severityText }),\n ...(typeof record.body === \"string\" ? { body: record.body } : {}),\n timeMillis: record.hrTime[0] * 1000 + Math.round(record.hrTime[1] / 1e6),\n observedTimeMillis:\n record.hrTimeObserved[0] * 1000 + Math.round(record.hrTimeObserved[1] / 1e6),\n ...(context === undefined ? {} : { traceId: context.traceId, spanId: context.spanId }),\n attributes: toSpoolAttributes(record.attributes),\n };\n};\n\nconst deserializeRecord = (\n serialized: SerializedLogRecord,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableLogRecord => {\n const spanContext: SpanContext | undefined =\n serialized.traceId === undefined || serialized.spanId === undefined\n ? undefined\n : {\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n return {\n hrTime: millisToHrTime(serialized.timeMillis),\n hrTimeObserved: millisToHrTime(serialized.observedTimeMillis),\n ...(spanContext === undefined ? {} : { spanContext }),\n severityNumber: serialized.severityNumber,\n ...(serialized.severityText === undefined ? {} : { severityText: serialized.severityText }),\n ...(serialized.body === undefined ? {} : { body: serialized.body }),\n eventName: serialized.eventName,\n resource,\n instrumentationScope: scope,\n attributes: serialized.attributes,\n droppedAttributesCount: 0,\n };\n};\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nexport type OtlpLogSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableLogSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Whether disclosed content text may reach a log body. Defaults to\n * {@link NO_LOG_CONTENT}, which is what an unconfigured installation gets.\n */\n readonly content?: LogContentPolicy;\n /**\n * Supplies cross-process pairing so a record correlates to the span id the trace\n * pipeline actually exported. Omitted, records still carry a derived trace and\n * span id, computed from the batch alone.\n *\n * Injected as a plain function rather than as a correlator so the telemetry layer\n * keeps no dependency on lifecycle or on the state store (ADR 0006). When both\n * sinks are wired, the fanout resolves correlation *once* and hands the same\n * answer to each — `correlateBatch` writes state, so calling it twice per batch\n * would record a start edge twice.\n */\n readonly correlate?: SpanCorrelationResolver;\n};\n\nexport interface OtlpLogTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/**\n * Sink that swallows every batch: logs disabled, or configured but unroutable.\n *\n * Reports **zero accepted and zero rejected**, which is the one place this differs\n * from the trace sink's disabled path — and it has to. The counts a sink returns are\n * what `classifyDurability` decides commit-or-retry from, and they are summed across\n * signals. A disabled signal that claimed to have accepted the batch would make a\n * *total* trace loss look like a partial delivery: `accepted > 0` from a sink that\n * sent nothing, `rejected > 0` from the sink that failed, so the callback would\n * commit as terminally-partial instead of releasing its claim for retry. Contributing\n * nothing is the truthful answer, and it leaves durability decided entirely by the\n * signals that actually tried — so an installation with logs off behaves exactly as\n * it did before logs existed.\n *\n * Health still records the batch as accepted: nothing failed, and a disabled signal\n * must not read as unhealthy.\n */\nconst createDisabledSink = (): OtlpLogTelemetrySink => {\n const health = createHealthTracker(\"telemetry-log-sink\");\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: 0, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{\n readonly drained: number;\n readonly remaining: number;\n readonly failed: number;\n }> => Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * Whether this configuration can deliver logs at all.\n *\n * Separated from the constructor so `doctor` can report the same verdict without\n * building an exporter, and so each refusal names itself rather than collapsing\n * into one \"disabled\" state an operator then has to bisect.\n */\nexport type LogsDeliverability =\n | { readonly status: \"configured\"; readonly endpoint: string; readonly derivedEndpoint: boolean }\n | {\n readonly status: \"disabled\";\n readonly reason:\n | \"logs-disabled\"\n | \"exporter-disabled\"\n | \"protocol-none\"\n | \"protocol-unsupported\"\n | \"no-endpoint\";\n };\n\nexport const describeLogsDeliverability = (exporter: ExporterPolicy): LogsDeliverability => {\n if (!exporter.logs.enabled) {\n return { status: \"disabled\", reason: \"logs-disabled\" };\n }\n if (!exporter.enabled) {\n return { status: \"disabled\", reason: \"exporter-disabled\" };\n }\n if (exporter.protocol === \"none\") {\n return { status: \"disabled\", reason: \"protocol-none\" };\n }\n if (exporter.protocol !== \"http/protobuf\") {\n return { status: \"disabled\", reason: \"protocol-unsupported\" };\n }\n const resolved = resolveLogsEndpoint(exporter);\n if (\"unresolvable\" in resolved) {\n return { status: \"disabled\", reason: \"no-endpoint\" };\n }\n return { status: \"configured\", endpoint: resolved.endpoint, derivedEndpoint: resolved.derived };\n};\n\nconst DISABLED_DETAIL: Readonly<Record<Extract<LogsDeliverability, { status: \"disabled\" }>[\"reason\"], string>> =\n Object.freeze({\n \"logs-disabled\": \"otlp log sink disabled: exporter.logs.enabled is false\",\n \"exporter-disabled\": \"otlp log sink disabled: the exporter is disabled\",\n \"protocol-none\": \"otlp log sink disabled: protocol is none\",\n \"protocol-unsupported\":\n \"otlp log sink disabled: protocol not supported by this build, falling back to disabled\",\n \"no-endpoint\": \"otlp log sink disabled: no logs endpoint configured and none could be derived\",\n });\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink} for the logs signal.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is no\n * span to correlate to, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpLogSink = (options: OtlpLogSinkOptions): OtlpLogTelemetrySink => {\n const deliverability = describeLogsDeliverability(options.exporter);\n if (deliverability.status === \"disabled\") {\n if (deliverability.reason !== \"logs-disabled\") {\n // `logs-disabled` is the default posture, not a misconfiguration, so it is\n // not worth a warning on every invocation. The rest are: somebody asked for\n // logs and will not get them.\n options.logger?.warn(DISABLED_DETAIL[deliverability.reason], {\n \"exporter.protocol\": options.exporter.protocol,\n });\n }\n return createDisabledSink();\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const content = options.content ?? NO_LOG_CONTENT;\n const health = createHealthTracker(\"telemetry-log-sink\");\n const exporter = new OTLPLogExporter({\n url: deliverability.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportRecords = (records: readonly ReadableLogRecord[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...records], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (records: readonly ReadableLogRecord[]): LogSpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...resource.attributes },\n instrumentationScope: {\n name: scope.name,\n ...(scope.version === undefined ? {} : { version: scope.version }),\n },\n records: records.map(serializeRecord),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: LogSpoolBatch): Promise<boolean> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const records = batch.records.map((record) =>\n deserializeRecord(record, batchResource, batch.instrumentationScope),\n );\n const result = await exportRecords(records);\n return result.code === ExportResultCode.SUCCESS;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each record correlated from the batch\n * alone rather than dropped.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting uncorrelated log records\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n const mapped = canonicalEventsToLogRecords(events, {\n resource,\n instrumentationScope: scope,\n content,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n if (mapped.droppedFacts > 0) {\n // Said out loud rather than truncated silently: a caller that saw only\n // \"accepted\" would read a clipped batch as a complete one.\n options.logger?.warn(\"log records dropped: batch or per-event bound reached\", {\n \"logs.dropped_facts\": mapped.droppedFacts,\n });\n }\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(mapped.records, options.exporter.logs.maxBatchSize)) {\n if (batch.length === 0) {\n continue;\n }\n let result: ExportResult;\n try {\n result = await exportRecords(batch);\n } catch (thrown) {\n result = {\n code: ExportResultCode.FAILED,\n error: thrown instanceof Error ? thrown : new Error(\"export threw\"),\n };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n if (options.spool !== undefined) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"collector rejected or was unreachable for a log record batch\",\n details: { \"export.batch_size\": batch.length, \"export.signal\": \"logs\" },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, {\n ...(maxBatches === undefined ? {} : { maxBatches }),\n });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type * as api from '@opentelemetry/api';\nimport { otperformance as performance } from '../platform';\n\nconst NANOSECOND_DIGITS = 9;\nconst NANOSECOND_DIGITS_IN_MILLIS = 6;\nconst MILLISECONDS_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS_IN_MILLIS);\nconst SECOND_TO_NANOSECONDS = Math.pow(10, NANOSECOND_DIGITS);\n\n/**\n * Converts a number of milliseconds from epoch to HrTime([seconds, remainder in nanoseconds]).\n * @param epochMillis\n */\nexport function millisToHrTime(epochMillis: number): api.HrTime {\n const epochSeconds = epochMillis / 1000;\n // Decimals only.\n const seconds = Math.trunc(epochSeconds);\n // Round sub-nanosecond accuracy to nanosecond.\n const nanos = Math.round((epochMillis % 1000) * MILLISECONDS_TO_NANOSECONDS);\n return [seconds, nanos];\n}\n\n/**\n * @deprecated Use `performance.timeOrigin` directly.\n */\nexport function getTimeOrigin(): number {\n return performance.timeOrigin;\n}\n\n/**\n * Returns an hrtime calculated via performance component.\n * @param performanceNow\n */\nexport function hrTime(performanceNow?: number): api.HrTime {\n const timeOrigin = millisToHrTime(performance.timeOrigin);\n const now = millisToHrTime(\n typeof performanceNow === 'number' ? performanceNow : performance.now()\n );\n\n return addHrTimes(timeOrigin, now);\n}\n\n/**\n *\n * Converts a TimeInput to an HrTime, defaults to _hrtime().\n * @param time\n */\nexport function timeInputToHrTime(time: api.TimeInput): api.HrTime {\n // process.hrtime\n if (isTimeInputHrTime(time)) {\n return time as api.HrTime;\n } else if (typeof time === 'number') {\n // Distinguish between a relative performance.now() value and an absolute\n // epoch-millisecond timestamp.\n //\n // performance.timeOrigin uses a monotonic clock that may be slightly ahead\n // of Date.now() due to clock adjustments (see MDN docs). This means a\n // real epoch-ms value (e.g. Date.now()) can land just below\n // performance.timeOrigin, causing it to be misclassified as a relative\n // performance.now() reading and doubled when timeOrigin is added.\n //\n // A genuine performance.now() value represents elapsed time since the\n // document/process started, so it is bounded by system uptime. No real\n // system has been running long enough for performance.now() to reach half\n // the current epoch time (~1994 in ms terms). We therefore treat any value\n // below half of performance.timeOrigin as a relative performance.now()\n // reading, and everything else as an absolute epoch-millisecond timestamp.\n if (time < performance.timeOrigin / 2) {\n return hrTime(time);\n } else {\n // epoch milliseconds or performance.timeOrigin\n return millisToHrTime(time);\n }\n } else if (time instanceof Date) {\n return millisToHrTime(time.getTime());\n } else {\n throw TypeError('Invalid input type');\n }\n}\n\n/**\n * Returns a duration of two hrTime.\n * @param startTime\n * @param endTime\n */\nexport function hrTimeDuration(\n startTime: api.HrTime,\n endTime: api.HrTime\n): api.HrTime {\n let seconds = endTime[0] - startTime[0];\n let nanos = endTime[1] - startTime[1];\n\n // overflow\n if (nanos < 0) {\n seconds -= 1;\n // negate\n nanos += SECOND_TO_NANOSECONDS;\n }\n\n return [seconds, nanos];\n}\n\n/**\n * Convert hrTime to timestamp, for example \"2019-05-14T17:00:00.000123456Z\"\n * @param time\n */\nexport function hrTimeToTimeStamp(time: api.HrTime): string {\n const precision = NANOSECOND_DIGITS;\n const tmp = `${'0'.repeat(precision)}${time[1]}Z`;\n const nanoString = tmp.substring(tmp.length - precision - 1);\n const date = new Date(time[0] * 1000).toISOString();\n return date.replace('000Z', nanoString);\n}\n\n/**\n * Convert hrTime to nanoseconds.\n * @param time\n */\nexport function hrTimeToNanoseconds(time: api.HrTime): number {\n return time[0] * SECOND_TO_NANOSECONDS + time[1];\n}\n\n/**\n * Convert hrTime to microseconds.\n * @param time\n */\nexport function hrTimeToMicroseconds(time: api.HrTime): number {\n return time[0] * 1e6 + time[1] / 1e3;\n}\n\n/**\n * Convert hrTime to milliseconds.\n * @param time\n */\nexport function hrTimeToMilliseconds(time: api.HrTime): number {\n return time[0] * 1e3 + time[1] / 1e6;\n}\n\n/**\n * Convert hrTime to seconds.\n * @param time\n */\nexport function hrTimeToSeconds(time: api.HrTime): number {\n return time[0] + time[1] / SECOND_TO_NANOSECONDS;\n}\n/**\n * check if time is HrTime\n * @param value\n */\nexport function isTimeInputHrTime(value: unknown): value is api.HrTime {\n return (\n Array.isArray(value) &&\n value.length === 2 &&\n typeof value[0] === 'number' &&\n typeof value[1] === 'number'\n );\n}\n\n/**\n * check if input value is a correct types.TimeInput\n * @param value\n */\nexport function isTimeInput(\n value: unknown\n): value is api.HrTime | number | Date {\n return (\n isTimeInputHrTime(value) ||\n typeof value === 'number' ||\n value instanceof Date\n );\n}\n\n/**\n * Given 2 HrTime formatted times, return their sum as an HrTime.\n */\nexport function addHrTimes(time1: api.HrTime, time2: api.HrTime): api.HrTime {\n const out = [time1[0] + time2[0], time1[1] + time2[1]] as api.HrTime;\n\n // Nanoseconds\n if (out[1] >= SECOND_TO_NANOSECONDS) {\n out[1] -= SECOND_TO_NANOSECONDS;\n out[0] += 1;\n }\n\n return out;\n}\n","/*\n * Copyright The OpenTelemetry Authors\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport interface ExportResult {\n code: ExportResultCode;\n error?: Error;\n}\n\nexport enum ExportResultCode {\n SUCCESS,\n FAILED,\n}\n","import { resourceFromAttributes, type Resource } from \"@opentelemetry/resources\";\nimport type { Attributes } from \"@opentelemetry/api\";\n\nimport {\n checkResourceAttributeKey,\n isReservedResourceAttributeKey,\n MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH,\n MAX_RESOURCE_ATTRIBUTES,\n sanitizeResourceAttributes,\n} from \"../config/resource-attributes.js\";\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { MAX_IDENTIFIER_LENGTH } from \"../model/primitives.js\";\n\n/**\n * The OTLP `Resource` every record of a signal is exported under.\n *\n * Shared by the trace and log sinks rather than written twice: a resource carries\n * the service identity, so two sinks disagreeing about how it is built or\n * re-validated would attribute the same installation's two signals to two\n * services — and the divergence would only be visible in a backend, long after.\n */\n\n/**\n * Resource for the live path, from exporter policy.\n *\n * Custom attributes first, then service identity: spread order makes the policy\n * fields structurally unoverridable. `sanitizeResourceAttributes` already drops\n * the reserved keys, so this is belt-and-braces for a caller who hand-built an\n * `ExporterPolicy` without running it through the schema — but between them,\n * `service.name` can only ever come from policy.\n */\nexport const resourceFromExporterPolicy = (policy: ExporterPolicy): Resource =>\n resourceFromAttributes({\n ...sanitizeResourceAttributes(policy.resourceAttributes),\n \"service.name\": policy.serviceName,\n ...(policy.serviceNamespace === undefined\n ? {}\n : { \"service.namespace\": policy.serviceNamespace }),\n });\n\n/**\n * A spool file is a plain JSON file in a state directory, so everything read back\n * out of one is untrusted input — it can be hand-edited, truncated, or written by\n * an older release with a different schema. These bounds mirror the live path's,\n * because \"what the exporter would have refused from a flag\" and \"what it accepts\n * from disk\" diverging is the whole vulnerability.\n */\nconst isReplayableValue = (value: unknown): value is string | number | boolean =>\n (typeof value === \"string\" && value.length <= MAX_RESOURCE_ATTRIBUTE_VALUE_LENGTH) ||\n (typeof value === \"number\" && Number.isFinite(value)) ||\n typeof value === \"boolean\";\n\n/**\n * Validate a service identity read back from a spool file.\n *\n * `service.name` decides which service every replayed record is attributed to, so\n * a spool that could set it freely could attribute this installation's telemetry\n * to somebody else's service — the one resource field where a forged value is a\n * reporting-integrity problem rather than a cosmetic one. It is therefore held to\n * the same contract as the typed policy field: a non-empty string within\n * {@link MAX_IDENTIFIER_LENGTH}. Anything else is not \"replayed as recorded\", it is\n * discarded in favour of the draining process's own policy.\n */\nconst replayableServiceIdentity = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 && value.length <= MAX_IDENTIFIER_LENGTH\n ? value\n : undefined;\n\n/**\n * Rebuild the resource a spooled batch was recorded with.\n *\n * A recorded `service.name` is a fact about the process that made the observation,\n * not about the one draining the spool, so a *valid* one is replayed as recorded.\n * But every field is re-validated on the way out, at the same bounds the live path\n * enforces: custom keys must pass {@link checkResourceAttributeKey} (which refuses\n * reserved and secret-looking names), values must be primitives within the length\n * bound, the custom count is capped, and the two reserved service fields must look\n * like the identifiers they are. A batch that fails the service check falls back to\n * the live policy rather than exporting with no service identity, because a resource\n * without `service.name` is rejected or bucketed as \"unknown_service\" by most\n * collectors — losing the batch to a tampered byte would make the validation itself\n * the outage.\n */\nexport const replayResource = (attributes: Attributes, policy: ExporterPolicy): Resource => {\n const safe: Record<string, string | number | boolean> = {};\n let customCount = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (isReservedResourceAttributeKey(key)) {\n // Handled below against the policy fallback, never copied verbatim.\n continue;\n }\n if (!isReplayableValue(value)) {\n continue;\n }\n if (checkResourceAttributeKey(key) !== undefined || customCount >= MAX_RESOURCE_ATTRIBUTES) {\n continue;\n }\n customCount += 1;\n safe[key] = value;\n }\n\n // Reserved keys last and unconditionally, so a spooled custom attribute can\n // never occupy the slot a service field is about to be written into.\n const recordedName = replayableServiceIdentity(attributes[\"service.name\"]);\n const recordedNamespace = replayableServiceIdentity(attributes[\"service.namespace\"]);\n safe[\"service.name\"] = recordedName ?? policy.serviceName;\n const namespace = recordedNamespace ?? policy.serviceNamespace;\n if (namespace !== undefined) {\n safe[\"service.namespace\"] = namespace;\n }\n\n return resourceFromAttributes(safe);\n};\n","import { TraceFlags, type SpanContext } from \"@opentelemetry/api\";\nimport { SeverityNumber, type LogAttributes } from \"@opentelemetry/api-logs\";\nimport { millisToHrTime, type InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableLogRecord } from \"@opentelemetry/sdk-logs\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_SESSION_ID,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { ContentFact } from \"../model/content.js\";\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport {\n canonicalEventTraceIdentities,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n} from \"./semconv.js\";\n\n/**\n * Pure, stateless canonical-event-to-OTLP-log-record mapping.\n *\n * The counterpart of `semconv.ts` for the logs signal, and deliberately the same\n * shape: no state is read here, no clock is consulted, and the only inputs are\n * the batch plus the correlations the caller already resolved. Batching, retry,\n * spooling, and delivery live in `otlp-log-sink.ts`.\n *\n * ## Why logs at all, when traces already exist\n *\n * A span reports that a tool call happened, how long it took, and whether it\n * failed. It does not report *what was in it*, and it cannot: span attributes are\n * a flat bounded map, one record per span, exported once. A conversation turn is a\n * sequence of distinct pieces of content — a prompt, a response, reasoning, a tool\n * input, a tool output — each with its own role, its own length, and its own\n * disclosure decision. That is a log stream, and OTLP has one.\n *\n * So this mapping emits **one record per content fact**, plus one record per event\n * that carries no content, and correlates every record to the span the same batch\n * produced (or will produce). Nothing here decides *whether* content is\n * disclosed — the privacy service already did that, upstream, once — but the\n * gate is re-checked here because this is the last boundary before the wire.\n *\n * ## Identity and correlation\n *\n * Every record carries the same identity attributes a span does, and a\n * `spanContext` built from {@link canonicalEventTraceIdentities}: the trace id and\n * span id are derived from the event's own `(providerId, sessionId)` and its\n * lifecycle scope, so a record lands in the same trace as its span without either\n * signal knowing about the other. Two sessions in one batch derive two trace ids;\n * there is no batch-level or module-level trace state to contaminate.\n */\n\n/**\n * Version of this mapping.\n *\n * Consumers pin it. Bumped on any change to what an existing attribute or signal\n * *means*; adding a new attribute or a new signal value does not bump it, on the\n * same additive-compatibility rule the canonical model follows\n * (`CANONICAL_SCHEMA_VERSION`). Every record carries it as\n * `otelhook.log.mapping_version`, so a consumer never has to infer which\n * vocabulary it is reading.\n */\nexport const LOG_MAPPING_VERSION = 1 as const;\n\n/**\n * Coarse routing key for one log record.\n *\n * The fact's own `otelhook.content.kind` states precisely what the content is;\n * this states which *pipeline* it belongs to, so an operator can route or drop a\n * whole class (\"no tool output off this host\") with one collector rule rather\n * than an enumeration of event types.\n */\nexport const LOG_SIGNALS = [\n \"session\",\n \"prompt\",\n \"response\",\n \"reasoning\",\n \"tool\",\n \"shell\",\n \"file-operation\",\n \"mcp\",\n \"delegation\",\n \"compaction\",\n \"error\",\n] as const;\nexport type LogSignal = (typeof LOG_SIGNALS)[number];\n\n/**\n * Naming convention that marks a tool call as MCP-mediated.\n *\n * The canonical model has no \"this went through MCP\" field, because no provider\n * contract this package has verified carries one: what they carry is a *tool\n * name*, and three of the four non-synthetic contracts (Claude Code, Codex,\n * Gemini CLI) name MCP tools `mcp__<server>__<tool>`. So the convention is the\n * evidence, matched on the canonical tool name rather than on any provider's\n * payload.\n *\n * This deliberately **under-reports**: a provider whose MCP tool names do not\n * follow the convention classifies as `tool`, which is true but less specific.\n * The alternative — per-provider branching in the canonical layer, or a canonical\n * field no adapter can populate from a verified contract — would either leak\n * provider knowledge across the boundary or invent a contract. See\n * `docs/canonical-log-mapping.md`.\n */\nexport const MCP_TOOL_NAME_PATTERN = /^mcp__/i;\n\n/**\n * Most records one event may produce.\n *\n * Matches `contentFactsSchema`'s own cap, so in practice the mapping never drops\n * a fact an adapter produced; it is the backstop for a hand-built event, not a\n * routine truncation.\n */\nexport const MAX_LOG_RECORDS_PER_EVENT = 64;\n\n/** Most records one batch may produce, whatever the batch contains. */\nexport const MAX_LOG_RECORDS_PER_BATCH = 2_048;\n\n/**\n * Longest disclosed body this mapping will put on the wire.\n *\n * Separate from, and stricter than, the privacy policy's `maxStringLength` (which\n * may be configured up to 64Ki characters): a policy bound is about *disclosure*,\n * this is about the size of one OTLP record. A body cut here is reported as\n * `otelhook.content.body_truncated` rather than as the fact's own `truncated`\n * flag, so \"the privacy policy shortened this\" and \"the log record shortened\n * this\" stay distinguishable.\n */\nexport const MAX_LOG_BODY_CHARACTERS = 8_192;\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\nconst ATTR_OTELHOOK_EVENT_TYPE = \"otelhook.event.type\";\nconst ATTR_OTELHOOK_EVENT_ID = \"otelhook.event.id\";\nconst ATTR_OTELHOOK_EVENT_SEQUENCE = \"otelhook.event.sequence\";\nconst ATTR_OTELHOOK_LOG_SIGNAL = \"otelhook.log.signal\";\nconst ATTR_OTELHOOK_LOG_MAPPING_VERSION = \"otelhook.log.mapping_version\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_TOOL_PERMISSION = \"otelhook.tool.permission_decision\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_SUBAGENT_TYPE = \"otelhook.subagent.type\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\nconst ATTR_OTELHOOK_SESSION_KIND = \"otelhook.session.kind\";\nconst ATTR_OTELHOOK_PROMPT_SOURCE = \"otelhook.prompt.source\";\nconst ATTR_OTELHOOK_PROMPT_TURN_INDEX = \"otelhook.prompt.turn_index\";\nconst ATTR_OTELHOOK_GENERATION_ID = \"otelhook.generation.id\";\nconst ATTR_OTELHOOK_STOP_REASON = \"otelhook.generation.stop_reason\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE = \"otelhook.compaction.context_tokens_before\";\nconst ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER = \"otelhook.compaction.context_tokens_after\";\nconst ATTR_OTELHOOK_DROPPED_MESSAGES = \"otelhook.compaction.dropped_message_count\";\nconst ATTR_OTELHOOK_ERROR_PHASE = \"otelhook.error.phase\";\nconst ATTR_OTELHOOK_ERROR_RETRYABLE = \"otelhook.error.retryable\";\nconst ATTR_OTELHOOK_ERROR_SEVERITY = \"otelhook.error.severity\";\n\nconst ATTR_CONTENT_KIND = \"otelhook.content.kind\";\nconst ATTR_CONTENT_ROLE = \"otelhook.content.role\";\nconst ATTR_CONTENT_DISCLOSURE = \"otelhook.content.disclosure\";\nconst ATTR_CONTENT_CHARACTER_LENGTH = \"otelhook.content.character_length\";\nconst ATTR_CONTENT_BYTE_LENGTH = \"otelhook.content.byte_length\";\nconst ATTR_CONTENT_HASH = \"otelhook.content.hash\";\nconst ATTR_CONTENT_TRUNCATED = \"otelhook.content.truncated\";\nconst ATTR_CONTENT_SECRETS_REDACTED = \"otelhook.content.secrets_redacted\";\nconst ATTR_CONTENT_LABEL = \"otelhook.content.label\";\nconst ATTR_CONTENT_WITHHELD = \"otelhook.content.withheld\";\nconst ATTR_CONTENT_BODY_TRUNCATED = \"otelhook.content.body_truncated\";\n\n/**\n * Why a content fact reached the wire without its text.\n *\n * Stated rather than left as an absence, because \"this prompt was empty\", \"this\n * deployment omits content\", and \"this deployment discloses content but not to\n * the logs pipeline\" are three different operational facts that all look like a\n * missing body.\n */\nexport type ContentWithholdingReason =\n /** The privacy policy produced no text at all — the default `omit` posture. */\n | \"privacy-policy\"\n /** Content is disclosed elsewhere, but the logs pipeline is not permitted it. */\n | \"logs-content-disabled\"\n /** The fact carries verbatim text and `allowRawContent` is not set. */\n | \"raw-not-permitted\";\n\n/**\n * Whether disclosed content text may reach a log body.\n *\n * Two gates rather than one, and both must open. `includeContent` is the logs\n * pipeline's own switch, and it exists because spans carry no content in *any*\n * content mode: without it, turning on `privacy.contentMode` to get a hash and a\n * length — which is all it ever bought before — would start putting prompts on\n * the wire. `allowRawContent` is the pre-existing verbatim-content opt-in,\n * re-checked here because the sink is the last boundary before the wire and a\n * hand-built fact could otherwise carry `disclosure: \"raw\"` past a policy that\n * never permitted it.\n */\nexport type LogContentPolicy = {\n readonly includeContent: boolean;\n readonly allowRawContent: boolean;\n};\n\n/** Content disabled, which is what an unconfigured installation gets. */\nexport const NO_LOG_CONTENT: LogContentPolicy = Object.freeze({\n includeContent: false,\n allowRawContent: false,\n});\n\nconst codePointLength = (value: string): number => [...value].length;\n\nconst sliceCodePoints = (value: string, max: number): string => {\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\n/**\n * Which pipeline an event's records belong to.\n *\n * `factKind` refines the answer where one event type carries more than one kind\n * of content: a `generation.end` holds the response *and*, on providers that\n * report it, the reasoning that produced it, and collapsing those into one signal\n * would make \"drop reasoning, keep responses\" unexpressible.\n */\nexport const logSignalOf = (event: CanonicalEvent, factKind?: ContentFact[\"kind\"]): LogSignal => {\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"prompt.submitted\":\n return \"prompt\";\n case \"generation.start\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"prompt\";\n case \"generation.end\":\n return factKind === \"reasoning\" ? \"reasoning\" : \"response\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"delegation\";\n case \"compaction.performed\":\n return \"compaction\";\n case \"error.raised\":\n return \"error\";\n case \"tool.start\":\n return toolSignal(event.toolName, event.toolKind);\n case \"tool.end\":\n // A `tool.end` carries no `toolKind`: only the start edge does. Classifying\n // from the name alone is what the canonical model permits here, so a shell\n // or file operation whose name does not say so lands on `tool` — and the\n // span for the same scope, which *did* recover the kind from state, is where\n // that detail is authoritative.\n return toolSignal(event.toolName, undefined);\n }\n};\n\nconst toolSignal = (\n toolName: string,\n toolKind: Extract<CanonicalEvent, { type: \"tool.start\" }>[\"toolKind\"] | undefined,\n): LogSignal => {\n if (MCP_TOOL_NAME_PATTERN.test(toolName)) {\n return \"mcp\";\n }\n switch (toolKind) {\n case \"execute\":\n return \"shell\";\n case \"read\":\n case \"write\":\n return \"file-operation\";\n case \"delegate\":\n return \"delegation\";\n default:\n return \"tool\";\n }\n};\n\n/**\n * Log signals an adapter declaring these lifecycle events can produce.\n *\n * Derived from the adapter's existing `lifecycleEvents` declaration rather than\n * declared separately, which is the whole point: a hand-maintained second list\n * can disagree with the first, and a capability declaration that has gone stale is\n * worse than none — a consumer cannot tell \"this provider reports no tool output\"\n * from \"this declaration was never updated\".\n *\n * The tool refinements (`shell`, `file-operation`, `mcp`) are reported whenever\n * the adapter emits tool events at all, because which of them a given callback\n * produces depends on the payload, not on the adapter. So this is a statement\n * about what *may* appear, not what always will.\n */\nexport const logSignalsForLifecycleEvents = (\n lifecycleEvents: readonly CanonicalEventType[],\n): readonly LogSignal[] => {\n const signals = new Set<LogSignal>();\n const add = (...values: readonly LogSignal[]): void => {\n for (const value of values) {\n signals.add(value);\n }\n };\n for (const type of lifecycleEvents) {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n add(\"session\");\n break;\n case \"prompt.submitted\":\n add(\"prompt\");\n break;\n case \"generation.start\":\n add(\"prompt\");\n break;\n case \"generation.end\":\n add(\"response\", \"reasoning\");\n break;\n case \"tool.start\":\n case \"tool.end\":\n add(\"tool\", \"shell\", \"file-operation\", \"mcp\", \"delegation\");\n break;\n case \"subagent.start\":\n case \"subagent.end\":\n add(\"delegation\");\n break;\n case \"compaction.performed\":\n add(\"compaction\");\n break;\n case \"error.raised\":\n add(\"error\");\n break;\n }\n }\n return LOG_SIGNALS.filter((signal) => signals.has(signal));\n};\n\nconst severityFor = (event: CanonicalEvent): SeverityNumber => {\n switch (event.type) {\n case \"error.raised\":\n return event.severity === \"error\" ? SeverityNumber.ERROR : SeverityNumber.WARN;\n case \"session.end\":\n return event.reason === \"error\" || event.reason === \"timeout\"\n ? SeverityNumber.ERROR\n : event.reason === \"aborted\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n case \"generation.end\":\n case \"tool.end\":\n case \"subagent.end\":\n return event.outcome === \"error\" || event.outcome === \"timeout\"\n ? SeverityNumber.ERROR\n : event.outcome === \"denied\" || event.outcome === \"cancelled\"\n ? SeverityNumber.WARN\n : SeverityNumber.INFO;\n default:\n return SeverityNumber.INFO;\n }\n};\n\nconst SEVERITY_TEXT: Readonly<Record<number, string>> = Object.freeze({\n [SeverityNumber.INFO]: \"INFO\",\n [SeverityNumber.WARN]: \"WARN\",\n [SeverityNumber.ERROR]: \"ERROR\",\n});\n\nconst identityAttributes = (event: CanonicalEvent): LogAttributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n});\n\n/**\n * Attributes describing the event itself, independent of any content it carries.\n *\n * Every attribute here is a closed vocabulary, an identifier this library\n * derived, a count, or a boolean — the same restriction the privacy service\n * applies everywhere else, so an attribute can never become a second disclosure\n * path alongside the body.\n */\nconst eventAttributes = (event: CanonicalEvent): LogAttributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n [ATTR_OTELHOOK_SESSION_KIND]: event.sessionKind,\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n ...(event.model === undefined\n ? {}\n : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"session.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.reason,\n ...usageAttributes(event.usage),\n };\n case \"prompt.submitted\":\n return {\n [ATTR_OTELHOOK_PROMPT_SOURCE]: event.promptSource,\n ...(event.turnIndex === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROMPT_TURN_INDEX]: event.turnIndex }),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n case \"generation.end\":\n return {\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n [ATTR_OTELHOOK_GENERATION_ID]: event.generationId,\n [ATTR_GEN_AI_RESPONSE_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.stopReason === undefined ? {} : { [ATTR_OTELHOOK_STOP_REASON]: event.stopReason }),\n ...usageAttributes(event.usage),\n };\n case \"tool.start\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind,\n ...(event.generationId === undefined\n ? {}\n : { [ATTR_OTELHOOK_GENERATION_ID]: event.generationId }),\n };\n case \"tool.end\":\n return {\n [ATTR_GEN_AI_TOOL_NAME]: event.toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: event.toolCallId,\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...(event.permissionDecision === undefined\n ? {}\n : { [ATTR_OTELHOOK_TOOL_PERMISSION]: event.permissionDecision }),\n };\n case \"subagent.start\":\n return {\n [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth,\n ...(event.subagentType === undefined\n ? {}\n : { [ATTR_OTELHOOK_SUBAGENT_TYPE]: event.subagentType }),\n ...(event.model === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId }),\n };\n case \"subagent.end\":\n return {\n [ATTR_OTELHOOK_OUTCOME]: event.outcome,\n ...usageAttributes(event.usage),\n };\n case \"compaction.performed\":\n return {\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...(event.contextTokensBefore === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_BEFORE]: event.contextTokensBefore }),\n ...(event.contextTokensAfter === undefined\n ? {}\n : { [ATTR_OTELHOOK_CONTEXT_TOKENS_AFTER]: event.contextTokensAfter }),\n ...(event.droppedMessageCount === undefined\n ? {}\n : { [ATTR_OTELHOOK_DROPPED_MESSAGES]: event.droppedMessageCount }),\n ...usageAttributes(event.usage),\n };\n case \"error.raised\":\n return {\n [ATTR_ERROR_TYPE]: event.errorCode,\n [ATTR_OTELHOOK_ERROR_PHASE]: event.phase,\n [ATTR_OTELHOOK_ERROR_RETRYABLE]: event.retryable,\n [ATTR_OTELHOOK_ERROR_SEVERITY]: event.severity,\n };\n }\n};\n\nconst usageAttributes = (\n usage: { readonly inputTokens: number; readonly outputTokens: number } | undefined,\n): LogAttributes =>\n usage === undefined\n ? {}\n : {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n };\n\n/** Content facts an event carries, paired with the field they came from. */\nconst contentFactsOf = (event: CanonicalEvent): readonly ContentFact[] => {\n switch (event.type) {\n case \"prompt.submitted\":\n return event.content === undefined ? [] : [event.content];\n case \"generation.start\":\n return event.inputContent ?? [];\n case \"generation.end\":\n return event.outputContent ?? [];\n case \"tool.start\":\n return event.input === undefined ? [] : [event.input];\n case \"tool.end\":\n return event.output === undefined ? [] : [event.output];\n case \"error.raised\":\n return event.message === undefined ? [] : [event.message];\n default:\n return [];\n }\n};\n\ntype DisclosedBody =\n | { readonly text: string; readonly truncated: boolean }\n | { readonly withheld: ContentWithholdingReason };\n\nconst discloseBody = (fact: ContentFact, policy: LogContentPolicy): DisclosedBody => {\n if (fact.text === undefined) {\n return { withheld: \"privacy-policy\" };\n }\n if (!policy.includeContent) {\n return { withheld: \"logs-content-disabled\" };\n }\n if (fact.disclosure === \"raw\" && !policy.allowRawContent) {\n // Belt to the privacy service's braces: `resolvePrivacyPolicy` already\n // downgrades `raw` without the opt-in, so reaching here means a fact was built\n // outside that path. Refusing rather than trusting it keeps the opt-in a\n // property of the wire, not of one code path.\n return { withheld: \"raw-not-permitted\" };\n }\n const length = codePointLength(fact.text);\n return length <= MAX_LOG_BODY_CHARACTERS\n ? { text: fact.text, truncated: false }\n : { text: sliceCodePoints(fact.text, MAX_LOG_BODY_CHARACTERS), truncated: true };\n};\n\nconst contentAttributes = (fact: ContentFact, body: DisclosedBody): LogAttributes => ({\n [ATTR_CONTENT_KIND]: fact.kind,\n ...(fact.role === undefined ? {} : { [ATTR_CONTENT_ROLE]: fact.role }),\n [ATTR_CONTENT_DISCLOSURE]: fact.disclosure,\n [ATTR_CONTENT_CHARACTER_LENGTH]: fact.characterLength,\n [ATTR_CONTENT_BYTE_LENGTH]: fact.byteLength,\n [ATTR_CONTENT_HASH]: fact.contentHash,\n [ATTR_CONTENT_TRUNCATED]: fact.truncated,\n [ATTR_CONTENT_SECRETS_REDACTED]: fact.secretsRedacted,\n ...(fact.label === undefined ? {} : { [ATTR_CONTENT_LABEL]: fact.label }),\n ...(\"withheld\" in body\n ? { [ATTR_CONTENT_WITHHELD]: body.withheld }\n : { [ATTR_CONTENT_BODY_TRUNCATED]: body.truncated }),\n});\n\nexport type LogMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /** Whether disclosed text may reach a body. Defaults to {@link NO_LOG_CONTENT}. */\n readonly content?: LogContentPolicy;\n /**\n * The same cross-process pairing facts the span mapping is given, so a record's\n * `spanContext` names the span id that batch actually exported.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /** See `SemanticMappingOptions.correlationAvailable`. */\n readonly correlationAvailable?: boolean;\n};\n\nexport type LogMappingResult = {\n readonly records: readonly ReadableLogRecord[];\n /**\n * Content facts no record was produced for, because a bound was reached.\n *\n * Reported rather than truncated silently: a caller that logged \"N records\n * exported\" and nothing else would read a clipped batch as a complete one.\n */\n readonly droppedFacts: number;\n};\n\nconst buildRecord = (input: {\n readonly event: CanonicalEvent;\n readonly signal: LogSignal;\n readonly attributes: LogAttributes;\n readonly body?: string;\n readonly spanContext: SpanContext;\n readonly resource: Resource;\n readonly scope: InstrumentationScope;\n}): ReadableLogRecord => {\n const severityNumber = severityFor(input.event);\n const hrTime = millisToHrTime(input.event.occurredAt);\n return {\n hrTime,\n // A hook observes an event that already happened, and this mapping is pure —\n // there is no clock here to read a real observation time from. Reporting the\n // occurrence time for both is the honest answer: it says \"this is when it\n // happened\" twice rather than inventing a second, wrong timestamp.\n hrTimeObserved: hrTime,\n spanContext: input.spanContext,\n severityNumber,\n severityText: SEVERITY_TEXT[severityNumber] ?? \"INFO\",\n ...(input.body === undefined ? {} : { body: input.body }),\n eventName: `otelhook.${input.event.type}`,\n resource: input.resource,\n instrumentationScope: input.scope,\n attributes: {\n ...identityAttributes(input.event),\n [ATTR_OTELHOOK_EVENT_TYPE]: input.event.type,\n [ATTR_OTELHOOK_EVENT_ID]: input.event.eventId,\n [ATTR_OTELHOOK_EVENT_SEQUENCE]: input.event.sequence,\n [ATTR_OTELHOOK_LOG_SIGNAL]: input.signal,\n [ATTR_OTELHOOK_LOG_MAPPING_VERSION]: LOG_MAPPING_VERSION,\n ...input.attributes,\n },\n droppedAttributesCount: 0,\n };\n};\n\n/**\n * Map one invocation's canonical event batch into OTLP-ready log records.\n *\n * One record per content fact, and one record per event that carries none, so an\n * event is never silently absent from the stream just because the provider\n * reported no text for it.\n */\nexport const canonicalEventsToLogRecords = (\n events: readonly CanonicalEvent[],\n options: LogMappingOptions,\n): LogMappingResult => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const content = options.content ?? NO_LOG_CONTENT;\n const identities = canonicalEventTraceIdentities(events, {\n ...(options.correlations === undefined ? {} : { correlations: options.correlations }),\n ...(options.correlationAvailable === undefined\n ? {}\n : { correlationAvailable: options.correlationAvailable }),\n });\n\n const records: ReadableLogRecord[] = [];\n let droppedFacts = 0;\n\n for (const event of events) {\n const identity = identities.get(event.eventId);\n if (identity === undefined) {\n // Unreachable: every event in the batch is given an identity above.\n continue;\n }\n const spanContext: SpanContext = {\n traceId: identity.traceId,\n spanId: identity.spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n };\n const shared = eventAttributes(event);\n const facts = contentFactsOf(event);\n\n if (facts.length === 0) {\n if (records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event),\n attributes: shared,\n spanContext,\n resource: options.resource,\n scope,\n }),\n );\n continue;\n }\n\n let perEvent = 0;\n for (const fact of facts) {\n if (perEvent >= MAX_LOG_RECORDS_PER_EVENT || records.length >= MAX_LOG_RECORDS_PER_BATCH) {\n droppedFacts += 1;\n continue;\n }\n perEvent += 1;\n const body = discloseBody(fact, content);\n records.push(\n buildRecord({\n event,\n signal: logSignalOf(event, fact.kind),\n attributes: { ...shared, ...contentAttributes(fact, body) },\n ...(\"withheld\" in body ? {} : { body: body.text }),\n spanContext,\n resource: options.resource,\n scope,\n }),\n );\n }\n }\n\n return { records, droppedFacts };\n};\n","import { createHash } from \"node:crypto\";\n\nimport { SpanKind, SpanStatusCode, TraceFlags, type Attributes, type SpanContext, type SpanStatus } from \"@opentelemetry/api\";\nimport { millisToHrTime } from \"@opentelemetry/core\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\nimport {\n ATTR_ERROR_TYPE,\n ATTR_GEN_AI_OPERATION_NAME,\n ATTR_GEN_AI_REQUEST_MODEL,\n ATTR_GEN_AI_RESPONSE_MODEL,\n ATTR_GEN_AI_SYSTEM,\n ATTR_GEN_AI_TOOL_CALL_ID,\n ATTR_GEN_AI_TOOL_NAME,\n ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_INPUT_TOKENS,\n ATTR_GEN_AI_USAGE_OUTPUT_TOKENS,\n ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS,\n ATTR_SESSION_ID,\n} from \"@opentelemetry/semantic-conventions/incubating\";\n\nimport type { CanonicalEvent, CanonicalEventType } from \"../model/events.js\";\nimport type { CanonicalUsage } from \"../model/usage.js\";\n\nconst SCOPE_NAME = \"@osfactory/otel-hook\";\n\nexport const DEFAULT_INSTRUMENTATION_SCOPE: InstrumentationScope = Object.freeze({\n name: SCOPE_NAME,\n version: \"0.1.0\",\n});\n\nconst ATTR_OTELHOOK_INVOCATION_ID = \"otelhook.invocation.id\";\nconst ATTR_OTELHOOK_PROVIDER_ID = \"otelhook.provider.id\";\nconst ATTR_OTELHOOK_PROVIDER_VERSION = \"otelhook.provider.version\";\nconst ATTR_OTELHOOK_WORKSPACE_ID = \"otelhook.workspace.id\";\nconst ATTR_OTELHOOK_SPAN_PAIRED = \"otelhook.span.paired\";\nconst ATTR_OTELHOOK_SPAN_PAIRING = \"otelhook.span.pairing\";\nconst ATTR_OTELHOOK_SPAN_ORPHAN = \"otelhook.span.orphan\";\nconst ATTR_OTELHOOK_OUTCOME = \"otelhook.outcome\";\nconst ATTR_OTELHOOK_RESET_DETECTED = \"otelhook.usage.reset_detected\";\nconst ATTR_OTELHOOK_TOOL_KIND = \"otelhook.tool.kind\";\nconst ATTR_OTELHOOK_DELEGATION_DEPTH = \"otelhook.delegation_depth\";\nconst ATTR_OTELHOOK_COMPACTION_TRIGGER = \"otelhook.compaction.trigger\";\nconst ATTR_OTELHOOK_AGENT_NAME = \"otelhook.agent.name\";\nconst ATTR_OTELHOOK_AGENT_VERSION = \"otelhook.agent.version\";\n\n/**\n * Pure, stateless canonical-event-to-span mapping.\n *\n * Isolated in one module so every other piece of the telemetry pipeline\n * — batching, retry, spooling — can change without touching what an attribute\n * means. Two edges of the same lifecycle scope are merged into one span when\n * they appear in the same batch; when they arrive in *different* short-lived\n * hook processes they are merged through a {@link SpanCorrelation} the caller\n * resolved from persisted state. Either way the mapping itself stays a pure\n * function: state is read by the correlator, never by this module.\n *\n * ## Identity of a span\n *\n * Trace and span ids are derived, never random, so two processes that never\n * meet still agree on them:\n *\n * - `traceId = H(providerId, sessionId)` — one trace per session per provider.\n * Deriving it from the session rather than the invocation is what lets a\n * `tool.end` emitted minutes later land in the same trace as its `tool.start`;\n * including the provider is what stops two providers that happen to reuse a\n * session id from being stitched into one trace.\n * - `spanId = H(providerId, sessionId, family, scopeKey)` — stable across\n * processes and idempotent under redelivery, so a collector that sees a\n * start-only span and later the completed span treats them as one span\n * rather than two.\n */\n// NUL, so joined parts cannot collide across a different split: no identifier\n// this library accepts can contain one, which a printable separator cannot\n// promise. Never emitted — only hashed, or used as an in-memory map key.\nconst FIELD_SEPARATOR = \"\\u0000\";\n\nconst digestHex = (parts: readonly string[], length: number): string =>\n createHash(\"sha256\").update(parts.join(FIELD_SEPARATOR)).digest(\"hex\").slice(0, length);\n\n/** Lifecycle scopes that pair a `*.start` edge with a later `*.end` edge. */\nexport type SpanFamily = \"session\" | \"generation\" | \"tool\" | \"subagent\";\n\n/** Identifies one lifecycle span within a session. */\nexport type SpanScopeRef = {\n readonly family: SpanFamily;\n readonly scopeKey: string;\n};\n\n/**\n * Why a lifecycle span is, or is not, a complete pair.\n *\n * Deliberately explicit rather than a bare boolean: \"we never saw the start\",\n * \"we saw it but it aged out of state\", and \"state could not be read at all\"\n * are different operational facts, and a dashboard that cannot tell them apart\n * cannot tell a broken host from a broken exporter.\n */\nexport type SpanOrphanClassification =\n /** Both edges are known — from this batch, or from persisted state. */\n | \"none\"\n /** The start is known; its end has not arrived yet. */\n | \"missing-end\"\n /** An end arrived and no start was ever recorded for this scope. */\n | \"missing-start\"\n /** A start was recorded but aged past the retention window before the end arrived. */\n | \"expired-start\"\n /** A start exists but was recorded by a different provider; pairing it would be a guess. */\n | \"provider-mismatch\"\n /** A second, distinct end arrived for a scope that was already closed. */\n | \"already-closed\"\n /** The persisted record was written by an incompatible version and was discarded. */\n | \"state-incompatible\"\n /** The persisted record could not be understood. */\n | \"state-corrupt\"\n /** State could not be consulted at all; the mapping degraded rather than failing. */\n | \"state-unavailable\";\n\nexport type SpanPairing =\n /** Both edges were present in this batch. */\n | \"in-batch\"\n /** The other edge came from state written by an earlier process. */\n | \"cross-process\"\n | \"unpaired\";\n\n/**\n * Whether this scope should produce an OTLP record now.\n *\n * OTLP has no notion of updating a span: a span is exported once, when it ends,\n * and a second record carrying the same trace and span id is not a revision of\n * the first — it is a duplicate that backends variously drop, keep the older of,\n * or display twice. Since every lifecycle span id here is *derived* from\n * `(provider, session, family, scopeKey)`, a `*.start` edge and its later `*.end`\n * edge compute the identical id, so exporting on both is precisely that\n * duplicate.\n *\n * `defer` is therefore the answer for a start whose end has not arrived: the\n * start is durable in the state store, and the end edge exports the one complete\n * span using the times recovered from it. Nothing is lost by waiting, and what is\n * gained is that the record a collector receives has a real duration.\n */\nexport type SpanDisposition =\n /** Export a record for this scope now. */\n | \"emit\"\n /** Hold: the start is recorded, and the end edge will export the complete span. */\n | \"defer\";\n\n/**\n * One scope's correlation facts, resolved from persisted state by the caller.\n *\n * Plain data on purpose: the telemetry layer must not reach into the state\n * store itself (ADR 0006), so it declares what it needs and the lifecycle layer\n * supplies it.\n */\nexport type SpanCorrelation = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n /**\n * Whether to export a record for this scope now. Defaults to `emit` when a\n * correlation is supplied without one.\n */\n readonly disposition?: SpanDisposition;\n /**\n * Extra component mixed into the derived span id.\n *\n * Set only when this record is a genuinely *additional* observation of a scope\n * that has already been exported once — a second, distinct end for a scope that\n * was already closed. Both records are real, so neither is dropped, and the\n * discriminator keeps them from claiming the same span id.\n */\n readonly spanIdDiscriminator?: string;\n /** Start recovered from state; authoritative over the batch's own start edge. */\n readonly startMillis?: number;\n /** End recovered from state; authoritative so a redelivered end re-exports an identical span. */\n readonly endMillis?: number;\n /** Parent recorded at start time, so an end-only process hangs the span in the same place. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge could supply, recovered for an end-only span. */\n readonly attributes?: Attributes;\n};\n\n/**\n * Resolves persisted correlation for one batch.\n *\n * Must never reject: a state failure is a degraded span, never a lost export.\n */\nexport type SpanCorrelationResolver = (\n events: readonly CanonicalEvent[],\n) => Promise<readonly SpanCorrelation[]>;\n\n/**\n * Upper bound on how many start-edge attributes the correlator may carry\n * forward, so persisted state cannot grow with provider-controlled input.\n */\nexport const MAX_RECOVERED_START_ATTRIBUTES = 16;\n\nconst familyOf = (type: CanonicalEventType): SpanFamily | undefined => {\n switch (type) {\n case \"session.start\":\n case \"session.end\":\n return \"session\";\n case \"generation.start\":\n case \"generation.end\":\n return \"generation\";\n case \"tool.start\":\n case \"tool.end\":\n return \"tool\";\n case \"subagent.start\":\n case \"subagent.end\":\n return \"subagent\";\n default:\n return undefined;\n }\n};\n\n/** The lifecycle span an event is an edge of, or undefined for a point-in-time event. */\nexport const spanScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n const family = familyOf(event.type);\n if (family === undefined) {\n return undefined;\n }\n switch (event.type) {\n case \"session.start\":\n case \"session.end\":\n return { family, scopeKey: event.sessionId };\n case \"generation.start\":\n case \"generation.end\":\n return { family, scopeKey: event.generationId };\n case \"tool.start\":\n case \"tool.end\":\n return { family, scopeKey: event.toolCallId };\n case \"subagent.start\":\n case \"subagent.end\":\n return { family, scopeKey: event.subagentInvocationId };\n default:\n return undefined;\n }\n};\n\n/**\n * Where a span hangs in the trace, judged from this event alone.\n *\n * Everything in a session descends from the session span. A tool call names its\n * generation only on `tool.start`, which is exactly why the correlator persists\n * the parent: the `tool.end` process would otherwise reparent the same span to\n * the session and produce a tree whose shape depends on which edge happened to\n * be exported last.\n */\nexport const parentScopeRefOf = (event: CanonicalEvent): SpanScopeRef | undefined => {\n if (event.type === \"session.start\" || event.type === \"session.end\") {\n return undefined;\n }\n if (event.type === \"tool.start\" && event.generationId !== undefined) {\n return { family: \"generation\", scopeKey: event.generationId };\n }\n return { family: \"session\", scopeKey: event.sessionId };\n};\n\n/**\n * Span attributes that only a `*.start` edge can supply.\n *\n * The correlator persists these verbatim so an end-only span in a later process\n * still carries the tool kind, requested model, delegation depth, or agent name\n * the start process saw. An allowlist, and bounded, so persisted state can\n * never become a second route for provider payload content to escape.\n */\nexport const startOnlySpanAttributes = (event: CanonicalEvent): Attributes => {\n switch (event.type) {\n case \"session.start\":\n return {\n ...(event.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: event.agentName }),\n ...(event.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: event.agentVersion }),\n };\n case \"generation.start\":\n return {\n [ATTR_GEN_AI_REQUEST_MODEL]: event.model.modelId,\n ...(event.model.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: event.model.vendor }),\n };\n // `toolName` and `toolCallId` are on both tool edges, so they are not\n // start-only and persisting them would just pad every record.\n case \"tool.start\":\n return { [ATTR_OTELHOOK_TOOL_KIND]: event.toolKind };\n case \"subagent.start\":\n return { [ATTR_OTELHOOK_DELEGATION_DEPTH]: event.delegationDepth };\n default:\n return {};\n }\n};\n\nconst deriveTraceId = (providerId: string, sessionId: string): string =>\n digestHex([\"otelhook/trace\", providerId, sessionId], 32);\n\nconst deriveSpanId = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n digestHex([\"otelhook/span\", providerId, sessionId, ref.family, ref.scopeKey], 16);\n\nconst deriveStandaloneSpanId = (\n providerId: string,\n sessionId: string,\n eventType: string,\n eventId: string,\n): string => digestHex([\"otelhook/span\", providerId, sessionId, \"event\", eventType, eventId], 16);\n\nconst correlationKey = (providerId: string, sessionId: string, ref: SpanScopeRef): string =>\n [providerId, sessionId, ref.family, ref.scopeKey].join(FIELD_SEPARATOR);\n\nconst outcomeStatus = (outcome: string | undefined): SpanStatus => {\n if (outcome === undefined || outcome === \"ok\" || outcome === \"unknown\") {\n return { code: SpanStatusCode.UNSET };\n }\n if (outcome === \"cancelled\") {\n return { code: SpanStatusCode.UNSET };\n }\n return { code: SpanStatusCode.ERROR, message: outcome };\n};\n\nconst identityAttributes = (event: CanonicalEvent): Attributes => ({\n [ATTR_SESSION_ID]: event.sessionId,\n [ATTR_OTELHOOK_INVOCATION_ID]: event.invocationId,\n [ATTR_OTELHOOK_PROVIDER_ID]: event.provenance.providerId,\n ...(event.provenance.providerVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_PROVIDER_VERSION]: event.provenance.providerVersion }),\n [ATTR_OTELHOOK_WORKSPACE_ID]: event.workspace.workspaceId,\n});\n\nconst usageAttributes = (usage: CanonicalUsage | undefined, resetDetected: boolean): Attributes => {\n if (usage === undefined) {\n return {};\n }\n return {\n [ATTR_GEN_AI_USAGE_INPUT_TOKENS]: usage.inputTokens,\n [ATTR_GEN_AI_USAGE_OUTPUT_TOKENS]: usage.outputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS]: usage.cachedInputTokens,\n [ATTR_GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS]: usage.cacheCreationInputTokens,\n [ATTR_GEN_AI_USAGE_REASONING_OUTPUT_TOKENS]: usage.reasoningOutputTokens,\n ...(resetDetected ? { [ATTR_OTELHOOK_RESET_DETECTED]: true } : {}),\n };\n};\n\ntype SpanGroup = {\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nconst buildSpanContext = (traceId: string, spanId: string): SpanContext => ({\n traceId,\n spanId,\n traceFlags: TraceFlags.SAMPLED,\n isRemote: false,\n});\n\nexport type ReadableSpanInput = {\n readonly name: string;\n readonly kind: SpanKind;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly attributes: Attributes;\n readonly status: SpanStatus;\n readonly traceId: string;\n readonly spanId: string;\n readonly parentSpanId?: string;\n readonly resource: Resource;\n readonly instrumentationScope: InstrumentationScope;\n};\n\n/** Reconstructs a {@link ReadableSpan} from plain, serializable fields. Used by the durable spool to replay a span it persisted earlier. */\nexport const assembleReadableSpan = (input: ReadableSpanInput): ReadableSpan => toReadableSpan(input);\n\nconst toReadableSpan = (input: ReadableSpanInput): ReadableSpan => {\n const startTime = millisToHrTime(input.startMillis);\n const endTime = millisToHrTime(Math.max(input.startMillis, input.endMillis));\n const duration = millisToHrTime(Math.max(0, input.endMillis - input.startMillis));\n return {\n name: input.name,\n kind: input.kind,\n spanContext: (): SpanContext => buildSpanContext(input.traceId, input.spanId),\n ...(input.parentSpanId === undefined\n ? {}\n : { parentSpanContext: buildSpanContext(input.traceId, input.parentSpanId) }),\n startTime,\n endTime,\n status: input.status,\n attributes: input.attributes,\n links: [],\n events: [],\n duration,\n ended: true,\n resource: input.resource,\n instrumentationScope: input.instrumentationScope,\n droppedAttributesCount: 0,\n droppedEventsCount: 0,\n droppedLinksCount: 0,\n };\n};\n\ntype ResolvedPairing = {\n readonly pairing: SpanPairing;\n readonly orphan: SpanOrphanClassification;\n readonly startMillis: number;\n readonly endMillis: number;\n readonly parent: SpanScopeRef | undefined;\n readonly recovered: Attributes;\n};\n\nconst resolvePairing = (\n group: SpanGroup,\n anchor: CanonicalEvent,\n correlation: SpanCorrelation | undefined,\n): ResolvedPairing => {\n const inBatch = group.start !== undefined && group.end !== undefined;\n const batchStart = group.start?.occurredAt ?? anchor.occurredAt;\n const batchEnd = group.end?.occurredAt ?? anchor.occurredAt;\n\n if (correlation === undefined) {\n return {\n pairing: inBatch ? \"in-batch\" : \"unpaired\",\n orphan: inBatch ? \"none\" : group.start === undefined ? \"missing-start\" : \"missing-end\",\n startMillis: batchStart,\n endMillis: inBatch ? batchEnd : batchStart,\n parent: parentScopeRefOf(anchor),\n recovered: {},\n };\n }\n\n // A correlation that reports no start (an orphaned end) must not fabricate\n // one: the span collapses onto the end instant rather than claiming a\n // duration measured from an event nobody ever saw.\n const startMillis = correlation.startMillis ?? (inBatch ? batchStart : batchEnd);\n const endMillis = correlation.endMillis ?? (group.end === undefined ? startMillis : batchEnd);\n return {\n pairing: correlation.pairing,\n orphan: correlation.orphan,\n startMillis,\n endMillis,\n parent: correlation.parent ?? parentScopeRefOf(anchor),\n recovered: correlation.attributes ?? {},\n };\n};\n\nconst buildLifecycleSpan = (\n plan: GroupPlan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const group = plan.group;\n const anchor = plan.anchor;\n const correlation = plan.correlation;\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n const resolved = resolvePairing(group, anchor, correlation);\n const traceId = plan.traceId;\n const spanId = plan.spanId;\n const parentSpanId =\n resolved.parent === undefined ? undefined : deriveSpanId(providerId, sessionId, resolved.parent);\n\n let name: string = group.ref.family;\n let kind: SpanKind = SpanKind.INTERNAL;\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n // Attributes recovered from the start process sit *beneath* whatever this\n // batch observed: a live edge always wins over a remembered one.\n let attributes: Attributes = {\n ...identityAttributes(anchor),\n ...resolved.recovered,\n [ATTR_OTELHOOK_SPAN_PAIRED]: resolved.pairing !== \"unpaired\",\n [ATTR_OTELHOOK_SPAN_PAIRING]: resolved.pairing,\n [ATTR_OTELHOOK_SPAN_ORPHAN]: resolved.orphan,\n };\n\n switch (group.ref.family) {\n case \"session\": {\n const end = group.end?.type === \"session.end\" ? group.end : undefined;\n const start = group.start?.type === \"session.start\" ? group.start : undefined;\n name = \"session\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.agentName === undefined ? {} : { [ATTR_OTELHOOK_AGENT_NAME]: start.agentName }),\n ...(start?.agentVersion === undefined\n ? {}\n : { [ATTR_OTELHOOK_AGENT_VERSION]: start.agentVersion }),\n ...(end === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.reason }),\n ...usageAttributes(end?.usage, false),\n };\n if (end?.reason === \"error\" || end?.reason === \"timeout\") {\n status = { code: SpanStatusCode.ERROR, message: end.reason };\n }\n break;\n }\n case \"generation\": {\n const start = group.start?.type === \"generation.start\" ? group.start : undefined;\n const end = group.end?.type === \"generation.end\" ? group.end : undefined;\n const model = end?.model ?? start?.model;\n name = model === undefined ? \"generation\" : `generation ${model.modelId}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_OPERATION_NAME]: \"chat\",\n ...(model?.vendor === undefined ? {} : { [ATTR_GEN_AI_SYSTEM]: model.vendor }),\n ...(start?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_REQUEST_MODEL]: start.model.modelId }),\n ...(end?.model?.modelId === undefined ? {} : { [ATTR_GEN_AI_RESPONSE_MODEL]: end.model.modelId }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"tool\": {\n const start = group.start?.type === \"tool.start\" ? group.start : undefined;\n const end = group.end?.type === \"tool.end\" ? group.end : undefined;\n const toolName = start?.toolName ?? end?.toolName ?? \"unknown\";\n name = `tool ${toolName}`;\n kind = SpanKind.CLIENT;\n attributes = {\n ...attributes,\n [ATTR_GEN_AI_TOOL_NAME]: toolName,\n [ATTR_GEN_AI_TOOL_CALL_ID]: start?.toolCallId ?? end?.toolCallId ?? group.ref.scopeKey,\n ...(start?.toolKind === undefined ? {} : { [ATTR_OTELHOOK_TOOL_KIND]: start.toolKind }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n case \"subagent\": {\n const start = group.start?.type === \"subagent.start\" ? group.start : undefined;\n const end = group.end?.type === \"subagent.end\" ? group.end : undefined;\n name = \"subagent\";\n kind = SpanKind.INTERNAL;\n attributes = {\n ...attributes,\n ...(start?.delegationDepth === undefined\n ? {}\n : { [ATTR_OTELHOOK_DELEGATION_DEPTH]: start.delegationDepth }),\n ...(end?.outcome === undefined ? {} : { [ATTR_OTELHOOK_OUTCOME]: end.outcome }),\n ...usageAttributes(end?.usage, false),\n };\n status = outcomeStatus(end?.outcome);\n break;\n }\n }\n\n if (status.code === SpanStatusCode.ERROR) {\n attributes = { ...attributes, [ATTR_ERROR_TYPE]: status.message ?? \"error\" };\n }\n\n return toReadableSpan({\n name,\n kind,\n startMillis: resolved.startMillis,\n endMillis: resolved.endMillis,\n attributes,\n status,\n traceId,\n spanId,\n ...(parentSpanId === undefined ? {} : { parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nconst buildStandaloneSpan = (\n event: CanonicalEvent,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan => {\n const providerId = event.provenance.providerId;\n const traceId = deriveTraceId(providerId, event.sessionId);\n const spanId = deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId);\n const parent = parentScopeRefOf(event);\n let attributes: Attributes = { ...identityAttributes(event), [ATTR_OTELHOOK_SPAN_PAIRED]: true };\n let status: SpanStatus = { code: SpanStatusCode.UNSET };\n let name: string = event.type;\n\n switch (event.type) {\n case \"prompt.submitted\":\n name = \"prompt\";\n attributes = { ...attributes, \"otelhook.prompt.source\": event.promptSource };\n break;\n case \"compaction.performed\":\n name = \"compaction\";\n attributes = {\n ...attributes,\n [ATTR_OTELHOOK_COMPACTION_TRIGGER]: event.trigger,\n ...usageAttributes(event.usage, false),\n };\n break;\n case \"error.raised\":\n name = \"error\";\n status = { code: SpanStatusCode.ERROR, message: event.errorCode };\n attributes = {\n ...attributes,\n [ATTR_ERROR_TYPE]: event.errorCode,\n \"otelhook.error.phase\": event.phase,\n \"otelhook.error.retryable\": event.retryable,\n };\n break;\n default:\n break;\n }\n\n return toReadableSpan({\n name,\n kind: SpanKind.INTERNAL,\n startMillis: event.occurredAt,\n endMillis: event.occurredAt,\n attributes,\n status,\n traceId,\n spanId,\n ...(parent === undefined\n ? {}\n : { parentSpanId: deriveSpanId(providerId, event.sessionId, parent) }),\n resource,\n instrumentationScope: scope,\n });\n};\n\nexport type SemanticMappingOptions = {\n readonly resource: Resource;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Cross-process pairing facts, at most one entry per lifecycle scope in\n * `events`. Omitted entirely, the mapping degrades to in-batch pairing only —\n * the behavior of a host that wired no state store.\n */\n readonly correlations?: readonly SpanCorrelation[];\n /**\n * Whether a correlator was consulted at all, and whether it answered.\n *\n * This is what separates \"the state store is holding this start, so the end edge\n * will publish it\" from \"nothing recorded this start\". Both look like an empty\n * `correlations` list, and only the first is safe to drop — dropping the second\n * would discard an observation that was neither persisted nor exported, while a\n * caller that saw zero rejections went on to mark the callback handled.\n *\n * - `true` — the correlator ran; an absent or non-`defer` entry means emit.\n * - `false` — the correlator failed; every unpaired start is emitted as an\n * explicitly labelled, uniquely identified fallback.\n * - omitted — no correlator is wired, so cross-process pairing was never on\n * offer and an unpaired start is deferred (the documented no-state-root\n * degradation).\n */\n readonly correlationAvailable?: boolean;\n};\n\n/**\n * Fill in a correlation for an unpaired start that nothing recorded.\n *\n * Reached when a correlator was consulted and either failed outright or reported\n * nothing for this scope. The synthesized entry says what is true — the state was\n * not consulted successfully, so this span is unpaired and no end can complete it\n * — and carries a discriminator so the record cannot claim the span id a later end\n * will publish for the same scope.\n */\nconst effectiveCorrelation = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n): SpanCorrelation | undefined => {\n if (correlation !== undefined || group.end !== undefined || group.start === undefined) {\n return correlation;\n }\n return {\n providerId: group.start.provenance.providerId,\n sessionId: group.start.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n spanIdDiscriminator: group.start.eventId,\n };\n};\n\n/** How one batch's events distribute over the lifecycle scopes they are edges of. */\ntype BatchLayout = {\n readonly groups: ReadonlyMap<string, SpanGroup>;\n readonly standalone: readonly CanonicalEvent[];\n /** Event id of each lifecycle edge, mapped to the group key it belongs to. */\n readonly groupOf: ReadonlyMap<string, string>;\n};\n\nconst layoutBatch = (events: readonly CanonicalEvent[]): BatchLayout => {\n const groups = new Map<string, SpanGroup>();\n const standalone: CanonicalEvent[] = [];\n const groupOf = new Map<string, string>();\n\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n standalone.push(event);\n continue;\n }\n const groupKey = correlationKey(event.provenance.providerId, event.sessionId, ref);\n const group: SpanGroup = groups.get(groupKey) ?? { ref };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n groupOf.set(event.eventId, groupKey);\n }\n return { groups, standalone, groupOf };\n};\n\nconst indexCorrelations = (\n correlations: readonly SpanCorrelation[] | undefined,\n): ReadonlyMap<string, SpanCorrelation> => {\n const indexed = new Map<string, SpanCorrelation>();\n for (const correlation of correlations ?? []) {\n indexed.set(\n correlationKey(correlation.providerId, correlation.sessionId, correlation.ref),\n correlation,\n );\n }\n return indexed;\n};\n\n/**\n * What this batch does with one lifecycle scope, decided once.\n *\n * Both the span mapping and the log mapping need the *same* answer to \"which\n * span id identifies this scope, and is a record for it going out now?\" — a log\n * record whose `spanContext` names a span id the exporter never published would\n * dangle at the collector. Computing it in one place is what keeps the two\n * signals pointing at the same span rather than at two plausible derivations of\n * it.\n */\ntype GroupPlan = {\n readonly group: SpanGroup;\n /** The event the span's identity and provenance are read from. */\n readonly anchor: CanonicalEvent;\n /**\n * False when the start is deferred: the state store is holding it and the end\n * edge will publish the one complete span, so nothing is exported for it now.\n */\n readonly emits: boolean;\n readonly correlation: SpanCorrelation | undefined;\n readonly traceId: string;\n readonly spanId: string;\n};\n\nconst planGroup = (\n group: SpanGroup,\n correlation: SpanCorrelation | undefined,\n correlationAvailable: boolean | undefined,\n): GroupPlan | undefined => {\n const anchor = group.start ?? group.end;\n if (anchor === undefined) {\n // Unreachable: a group exists only because an event was filed into it.\n return undefined;\n }\n const providerId = anchor.provenance.providerId;\n const sessionId = anchor.sessionId;\n\n // A start with no end in this batch is dropped **only** when something states\n // that it is durably recorded, because its span id is a pure function of the\n // scope: emitting here and again at the end edge would put two records with one\n // id on the wire, and OTLP has no update operation.\n //\n // `defer` is that statement, and it is the correlator's to make — it just wrote\n // the record. Anything else means nothing is holding this start, so dropping it\n // would lose an observation that was neither persisted nor exported, while the\n // caller saw zero rejections and marked the callback handled. Those are exported\n // under a discriminated span id instead.\n const durablyRecorded =\n group.end === undefined &&\n (correlation?.disposition === \"defer\" ||\n // No correlator wired at all: cross-process pairing was never on offer, so\n // this is the documented no-state-root degradation rather than a failure to\n // persist something that should have been persisted.\n (correlation === undefined && correlationAvailable === undefined));\n\n // A deferred start keeps the scope's *plain* span id, because that is the id the\n // end edge will publish. Only a record actually going out now may claim a\n // discriminated one.\n const effective = durablyRecorded ? correlation : effectiveCorrelation(group, correlation);\n const discriminator = durablyRecorded ? undefined : effective?.spanIdDiscriminator;\n\n return {\n group,\n anchor,\n emits: !durablyRecorded,\n correlation: effective,\n traceId: deriveTraceId(providerId, sessionId),\n spanId:\n discriminator === undefined\n ? deriveSpanId(providerId, sessionId, group.ref)\n : digestHex(\n [\n \"otelhook/span\",\n providerId,\n sessionId,\n group.ref.family,\n group.ref.scopeKey,\n discriminator,\n ],\n 16,\n ),\n };\n};\n\n/** Trace and span a record derived from one canonical event belongs to. */\nexport type EventTraceIdentity = {\n readonly traceId: string;\n readonly spanId: string;\n};\n\n/**\n * Resolve the trace and span identity of every event in one batch.\n *\n * Exposed for signals other than traces — a log record correlates by carrying\n * the *same* derived ids the span mapping would compute, including the deferred\n * and discriminated cases. Whole batch at once because a start's identity\n * depends on whether its end is in the same batch.\n *\n * Both ids come from the event's own `(providerId, sessionId)`, never from a\n * batch-level or module-level value, which is what makes cross-session\n * contamination structurally impossible: two sessions in one batch derive two\n * different trace ids.\n */\nexport const canonicalEventTraceIdentities = (\n events: readonly CanonicalEvent[],\n options: {\n readonly correlations?: readonly SpanCorrelation[];\n readonly correlationAvailable?: boolean;\n } = {},\n): ReadonlyMap<string, EventTraceIdentity> => {\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n const plans = new Map<string, GroupPlan>();\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan !== undefined) {\n plans.set(groupKey, plan);\n }\n }\n\n const identities = new Map<string, EventTraceIdentity>();\n for (const event of events) {\n const providerId = event.provenance.providerId;\n const groupKey = layout.groupOf.get(event.eventId);\n const plan = groupKey === undefined ? undefined : plans.get(groupKey);\n if (plan === undefined) {\n identities.set(event.eventId, {\n traceId: deriveTraceId(providerId, event.sessionId),\n spanId: deriveStandaloneSpanId(providerId, event.sessionId, event.type, event.eventId),\n });\n continue;\n }\n identities.set(event.eventId, { traceId: plan.traceId, spanId: plan.spanId });\n }\n return identities;\n};\n\n/** Maps one invocation's canonical event batch into OTLP-ready spans. */\nexport const canonicalEventsToReadableSpans = (\n events: readonly CanonicalEvent[],\n options: SemanticMappingOptions,\n): readonly ReadableSpan[] => {\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const layout = layoutBatch(events);\n const correlations = indexCorrelations(options.correlations);\n\n const spans: ReadableSpan[] = [];\n for (const [groupKey, group] of layout.groups) {\n const plan = planGroup(group, correlations.get(groupKey), options.correlationAvailable);\n if (plan === undefined || !plan.emits) {\n continue;\n }\n spans.push(buildLifecycleSpan(plan, options.resource, scope));\n }\n for (const event of layout.standalone) {\n spans.push(buildStandaloneSpan(event, options.resource, scope));\n }\n return spans;\n};\n","import { ExportResultCode, type ExportResult } from \"@opentelemetry/core\";\nimport { OTLPTraceExporter } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport type { InstrumentationScope } from \"@opentelemetry/core\";\nimport type { Resource } from \"@opentelemetry/resources\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace\";\n\nimport type { ExporterPolicy } from \"../config/schema.js\";\nimport { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createHealthTracker, type DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { Clock, Logger, TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { DurableSpool, SerializedSpan, SpoolBatch } from \"./durable-spool.js\";\nimport { replayResource, resourceFromExporterPolicy } from \"./exporter-resource.js\";\nimport {\n assembleReadableSpan,\n canonicalEventsToReadableSpans,\n DEFAULT_INSTRUMENTATION_SCOPE,\n type SpanCorrelation,\n type SpanCorrelationResolver,\n} from \"./semconv.js\";\n\nconst chunk = <T,>(items: readonly T[], size: number): readonly (readonly T[])[] => {\n if (size <= 0 || items.length <= size) {\n return [items];\n }\n const chunks: T[][] = [];\n for (let index = 0; index < items.length; index += size) {\n chunks.push(items.slice(index, index + size));\n }\n return chunks;\n};\n\nconst serializeSpan = (span: ReadableSpan): SerializedSpan => ({\n name: span.name,\n kind: span.kind,\n traceId: span.spanContext().traceId,\n spanId: span.spanContext().spanId,\n ...(span.parentSpanContext === undefined\n ? {}\n : { parentSpanId: span.parentSpanContext.spanId }),\n startMillis: span.startTime[0] * 1000 + Math.round(span.startTime[1] / 1e6),\n endMillis: span.endTime[0] * 1000 + Math.round(span.endTime[1] / 1e6),\n attributes: { ...span.attributes },\n statusCode: span.status.code,\n ...(span.status.message === undefined ? {} : { statusMessage: span.status.message }),\n});\n\nconst deserializeSpan = (\n serialized: SerializedSpan,\n resource: Resource,\n scope: InstrumentationScope,\n): ReadableSpan =>\n assembleReadableSpan({\n name: serialized.name,\n kind: serialized.kind,\n startMillis: serialized.startMillis,\n endMillis: serialized.endMillis,\n attributes: serialized.attributes,\n status: { code: serialized.statusCode, ...(serialized.statusMessage === undefined ? {} : { message: serialized.statusMessage }) },\n traceId: serialized.traceId,\n spanId: serialized.spanId,\n ...(serialized.parentSpanId === undefined ? {} : { parentSpanId: serialized.parentSpanId }),\n resource,\n instrumentationScope: scope,\n });\n\nexport type OtlpTraceSinkOptions = {\n readonly exporter: ExporterPolicy;\n /** Header values, kept out of the resolved-config snapshot (ADR: config carries only header *names*). */\n readonly headers?: Readonly<Record<string, string>>;\n readonly providerId: string;\n readonly installationId: string;\n readonly clock: Clock;\n readonly logger?: Logger;\n /** Persists batches an unreachable collector rejected, for a later retry. */\n readonly spool?: DurableSpool;\n readonly instrumentationScope?: InstrumentationScope;\n /**\n * Supplies cross-process pairing for lifecycle spans, normally the\n * {@link SpanCorrelator}. Omitted, the sink pairs only within a batch.\n *\n * Injected as a plain function rather than as a correlator so the telemetry\n * layer keeps no dependency on lifecycle or on the state store (ADR 0006).\n */\n readonly correlate?: SpanCorrelationResolver;\n};\n\nexport interface OtlpTelemetrySink extends TelemetrySink {\n health(): DeliveryHealthSnapshot;\n /** Attempts to resend previously spooled batches, bounded by `maxBatches`. */\n drainSpool(maxBatches?: number): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }>;\n}\n\n/** Sink that accepts every batch and does nothing else: exporter disabled or protocol `none`. */\nconst createDisabledSink = (): OtlpTelemetrySink => {\n const health = createHealthTracker(\"telemetry-sink\");\n return {\n emit: (events): Promise<TelemetryEmitResult> => {\n health.recordSuccess(events.length);\n return Promise.resolve({ accepted: events.length, rejected: 0, errors: [] });\n },\n flush: (): Promise<void> => Promise.resolve(),\n shutdown: (): Promise<void> => Promise.resolve(),\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool: (): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> =>\n Promise.resolve({ drained: 0, remaining: 0, failed: 0 }),\n };\n};\n\n/**\n * OTLP HTTP/protobuf {@link TelemetrySink}.\n *\n * Semantic mapping lives entirely in `semconv.ts`; this module only owns\n * batching, delivery, bounded flush/shutdown, health tracking, and — when a\n * spool is configured — persisting what a down collector rejected. Every\n * failure mode (disabled config, missing endpoint, export failure, timeout,\n * spool write failure, unreadable correlation state) degrades to a reported\n * diagnostic rather than a thrown error, preserving the hook's fail-open\n * contract.\n *\n * A disabled sink never calls `correlate`: with nothing being exported there is\n * no span to pair, and writing correlation state anyway would leave a disabled\n * installation quietly accumulating files.\n */\nexport const createOtlpTraceSink = (options: OtlpTraceSinkOptions): OtlpTelemetrySink => {\n if (!options.exporter.enabled || options.exporter.protocol === \"none\") {\n return createDisabledSink();\n }\n if (options.exporter.endpoint === undefined) {\n options.logger?.warn(\"otlp sink disabled: no endpoint configured\", {});\n return createDisabledSink();\n }\n if (options.exporter.protocol !== \"http/protobuf\") {\n options.logger?.warn(\"otlp sink: protocol not supported by this build, falling back to disabled\", {\n \"exporter.protocol\": options.exporter.protocol,\n });\n return createDisabledSink();\n }\n\n const scope = options.instrumentationScope ?? DEFAULT_INSTRUMENTATION_SCOPE;\n const resource = resourceFromExporterPolicy(options.exporter);\n const health = createHealthTracker(\"telemetry-sink\");\n const exporter = new OTLPTraceExporter({\n url: options.exporter.endpoint,\n headers: { ...options.headers },\n timeoutMillis: options.exporter.timeoutMillis,\n });\n let shutdownCompleted = false;\n\n const exportSpans = (spans: readonly ReadableSpan[]): Promise<ExportResult> =>\n new Promise((resolve) => {\n exporter.export([...spans], (result: ExportResult) => resolve(result));\n });\n\n const toSpoolBatch = (spans: readonly ReadableSpan[]): SpoolBatch => ({\n providerId: options.providerId,\n installationId: options.installationId,\n resourceAttributes: { ...resource.attributes },\n instrumentationScope: { name: scope.name, ...(scope.version === undefined ? {} : { version: scope.version }) },\n spans: spans.map(serializeSpan),\n enqueuedAt: options.clock.now(),\n });\n\n const sendSerializedBatch = async (batch: SpoolBatch): Promise<boolean> => {\n const batchResource = replayResource(batch.resourceAttributes, options.exporter);\n const spans = batch.spans.map((span) => deserializeSpan(span, batchResource, batch.instrumentationScope));\n const result = await exportSpans(spans);\n return result.code === ExportResultCode.SUCCESS;\n };\n\n /**\n * Cross-process pairing is an enrichment, never a precondition: if state is\n * unreadable the batch still exports, with each lifecycle span flagged\n * unpaired rather than dropped.\n *\n * `available` is reported separately from the (possibly empty) list because the\n * mapping needs the two apart. An empty list from a healthy correlator and an\n * empty list from a correlator that threw look identical, and only the first\n * means \"the state store is holding these starts\". Conflating them would drop an\n * unpaired start that nothing recorded, and the export would then report zero\n * rejections — so a caller would commit a callback whose telemetry went nowhere.\n */\n const resolveCorrelations = async (\n events: readonly CanonicalEvent[],\n ): Promise<{\n readonly correlations: readonly SpanCorrelation[];\n readonly available: boolean | undefined;\n }> => {\n if (options.correlate === undefined) {\n return { correlations: [], available: undefined };\n }\n try {\n return { correlations: await options.correlate(events), available: true };\n } catch {\n options.logger?.warn(\"span correlation unavailable; exporting unpaired spans\", {});\n return { correlations: [], available: false };\n }\n };\n\n const emit = async (events: Parameters<TelemetrySink[\"emit\"]>[0]): Promise<TelemetryEmitResult> => {\n if (events.length === 0) {\n return { accepted: 0, rejected: 0, errors: [] };\n }\n const resolved = await resolveCorrelations(events);\n const spans = canonicalEventsToReadableSpans(events, {\n resource,\n instrumentationScope: scope,\n correlations: resolved.correlations,\n ...(resolved.available === undefined ? {} : { correlationAvailable: resolved.available }),\n });\n const errors: OtelHookErrorInfo[] = [];\n let accepted = 0;\n let rejected = 0;\n\n for (const batch of chunk(spans, options.exporter.maxBatchSize)) {\n let result: ExportResult;\n try {\n result = await exportSpans(batch);\n } catch (thrown) {\n result = { code: ExportResultCode.FAILED, error: thrown instanceof Error ? thrown : new Error(\"export threw\") };\n }\n if (result.code === ExportResultCode.SUCCESS) {\n accepted += batch.length;\n health.recordSuccess(batch.length, options.clock.now());\n continue;\n }\n\n health.recordFailure(\"telemetry-export-failure\", batch.length, options.clock.now());\n if (options.spool !== undefined) {\n const spoolResult = await options.spool.enqueue(toSpoolBatch(batch)).catch(() => ({\n spooled: false as const,\n reason: \"capacity-exceeded\" as const,\n }));\n if (spoolResult.spooled) {\n accepted += batch.length;\n continue;\n }\n }\n rejected += batch.length;\n errors.push(\n createErrorInfo({\n code: \"telemetry-export-failure\",\n phase: \"export\",\n detail: \"collector rejected or was unreachable for a span batch\",\n details: { \"export.batch_size\": batch.length },\n }),\n );\n }\n\n return { accepted, rejected, errors };\n };\n\n const drainSpool = async (\n maxBatches?: number,\n ): Promise<{ readonly drained: number; readonly remaining: number; readonly failed: number }> => {\n if (options.spool === undefined) {\n return { drained: 0, remaining: 0, failed: 0 };\n }\n const result = await options.spool.drain(sendSerializedBatch, { ...(maxBatches === undefined ? {} : { maxBatches }) });\n if (result.drained > 0) {\n health.recordSuccess(result.drained, options.clock.now());\n }\n return result;\n };\n\n const flush = async (): Promise<void> => {\n try {\n await exporter.forceFlush();\n } catch {\n // Best-effort: flush failures are reported through health, never thrown.\n }\n await drainSpool().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n if (shutdownCompleted) {\n return;\n }\n shutdownCompleted = true;\n await flush();\n try {\n await exporter.shutdown();\n } catch {\n // Idempotent, non-throwing per the TelemetrySink contract.\n }\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): DeliveryHealthSnapshot => health.snapshot(),\n drainSpool,\n };\n};\n","/**\n * Package version, kept in its own module so the CLI can report it without\n * importing the whole library barrel (and every provider adapter with it).\n */\nexport const VERSION = \"0.1.0\";\n","import { describeResolvedConfig } from \"../config/resolve.js\";\nimport { summarizeHealth } from \"../diagnostics/health.js\";\nimport { CANONICAL_SCHEMA_VERSION } from \"../model/version.js\";\nimport { createPrivacyService } from \"../privacy/service.js\";\nimport { describeProviderCatalog } from \"../providers/defaults.js\";\nimport { createSystemClock } from \"../runtime/clock.js\";\nimport { createFilesystemStateStore } from \"../state/filesystem-store.js\";\nimport { createFileDurableLogSpool } from \"../telemetry/durable-log-spool.js\";\nimport { createFileDurableSpool } from \"../telemetry/durable-spool.js\";\nimport { describeLogsDeliverability } from \"../telemetry/otlp-log-sink.js\";\nimport { createOtlpTraceSink } from \"../telemetry/otlp-sink.js\";\nimport type { CliDoctorCommand } from \"./args.js\";\nimport {\n createCliLogger,\n resolveCliConfig,\n resolveInstallationId,\n resolveStateRootDir,\n writeLine,\n type CliIo,\n} from \"./context.js\";\nimport { VERSION } from \"../version.js\";\n\nexport type DoctorCheck = {\n readonly name: string;\n readonly ok: boolean;\n /** Non-sensitive explanation; never an exception message. */\n readonly detail: string;\n};\n\nexport type DoctorReport = {\n readonly ok: boolean;\n readonly version: string;\n readonly canonicalSchemaVersion: number;\n readonly checks: readonly DoctorCheck[];\n /** Attribute-safe configuration snapshot: endpoints reduced to origin, no header values. */\n readonly config: Readonly<Record<string, unknown>>;\n readonly configNotes: readonly string[];\n readonly configWarnings: readonly { readonly code: string; readonly message: string }[];\n readonly privacyNotes: readonly string[];\n /** Local paths, for an operator diagnosing this machine. Never exported as telemetry. */\n readonly state: {\n readonly rootDir: string;\n readonly installationId: string;\n readonly writable: boolean;\n readonly spooledBatches?: number;\n /** Queued log batches awaiting retry. Absent when logs or spooling are off. */\n readonly spooledLogBatches?: number;\n };\n readonly providers: readonly {\n readonly id: string;\n readonly version: string;\n readonly maturity: string;\n readonly lifecycleEvents: readonly string[];\n }[];\n};\n\nconst DOCTOR_STATE_NAMESPACE = \"doctor\";\nconst PROBE_KEY = \"diagnostics:doctor-probe\";\n\n/**\n * Report whether this installation could actually deliver telemetry.\n *\n * Every check is local: the state directory is probed with a real write/read/\n * delete cycle in the doctor's own namespace, and the exporter is *constructed*\n * (which is where a disabled exporter, a missing endpoint, or an unsupported\n * protocol surfaces) but never asked to send anything. A doctor that quietly\n * emitted a span to prove reachability would be a doctor that leaks data from a\n * misconfigured machine.\n */\nexport const collectDoctorReport = async (\n command: CliDoctorCommand,\n io: CliIo,\n): Promise<DoctorReport> => {\n const resolved = await resolveCliConfig(command.policy, io);\n const logger = createCliLogger(io, resolved.config.diagnostics.logLevel);\n const clock = createSystemClock();\n const privacy = createPrivacyService(resolved.config.privacy);\n const stateRootDir = resolveStateRootDir(command.policy, io);\n const installationId = resolveInstallationId(command.policy, io);\n const checks: DoctorCheck[] = [];\n\n checks.push({\n name: \"configuration\",\n ok: !resolved.usedDefaults && resolved.warnings.length === 0,\n detail: resolved.usedDefaults\n ? \"configuration could not be resolved; defaults are in force\"\n : resolved.warnings.length === 0\n ? \"resolved from defaults, file, environment, and flags\"\n : `${String(resolved.warnings.length)} configuration warning(s)`,\n });\n\n const stateStore = createFilesystemStateStore({\n rootDir: stateRootDir,\n providerId: DOCTOR_STATE_NAMESPACE,\n installationId,\n clock,\n logger,\n });\n let writable = false;\n try {\n await stateStore.write(PROBE_KEY, { kind: \"attributes\", attributes: { probedAt: clock.now() } });\n const readBack = await stateStore.read(PROBE_KEY);\n writable = readBack?.value.kind === \"attributes\";\n await stateStore.delete(PROBE_KEY);\n } catch (thrown) {\n logger.warn(\"state directory probe failed\", {\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n }\n checks.push({\n name: \"state-store\",\n ok: writable,\n detail: writable\n ? \"state directory is writable and a probe record round-tripped\"\n : \"state directory could not be written; cumulative usage will restart every invocation\",\n });\n\n let spooledBatches: number | undefined;\n let spooledLogBatches: number | undefined;\n if (command.policy.spoolDisabled !== true) {\n const spool = createFileDurableSpool({\n rootDir: stateRootDir,\n providerId: DOCTOR_STATE_NAMESPACE,\n installationId,\n clock,\n logger,\n });\n try {\n spooledBatches = await spool.size();\n } catch {\n spooledBatches = undefined;\n }\n if (resolved.config.exporter.logs.enabled) {\n // Only probed when logs are on: `size()` creates the queue directory, and a\n // doctor run must not leave a tree behind for a signal this installation\n // never emits.\n const logSpool = createFileDurableLogSpool({\n rootDir: stateRootDir,\n providerId: DOCTOR_STATE_NAMESPACE,\n installationId,\n clock,\n logger,\n });\n try {\n spooledLogBatches = await logSpool.size();\n } catch {\n spooledLogBatches = undefined;\n }\n }\n }\n\n const sink = createOtlpTraceSink({\n exporter: resolved.config.exporter,\n ...(Object.keys(command.policy.headers).length === 0\n ? {}\n : { headers: command.policy.headers }),\n providerId: DOCTOR_STATE_NAMESPACE,\n installationId,\n clock,\n logger,\n });\n const exporterConfigured =\n resolved.config.exporter.enabled &&\n resolved.config.exporter.protocol === \"http/protobuf\" &&\n resolved.config.exporter.endpoint !== undefined;\n checks.push({\n name: \"exporter\",\n ok: exporterConfigured,\n detail: exporterConfigured\n ? \"OTLP HTTP/protobuf exporter is configured\"\n : !resolved.config.exporter.enabled\n ? \"exporter is disabled; events are accepted and discarded\"\n : resolved.config.exporter.endpoint === undefined\n ? \"exporter is enabled but no endpoint is configured\"\n : `protocol ${resolved.config.exporter.protocol} is not supported by this build`,\n });\n /**\n * The logs signal, reported separately and never as a failure when it is simply\n * off.\n *\n * `ok` is true for a deliberately disabled pipeline, because `doctor` exiting\n * non-zero on the default configuration would make the check useless. What it\n * distinguishes is \"off\" from \"asked for and unroutable\", which is the state an\n * operator cannot otherwise see: the sink degrades to a no-op that accepts\n * everything, so a wrong endpoint looks exactly like success.\n */\n const logs = describeLogsDeliverability(resolved.config.exporter);\n checks.push({\n name: \"logs-exporter\",\n ok: logs.status === \"configured\" || logs.reason === \"logs-disabled\",\n detail:\n logs.status === \"configured\"\n ? `OTLP HTTP/protobuf logs exporter is configured${logs.derivedEndpoint ? \" (endpoint derived from the trace endpoint)\" : \"\"}; content ${\n resolved.config.exporter.logs.includeContent ? \"permitted\" : \"disabled\"\n }`\n : logs.reason === \"logs-disabled\"\n ? \"logs are disabled; only traces are exported\"\n : logs.reason === \"no-endpoint\"\n ? \"logs are enabled but no endpoint is configured and none could be derived\"\n : `logs are enabled but unroutable: ${logs.reason}`,\n });\n\n const health = summarizeHealth([sink.health()]);\n await sink.shutdown();\n\n checks.push({\n name: \"privacy\",\n ok: resolved.config.privacy.contentMode === \"omit\" || resolved.config.privacy.allowRawContent,\n detail: `content mode is \"${privacy.policy.contentMode}\"${\n privacy.policyNotes.length === 0 ? \"\" : `; ${privacy.policyNotes.join(\"; \")}`\n }`,\n });\n\n const providers = describeProviderCatalog({\n includeExperimental: command.policy.includeExperimental ?? true,\n });\n checks.push({\n name: \"providers\",\n ok: providers.length > 0,\n detail: `${String(providers.length)} adapter(s) registered`,\n });\n\n return {\n ok: checks.every((check) => check.ok) && health.healthy,\n version: VERSION,\n canonicalSchemaVersion: CANONICAL_SCHEMA_VERSION,\n checks,\n config: describeResolvedConfig(resolved.config),\n configNotes: resolved.notes,\n configWarnings: resolved.warnings.map((warning) => ({\n code: warning.code,\n message: warning.message,\n })),\n privacyNotes: privacy.policyNotes,\n state: {\n rootDir: stateRootDir,\n installationId,\n writable,\n ...(spooledBatches === undefined ? {} : { spooledBatches }),\n ...(spooledLogBatches === undefined ? {} : { spooledLogBatches }),\n },\n providers: providers.map((entry) => ({\n id: entry.id,\n version: entry.version,\n maturity: entry.maturity,\n lifecycleEvents: entry.lifecycleEvents,\n })),\n };\n};\n\nexport const runDoctorCommand = async (command: CliDoctorCommand, io: CliIo): Promise<number> => {\n const report = await collectDoctorReport(command, io);\n\n if (command.json) {\n writeLine(io.stdout, JSON.stringify(report, null, 2));\n return report.ok ? 0 : 1;\n }\n\n writeLine(io.stdout, `otel-hook ${report.version} (canonical schema v${String(report.canonicalSchemaVersion)})`);\n writeLine(io.stdout, \"\");\n for (const check of report.checks) {\n writeLine(io.stdout, `${check.ok ? \"ok \" : \"FAIL\"} ${check.name.padEnd(14)} ${check.detail}`);\n }\n writeLine(io.stdout, \"\");\n writeLine(io.stdout, `state directory: ${report.state.rootDir}`);\n writeLine(io.stdout, `installation id: ${report.state.installationId}`);\n if (report.state.spooledBatches !== undefined) {\n writeLine(io.stdout, `spooled batches: ${String(report.state.spooledBatches)}`);\n }\n if (report.state.spooledLogBatches !== undefined) {\n writeLine(io.stdout, `spooled log batches: ${String(report.state.spooledLogBatches)}`);\n }\n for (const note of report.configNotes) {\n writeLine(io.stdout, `note: ${note}`);\n }\n for (const warning of report.configWarnings) {\n writeLine(io.stdout, `warning: ${warning.message}`);\n }\n writeLine(io.stdout, \"\");\n writeLine(io.stdout, `providers: ${report.providers.map((entry) => `${entry.id} (${entry.maturity})`).join(\", \")}`);\n return report.ok ? 0 : 1;\n};\n","import type { HookHandlerPredicate } from \"../hook-document.js\";\nimport { ANTIGRAVITY_HOOK_EVENT_NAMES, type AntigravityHookEventName } from \"./payload.js\";\n\n/** One command entry inside an Antigravity hook event's list. */\nexport type AntigravityHookCommandEntry = {\n readonly matcher?: string;\n readonly command: string;\n};\n\nexport type MergeAntigravityHookRegistrationInput = {\n /** Parsed JSON of an existing hook file, or `undefined`/anything non-object if none exists yet. */\n readonly existing?: unknown;\n /** Command line this library's hook installs for every targeted event. */\n readonly command: string;\n /** Defaults to all five documented events. */\n readonly events?: readonly AntigravityHookEventName[];\n readonly matcher?: string;\n /**\n * Recognizes entries an earlier version of this tool wrote, so a changed\n * command string rewrites its own entry instead of leaving a stale one\n * firing beside the new one. Defaults to exact-command equality.\n */\n readonly identifies?: HookHandlerPredicate;\n};\n\nexport type MergeAntigravityHookRegistrationResult = {\n /** The merged document; write this back verbatim. */\n readonly config: Record<string, unknown>;\n /** True when the merge added or changed anything relative to `existing`. */\n readonly changed: boolean;\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * Idempotently merge this library's hook registration into an Antigravity\n * workspace or global hook file, without touching unrelated keys or events.\n *\n * Pure and filesystem-free by design (see ADR 0003): callers own reading and\n * writing the file. Calling this twice with the same inputs is a no-op the\n * second time (`changed: false`), and every top-level key and every hook\n * event not named in `events` is carried through unmodified.\n */\nexport const mergeAntigravityHookRegistration = (\n input: MergeAntigravityHookRegistrationInput,\n): MergeAntigravityHookRegistrationResult => {\n const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;\n const base = isPlainObject(input.existing) ? input.existing : {};\n const existingHooks = isPlainObject(base.hooks) ? base.hooks : {};\n let changed = !isPlainObject(input.existing) || !isPlainObject(base.hooks);\n\n const nextHooks: Record<string, unknown> = { ...existingHooks };\n\n const identifies: HookHandlerPredicate =\n input.identifies ?? ((entry): boolean => entry.command === input.command);\n const desired: AntigravityHookCommandEntry = {\n command: input.command,\n ...(input.matcher === undefined ? {} : { matcher: input.matcher }),\n };\n\n for (const event of events) {\n const currentList = Array.isArray(existingHooks[event]) ? [...(existingHooks[event] as unknown[])] : [];\n const managedIndex = currentList.findIndex((entry) => isPlainObject(entry) && identifies(entry));\n\n if (managedIndex === -1) {\n changed = true;\n nextHooks[event] = [...currentList, desired];\n continue;\n }\n\n // Rewrite our own entry in place (an upgrade) and drop any duplicate of it,\n // which would otherwise double every span this event produces.\n const managed = currentList[managedIndex] as Record<string, unknown>;\n const updated = { ...managed, ...desired };\n const next = currentList.filter(\n (entry, index) => index === managedIndex || !(isPlainObject(entry) && identifies(entry)),\n );\n next[next.indexOf(managed)] = updated;\n const rewritten = Object.entries(desired).some(([key, value]) => managed[key] !== value);\n if (next.length !== currentList.length || rewritten) {\n changed = true;\n }\n nextHooks[event] = next;\n }\n\n return {\n config: { ...base, hooks: nextHooks },\n changed,\n };\n};\n\nexport type RemoveAntigravityHookRegistrationInput = {\n readonly existing?: unknown;\n /** Restrict removal to these events. Omitted means every event in the document. */\n readonly events?: readonly AntigravityHookEventName[];\n /** Recognizes hook entries this tool wrote, across versions. */\n readonly identifies: HookHandlerPredicate;\n};\n\n/**\n * Reverse {@link mergeAntigravityHookRegistration}.\n *\n * Antigravity's hook file is a *flat* list of command entries per event, not\n * the nested matcher-group shape Claude Code, Codex, and the Gemini CLI use, so\n * this cannot share their engine. An event whose list becomes empty is deleted,\n * and an emptied `hooks` object is deleted with it, so an uninstall restores a\n * document that had no hooks before setup.\n */\nexport const removeAntigravityHookRegistration = (\n input: RemoveAntigravityHookRegistrationInput,\n): MergeAntigravityHookRegistrationResult => {\n const base = isPlainObject(input.existing) ? { ...input.existing } : {};\n if (!isPlainObject(base.hooks)) {\n return { config: base, changed: false };\n }\n\n const nextHooks: Record<string, unknown> = { ...base.hooks };\n const events = input.events ?? Object.keys(nextHooks);\n let changed = false;\n\n for (const event of events) {\n const currentList = nextHooks[event];\n if (!Array.isArray(currentList)) {\n continue;\n }\n const kept = currentList.filter(\n (entry) => !(isPlainObject(entry) && input.identifies(entry)),\n );\n if (kept.length === currentList.length) {\n continue;\n }\n changed = true;\n if (kept.length === 0) {\n delete nextHooks[event];\n } else {\n nextHooks[event] = kept;\n }\n }\n\n if (!changed) {\n return { config: base, changed: false };\n }\n const config = { ...base };\n if (Object.keys(nextHooks).length === 0) {\n delete config.hooks;\n } else {\n config.hooks = nextHooks;\n }\n return { config, changed };\n};\n\n/** Managed command strings currently registered, per event. */\nexport const readAntigravityHookRegistrations = (\n existing: unknown,\n identifies: HookHandlerPredicate,\n): ReadonlyMap<string, readonly string[]> => {\n const found = new Map<string, string[]>();\n if (!isPlainObject(existing) || !isPlainObject(existing.hooks)) {\n return found;\n }\n for (const [event, list] of Object.entries(existing.hooks)) {\n if (!Array.isArray(list)) {\n continue;\n }\n const commands = list\n .filter(\n (entry): entry is Record<string, unknown> =>\n isPlainObject(entry) && typeof entry.command === \"string\" && identifies(entry),\n )\n .map((entry) => entry.command as string);\n if (commands.length > 0) {\n found.set(event, commands);\n }\n }\n return found;\n};\n","/**\n * Pure merge/removal engine for the \"nested command hooks\" configuration family.\n *\n * Claude Code and the Codex CLI document the same document shape:\n *\n * ```jsonc\n * {\n * \"hooks\": {\n * \"<EventName>\": [\n * { \"matcher\": \"Bash\", \"hooks\": [{ \"type\": \"command\", \"command\": \"…\", \"timeout\": 30 }] }\n * ]\n * }\n * }\n * ```\n *\n * The shape is generic; the *vocabulary* is not. Which events exist, which\n * matchers are meaningful, and what a timeout means stay in each provider's own\n * planner (`claude/registration.ts`, `codex/registration.ts`), so nothing here\n * encodes a provider contract and nothing here has to be re-verified when one\n * provider adds an event.\n *\n * Everything is pure: callers read the file, pass the parsed value in, and write\n * the returned document back (ADR 0003). Two properties this engine guarantees,\n * both covered by tests:\n *\n * - **Idempotence.** Re-merging identical options against the returned document\n * yields `changed: false` and a deep-equal document.\n * - **Reversibility.** `removeNestedHookRegistrations` after\n * `mergeNestedHookRegistration` restores the input document exactly, including\n * dropping structure the merge created.\n *\n * A document whose `hooks` value is not the documented shape is *reported*, not\n * coerced: silently replacing a developer's unexpected `hooks` value would\n * destroy configuration this package does not understand.\n */\n\nexport type CommandHookEntry = {\n readonly type: \"command\";\n readonly command: string;\n /**\n * Whatever unit the *provider's* vocabulary uses — seconds for Claude Code and\n * the Codex CLI, milliseconds for the Gemini CLI. Each planner converts before\n * building its entry; this engine only copies the number through.\n */\n readonly timeout?: number;\n readonly [key: string]: unknown;\n};\n\nexport type HookGroupEntry = {\n readonly matcher?: string;\n readonly hooks: readonly unknown[];\n readonly [key: string]: unknown;\n};\n\nexport type HookDocumentAction = \"added\" | \"updated\" | \"unchanged\" | \"removed\";\n\nexport type HookDocumentChange = {\n readonly event: string;\n readonly action: HookDocumentAction;\n};\n\n/** A structural surprise. Reported so a caller can refuse to write. */\nexport type HookDocumentConflict = {\n /** Dotted location inside the document, e.g. `hooks.PreToolUse`. */\n readonly location: string;\n readonly detail: string;\n};\n\nexport type NestedHookDocumentResult = {\n /** Write this back verbatim. Identical to the input when `conflicts` is non-empty. */\n readonly document: Record<string, unknown>;\n readonly changed: boolean;\n readonly changes: readonly HookDocumentChange[];\n readonly conflicts: readonly HookDocumentConflict[];\n};\n\nexport type MergeNestedHookInput = {\n /** Parsed configuration document, or anything else when no file exists yet. */\n readonly existing?: unknown;\n readonly events: readonly string[];\n /** The exact command entry to write. Compared field-by-field for idempotence. */\n readonly entry: CommandHookEntry;\n /**\n * Matcher for a *newly created* group. Omitted means \"no matcher key\", which\n * both vocabularies define as matching every occurrence.\n */\n readonly matcher?: string;\n /**\n * Recognizes a handler this tool previously wrote, so an upgrade rewrites its\n * own entry instead of appending a second one. Takes the whole handler\n * because the identity key differs by vocabulary: Gemini CLI handlers carry a\n * `name`, Claude Code and Codex handlers are identified by their command.\n */\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type HookHandlerPredicate = (handler: Readonly<Record<string, unknown>>) => boolean;\n\nexport type RemoveNestedHookInput = {\n readonly existing?: unknown;\n /** Restrict removal to these events. Omitted means every event in the document. */\n readonly events?: readonly string[];\n readonly identifies: HookHandlerPredicate;\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/**\n * `\"*\"`, `\"\"` and an absent matcher are all documented as \"match everything\",\n * so they must compare equal or an upgrade would append a duplicate beside the\n * entry it meant to replace.\n */\nconst normalizeMatcher = (value: unknown): string | undefined =>\n typeof value === \"string\" && value !== \"\" && value !== \"*\" ? value : undefined;\n\nconst isManaged = (value: unknown, identifies: HookHandlerPredicate): boolean =>\n isPlainObject(value) && identifies(value);\n\nconst cloneGroup = (value: unknown): Record<string, unknown> | undefined =>\n isPlainObject(value) && Array.isArray(value.hooks)\n ? { ...value, hooks: [...(value.hooks as unknown[])] }\n : undefined;\n\n/** Field-by-field equality against the desired entry, over the desired keys only. */\nconst matchesDesired = (existing: Record<string, unknown>, desired: CommandHookEntry): boolean => {\n for (const [key, value] of Object.entries(desired)) {\n if (existing[key] !== value) {\n return false;\n }\n }\n return true;\n};\n\nconst readEventList = (\n hooks: Record<string, unknown>,\n event: string,\n conflicts: HookDocumentConflict[],\n): unknown[] | undefined => {\n const raw = hooks[event];\n if (raw === undefined) {\n return [];\n }\n if (!Array.isArray(raw)) {\n conflicts.push({\n location: `hooks.${event}`,\n detail: `expected an array of hook groups, found ${raw === null ? \"null\" : typeof raw}`,\n });\n return undefined;\n }\n return [...(raw as unknown[])];\n};\n\nconst readHooksObject = (\n base: Record<string, unknown>,\n conflicts: HookDocumentConflict[],\n): Record<string, unknown> | undefined => {\n const raw = base.hooks;\n if (raw === undefined) {\n return {};\n }\n if (!isPlainObject(raw)) {\n conflicts.push({\n location: \"hooks\",\n detail: `expected an object keyed by hook event name, found ${\n Array.isArray(raw) ? \"an array\" : raw === null ? \"null\" : typeof raw\n }`,\n });\n return undefined;\n }\n return { ...raw };\n};\n\n/** Drop groups with no handlers left, then the event key if no groups remain. */\nconst pruneEventList = (list: unknown[]): unknown[] =>\n list.filter((group) => !(isPlainObject(group) && Array.isArray(group.hooks) && group.hooks.length === 0));\n\nconst finalize = (\n base: Record<string, unknown>,\n hooks: Record<string, unknown>,\n): Record<string, unknown> => {\n const next = { ...base };\n if (Object.keys(hooks).length === 0) {\n // Dropping an emptied `hooks` key is what makes uninstall exactly reversible:\n // a document that had no hooks before setup has none after uninstall.\n delete next.hooks;\n return next;\n }\n next.hooks = hooks;\n return next;\n};\n\n/**\n * Merge one command registration into the document, once per event.\n *\n * Identity is `(event, managed handler)`, deliberately not\n * `(event, matcher, command)`. An event ends up with **exactly one** handler of\n * ours afterwards, wherever it was before, which is what makes the three\n * interesting cases behave:\n *\n * - *Repeat.* Same options twice is a no-op, in place, byte for byte.\n * - *Upgrade.* A changed command, timeout, or matcher rewrites — or moves —\n * the entry we already own instead of appending a second one that would\n * double every span this event produces.\n * - *Repair.* Pre-existing duplicates of ours are collapsed to one.\n *\n * A handler that stays in its group is rewritten at its original index rather\n * than removed and re-appended, so an unchanged merge cannot reorder a\n * developer's file.\n */\nexport const mergeNestedHookRegistration = (\n input: MergeNestedHookInput,\n): NestedHookDocumentResult => {\n const base = isPlainObject(input.existing) ? { ...input.existing } : {};\n const conflicts: HookDocumentConflict[] = [];\n const hooks = readHooksObject(base, conflicts);\n if (hooks === undefined) {\n return { document: base, changed: false, changes: [], conflicts };\n }\n\n const changes: HookDocumentChange[] = [];\n let changed = false;\n const desiredMatcher = normalizeMatcher(input.matcher);\n\n for (const event of input.events) {\n const list = readEventList(hooks, event, conflicts);\n if (list === undefined) {\n continue;\n }\n\n const groups = list.map((group) => cloneGroup(group) ?? group);\n const usableGroups = groups.filter(\n (group): group is Record<string, unknown> =>\n isPlainObject(group) && Array.isArray(group.hooks),\n );\n\n let ownHandler: Record<string, unknown> | undefined;\n let ownGroup: Record<string, unknown> | undefined;\n let ownIndex = -1;\n let duplicates = 0;\n for (const group of usableGroups) {\n const handlers = group.hooks as unknown[];\n for (let index = 0; index < handlers.length; index += 1) {\n if (!isManaged(handlers[index], input.identifies)) {\n continue;\n }\n if (ownHandler === undefined) {\n ownHandler = handlers[index] as Record<string, unknown>;\n ownGroup = group;\n ownIndex = index;\n } else {\n duplicates += 1;\n }\n }\n }\n\n if (duplicates > 0) {\n // Everything of ours except the first, which stays where it is so\n // `ownIndex` remains valid.\n for (const group of usableGroups) {\n group.hooks = (group.hooks as unknown[]).filter(\n (handler) => handler === ownHandler || !isManaged(handler, input.identifies),\n );\n }\n }\n\n let target = usableGroups.find(\n (group) => normalizeMatcher(group.matcher) === desiredMatcher,\n );\n if (target === undefined) {\n target = {\n ...(input.matcher === undefined ? {} : { matcher: input.matcher }),\n hooks: [] as unknown[],\n };\n groups.push(target);\n }\n\n let action: HookDocumentAction;\n if (ownHandler === undefined) {\n target.hooks = [...(target.hooks as unknown[]), { ...input.entry }];\n action = \"added\";\n } else if (ownGroup === target) {\n const handlers = [...(target.hooks as unknown[])];\n const alreadyDesired = matchesDesired(ownHandler, input.entry);\n handlers[ownIndex] = alreadyDesired ? ownHandler : { ...ownHandler, ...input.entry };\n target.hooks = handlers;\n action = alreadyDesired && duplicates === 0 ? \"unchanged\" : \"updated\";\n } else {\n // The requested matcher changed: move our entry rather than leave one\n // firing under the old matcher and add another under the new one.\n if (ownGroup !== undefined) {\n ownGroup.hooks = (ownGroup.hooks as unknown[]).filter((handler) => handler !== ownHandler);\n }\n target.hooks = [...(target.hooks as unknown[]), { ...ownHandler, ...input.entry }];\n action = \"updated\";\n }\n\n changes.push({ event, action });\n changed = changed || action !== \"unchanged\";\n\n hooks[event] = pruneEventList(groups);\n }\n\n if (conflicts.length > 0) {\n return { document: base, changed: false, changes: [], conflicts };\n }\n return { document: finalize(base, hooks), changed, changes, conflicts };\n};\n\n/**\n * Remove every registration this tool owns, leaving all other handlers,\n * matchers, events, and top-level keys untouched.\n *\n * Removal scans events actually present in the document rather than a fixed\n * list, so an uninstall still cleans up after a setup that used `--event`.\n */\nexport const removeNestedHookRegistrations = (\n input: RemoveNestedHookInput,\n): NestedHookDocumentResult => {\n const base = isPlainObject(input.existing) ? { ...input.existing } : {};\n const conflicts: HookDocumentConflict[] = [];\n const hooks = readHooksObject(base, conflicts);\n if (hooks === undefined) {\n return { document: base, changed: false, changes: [], conflicts };\n }\n\n const changes: HookDocumentChange[] = [];\n let changed = false;\n const events = input.events ?? Object.keys(hooks);\n\n for (const event of events) {\n if (!(event in hooks)) {\n continue;\n }\n const list = readEventList(hooks, event, conflicts);\n if (list === undefined) {\n continue;\n }\n\n let removedHere = false;\n const groups: unknown[] = [];\n for (const group of list) {\n const cloned = cloneGroup(group);\n if (cloned === undefined) {\n groups.push(group);\n continue;\n }\n const handlers = (cloned.hooks as unknown[]).filter(\n (handler) => !isManaged(handler, input.identifies),\n );\n if (handlers.length !== (cloned.hooks as unknown[]).length) {\n removedHere = true;\n }\n cloned.hooks = handlers;\n groups.push(cloned);\n }\n\n if (!removedHere) {\n continue;\n }\n changed = true;\n changes.push({ event, action: \"removed\" });\n const pruned = pruneEventList(groups);\n if (pruned.length === 0) {\n delete hooks[event];\n } else {\n hooks[event] = pruned;\n }\n }\n\n if (conflicts.length > 0) {\n return { document: base, changed: false, changes: [], conflicts };\n }\n return { document: finalize(base, hooks), changed, changes, conflicts };\n};\n\n/**\n * Every managed command string currently registered, per event.\n *\n * Used by `diagnose` to tell \"registered with the command we would write\" from\n * \"registered with a stale command an upgrade should rewrite\".\n */\nexport const readNestedHookRegistrations = (\n existing: unknown,\n identifies: HookHandlerPredicate,\n): ReadonlyMap<string, readonly string[]> => {\n const found = new Map<string, string[]>();\n if (!isPlainObject(existing) || !isPlainObject(existing.hooks)) {\n return found;\n }\n for (const [event, list] of Object.entries(existing.hooks)) {\n if (!Array.isArray(list)) {\n continue;\n }\n const commands: string[] = [];\n for (const group of list) {\n if (!isPlainObject(group) || !Array.isArray(group.hooks)) {\n continue;\n }\n for (const handler of group.hooks) {\n if (isManaged(handler, identifies)) {\n const command = (handler as Record<string, unknown>).command;\n commands.push(typeof command === \"string\" ? command : \"\");\n }\n }\n }\n if (commands.length > 0) {\n found.set(event, commands);\n }\n }\n return found;\n};\n","import {\n mergeNestedHookRegistration,\n readNestedHookRegistrations,\n removeNestedHookRegistrations,\n type CommandHookEntry,\n type HookHandlerPredicate,\n type NestedHookDocumentResult,\n} from \"../hook-document.js\";\nimport { CLAUDE_HOOK_EVENT_NAMES, type ClaudeHookEventName } from \"./schema.js\";\n\n/**\n * Idempotent registration planner for Claude Code's `settings.json`.\n *\n * ## Evidence\n *\n * The document shape, the scopes, and the event vocabulary come from the public\n * Claude Code hooks reference (`code.claude.com/docs/en/hooks`, read 2026-07),\n * cross-checked against the setup implementation in\n * `o11y-dev/opentelemetry-hooks` v0.14.0 (`setup.sh`, `setup_claude`). Both\n * agree on:\n *\n * - `hooks.<EventName>` is an array of groups; each group is\n * `{ matcher?, hooks: [{ type: \"command\", command, timeout? }] }`.\n * - `~/.claude/settings.json` is the user-global file and\n * `.claude/settings.json` the project file (`.claude/settings.local.json` is\n * the gitignored project override).\n * - `timeout` is in seconds.\n *\n * The reference additionally documents that an omitted `matcher` matches every\n * occurrence, and that `UserPromptSubmit` and `Stop` take no matcher at all.\n * This planner therefore writes **no** `matcher` key by default: one spelling\n * that is valid for every event it registers, rather than a per-event table\n * that would have to be re-verified whenever Claude Code adds an event.\n *\n * ## Why not every documented event\n *\n * {@link CLAUDE_REGISTRABLE_HOOK_EVENTS} is the intersection of \"documented as a\n * hook event\" and \"this adapter turns it into a canonical event\". `PreCompact`\n * and `PermissionRequest` are parsed but deliberately produce no telemetry\n * (see `events.ts`), so registering them would spawn a process per occurrence\n * for nothing. Callers who want them anyway can pass `events` explicitly.\n */\n\n/** Every event name this repository's Claude Code adapter accepts on stdin. */\nexport const CLAUDE_HOOK_EVENTS_MODELLED: readonly ClaudeHookEventName[] = CLAUDE_HOOK_EVENT_NAMES;\n\n/**\n * Default registration set: the modelled events that yield telemetry.\n * Ordered as the reference documents the lifecycle, so a written settings file\n * reads in the order the events fire.\n */\nexport const CLAUDE_REGISTRABLE_HOOK_EVENTS: readonly ClaudeHookEventName[] = Object.freeze([\n \"SessionStart\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"PostToolUseFailure\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"PostCompact\",\n \"Stop\",\n \"StopFailure\",\n \"SessionEnd\",\n] as const);\n\n/** Documented but intentionally not registered, with the reason. */\nexport const CLAUDE_UNREGISTERED_HOOK_EVENTS: Readonly<Record<string, string>> = Object.freeze({\n PermissionRequest:\n \"the adapter reports permission decisions on the paired tool.end event, so a hook here would emit nothing\",\n PreCompact:\n \"the adapter reports compaction once it completes, at PostCompact, so a hook here would emit nothing\",\n});\n\nexport type ClaudeHookRegistrationOptions = {\n /** Parsed `settings.json`, or `undefined` when the file does not exist yet. */\n readonly existing?: unknown;\n readonly command: string;\n /** Defaults to {@link CLAUDE_REGISTRABLE_HOOK_EVENTS}. */\n readonly events?: readonly string[];\n /** Seconds. Omitted leaves Claude Code's own default in force. */\n readonly timeoutSeconds?: number;\n /**\n * Written only when creating a new group. Omitted (the default) means \"every\n * occurrence\", the only spelling valid for every registrable event.\n */\n readonly matcher?: string;\n /** Recognizes entries written by an earlier version of this tool. */\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type ClaudeHookRemovalOptions = {\n readonly existing?: unknown;\n readonly events?: readonly string[];\n readonly identifies: HookHandlerPredicate;\n};\n\nconst buildEntry = (options: ClaudeHookRegistrationOptions): CommandHookEntry => ({\n type: \"command\",\n command: options.command,\n ...(options.timeoutSeconds === undefined ? {} : { timeout: options.timeoutSeconds }),\n});\n\nexport const mergeClaudeHookRegistration = (\n options: ClaudeHookRegistrationOptions,\n): NestedHookDocumentResult =>\n mergeNestedHookRegistration({\n ...(options.existing === undefined ? {} : { existing: options.existing }),\n events: options.events ?? CLAUDE_REGISTRABLE_HOOK_EVENTS,\n entry: buildEntry(options),\n ...(options.matcher === undefined ? {} : { matcher: options.matcher }),\n identifies: options.identifies,\n });\n\nexport const removeClaudeHookRegistration = (\n options: ClaudeHookRemovalOptions,\n): NestedHookDocumentResult =>\n removeNestedHookRegistrations({\n ...(options.existing === undefined ? {} : { existing: options.existing }),\n ...(options.events === undefined ? {} : { events: options.events }),\n identifies: options.identifies,\n });\n\nexport const readClaudeHookRegistrations = readNestedHookRegistrations;\n","import {\n mergeNestedHookRegistration,\n readNestedHookRegistrations,\n removeNestedHookRegistrations,\n type CommandHookEntry,\n type HookHandlerPredicate,\n type NestedHookDocumentResult,\n} from \"../hook-document.js\";\nimport { CODEX_HOOK_EVENT_NAMES, type CodexHookEventName } from \"./payload.js\";\n\n/**\n * Idempotent registration planner for the Codex CLI's `hooks.json`.\n *\n * ## Evidence\n *\n * The public Codex hooks reference (`developers.openai.com/codex/hooks`,\n * redirecting to `learn.chatgpt.com/docs/hooks`, read 2026-07 — the same source\n * `payload.ts` cites for the stdin payloads) documents:\n *\n * - Discovery locations `~/.codex/hooks.json` and `<repo>/.codex/hooks.json`,\n * with equivalent inline `[[hooks.EventName]]` tables in `config.toml`.\n * - The `hooks.<EventName>` → array-of-groups → `{ matcher?, hooks: [...] }`\n * shape, matching Claude Code's.\n * - `matcher` optional, where omitting it \"matches every occurrence\".\n * - `timeout` in seconds.\n * - Hooks **enabled by default**; `[features] hooks = false` in `config.toml`\n * turns them off.\n *\n * This planner writes only `hooks.json`. It never edits `config.toml`: hooks\n * being on by default means no edit is required, and rewriting a hand-authored\n * TOML file to flip a flag that is already set is a mutation with more downside\n * (comment loss, formatting loss, merge-warning on a layer that also declares\n * inline hooks) than value. {@link readCodexHooksFeatureFlag} lets `diagnose`\n * *report* an explicit opt-out instead.\n *\n * ## Why not every documented event\n *\n * The reference lists `SessionEnd`, but this repository's adapter deliberately\n * does not model it (see `payload.ts`: Codex has no dependable `SessionEnd`, and\n * `adapter.ts` substitutes `Stop` plus a state-store TTL). Registering an event\n * whose payload the adapter would reject is worse than not registering it.\n * `PermissionRequest` is modelled but produces no telemetry of its own, so it is\n * not in the default set either.\n */\n\n/** Every `hook_event_name` this repository's Codex adapter accepts. */\nexport const CODEX_HOOK_EVENTS_MODELLED: readonly CodexHookEventName[] = CODEX_HOOK_EVENT_NAMES;\n\n/** Default registration set: modelled events that yield telemetry, in lifecycle order. */\nexport const CODEX_REGISTRABLE_HOOK_EVENTS: readonly CodexHookEventName[] = Object.freeze([\n \"SessionStart\",\n \"UserPromptSubmit\",\n \"PreToolUse\",\n \"PostToolUse\",\n \"SubagentStart\",\n \"SubagentStop\",\n \"PreCompact\",\n \"PostCompact\",\n \"Stop\",\n] as const);\n\n/** Documented or modelled but intentionally not registered, with the reason. */\nexport const CODEX_UNREGISTERED_HOOK_EVENTS: Readonly<Record<string, string>> = Object.freeze({\n PermissionRequest:\n \"the adapter reports the decision on the paired tool.end event, so a hook here would emit nothing\",\n SessionEnd:\n \"documented by Codex but not modelled by this adapter; the payload would be rejected (see payload.ts)\",\n});\n\nexport type CodexHookRegistrationOptions = {\n /** Parsed `hooks.json`, or `undefined` when the file does not exist yet. */\n readonly existing?: unknown;\n readonly command: string;\n /** Defaults to {@link CODEX_REGISTRABLE_HOOK_EVENTS}. */\n readonly events?: readonly string[];\n /** Seconds. Omitted leaves Codex's own per-event default in force. */\n readonly timeoutSeconds?: number;\n readonly matcher?: string;\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type CodexHookRemovalOptions = {\n readonly existing?: unknown;\n readonly events?: readonly string[];\n readonly identifies: HookHandlerPredicate;\n};\n\nconst buildEntry = (options: CodexHookRegistrationOptions): CommandHookEntry => ({\n type: \"command\",\n command: options.command,\n ...(options.timeoutSeconds === undefined ? {} : { timeout: options.timeoutSeconds }),\n});\n\nexport const mergeCodexHookRegistration = (\n options: CodexHookRegistrationOptions,\n): NestedHookDocumentResult =>\n mergeNestedHookRegistration({\n ...(options.existing === undefined ? {} : { existing: options.existing }),\n events: options.events ?? CODEX_REGISTRABLE_HOOK_EVENTS,\n entry: buildEntry(options),\n ...(options.matcher === undefined ? {} : { matcher: options.matcher }),\n identifies: options.identifies,\n });\n\nexport const removeCodexHookRegistration = (\n options: CodexHookRemovalOptions,\n): NestedHookDocumentResult =>\n removeNestedHookRegistrations({\n ...(options.existing === undefined ? {} : { existing: options.existing }),\n ...(options.events === undefined ? {} : { events: options.events }),\n identifies: options.identifies,\n });\n\nexport const readCodexHookRegistrations = readNestedHookRegistrations;\n\nexport type CodexHooksFeatureFlag = \"enabled\" | \"disabled\" | \"unset\";\n\n/**\n * Read the `[features] hooks` opt-out from a `config.toml`'s text.\n *\n * Line-scoped on purpose: this is a read-only diagnostic for one documented\n * boolean, not a TOML parser, and it must never be used to decide a write. It\n * looks only at bare `key = value` lines inside a top-level `[features]` table,\n * so a `hooks` key in any other table cannot be mistaken for this one. Anything\n * it cannot interpret is reported as `\"unset\"` — Codex's own default.\n */\nexport const readCodexHooksFeatureFlag = (configToml: string): CodexHooksFeatureFlag => {\n let inFeatures = false;\n for (const line of configToml.split(/\\r?\\n/)) {\n const trimmed = line.trim();\n if (trimmed.startsWith(\"#\") || trimmed.length === 0) {\n continue;\n }\n if (trimmed.startsWith(\"[\")) {\n inFeatures = trimmed === \"[features]\";\n continue;\n }\n if (!inFeatures) {\n continue;\n }\n const match = /^hooks\\s*=\\s*(true|false)\\s*(?:#.*)?$/.exec(trimmed);\n if (match !== null) {\n return match[1] === \"false\" ? \"disabled\" : \"enabled\";\n }\n }\n return \"unset\";\n};\n","import type { HookHandlerPredicate } from \"../hook-document.js\";\nimport { CURSOR_HOOK_EVENT_NAMES, type CursorHookEventName } from \"./payload.js\";\n\n/**\n * Idempotent registration planner for Cursor's `hooks.json`.\n *\n * ## Evidence\n *\n * The document half was already verified before the payload half was: Cursor's\n * hooks reference (`cursor.com/docs/agent/hooks` and `cursor.com/docs/hooks.md`,\n * read 2026-07-29) documents the discovery locations `~/.cursor/hooks.json`\n * (user) and `<project-root>/.cursor/hooks.json` (project), and the document\n * shape\n *\n * ```jsonc\n * {\n * \"version\": 1,\n * \"hooks\": {\n * \"preToolUse\": [\n * { \"command\": \"…\", \"type\": \"command\", \"timeout\": 30, \"matcher\": \"…\" }\n * ]\n * }\n * }\n * ```\n *\n * with `timeout` in **seconds**, `type` defaulting to `\"command\"`, `matcher`\n * optional, and `failClosed` defaulting to false. `o11y-dev/opentelemetry-hooks`\n * v0.14.0 writes exactly that shape. Enterprise-managed locations\n * (`/etc/cursor/hooks.json` and the macOS/Windows equivalents) are documented\n * too but are deliberately not offered as a scope: they are MDM-owned, live\n * outside a home directory, and this tool has no business writing there.\n *\n * The list is *flat* — one array of command entries per event, no matcher-group\n * nesting — so this cannot share the engine Claude Code, Codex, and the Gemini\n * CLI use, for the same reason Antigravity cannot.\n *\n * ## Why not every documented event\n *\n * {@link CURSOR_REGISTRABLE_HOOK_EVENTS} is the intersection of \"Cursor\n * documents it\", \"this adapter turns it into telemetry\", and \"registering it\n * does not double-count something already registered\".\n * {@link CURSOR_UNREGISTERED_HOOK_EVENTS} records every exclusion with its\n * reason; the shell and MCP exclusions are the interesting ones, and they come\n * from a capture rather than from the reference — see `payload.ts`.\n */\n\n/** Every `hook_event_name` this repository's Cursor adapter accepts. */\nexport const CURSOR_HOOK_EVENTS_MODELLED: readonly CursorHookEventName[] = CURSOR_HOOK_EVENT_NAMES;\n\n/** Default registration set: modelled events that yield telemetry, in lifecycle order. */\nexport const CURSOR_REGISTRABLE_HOOK_EVENTS: readonly CursorHookEventName[] = Object.freeze([\n \"sessionStart\",\n \"beforeSubmitPrompt\",\n \"preToolUse\",\n \"postToolUse\",\n \"postToolUseFailure\",\n \"afterFileEdit\",\n \"preCompact\",\n \"stop\",\n \"sessionEnd\",\n] as const);\n\n/** Documented or modelled but intentionally not registered, with the reason. */\nexport const CURSOR_UNREGISTERED_HOOK_EVENTS: Readonly<Record<string, string>> = Object.freeze({\n afterAgentResponse:\n \"the generation's outcome and the same token snapshot arrive on stop; registering both would double-count usage\",\n afterAgentThought:\n \"a reasoning notification with no canonical event type, and its text is never exported\",\n beforeShellExecution:\n \"one shell call also fires preToolUse/postToolUse — the capture's fired.log shows all four for a single command — and only the generic pair carries tool_use_id, so registering this one duplicates the tool call\",\n afterShellExecution:\n \"the same shell call also fires postToolUse, which duplicates this tool end and — unlike this callback — carries both a tool_use_id and a success/failure signal\",\n beforeMCPExecution:\n \"an MCP call also fires preToolUse/postToolUse, which additionally carry tool_use_id; registering this one duplicates the tool call\",\n afterMCPExecution:\n \"the same MCP call also fires postToolUse, which duplicates this tool end and, unlike this callback, reports a success/failure signal\",\n beforeReadFile:\n \"no completion callback exists for it, so a tool.start emitted here would never close\",\n subagentStart:\n \"subagentStop carries no subagent id to pair with, so no closable delegation lifecycle can be produced\",\n subagentStop:\n \"it carries no subagent id, so it cannot be paired with the subagentStart it ends\",\n beforeTabFileRead: \"a Tab (inline-completion) hook, not an agent-session hook; not modelled by this adapter\",\n afterTabFileEdit: \"a Tab (inline-completion) hook, not an agent-session hook; not modelled by this adapter\",\n workspaceOpen:\n \"an app-lifecycle hook that carries no conversation_id, so it has no session to attribute telemetry to\",\n});\n\n/** The schema version Cursor documents for `hooks.json`. */\nexport const CURSOR_HOOKS_DOCUMENT_VERSION = 1;\n\n/** One command entry inside a Cursor hook event's list. */\nexport type CursorHookCommandEntry = {\n readonly type: \"command\";\n readonly command: string;\n /** Seconds, per the reference. */\n readonly timeout?: number;\n readonly matcher?: string;\n};\n\nexport type MergeCursorHookRegistrationInput = {\n /** Parsed `hooks.json`, or `undefined`/anything non-object when none exists yet. */\n readonly existing?: unknown;\n readonly command: string;\n /** Defaults to {@link CURSOR_REGISTRABLE_HOOK_EVENTS}. */\n readonly events?: readonly string[];\n /** Seconds. Omitted leaves Cursor's own default in force. */\n readonly timeoutSeconds?: number;\n readonly matcher?: string;\n /** Recognizes entries an earlier version of this tool wrote. */\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type CursorHookRemovalInput = {\n readonly existing?: unknown;\n /** Restrict removal to these events. Omitted means every event in the document. */\n readonly events?: readonly string[];\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type CursorHookDocumentResult = {\n /** Write this back verbatim. */\n readonly config: Record<string, unknown>;\n readonly changed: boolean;\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nconst buildEntry = (input: MergeCursorHookRegistrationInput): CursorHookCommandEntry => ({\n type: \"command\",\n command: input.command,\n ...(input.timeoutSeconds === undefined ? {} : { timeout: input.timeoutSeconds }),\n ...(input.matcher === undefined ? {} : { matcher: input.matcher }),\n});\n\n/**\n * Merge this tool's registration into a Cursor hook document.\n *\n * Pure and filesystem-free (ADR 0003): the caller reads the file, passes the\n * parsed value in, and writes the returned document back. Two guarantees, both\n * asserted in `tests/install/cursor-registration.test.ts`:\n *\n * - **Idempotence.** Re-merging identical options against the returned document\n * is a no-op (`changed: false`) with a deep-equal document.\n * - **One entry per event.** Our entry is rewritten in place on an upgrade and\n * any duplicate of it is collapsed, so a changed command cannot leave a stale\n * handler firing beside the new one and double every span.\n *\n * `version` is added only when the document does not already declare one. A\n * developer's existing `version` is never rewritten — Cursor could raise it, and\n * downgrading a document to match this constant would be a guess about a schema\n * this tool does not own.\n */\nexport const mergeCursorHookRegistration = (\n input: MergeCursorHookRegistrationInput,\n): CursorHookDocumentResult => {\n const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;\n const base = isPlainObject(input.existing) ? { ...input.existing } : {};\n const existingHooks = isPlainObject(base.hooks) ? base.hooks : {};\n const nextHooks: Record<string, unknown> = { ...existingHooks };\n const desired = buildEntry(input);\n\n let changed = false;\n if (base.version === undefined) {\n base.version = CURSOR_HOOKS_DOCUMENT_VERSION;\n changed = true;\n }\n\n for (const event of events) {\n const currentList = Array.isArray(existingHooks[event])\n ? [...(existingHooks[event] as unknown[])]\n : [];\n const managed = currentList.filter(\n (entry): entry is Record<string, unknown> => isPlainObject(entry) && input.identifies(entry),\n );\n const [ours] = managed;\n\n if (ours === undefined) {\n nextHooks[event] = [...currentList, desired];\n changed = true;\n continue;\n }\n\n // Rewrite our own entry where it already sits, and drop every duplicate of\n // it. Rewriting in place rather than re-appending keeps an unchanged merge\n // from reordering a developer's file.\n const rewritten = { ...ours, ...desired };\n const next = currentList\n .filter((entry) => entry === ours || !(isPlainObject(entry) && input.identifies(entry)))\n .map((entry) => (entry === ours ? rewritten : entry));\n const entryChanged = Object.entries(desired).some(([key, value]) => ours[key] !== value);\n if (entryChanged || managed.length > 1) {\n changed = true;\n }\n nextHooks[event] = next;\n }\n\n return { config: { ...base, hooks: nextHooks }, changed };\n};\n\n/**\n * Reverse {@link mergeCursorHookRegistration}.\n *\n * An event whose list becomes empty is deleted, and an emptied `hooks` object is\n * deleted with it, so uninstalling restores a document that had no hooks before\n * setup. A lone `version` left behind by that pruning is dropped too: a\n * `hooks.json` declaring a schema version for no hooks is a document Cursor\n * reads nothing from, and leaving it would mean `setup` followed by `uninstall`\n * created a file where there was none.\n */\nexport const removeCursorHookRegistration = (\n input: CursorHookRemovalInput,\n): CursorHookDocumentResult => {\n const base = isPlainObject(input.existing) ? { ...input.existing } : {};\n if (!isPlainObject(base.hooks)) {\n return { config: base, changed: false };\n }\n\n const nextHooks: Record<string, unknown> = { ...base.hooks };\n const events = input.events ?? Object.keys(nextHooks);\n let changed = false;\n\n for (const event of events) {\n const currentList = nextHooks[event];\n if (!Array.isArray(currentList)) {\n continue;\n }\n const kept = currentList.filter(\n (entry) => !(isPlainObject(entry) && input.identifies(entry)),\n );\n if (kept.length === currentList.length) {\n continue;\n }\n changed = true;\n if (kept.length === 0) {\n delete nextHooks[event];\n } else {\n nextHooks[event] = kept;\n }\n }\n\n if (!changed) {\n return { config: base, changed: false };\n }\n\n const config = { ...base };\n if (Object.keys(nextHooks).length === 0) {\n delete config.hooks;\n if (Object.keys(config).length === 1 && config.version === CURSOR_HOOKS_DOCUMENT_VERSION) {\n delete config.version;\n }\n } else {\n config.hooks = nextHooks;\n }\n return { config, changed };\n};\n\n/** Managed command strings currently registered, per event. */\nexport const readCursorHookRegistrations = (\n existing: unknown,\n identifies: HookHandlerPredicate,\n): ReadonlyMap<string, readonly string[]> => {\n const found = new Map<string, string[]>();\n if (!isPlainObject(existing) || !isPlainObject(existing.hooks)) {\n return found;\n }\n for (const [event, list] of Object.entries(existing.hooks)) {\n if (!Array.isArray(list)) {\n continue;\n }\n const commands = list\n .filter(\n (entry): entry is Record<string, unknown> =>\n isPlainObject(entry) && typeof entry.command === \"string\" && identifies(entry),\n )\n .map((entry) => entry.command as string);\n if (commands.length > 0) {\n found.set(event, commands);\n }\n }\n return found;\n};\n","import {\n mergeNestedHookRegistration,\n readNestedHookRegistrations,\n removeNestedHookRegistrations,\n type HookDocumentChange,\n type HookDocumentConflict,\n type HookHandlerPredicate,\n type NestedHookDocumentResult,\n} from \"../hook-document.js\";\nimport { GEMINI_HOOK_EVENT_NAMES, type GeminiHookEventName } from \"./schema.js\";\n\n/**\n * Idempotent helper for registering this adapter's command hook into a Gemini\n * CLI `settings.json`. It never touches the filesystem itself — callers read\n * the existing settings, pass the parsed value in, and write the returned\n * value back — so the merge logic stays pure and testable, and this package\n * never needs a filesystem handle (see ADR 0003).\n *\n * Gemini CLI's settings share the nested `hooks -> event -> [{matcher, hooks}]`\n * shape that Claude Code and the Codex CLI document, so the merge itself is\n * delegated to `providers/hook-document.ts`; what stays here is the part that is\n * specific to Gemini. Four things are, all read from\n * `google-gemini/gemini-cli@3499c84` (`docs/hooks/reference.md`,\n * `packages/core/src/hooks/types.ts`, `packages/core/src/hooks/hookPlanner.ts`):\n *\n * - **`timeout` is milliseconds**, default `60000` — not seconds, as Claude Code\n * and the Codex CLI both use. `hookRunner` passes the value straight to\n * `setTimeout`. Callers speak seconds ({@link RegisterGeminiHookOptions}), and\n * the conversion happens here, because writing `timeout: 30` from a\n * `--timeout-seconds 30` would kill the hook after 30ms.\n * - **`\"*\"` is a real matcher value.** `HookPlanner.matchesContext` special-cases\n * `\"\"` and `\"*\"` as match-everything before treating a matcher as a regex, so\n * the wildcard is safe here even though `new RegExp(\"*\")` would throw.\n * - **`name` is the identity key.** The CLI's own `getHookKey` is\n * `` `${name}:${command}` ``, which would treat a changed command as a\n * *different* hook and leave the stale entry firing beside the new one. This\n * planner keys on `name` alone so an upgrade rewrites in place.\n * - **`hooks` holds non-event keys.** `HOOKS_CONFIG_FIELDS` is\n * `['enabled', 'disabled', 'notifications']`, so `hooks.enabled: true` sits\n * beside the event arrays. Both merge and removal are therefore driven by an\n * explicit event list and never iterate the object's keys.\n *\n * The scopes are `~/.gemini/settings.json` (user-global) and\n * `.gemini/settings.json` (project), as written by `o11y-dev/opentelemetry-hooks`\n * v0.14.0 (`setup.sh`, `setup_gemini`).\n */\n\nexport type GeminiHookCommandEntry = {\n readonly name: string;\n readonly type: \"command\";\n readonly command: string;\n /** Milliseconds, per the Gemini CLI's own `CommandHookConfig`. */\n readonly timeout?: number;\n};\n\nexport type GeminiHookMatcherEntry = {\n readonly matcher?: string;\n /** True runs the group's hooks one after another; preserved, never written. */\n readonly sequential?: boolean;\n readonly hooks: readonly GeminiHookCommandEntry[];\n};\n\n/**\n * Default registration set: the documented events this adapter turns into\n * telemetry, in the order the CLI fires them. A hook registered on an event that\n * emits nothing is a process spawn per occurrence for no data.\n */\nexport const GEMINI_REGISTRABLE_HOOK_EVENTS: readonly GeminiHookEventName[] = Object.freeze([\n \"SessionStart\",\n \"BeforeAgent\",\n \"BeforeModel\",\n \"AfterModel\",\n \"BeforeTool\",\n \"AfterTool\",\n \"PreCompress\",\n \"SessionEnd\",\n]);\n\n/** Documented and modelled, but intentionally not registered, with the reason. */\nexport const GEMINI_UNREGISTERED_HOOK_EVENTS: Readonly<Record<string, string>> = Object.freeze({\n AfterAgent:\n \"marks turn completion, which the canonical model has no event for distinct from generation.end\",\n BeforeToolSelection: \"carries tool-choice configuration only, so the adapter emits nothing\",\n Notification: \"observability-only in this protocol; no canonical event type corresponds\",\n});\n\n/**\n * Keys the CLI documents *inside* `hooks` that are not event names\n * (`HOOKS_CONFIG_FIELDS`). Anything registering or removing hooks has to know\n * these exist, or it will read `hooks.enabled: true` as a malformed event list.\n */\nexport const GEMINI_HOOKS_CONFIG_FIELDS = Object.freeze([\n \"enabled\",\n \"disabled\",\n \"notifications\",\n] as const);\n\nexport type GeminiHooksObject = Partial<\n Record<GeminiHookEventName, readonly GeminiHookMatcherEntry[]>\n> & {\n readonly enabled?: boolean;\n readonly disabled?: readonly string[];\n readonly notifications?: unknown;\n};\n\nexport type GeminiHooksSettings = {\n readonly hooks?: GeminiHooksObject;\n readonly [key: string]: unknown;\n};\n\nexport type RegisterGeminiHookOptions = {\n /** Hook id as it will appear in settings.json; also the idempotency key. */\n readonly name: string;\n readonly command: string;\n /** Defaults to `\"*\"` (every tool / every context). */\n readonly matcher?: string;\n /** Defaults to {@link GEMINI_REGISTRABLE_HOOK_EVENTS}. */\n readonly events?: readonly GeminiHookEventName[];\n /**\n * Seconds, matching every other planner's vocabulary. Converted to the\n * milliseconds the Gemini CLI expects before it is written.\n */\n readonly timeoutSeconds?: number;\n /**\n * Recognizes registrations this tool owns. Defaults to `name` equality — the\n * documented idempotency key — but an installer that has to find entries an\n * older version wrote under a different name can widen it.\n */\n readonly identifies?: HookHandlerPredicate;\n};\n\nexport type MergeGeminiHookResult = {\n readonly settings: GeminiHooksSettings;\n /** False when every requested event already had this exact registration. */\n readonly changed: boolean;\n readonly registeredEvents: readonly GeminiHookEventName[];\n /** Per-event outcome, for a caller that reports what it is about to do. */\n readonly changes: readonly HookDocumentChange[];\n /** Non-empty when the document's `hooks` value is not the documented shape. */\n readonly conflicts: readonly HookDocumentConflict[];\n};\n\nconst MILLIS_PER_SECOND = 1_000;\n\nconst buildCommandEntry = (options: RegisterGeminiHookOptions): GeminiHookCommandEntry => ({\n name: options.name,\n type: \"command\",\n command: options.command,\n ...(options.timeoutSeconds === undefined\n ? {}\n : { timeout: options.timeoutSeconds * MILLIS_PER_SECOND }),\n});\n\n/**\n * Identity is the hook's `name`, exactly as {@link RegisterGeminiHookOptions}\n * documents it: re-running setup after the command string changed (a new\n * install path, a new endpoint flag) must *rewrite* the existing entry, not\n * leave a stale one firing beside it.\n */\nconst identifiesByName =\n (name: string): HookHandlerPredicate =>\n (handler): boolean =>\n handler.name === name;\n\n/**\n * Merge this adapter's hook registration into an existing (parsed)\n * `settings.json` value, once per requested event.\n *\n * Re-running with identical options is a no-op (`changed: false`). Existing\n * hooks from other tools, matchers a developer narrowed by hand, and settings\n * fields outside `hooks` are all preserved untouched.\n */\nexport const mergeGeminiHookRegistration = (\n existing: unknown,\n options: RegisterGeminiHookOptions,\n): MergeGeminiHookResult => {\n const events = options.events ?? GEMINI_REGISTRABLE_HOOK_EVENTS;\n const merged = mergeNestedHookRegistration({\n existing,\n events,\n entry: buildCommandEntry(options),\n matcher: options.matcher ?? \"*\",\n identifies: options.identifies ?? identifiesByName(options.name),\n });\n\n return {\n settings: merged.document,\n changed: merged.changed,\n registeredEvents: merged.conflicts.length > 0 ? [] : events,\n changes: merged.changes,\n conflicts: merged.conflicts,\n };\n};\n\nexport type RemoveGeminiHookOptions = {\n /** Restrict removal to these events. Omitted means the whole event vocabulary. */\n readonly events?: readonly GeminiHookEventName[];\n /** Recognizes handlers this tool wrote, across versions. */\n readonly identifies: HookHandlerPredicate;\n};\n\n/**\n * Reverse {@link mergeGeminiHookRegistration}.\n *\n * An emptied matcher group, an emptied event, and an emptied `hooks` key are all\n * dropped, which is what makes setup-then-uninstall restore the original\n * document exactly.\n *\n * Removal names the full event vocabulary rather than letting the engine scan\n * the document's own keys, because in this vocabulary not every key under\n * `hooks` is an event: `HOOKS_CONFIG_FIELDS` puts `enabled`, `disabled`, and\n * `notifications` there too. Scanning would read `hooks.enabled: true` as a\n * malformed event list, report a conflict, and abandon the whole uninstall —\n * leaving every registration in place on exactly the documents that had hooks\n * configured most deliberately. `GEMINI_HOOK_EVENT_NAMES` is complete, so naming\n * it loses nothing: the CLI cannot fire an event outside it.\n */\nexport const removeGeminiHookRegistration = (\n existing: unknown,\n options: RemoveGeminiHookOptions,\n): NestedHookDocumentResult =>\n removeNestedHookRegistrations({\n existing,\n events: options.events ?? GEMINI_HOOK_EVENT_NAMES,\n identifies: options.identifies,\n });\n\nexport const readGeminiHookRegistrations = readNestedHookRegistrations;\n","import { ANTIGRAVITY_PROVIDER_ID } from \"../providers/antigravity/adapter.js\";\nimport { ANTIGRAVITY_HOOK_EVENT_NAMES } from \"../providers/antigravity/payload.js\";\nimport {\n mergeAntigravityHookRegistration,\n readAntigravityHookRegistrations,\n removeAntigravityHookRegistration,\n} from \"../providers/antigravity/registration.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"../providers/claude/detect.js\";\nimport {\n CLAUDE_REGISTRABLE_HOOK_EVENTS,\n mergeClaudeHookRegistration,\n readClaudeHookRegistrations,\n removeClaudeHookRegistration,\n} from \"../providers/claude/registration.js\";\nimport {\n CODEX_REGISTRABLE_HOOK_EVENTS,\n mergeCodexHookRegistration,\n readCodexHookRegistrations,\n removeCodexHookRegistration,\n} from \"../providers/codex/registration.js\";\nimport { CODEX_PROVIDER_ID } from \"../providers/codex/version.js\";\nimport { CURSOR_PROVIDER_ID } from \"../providers/cursor/payload.js\";\nimport {\n CURSOR_REGISTRABLE_HOOK_EVENTS,\n mergeCursorHookRegistration,\n readCursorHookRegistrations,\n removeCursorHookRegistration,\n} from \"../providers/cursor/registration.js\";\nimport { GEMINI_PROVIDER_ID } from \"../providers/gemini/adapter.js\";\nimport { type GeminiHookEventName } from \"../providers/gemini/schema.js\";\nimport {\n GEMINI_REGISTRABLE_HOOK_EVENTS,\n mergeGeminiHookRegistration,\n readGeminiHookRegistrations,\n removeGeminiHookRegistration,\n} from \"../providers/gemini/setup.js\";\nimport type {\n HookDocumentChange,\n HookDocumentConflict,\n HookHandlerPredicate,\n NestedHookDocumentResult,\n} from \"../providers/hook-document.js\";\n\n/**\n * One uniform interface over planners whose *document shapes differ*.\n *\n * Four providers, three shapes: Claude Code, the Codex CLI, and the Gemini CLI\n * share the nested matcher-group document (with Gemini adding a `name` field),\n * while Antigravity's hook file is a flat list per event. Keeping the shape\n * knowledge inside each provider's planner and adapting only the *result* here\n * is what lets `setup`, `diagnose`, and `uninstall` be written once.\n *\n * Nothing in this module reads or writes a file; `lifecycle.ts` does that.\n */\n\n/** The hook name this tool registers under, where the vocabulary has one. */\nexport const MANAGED_HOOK_NAME = \"otel-hook\";\n\n/**\n * Substring that marks a command as this tool's, across versions.\n *\n * Setup has to recognize what an *older* version of itself wrote, or an upgrade\n * that changed the command string (a new absolute path, a new `--endpoint`)\n * would append a second registration and double every span. There is no field\n * in either documented vocabulary to stamp ownership into, so the command\n * string is the only available marker.\n */\nexport const DEFAULT_MANAGED_COMMAND_MARKER = \"otel-hook\";\n\n/**\n * The token that makes a marker *this tool's*.\n *\n * Ownership cannot be inferred from a command being \"specific enough\" — a\n * plausible-looking marker like `run` or `npm` is specific enough to read as\n * deliberate and still matches half the hooks a developer has configured. So the\n * marker has to name this package, and the only name that does is this one.\n */\nexport const MANAGED_MARKER_TOKEN = \"otel-hook\";\n\nexport const MAX_MANAGED_COMMAND_MARKER_LENGTH = 200;\n\n/**\n * Shortest absolute path accepted as an ownership marker in its own right.\n *\n * An absolute path is a different kind of evidence from a name: `/opt/tools/oh`\n * does not contain `otel-hook`, but it also cannot appear inside `npm run build`\n * or any other command that is not literally invoking that path. So a rooted,\n * separator-bearing path is accepted on its specificity rather than its spelling —\n * which is what lets an operator point at a bespoke install location.\n */\nconst MIN_ABSOLUTE_PATH_MARKER_LENGTH = 8;\n\nexport type ManagedMarkerRejection =\n | \"empty\"\n | \"too-long\"\n | \"untrimmed\"\n | \"not-ownership-bearing\";\n\n/** Non-sensitive explanations, safe to print: the operator just typed the marker. */\nexport const MANAGED_MARKER_REJECTION_DETAIL: Readonly<Record<ManagedMarkerRejection, string>> =\n Object.freeze({\n empty: \"the managed marker is empty, which would match every hook already configured\",\n \"too-long\": `the managed marker is longer than ${String(MAX_MANAGED_COMMAND_MARKER_LENGTH)} characters`,\n untrimmed:\n \"the managed marker has leading or trailing whitespace, which is almost always a quoting mistake and would not match the command as written\",\n \"not-ownership-bearing\":\n `the managed marker must identify this tool: either contain \"${MANAGED_MARKER_TOKEN}\", or be an absolute path to the installed command. ` +\n \"A generic marker matches hooks this tool does not own, and uninstall would delete them\",\n });\n\n/**\n * Whether a marker is an absolute path, on either platform's spelling.\n *\n * POSIX `/usr/local/bin/...`, Windows `C:\\...` or `C:/...`, and UNC `\\\\host\\share`\n * all count. Deliberately platform-independent rather than using `path.isAbsolute`:\n * a settings file written on one machine is read on another, and a marker that\n * validated on Linux must not become unusable when the same repository is opened\n * on Windows.\n */\nconst isAbsolutePathMarker = (marker: string): boolean =>\n /^\\//.test(marker) || /^[A-Za-z]:[\\\\/]/.test(marker) || /^\\\\\\\\[^\\\\]/.test(marker);\n\n/**\n * Why a managed marker is unusable, or `undefined` when it is safe.\n *\n * The marker is used as a **substring test** against commands already in a\n * developer's configuration, and that test decides what `uninstall` deletes and\n * what `setup` rewrites in place. Two failure modes, both destructive, and neither\n * recoverable from a backup the developer does not have:\n *\n * - An empty marker makes `\"\".includes()` true for every handler, so\n * `uninstall --managed-marker \"\"` would delete every hook configured by every\n * tool.\n * - A *generic* marker is the same bug wearing a disguise. `run` matches\n * `npm run build`, `cargo run`, and any `runner.sh`; `npm` matches every npm\n * script hook a developer has. Length and alphanumerics do not distinguish these\n * from a real marker, so the test is ownership: the marker must either name this\n * package or be an absolute path to it.\n *\n * Validated *before* a document is read, let alone written — a refusal costs one\n * re-run, a wrong match costs a configuration nobody has a copy of.\n */\nexport const checkManagedMarker = (marker: string): ManagedMarkerRejection | undefined => {\n if (marker.length === 0) {\n return \"empty\";\n }\n if (marker !== marker.trim()) {\n return \"untrimmed\";\n }\n if (marker.length > MAX_MANAGED_COMMAND_MARKER_LENGTH) {\n return \"too-long\";\n }\n // Case-insensitive: a Windows path may well be spelled `Otel-Hook`, and the\n // comparison that matters happens against the command string either way.\n if (marker.toLowerCase().includes(MANAGED_MARKER_TOKEN)) {\n return undefined;\n }\n if (isAbsolutePathMarker(marker) && marker.length >= MIN_ABSOLUTE_PATH_MARKER_LENGTH) {\n return undefined;\n }\n return \"not-ownership-bearing\";\n};\n\n/**\n * Recognizes a hook handler this tool owns, by hook name or command marker.\n *\n * Throws on a marker {@link checkManagedMarker} refuses. A predicate is built\n * before any file is opened, so throwing here cannot leave a document\n * half-changed — and returning a match-everything predicate instead would turn\n * an operator's typo into data loss.\n */\nexport const managedHookPredicate = (marker: string): HookHandlerPredicate => {\n const rejection = checkManagedMarker(marker);\n if (rejection !== undefined) {\n throw new Error(MANAGED_MARKER_REJECTION_DETAIL[rejection]);\n }\n return (handler): boolean =>\n handler.name === MANAGED_HOOK_NAME ||\n (typeof handler.command === \"string\" && handler.command.includes(marker));\n};\n\nexport type RegistrationPlanInput = {\n /** Parsed configuration document, or `undefined` when the file is absent. */\n readonly existing?: unknown;\n readonly command: string;\n /** Overrides the planner's default event set. */\n readonly events?: readonly string[];\n readonly matcher?: string;\n readonly timeoutSeconds?: number;\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type RegistrationRemovalInput = {\n readonly existing?: unknown;\n readonly events?: readonly string[];\n readonly identifies: HookHandlerPredicate;\n};\n\nexport type ProviderRegistrationPlanner = {\n readonly providerId: string;\n /**\n * Events registered when the caller names none: the intersection of \"the\n * provider documents it\" and \"this adapter turns it into telemetry\". Each\n * planner's module records the exclusions and why.\n */\n readonly defaultEvents: readonly string[];\n merge(input: RegistrationPlanInput): NestedHookDocumentResult;\n remove(input: RegistrationRemovalInput): NestedHookDocumentResult;\n read(existing: unknown, identifies: HookHandlerPredicate): ReadonlyMap<string, readonly string[]>;\n};\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\n/** Reads the managed registrations out of a document, per event. */\ntype RegistrationReader = (\n existing: unknown,\n identifies: HookHandlerPredicate,\n) => ReadonlyMap<string, readonly string[]>;\n\n/**\n * The flat-document planners (Antigravity, Cursor) report only\n * `{ config, changed }`. Rather than change a published contract, the per-event\n * outcome is recovered by comparing the registrations before and after, and the\n * one structural check the flat shape needs is applied separately.\n */\nconst adaptFlatResult = (\n read: RegistrationReader,\n existing: unknown,\n events: readonly string[],\n identifies: HookHandlerPredicate,\n result: { readonly config: Record<string, unknown>; readonly changed: boolean },\n removal: boolean,\n): NestedHookDocumentResult => {\n const before = read(existing, identifies);\n const after = read(result.config, identifies);\n const changes: HookDocumentChange[] = [];\n\n for (const event of events) {\n const had = before.has(event);\n const has = after.has(event);\n if (removal) {\n if (had && !has) {\n changes.push({ event, action: \"removed\" });\n }\n continue;\n }\n if (!had) {\n changes.push({ event, action: \"added\" });\n } else {\n const same =\n JSON.stringify(before.get(event) ?? []) === JSON.stringify(after.get(event) ?? []);\n changes.push({ event, action: same ? \"unchanged\" : \"updated\" });\n }\n }\n\n return { document: result.config, changed: result.changed, changes, conflicts: [] };\n};\n\n/**\n * Structural check for the flat shape: `hooks` must be an object keyed by event\n * name whose values are arrays of entries. Anything else is reported so the\n * caller refuses to write, rather than coerced.\n */\nconst flatHookConflicts = (existing: unknown): readonly HookDocumentConflict[] => {\n if (!isPlainObject(existing) || existing.hooks === undefined) {\n return [];\n }\n if (!isPlainObject(existing.hooks)) {\n return [\n {\n location: \"hooks\",\n detail: `expected an object keyed by hook event name, found ${\n Array.isArray(existing.hooks) ? \"an array\" : typeof existing.hooks\n }`,\n },\n ];\n }\n const conflicts: HookDocumentConflict[] = [];\n for (const [event, list] of Object.entries(existing.hooks)) {\n if (!Array.isArray(list)) {\n conflicts.push({\n location: `hooks.${event}`,\n detail: `expected an array of hook entries, found ${list === null ? \"null\" : typeof list}`,\n });\n }\n }\n return conflicts;\n};\n\nconst asAntigravityEvents = (events: readonly string[]): readonly (typeof ANTIGRAVITY_HOOK_EVENT_NAMES)[number][] =>\n events as readonly (typeof ANTIGRAVITY_HOOK_EVENT_NAMES)[number][];\n\n/** Event keys actually present in a flat document, for a removal with no `--event`. */\nconst documentEventNames = (existing: unknown): readonly string[] =>\n isPlainObject(existing) && isPlainObject(existing.hooks) ? Object.keys(existing.hooks) : [];\n\nconst PLANNERS: readonly ProviderRegistrationPlanner[] = Object.freeze([\n Object.freeze({\n providerId: ANTIGRAVITY_PROVIDER_ID,\n defaultEvents: ANTIGRAVITY_HOOK_EVENT_NAMES,\n merge: (input: RegistrationPlanInput): NestedHookDocumentResult => {\n const conflicts = flatHookConflicts(input.existing);\n if (conflicts.length > 0) {\n return {\n document: isPlainObject(input.existing) ? input.existing : {},\n changed: false,\n changes: [],\n conflicts,\n };\n }\n const events = input.events ?? ANTIGRAVITY_HOOK_EVENT_NAMES;\n return adaptFlatResult(\n readAntigravityHookRegistrations,\n input.existing,\n events,\n input.identifies,\n mergeAntigravityHookRegistration({\n ...(input.existing === undefined ? {} : { existing: input.existing }),\n command: input.command,\n events: asAntigravityEvents(events),\n ...(input.matcher === undefined ? {} : { matcher: input.matcher }),\n identifies: input.identifies,\n }),\n false,\n );\n },\n remove: (input: RegistrationRemovalInput): NestedHookDocumentResult => {\n const conflicts = flatHookConflicts(input.existing);\n if (conflicts.length > 0) {\n return {\n document: isPlainObject(input.existing) ? input.existing : {},\n changed: false,\n changes: [],\n conflicts,\n };\n }\n const events = input.events ?? documentEventNames(input.existing);\n return adaptFlatResult(\n readAntigravityHookRegistrations,\n input.existing,\n events,\n input.identifies,\n removeAntigravityHookRegistration({\n ...(input.existing === undefined ? {} : { existing: input.existing }),\n ...(input.events === undefined ? {} : { events: asAntigravityEvents(input.events) }),\n identifies: input.identifies,\n }),\n true,\n );\n },\n read: readAntigravityHookRegistrations,\n }),\n Object.freeze({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n defaultEvents: CLAUDE_REGISTRABLE_HOOK_EVENTS,\n merge: (input: RegistrationPlanInput): NestedHookDocumentResult =>\n mergeClaudeHookRegistration(input),\n remove: (input: RegistrationRemovalInput): NestedHookDocumentResult =>\n removeClaudeHookRegistration(input),\n read: readClaudeHookRegistrations,\n }),\n Object.freeze({\n providerId: CODEX_PROVIDER_ID,\n defaultEvents: CODEX_REGISTRABLE_HOOK_EVENTS,\n merge: (input: RegistrationPlanInput): NestedHookDocumentResult =>\n mergeCodexHookRegistration(input),\n remove: (input: RegistrationRemovalInput): NestedHookDocumentResult =>\n removeCodexHookRegistration(input),\n read: readCodexHookRegistrations,\n }),\n Object.freeze({\n providerId: CURSOR_PROVIDER_ID,\n defaultEvents: CURSOR_REGISTRABLE_HOOK_EVENTS,\n merge: (input: RegistrationPlanInput): NestedHookDocumentResult => {\n const conflicts = flatHookConflicts(input.existing);\n if (conflicts.length > 0) {\n return {\n document: isPlainObject(input.existing) ? input.existing : {},\n changed: false,\n changes: [],\n conflicts,\n };\n }\n const events = input.events ?? CURSOR_REGISTRABLE_HOOK_EVENTS;\n return adaptFlatResult(\n readCursorHookRegistrations,\n input.existing,\n events,\n input.identifies,\n mergeCursorHookRegistration({\n ...(input.existing === undefined ? {} : { existing: input.existing }),\n command: input.command,\n events,\n ...(input.matcher === undefined ? {} : { matcher: input.matcher }),\n ...(input.timeoutSeconds === undefined ? {} : { timeoutSeconds: input.timeoutSeconds }),\n identifies: input.identifies,\n }),\n false,\n );\n },\n remove: (input: RegistrationRemovalInput): NestedHookDocumentResult => {\n const conflicts = flatHookConflicts(input.existing);\n if (conflicts.length > 0) {\n return {\n document: isPlainObject(input.existing) ? input.existing : {},\n changed: false,\n changes: [],\n conflicts,\n };\n }\n return adaptFlatResult(\n readCursorHookRegistrations,\n input.existing,\n input.events ?? documentEventNames(input.existing),\n input.identifies,\n removeCursorHookRegistration({\n ...(input.existing === undefined ? {} : { existing: input.existing }),\n ...(input.events === undefined ? {} : { events: input.events }),\n identifies: input.identifies,\n }),\n true,\n );\n },\n read: readCursorHookRegistrations,\n }),\n Object.freeze({\n providerId: GEMINI_PROVIDER_ID,\n defaultEvents: GEMINI_REGISTRABLE_HOOK_EVENTS,\n merge: (input: RegistrationPlanInput): NestedHookDocumentResult => {\n const merged = mergeGeminiHookRegistration(input.existing, {\n name: MANAGED_HOOK_NAME,\n command: input.command,\n events: (input.events ?? GEMINI_REGISTRABLE_HOOK_EVENTS) as readonly GeminiHookEventName[],\n ...(input.matcher === undefined ? {} : { matcher: input.matcher }),\n // Seconds in; the Gemini planner converts to the milliseconds that\n // vocabulary uses.\n ...(input.timeoutSeconds === undefined ? {} : { timeoutSeconds: input.timeoutSeconds }),\n identifies: input.identifies,\n });\n return {\n document: merged.settings,\n changed: merged.changed,\n changes: merged.changes,\n conflicts: merged.conflicts,\n };\n },\n remove: (input: RegistrationRemovalInput): NestedHookDocumentResult =>\n removeGeminiHookRegistration(input.existing, {\n ...(input.events === undefined\n ? {}\n : { events: input.events as readonly GeminiHookEventName[] }),\n identifies: input.identifies,\n }),\n read: readGeminiHookRegistrations,\n }),\n]);\n\nexport const findRegistrationPlanner = (\n providerId: string,\n): ProviderRegistrationPlanner | undefined =>\n PLANNERS.find((planner) => planner.providerId === providerId);\n\nexport const REGISTRATION_PLANNERS = PLANNERS;\n","import { ANTIGRAVITY_PROVIDER_ID } from \"../providers/antigravity/adapter.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"../providers/claude/detect.js\";\nimport { CODEX_PROVIDER_ID } from \"../providers/codex/version.js\";\nimport { CURSOR_PROVIDER_ID } from \"../providers/cursor/payload.js\";\nimport { GEMINI_PROVIDER_ID } from \"../providers/gemini/adapter.js\";\n\n/**\n * Per-provider registration availability, and the evidence behind it.\n *\n * `supported: false` is a statement about *this repository's* verified\n * knowledge, not about the provider. Each entry is meant to be checkable: a\n * reviewer should be able to read the reason, open the named source, and agree\n * or disagree without running anything.\n */\n\nexport type ProviderRegistrationSupport = {\n readonly providerId: string;\n readonly supported: boolean;\n /** Why registration is or is not offered, in one reviewable sentence. */\n readonly reason: string;\n /** Name of the planner to call, when supported. */\n readonly helper?: string;\n /** For an unsupported provider: precisely what would have to be verified. */\n readonly evidenceBlocker?: string;\n};\n\nexport const PROVIDER_REGISTRATION_SUPPORT: readonly ProviderRegistrationSupport[] = Object.freeze([\n Object.freeze({\n providerId: ANTIGRAVITY_PROVIDER_ID,\n supported: true,\n reason:\n \"the five documented camelCase command hooks and the hook-file shape are recorded by the antigravity adapter\",\n helper: \"mergeAntigravityHookRegistration\",\n }),\n Object.freeze({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n supported: true,\n reason:\n \"the settings.json hook document, its global and project scopes, and every event this adapter models are \" +\n \"documented at code.claude.com/docs/en/hooks and cross-checked against o11y-dev/opentelemetry-hooks v0.14.0\",\n helper: \"mergeClaudeHookRegistration\",\n }),\n Object.freeze({\n providerId: CODEX_PROVIDER_ID,\n supported: true,\n reason:\n \"the .codex/hooks.json document, its global and project scopes, and the event vocabulary are documented at \" +\n \"learn.chatgpt.com/docs/hooks — the same reference this adapter's payload contract is drawn from\",\n helper: \"mergeCodexHookRegistration\",\n }),\n Object.freeze({\n providerId: CURSOR_PROVIDER_ID,\n supported: true,\n reason:\n \"the ~/.cursor/hooks.json and .cursor/hooks.json documents, their shape, and the event vocabulary are \" +\n \"documented at cursor.com/docs/agent/hooks, and the payload contract this adapter parses is derived from \" +\n \"that reference plus four real redacted capture runs (Cursor IDE 3.12.17 and CLI 2026.07.17, recorded in \" +\n \"providers/cursor/payload.ts and replayed from fixtures/parity/cursor)\",\n helper: \"mergeCursorHookRegistration\",\n }),\n Object.freeze({\n providerId: GEMINI_PROVIDER_ID,\n supported: true,\n reason: \"the Gemini CLI settings.json hooks schema and event vocabulary are recorded by the gemini adapter\",\n helper: \"mergeGeminiHookRegistration\",\n }),\n]);\n\nexport const findRegistrationSupport = (providerId: string): ProviderRegistrationSupport | undefined =>\n PROVIDER_REGISTRATION_SUPPORT.find((entry) => entry.providerId === providerId);\n\n/** Provider ids this repository can plan a registration for, in catalog order. */\nexport const SUPPORTED_REGISTRATION_PROVIDER_IDS: readonly string[] = Object.freeze(\n PROVIDER_REGISTRATION_SUPPORT.filter((entry) => entry.supported).map((entry) => entry.providerId),\n);\n","import * as path from \"node:path\";\n\nimport { ANTIGRAVITY_PROVIDER_ID } from \"../providers/antigravity/adapter.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"../providers/claude/detect.js\";\nimport { CODEX_PROVIDER_ID } from \"../providers/codex/version.js\";\nimport { CURSOR_PROVIDER_ID } from \"../providers/cursor/payload.js\";\nimport { GEMINI_PROVIDER_ID } from \"../providers/gemini/adapter.js\";\n\n/**\n * Where each provider keeps the configuration document this tool registers into.\n *\n * A path here is a claim about a third party's on-disk layout, so each one names\n * the source that established it. A provider with a verified *planner* but no\n * verified *location* (Antigravity) is deliberately absent: `setup` then requires\n * an explicit `--settings-file`, which is honest about what this repository knows\n * rather than writing a plausible-looking path into a developer's home\n * directory.\n */\n\nexport type RegistrationScope = \"global\" | \"project\";\nexport const REGISTRATION_SCOPES: readonly RegistrationScope[] = Object.freeze([\n \"global\",\n \"project\",\n] as const);\n\nexport type InstallLocation = {\n readonly providerId: string;\n readonly scope: RegistrationScope;\n /** Path segments below the home directory (global) or project root (project). */\n readonly segments: readonly string[];\n /** One reviewable sentence naming what verified this path. */\n readonly evidence: string;\n};\n\nconst CLAUDE_EVIDENCE =\n \"code.claude.com/docs/en/hooks settings-file table, cross-checked against o11y-dev/opentelemetry-hooks v0.14.0 setup.sh\";\nconst CODEX_EVIDENCE =\n \"learn.chatgpt.com/docs/hooks discovery-locations list, cross-checked against o11y-dev/opentelemetry-hooks v0.14.0 setup.sh\";\nconst GEMINI_EVIDENCE =\n \"o11y-dev/opentelemetry-hooks v0.14.0 setup.sh (setup_gemini) and its supported-agents table\";\n/**\n * Cursor also documents enterprise-managed locations (`/etc/cursor/hooks.json`\n * and the macOS/Windows equivalents). They are deliberately not offered as a\n * scope: they are MDM-owned and outside any home directory.\n */\nconst CURSOR_EVIDENCE =\n \"cursor.com/docs/agent/hooks configuration-levels list (user and project), cross-checked against o11y-dev/opentelemetry-hooks v0.14.0 setup.sh\";\n\nexport const PROVIDER_INSTALL_LOCATIONS: readonly InstallLocation[] = Object.freeze([\n Object.freeze({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n scope: \"global\" as const,\n segments: Object.freeze([\".claude\", \"settings.json\"]),\n evidence: CLAUDE_EVIDENCE,\n }),\n Object.freeze({\n providerId: CLAUDE_CODE_PROVIDER_ID,\n scope: \"project\" as const,\n segments: Object.freeze([\".claude\", \"settings.json\"]),\n evidence: CLAUDE_EVIDENCE,\n }),\n Object.freeze({\n providerId: CODEX_PROVIDER_ID,\n scope: \"global\" as const,\n segments: Object.freeze([\".codex\", \"hooks.json\"]),\n evidence: CODEX_EVIDENCE,\n }),\n Object.freeze({\n providerId: CODEX_PROVIDER_ID,\n scope: \"project\" as const,\n segments: Object.freeze([\".codex\", \"hooks.json\"]),\n evidence: CODEX_EVIDENCE,\n }),\n Object.freeze({\n providerId: CURSOR_PROVIDER_ID,\n scope: \"global\" as const,\n segments: Object.freeze([\".cursor\", \"hooks.json\"]),\n evidence: CURSOR_EVIDENCE,\n }),\n Object.freeze({\n providerId: CURSOR_PROVIDER_ID,\n scope: \"project\" as const,\n segments: Object.freeze([\".cursor\", \"hooks.json\"]),\n evidence: CURSOR_EVIDENCE,\n }),\n Object.freeze({\n providerId: GEMINI_PROVIDER_ID,\n scope: \"global\" as const,\n segments: Object.freeze([\".gemini\", \"settings.json\"]),\n evidence: GEMINI_EVIDENCE,\n }),\n Object.freeze({\n providerId: GEMINI_PROVIDER_ID,\n scope: \"project\" as const,\n segments: Object.freeze([\".gemini\", \"settings.json\"]),\n evidence: GEMINI_EVIDENCE,\n }),\n]);\n\n/**\n * Providers whose planner is verified but whose install location is not, with\n * the blocker. `setup --provider <id> --settings-file <path>` still works.\n */\nexport const PROVIDERS_WITHOUT_VERIFIED_LOCATION: Readonly<Record<string, string>> = Object.freeze({\n [ANTIGRAVITY_PROVIDER_ID]:\n \"no Antigravity hook-file path has been verified; o11y-dev/opentelemetry-hooks v0.14.0 lists Antigravity as \" +\n 'a \"manual hook command, runner-defined\" integration and writes no file for it',\n});\n\n/**\n * Providers this tool can find on its own, in catalog order.\n *\n * This — not \"every provider with a planner\" — is what a bare `diagnose`\n * sweeps: a provider whose path must be supplied by hand has nowhere to look.\n */\nexport const PROVIDERS_WITH_VERIFIED_LOCATION: readonly string[] = Object.freeze([\n ...new Set(PROVIDER_INSTALL_LOCATIONS.map((entry) => entry.providerId)),\n]);\n\nexport const findInstallLocation = (\n providerId: string,\n scope: RegistrationScope,\n): InstallLocation | undefined =>\n PROVIDER_INSTALL_LOCATIONS.find(\n (entry) => entry.providerId === providerId && entry.scope === scope,\n );\n\nexport type ScopeRoots = {\n readonly homeDir: string;\n readonly projectDir: string;\n};\n\nexport const resolveInstallPath = (location: InstallLocation, roots: ScopeRoots): string =>\n path.resolve(\n location.scope === \"global\" ? roots.homeDir : roots.projectDir,\n ...location.segments,\n );\n","import { randomBytes } from \"node:crypto\";\nimport { chmod, mkdir, open, readFile, rename, stat, unlink } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\n/**\n * Reading and writing a *third party's* configuration document.\n *\n * Two properties matter more here than anywhere else in this package, because\n * the file belongs to the developer and not to us:\n *\n * 1. **Never lose a byte we did not mean to change.** The file's indentation,\n * line endings, and trailing newline are detected on read and reproduced on\n * write, so a registration shows up in `git diff` as the lines it added and\n * nothing else. A document that cannot be parsed is reported, never\n * overwritten.\n * 2. **Never leave a half-written file.** Every write lands through a temp file\n * in the same directory plus `rename`, which is atomic on POSIX and, via\n * libuv's `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, on Windows. A process\n * killed mid-write leaves an orphaned temp file, never a truncated\n * `settings.json`.\n */\n\nexport type JsonDocumentFormat = {\n /** Indent string detected from the file, e.g. `\" \"` or `\"\\t\"`. */\n readonly indent: string;\n readonly eol: \"\\n\" | \"\\r\\n\";\n readonly trailingNewline: boolean;\n};\n\n/**\n * What a brand-new document looks like. `\"\\n\"` rather than the platform EOL: a\n * config file this tool creates should read the same on every machine that\n * shares the repository, and every JSON parser accepts it.\n */\nexport const DEFAULT_DOCUMENT_FORMAT: JsonDocumentFormat = Object.freeze({\n indent: \" \",\n eol: \"\\n\" as const,\n trailingNewline: true,\n});\n\nexport type ReadDocumentResult =\n | { readonly status: \"absent\"; readonly format: JsonDocumentFormat }\n | {\n readonly status: \"ok\";\n readonly value: unknown;\n readonly raw: string;\n readonly format: JsonDocumentFormat;\n }\n | {\n readonly status: \"unparseable\";\n readonly raw: string;\n /** Non-sensitive: the parser message, never the file's contents. */\n readonly detail: string;\n readonly format: JsonDocumentFormat;\n }\n | { readonly status: \"unreadable\"; readonly detail: string };\n\nconst isErrnoException = (thrown: unknown, ...codes: readonly string[]): boolean =>\n thrown instanceof Error && codes.includes((thrown as NodeJS.ErrnoException).code ?? \"\");\n\n/**\n * Infer the indent, line ending, and trailing newline actually used.\n *\n * The indent is read from the first indented line rather than from the deepest\n * one, because that is the level `JSON.stringify` will reproduce first and the\n * only one it can reproduce at all — it has a single indent setting.\n */\nexport const detectDocumentFormat = (raw: string): JsonDocumentFormat => {\n const eol = /\\r\\n/.test(raw) ? (\"\\r\\n\" as const) : (\"\\n\" as const);\n const indentMatch = /(?:\\r?\\n)([ \\t]+)\\S/.exec(raw);\n return {\n indent: indentMatch?.[1] ?? DEFAULT_DOCUMENT_FORMAT.indent,\n eol,\n trailingNewline: raw.length === 0 || /\\r?\\n$/.test(raw),\n };\n};\n\nexport const renderJsonDocument = (value: unknown, format: JsonDocumentFormat): string => {\n const body = JSON.stringify(value, null, format.indent);\n const withEol = format.eol === \"\\n\" ? body : body.split(\"\\n\").join(format.eol);\n return format.trailingNewline ? `${withEol}${format.eol}` : withEol;\n};\n\nexport const readJsonDocument = async (filePath: string): Promise<ReadDocumentResult> => {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (thrown) {\n if (isErrnoException(thrown, \"ENOENT\")) {\n return { status: \"absent\", format: DEFAULT_DOCUMENT_FORMAT };\n }\n return {\n status: \"unreadable\",\n detail: thrown instanceof Error ? thrown.name : typeof thrown,\n };\n }\n\n const format = detectDocumentFormat(raw);\n if (raw.trim().length === 0) {\n // An empty file is a legitimate \"nothing configured yet\" state that\n // `JSON.parse` rejects. Treating it as absent lets setup populate it.\n return { status: \"absent\", format };\n }\n try {\n return { status: \"ok\", value: JSON.parse(raw) as unknown, raw, format };\n } catch (thrown) {\n return {\n status: \"unparseable\",\n raw,\n detail: thrown instanceof Error ? thrown.message.slice(0, 200) : \"not well-formed JSON\",\n format,\n };\n }\n};\n\n/**\n * On Windows a rename can transiently fail while an indexer or antivirus holds\n * the destination open. A short bounded retry turns a spurious failure into a\n * successful write; a real permission problem still surfaces after the last try.\n */\nconst RENAME_RETRY_DELAYS_MILLIS: readonly number[] = [10, 25, 50, 100];\n\n/** Not `unref`'d: see the note in `file-lock.ts` — a waiter must keep the process alive. */\nconst delay = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, millis);\n });\n\nconst renameWithRetry = async (from: string, to: string): Promise<void> => {\n for (let attempt = 0; ; attempt += 1) {\n try {\n await rename(from, to);\n return;\n } catch (thrown) {\n const retryable = isErrnoException(thrown, \"EPERM\", \"EACCES\", \"EBUSY\");\n const remaining = RENAME_RETRY_DELAYS_MILLIS[attempt];\n if (!retryable || remaining === undefined) {\n throw thrown;\n }\n await delay(remaining);\n }\n }\n};\n\n/**\n * Mode for a configuration document this tool creates: owner read/write only.\n *\n * Deliberately not left to the process umask. A hook command line can carry an\n * `--endpoint` with a token in it, and these files sit in a home directory that\n * is frequently group- or world-readable; a default umask of 022 would publish\n * every registration this tool writes to any local account. An operator who\n * wants it wider can widen it, and a *replacement* never narrows what was\n * already there — see {@link writeDocumentAtomically}.\n */\nexport const NEW_DOCUMENT_MODE = 0o600;\n\n/** Owner-only mode for the temp file, so the window before the rename is not wider than the result. */\nconst TEMPORARY_DOCUMENT_MODE = 0o600;\n\n/**\n * Write `contents` to `filePath` atomically, creating parent directories.\n *\n * The temp file is created in the destination directory so the rename stays\n * within one filesystem, and is fsynced before the rename so a crash cannot\n * leave the renamed file pointing at unflushed data.\n *\n * A rename replaces the destination *inode*, so the mode travels with the temp\n * file rather than with the path — which means an atomic replace silently\n * re-permissions the file unless the original mode is carried across. An\n * existing document keeps exactly the mode it had (a developer who chmodded\n * their `settings.json` to 0600, or to 0644, keeps that decision); a file this\n * tool creates gets {@link NEW_DOCUMENT_MODE} rather than whatever the umask\n * would have allowed. The temp file is owner-only for its whole life, so the\n * contents are never briefly readable by anyone who could not read the result.\n */\nexport const writeDocumentAtomically = async (\n filePath: string,\n contents: string,\n): Promise<void> => {\n const directory = path.dirname(filePath);\n await mkdir(directory, { recursive: true });\n const temporary = path.join(\n directory,\n `.${path.basename(filePath)}.${randomBytes(6).toString(\"hex\")}.tmp`,\n );\n\n // Read before writing: after the rename the original inode is gone.\n let existingMode: number | undefined;\n try {\n existingMode = (await stat(filePath)).mode & 0o7777;\n } catch (thrown) {\n if (!isErrnoException(thrown, \"ENOENT\")) {\n throw thrown;\n }\n }\n const targetMode = existingMode ?? NEW_DOCUMENT_MODE;\n\n try {\n const handle = await open(temporary, \"wx\", TEMPORARY_DOCUMENT_MODE);\n try {\n await handle.writeFile(contents, \"utf8\");\n await handle.sync();\n // Through the open handle, so the mode lands on the inode being renamed\n // even if something replaced the temp path underneath us.\n await handle.chmod(targetMode);\n } finally {\n await handle.close();\n }\n await renameWithRetry(temporary, filePath);\n } catch (thrown) {\n await unlink(temporary).catch(() => undefined);\n throw thrown;\n }\n};\n\n/**\n * Narrow an existing document to owner-only, reporting the mode it had.\n *\n * Exported for `diagnose`, which can then say that a registration it did not\n * create is world-readable without changing it behind the operator's back.\n */\nexport const documentMode = async (filePath: string): Promise<number | undefined> => {\n try {\n return (await stat(filePath)).mode & 0o7777;\n } catch {\n return undefined;\n }\n};\n\n/** Set a document's mode, ignoring a platform that does not implement it. */\nexport const setDocumentMode = async (filePath: string, mode: number): Promise<void> => {\n await chmod(filePath, mode).catch(() => undefined);\n};\n","import { randomBytes } from \"node:crypto\";\nimport { mkdir, open, readFile, rename, stat, unlink } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport type { Clock } from \"../runtime/ports.js\";\n\n/**\n * Cross-process advisory lock around one configuration file.\n *\n * Two `otel-hook setup` runs against the same `settings.json` — a shell loop, a\n * provisioning tool, two terminals — would otherwise both read the original\n * document and both write their own merge, so whichever finished last would\n * silently drop the other's registration. Atomic renames make each *write*\n * safe; only a lock makes the read-merge-write *sequence* safe.\n *\n * `open(path, \"wx\")` is the primitive: it either creates the file or fails with\n * `EEXIST`, atomically, on every platform this package supports. A lock whose\n * recorded acquisition time is older than `staleMillis` is assumed to belong to\n * a process that crashed while holding it and is reclaimed, so a killed setup\n * cannot wedge every later one.\n *\n * This is a separate implementation from the state store's session lock on\n * purpose: that one is namespaced under the state directory and keyed by session\n * id, while this one has to live beside a file it does not own.\n */\n\nexport type FileLockOptions = {\n readonly clock: Clock;\n /** How long to wait for the holder before giving up. Default 5,000ms. */\n readonly timeoutMillis?: number;\n /** A lock older than this is treated as abandoned. Default 30,000ms. */\n readonly staleMillis?: number;\n /** Delay between acquisition attempts. Default 25ms. */\n readonly pollIntervalMillis?: number;\n};\n\nexport class FileLockTimeoutError extends Error {\n constructor(lockPath: string, timeoutMillis: number) {\n super(\n `timed out after ${String(timeoutMillis)}ms waiting for the lock on ${path.basename(lockPath)}`,\n );\n this.name = \"FileLockTimeoutError\";\n }\n}\n\n/** Where the lock for a configuration file lives: beside it, clearly ours. */\nexport const lockPathFor = (filePath: string): string => `${filePath}.otel-hook.lock`;\n\n/**\n * Contents of a held lock. `token` is what makes reclaim safe.\n *\n * Without it, \"release the lock\" means \"unlink this path\", which is not the same\n * operation: a holder slow enough to be declared stale gets its lock unlinked by\n * a waiter, the waiter creates its *own* lock at the same path, and then the\n * original holder's `finally` unlinks the successor's lock — leaving the file\n * unprotected while the successor still believes it holds it, and letting a\n * third process run concurrently with it. A random token per acquisition turns\n * both reclaim and release into compare-and-delete, so a lock can only ever be\n * removed by the process that actually owns it.\n */\ntype LockContents = {\n readonly token: string;\n readonly pid: number;\n readonly acquiredAt: number;\n};\n\n/**\n * Stand-in token for reclaiming a lock whose own token cannot be read.\n *\n * `releaseIfOwned` only restores a captured file when it reads a token that\n * *differs* from the one supplied; an unreadable file yields no token, so it is\n * removed. That is the intended behaviour here — the file has already been judged\n * stale — and it is why nothing else may ever use this value as a real token.\n */\n/*\n * Filesystem-safe, because it becomes part of a tombstone filename, and unable to\n * collide with a real token, which is always 32 hex characters.\n */\nconst RECLAIM_UNTOKENED = \"reclaim-untokened\";\n\nconst isErrnoException = (thrown: unknown, code: string): boolean =>\n thrown instanceof Error && (thrown as NodeJS.ErrnoException).code === code;\n\nconst readLockContents = async (lockPath: string): Promise<LockContents | undefined> => {\n let raw: string;\n try {\n raw = await readFile(lockPath, \"utf8\");\n } catch {\n return undefined;\n }\n try {\n const parsed = JSON.parse(raw) as Partial<LockContents>;\n return typeof parsed.token === \"string\" &&\n typeof parsed.acquiredAt === \"number\" &&\n typeof parsed.pid === \"number\"\n ? { token: parsed.token, pid: parsed.pid, acquiredAt: parsed.acquiredAt }\n : undefined;\n } catch {\n return undefined;\n }\n};\n\n/**\n * Remove the lock if and only if we still own it — via a tombstone rename.\n *\n * Read-then-unlink cannot be made safe, however narrow the window: between the\n * read and the unlink the lock can be released and re-taken by someone else, and\n * the unlink then destroys a live lock. `unlink` takes a *path*, and a path is\n * exactly the thing that stops identifying our lock the moment we let go of it.\n *\n * So the delete is staged through a rename to a name only this call knows:\n *\n * 1. `rename(lockPath, tombstone)` — atomic on POSIX and, via\n * `MoveFileExW(MOVEFILE_REPLACE_EXISTING)`, on Windows. After it, *nothing*\n * else can be at `lockPath` under our name; whatever we captured is now\n * private to us, and a competitor's `open(lockPath, \"wx\")` will simply succeed.\n * 2. Read the tombstone and compare tokens. If it is ours, unlink it: the lock is\n * released, and the release could not have touched anybody else's lock because\n * we were holding the only reference to it.\n * 3. If it is *not* ours, we just moved a live lock out from under its owner, so\n * put it back: `rename(tombstone, lockPath)`. The owner never observes a gap it\n * can act on, because it only ever reads its lock to verify ownership, and it\n * will find its own token restored.\n *\n * Honest limits, since this is a lock file and not a database:\n *\n * - The restore in step 3 is not itself atomic with step 1. A third process can\n * acquire `lockPath` inside that window (the original owner having been judged\n * stale by someone). The restore then replaces it. Both are recorded as *held*,\n * so the outcome is a lock held by a process that will not release it until its\n * own stale window elapses — a delay, not two writers, which is the failure\n * direction that matters for a config-file installer.\n * - If the process dies between steps 1 and 3 the lock is left as a tombstone.\n * Tombstones are named with our own token and are never treated as locks, so the\n * effect is a released lock plus one stray file, not a wedge.\n * - `rename` across the same directory is required; the tombstone therefore lives\n * beside the lock rather than in a temp directory.\n */\nconst releaseIfOwned = async (lockPath: string, token: string): Promise<boolean> => {\n const tombstone = `${lockPath}.${token}.releasing`;\n try {\n await rename(lockPath, tombstone);\n } catch {\n // Already gone, or never ours to move. Either way there is nothing to release\n // and nothing of anybody else's has been touched.\n return false;\n }\n\n const captured = await readLockContents(tombstone);\n if (captured !== undefined && captured.token !== token) {\n // Someone else's live lock. Put it back exactly as found.\n await rename(tombstone, lockPath).catch(async () => {\n // The restore failed, which would silently strand a live holder. Leave the\n // tombstone in place rather than deleting it, so the situation is\n // recoverable by inspection instead of invisible.\n await Promise.resolve();\n });\n return false;\n }\n\n await unlink(tombstone).catch(() => undefined);\n return true;\n};\n\n/**\n * Deliberately *not* `unref`'d. A process polling for this lock has nothing\n * else on its event loop, so an unref'd timer would let Node decide the program\n * was finished and exit — silently, with the setup never performed.\n */\nconst delay = (millis: number): Promise<void> =>\n new Promise((resolve) => {\n setTimeout(resolve, millis);\n });\n\n/**\n * Whether the current holder has abandoned the lock.\n *\n * The subtle case, and the reason this is not a one-liner: `open(path, \"wx\")`\n * creates the file *before* its contents are written, so a waiter can observe a\n * lock that is legitimately held but still empty. Treating \"unparseable\" as\n * \"abandoned\" would let that waiter delete a live lock and run concurrently\n * with its holder — which is precisely the lost update the lock exists to\n * prevent, made rare enough to look like flakiness.\n *\n * So the recorded timestamp is preferred (it comes from the same injected clock\n * as the timeout), and the file's mtime is consulted only when there is no\n * readable timestamp — which answers \"was this created microseconds ago, or did\n * someone die mid-write half an hour back?\" without guessing.\n */\nconst isStale = async (\n lockPath: string,\n clock: Clock,\n staleMillis: number,\n): Promise<{ readonly stale: boolean; readonly token?: string }> => {\n let raw: string;\n try {\n raw = await readFile(lockPath, \"utf8\");\n } catch (thrown) {\n // Released between our EEXIST and this read: not stale, just gone.\n return { stale: !isErrnoException(thrown, \"ENOENT\") };\n }\n\n try {\n const parsed = JSON.parse(raw) as { acquiredAt?: unknown; token?: unknown };\n if (typeof parsed.acquiredAt === \"number\") {\n return {\n stale: clock.now() - parsed.acquiredAt > staleMillis,\n ...(typeof parsed.token === \"string\" ? { token: parsed.token } : {}),\n };\n }\n } catch {\n // Fall through to the mtime check.\n }\n\n try {\n const stats = await stat(lockPath);\n return { stale: clock.now() - stats.mtimeMs > staleMillis };\n } catch (thrown) {\n return { stale: !isErrnoException(thrown, \"ENOENT\") };\n }\n};\n\n/**\n * Run `fn` while holding the lock for `filePath`, releasing it on every path.\n *\n * The timeout bounds only lock *acquisition*; `fn` itself is not interrupted,\n * because aborting a caller partway through a read-merge-write is exactly the\n * outcome the lock exists to prevent.\n */\nexport const withFileLock = async <T>(\n filePath: string,\n options: FileLockOptions,\n fn: () => Promise<T>,\n): Promise<T> => {\n const timeoutMillis = options.timeoutMillis ?? 5_000;\n const staleMillis = options.staleMillis ?? 30_000;\n const pollIntervalMillis = options.pollIntervalMillis ?? 25;\n const lockPath = lockPathFor(filePath);\n const startedAt = options.clock.monotonicMillis();\n\n await mkdir(path.dirname(filePath), { recursive: true });\n\n // Acquisition is a loop of its own so that an error thrown by `fn` — which may\n // legitimately be an EEXIST from something else entirely — can never be\n // mistaken for lock contention and cause `fn` to run a second time.\n for (;;) {\n const token = randomBytes(16).toString(\"hex\");\n let acquired = false;\n try {\n const handle = await open(lockPath, \"wx\", 0o600);\n try {\n const contents: LockContents = {\n token,\n pid: process.pid,\n acquiredAt: options.clock.now(),\n };\n await handle.writeFile(JSON.stringify(contents));\n // Durable before the lock is treated as held: a waiter that reads a\n // half-written lock cannot see a token, and would fall back to mtime.\n await handle.sync();\n } finally {\n await handle.close();\n }\n acquired = true;\n } catch (thrown) {\n if (!isErrnoException(thrown, \"EEXIST\")) {\n throw thrown;\n }\n }\n\n if (acquired) {\n try {\n return await fn();\n } finally {\n // Only our own lock. If a waiter declared us stale and took over, the\n // captured file carries the successor's token and is put straight back.\n await releaseIfOwned(lockPath, token);\n }\n }\n\n const staleness = await isStale(lockPath, options.clock, staleMillis);\n if (staleness.stale) {\n // Reclaim the exact lock we judged stale, through the same tombstone\n // protocol. Two waiters can decide a lock is stale at the same instant; with\n // a plain unlink the slower one would delete whichever lock had been created\n // in the meantime — including the faster one's. Capturing by rename and\n // comparing the token means only the holder of the *judged* lock is removed,\n // and anything else found is restored.\n if (staleness.token === undefined) {\n // No readable token — a lock still being written, or one from a release\n // that predates tokens. Capture it anyway, but only delete what we\n // captured; the token check inside is a no-op for an unreadable file, which\n // is the best available and is why the staleness bound is generous.\n await releaseIfOwned(lockPath, RECLAIM_UNTOKENED);\n } else {\n await releaseIfOwned(lockPath, staleness.token);\n }\n continue;\n }\n if (options.clock.monotonicMillis() - startedAt >= timeoutMillis) {\n throw new FileLockTimeoutError(lockPath, timeoutMillis);\n }\n await delay(pollIntervalMillis);\n }\n};\n","import { readFile } from \"node:fs/promises\";\nimport * as path from \"node:path\";\n\nimport { CODEX_PROVIDER_ID } from \"../providers/codex/version.js\";\nimport { readCodexHooksFeatureFlag } from \"../providers/codex/registration.js\";\nimport type { HookDocumentChange, HookDocumentConflict } from \"../providers/hook-document.js\";\nimport type { Clock } from \"../runtime/ports.js\";\nimport {\n DEFAULT_DOCUMENT_FORMAT,\n readJsonDocument,\n renderJsonDocument,\n writeDocumentAtomically,\n type JsonDocumentFormat,\n} from \"./document.js\";\nimport { withFileLock, type FileLockOptions } from \"./file-lock.js\";\nimport {\n checkManagedMarker,\n DEFAULT_MANAGED_COMMAND_MARKER,\n findRegistrationPlanner,\n MANAGED_MARKER_REJECTION_DETAIL,\n managedHookPredicate,\n} from \"./planners.js\";\nimport {\n findInstallLocation,\n PROVIDERS_WITHOUT_VERIFIED_LOCATION,\n resolveInstallPath,\n type RegistrationScope,\n type ScopeRoots,\n} from \"./scopes.js\";\nimport { findRegistrationSupport } from \"./support.js\";\n\n/**\n * `setup`, `diagnose`, and `uninstall` over a provider's configuration file.\n *\n * The three commands are one function because they are one algorithm with three\n * endings: resolve where the document lives, take the lock, read it, ask the\n * provider's pure planner what the document should become, and then either\n * report the plan (`diagnose`, `--dry-run`) or write it atomically. Sharing the\n * path means a dry run cannot drift from what a real run would do — it is\n * literally the same plan, printed instead of written.\n *\n * Refusals are deliberate and specific. A document that does not parse, or whose\n * `hooks` value is not the documented shape, is reported and left exactly as it\n * is: overwriting a developer's configuration to make an installer succeed is a\n * worse outcome than the installer failing.\n */\n\nexport type RegistrationAction = \"setup\" | \"diagnose\" | \"uninstall\";\n\nexport type RegistrationOutcomeStatus =\n /** A change is required and this is a dry run. */\n | \"planned\"\n /** A change was required and has been written. */\n | \"applied\"\n /** The document already says exactly what it should. */\n | \"unchanged\"\n /** Nothing of ours is registered here (diagnose and uninstall). */\n | \"absent\"\n /** We refuse to touch this document; see `problems`. */\n | \"blocked\"\n /** This repository cannot plan a registration for this provider. */\n | \"unsupported\"\n /** The filesystem operation itself failed. */\n | \"failed\";\n\nexport type RegistrationOutcome = {\n readonly providerId: string;\n readonly scope: RegistrationScope;\n readonly configPath?: string;\n /** What established the path and document shape. */\n readonly evidence?: string;\n readonly status: RegistrationOutcomeStatus;\n readonly changed: boolean;\n readonly changes: readonly HookDocumentChange[];\n readonly conflicts: readonly HookDocumentConflict[];\n /** Events with a registration of ours right now. */\n readonly registeredEvents: readonly string[];\n /** Events that should be registered but are not. */\n readonly missingEvents: readonly string[];\n /** Informational; never a reason to exit non-zero. */\n readonly notes: readonly string[];\n /** Anything an operator must act on. Non-empty means the run is not `ok`. */\n readonly problems: readonly string[];\n /** Exact bytes a non-dry run would write. Present only when a change is planned. */\n readonly plannedContents?: string;\n};\n\nexport type RegistrationReport = {\n readonly action: RegistrationAction;\n readonly dryRun: boolean;\n readonly ok: boolean;\n readonly hookCommand: string;\n readonly outcomes: readonly RegistrationOutcome[];\n};\n\nexport type RegistrationLifecycleRequest = {\n readonly action: RegistrationAction;\n readonly providerIds: readonly string[];\n readonly scopes: readonly RegistrationScope[];\n readonly roots: ScopeRoots;\n /** Overrides the resolved location. Required for a provider with no verified path. */\n readonly configFile?: string;\n /** Defaults to {@link defaultHookCommand} for each provider. */\n readonly command?: string;\n readonly events?: readonly string[];\n readonly matcher?: string;\n readonly timeoutSeconds?: number;\n readonly managedMarker?: string;\n readonly dryRun: boolean;\n readonly clock: Clock;\n readonly lock?: Omit<FileLockOptions, \"clock\">;\n};\n\n/** What this tool registers when the caller names no command. */\nexport const defaultHookCommand = (providerId: string): string =>\n `otel-hook run --provider ${providerId}`;\n\nconst unsupportedOutcome = (\n providerId: string,\n scope: RegistrationScope,\n reason: string,\n): RegistrationOutcome => ({\n providerId,\n scope,\n status: \"unsupported\",\n changed: false,\n changes: [],\n conflicts: [],\n registeredEvents: [],\n missingEvents: [],\n notes: [],\n problems: [reason],\n});\n\ntype ResolvedTarget = {\n readonly configPath: string;\n readonly evidence: string;\n};\n\nconst resolveTarget = (\n providerId: string,\n scope: RegistrationScope,\n request: RegistrationLifecycleRequest,\n): ResolvedTarget | { readonly reason: string } => {\n if (request.configFile !== undefined) {\n return {\n configPath: path.resolve(request.configFile),\n evidence: \"path supplied by the caller with --settings-file\",\n };\n }\n const location = findInstallLocation(providerId, scope);\n if (location !== undefined) {\n return {\n configPath: resolveInstallPath(location, request.roots),\n evidence: location.evidence,\n };\n }\n const blocker = PROVIDERS_WITHOUT_VERIFIED_LOCATION[providerId];\n return {\n reason:\n blocker === undefined\n ? `no ${scope} configuration path is known for provider \"${providerId}\"`\n : `${blocker}; pass --settings-file to register into a path you have verified yourself`,\n };\n};\n\n/**\n * Codex documents hooks as on by default, so setup never edits `config.toml`.\n * An explicit opt-out is still worth reporting: the registration would be\n * written correctly and simply never fire.\n */\nconst codexFeatureNote = async (configPath: string): Promise<string | undefined> => {\n const tomlPath = path.join(path.dirname(configPath), \"config.toml\");\n let raw: string;\n try {\n raw = await readFile(tomlPath, \"utf8\");\n } catch {\n return undefined;\n }\n return readCodexHooksFeatureFlag(raw) === \"disabled\"\n ? `${path.basename(tomlPath)} sets [features] hooks = false; registered hooks will not fire until that is removed`\n : undefined;\n};\n\ntype DocumentState = {\n readonly existing: unknown;\n readonly format: JsonDocumentFormat;\n readonly existed: boolean;\n};\n\nconst readState = async (\n configPath: string,\n): Promise<DocumentState | { readonly problem: string; readonly status: RegistrationOutcomeStatus }> => {\n const read = await readJsonDocument(configPath);\n switch (read.status) {\n case \"absent\":\n return { existing: undefined, format: read.format, existed: false };\n case \"ok\":\n return { existing: read.value, format: read.format, existed: true };\n case \"unparseable\":\n return {\n status: \"blocked\",\n problem: `${path.basename(configPath)} is not well-formed JSON (${read.detail}); it was left untouched`,\n };\n case \"unreadable\":\n return {\n status: \"failed\",\n problem: `${path.basename(configPath)} could not be read (${read.detail})`,\n };\n }\n};\n\nconst duplicateProblems = (\n registrations: ReadonlyMap<string, readonly string[]>,\n): readonly string[] => {\n const duplicated = [...registrations.entries()]\n .filter(([, commands]) => commands.length > 1)\n .map(([event]) => event);\n return duplicated.length === 0\n ? []\n : [\n `${String(duplicated.length)} event(s) carry more than one registration of this hook ` +\n `(${duplicated.join(\", \")}), which would duplicate every span; re-run setup to collapse them`,\n ];\n};\n\nconst staleCommandNotes = (\n registrations: ReadonlyMap<string, readonly string[]>,\n command: string,\n): readonly string[] => {\n const stale = new Set<string>();\n for (const commands of registrations.values()) {\n for (const found of commands) {\n if (found !== command) {\n stale.add(found);\n }\n }\n }\n return [...stale]\n .sort()\n .map(\n (found) =>\n `registered command \"${found}\" differs from \"${command}\"; re-run setup to rewrite it in place`,\n );\n};\n\nconst runOneTarget = async (\n providerId: string,\n scope: RegistrationScope,\n request: RegistrationLifecycleRequest,\n command: string,\n): Promise<RegistrationOutcome> => {\n const support = findRegistrationSupport(providerId);\n const planner = findRegistrationPlanner(providerId);\n if (planner === undefined || support?.supported !== true) {\n return unsupportedOutcome(\n providerId,\n scope,\n support?.reason ?? `no registration planner is available for provider \"${providerId}\"`,\n );\n }\n\n const target = resolveTarget(providerId, scope, request);\n if (\"reason\" in target) {\n return unsupportedOutcome(providerId, scope, target.reason);\n }\n const { configPath, evidence } = target;\n\n const identifies = managedHookPredicate(\n request.managedMarker ?? DEFAULT_MANAGED_COMMAND_MARKER,\n );\n const events = request.events ?? planner.defaultEvents;\n const notes: string[] = [];\n if (providerId === CODEX_PROVIDER_ID) {\n const note = await codexFeatureNote(configPath);\n if (note !== undefined) {\n notes.push(note);\n }\n }\n\n const base = {\n providerId,\n scope,\n configPath,\n evidence,\n changes: [] as readonly HookDocumentChange[],\n conflicts: [] as readonly HookDocumentConflict[],\n };\n\n const work = async (): Promise<RegistrationOutcome> => {\n const state = await readState(configPath);\n if (\"problem\" in state) {\n return {\n ...base,\n status: state.status,\n changed: false,\n registeredEvents: [],\n missingEvents: [],\n notes,\n problems: [state.problem],\n };\n }\n\n const registrations = planner.read(state.existing, identifies);\n const registeredEvents = [...registrations.keys()].sort();\n\n if (request.action === \"diagnose\") {\n const missingEvents = events.filter((event) => !registrations.has(event));\n const problems = [...duplicateProblems(registrations)];\n if (registeredEvents.length > 0 && missingEvents.length > 0) {\n problems.push(\n `registered for ${String(registeredEvents.length)} event(s) but missing ` +\n `${String(missingEvents.length)} (${missingEvents.join(\", \")}); re-run setup`,\n );\n }\n return {\n ...base,\n status: registeredEvents.length === 0 ? \"absent\" : \"unchanged\",\n changed: false,\n registeredEvents,\n missingEvents,\n notes: [...notes, ...staleCommandNotes(registrations, command)],\n problems,\n };\n }\n\n const planned =\n request.action === \"setup\"\n ? planner.merge({\n ...(state.existing === undefined ? {} : { existing: state.existing }),\n command,\n events,\n ...(request.matcher === undefined ? {} : { matcher: request.matcher }),\n ...(request.timeoutSeconds === undefined\n ? {}\n : { timeoutSeconds: request.timeoutSeconds }),\n identifies,\n })\n : planner.remove({\n ...(state.existing === undefined ? {} : { existing: state.existing }),\n ...(request.events === undefined ? {} : { events: request.events }),\n identifies,\n });\n\n if (planned.conflicts.length > 0) {\n return {\n ...base,\n status: \"blocked\",\n changed: false,\n conflicts: planned.conflicts,\n registeredEvents,\n missingEvents: [],\n notes,\n problems: planned.conflicts.map(\n (conflict) =>\n `${path.basename(configPath)} has an unexpected shape at ${conflict.location}: ${conflict.detail}; it was left untouched`,\n ),\n };\n }\n\n if (request.action === \"uninstall\" && !state.existed) {\n return {\n ...base,\n status: \"absent\",\n changed: false,\n registeredEvents: [],\n missingEvents: [],\n notes: [...notes, `${path.basename(configPath)} does not exist; nothing to remove`],\n problems: [],\n };\n }\n\n if (!planned.changed) {\n return {\n ...base,\n status: request.action === \"uninstall\" && registeredEvents.length === 0 ? \"absent\" : \"unchanged\",\n changed: false,\n changes: planned.changes,\n registeredEvents,\n missingEvents: [],\n notes,\n problems: [],\n };\n }\n\n const format = state.existed ? state.format : DEFAULT_DOCUMENT_FORMAT;\n const contents = renderJsonDocument(planned.document, format);\n\n if (request.dryRun) {\n return {\n ...base,\n status: \"planned\",\n changed: true,\n changes: planned.changes,\n registeredEvents,\n missingEvents: [],\n notes,\n problems: [],\n plannedContents: contents,\n };\n }\n\n try {\n await writeDocumentAtomically(configPath, contents);\n } catch (thrown) {\n return {\n ...base,\n status: \"failed\",\n changed: false,\n changes: planned.changes,\n registeredEvents,\n missingEvents: [],\n notes,\n problems: [\n `could not write ${path.basename(configPath)} (${\n thrown instanceof Error ? thrown.name : typeof thrown\n })`,\n ],\n };\n }\n\n return {\n ...base,\n status: \"applied\",\n changed: true,\n changes: planned.changes,\n registeredEvents,\n missingEvents: [],\n notes,\n problems: [],\n };\n };\n\n // Only a run that will actually write takes the lock. The lock guards the\n // read-merge-write *sequence*; a reader never needs it, because every write\n // lands through an atomic rename and so is never observed half-applied. It\n // also matters that `diagnose` and `--dry-run` take no lock: creating the\n // lock file would mean creating `~/.claude/` to hold it, and a read-only\n // command that leaves directories behind in a home directory is a bug.\n const mutating = request.action !== \"diagnose\" && !request.dryRun;\n try {\n return mutating\n ? await withFileLock(configPath, { ...request.lock, clock: request.clock }, work)\n : await work();\n } catch (thrown) {\n return {\n ...base,\n status: \"failed\",\n changed: false,\n registeredEvents: [],\n missingEvents: [],\n notes,\n problems: [\n thrown instanceof Error\n ? `${path.basename(configPath)}: ${thrown.message}`\n : `${path.basename(configPath)}: the configuration file could not be locked`,\n ],\n };\n }\n};\n\n/**\n * Run one lifecycle action across every requested provider and scope.\n *\n * Targets are processed sequentially rather than concurrently: they are few, and\n * a serial run makes the output order deterministic and keeps two targets that\n * resolve to the same file (a `--settings-file` naming a shared document) from\n * contending for the same lock.\n */\nexport const runRegistrationLifecycle = async (\n request: RegistrationLifecycleRequest,\n): Promise<RegistrationReport> => {\n // Checked once, before any target is resolved and before any document is\n // opened. The marker decides what `uninstall` deletes, so an unsafe one is\n // refused for every target rather than per target — a partial run that\n // mangled the first provider's file and then refused the second would be the\n // worst of both outcomes.\n const markerRejection = checkManagedMarker(\n request.managedMarker ?? DEFAULT_MANAGED_COMMAND_MARKER,\n );\n if (markerRejection !== undefined) {\n const reason = `refusing to run ${request.action}: ${MANAGED_MARKER_REJECTION_DETAIL[markerRejection]}`;\n return {\n action: request.action,\n dryRun: request.dryRun,\n ok: false,\n hookCommand: request.command ?? defaultHookCommand(\"<provider>\"),\n outcomes: request.providerIds.flatMap((providerId) =>\n request.scopes.map((scope) => ({\n ...unsupportedOutcome(providerId, scope, reason),\n status: \"blocked\" as const,\n })),\n ),\n };\n }\n\n const outcomes: RegistrationOutcome[] = [];\n for (const providerId of request.providerIds) {\n const command = request.command ?? defaultHookCommand(providerId);\n for (const scope of request.scopes) {\n outcomes.push(await runOneTarget(providerId, scope, request, command));\n }\n }\n\n return {\n action: request.action,\n dryRun: request.dryRun,\n ok: outcomes.every((outcome) => outcome.problems.length === 0),\n hookCommand: request.command ?? defaultHookCommand(\"<provider>\"),\n outcomes,\n };\n};\n","import {\n DELIVERY_IDENTIFIER_SUMMARY,\n describeProviderCatalog,\n type ProviderCatalogEntry,\n} from \"../providers/defaults.js\";\nimport { findRegistrationSupport } from \"../install/index.js\";\nimport type { CliProvidersCommand } from \"./args.js\";\nimport { writeLine, type CliIo } from \"./context.js\";\n\nexport type ProviderListing = ProviderCatalogEntry & {\n /** Whether this repository can plan a hook registration for the provider. */\n readonly registrationSupported: boolean;\n readonly registrationNote: string;\n};\n\nexport const collectProviderListing = (\n command: CliProvidersCommand,\n): readonly ProviderListing[] =>\n describeProviderCatalog({ includeExperimental: command.includeExperimental }).map((entry) => {\n const support = findRegistrationSupport(entry.id);\n return {\n ...entry,\n registrationSupported: support?.supported ?? false,\n registrationNote: support?.reason ?? \"no registration planner is available\",\n };\n });\n\n/**\n * List adapters and what each one can actually observe.\n *\n * Capabilities are printed rather than inferred from the data because \"this\n * provider does not report cached tokens\" and \"this session used no cache\" look\n * identical downstream. A consumer needs to be able to tell them apart before\n * building a dashboard on the difference.\n */\nexport const runProvidersCommand = (command: CliProvidersCommand, io: CliIo): number => {\n const listing = collectProviderListing(command);\n\n if (command.json) {\n writeLine(io.stdout, JSON.stringify(listing, null, 2));\n return 0;\n }\n\n for (const entry of listing) {\n writeLine(io.stdout, `${entry.id} ${entry.title}`);\n writeLine(io.stdout, ` adapter version ${entry.version}`);\n writeLine(io.stdout, ` maturity ${entry.maturity}`);\n writeLine(io.stdout, ` lifecycle events ${entry.lifecycleEvents.join(\", \")}`);\n writeLine(\n io.stdout,\n ` usage temporality ${entry.usageTemporality}${\n entry.cumulativeUsageSeries === undefined\n ? \"\"\n : ` (series: ${entry.cumulativeUsageSeries})`\n }`,\n );\n writeLine(\n io.stdout,\n ` usage reported cached-input=${String(entry.reportsCachedInput)} ` +\n `cache-creation=${String(entry.reportsCacheCreation)} (${entry.cacheCreationAccounting}) ` +\n `reasoning=${String(entry.reportsReasoningOutput)} provider-total=${String(entry.reportsProviderTotal)} ` +\n `cost=${String(entry.reportsCost)}`,\n );\n writeLine(\n io.stdout,\n ` emits subagent=${String(entry.emitsSubagentEvents)} compaction=${String(\n entry.emitsCompactionEvents,\n )}`,\n );\n writeLine(io.stdout, ` stdout protocol ${entry.requiresHookResponse ? \"required\" : \"silent\"}`);\n writeLine(\n io.stdout,\n ` delivery dedup ${entry.deliveryIdentifier} — ${\n DELIVERY_IDENTIFIER_SUMMARY[entry.deliveryIdentifier]\n }`,\n );\n writeLine(\n io.stdout,\n ` registration ${entry.registrationSupported ? \"supported\" : \"unsupported\"} — ${entry.registrationNote}`,\n );\n if (entry.promotionGates.length > 0) {\n writeLine(io.stdout, ` promotion gates ${String(entry.promotionGates.length)} open:`);\n for (const gate of entry.promotionGates) {\n writeLine(io.stdout, ` - ${gate}`);\n }\n }\n writeLine(io.stdout, \"\");\n }\n return 0;\n};\n","import * as os from \"node:os\";\nimport * as path from \"node:path\";\n\nimport {\n PROVIDERS_WITH_VERIFIED_LOCATION,\n runRegistrationLifecycle,\n type RegistrationOutcome,\n type RegistrationReport,\n} from \"../install/index.js\";\nimport { createSystemClock } from \"../runtime/clock.js\";\nimport type { CliRegistrationCommand } from \"./args.js\";\nimport { writeLine, type CliIo } from \"./context.js\";\nimport { VERSION } from \"../version.js\";\n\n/**\n * `setup`, `diagnose`, and `uninstall`.\n *\n * The command layer only resolves *where* to look — provider ids, scopes, the\n * project root, the home directory — and formats the result. Every decision\n * about what a document should contain lives in `install/lifecycle.ts` and the\n * pure planners beneath it, so the human-readable and `--json` outputs describe\n * exactly the same plan and a dry run cannot diverge from a real one.\n *\n * Unlike `run`, these commands are ordinary programs: they exit non-zero when\n * something needs an operator's attention, so CI can gate on\n * `otel-hook diagnose --json`. Nothing here can affect a hook invocation.\n */\n\nconst resolveProjectDir = (command: CliRegistrationCommand, io: CliIo): string =>\n path.resolve(command.projectDir ?? io.env.PWD ?? process.cwd());\n\nconst resolveHomeDir = (command: CliRegistrationCommand, io: CliIo): string =>\n path.resolve(command.homeDir ?? io.homeDir ?? os.homedir());\n\nexport const collectRegistrationReport = async (\n command: CliRegistrationCommand,\n io: CliIo,\n): Promise<RegistrationReport> =>\n runRegistrationLifecycle({\n action: command.name,\n // A bare `diagnose` sweeps the providers this tool can locate by itself.\n // One whose path has to be supplied by hand (see\n // PROVIDERS_WITHOUT_VERIFIED_LOCATION) has nowhere to be swept, so naming\n // it would only ever produce a self-inflicted failure.\n providerIds:\n command.providerIds.length > 0 ? command.providerIds : PROVIDERS_WITH_VERIFIED_LOCATION,\n scopes: command.scopes,\n roots: { homeDir: resolveHomeDir(command, io), projectDir: resolveProjectDir(command, io) },\n ...(command.settingsFile === undefined ? {} : { configFile: command.settingsFile }),\n ...(command.hookCommand === undefined ? {} : { command: command.hookCommand }),\n ...(command.events === undefined ? {} : { events: command.events }),\n ...(command.matcher === undefined ? {} : { matcher: command.matcher }),\n ...(command.timeoutSeconds === undefined ? {} : { timeoutSeconds: command.timeoutSeconds }),\n ...(command.managedMarker === undefined ? {} : { managedMarker: command.managedMarker }),\n dryRun: command.dryRun,\n clock: createSystemClock(),\n });\n\nconst STATUS_LABEL: Readonly<Record<RegistrationOutcome[\"status\"], string>> = Object.freeze({\n planned: \"would change\",\n applied: \"changed \",\n unchanged: \"up to date \",\n absent: \"not present \",\n blocked: \"REFUSED \",\n unsupported: \"UNSUPPORTED \",\n failed: \"FAILED \",\n});\n\nconst writeOutcome = (io: CliIo, outcome: RegistrationOutcome, dryRun: boolean): void => {\n writeLine(\n io.stdout,\n `${STATUS_LABEL[outcome.status]} ${outcome.providerId} (${outcome.scope})` +\n (outcome.configPath === undefined ? \"\" : ` ${outcome.configPath}`),\n );\n\n const added = outcome.changes.filter((change) => change.action === \"added\").map((c) => c.event);\n const updated = outcome.changes.filter((change) => change.action === \"updated\").map((c) => c.event);\n const removed = outcome.changes.filter((change) => change.action === \"removed\").map((c) => c.event);\n if (added.length > 0) {\n writeLine(io.stdout, ` add ${added.join(\", \")}`);\n }\n if (updated.length > 0) {\n writeLine(io.stdout, ` update ${updated.join(\", \")}`);\n }\n if (removed.length > 0) {\n writeLine(io.stdout, ` remove ${removed.join(\", \")}`);\n }\n if (outcome.registeredEvents.length > 0 && outcome.changes.length === 0) {\n writeLine(io.stdout, ` events ${outcome.registeredEvents.join(\", \")}`);\n }\n for (const note of outcome.notes) {\n writeLine(io.stdout, ` note ${note}`);\n }\n for (const problem of outcome.problems) {\n writeLine(io.stdout, ` problem ${problem}`);\n }\n if (dryRun && outcome.plannedContents !== undefined) {\n writeLine(io.stdout, \" --- would write ---\");\n for (const line of outcome.plannedContents.replace(/\\r?\\n$/, \"\").split(/\\r?\\n/)) {\n writeLine(io.stdout, ` ${line}`);\n }\n writeLine(io.stdout, \" --- end ---\");\n }\n};\n\nexport const runRegistrationCommand = async (\n command: CliRegistrationCommand,\n io: CliIo,\n): Promise<number> => {\n const report = await collectRegistrationReport(command, io);\n\n if (command.json) {\n writeLine(io.stdout, JSON.stringify({ version: VERSION, ...report }, null, 2));\n return report.ok ? 0 : 1;\n }\n\n writeLine(\n io.stdout,\n `otel-hook ${VERSION} — ${report.action}${report.dryRun ? \" (dry run; nothing was written)\" : \"\"}`,\n );\n writeLine(io.stdout, \"\");\n for (const outcome of report.outcomes) {\n writeOutcome(io, outcome, report.dryRun);\n writeLine(io.stdout, \"\");\n }\n return report.ok ? 0 : 1;\n};\n","import * as path from \"node:path\";\n\nimport type { DetectionPolicy } from \"../config/schema.js\";\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport { createHookRuntime, type HookProcessOutcome } from \"../integration/hook-runtime.js\";\nimport { createPrivacyService } from \"../privacy/service.js\";\nimport type { ProviderAdapter, ProviderContext, ProviderDetectionInput } from \"../providers/adapter.js\";\nimport {\n createDefaultProviderRegistry,\n findProviderDescriptor,\n PROVIDER_DESCRIPTORS,\n} from \"../providers/defaults.js\";\nimport { createProviderRegistry, type ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"../runtime/clock.js\";\nimport { createDeterministicIdGenerator } from \"../runtime/ids.js\";\nimport type { Logger } from \"../runtime/ports.js\";\nimport type { CliRunCommand } from \"./args.js\";\nimport {\n createCliLogger,\n readIdentityFile,\n resolveCliConfig,\n resolveInstallationId,\n resolveStateRootDir,\n type CliIo,\n} from \"./context.js\";\nimport { autoDetectProvider } from \"./detection.js\";\nimport { providerVisibleEnvironment } from \"./environment-view.js\";\nimport { claimFromIdentityFile, claimFromIdentityFlags } from \"./identity.js\";\nimport { readBoundedJson } from \"./stdin.js\";\n\nconst MAX_LOGGED_DIAGNOSTICS = 16;\n\nconst logDiagnostics = (logger: Logger, diagnostics: readonly OtelHookErrorInfo[]): void => {\n for (const info of diagnostics.slice(0, MAX_LOGGED_DIAGNOSTICS)) {\n const fields = {\n \"error.code\": info.code,\n \"error.phase\": info.phase,\n \"error.posture\": info.posture,\n ...(info.details ?? {}),\n };\n if (info.severity === \"error\") {\n logger.error(info.message, fields);\n } else {\n logger.warn(info.message, fields);\n }\n }\n if (diagnostics.length > MAX_LOGGED_DIAGNOSTICS) {\n logger.warn(\"additional diagnostics were not logged\", {\n \"diagnostics.total\": diagnostics.length,\n \"diagnostics.logged\": MAX_LOGGED_DIAGNOSTICS,\n });\n }\n};\n\nconst logNotes = (logger: Logger, notes: readonly string[]): void => {\n for (const note of notes) {\n logger.warn(note, {});\n }\n};\n\ntype ProviderSelection =\n | {\n readonly status: \"selected\";\n /** Single-adapter registry: the choice is made here, once, and visibly. */\n readonly registry: ProviderRegistry;\n readonly detectionPolicy: DetectionPolicy;\n /**\n * Present only when the *caller* named the provider. Auto-detection never\n * sets it, so a detected provider's provenance keeps the adapter's own\n * confidence instead of being promoted to `exact` by our own guess.\n */\n readonly providerHint?: string;\n /** Namespace for state and spool directories. Never an identity. */\n readonly namespace: string;\n }\n | { readonly status: \"rejected\"; readonly reason: string };\n\n/**\n * Resolve `--provider <id>` to a single-adapter registry.\n *\n * The caller's assertion is the strongest signal available: it is the only path\n * that reaches `exact` confidence for a payload with no self-identifying\n * provider field, and it makes ambiguity structurally impossible. The minimum\n * confidence is lowered to `weak` for the same reason — once the caller has named\n * the provider, a payload that only weakly matches that provider's schema is\n * still that provider's payload, and the shape problem surfaces from `parse` as a\n * diagnostic instead of as a silent non-attribution.\n */\nconst selectExplicitProvider = (\n providerId: string,\n detectionPolicy: DetectionPolicy,\n logger: Logger,\n): ProviderSelection => {\n const descriptor = findProviderDescriptor(providerId);\n if (descriptor === undefined) {\n return {\n status: \"rejected\",\n reason: `unknown provider \"${providerId}\"; registered providers are ${PROVIDER_DESCRIPTORS.map(\n (entry) => entry.id,\n ).join(\", \")}`,\n };\n }\n if (descriptor.maturity === \"experimental\") {\n logger.warn(\"selected provider adapter is experimental\", {\n \"provider.id\": descriptor.id,\n \"provider.maturity\": descriptor.maturity,\n \"provider.promotion_gates\": descriptor.promotionGates.length,\n });\n }\n return {\n status: \"selected\",\n registry: createProviderRegistry([descriptor.createAdapter()]),\n detectionPolicy: {\n ...detectionPolicy,\n minimumConfidence: \"weak\",\n allowAmbiguousFallback: false,\n allowedProviderIds: [descriptor.id],\n },\n providerHint: descriptor.id,\n namespace: descriptor.id,\n };\n};\n\nconst selectDetectedProvider = (\n adapter: ProviderAdapter,\n detectionPolicy: DetectionPolicy,\n): ProviderSelection => ({\n status: \"selected\",\n registry: createProviderRegistry([adapter]),\n detectionPolicy: { ...detectionPolicy, allowedProviderIds: [adapter.id] },\n namespace: adapter.id,\n});\n\n/**\n * Process one hook payload.\n *\n * Always resolves to exit code 0. A telemetry hook that can fail its host will\n * be uninstalled, so every failure mode here — unreadable stdin, malformed JSON,\n * an unknown provider, an ambiguous detection, conflicting identity, an\n * unreachable collector, an unwritable state directory — becomes a stderr\n * diagnostic and an exit code of 0 (ADR 0004).\n */\nexport const runHookCommand = async (command: CliRunCommand, io: CliIo): Promise<number> => {\n const resolved = await resolveCliConfig(command.policy, io);\n const logger = createCliLogger(io, resolved.config.diagnostics.logLevel);\n logDiagnostics(logger, resolved.warnings);\n for (const note of resolved.notes) {\n logger.info(note, {});\n }\n if (resolved.usedDefaults) {\n logger.warn(\"configuration could not be resolved; falling back to defaults\", {});\n }\n\n const decoded = await readBoundedJson(io.stdin, command.maxInputBytes);\n if (decoded.status === \"error\") {\n logger.warn(decoded.detail, {\n \"input.code\": decoded.code,\n ...(decoded.byteLength === undefined ? {} : { \"input.byte_length\": decoded.byteLength }),\n });\n return 0;\n }\n\n const privacy = createPrivacyService(resolved.config.privacy);\n logNotes(logger, privacy.policyNotes);\n const clock = createSystemClock();\n const ids = createDeterministicIdGenerator();\n const environment = providerVisibleEnvironment(io.env, privacy);\n const providerContext: ProviderContext = {\n privacy,\n clock,\n ids,\n logger,\n limits: privacy.policy.limits,\n };\n\n let selection: ProviderSelection;\n if (command.providerId !== undefined) {\n selection = selectExplicitProvider(command.providerId, resolved.config.detection, logger);\n } else {\n const detectionInput: ProviderDetectionInput = {\n payload: decoded.value,\n transport: command.transport,\n environment,\n };\n const detected = autoDetectProvider(\n createDefaultProviderRegistry({\n includeExperimental: command.policy.includeExperimental ?? true,\n }),\n detectionInput,\n providerContext,\n resolved.config.detection,\n );\n if (detected.status === \"resolved\") {\n logger.info(\"provider auto-detected\", {\n \"provider.id\": detected.adapter.id,\n \"detection.confidence\": detected.confidence,\n });\n selection = selectDetectedProvider(detected.adapter, resolved.config.detection);\n } else if (detected.status === \"ambiguous\") {\n selection = {\n status: \"rejected\",\n reason:\n `auto-detection refused: ${String(detected.candidates.length)} adapters recognize this payload ` +\n `(${detected.candidates.map((candidate) => `${candidate.providerId}:${candidate.confidence}`).join(\", \")}). ` +\n \"Pass --provider <id> to state which one it is; nothing is attributed by guessing.\",\n };\n } else {\n selection = {\n status: \"rejected\",\n reason: `auto-detection refused: no registered adapter recognized this payload (${detected.reasons\n .join(\"; \")\n .slice(0, 240)}). Pass --provider <id> if you know which provider sent it.`,\n };\n }\n }\n\n if (selection.status === \"rejected\") {\n // No provider means no known stdout contract, so the response is silence —\n // the same posture as SILENT_HOOK_RESPONSE (ADR 0004).\n logger.error(selection.reason, {});\n return 0;\n }\n\n const identityClaims = [];\n if (command.identity.identityFile !== undefined) {\n const read = await readIdentityFile(path.resolve(command.identity.identityFile));\n if (\"error\" in read) {\n logDiagnostics(logger, [read.error]);\n } else {\n const fromFile = claimFromIdentityFile(\n read.value,\n path.basename(command.identity.identityFile),\n );\n logDiagnostics(logger, fromFile.errors);\n identityClaims.push(...fromFile.claims);\n }\n }\n const fromFlags = claimFromIdentityFlags(command.identity);\n logDiagnostics(logger, fromFlags.errors);\n identityClaims.push(...fromFlags.claims);\n\n const runtime = createHookRuntime({\n // Detection policy narrowed to the selected adapter; everything else is the\n // resolved configuration exactly as it stands.\n config: { ...resolved.config, detection: selection.detectionPolicy },\n registry: selection.registry,\n stateRootDir: resolveStateRootDir(command.policy, io),\n installationId: resolveInstallationId(command.policy, io),\n providerNamespace: selection.namespace,\n ...(Object.keys(command.policy.headers).length === 0\n ? {}\n : { headers: command.policy.headers }),\n clock,\n ids,\n logger,\n privacy,\n ...(command.policy.flushTimeoutMillis === undefined\n ? {}\n : { flushTimeoutMillis: command.policy.flushTimeoutMillis }),\n ...(command.policy.spoolDisabled === true ? { enableSpool: false } : {}),\n ...(command.requireCallbackId === true ? { requireCallbackId: true } : {}),\n ...(command.noDeriveCallbackId === true ? { deriveDeliveryIdentity: false } : {}),\n });\n\n let outcome: HookProcessOutcome | undefined;\n try {\n outcome = await runtime.process({\n payload: decoded.value,\n transport: command.transport,\n environment,\n ...(selection.providerHint === undefined ? {} : { providerHint: selection.providerHint }),\n ...(identityClaims.length === 0 ? {} : { identityClaims }),\n ...(Object.keys(command.consumerAttributes).length === 0\n ? {}\n : { consumerAttributes: command.consumerAttributes }),\n ...(command.callbackId === undefined\n ? {}\n : {\n delivery: {\n callbackId: command.callbackId,\n ...(command.callbackScope === undefined ? {} : { scope: command.callbackScope }),\n },\n }),\n });\n } catch (thrown) {\n // `process` is contractually non-throwing; this is the belt to its braces.\n logger.error(\"hook processing contained an unexpected failure\", {\n \"error.name\": thrown instanceof Error ? thrown.name : typeof thrown,\n });\n }\n\n if (outcome !== undefined) {\n const { hookResponse } = outcome.ingest;\n if (hookResponse.stderr !== undefined) {\n io.stderr.write(hookResponse.stderr);\n }\n // The only write to stdout in the whole run path, and only when the\n // provider's own protocol asks for one (ADR 0004).\n if (hookResponse.stdout !== undefined) {\n io.stdout.write(hookResponse.stdout);\n }\n logDiagnostics(logger, [...outcome.ingest.diagnostics, ...outcome.diagnostics]);\n logger.info(\"hook processed\", {\n \"provider.id\": outcome.ingest.providerId,\n \"attribution.outcome\": outcome.ingest.attribution,\n ...(outcome.ingest.attributionReason === undefined\n ? {}\n : { \"attribution.reason\": outcome.ingest.attributionReason }),\n \"events.emitted\": outcome.ingest.emitted,\n \"events.dropped\": outcome.ingest.dropped,\n \"delivery.duplicate\": outcome.duplicateDelivery,\n \"delivery.deduplicated\": outcome.delivery.deduplicated,\n ...(outcome.delivery.origin === undefined\n ? {}\n : { \"delivery.origin\": outcome.delivery.origin }),\n ...(outcome.delivery.outcome === undefined\n ? {}\n : { \"delivery.outcome\": outcome.delivery.outcome }),\n ...(outcome.delivery.reason === undefined\n ? {}\n : { \"delivery.unavailable_reason\": outcome.delivery.reason }),\n \"usage.rollups\": outcome.usageRollups.length,\n \"hook_response.contract\": hookResponse.contract,\n });\n }\n\n const shutdown = await runtime.shutdown();\n if (!shutdown.flushCompleted) {\n logger.warn(\"telemetry flush did not complete within its bound\", {\n \"shutdown.flush_timeout_millis\": shutdown.flushTimeoutMillis,\n });\n }\n return 0;\n};\n","import { randomBytes } from \"node:crypto\";\n\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateRecord, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { dedupKey, dedupScanPrefix, dedupScopeOf } from \"./keys.js\";\n\nexport type DedupCheckResult = {\n /** True when `callbackId` was already marked seen for this scope. */\n readonly duplicate: boolean;\n};\n\nexport type DedupCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Aged-out records the sweep deliberately kept because they are uncommitted\n * claims younger than the stale-claim window — a live process may still be\n * working on them.\n *\n * Reported rather than merely not-removed, because the two are indistinguishable\n * in `removed` and only one of them means \"retention is configured shorter than\n * this installation's own export budget\". Absent when nothing was retained.\n */\n readonly retainedInFlight?: number;\n};\n\n/**\n * What happened when a delivery tried to take ownership of a callback id.\n *\n * - `fresh`: nothing had this id. The caller owns it and must `commit`.\n * - `duplicate`: a previous delivery ran this callback to completion.\n * - `in-flight`: another delivery holds the id right now — a concurrent process,\n * or one that has not committed yet. Treated as a duplicate.\n * - `reclaimed`: a claim was abandoned long enough ago to be assumed dead, and\n * this delivery has taken it over. The caller owns it and must `commit`.\n */\nexport type DeliveryClaimOutcome = \"fresh\" | \"duplicate\" | \"in-flight\" | \"reclaimed\";\n\nexport type DeliveryClaimResult = {\n readonly outcome: DeliveryClaimOutcome;\n /** True for `duplicate` and `in-flight`: the caller must not export or account. */\n readonly duplicate: boolean;\n /** True for `fresh` and `reclaimed`: the caller owns the id and should commit. */\n readonly owned: boolean;\n /** How many deliveries have claimed this id, including this one. */\n readonly attempt: number;\n /** Age of the claim that was taken over. Present only for `reclaimed`. */\n readonly abandonedForMillis?: number;\n /**\n * Opaque proof that *this* delivery owns the claim. Present when `owned`.\n *\n * No floor computation can be proven exact, so the stale window may still be too\n * short for some real installation. Passing this back to {@link\n * CallbackDeduplicator.commit} turns that from a silent double-count into a\n * detected, reported condition: if a peer reclaimed the id in the meantime the\n * record carries a different token, and the commit refuses rather than\n * overwriting the peer's in-flight work.\n */\n readonly owner?: string;\n};\n\n/** Whether a commit actually took effect. */\nexport type DeliveryCommitResult = {\n readonly status: \"committed\" | \"superseded\";\n /** The attempt number recorded, for diagnostics. */\n readonly attempt: number;\n};\n\nexport type DeliveryClaimOptions = {\n /**\n * How long an uncommitted claim is respected before it is assumed to belong to\n * a process that died mid-flight. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n};\n\n/**\n * Delivery guard: suppresses a redelivered callback while local state is intact.\n *\n * Deliberately not described as \"exactly-once\". This records intent and completion\n * in a local store; the collector it protects is a separate system with no shared\n * transaction, so a process killed between an accepted export and `commit` leaves a\n * callback that will be exported again. What this guarantees is that a redelivery\n * seen by a *live* store is suppressed, and that a crash is recoverable rather than\n * either silently lost or permanently blocked.\n *\n * Coding-agent hosts redeliver callbacks — a retried hook invocation, a\n * duplicated event, a replayed transcript — and a deterministic identity makes\n * the replay recomputable, but something still has to remember which identities\n * have already been handled. This is that memory: a bounded, TTL-swept set of\n * seen ids per scope, independent of what the id actually names.\n *\n * Ownership is two-phase on purpose. `claim` records an intent before the caller\n * exports anything and `commit` records completion afterwards, so the window\n * where a crash could produce a double export does not exist: a second delivery\n * arriving in that window sees `in-flight` and stands down. The cost of that\n * choice is that a process killed between the two leaves an uncommitted claim,\n * which is why an old one is reclaimable rather than permanent — permanent would\n * turn every crash into silently lost telemetry.\n */\nexport interface CallbackDeduplicator {\n /**\n * Single-phase check: marks the id complete immediately and reports whether it\n * had been seen. Retained for callers that have nothing to protect between the\n * check and the side effect; `claim`/`commit` is the stronger guarantee.\n */\n checkAndMark(scope: string, callbackId: string): Promise<DedupCheckResult>;\n /** Take ownership of a callback id before acting on it. */\n claim(\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult>;\n /**\n * Record that a claimed callback ran to completion.\n *\n * `owner` is the token {@link DeliveryClaimResult.owner} handed out. Supplied and\n * matching, the claim completes. Supplied and *not* matching, the claim has been\n * reclaimed by a peer while this delivery was still working, and the commit is\n * refused — reported as `\"superseded\"` so the caller can say so instead of\n * silently marking a callback handled that somebody else is mid-flight on.\n */\n commit(scope: string, callbackId: string, owner?: string): Promise<DeliveryCommitResult>;\n /**\n * Give up a claim without completing it, so the next delivery of the same\n * callback is treated as fresh instead of waiting out the stale window.\n */\n release(scope: string, callbackId: string): Promise<void>;\n /**\n * Drop dedup records older than `maxAgeMillis`.\n *\n * An uncommitted claim is held back until it is also older than\n * `staleClaimMillis`, whatever the retention says. Retention is an operator's\n * answer to \"how long should a handled callback stay recognizable\"; the stale\n * window is a statement about how long one process's own work can take. Deleting\n * a claim inside that window would hand the callback to a concurrent delivery as\n * *fresh* while the holder is still exporting it — a retention setting silently\n * converting suppression into a double export, which is the opposite of what\n * tightening retention looks like it does.\n */\n cleanup(\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n /** Floor on how long an uncommitted claim survives. Default 60,000ms. */\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult>;\n}\n\nexport type CallbackDeduplicatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\ntype DedupState = \"claimed\" | \"completed\";\n\n/**\n * Read the recorded state of a dedup record.\n *\n * A record written by an older release carries only `seenAt`, which meant\n * \"handled\". Absent a `state` field it is therefore read as `completed`, so an\n * upgrade never resurrects a callback the previous version had already exported.\n */\nconst stateOf = (record: StateRecord | undefined): DedupState | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const declared = record.value.attributes.state;\n if (declared === \"claimed\" || declared === \"completed\") {\n return declared;\n }\n return \"completed\";\n};\n\nconst attemptOf = (record: StateRecord | undefined): number => {\n if (record?.value.kind !== \"attributes\") {\n return 0;\n }\n const attempt = record.value.attributes.attempt;\n return typeof attempt === \"number\" && Number.isInteger(attempt) && attempt > 0 ? attempt : 1;\n};\n\nconst ownerOf = (record: StateRecord | undefined): string | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const owner = record.value.attributes.owner;\n return typeof owner === \"string\" && owner.length > 0 ? owner : undefined;\n};\n\nconst newOwnerToken = (): string => randomBytes(12).toString(\"hex\");\n\nconst claimedAtOf = (record: StateRecord | undefined): number | undefined => {\n if (record?.value.kind !== \"attributes\") {\n return undefined;\n }\n const claimedAt = record.value.attributes.claimedAt;\n return typeof claimedAt === \"number\" ? claimedAt : record.updatedAt;\n};\n\nexport const createCallbackDeduplicator = (\n deps: CallbackDeduplicatorDependencies,\n): CallbackDeduplicator => {\n const { stateStore, clock } = deps;\n\n const write = (key: string, attributes: Attributes): Promise<unknown> =>\n stateStore.write(key, { kind: \"attributes\", attributes });\n\n const checkAndMark = (scope: string, callbackId: string): Promise<DedupCheckResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DedupCheckResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n if (existing?.value.kind === \"attributes\") {\n return { duplicate: true };\n }\n const now = clock.now();\n await write(key, {\n state: \"completed\",\n attempt: 1,\n claimedAt: now,\n seenAt: now,\n owner: newOwnerToken(),\n });\n return { duplicate: false };\n });\n\n const claim = (\n scope: string,\n callbackId: string,\n options?: DeliveryClaimOptions,\n ): Promise<DeliveryClaimResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryClaimResult> => {\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const state = stateOf(existing);\n const now = clock.now();\n\n if (state === \"completed\") {\n return { outcome: \"duplicate\", duplicate: true, owned: false, attempt: attemptOf(existing) };\n }\n\n if (state === \"claimed\") {\n const claimedAt = claimedAtOf(existing) ?? now;\n const age = now - claimedAt;\n if (age <= staleClaimMillis) {\n return {\n outcome: \"in-flight\",\n duplicate: true,\n owned: false,\n attempt: attemptOf(existing),\n };\n }\n const attempt = attemptOf(existing) + 1;\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt, claimedAt: now, owner });\n return {\n outcome: \"reclaimed\",\n duplicate: false,\n owned: true,\n attempt,\n abandonedForMillis: age,\n owner,\n };\n }\n\n const owner = newOwnerToken();\n await write(key, { state: \"claimed\", attempt: 1, claimedAt: now, owner });\n return { outcome: \"fresh\", duplicate: false, owned: true, attempt: 1, owner };\n });\n\n const commit = (\n scope: string,\n callbackId: string,\n owner?: string,\n ): Promise<DeliveryCommitResult> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<DeliveryCommitResult> => {\n const key = dedupKey(scope, callbackId);\n const existing = await stateStore.read(key);\n const now = clock.now();\n const attempt = Math.max(attemptOf(existing), 1);\n\n const recordedOwner = ownerOf(existing);\n if (owner !== undefined && recordedOwner !== undefined && recordedOwner !== owner) {\n // A peer reclaimed this id while we were still working, which means the\n // stale window was shorter than this installation's real worst case.\n // Completing it now would tell that peer's delivery to stand down after it\n // has already exported. Refusing is the honest answer, and being able to\n // say so is the point of the token: no floor computation can be proven\n // exact, so the failure has to be detectable rather than merely unlikely.\n return { status: \"superseded\", attempt };\n }\n\n await write(key, {\n state: \"completed\",\n attempt,\n claimedAt: claimedAtOf(existing) ?? now,\n completedAt: now,\n seenAt: now,\n ...(recordedOwner === undefined ? {} : { owner: recordedOwner }),\n });\n return { status: \"committed\", attempt };\n });\n\n const release = (scope: string, callbackId: string): Promise<void> =>\n withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n const key = dedupKey(scope, callbackId);\n // Only an uncommitted claim is droppable: releasing a completed record\n // would re-open a callback whose telemetry has already been exported.\n if (stateOf(await stateStore.read(key)) === \"claimed\") {\n await stateStore.delete(key);\n }\n });\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: {\n readonly maxEntries?: number;\n readonly sessionId?: string;\n readonly staleClaimMillis?: number;\n },\n ): Promise<DedupCleanupResult> => {\n const keys = await stateStore.keys(dedupScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const staleClaimMillis = options?.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let retainedInFlight = 0;\n\n /** Whether this record may be dropped, counting a live claim as it goes. */\n const isDroppable = (record: StateRecord | undefined, count: boolean): boolean => {\n if (record === undefined || now - record.updatedAt <= maxAgeMillis) {\n return false;\n }\n if (stateOf(record) === \"claimed\") {\n const age = now - (claimedAtOf(record) ?? record.updatedAt);\n if (age <= staleClaimMillis) {\n if (count) {\n retainedInFlight += 1;\n }\n return false;\n }\n }\n return true;\n };\n\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n\n // Unlocked first pass. It decides only whether this key is worth locking for,\n // which is what keeps a sweep of a mostly-live store from paying a lock\n // acquisition per record: the common answer is \"not aged out, leave it\".\n if (!isDroppable(await stateStore.read(key), true)) {\n continue;\n }\n\n const scope = dedupScopeOf(key);\n if (scope === undefined) {\n // A key from a previous layout version: unreachable by any current read, so\n // there is no claim to race and no scope to lock on.\n await stateStore.delete(key);\n removed += 1;\n continue;\n }\n\n // Locked second pass, because a peer's `claim` takes this same lock and may\n // have refreshed the record since the first read. Deciding once, outside the\n // lock, would let a sweep delete a claim written microseconds earlier — and the\n // concurrent redelivery would then read `fresh` and export a second time.\n await withOptionalSessionLock(stateStore, scope, async (): Promise<void> => {\n if (!isDroppable(await stateStore.read(key), false)) {\n return;\n }\n await stateStore.delete(key);\n removed += 1;\n });\n }\n\n return {\n removed,\n scanned,\n ...(retainedInFlight === 0 ? {} : { retainedInFlight }),\n };\n };\n\n return { checkAndMark, claim, commit, release, cleanup };\n};\n","/**\n * State key namespaces for lifecycle bookkeeping.\n *\n * Prefixed with `lifecycle:` so these keys can never collide with the\n * orchestrator's own `sequence:<sessionId>` and `usage:<sessionId>:...` keys\n * in the same {@link StateStore}, even though both share the store.\n *\n * Two properties are load-bearing here, because the store hashes a *whole\n * logical key* into one record: keys must be unambiguous, and a key space whose\n * layout changes must not be readable under its old meaning.\n */\nexport const LIFECYCLE_PREFIX = \"lifecycle\";\n\n/**\n * Layout version of the span key space.\n *\n * Bumped when the *segments* change, not when a record's contents do — that is\n * {@link SPAN_RECORD_VERSION}'s job. Version 2 inserted the provider segment,\n * so a v1 key must never be reachable: reading one would pair a span across\n * providers, which is exactly the attribution guess this library refuses.\n */\nexport const SPAN_KEY_VERSION = 2;\n\n/**\n * Layout version of the dedup key space.\n *\n * Version 2 re-scoped these keys from a session id to a delivery scope. The two\n * spaces are not interchangeable — a v1 key found under a v2 read would suppress\n * an unrelated callback — so the version segment keeps them disjoint.\n */\nexport const DEDUP_KEY_VERSION = 2;\n\n/**\n * Make a variable segment unambiguous within a `:`-delimited key.\n *\n * Without this, `dedupKey(\"a:b\", \"c\")` and `dedupKey(\"a\", \"b:c\")` produce the\n * identical logical key, and the store hashes both to one record — so one\n * delivery silently suppresses an unrelated one. That is reachable input, not a\n * theoretical one: `--callback-scope` is host-supplied, and a provider's session\n * or tool-call id is not required to avoid a colon.\n *\n * `%` is escaped first so the encoding stays injective, which makes this a true\n * bijection on segments rather than a lossy scrub. A segment containing neither\n * character encodes to itself, so keys already on disk keep their identity and\n * no cumulative baseline is reset by adopting this.\n */\nconst encodeSegment = (segment: string): string =>\n segment.replaceAll(\"%\", \"%25\").replaceAll(\":\", \"%3A\");\n\n/**\n * Session first, then provider: the janitor sweeps a whole session by prefix,\n * so the session segment has to lead. The provider segment below it is what\n * makes cross-provider pairing impossible by construction rather than only by\n * the runtime check in the span correlator.\n */\nexport const spanKey = (\n sessionId: string,\n providerId: string,\n scope: string,\n scopeKey: string,\n): string =>\n `${spanScanPrefix(sessionId)}${encodeSegment(providerId)}:${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\n/**\n * The session-scoped prefix names one layout version; the bare prefix names\n * every one of them. That asymmetry is deliberate: a sweep must be able to\n * reclaim records written by a previous version, which a versioned prefix could\n * never match, while a *read* must never reach across a layout change.\n */\nexport const spanScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:span:`\n : `${LIFECYCLE_PREFIX}:span:v${String(SPAN_KEY_VERSION)}:${encodeSegment(sessionId)}:`;\n\n/**\n * Dedup keys are scoped by a *delivery scope*, not by a session id.\n *\n * A host-supplied delivery id carries its own namespace, and a provider-derived\n * one is scoped by a digest of provider, installation, and session — so neither\n * is a session id, and neither can be found by scanning for one.\n */\nexport const dedupKey = (scope: string, callbackId: string): string =>\n `${dedupScanPrefix(scope)}${encodeSegment(callbackId)}`;\n\nexport const dedupScanPrefix = (scope?: string): string =>\n scope === undefined\n ? `${LIFECYCLE_PREFIX}:dedup:`\n : `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:${encodeSegment(scope)}:`;\n\nconst decodeSegment = (segment: string): string =>\n segment.replaceAll(\"%3A\", \":\").replaceAll(\"%25\", \"%\");\n\n/**\n * Recover the delivery scope a dedup key belongs to.\n *\n * Needed by the sweep and nothing else. A sweep enumerates keys rather than being\n * handed a scope, but deleting a dedup record is a read-modify-write against the\n * same record a concurrent `claim` is deciding on — so the sweep has to take the\n * same per-scope lock, and to take it, it has to know the scope. Recovering it\n * from the key is safe precisely because {@link encodeSegment} is injective.\n *\n * Returns `undefined` for a key from a previous layout version, which no lock\n * protects because no current read can reach it.\n */\nexport const dedupScopeOf = (key: string): string | undefined => {\n const prefix = `${LIFECYCLE_PREFIX}:dedup:v${String(DEDUP_KEY_VERSION)}:`;\n if (!key.startsWith(prefix)) {\n return undefined;\n }\n // Exactly two segments follow the prefix, and neither can contain a raw `:`,\n // so the first `:` after the prefix is unambiguously the boundary.\n const rest = key.slice(prefix.length);\n const boundary = rest.indexOf(\":\");\n return boundary <= 0 ? undefined : decodeSegment(rest.slice(0, boundary));\n};\n\n/**\n * Usage rollup keys are escaped but deliberately *not* versioned: their layout\n * has not changed, and a version segment would orphan every cumulative token\n * baseline on disk — resetting usage accounting to fix a bug that escaping\n * already fixes.\n */\nexport const rollupUsageKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupEpochKey = (sessionId: string, scope: string, scopeKey: string): string =>\n `${rollupEpochScanPrefix(sessionId)}${encodeSegment(scope)}:${encodeSegment(scopeKey)}`;\n\nexport const rollupScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:usage:`\n : `${LIFECYCLE_PREFIX}:usage:${encodeSegment(sessionId)}:`;\n\nexport const rollupEpochScanPrefix = (sessionId?: string): string =>\n sessionId === undefined\n ? `${LIFECYCLE_PREFIX}:epoch:`\n : `${LIFECYCLE_PREFIX}:epoch:${encodeSegment(sessionId)}:`;\n","import type { CallbackDeduplicator } from \"./dedup.js\";\nimport type { SpanCorrelator } from \"./span-correlator.js\";\nimport type { UsageAccumulator } from \"./usage-accumulator.js\";\n\nconst DEFAULT_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_MAX_ENTRIES_PER_COMPONENT = 1_000;\n\nexport type LifecycleJanitorOptions = {\n readonly spanCorrelator?: SpanCorrelator;\n readonly deduplicator?: CallbackDeduplicator;\n readonly usageAccumulator?: UsageAccumulator;\n readonly spanMaxAgeMillis?: number;\n readonly dedupMaxAgeMillis?: number;\n /**\n * Floor on how long an uncommitted delivery claim survives the sweep, whatever\n * `dedupMaxAgeMillis` says.\n *\n * Passed through rather than left to the deduplicator's default so it can be the\n * *effective* window the runtime computed, which is raised from the requested one\n * to cover a process's whole export budget. A sweep using a smaller number than\n * the claim path uses would delete claims the claim path still considers live.\n */\n readonly dedupStaleClaimMillis?: number;\n readonly usageMaxAgeMillis?: number;\n /** Caps how many keys any single component scans per sweep. */\n readonly maxEntriesPerComponent?: number;\n};\n\nexport type LifecycleSweepStats = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Span records dropped with a start and no end — spans that were never\n * exported. Reported only by the span sweep; see `SpanCleanupResult`.\n */\n readonly expiredOpen?: number;\n /**\n * Aged-out records kept back because they are delivery claims a live process may\n * still hold. Reported only by the dedup sweep; see `DedupCleanupResult`.\n */\n readonly retainedInFlight?: number;\n};\n\nexport type LifecycleCleanupReport = {\n readonly span?: LifecycleSweepStats;\n readonly dedup?: LifecycleSweepStats;\n readonly usage?: LifecycleSweepStats;\n};\n\n/**\n * Fans a single bounded cleanup pass out across whichever lifecycle\n * components are configured.\n *\n * Each component already bounds its own sweep (`maxEntries`); this exists so\n * a caller — a CLI subcommand, a periodic timer, an opportunistic call at the\n * end of `flush()` — can run \"the\" cleanup without wiring each component by\n * hand, and so the bound is enforced uniformly rather than per call site.\n */\nexport interface LifecycleJanitor {\n runOnce(sessionId?: string): Promise<LifecycleCleanupReport>;\n}\n\nexport const createLifecycleJanitor = (options: LifecycleJanitorOptions): LifecycleJanitor => {\n const maxEntries = options.maxEntriesPerComponent ?? DEFAULT_MAX_ENTRIES_PER_COMPONENT;\n const spanMaxAge = options.spanMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const dedupMaxAge = options.dedupMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n const usageMaxAge = options.usageMaxAgeMillis ?? DEFAULT_MAX_AGE_MILLIS;\n\n const runOnce = async (sessionId?: string): Promise<LifecycleCleanupReport> => {\n const scope = { maxEntries, ...(sessionId === undefined ? {} : { sessionId }) };\n const [span, dedup, usage] = await Promise.all([\n options.spanCorrelator?.cleanup(spanMaxAge, scope),\n // Deduplication is deliberately swept across every scope rather than the\n // ending session's: a delivery scope is a host-chosen namespace or a\n // digest of provider/installation/session, never a session id, so scoping\n // this sweep by `sessionId` would match nothing and let records accumulate\n // forever. The sweep is TTL-driven and still bounded by `maxEntries`.\n options.deduplicator?.cleanup(dedupMaxAge, {\n maxEntries,\n ...(options.dedupStaleClaimMillis === undefined\n ? {}\n : { staleClaimMillis: options.dedupStaleClaimMillis }),\n }),\n options.usageAccumulator?.cleanup(usageMaxAge, scope),\n ]);\n return {\n ...(span === undefined ? {} : { span }),\n ...(dedup === undefined ? {} : { dedup }),\n ...(usage === undefined ? {} : { usage }),\n };\n };\n\n return { runOnce };\n};\n","import type { Attributes as SpanAttributes } from \"@opentelemetry/api\";\n\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n MAX_ATTRIBUTE_STRING_LENGTH,\n MAX_IDENTIFIER_LENGTH,\n type Attributes,\n} from \"../model/primitives.js\";\nimport type { Clock, StateStore, StateValue } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport {\n MAX_RECOVERED_START_ATTRIBUTES,\n parentScopeRefOf,\n spanScopeRefOf,\n startOnlySpanAttributes,\n type SpanCorrelation,\n type SpanFamily,\n type SpanOrphanClassification,\n type SpanScopeRef,\n} from \"../telemetry/semconv.js\";\nimport { spanKey, spanScanPrefix } from \"./keys.js\";\n\n/** Correlation scopes that pair a `*.start` event with a later `*.end` event. */\nexport type LifecycleScope = SpanFamily;\n\n/**\n * Shape version of a persisted span record.\n *\n * A record written under a different version is discarded on read rather than\n * interpreted: guessing at an older layout is exactly the kind of silent\n * mis-attribution this library refuses to do. See `docs/state-retention.md`.\n */\nexport const SPAN_RECORD_VERSION = 2;\n\n/** Facts about a span recovered from, or written to, persisted state. */\nexport type SpanCorrelationFacts = {\n readonly startedAt?: number;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanStartInput = {\n readonly sessionId: string;\n /** Attribution boundary: a scope recorded by one provider never pairs with another's. */\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n /** The canonical event id of the start event; used to detect redelivery. */\n readonly eventId: string;\n readonly occurredAt: number;\n /** Where this span hangs, so an end-only process reparents it identically. */\n readonly parent?: SpanScopeRef;\n /** Attributes only the start edge knows; carried forward to the end-side span. */\n readonly attributes?: SpanAttributes;\n};\n\nexport type SpanEndInput = {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n readonly eventId: string;\n readonly occurredAt: number;\n};\n\nexport type SpanStartResult =\n | { readonly status: \"recorded\"; readonly facts: SpanCorrelationFacts }\n /** The same start (by event id) was already recorded; state is unchanged. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n /**\n * The record was completed, but an OTLP record for this scope has already been\n * published under its span id — so this edge must not export one.\n */\n | { readonly status: \"published\"; readonly facts: SpanCorrelationFacts }\n /** A different provider owns this scope key in this session; nothing was written. */\n | { readonly status: \"conflict\"; readonly reason: \"provider-mismatch\" };\n\n/** Why an end could not be paired with a recorded start. */\nexport type SpanEndOrphanReason =\n | \"no-start-recorded\"\n | \"start-expired\"\n | \"already-closed\"\n | \"provider-mismatch\"\n | \"state-incompatible\"\n | \"state-corrupt\";\n\nexport type SpanEndResult =\n | {\n readonly status: \"matched\";\n readonly startedAt: number;\n readonly durationMillis: number;\n readonly facts: SpanCorrelationFacts;\n }\n /** This exact end (by event id) was already applied; the same facts are replayed. */\n | { readonly status: \"duplicate\"; readonly facts: SpanCorrelationFacts }\n | {\n readonly status: \"orphaned\";\n readonly reason: SpanEndOrphanReason;\n readonly facts: SpanCorrelationFacts;\n };\n\nexport type SpanCleanupResult = {\n readonly removed: number;\n readonly scanned: number;\n /**\n * Records dropped that held a start and never received an end.\n *\n * These are the spans that will never be exported at all: the end edge is what\n * emits a lifecycle span, so a scope whose end never arrives — a session the\n * host killed, a tool call that outlived the retention window — produces no\n * OTLP record. That is the standard OpenTelemetry outcome for a span that never\n * ends, and it is deliberately not papered over with a synthetic end time,\n * because a fabricated duration is a wrong measurement rather than a missing\n * one. Counting them keeps the cost visible: a non-zero number here means real\n * activity went unreported, which is a signal about the host or the retention\n * window rather than noise. See `docs/state-retention.md`.\n */\n readonly expiredOpen: number;\n};\n\n/**\n * Cross-invocation start/end correlation for session, generation, tool, and\n * subagent scopes.\n *\n * A coding-agent hook fires once per lifecycle edge, usually as a separate\n * short-lived process for the start and for the end. This records an open span\n * in the shared state store so the end side can report a real start time,\n * duration, parent, and start-only attributes even though its process has no\n * memory of the start — and so a redelivered start or end (an at-least-once\n * host retry) re-exports an identical span instead of being double-counted.\n *\n * ## What it refuses to do\n *\n * - **Pair across sessions.** The state key is session-scoped, so two sessions\n * cannot see each other's open spans.\n * - **Pair across providers.** The key is provider-scoped *and* the record\n * carries the provider that wrote it, so a mismatch is reported rather than\n * guessed at — the same defense in depth the durable spool uses.\n * - **Trust a stale start.** A start older than `maxStartAgeMillis` when its end\n * arrives is dropped and classified `start-expired`, rather than reporting a\n * duration that really measures a machine suspend or a reused id.\n * - **Interpret a record it does not understand.** A corrupt or wrong-version\n * record is deleted and classified, never partially read.\n */\nexport interface SpanCorrelator {\n recordStart(input: SpanStartInput): Promise<SpanStartResult>;\n recordEnd(input: SpanEndInput): Promise<SpanEndResult>;\n /**\n * Records every lifecycle edge in a batch and reports what the exported spans\n * should say. Never rejects: a state failure degrades one scope to\n * `state-unavailable` rather than losing the batch (fail-open telemetry).\n */\n correlateBatch(events: readonly CanonicalEvent[]): Promise<readonly SpanCorrelation[]>;\n /** Bounded sweep: drops spans untouched for longer than `maxAgeMillis`. */\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult>;\n}\n\nexport type SpanCorrelatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n /**\n * A recorded start older than this when its end arrives is not trusted.\n * Default 24 hours, matching the janitor's retention window.\n */\n readonly maxStartAgeMillis?: number;\n};\n\nconst DEFAULT_MAX_START_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst ATTRIBUTE_PREFIX = \"a:\";\n\ntype SpanRecord = {\n readonly providerId: string;\n readonly startEventId?: string;\n readonly startedAt?: number;\n readonly endEventId?: string;\n readonly endedAt?: number;\n readonly parent?: SpanScopeRef;\n readonly attributes?: SpanAttributes;\n /**\n * True once an OTLP record has been produced for this scope under its derived\n * span id.\n *\n * Needed for the ordering nobody controls: the end edge can be mapped before\n * the start edge, and then the end has already exported an orphan carrying the\n * scope's canonical span id. Without this flag the late start would look like\n * the benign \"end raced ahead\" case and export a *second* record with that same\n * id — the duplicate the whole defer strategy exists to avoid. So the flag turns\n * \"was this scope already published?\" into a fact on disk rather than an\n * assumption about arrival order.\n */\n readonly exported?: boolean;\n};\n\ntype DecodedRecord =\n | { readonly kind: \"absent\" }\n | { readonly kind: \"incompatible\" }\n | { readonly kind: \"corrupt\" }\n | { readonly kind: \"present\"; readonly record: SpanRecord };\n\nconst SPAN_FAMILIES: readonly SpanFamily[] = [\"session\", \"generation\", \"tool\", \"subagent\"];\n\nconst isSpanFamily = (value: unknown): value is SpanFamily =>\n typeof value === \"string\" && (SPAN_FAMILIES as readonly string[]).includes(value);\n\nconst optionalNumber = (value: unknown): number | undefined =>\n typeof value === \"number\" && Number.isFinite(value) ? value : undefined;\n\nconst optionalString = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.length > 0 ? value : undefined;\n\n/**\n * Persisted attributes are flattened under a prefix rather than nested: the\n * state schema admits only flat primitives, which is what keeps a provider\n * payload from ever being smuggled through the state store.\n */\nconst encodeAttributes = (attributes: SpanAttributes | undefined): Attributes => {\n const encoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes ?? {})) {\n if (count >= MAX_RECOVERED_START_ATTRIBUTES) {\n break;\n }\n const encodedKey = `${ATTRIBUTE_PREFIX}${key}`;\n if (encodedKey.length > MAX_IDENTIFIER_LENGTH) {\n continue;\n }\n if (typeof value === \"string\") {\n encoded[encodedKey] = value.slice(0, MAX_ATTRIBUTE_STRING_LENGTH);\n } else if (typeof value === \"number\" && Number.isFinite(value)) {\n encoded[encodedKey] = value;\n } else if (typeof value === \"boolean\") {\n encoded[encodedKey] = value;\n } else {\n continue;\n }\n count += 1;\n }\n return encoded;\n};\n\nconst decodeAttributes = (attributes: Attributes): SpanAttributes | undefined => {\n const decoded: Record<string, string | number | boolean> = {};\n let count = 0;\n for (const [key, value] of Object.entries(attributes)) {\n if (!key.startsWith(ATTRIBUTE_PREFIX) || count >= MAX_RECOVERED_START_ATTRIBUTES) {\n continue;\n }\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\") {\n decoded[key.slice(ATTRIBUTE_PREFIX.length)] = value;\n count += 1;\n }\n }\n return count === 0 ? undefined : decoded;\n};\n\nconst encodeRecord = (record: SpanRecord): StateValue => ({\n kind: \"attributes\",\n attributes: {\n v: SPAN_RECORD_VERSION,\n providerId: record.providerId,\n ...(record.startEventId === undefined ? {} : { startEventId: record.startEventId }),\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endEventId === undefined ? {} : { endEventId: record.endEventId }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.exported === true ? { exported: true } : {}),\n ...(record.parent === undefined\n ? {}\n : { parentFamily: record.parent.family, parentScopeKey: record.parent.scopeKey }),\n ...encodeAttributes(record.attributes),\n },\n});\n\nconst decodeRecord = (attributes: Attributes): DecodedRecord => {\n if (attributes[\"v\"] !== SPAN_RECORD_VERSION) {\n return { kind: \"incompatible\" };\n }\n const providerId = optionalString(attributes[\"providerId\"]);\n if (providerId === undefined) {\n return { kind: \"corrupt\" };\n }\n // A half-written edge (a timestamp with no event id, or the reverse) is not\n // an edge we can reason about; the record is refused rather than completed\n // with an invented half.\n const startedAt = optionalNumber(attributes[\"startedAt\"]);\n const startEventId = optionalString(attributes[\"startEventId\"]);\n if ((startedAt === undefined) !== (startEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const endedAt = optionalNumber(attributes[\"endedAt\"]);\n const endEventId = optionalString(attributes[\"endEventId\"]);\n if ((endedAt === undefined) !== (endEventId === undefined)) {\n return { kind: \"corrupt\" };\n }\n const exported = attributes[\"exported\"] === true;\n const parentFamily = attributes[\"parentFamily\"];\n const parentScopeKey = optionalString(attributes[\"parentScopeKey\"]);\n const parent =\n isSpanFamily(parentFamily) && parentScopeKey !== undefined\n ? { family: parentFamily, scopeKey: parentScopeKey }\n : undefined;\n const decodedAttributes = decodeAttributes(attributes);\n return {\n kind: \"present\",\n record: {\n providerId,\n ...(startEventId === undefined ? {} : { startEventId }),\n ...(startedAt === undefined ? {} : { startedAt }),\n ...(endEventId === undefined ? {} : { endEventId }),\n ...(endedAt === undefined ? {} : { endedAt }),\n ...(parent === undefined ? {} : { parent }),\n ...(exported ? { exported: true } : {}),\n ...(decodedAttributes === undefined ? {} : { attributes: decodedAttributes }),\n },\n };\n};\n\nconst factsOf = (record: SpanRecord): SpanCorrelationFacts => ({\n ...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),\n ...(record.endedAt === undefined ? {} : { endedAt: record.endedAt }),\n ...(record.parent === undefined ? {} : { parent: record.parent }),\n ...(record.attributes === undefined ? {} : { attributes: record.attributes }),\n});\n\n/**\n * Persisted facts speak in event time (`startedAt`); a span speaks in the\n * milliseconds it is stamped with. Translated in one place so the two\n * vocabularies cannot silently drift apart.\n */\nconst correlationTimesOf = (\n facts: SpanCorrelationFacts,\n options: { readonly withStart: boolean } = { withStart: true },\n): Pick<SpanCorrelation, \"startMillis\" | \"endMillis\" | \"parent\" | \"attributes\"> => ({\n ...(facts.startedAt === undefined || !options.withStart ? {} : { startMillis: facts.startedAt }),\n ...(facts.endedAt === undefined ? {} : { endMillis: facts.endedAt }),\n ...(facts.parent === undefined ? {} : { parent: facts.parent }),\n ...(facts.attributes === undefined ? {} : { attributes: facts.attributes }),\n});\n\nconst orphanClassificationOf = (reason: SpanEndOrphanReason): SpanOrphanClassification => {\n switch (reason) {\n case \"no-start-recorded\":\n return \"missing-start\";\n case \"start-expired\":\n return \"expired-start\";\n case \"already-closed\":\n return \"already-closed\";\n case \"provider-mismatch\":\n return \"provider-mismatch\";\n case \"state-incompatible\":\n return \"state-incompatible\";\n case \"state-corrupt\":\n return \"state-corrupt\";\n }\n};\n\ntype BatchGroup = {\n readonly providerId: string;\n readonly sessionId: string;\n readonly ref: SpanScopeRef;\n start?: CanonicalEvent;\n end?: CanonicalEvent;\n};\n\nexport const createSpanCorrelator = (deps: SpanCorrelatorDependencies): SpanCorrelator => {\n const { stateStore, clock } = deps;\n const maxStartAgeMillis = deps.maxStartAgeMillis ?? DEFAULT_MAX_START_AGE_MILLIS;\n\n const keyFor = (input: {\n readonly sessionId: string;\n readonly providerId: string;\n readonly scope: LifecycleScope;\n readonly scopeKey: string;\n }): string => spanKey(input.sessionId, input.providerId, input.scope, input.scopeKey);\n\n /**\n * Reads and validates one record, deleting anything it refuses to interpret.\n * Self-healing on purpose: a single unreadable record must not make the same\n * scope unreadable forever.\n */\n const readRecord = async (key: string): Promise<DecodedRecord> => {\n const existing = await stateStore.read(key);\n if (existing === undefined) {\n return { kind: \"absent\" };\n }\n if (existing.value.kind !== \"attributes\") {\n await stateStore.delete(key);\n return { kind: \"corrupt\" };\n }\n const decoded = decodeRecord(existing.value.attributes);\n if (decoded.kind === \"corrupt\" || decoded.kind === \"incompatible\") {\n await stateStore.delete(key);\n }\n return decoded;\n };\n\n const recordStart = (input: SpanStartInput): Promise<SpanStartResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanStartResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"present\") {\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return { status: \"conflict\", reason: \"provider-mismatch\" };\n }\n if (existing.startEventId === input.eventId) {\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.startEventId === undefined && existing.endEventId !== undefined) {\n // The end raced ahead of the start (two hook processes, no ordering\n // guarantee between them). Complete the record rather than treating\n // the late start as the beginning of a second span.\n //\n // If that end was already exported, the scope's canonical span id is\n // already on the wire and this start must stay silent: re-exporting a\n // now-complete span under the same id would be a duplicate, not a\n // correction, because OTLP has no update. The enrichment is lost and the\n // published record remains the orphan the end could honestly produce.\n const completed: SpanRecord = {\n ...existing,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(completed));\n return existing.exported === true\n ? { status: \"published\", facts: factsOf(completed) }\n : { status: \"recorded\", facts: factsOf(completed) };\n }\n }\n\n // Either nothing was recorded, or a *different* start claims this scope\n // key: the previous span is superseded rather than merged into.\n const fresh: SpanRecord = {\n providerId: input.providerId,\n startEventId: input.eventId,\n startedAt: input.occurredAt,\n ...(input.parent === undefined ? {} : { parent: input.parent }),\n ...(input.attributes === undefined ? {} : { attributes: input.attributes }),\n };\n await stateStore.write(key, encodeRecord(fresh));\n return { status: \"recorded\", facts: factsOf(fresh) };\n });\n\n const recordEnd = (input: SpanEndInput): Promise<SpanEndResult> =>\n withOptionalSessionLock(stateStore, input.sessionId, async (): Promise<SpanEndResult> => {\n const key = keyFor(input);\n const decoded = await readRecord(key);\n\n if (decoded.kind === \"incompatible\" || decoded.kind === \"corrupt\") {\n const reason = decoded.kind === \"incompatible\" ? \"state-incompatible\" : \"state-corrupt\";\n return { status: \"orphaned\", reason, facts: { endedAt: input.occurredAt } };\n }\n if (decoded.kind === \"absent\") {\n // Remember the end anyway: a start that arrives late still deserves to\n // be paired rather than exported as a second orphan.\n const endOnly: SpanRecord = {\n providerId: input.providerId,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n // This end is about to be exported as an orphan under the scope's\n // canonical span id, so a start arriving later must not reuse it.\n exported: true,\n };\n await stateStore.write(key, encodeRecord(endOnly));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(endOnly) };\n }\n\n const existing = decoded.record;\n if (existing.providerId !== input.providerId) {\n return {\n status: \"orphaned\",\n reason: \"provider-mismatch\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.endEventId === input.eventId) {\n // Idempotent replay: answer with the facts already on disk so the\n // re-exported span is byte-identical to the first one.\n return { status: \"duplicate\", facts: factsOf(existing) };\n }\n if (existing.endEventId !== undefined) {\n return {\n status: \"orphaned\",\n reason: \"already-closed\",\n facts: { endedAt: input.occurredAt },\n };\n }\n if (existing.startedAt === undefined) {\n const replaced: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(replaced));\n return { status: \"orphaned\", reason: \"no-start-recorded\", facts: factsOf(replaced) };\n }\n if (input.occurredAt - existing.startedAt > maxStartAgeMillis) {\n await stateStore.delete(key);\n return { status: \"orphaned\", reason: \"start-expired\", facts: { endedAt: input.occurredAt } };\n }\n\n const closed: SpanRecord = {\n ...existing,\n endEventId: input.eventId,\n endedAt: input.occurredAt,\n exported: true,\n };\n await stateStore.write(key, encodeRecord(closed));\n return {\n status: \"matched\",\n startedAt: existing.startedAt,\n durationMillis: Math.max(0, input.occurredAt - existing.startedAt),\n facts: factsOf(closed),\n };\n });\n\n const correlateGroup = async (group: BatchGroup): Promise<SpanCorrelation> => {\n const base = {\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n } as const;\n const unpaired = (\n orphan: SpanOrphanClassification,\n facts: SpanCorrelationFacts,\n ): SpanCorrelation => ({\n ...base,\n pairing: \"unpaired\",\n orphan,\n // An unpaired span has no trustworthy start, so a start time is the one\n // fact it must not carry; everything else recovered is still true.\n ...correlationTimesOf(facts, { withStart: false }),\n });\n\n let startFacts: SpanCorrelationFacts | undefined;\n if (group.start !== undefined) {\n const parent = parentScopeRefOf(group.start);\n const result = await recordStart({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.start.eventId,\n occurredAt: group.start.occurredAt,\n ...(parent === undefined ? {} : { parent }),\n attributes: startOnlySpanAttributes(group.start),\n });\n if (result.status === \"conflict\") {\n return unpaired(\"provider-mismatch\", {});\n }\n if (result.status === \"published\" && group.end === undefined) {\n // The end already exported this scope's span. Completing the record was\n // still worth doing (a redelivered end replays identical facts), but\n // emitting here would duplicate a span id already on the wire.\n return { ...unpaired(\"already-closed\", result.facts), disposition: \"defer\" };\n }\n startFacts = result.facts;\n }\n\n if (group.end === undefined) {\n const facts = startFacts ?? {};\n // A start whose end already landed (the racing-process case) closes a\n // complete span, even though only the start is in this batch.\n if (facts.endedAt !== undefined) {\n return {\n ...base,\n pairing: \"cross-process\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(facts),\n };\n }\n // The end has not arrived. The start is durable now, so the end edge will\n // export one complete span under this scope's derived id; exporting a\n // zero-duration record here as well would put two records with that same id\n // on the wire, and OTLP cannot revise a span.\n return { ...unpaired(\"missing-end\", facts), disposition: \"defer\" };\n }\n\n const result = await recordEnd({\n sessionId: group.sessionId,\n providerId: group.providerId,\n scope: group.ref.family,\n scopeKey: group.ref.scopeKey,\n eventId: group.end.eventId,\n occurredAt: group.end.occurredAt,\n });\n\n if (result.status === \"orphaned\") {\n const orphan = orphanClassificationOf(result.reason);\n // `already-closed` means a *second, distinct* end for a scope whose first\n // end has already been exported under this scope's derived span id. Both\n // ends are real observations, so neither is dropped — but the second must\n // not reuse that id. Keying the discriminator on the end event id keeps a\n // redelivery of this same second end idempotent, since it recomputes the\n // same id rather than inventing a third.\n return orphan === \"already-closed\"\n ? {\n ...unpaired(orphan, result.facts),\n disposition: \"emit\",\n spanIdDiscriminator: group.end.eventId,\n }\n : { ...unpaired(orphan, result.facts), disposition: \"emit\" };\n }\n if (result.status === \"duplicate\" && result.facts.startedAt === undefined) {\n // A replayed end that never had a start is still an orphan.\n return { ...unpaired(\"missing-start\", result.facts), disposition: \"emit\" };\n }\n return {\n ...base,\n pairing: group.start === undefined ? \"cross-process\" : \"in-batch\",\n orphan: \"none\",\n disposition: \"emit\",\n ...correlationTimesOf(result.facts),\n };\n };\n\n const correlateBatch = async (\n events: readonly CanonicalEvent[],\n ): Promise<readonly SpanCorrelation[]> => {\n const groups = new Map<string, BatchGroup>();\n for (const event of events) {\n const ref = spanScopeRefOf(event);\n if (ref === undefined) {\n continue;\n }\n const providerId = event.provenance.providerId;\n const groupKey = [providerId, event.sessionId, ref.family, ref.scopeKey].join(\"\\u0000\");\n const group: BatchGroup = groups.get(groupKey) ?? {\n providerId,\n sessionId: event.sessionId,\n ref,\n };\n if (event.type.endsWith(\".start\")) {\n group.start = event;\n } else {\n group.end = event;\n }\n groups.set(groupKey, group);\n }\n\n const correlations: SpanCorrelation[] = [];\n for (const group of groups.values()) {\n try {\n correlations.push(await correlateGroup(group));\n } catch {\n // Fail open: an unreachable, locked, or unwritable state store costs a\n // span its pairing, never the whole export.\n //\n // A start whose record could not be written is the case that needs care.\n // It is *not* deferrable — deferring means \"the state store is holding\n // this, the end edge will publish it\", and here the state store is exactly\n // what failed. So it must be exported, and it must not use the scope's\n // canonical span id: nothing recorded this start, so a later end will\n // publish that id itself as an orphan, and reusing it would put two\n // records with one identity on the wire. Discriminating by the start's own\n // event id makes this record honest and collision-free.\n const unrecordedStart = group.start !== undefined && group.end === undefined;\n correlations.push({\n providerId: group.providerId,\n sessionId: group.sessionId,\n ref: group.ref,\n pairing: \"unpaired\",\n orphan: \"state-unavailable\",\n disposition: \"emit\",\n ...(unrecordedStart && group.start !== undefined\n ? { spanIdDiscriminator: group.start.eventId }\n : {}),\n });\n }\n }\n return correlations;\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<SpanCleanupResult> => {\n const keys = await stateStore.keys(spanScanPrefix(options?.sessionId));\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n let expiredOpen = 0;\n for (const key of keys) {\n if (scanned >= cap) {\n break;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n // Classified before deletion: a record with a start and no end is a span\n // that will never be exported, which is worth counting rather than\n // discarding silently.\n if (record.value.kind === \"attributes\") {\n const decoded = decodeRecord(record.value.attributes);\n if (\n decoded.kind === \"present\" &&\n decoded.record.startedAt !== undefined &&\n decoded.record.endedAt === undefined\n ) {\n expiredOpen += 1;\n }\n }\n await stateStore.delete(key);\n removed += 1;\n }\n }\n return { removed, scanned, expiredOpen };\n };\n\n return { recordStart, recordEnd, correlateBatch, cleanup };\n};\n","import {\n UsageNormalizationError,\n normalizeUsageOrThrow,\n type CanonicalUsage,\n} from \"../model/usage.js\";\nimport type { Attributes } from \"../model/primitives.js\";\nimport type { Clock, StateStore } from \"../runtime/ports.js\";\nimport { withOptionalSessionLock } from \"../state/store.js\";\nimport { rollupEpochKey, rollupEpochScanPrefix, rollupScanPrefix, rollupUsageKey } from \"./keys.js\";\n\nexport type UsageAccumulatorKey = {\n readonly sessionId: string;\n readonly scope: string;\n readonly scopeKey: string;\n};\n\nexport type UsageAccumulatorSnapshot = {\n readonly total: CanonicalUsage;\n /** Increments every time {@link UsageAccumulator.recordReset} is called for this key. */\n readonly epoch: number;\n};\n\nexport type RollupCleanupResult = { readonly removed: number; readonly scanned: number };\n\n/**\n * Which delivery an accumulation belongs to, and which of its observations this is.\n *\n * Supplying it makes the accumulation idempotent for *that delivery*: a second\n * application of the same `(callbackId, ordinal)` is a no-op that returns the\n * current total. Omitting it keeps the old unconditional behaviour, which is right\n * for a caller that has no delivery identity to key on — there is nothing to\n * recognize a repeat by, and refusing to accumulate would lose a real observation.\n *\n * `callbackId` must be an opaque digest, not a raw host or provider id: it is\n * written into a state record.\n */\nexport type DeliveryStamp = {\n readonly callbackId: string;\n /** Zero-based index of this observation within the delivery, per rollup key. */\n readonly ordinal: number;\n};\n\nexport type AccumulateOptions = { readonly delivery?: DeliveryStamp };\n\n/**\n * Rolls a stream of `delta` usage observations up into a running `cumulative`\n * total per scope, independent of the orchestrator's own per-scope\n * cumulative-to-delta baseline (`docs/usage-semantics.md`) — that baseline\n * answers \"what changed since last time\"; this answers \"what is the running\n * total\", which a diagnostics view or a parent scope (tool -> generation ->\n * session) needs and the core does not compute.\n *\n * A provider counter can restart mid-session (a process restart, a replayed\n * transcript). Rather than let a smaller cumulative total silently deflate the\n * running rollup, {@link UsageAccumulator.recordReset} starts a new epoch: the\n * total resets to zero and the epoch number increments, so a downstream\n * consumer can tell \"the counter restarted\" from \"usage actually decreased\"\n * and never sums across the boundary as if it were one continuous series.\n */\nexport interface UsageAccumulator {\n /**\n * Fold `delta` into the running total for `key`.\n *\n * With `options.delivery`, folding is idempotent for that delivery: a redelivered\n * callback whose claim was reclaimed or superseded re-derives the same delta and\n * would otherwise count it twice. The marker lives in the same record as the total\n * it describes, so the check and the write are one atomic operation — which is the\n * only reason this is expressible without a multi-key transaction. What it does\n * *not* cover is a delivery whose marker a later, different delivery has since\n * overwritten: only the most recent delivery per rollup key is recognizable, which\n * is exactly the retry window and nothing beyond it.\n */\n accumulateDelta(\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot>;\n /** Start a new epoch. Idempotent per delivery when `options.delivery` is given. */\n recordReset(key: UsageAccumulatorKey, options?: AccumulateOptions): Promise<{ readonly epoch: number }>;\n read(key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined>;\n cleanup(\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult>;\n}\n\nexport type UsageAccumulatorDependencies = {\n readonly stateStore: StateStore;\n readonly clock: Clock;\n};\n\nconst EMPTY_CUMULATIVE_USAGE: CanonicalUsage = normalizeUsageOrThrow({ temporality: \"cumulative\" });\n\nconst combineCumulativeWithDelta = (total: CanonicalUsage, delta: CanonicalUsage): CanonicalUsage => {\n if (total.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage rollup total must have cumulative temporality\" },\n ]);\n }\n if (delta.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"usage accumulator only accepts delta observations\" },\n ]);\n }\n\n const accounting =\n total.cacheCreationInputTokens === 0 && total.cacheCreationAccounting === \"not-reported\"\n ? delta.cacheCreationAccounting\n : delta.cacheCreationInputTokens === 0 && delta.cacheCreationAccounting === \"not-reported\"\n ? total.cacheCreationAccounting\n : total.cacheCreationAccounting;\n\n if (\n total.cacheCreationInputTokens !== 0 &&\n delta.cacheCreationInputTokens !== 0 &&\n total.cacheCreationAccounting !== delta.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot roll up usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n total.providerTotalTokens === undefined && delta.providerTotalTokens === undefined\n ? undefined\n : (total.providerTotalTokens ?? 0) + (delta.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"cumulative\",\n inputTokens: total.inputTokens + delta.inputTokens,\n cachedInputTokens: total.cachedInputTokens + delta.cachedInputTokens,\n cacheCreationInputTokens: total.cacheCreationInputTokens + delta.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: total.outputTokens + delta.outputTokens,\n reasoningOutputTokens: total.reasoningOutputTokens + delta.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n\nexport const createUsageAccumulator = (deps: UsageAccumulatorDependencies): UsageAccumulator => {\n const { stateStore, clock } = deps;\n\n /**\n * The epoch record's own delivery marker.\n *\n * Kept in the epoch record for the same reason the total's marker is kept in the\n * total: one write, so the counter and the statement about who moved it cannot\n * disagree. The epoch record is an `attributes` value, so the two fields are\n * flat rather than nested.\n */\n const readEpochMarker = (\n attributes: Attributes,\n ): { readonly callbackId: string; readonly applications: number } | undefined => {\n const callbackId = attributes.resetDelivery;\n const applications = attributes.resetApplications;\n if (\n typeof callbackId !== \"string\" ||\n callbackId.length === 0 ||\n typeof applications !== \"number\" ||\n !Number.isInteger(applications) ||\n applications < 1\n ) {\n return undefined;\n }\n return { callbackId, applications };\n };\n\n const readEpoch = async (key: UsageAccumulatorKey): Promise<number> => {\n const record = await stateStore.read(rollupEpochKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind === \"attributes\" && typeof record.value.attributes.epoch === \"number\") {\n return record.value.attributes.epoch;\n }\n return 0;\n };\n\n /**\n * Whether this delivery's observation number `ordinal` is already folded in.\n *\n * The comparison is `<` rather than `===` because observations are applied in\n * order: `applications` is the count folded in so far, so any ordinal below it has\n * been seen. A marker naming a *different* delivery means this rollup has moved on\n * and nothing can be recognized.\n */\n const alreadyApplied = (\n marker: { readonly callbackId: string; readonly applications: number } | undefined,\n delivery: DeliveryStamp | undefined,\n ): boolean =>\n delivery !== undefined &&\n marker !== undefined &&\n marker.callbackId === delivery.callbackId &&\n delivery.ordinal < marker.applications;\n\n const markerFor = (\n delivery: DeliveryStamp | undefined,\n ): { readonly appliedDelivery?: { readonly callbackId: string; readonly applications: number } } =>\n delivery === undefined\n ? {}\n : {\n appliedDelivery: { callbackId: delivery.callbackId, applications: delivery.ordinal + 1 },\n };\n\n const accumulateDelta = (\n key: UsageAccumulatorKey,\n delta: CanonicalUsage,\n options?: AccumulateOptions,\n ): Promise<UsageAccumulatorSnapshot> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<UsageAccumulatorSnapshot> => {\n const usageKey = rollupUsageKey(key.sessionId, key.scope, key.scopeKey);\n const existing = await stateStore.read(usageKey);\n const previousTotal =\n existing?.value.kind === \"usage-cumulative\" ? existing.value.usage : EMPTY_CUMULATIVE_USAGE;\n\n if (\n existing?.value.kind === \"usage-cumulative\" &&\n alreadyApplied(existing.value.appliedDelivery, options?.delivery)\n ) {\n // This exact observation of this exact delivery is already in the total.\n // Reporting the total unchanged is the honest answer: the caller asked for\n // the running figure after its delta, and that is what this is.\n return { total: previousTotal, epoch: await readEpoch(key) };\n }\n\n const total = combineCumulativeWithDelta(previousTotal, delta);\n await stateStore.write(usageKey, {\n kind: \"usage-cumulative\",\n usage: total,\n ...markerFor(options?.delivery),\n });\n return { total, epoch: await readEpoch(key) };\n });\n\n const recordReset = (\n key: UsageAccumulatorKey,\n options?: AccumulateOptions,\n ): Promise<{ readonly epoch: number }> =>\n withOptionalSessionLock(stateStore, key.sessionId, async (): Promise<{ readonly epoch: number }> => {\n const epochKey = rollupEpochKey(key.sessionId, key.scope, key.scopeKey);\n const existingEpoch = await stateStore.read(epochKey);\n const marker =\n existingEpoch?.value.kind === \"attributes\"\n ? readEpochMarker(existingEpoch.value.attributes)\n : undefined;\n\n if (alreadyApplied(marker, options?.delivery)) {\n // A replayed reset must not open a second epoch: the epoch number is what a\n // consumer uses to refuse summing across a counter restart, and inflating it\n // twice for one restart makes a real series look like two.\n return { epoch: await readEpoch(key) };\n }\n\n const epoch = (await readEpoch(key)) + 1;\n const applied = markerFor(options?.delivery).appliedDelivery;\n await stateStore.write(epochKey, {\n kind: \"attributes\",\n attributes: {\n epoch,\n ...(applied === undefined\n ? {}\n : { resetDelivery: applied.callbackId, resetApplications: applied.applications }),\n },\n });\n await stateStore.delete(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n return { epoch };\n });\n\n const read = async (key: UsageAccumulatorKey): Promise<UsageAccumulatorSnapshot | undefined> => {\n const record = await stateStore.read(rollupUsageKey(key.sessionId, key.scope, key.scopeKey));\n if (record?.value.kind !== \"usage-cumulative\") {\n return undefined;\n }\n return { total: record.value.usage, epoch: await readEpoch(key) };\n };\n\n const cleanup = async (\n maxAgeMillis: number,\n options?: { readonly maxEntries?: number; readonly sessionId?: string },\n ): Promise<RollupCleanupResult> => {\n const cap = options?.maxEntries ?? 1_000;\n const now = clock.now();\n let removed = 0;\n let scanned = 0;\n\n const sweep = async (keys: readonly string[]): Promise<void> => {\n for (const key of keys) {\n if (scanned >= cap) {\n return;\n }\n scanned += 1;\n const record = await stateStore.read(key);\n if (record !== undefined && now - record.updatedAt > maxAgeMillis) {\n await stateStore.delete(key);\n removed += 1;\n }\n }\n };\n\n await sweep(await stateStore.keys(rollupScanPrefix(options?.sessionId)));\n await sweep(await stateStore.keys(rollupEpochScanPrefix(options?.sessionId)));\n return { removed, scanned };\n };\n\n return { accumulateDelta, recordReset, read, cleanup };\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 type ContentFact,\n} from \"../model/content.js\";\nimport type { CanonicalEvent } 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 { Clock, IdGenerator, Logger, StateStore, TelemetrySink } from \"./ports.js\";\nimport { isStateLockContention, withOptionalSessionLock } from \"../state/store.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\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 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 * 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) => 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 };\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\n let parsed;\n try {\n parsed = adapter.parse(\n { ...detectionInput, detection, identity, sequenceBase },\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\n return { kind: \"ready\", batch, dropped: screened.dropped };\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 { batch, dropped } = prepared;\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\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 type { DeliveryHealthSnapshot } from \"../diagnostics/health.js\";\nimport type { OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport type { TelemetryEmitResult, TelemetrySink } from \"../runtime/ports.js\";\nimport type { OtlpLogTelemetrySink } from \"./otlp-log-sink.js\";\nimport type { OtlpTelemetrySink } from \"./otlp-sink.js\";\nimport type { SpanCorrelation, SpanCorrelationResolver } from \"./semconv.js\";\n\n/**\n * One canonical batch, two OTLP signals.\n *\n * A hook has a single {@link TelemetrySink} seam, and both signals map the *same*\n * canonical events — so this fans one batch out rather than making the orchestrator\n * aware that there is more than one destination.\n *\n * ## Durability adds up across signals\n *\n * The counts are summed rather than taken from the primary signal, because the\n * caller's question is \"may I commit this callback?\" and the answer turns on whether\n * *anything* reached a collector or a spool. Summing gives `classifyDurability`\n * exactly the right inputs:\n *\n * - both signals delivered → `delivered`\n * - neither delivered → `lost`, and the callback is safe to retry precisely because\n * there is nothing to duplicate\n * - one delivered and one did not → `partial`, which is terminal: retrying would\n * re-export what the healthy signal already delivered, and a duplicate silently\n * corrupts a total whereas a reported loss is a number somebody can act on\n *\n * A disabled sink accepts everything, so an installation with logs off behaves\n * exactly as it did before logs existed.\n *\n * ## Correlation must be resolved once per batch\n *\n * Both sinks want the same pairing facts, and `SpanCorrelator.correlateBatch` is not\n * a read — it records a start edge, marks a scope published, and takes the session\n * lock to do it. Wrap the correlator in {@link shareCorrelationPerBatch} and give\n * *the same wrapped function* to both sinks; `emit` here is sequential so the first\n * sink resolves it and the second is served the memoized answer.\n */\n\nexport type SignalFanoutOptions = {\n readonly traces: OtlpTelemetrySink;\n readonly logs: OtlpLogTelemetrySink;\n};\n\nexport interface SignalFanoutSink extends TelemetrySink {\n /** One snapshot per wired signal, in a stable order: traces, then logs. */\n health(): readonly DeliveryHealthSnapshot[];\n}\n\nexport const createSignalFanout = (options: SignalFanoutOptions): SignalFanoutSink => {\n const emit = async (events: readonly CanonicalEvent[]): Promise<TelemetryEmitResult> => {\n // Sequential, not concurrent: the first sink to ask resolves correlation, and\n // the second must be served that answer rather than race to start a second\n // resolution against the same state.\n const traces = await options.traces.emit(events);\n const logs = await options.logs.emit(events);\n const errors: readonly OtelHookErrorInfo[] = [...traces.errors, ...logs.errors];\n return {\n accepted: traces.accepted + logs.accepted,\n rejected: traces.rejected + logs.rejected,\n errors,\n };\n };\n\n const flush = async (): Promise<void> => {\n // Each signal's flush is already best-effort and non-throwing; awaiting both\n // unconditionally means a stuck logs endpoint cannot skip the trace flush.\n await options.traces.flush().catch(() => undefined);\n await options.logs.flush().catch(() => undefined);\n };\n\n const shutdown = async (): Promise<void> => {\n await options.traces.shutdown().catch(() => undefined);\n await options.logs.shutdown().catch(() => undefined);\n };\n\n return {\n emit,\n flush,\n shutdown,\n health: (): readonly DeliveryHealthSnapshot[] => [\n options.traces.health(),\n options.logs.health(),\n ],\n };\n};\n\n/**\n * Wrap a correlation resolver so one batch resolves at most once.\n *\n * Memoized on the identity of the `events` array, which is what makes it correct\n * without a reset: every batch is a distinct array, so a new batch cannot be served\n * a previous one's answer, and a retry of the *same* array deliberately is. The\n * promise is cached rather than its value, so two callers arriving before the first\n * resolution completes still share it.\n *\n * Exported because the one-call-per-batch property is a requirement of the\n * correlator, not a convenience of the fanout: a host wiring its own pair of sinks\n * needs to be able to express it too.\n */\nexport const shareCorrelationPerBatch = (\n correlate: SpanCorrelationResolver,\n): SpanCorrelationResolver => {\n let pending:\n | {\n readonly events: readonly CanonicalEvent[];\n readonly result: Promise<readonly SpanCorrelation[]>;\n }\n | undefined;\n return (events): Promise<readonly SpanCorrelation[]> => {\n if (pending?.events === events) {\n return pending.result;\n }\n const result = correlate(events);\n pending = { events, result };\n return result;\n };\n};\n","import type { OtelHookConfig } from \"../config/schema.js\";\nimport { summarizeHealth, type DeliveryHealthSnapshot, type OverallHealth } from \"../diagnostics/health.js\";\nimport { createErrorInfo, errorInfoFromThrown, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport type { CanonicalEvent } from \"../model/events.js\";\nimport {\n createCallbackDeduplicator,\n type CallbackDeduplicator,\n type DeliveryClaimOutcome,\n} from \"../lifecycle/dedup.js\";\nimport { createLifecycleJanitor, type LifecycleCleanupReport, type LifecycleJanitor } from \"../lifecycle/janitor.js\";\nimport { createSpanCorrelator, type SpanCorrelator } from \"../lifecycle/span-correlator.js\";\nimport {\n createUsageAccumulator,\n type UsageAccumulator,\n type UsageAccumulatorSnapshot,\n} from \"../lifecycle/usage-accumulator.js\";\nimport { createPrivacyService, type PrivacyService } from \"../privacy/service.js\";\nimport type { ProviderRegistry } from \"../providers/registry.js\";\nimport { createSystemClock } from \"../runtime/clock.js\";\nimport {\n createOtelHook,\n isCommittable,\n type HookIngestInput,\n type HookIngestOutcome,\n type OtelHook,\n type UsageObservation,\n} from \"../runtime/hook.js\";\nimport {\n hostDeliveryIdentity,\n type DeliveryOrigin,\n type DeliveryResolution,\n type DeliveryUnavailableReason,\n type ResolvedDeliveryIdentity,\n} from \"../runtime/delivery.js\";\nimport { createDeterministicIdGenerator } from \"../runtime/ids.js\";\nimport { createNullLogger } from \"../runtime/logger.js\";\nimport type { Clock, IdGenerator, Logger } from \"../runtime/ports.js\";\nimport { createAsyncLock } from \"../state/async-lock.js\";\nimport { createFilesystemStateStore, type FilesystemStateStore } from \"../state/filesystem-store.js\";\nimport {\n createFileDurableLogSpool,\n type DurableLogSpool,\n} from \"../telemetry/durable-log-spool.js\";\nimport { createFileDurableSpool, type DurableSpool } from \"../telemetry/durable-spool.js\";\nimport { createOtlpLogSink, type OtlpLogTelemetrySink } from \"../telemetry/otlp-log-sink.js\";\nimport { createOtlpTraceSink, type OtlpTelemetrySink } from \"../telemetry/otlp-sink.js\";\nimport {\n createSignalFanout,\n shareCorrelationPerBatch,\n} from \"../telemetry/signal-fanout.js\";\n\n/**\n * A hook process lives for milliseconds and then exits, but the facts it needs\n * — the previous cumulative token baseline, the next sequence number, a running\n * per-scope rollup, which deliveries have already been handled — span a whole\n * session. This module is the wiring that makes those two facts coexist without\n * a daemon: filesystem-backed state, a filesystem spool for batches an\n * unreachable collector refused, and a *bounded* flush so a hanging collector\n * costs the host a known number of milliseconds rather than a stalled agent.\n *\n * ## Delivery deduplication\n *\n * A redelivered callback must not be exported or accounted twice, and it must\n * stay suppressed across a process restart — which rules out anything held in\n * memory. Two identities can carry that:\n *\n * 1. An explicit, host-supplied delivery id ({@link HookProcessInput.delivery}),\n * unique by construction because only the host knows it.\n * 2. One normalized from payload fields the selected adapter vouches for — a\n * `tool_use_id`, an `agent_id`, a `prompt_id`. Adapters declare coverage as\n * `deliveryIdentifier` and report components per callback, and the runtime\n * digests them into an opaque, installation-and-session-scoped pair.\n *\n * Neither `invocationId` nor `eventId` can serve: some adapters seed the former\n * with a clock reading (Claude Code documents each hook firing as a distinct\n * invocation), and the latter is seeded with a session sequence number that has\n * already advanced by the time a redelivery arrives.\n *\n * Ownership is taken *before* `ingest` and committed only once the batch is\n * somewhere durable: a delivery arriving inside the window sees the claim and\n * stands down, and a batch that reached neither the collector nor the spool\n * releases its claim for retry instead of committing a loss.\n *\n * **This is at-least-once export, not exactly-once.** The collector is a separate\n * system and there is no transaction spanning an OTLP acceptance and a local state\n * write, so a process killed after the collector took a batch and before the claim\n * commits will re-export on redelivery. That ordering is deliberate: a duplicate\n * carries the same derived trace and span id and can be dropped at the collector,\n * whereas committing first would turn the same window into silent loss. Local\n * accounting *is* at-most-once, because it commits under the claim's own lock.\n *\n * ## Ordering and locks\n *\n * Two locks, always acquired in one order — delivery-scope lock, then state lock —\n * and never nested one state lock inside another:\n *\n * - An in-process lock on the delivery scope serializes same-scope deliveries in\n * arrival order, so deduplication never reorders what it lets through.\n * - `ingest` holds the store's *cross-process* session lock across the session\n * state critical section, which is what stops two hook processes from stamping\n * two batches with one sequence range. Export happens after that lock is\n * released: the span correlator takes the same session lock from inside the sink,\n * and it is not reentrant.\n *\n * ## Deliberate limitations\n *\n * 1. **Deduplication coverage is per provider, and partial for every adapter.** An\n * adapter that declares `deliveryIdentifier: \"partial\"` identifies only the\n * callbacks carrying a field that separates a genuine second firing from a\n * redelivery — for most that means per-tool-call and per-subagent edges, and for\n * the Gemini CLI, whose protocol has no such field at all, only the\n * once-per-session edges. The rest are exported without the at-most-once\n * guarantee unless the host supplies a delivery id; with `requireCallbackId` the\n * runtime says so per callback instead of leaving it to be inferred.\n * 2. **Cross-process span pairing needs a durable state root.** The\n * {@link SpanCorrelator} is wired into the sink, so a `*.end` emitted by a\n * later process carries its start time, duration, parent, and start-only\n * attributes. That correlation lives entirely in the state store: point two\n * invocations at different `stateRootDir`s and each exports a lone,\n * explicitly classified orphan instead. A disabled exporter records nothing,\n * since there is no span to pair.\n */\n\nexport type HookRuntimeDelivery = {\n /**\n * Host-supplied identifier for *this* delivery of a hook callback. Stable\n * across a redelivery of the same callback, unique between distinct\n * callbacks. Nothing derives it: only the host knows it.\n */\n readonly callbackId: string;\n /** Namespace the id is unique within. Defaults to `\"delivery\"`. */\n readonly scope?: string;\n};\n\nexport type HookProcessInput = HookIngestInput & {\n readonly delivery?: HookRuntimeDelivery;\n};\n\n/**\n * What deduplication did with this callback.\n *\n * Reported rather than inferred: \"exported once because it was fresh\" and\n * \"exported once because nothing could tell it apart from a redelivery\" produce\n * identical telemetry, and only the first is a guarantee.\n */\nexport type DeliveryReport = {\n /**\n * True when a replay-stable identity was established and a claim enforced.\n *\n * Not a promise of exactly-once export: see this module's note on crash\n * semantics. It means a redelivery arriving *while local state is intact* is\n * suppressed.\n */\n readonly deduplicated: boolean;\n /** Where the identity came from. Absent when none was established. */\n readonly origin?: DeliveryOrigin;\n /** How the claim resolved. Absent when no identity was established. */\n readonly outcome?: DeliveryClaimOutcome;\n /** Why no identity was established. Absent when one was. */\n readonly reason?: DeliveryUnavailableReason;\n /** The adapter's declared coverage, when a provider was selected. */\n readonly capability?: string;\n /**\n * The provider's own name for the callback that could not be identified.\n *\n * Present only alongside `reason`. Coverage is per callback, so a host auditing\n * its own gaps needs the callback name to act on the report at all — the\n * provider id and the capability are the same for every one of them.\n */\n readonly sourceEventName?: string;\n /**\n * The adapter's own account of why this callback has no identity, and what field\n * would close the gap. Absent when the adapter documents none.\n */\n readonly detail?: string;\n /** Adapter-supplied justifications for a provider-derived identity. */\n readonly evidence?: readonly string[];\n /**\n * True when a claim was released because the batch reached neither the\n * collector nor the spool, so redelivering this callback is expected to\n * re-export it rather than be suppressed.\n */\n readonly retryable?: boolean;\n /**\n * Spans permanently lost on a callback that is nonetheless **committed**.\n *\n * Present only for a partial batch: some spans reached the collector or the\n * spool and some did not. The callback is not retried, because retrying would\n * re-export the accepted spans, so these observations are gone. Reported as a\n * number rather than folded into `retryable` because the two demand opposite\n * responses — a retryable callback needs redelivering, a partial loss needs\n * investigating.\n */\n readonly partialLoss?: number;\n /**\n * True when another process reclaimed this callback's claim before this one\n * committed.\n *\n * Deduplication did not hold for this callback: both deliveries may have\n * exported it. Reported rather than hidden, because the cause is a\n * configured stale window that is too short for this installation and only an\n * operator can fix that.\n */\n readonly superseded?: boolean;\n};\n\nexport type HookProcessOutcome = {\n readonly ingest: HookIngestOutcome;\n /**\n * True when a matching delivery id had already been handled, so this\n * invocation's events were deliberately not exported. `ingest.emitted` is 0 in\n * that case; the provider's hook response is still produced normally, because\n * a redelivered callback still expects its protocol response.\n */\n readonly duplicateDelivery: boolean;\n /** Why this callback was, or was not, deduplicated. */\n readonly delivery: DeliveryReport;\n /** Running per-scope totals after applying this invocation's deltas. */\n readonly usageRollups: readonly UsageRollup[];\n /** Cleanup performed opportunistically; absent when no sweep ran. */\n readonly cleanup?: LifecycleCleanupReport;\n /** Diagnostics raised by this module, in addition to `ingest.diagnostics`. */\n readonly diagnostics: readonly OtelHookErrorInfo[];\n};\n\nexport type UsageRollup = {\n readonly scope: UsageObservation[\"scope\"];\n readonly scopeKey: string;\n readonly snapshot: UsageAccumulatorSnapshot;\n};\n\nexport type HookShutdownReport = {\n /** False when the bounded flush window elapsed before delivery finished. */\n readonly flushCompleted: boolean;\n readonly flushTimeoutMillis: number;\n readonly health: OverallHealth;\n};\n\nexport interface HookRuntime {\n readonly hook: OtelHook;\n readonly config: OtelHookConfig;\n readonly stateStore: FilesystemStateStore;\n /** The traces signal. Named `sink` because it is the one every installation has. */\n readonly sink: OtlpTelemetrySink;\n /** The logs signal. A no-op sink unless `exporter.logs.enabled` is set. */\n readonly logSink: OtlpLogTelemetrySink;\n readonly spool?: DurableSpool;\n /** Retry queue for the logs signal. Absent when spooling or logs are disabled. */\n readonly logSpool?: DurableLogSpool;\n readonly privacy: PrivacyService;\n readonly deduplicator: CallbackDeduplicator;\n readonly usageAccumulator: UsageAccumulator;\n /** Backs the cross-process pairing the sink applies to every exported span. */\n readonly spanCorrelator: SpanCorrelator;\n readonly janitor: LifecycleJanitor;\n /** Ingest one observation, then apply lifecycle accumulation. Never throws. */\n process(input: HookProcessInput): Promise<HookProcessOutcome>;\n /** Bounded flush + shutdown. Never throws; idempotent. */\n shutdown(): Promise<HookShutdownReport>;\n health(): OverallHealth;\n}\n\nexport type HookRuntimeOptions = {\n readonly config: OtelHookConfig;\n readonly registry: ProviderRegistry;\n /** Root of the state and spool trees. One directory per provider/installation below it. */\n readonly stateRootDir: string;\n /**\n * Namespace separating one deployment's state from another's. Not identity: it\n * never reaches an event, and no session or workspace is derived from it.\n */\n readonly installationId: string;\n /** State/spool namespace segment; the selected provider id, or a placeholder. */\n readonly providerNamespace: string;\n /** Exporter header *values*, deliberately absent from the config snapshot. */\n readonly headers?: Readonly<Record<string, string>>;\n readonly clock?: Clock;\n readonly ids?: IdGenerator;\n readonly logger?: Logger;\n readonly privacy?: PrivacyService;\n /** Upper bound on flush + shutdown. Default 2,000ms. */\n readonly flushTimeoutMillis?: number;\n /** Persist batches an unreachable collector refused. Default true. */\n readonly enableSpool?: boolean;\n /** Bounded lock waits keep a stuck peer from stalling the host. Default 1,000ms. */\n readonly stateLockTimeoutMillis?: number;\n /** Sweep expired lifecycle state when a session ends. Default true. */\n readonly sweepOnSessionEnd?: boolean;\n readonly lifecycleMaxAgeMillis?: number;\n /**\n * Normalize a delivery identity from the adapter when the host supplies none.\n * Default true. Set false to keep deduplication strictly opt-in per callback.\n */\n readonly deriveDeliveryIdentity?: boolean;\n /**\n * Raise `delivery-identifier-unavailable` for every callback that could not be\n * deduplicated, naming the provider and the capability that is missing. Default\n * false: without it, an unidentifiable callback is a silent absence of a\n * guarantee, which is exactly what a host auditing its own coverage cannot see.\n */\n readonly requireCallbackId?: boolean;\n /**\n * How long an uncommitted claim is respected before a later delivery may\n * assume the process that took it died. Default 60,000ms.\n */\n readonly staleClaimMillis?: number;\n /** TTL for dedup records specifically. Defaults to `lifecycleMaxAgeMillis`. */\n readonly deliveryRetentionMillis?: number;\n};\n\nconst DEFAULT_FLUSH_TIMEOUT_MILLIS = 2_000;\nconst DEFAULT_STATE_LOCK_TIMEOUT_MILLIS = 1_000;\nconst DEFAULT_LIFECYCLE_MAX_AGE_MILLIS = 24 * 60 * 60 * 1000;\nconst DEFAULT_STALE_CLAIM_MILLIS = 60_000;\n\nconst delay = (millis: number): Promise<\"timeout\"> =>\n new Promise((resolve) => {\n const timer = setTimeout(() => resolve(\"timeout\"), millis);\n timer.unref?.();\n });\n\nconst containsSessionEnd = (events: readonly CanonicalEvent[]): boolean =>\n events.some((event) => event.type === \"session.end\");\n\n/** Delivery is this module's own concern; `ingest` never sees it. */\nconst withoutDelivery = (input: HookProcessInput): HookIngestInput => {\n const { delivery, ...ingestInput } = input;\n void delivery;\n return ingestInput;\n};\n\n/**\n * Smallest stale-claim window that cannot expire while a live process is still\n * working on the callback it claimed.\n *\n * A claim is taken before `ingest` and committed after export, so the window has\n * to cover the whole of that: waiting for the session state lock, the adapter's\n * work, then every export attempt the exporter policy permits, then the bounded\n * flush. If `staleClaimMillis` is shorter than that, a second delivery arriving\n * mid-flight declares the first one abandoned and *reclaims* it — and then both\n * processes export the same callback. That is not a smaller guarantee, it is the\n * opposite of the one being advertised, produced by a configuration value that\n * looks like a harmless tuning knob.\n *\n * So the floor is derived from the same policy the work is bounded by, rather\n * than being a constant that a later timeout change could silently outgrow. The\n * multiplier on the export timeout counts the first attempt plus each retry.\n */\n/**\n * Bounded lock acquisitions between `claim` and `commit`, counted rather than\n * guessed.\n *\n * Each one can cost a full `stateLockTimeoutMillis` under contention, so the floor\n * has to include all of them. Enumerated so that adding a locked step without\n * revisiting this number is visibly an omission:\n *\n * 1. `ingest` phase 1 — the session-state critical section (read sequence, parse,\n * reserve).\n * 2. `ingest` phase 3 — the usage-accounting critical section.\n * 3. the span correlator, called from inside the sink during export.\n * 4. `deduplicator.commit` itself.\n */\nconst POST_CLAIM_LOCK_ACQUISITIONS = 4;\n\n/**\n * Locked operations the *accounting* phase performs, per usage observation.\n *\n * `recordReset` then `accumulateDelta`, each taking the session lock on its own.\n * Multiplied by the observation cap below rather than by the raw event limit: usage\n * lands on end-edge events only, so the cap is generous rather than exact.\n */\nconst ACCOUNTING_LOCKS_PER_OBSERVATION = 2;\n\n/**\n * How many usage observations the floor budgets for.\n *\n * Deliberately not `limits.maxEventsPerInvocation` (512 by default): summing 1,024\n * lock timeouts would put the floor in the tens of minutes, and a floor that large\n * is its own problem — it delays recovery of genuinely crashed claims by that long.\n * A real hook callback carries a handful of usage-bearing events, so this is the\n * conservative-but-useful bound, and the ownership check below is what covers the\n * case where reality exceeds it: a claim reclaimed under a live holder is *detected*\n * at commit rather than silently double-counted.\n */\nconst BUDGETED_USAGE_OBSERVATIONS = 8;\n\n/**\n * Smallest stale-claim window that cannot expire while a live process is still\n * working on the callback it claimed.\n *\n * A claim is taken before `ingest` and committed after accounting, so the window has\n * to cover the whole of that: every bounded lock acquisition on the way, every\n * export attempt the exporter policy permits, the spool write that follows a refused\n * export, and the bounded flush. If `staleClaimMillis` is shorter, a second delivery\n * arriving mid-flight declares the first one abandoned and *reclaims* it — and then\n * both processes export the same callback. That is not a smaller guarantee, it is\n * the opposite of the one being advertised, produced by a value that looks like a\n * harmless tuning knob.\n *\n * Derived from the same policy the work is bounded by, rather than a constant a\n * later timeout change could silently outgrow. It is a *floor*, not a prediction:\n * being generous costs only recovery latency after a crash, while being short costs\n * correctness.\n */\nexport const minimumStaleClaimMillis = (input: {\n readonly exportTimeoutMillis: number;\n readonly maxRetryAttempts: number;\n readonly flushTimeoutMillis: number;\n readonly stateLockTimeoutMillis: number;\n}): number => {\n const exportBudget = input.exportTimeoutMillis * (input.maxRetryAttempts + 1);\n const lockBudget =\n input.stateLockTimeoutMillis *\n (POST_CLAIM_LOCK_ACQUISITIONS +\n ACCOUNTING_LOCKS_PER_OBSERVATION * BUDGETED_USAGE_OBSERVATIONS);\n // A refused export writes the batch to the spool before returning, and the\n // janitor may sweep on a session-end callback. Both are bounded but neither has\n // its own configured timeout, so they share one allowance.\n const spoolAndSweepAllowance = 2 * input.stateLockTimeoutMillis;\n // A margin so a value derived from the same numbers is not exactly on the\n // boundary; process scheduling alone can cost tens of milliseconds.\n const margin = 1_000;\n return lockBudget + exportBudget + input.flushTimeoutMillis + spoolAndSweepAllowance + margin;\n};\n\nconst DELIVERY_UNAVAILABLE_DETAIL: Readonly<Record<DeliveryUnavailableReason, string>> =\n Object.freeze({\n \"provider-unattributed\":\n \"no provider was attributed, so no adapter could vouch for a replay-stable identifier\",\n \"provider-declares-none\":\n \"the selected adapter declares deliveryIdentifier=none: no callback of this provider carries a replay-stable identifier, so only --callback-id can deduplicate it\",\n \"callback-not-identifiable\":\n \"the selected adapter identifies some callbacks but not this one; it carries no field that separates a redelivery from a genuine second firing\",\n \"claim-rejected\":\n \"the selected adapter offered a delivery identity that failed the contract's own guards\",\n \"state-unavailable\":\n \"a delivery identity was established but the state store could not record a claim against it\",\n });\n\nexport const createHookRuntime = (options: HookRuntimeOptions): HookRuntime => {\n const clock = options.clock ?? createSystemClock();\n const ids = options.ids ?? createDeterministicIdGenerator();\n const logger = options.logger ?? createNullLogger();\n const privacy = options.privacy ?? createPrivacyService(options.config.privacy);\n const flushTimeoutMillis = options.flushTimeoutMillis ?? DEFAULT_FLUSH_TIMEOUT_MILLIS;\n const lifecycleMaxAge = options.lifecycleMaxAgeMillis ?? DEFAULT_LIFECYCLE_MAX_AGE_MILLIS;\n const stateLockTimeoutMillis = options.stateLockTimeoutMillis ?? DEFAULT_STATE_LOCK_TIMEOUT_MILLIS;\n\n // Raised, never lowered, and reported when raised: silently honouring a window\n // shorter than one process's own work would turn suppression into a double\n // export. See `minimumStaleClaimMillis`.\n const staleClaimFloor = minimumStaleClaimMillis({\n exportTimeoutMillis: options.config.exporter.timeoutMillis,\n maxRetryAttempts: options.config.exporter.maxRetryAttempts,\n flushTimeoutMillis,\n stateLockTimeoutMillis,\n });\n const requestedStaleClaim = options.staleClaimMillis ?? DEFAULT_STALE_CLAIM_MILLIS;\n const staleClaimMillis = Math.max(requestedStaleClaim, staleClaimFloor);\n if (staleClaimMillis > requestedStaleClaim) {\n logger.warn(\"staleClaimMillis raised to cover this installation's own export budget\", {\n \"delivery.stale_claim_requested_millis\": requestedStaleClaim,\n \"delivery.stale_claim_effective_millis\": staleClaimMillis,\n });\n }\n\n const stateStore = createFilesystemStateStore({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n lockTimeoutMillis: stateLockTimeoutMillis,\n });\n\n const spool =\n options.enableSpool === false\n ? undefined\n : createFileDurableSpool({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n });\n\n // A separate queue from the trace spool, so a logs outage cannot consume the\n // capacity the primary signal's retries need. Only built when logs are on: a\n // default installation must not create a directory for a signal it never emits.\n const logSpool =\n options.enableSpool === false || !options.config.exporter.logs.enabled\n ? undefined\n : createFileDurableLogSpool({\n rootDir: options.stateRootDir,\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n });\n\n const spanCorrelator = createSpanCorrelator({\n stateStore,\n clock,\n maxStartAgeMillis: lifecycleMaxAge,\n });\n\n /**\n * One correlation resolution per batch, shared by both signals.\n *\n * `correlateBatch` records the start edge and marks a scope published, so two\n * calls for one batch would have the second see the first's writes and report a\n * start it just recorded as a duplicate — leaving the two signals pointing at\n * different span ids for the same scope.\n */\n const correlate = shareCorrelationPerBatch((events) => spanCorrelator.correlateBatch(events));\n\n const traceSink = createOtlpTraceSink({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(spool === undefined ? {} : { spool }),\n correlate,\n });\n\n const logSink = createOtlpLogSink({\n exporter: options.config.exporter,\n ...(options.headers === undefined ? {} : { headers: options.headers }),\n providerId: options.providerNamespace,\n installationId: options.installationId,\n clock,\n logger,\n ...(logSpool === undefined ? {} : { spool: logSpool }),\n content: {\n includeContent: options.config.exporter.logs.includeContent,\n // The pre-existing verbatim-content opt-in, passed through rather than\n // re-derived: `raw` disclosure in a log body is governed by the same flag it\n // has always been governed by.\n allowRawContent: privacy.policy.allowRawContent,\n },\n correlate,\n });\n\n const sink = createSignalFanout({ traces: traceSink, logs: logSink });\n\n const hookDeps = {\n stateStore,\n config: options.config,\n registry: options.registry,\n clock,\n ids,\n privacy,\n logger,\n installationId: options.installationId,\n };\n const hook = createOtelHook({ ...hookDeps, sink });\n\n const deduplicator = createCallbackDeduplicator({ stateStore, clock });\n const usageAccumulator = createUsageAccumulator({ stateStore, clock });\n const deliveryRetentionMillis = options.deliveryRetentionMillis ?? lifecycleMaxAge;\n if (deliveryRetentionMillis < staleClaimMillis) {\n // Not raised, only reported: an operator who wants dedup records gone in a\n // minute is entitled to that, and the sweep already refuses to drop a claim\n // inside the stale window. What they are not entitled to is a *silent* gap —\n // a completed record that expires before a redelivery could plausibly arrive\n // stops suppressing it, and this is the number that explains why.\n logger.warn(\"delivery retention is shorter than the stale-claim window\", {\n \"delivery.retention_millis\": deliveryRetentionMillis,\n \"delivery.stale_claim_effective_millis\": staleClaimMillis,\n });\n }\n const janitor = createLifecycleJanitor({\n spanCorrelator,\n deduplicator,\n usageAccumulator,\n spanMaxAgeMillis: lifecycleMaxAge,\n dedupMaxAgeMillis: deliveryRetentionMillis,\n // The *effective* window, not the requested one: a sweep that considered a\n // claim dead earlier than the claim path does would hand a live callback to a\n // peer as fresh.\n dedupStaleClaimMillis: staleClaimMillis,\n usageMaxAgeMillis: lifecycleMaxAge,\n });\n\n const deliveryLock = createAsyncLock();\n\n const stateDiagnostic = (thrown: unknown): OtelHookErrorInfo =>\n errorInfoFromThrown(thrown, { code: \"state-store-failure\", phase: \"state\", occurredAt: clock.now() });\n\n /**\n * Opaque, replay-stable token for a delivery, safe to write into a state record.\n *\n * Digested rather than used directly, because a *host-supplied* callback id is a\n * raw external identifier and a rollup record's contents are not a place one may\n * appear as a side effect of deduplicating on it. The digest is content-addressed,\n * so a later process recomputes the same token — which is the whole point: the\n * retry has to recognize its own earlier application.\n */\n const rollupDeliveryToken = (identity: ResolvedDeliveryIdentity): string | undefined => {\n // Clamped to the shape the state schema admits, because `ids` is injected: the\n // default generator returns a hex digest, but a host's own could return anything.\n // An unusable token must cost the *idempotency check* and nothing else — writing\n // it would fail validation and take the whole rollup down with it, which trades a\n // possible double count for a certain lost one.\n const token = ids\n .newOpaqueId([\"usage-delivery\", identity.scope, identity.callbackId])\n .replace(/[^A-Za-z0-9_-]/g, \"\")\n .slice(0, 128);\n return token.length === 0 ? undefined : token;\n };\n\n const applyRollups = async (\n sessionId: string,\n observations: readonly UsageObservation[],\n diagnostics: OtelHookErrorInfo[],\n deliveryToken?: string,\n ): Promise<readonly UsageRollup[]> => {\n const rollups: UsageRollup[] = [];\n // Per rollup key, because idempotency is per record: two observations landing on\n // one key are the first and second application *to that key*, whatever their\n // position in the batch.\n const ordinals = new Map<string, number>();\n for (const observation of observations) {\n const key = { sessionId, scope: observation.scope, scopeKey: observation.scopeKey };\n const rollupId = `${observation.scope}\u0000${observation.scopeKey}`;\n const ordinal = ordinals.get(rollupId) ?? 0;\n ordinals.set(rollupId, ordinal + 1);\n // Absent when no delivery identity was established: there is then nothing to\n // recognize a repeat by, and declining to accumulate would lose a real\n // observation rather than avoid a duplicate one.\n const options =\n deliveryToken === undefined\n ? undefined\n : { delivery: { callbackId: deliveryToken, ordinal } };\n try {\n if (observation.resetDetected) {\n // A restarted provider counter starts a new epoch rather than\n // deflating the running total (see createUsageAccumulator).\n await usageAccumulator.recordReset(key, options);\n }\n const snapshot = await usageAccumulator.accumulateDelta(key, observation.delta, options);\n rollups.push({ scope: observation.scope, scopeKey: observation.scopeKey, snapshot });\n } catch (thrown) {\n diagnostics.push(\n errorInfoFromThrown(thrown, {\n code: \"usage-invalid\",\n phase: \"normalization\",\n occurredAt: clock.now(),\n }),\n );\n }\n }\n return rollups;\n };\n\n /**\n * Establish this callback's delivery identity.\n *\n * A host-supplied id always wins: the host knows things about its own\n * redelivery that no payload states. Only when there is none does the adapter\n * get asked, and only if derivation is enabled.\n */\n const identifyDelivery = (\n input: HookProcessInput,\n ): { readonly identity?: ResolvedDeliveryIdentity; readonly unavailable?: DeliveryResolution } => {\n if (input.delivery !== undefined) {\n return {\n identity: hostDeliveryIdentity(input.delivery.callbackId, input.delivery.scope),\n };\n }\n if (options.deriveDeliveryIdentity === false) {\n return {};\n }\n const resolution = hook.resolveDelivery(withoutDelivery(input));\n return resolution.status === \"resolved\"\n ? { identity: resolution.identity }\n : { unavailable: resolution };\n };\n\n const reportUnavailable = (\n resolution: DeliveryResolution | undefined,\n diagnostics: OtelHookErrorInfo[],\n ): DeliveryReport => {\n if (resolution === undefined || resolution.status === \"resolved\") {\n // Either an identity was established, or none was even attempted because the\n // host supplied its own id or switched derivation off. Neither is a provider\n // gap, so `requireCallbackId` has nothing to report.\n return { deduplicated: false };\n }\n if (options.requireCallbackId === true) {\n // The generic sentence explains the *reason code*; the adapter's own gap\n // explains the *callback*. Both are useful and they answer different\n // questions, so the detail carries the general statement and then the\n // specific one rather than replacing either.\n const generic = DELIVERY_UNAVAILABLE_DETAIL[resolution.reason];\n const detail =\n resolution.detail === undefined ? generic : `${generic}; ${resolution.detail}`;\n diagnostics.push(\n createErrorInfo({\n code: \"delivery-identifier-unavailable\",\n phase: \"identity\",\n detail: detail.slice(0, 400),\n details: {\n \"delivery.reason\": resolution.reason,\n ...(resolution.providerId === undefined ? {} : { \"provider.id\": resolution.providerId }),\n ...(resolution.capability === undefined\n ? {}\n : { \"provider.delivery_identifier\": resolution.capability }),\n ...(resolution.sourceEventName === undefined\n ? {}\n : { \"delivery.source_event_name\": resolution.sourceEventName }),\n \"delivery.remedy\": \"pass an explicit host delivery id (--callback-id)\",\n },\n occurredAt: clock.now(),\n }),\n );\n }\n return {\n deduplicated: false,\n reason: resolution.reason,\n ...(resolution.capability === undefined ? {} : { capability: resolution.capability }),\n ...(resolution.sourceEventName === undefined\n ? {}\n : { sourceEventName: resolution.sourceEventName }),\n ...(resolution.detail === undefined ? {} : { detail: resolution.detail }),\n };\n };\n\n const runProcess = async (\n input: HookProcessInput,\n identity: ResolvedDeliveryIdentity | undefined,\n report: DeliveryReport,\n diagnostics: OtelHookErrorInfo[],\n ): Promise<HookProcessOutcome> => {\n let delivery = report;\n let owned = false;\n let claimOwner: string | undefined;\n\n if (identity !== undefined) {\n try {\n const claimed = await deduplicator.claim(identity.scope, identity.callbackId, {\n staleClaimMillis,\n });\n owned = claimed.owned;\n claimOwner = claimed.owner;\n delivery = {\n deduplicated: true,\n origin: identity.origin,\n outcome: claimed.outcome,\n ...(identity.evidence.length === 0 ? {} : { evidence: identity.evidence }),\n };\n if (claimed.outcome === \"reclaimed\") {\n logger.warn(\"took over a delivery claim no process ever completed\", {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": claimed.attempt,\n \"delivery.abandoned_for_millis\": claimed.abandonedForMillis ?? 0,\n });\n }\n if (claimed.duplicate) {\n logger.info(\"delivery already handled; telemetry suppressed\", {\n \"delivery.origin\": identity.origin,\n \"delivery.outcome\": claimed.outcome,\n });\n }\n } catch (thrown) {\n // An unreadable dedup record must not drop telemetry: exporting a\n // possible duplicate is recoverable at the collector, losing a real\n // observation is not. Deduplication is what lapses here, so\n // the report says so rather than claiming a guarantee that did not hold.\n diagnostics.push(stateDiagnostic(thrown));\n delivery = { deduplicated: false, origin: identity.origin, reason: \"state-unavailable\" };\n }\n }\n\n const duplicateDelivery = delivery.outcome === \"duplicate\" || delivery.outcome === \"in-flight\";\n // A redelivery is parsed but changes nothing: no export, no sequence advance,\n // no cumulative-usage rewrite. Suppressing inside `ingest` rather than at the\n // sink is what makes that true — a discarding sink still let the orchestrator\n // renumber the session and move the usage baseline, so a redelivered callback\n // silently shifted every later event's derived id.\n const ingest = await hook.ingest(withoutDelivery(input), { suppress: duplicateDelivery });\n\n let usageRollups: readonly UsageRollup[] = [];\n if (!duplicateDelivery && ingest.identity !== undefined && ingest.usageObservations.length > 0) {\n // The rollup is the one piece of accounting that sits *outside* `ingest`'s\n // own transaction, in a second critical section — the accumulator takes the\n // same non-reentrant session lock. That leaves this the only place a retried\n // or reclaimed delivery could apply its numbers twice, so it is the one place\n // that gets stamped with the delivery it belongs to.\n usageRollups = await applyRollups(\n ingest.identity.sessionId,\n ingest.usageObservations,\n diagnostics,\n identity === undefined ? undefined : rollupDeliveryToken(identity),\n );\n }\n\n if (owned && identity !== undefined) {\n // Committing means \"this callback is accounted for; never process it again\",\n // so the decision turns on whether *anything* survived rather than whether\n // everything did — see `DeliveryDurability`.\n //\n // A partially delivered batch is terminal, and that is the uncomfortable but\n // correct answer. Releasing it would retry the whole callback and re-export\n // every span a collector already accepted, turning a reported loss into a\n // silent double-count; a duplicated span corrupts a total that nobody can\n // reconstruct, whereas a reported loss is a number somebody can act on. So\n // the callback commits and the loss is stated.\n try {\n if (isCommittable(ingest.durability)) {\n const committed = await deduplicator.commit(\n identity.scope,\n identity.callbackId,\n claimOwner,\n );\n if (committed.status === \"superseded\") {\n // The stale window was shorter than this installation's real worst\n // case, so a peer took the claim over mid-flight and both of us may have\n // exported. No floor computation can rule this out, so it is reported\n // rather than assumed away.\n delivery = { ...delivery, deduplicated: false, superseded: true };\n diagnostics.push(\n createErrorInfo({\n code: \"delivery-claim-superseded\",\n phase: \"state\",\n detail:\n \"another process reclaimed this delivery claim before it was committed; raise staleClaimMillis\",\n details: {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": committed.attempt,\n },\n occurredAt: clock.now(),\n }),\n );\n logger.warn(\"delivery claim superseded before commit; deduplication did not hold\", {\n \"delivery.origin\": identity.origin,\n \"delivery.attempt\": committed.attempt,\n });\n }\n if (ingest.durability === \"partial\") {\n delivery = { ...delivery, partialLoss: ingest.exportRejected };\n logger.warn(\"delivery partially lost; committed to avoid re-exporting accepted spans\", {\n \"delivery.origin\": identity.origin,\n \"export.accepted\": ingest.emitted,\n \"export.rejected\": ingest.exportRejected,\n });\n }\n } else {\n // Nothing survived, so a retry cannot duplicate anything. Released rather\n // than left to age out, so the next delivery is treated as fresh\n // immediately instead of standing down for the whole stale window against\n // a process that is no longer running.\n await deduplicator.release(identity.scope, identity.callbackId);\n delivery = { ...delivery, deduplicated: false, retryable: true };\n logger.warn(\"delivery not durably recorded; claim released for retry\", {\n \"delivery.origin\": identity.origin,\n \"export.rejected\": ingest.exportRejected,\n });\n }\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n }\n }\n\n let cleanup: LifecycleCleanupReport | undefined;\n if (\n (options.sweepOnSessionEnd ?? true) &&\n ingest.identity !== undefined &&\n containsSessionEnd(ingest.events)\n ) {\n try {\n cleanup = await janitor.runOnce(ingest.identity.sessionId);\n const neverExported = cleanup.span?.expiredOpen ?? 0;\n if (neverExported > 0) {\n // A start that aged out without its end never produced a span at all.\n // Said out loud, because the alternative reading of the same silence is\n // \"nothing happened\".\n logger.warn(\"expired lifecycle spans were never completed, so never exported\", {\n \"lifecycle.expired_open_spans\": neverExported,\n });\n }\n } catch (thrown) {\n diagnostics.push(stateDiagnostic(thrown));\n }\n }\n\n return {\n ingest,\n duplicateDelivery,\n delivery,\n usageRollups,\n ...(cleanup === undefined ? {} : { cleanup }),\n diagnostics,\n };\n };\n\n const process_ = async (input: HookProcessInput): Promise<HookProcessOutcome> => {\n const diagnostics: OtelHookErrorInfo[] = [];\n const identified = identifyDelivery(input);\n const report = reportUnavailable(identified.unavailable, diagnostics);\n\n if (identified.identity === undefined) {\n return runProcess(input, undefined, report, diagnostics);\n }\n\n // Deliveries sharing a scope run one at a time, in arrival order: a claim\n // that is only decided after a peer has already exported is not a claim.\n // Unrelated scopes stay concurrent, and this is an in-process lock layered\n // over the store's cross-process one, so it never contends with itself.\n return deliveryLock.run(identified.identity.scope, () =>\n runProcess(input, identified.identity, report, diagnostics),\n );\n };\n\n const snapshots = (): readonly DeliveryHealthSnapshot[] => sink.health();\n\n let shutdownReport: Promise<HookShutdownReport> | undefined;\n const shutdown = (): Promise<HookShutdownReport> => {\n shutdownReport ??= (async (): Promise<HookShutdownReport> => {\n const raced = await Promise.race([\n hook.shutdown().then(() => \"completed\" as const),\n delay(flushTimeoutMillis),\n ]);\n if (raced === \"timeout\") {\n // Not an error the host should ever feel: the batch is either spooled\n // for a later invocation or reported unhealthy, and either way the hook\n // returns within a bounded time.\n logger.warn(\"bounded flush window elapsed before delivery completed\", {\n \"shutdown.flush_timeout_millis\": flushTimeoutMillis,\n });\n }\n return {\n flushCompleted: raced === \"completed\",\n flushTimeoutMillis,\n health: summarizeHealth(snapshots()),\n };\n })();\n return shutdownReport;\n };\n\n return {\n hook,\n config: options.config,\n stateStore,\n sink: traceSink,\n logSink,\n ...(spool === undefined ? {} : { spool }),\n ...(logSpool === undefined ? {} : { logSpool }),\n privacy,\n deduplicator,\n usageAccumulator,\n spanCorrelator,\n janitor,\n process: process_,\n shutdown,\n health: (): OverallHealth => summarizeHealth(snapshots()),\n };\n};\n","import type { DetectionPolicy } from \"../config/schema.js\";\nimport type { DetectionConfidence } from \"../model/primitives.js\";\nimport type {\n ProviderAdapter,\n ProviderContext,\n ProviderDetectionInput,\n} from \"../providers/adapter.js\";\nimport type { ProviderRegistry } from \"../providers/registry.js\";\n\nexport type AutoDetectionCandidate = {\n readonly providerId: string;\n readonly confidence: DetectionConfidence;\n};\n\nexport type AutoDetectionResult =\n | {\n readonly status: \"resolved\";\n readonly adapter: ProviderAdapter;\n readonly confidence: DetectionConfidence;\n readonly reasons: readonly string[];\n }\n | {\n readonly status: \"ambiguous\";\n readonly candidates: readonly AutoDetectionCandidate[];\n }\n | { readonly status: \"unrecognized\"; readonly reasons: readonly string[] };\n\n/**\n * Auto-detect the provider, refusing whenever more than one adapter recognizes\n * the payload at all.\n *\n * The registry's own rule — highest self-reported confidence wins, a tie is\n * ambiguous — is correct for arbitrating *one* provider's evidence, but\n * comparing confidence *across* providers is not evidence at all: each adapter\n * scores only its own schema, and several coding agents share a PascalCase hook\n * vocabulary (`SessionStart`, `PreToolUse`, `PostToolUse`, `Stop`,\n * `PreCompact`, `SubagentStop`, ...). Measured against this package's own\n * fixtures, a real Claude Code `SessionStart` payload is claimed by the Gemini\n * CLI adapter at `exact` and by the Codex adapter at `strong`, and a Claude Code\n * `Stop` payload is claimed by Codex at `strong` — so a confidence comparison\n * would silently file one agent's telemetry under another's provider id, which\n * is worse than filing it nowhere.\n *\n * So auto-detection here requires a *unique* recognizer. Overlapping payload\n * families must be disambiguated with an explicit `--provider`, which is also\n * the only way to reach `exact` confidence for a payload that carries no\n * self-identifying provider field. There is no tie-break by registration order\n * and no default provider.\n */\nexport const autoDetectProvider = (\n registry: ProviderRegistry,\n input: ProviderDetectionInput,\n context: ProviderContext,\n policy: DetectionPolicy,\n): AutoDetectionResult => {\n const detected = registry.detect(input, context, policy);\n const candidates: readonly AutoDetectionCandidate[] = detected.candidates.map((candidate) => ({\n providerId: candidate.adapter.id,\n confidence: candidate.detection.confidence,\n }));\n\n if (candidates.length > 1) {\n return { status: \"ambiguous\", candidates };\n }\n if (detected.status !== \"selected\") {\n return { status: \"unrecognized\", reasons: detected.detection.reasons };\n }\n return {\n status: \"resolved\",\n adapter: detected.adapter,\n confidence: detected.detection.confidence,\n reasons: detected.detection.reasons,\n };\n};\n","import type { PrivacyService } from \"../privacy/service.js\";\n\n/**\n * Prefixes of environment variables a provider adapter may legitimately see.\n *\n * A hook inherits the developer's whole environment, which routinely holds\n * registry tokens, cloud credentials, and CI secrets. The adapter contract hands\n * `environment` to every `detect`/`identify` call, so passing `process.env`\n * straight through would make every adapter a potential disclosure path for\n * variables that have nothing to do with telemetry. The allow-list keeps that\n * capability scoped to variables about this library or the coding agents it\n * models.\n */\nexport const PROVIDER_VISIBLE_ENVIRONMENT_PREFIXES: readonly string[] = Object.freeze([\n \"OTEL_\",\n \"CLAUDE_\",\n \"CURSOR_\",\n \"CODEX_\",\n \"GEMINI_\",\n \"ANTIGRAVITY_\",\n]);\n\n/**\n * Variables inside an allowed prefix that still carry credentials.\n *\n * The OTLP `*_HEADERS` variables hold an `authorization=...` value verbatim.\n * They are named explicitly rather than left to the privacy service's key\n * heuristics, which look for `auth_header`-style words and do not match the\n * plural `HEADERS` spelling the OpenTelemetry specification uses.\n */\nexport const PROVIDER_HIDDEN_ENVIRONMENT_NAMES: readonly string[] = Object.freeze([\n \"OTEL_EXPORTER_OTLP_HEADERS\",\n \"OTEL_EXPORTER_OTLP_TRACES_HEADERS\",\n \"OTEL_EXPORTER_OTLP_METRICS_HEADERS\",\n \"OTEL_EXPORTER_OTLP_LOGS_HEADERS\",\n]);\n\n/**\n * Narrow the process environment to what adapters may observe.\n *\n * Three filters apply, in order: the name must match an allowed prefix, it must\n * not be one of the credential-carrying names above, and it must not look like a\n * secret according to the central privacy policy.\n */\nexport const providerVisibleEnvironment = (\n env: Readonly<Record<string, string | undefined>>,\n privacy: PrivacyService,\n): Readonly<Record<string, string | undefined>> => {\n const visible: Record<string, string | undefined> = {};\n for (const [name, value] of Object.entries(env)) {\n if (!PROVIDER_VISIBLE_ENVIRONMENT_PREFIXES.some((prefix) => name.startsWith(prefix))) {\n continue;\n }\n if (PROVIDER_HIDDEN_ENVIRONMENT_NAMES.includes(name) || privacy.isSecretKey(name)) {\n continue;\n }\n visible[name] = value;\n }\n return Object.freeze(visible);\n};\n","import { createErrorInfo, type OtelHookErrorInfo } from \"../errors/index.js\";\nimport { identityClaimFieldsSchema, identityClaimSchema, type IdentityClaim } from \"../model/identity.js\";\nimport type { CliIdentityFlags } from \"./args.js\";\n\n/**\n * Turn caller-asserted identity into claims.\n *\n * Flags and an identity file are *separate* claims at the same confidence, not a\n * merged record. That is deliberate: if they disagree about a field, the core's\n * arbitration reports an identity conflict and declines attribution, which is\n * the documented posture (ADR 0001). Merging them by precedence would silently\n * pick a winner between two assertions that are equally explicit.\n *\n * Claims are contributed at `exact` confidence because they are assertions, not\n * inferences. A caller-asserted session id that disagrees with the one in the\n * provider payload is therefore also a conflict — the invocation is not\n * attributed rather than attributed to a guess.\n */\nexport type CliIdentityResolution = {\n readonly claims: readonly IdentityClaim[];\n readonly errors: readonly OtelHookErrorInfo[];\n};\n\nconst invalid = (detail: string): OtelHookErrorInfo =>\n createErrorInfo({ code: \"identity-incomplete\", phase: \"identity\", detail });\n\nexport const claimFromIdentityFlags = (flags: CliIdentityFlags): CliIdentityResolution => {\n const fields = {\n ...(flags.sessionId === undefined ? {} : { sessionId: flags.sessionId }),\n ...(flags.invocationId === undefined ? {} : { invocationId: flags.invocationId }),\n ...(flags.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: flags.parentInvocationId }),\n ...(flags.rootSessionId === undefined ? {} : { rootSessionId: flags.rootSessionId }),\n ...(flags.agentInstanceId === undefined ? {} : { agentInstanceId: flags.agentInstanceId }),\n };\n if (Object.keys(fields).length === 0) {\n return { claims: [], errors: [] };\n }\n const parsed = identityClaimFieldsSchema.safeParse(fields);\n if (!parsed.success) {\n return {\n claims: [],\n errors: [\n invalid(\n `identity flags rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`,\n ),\n ],\n };\n }\n return {\n claims: [\n identityClaimSchema.parse({ source: \"cli:flags\", confidence: \"exact\", fields: parsed.data }),\n ],\n errors: [],\n };\n};\n\n/**\n * Build a claim from the parsed contents of an identity file.\n *\n * The file is validated against `identityClaimFieldsSchema`, which is strict: an\n * unknown key is an error rather than being ignored, so a typo cannot silently\n * drop the session id it was meant to set.\n */\nexport const claimFromIdentityFile = (contents: unknown, origin: string): CliIdentityResolution => {\n const parsed = identityClaimFieldsSchema.safeParse(contents);\n if (!parsed.success) {\n return {\n claims: [],\n errors: [\n invalid(\n `identity file rejected: ${parsed.error.issues\n .map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`)\n .join(\"; \")}`,\n ),\n ],\n };\n }\n if (Object.keys(parsed.data).length === 0) {\n return { claims: [], errors: [invalid(\"identity file contained no identity fields\")] };\n }\n return {\n claims: [\n identityClaimSchema.parse({\n // The label names the source kind, never the path: a path in a claim\n // source would end up in a diagnostic.\n source: `cli:identity-file:${origin}`,\n confidence: \"exact\",\n fields: parsed.data,\n }),\n ],\n errors: [],\n };\n};\n","import type { Readable } from \"node:stream\";\n\n/**\n * Bounded stdin reader.\n *\n * A hook is invoked with one payload on stdin. Reading it without a bound would\n * let a misbehaving host (or a redirected file) grow this process's memory\n * without limit, so the read aborts as soon as the accumulated length exceeds\n * the configured cap rather than after buffering everything.\n *\n * \"Exactly one value\" is enforced by `JSON.parse`: it rejects trailing content,\n * so a concatenated stream of payloads (`{...}{...}`) is an error rather than a\n * silently truncated first object.\n */\nexport type StdinDecodeResult =\n | { readonly status: \"ok\"; readonly value: unknown; readonly byteLength: number }\n | {\n readonly status: \"error\";\n readonly code: \"empty-input\" | \"input-too-large\" | \"not-json\" | \"read-failed\";\n readonly detail: string;\n readonly byteLength?: number;\n };\n\nexport const readBoundedJson = async (\n stream: Readable,\n maxBytes: number,\n): Promise<StdinDecodeResult> => {\n const chunks: Buffer[] = [];\n let byteLength = 0;\n\n try {\n for await (const chunk of stream) {\n const buffer = typeof chunk === \"string\" ? Buffer.from(chunk, \"utf8\") : (chunk as Buffer);\n byteLength += buffer.byteLength;\n if (byteLength > maxBytes) {\n // Stop consuming immediately; the payload is already unusable and\n // draining the rest only costs memory.\n stream.destroy();\n return {\n status: \"error\",\n code: \"input-too-large\",\n detail: `stdin exceeded the ${String(maxBytes)}-byte bound`,\n byteLength,\n };\n }\n chunks.push(buffer);\n }\n } catch (thrown) {\n return {\n status: \"error\",\n code: \"read-failed\",\n // Only the error's constructor name crosses this boundary: a stream error\n // message can contain a path.\n detail: thrown instanceof Error ? `stdin read failed (${thrown.name})` : \"stdin read failed\",\n byteLength,\n };\n }\n\n const text = Buffer.concat(chunks).toString(\"utf8\");\n if (text.trim().length === 0) {\n return { status: \"error\", code: \"empty-input\", detail: \"stdin was empty\", byteLength };\n }\n\n try {\n return { status: \"ok\", value: JSON.parse(text) as unknown, byteLength };\n } catch {\n // The parser's message quotes the offending input, which may be a prompt.\n return {\n status: \"error\",\n code: \"not-json\",\n detail: \"stdin was not a single well-formed JSON value\",\n byteLength,\n };\n }\n};\n","import { CLI_USAGE, parseCliArgs } from \"./args.js\";\nimport { writeLine, type CliIo } from \"./context.js\";\nimport { runDoctorCommand } from \"./doctor.js\";\nimport { runProvidersCommand } from \"./providers.js\";\nimport { runRegistrationCommand } from \"./registration.js\";\nimport { runHookCommand } from \"./run.js\";\nimport { VERSION } from \"../version.js\";\n\n/**\n * Exit codes.\n *\n * `run` is special: it always resolves to {@link EXIT_OK}, because a hook that\n * can fail its host agent is a liability (ADR 0004). The non-hook commands are\n * ordinary CLI programs and report failure normally, so a CI job can gate on\n * `otel-hook doctor`.\n */\nexport const EXIT_OK = 0;\nexport const EXIT_UNHEALTHY = 1;\nexport const EXIT_USAGE = 2;\n\n/**\n * CLI entry point.\n *\n * Takes its argv, environment, and streams as arguments and returns an exit\n * code: nothing here reads `process`, writes to the environment, or holds state\n * between calls, so the whole surface is testable in-process and two invocations\n * in one process cannot see each other's identity.\n */\nexport const runCli = async (io: CliIo): Promise<number> => {\n const parsed = parseCliArgs(io.argv);\n\n switch (parsed.status) {\n case \"version\":\n writeLine(io.stdout, VERSION);\n return EXIT_OK;\n\n case \"help\":\n writeLine(io.stdout, CLI_USAGE);\n return EXIT_OK;\n\n case \"error\":\n for (const error of parsed.errors) {\n writeLine(io.stderr, `otel-hook: ${error}`);\n }\n writeLine(io.stderr, 'run \"otel-hook --help\" for usage');\n return EXIT_USAGE;\n\n case \"command\":\n break;\n }\n\n switch (parsed.command.name) {\n case \"run\":\n return runHookCommand(parsed.command, io);\n case \"doctor\":\n return runDoctorCommand(parsed.command, io);\n case \"providers\":\n return Promise.resolve(runProvidersCommand(parsed.command, io));\n case \"setup\":\n case \"diagnose\":\n case \"uninstall\":\n return runRegistrationCommand(parsed.command, io);\n }\n};\n","#!/usr/bin/env node\n\nimport { runCli } from \"./cli/main.js\";\n\n/**\n * Thin process wrapper.\n *\n * All behaviour lives in `runCli`, which is handed its argv, environment, and\n * streams; this file is the only place that touches `process` at all, and it\n * never writes to `process.env`.\n */\nconst flushStream = (stream: NodeJS.WriteStream): Promise<void> =>\n // Unconditional: the callback fires once everything queued before it has been\n // handed to the OS. Checking `writableLength` first is not equivalent — a\n // pipe's queue can read as empty while bytes are still in flight, and a\n // truncated hook response would corrupt the host agent's protocol.\n new Promise<void>((resolve) => {\n stream.write(\"\", () => resolve());\n });\n\nconst main = async (): Promise<void> => {\n const argv = process.argv.slice(2);\n let code: number;\n try {\n code = await runCli({\n argv,\n env: process.env,\n stdin: process.stdin,\n stdout: process.stdout,\n stderr: process.stderr,\n });\n } catch (thrown) {\n // Unreachable by contract; still contained, because an unhandled rejection\n // here would surface to the host agent as a crashed hook.\n process.stderr.write(\n `otel-hook: unexpected failure (${thrown instanceof Error ? thrown.name : typeof thrown})\\n`,\n );\n code = 0;\n }\n\n await flushStream(process.stdout);\n await flushStream(process.stderr);\n\n if (argv[0] === \"run\") {\n // A bounded flush may have given up on a collector that is still holding a\n // socket open. Waiting for the event loop to drain would make the host agent\n // pay for that, so the hook path exits explicitly once its streams are out.\n process.exit(code);\n }\n // The diagnostic commands are ordinary programs: let Node exit naturally so\n // nothing they wrote can be cut short.\n process.exitCode = code;\n};\n\nawait main();\n"],"mappings":";;;AAAA,SAAS,KAAAA,UAAS;;;ACAlB,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;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ACA,WAAO;AAAA,EACT;AAEA,QAAM,YAAY,QAAQ,MAAM;AAChC,QAAM,YAAY,QAAQ,MAAM;AAEhC,MAAI,KAAK,CAAC,MAAM,OAAO;AAIrB,YAAQ,KAAK,IAAI;AAAA,EACnB;AAGA,UAAQ,WAAW;AACrB;AAEA,MAAM,KAAK;","names":["z","z","z","policy","z","z","z","z","z","z","z","path","parsed","z","z","z","z","z","z","z","bounded","path","z","z","parsed","z","z","z","z","z","z","z","detect","identify","parse","hookResponse","z","commonFields","preToolUsePayloadSchema","postToolUsePayloadSchema","stopPayloadSchema","z","z","z","event","sessionStartPayloadSchema","sessionEndPayloadSchema","preToolUsePayloadSchema","postToolUsePayloadSchema","postToolUseFailurePayloadSchema","subagentStartPayloadSchema","subagentStopPayloadSchema","preCompactPayloadSchema","stopPayloadSchema","isPlainObject","deliveryComponents","UNKNOWN_MODEL","detect","identify","parse","hookResponse","z","BUILT_IN_TOOL_KIND","detect","identify","parse","hookResponse","readFile","path","createHash","resolve","readFile","randomBytes","mkdir","readFile","readdir","rename","unlink","writeFile","path","isErrnoException","mkdir","readdir","randomBytes","writeFile","rename","unlink","readFile","isPlainObject","TRACE_ID_PATTERN","SPAN_ID_PATTERN","isFiniteNonNegative","isBoundedString","isPlainObject","TraceFlags","ExportResultCode","TraceFlags","ATTR_ERROR_TYPE","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_REQUEST_MODEL","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","ATTR_SESSION_ID","createHash","createHash","event","ATTR_OTELHOOK_INVOCATION_ID","ATTR_OTELHOOK_PROVIDER_ID","ATTR_OTELHOOK_PROVIDER_VERSION","ATTR_OTELHOOK_WORKSPACE_ID","ATTR_OTELHOOK_OUTCOME","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_OTELHOOK_COMPACTION_TRIGGER","codePointLength","sliceCodePoints","event","event","identityAttributes","ATTR_SESSION_ID","ATTR_OTELHOOK_INVOCATION_ID","ATTR_OTELHOOK_PROVIDER_ID","ATTR_OTELHOOK_PROVIDER_VERSION","ATTR_OTELHOOK_WORKSPACE_ID","ATTR_OTELHOOK_AGENT_NAME","ATTR_OTELHOOK_AGENT_VERSION","ATTR_GEN_AI_REQUEST_MODEL","ATTR_OTELHOOK_OUTCOME","usageAttributes","ATTR_GEN_AI_OPERATION_NAME","ATTR_GEN_AI_SYSTEM","ATTR_GEN_AI_RESPONSE_MODEL","ATTR_GEN_AI_TOOL_NAME","ATTR_GEN_AI_TOOL_CALL_ID","ATTR_OTELHOOK_TOOL_KIND","ATTR_OTELHOOK_DELEGATION_DEPTH","ATTR_OTELHOOK_COMPACTION_TRIGGER","ATTR_ERROR_TYPE","ATTR_GEN_AI_USAGE_INPUT_TOKENS","ATTR_GEN_AI_USAGE_OUTPUT_TOKENS","codePointLength","sliceCodePoints","hrTime","TraceFlags","TraceFlags","resolve","chunk","createDisabledSink","resolve","isPlainObject","event","isPlainObject","event","buildEntry","isPlainObject","buildEntry","event","isPlainObject","event","path","randomBytes","mkdir","open","readFile","rename","unlink","path","isErrnoException","resolve","randomBytes","mkdir","open","readFile","rename","stat","unlink","path","isErrnoException","delay","resolve","readFile","path","readFile","event","os","path","path","randomBytes","randomBytes","owner","result","event","usageKey","z","createHash","createHash","z","event","batch","DEFAULT_STALE_CLAIM_MILLIS","delay","resolve","event","options","chunk","hookResponse","resolve"]}