@osfactory/otel-hook 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +37 -9
- package/dist/cli.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.js +37 -9
- package/dist/index.js.map +1 -1
- package/dist/install.js +6 -1
- package/dist/install.js.map +1 -1
- package/dist/integration.js +7 -2
- package/dist/integration.js.map +1 -1
- package/dist/lifecycle.js +1 -1
- package/dist/lifecycle.js.map +1 -1
- package/dist/providers.js +36 -8
- package/dist/providers.js.map +1 -1
- package/dist/runtime.js +6 -1
- package/dist/runtime.js.map +1 -1
- package/dist/telemetry.js +1 -1
- package/dist/telemetry.js.map +1 -1
- package/dist/testing.js +36 -8
- package/dist/testing.js.map +1 -1
- package/package.json +1 -1
package/dist/install.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/providers/antigravity/payload.ts","../src/providers/antigravity/registration.ts","../src/providers/hook-document.ts","../src/providers/claude/schema.ts","../src/providers/claude/registration.ts","../src/providers/codex/payload.ts","../src/providers/codex/registration.ts","../src/providers/cursor/payload.ts","../src/providers/cursor/registration.ts","../src/providers/gemini/schema.ts","../src/providers/gemini/setup.ts","../src/errors/index.ts","../src/model/primitives.ts","../src/errors/taxonomy.ts","../src/model/identity.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/model/content.ts","../src/model/extensions.ts","../src/model/usage.ts","../src/model/version.ts","../src/providers/antigravity/delivery.ts","../src/providers/antigravity/adapter.ts","../src/providers/claude/detect.ts","../src/providers/codex/version.ts","../src/providers/gemini/delivery.ts","../src/providers/gemini/tool-kind.ts","../src/providers/gemini/adapter.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/install/index.ts"],"sourcesContent":["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 { 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 { 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 {\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 { 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 {\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 { 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 { 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 { 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 {\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 { 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/** 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\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport 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 { 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 { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import 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","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 { 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","/**\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 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 { 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 { 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","/**\n * Registration lifecycle: pure planners, plus the safe application of a plan.\n *\n * Two layers, deliberately separated:\n *\n * - **Planners** (`providers/<id>/registration.ts`, re-exported here) are pure.\n * They take the *already parsed* contents of a provider's configuration\n * document and return the document to write back plus whether anything\n * changed. ADR 0003 keeps a provider adapter away from the filesystem, and a\n * pure merge is testable against every \"already registered\", \"registered with\n * an older command\", and \"unrelated hooks present\" case without a temporary\n * directory.\n * - **Lifecycle** (`lifecycle.ts`) reads and writes real files: locking a\n * third party's config for the read-merge-write, preserving its formatting,\n * writing atomically, and refusing rather than clobbering when the document\n * is not what the provider documents.\n *\n * Registration is only offered for providers whose configuration contract this\n * repository has verified. {@link PROVIDER_REGISTRATION_SUPPORT} names the\n * others and says exactly what would unblock them — an invented settings shape\n * written into a real `settings.json` is worse than no installer at all.\n */\nimport { ANTIGRAVITY_PROVIDER_ID } from \"../providers/antigravity/adapter.js\";\nimport {\n mergeAntigravityHookRegistration,\n readAntigravityHookRegistrations,\n removeAntigravityHookRegistration,\n type AntigravityHookCommandEntry,\n type MergeAntigravityHookRegistrationInput,\n type MergeAntigravityHookRegistrationResult,\n type RemoveAntigravityHookRegistrationInput,\n} from \"../providers/antigravity/registration.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"../providers/claude/detect.js\";\nimport {\n CLAUDE_HOOK_EVENTS_MODELLED,\n CLAUDE_REGISTRABLE_HOOK_EVENTS,\n CLAUDE_UNREGISTERED_HOOK_EVENTS,\n mergeClaudeHookRegistration,\n readClaudeHookRegistrations,\n removeClaudeHookRegistration,\n type ClaudeHookRegistrationOptions,\n type ClaudeHookRemovalOptions,\n} from \"../providers/claude/registration.js\";\nimport {\n CODEX_HOOK_EVENTS_MODELLED,\n CODEX_REGISTRABLE_HOOK_EVENTS,\n CODEX_UNREGISTERED_HOOK_EVENTS,\n mergeCodexHookRegistration,\n readCodexHookRegistrations,\n readCodexHooksFeatureFlag,\n removeCodexHookRegistration,\n type CodexHookRegistrationOptions,\n type CodexHookRemovalOptions,\n type CodexHooksFeatureFlag,\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_HOOK_EVENTS_MODELLED,\n CURSOR_HOOKS_DOCUMENT_VERSION,\n CURSOR_REGISTRABLE_HOOK_EVENTS,\n CURSOR_UNREGISTERED_HOOK_EVENTS,\n mergeCursorHookRegistration,\n readCursorHookRegistrations,\n removeCursorHookRegistration,\n type CursorHookCommandEntry,\n type CursorHookDocumentResult,\n type CursorHookRemovalInput,\n type MergeCursorHookRegistrationInput,\n} from \"../providers/cursor/registration.js\";\nimport { GEMINI_PROVIDER_ID } from \"../providers/gemini/adapter.js\";\nimport {\n mergeGeminiHookRegistration,\n readGeminiHookRegistrations,\n removeGeminiHookRegistration,\n type GeminiHookCommandEntry,\n type GeminiHookMatcherEntry,\n type GeminiHooksSettings,\n type MergeGeminiHookResult,\n type RegisterGeminiHookOptions,\n type RemoveGeminiHookOptions,\n} from \"../providers/gemini/setup.js\";\nimport {\n mergeNestedHookRegistration,\n readNestedHookRegistrations,\n removeNestedHookRegistrations,\n type CommandHookEntry,\n type HookDocumentAction,\n type HookDocumentChange,\n type HookDocumentConflict,\n type HookGroupEntry,\n type HookHandlerPredicate,\n type MergeNestedHookInput,\n type NestedHookDocumentResult,\n type RemoveNestedHookInput,\n} from \"../providers/hook-document.js\";\nimport { findRegistrationPlanner, managedHookPredicate } from \"./planners.js\";\nimport { findRegistrationSupport } from \"./support.js\";\n\nexport {\n CLAUDE_HOOK_EVENTS_MODELLED,\n CLAUDE_REGISTRABLE_HOOK_EVENTS,\n CLAUDE_UNREGISTERED_HOOK_EVENTS,\n CODEX_HOOK_EVENTS_MODELLED,\n CODEX_REGISTRABLE_HOOK_EVENTS,\n CODEX_UNREGISTERED_HOOK_EVENTS,\n CURSOR_HOOK_EVENTS_MODELLED,\n CURSOR_HOOKS_DOCUMENT_VERSION,\n CURSOR_REGISTRABLE_HOOK_EVENTS,\n CURSOR_UNREGISTERED_HOOK_EVENTS,\n mergeAntigravityHookRegistration,\n mergeClaudeHookRegistration,\n mergeCodexHookRegistration,\n mergeCursorHookRegistration,\n mergeGeminiHookRegistration,\n mergeNestedHookRegistration,\n readAntigravityHookRegistrations,\n readClaudeHookRegistrations,\n readCodexHookRegistrations,\n readCodexHooksFeatureFlag,\n readCursorHookRegistrations,\n readGeminiHookRegistrations,\n readNestedHookRegistrations,\n removeAntigravityHookRegistration,\n removeClaudeHookRegistration,\n removeCodexHookRegistration,\n removeCursorHookRegistration,\n removeGeminiHookRegistration,\n removeNestedHookRegistrations,\n type AntigravityHookCommandEntry,\n type ClaudeHookRegistrationOptions,\n type ClaudeHookRemovalOptions,\n type CodexHookRegistrationOptions,\n type CodexHookRemovalOptions,\n type CodexHooksFeatureFlag,\n type CommandHookEntry,\n type CursorHookCommandEntry,\n type CursorHookDocumentResult,\n type CursorHookRemovalInput,\n type GeminiHookCommandEntry,\n type GeminiHookMatcherEntry,\n type GeminiHooksSettings,\n type HookDocumentAction,\n type HookDocumentChange,\n type HookDocumentConflict,\n type HookGroupEntry,\n type HookHandlerPredicate,\n type MergeAntigravityHookRegistrationInput,\n type MergeAntigravityHookRegistrationResult,\n type MergeCursorHookRegistrationInput,\n type MergeGeminiHookResult,\n type MergeNestedHookInput,\n type NestedHookDocumentResult,\n type RegisterGeminiHookOptions,\n type RemoveAntigravityHookRegistrationInput,\n type RemoveGeminiHookOptions,\n type RemoveNestedHookInput,\n};\n\nexport {\n checkManagedMarker,\n DEFAULT_MANAGED_COMMAND_MARKER,\n MANAGED_HOOK_NAME,\n MANAGED_MARKER_REJECTION_DETAIL,\n MANAGED_MARKER_TOKEN,\n REGISTRATION_PLANNERS,\n findRegistrationPlanner,\n managedHookPredicate,\n type ManagedMarkerRejection,\n type ProviderRegistrationPlanner,\n type RegistrationPlanInput,\n type RegistrationRemovalInput,\n} from \"./planners.js\";\n\nexport {\n PROVIDER_REGISTRATION_SUPPORT,\n SUPPORTED_REGISTRATION_PROVIDER_IDS,\n findRegistrationSupport,\n type ProviderRegistrationSupport,\n} from \"./support.js\";\n\nexport {\n PROVIDERS_WITHOUT_VERIFIED_LOCATION,\n PROVIDERS_WITH_VERIFIED_LOCATION,\n PROVIDER_INSTALL_LOCATIONS,\n REGISTRATION_SCOPES,\n findInstallLocation,\n resolveInstallPath,\n type InstallLocation,\n type RegistrationScope,\n type ScopeRoots,\n} from \"./scopes.js\";\n\nexport {\n DEFAULT_DOCUMENT_FORMAT,\n detectDocumentFormat,\n readJsonDocument,\n renderJsonDocument,\n writeDocumentAtomically,\n type JsonDocumentFormat,\n type ReadDocumentResult,\n} from \"./document.js\";\n\nexport {\n FileLockTimeoutError,\n lockPathFor,\n withFileLock,\n type FileLockOptions,\n} from \"./file-lock.js\";\n\nexport {\n defaultHookCommand,\n runRegistrationLifecycle,\n type RegistrationAction,\n type RegistrationLifecycleRequest,\n type RegistrationOutcome,\n type RegistrationOutcomeStatus,\n type RegistrationReport,\n} from \"./lifecycle.js\";\n\nexport type PlanProviderRegistrationInput =\n | {\n readonly providerId: typeof GEMINI_PROVIDER_ID;\n /** Parsed contents of the provider's settings document, if one exists. */\n readonly existing?: unknown;\n readonly options: RegisterGeminiHookOptions;\n }\n | {\n readonly providerId: typeof ANTIGRAVITY_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<MergeAntigravityHookRegistrationInput, \"existing\">;\n }\n | {\n readonly providerId: typeof CLAUDE_CODE_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<ClaudeHookRegistrationOptions, \"existing\" | \"identifies\"> & {\n readonly identifies?: HookHandlerPredicate;\n };\n }\n | {\n readonly providerId: typeof CODEX_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<CodexHookRegistrationOptions, \"existing\" | \"identifies\"> & {\n readonly identifies?: HookHandlerPredicate;\n };\n }\n | {\n readonly providerId: typeof CURSOR_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<MergeCursorHookRegistrationInput, \"existing\" | \"identifies\"> & {\n readonly identifies?: HookHandlerPredicate;\n };\n }\n | {\n readonly providerId: string;\n readonly existing?: unknown;\n readonly options?: unknown;\n };\n\nexport type PlanProviderRegistrationResult =\n | {\n readonly status: \"planned\";\n readonly providerId: string;\n /** Write this back verbatim; unrelated keys are carried through unchanged. */\n readonly document: Record<string, unknown>;\n /** False when the document already contained exactly this registration. */\n readonly changed: boolean;\n readonly changes: readonly HookDocumentChange[];\n }\n | {\n /** The document is not the shape this provider documents; nothing was changed. */\n readonly status: \"conflict\";\n readonly providerId: string;\n readonly conflicts: readonly HookDocumentConflict[];\n }\n | { readonly status: \"unsupported\"; readonly providerId: string; readonly reason: string }\n | { readonly status: \"invalid\"; readonly providerId: string; readonly reason: string };\n\n/**\n * Plan one provider's hook registration.\n *\n * Idempotent: calling it again with the same `options` against the document it\n * returned yields `changed: false` and an identical document.\n */\nexport const planProviderRegistration = (\n input: PlanProviderRegistrationInput,\n): PlanProviderRegistrationResult => {\n const support = findRegistrationSupport(input.providerId);\n const planner = findRegistrationPlanner(input.providerId);\n if (planner === undefined || support?.supported !== true) {\n return {\n status: \"unsupported\",\n providerId: input.providerId,\n reason: support?.reason ?? `no registration planner is available for provider \"${input.providerId}\"`,\n };\n }\n\n const options = (input.options ?? {}) as {\n readonly command?: unknown;\n readonly events?: readonly string[];\n readonly matcher?: string;\n readonly timeout?: number;\n readonly timeoutSeconds?: number;\n readonly identifies?: HookHandlerPredicate;\n };\n if (typeof options.command !== \"string\" || options.command.length === 0) {\n return {\n status: \"invalid\",\n providerId: input.providerId,\n reason: `planning a \"${input.providerId}\" registration requires a non-empty options.command`,\n };\n }\n\n const timeoutSeconds = options.timeoutSeconds ?? options.timeout;\n const result = planner.merge({\n ...(input.existing === undefined ? {} : { existing: input.existing }),\n command: options.command,\n ...(options.events === undefined ? {} : { events: options.events }),\n ...(options.matcher === undefined ? {} : { matcher: options.matcher }),\n ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),\n identifies: options.identifies ?? managedHookPredicate(options.command),\n });\n\n if (result.conflicts.length > 0) {\n return { status: \"conflict\", providerId: input.providerId, conflicts: result.conflicts };\n }\n return {\n status: \"planned\",\n providerId: input.providerId,\n document: result.document,\n changed: result.changed,\n changes: result.changes,\n };\n};\n"],"mappings":";AAAA,SAAS,SAAS;AAkBX,IAAM,+BAA+B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,sBAAsB,EAAE,KAAK,4BAA4B;AAMxD,IAAM,6BAA6B,EAAE,OAAO,EAAE,eAAe,oBAAoB,CAAC,EAAE,YAAY;AAEvG,IAAM,eAAe;AAAA,EACnB,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChC,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,IAAI,EAAE;AAAA,EACjD,eAAe,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,CAAC;AAAA;AAAA,EAErC,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAAA;AAAA,EAE3C,uBAAuB,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AACpD;AAEO,IAAM,6BAA6B,EAAE,OAAO;AAAA,EACjD,eAAe,EAAE,QAAQ,eAAe;AAAA,EACxC,GAAG;AAAA,EACH,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAC3C,CAAC;AAGM,IAAM,8BAA8B,EAAE,OAAO;AAAA,EAClD,eAAe,EAAE,QAAQ,gBAAgB;AAAA,EACzC,GAAG;AAAA,EACH,cAAc,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,SAAS;AAC3C,CAAC;AAGM,IAAM,0BAA0B,EAAE,OAAO;AAAA,EAC9C,eAAe,EAAE,QAAQ,YAAY;AAAA,EACrC,GAAG;AAAA,EACH,SAAS,EAAE,OAAO,EAAE,I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AA,IAChB,SAAS,OAAO;AAAA,EAClB;AACF;","names":["event","isPlainObject","event","z","commonFields","preToolUsePayloadSchema","postToolUsePayloadSchema","stopPayloadSchema","z","buildEntry","z","z","sessionStartPayloadSchema","sessionEndPayloadSchema","preToolUsePayloadSchema","postToolUsePayloadSchema","postToolUseFailurePayloadSchema","subagentStartPayloadSchema","subagentStopPayloadSchema","preCompactPayloadSchema","stopPayloadSchema","isPlainObject","buildEntry","event","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","event","z","isPlainObject","event","path","resolve","randomBytes","mkdir","open","readFile","rename","stat","unlink","path","isErrnoException","delay","resolve","readFile","path","readFile","event"]}
|
|
1
|
+
{"version":3,"sources":["../src/providers/antigravity/payload.ts","../src/providers/antigravity/registration.ts","../src/providers/hook-document.ts","../src/providers/claude/schema.ts","../src/providers/claude/registration.ts","../src/providers/codex/payload.ts","../src/providers/codex/registration.ts","../src/providers/cursor/payload.ts","../src/providers/cursor/registration.ts","../src/providers/gemini/schema.ts","../src/providers/gemini/setup.ts","../src/errors/index.ts","../src/model/primitives.ts","../src/errors/taxonomy.ts","../src/model/identity.ts","../src/providers/adapter.ts","../src/model/events.ts","../src/model/content.ts","../src/model/extensions.ts","../src/model/usage.ts","../src/model/version.ts","../src/providers/antigravity/delivery.ts","../src/providers/antigravity/adapter.ts","../src/providers/claude/detect.ts","../src/providers/codex/version.ts","../src/providers/gemini/delivery.ts","../src/providers/gemini/tool-kind.ts","../src/providers/gemini/adapter.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/install/index.ts"],"sourcesContent":["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 { 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 { 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 {\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 { 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 {\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 { z } from \"zod\";\n\n/**\n * Cursor agent-hook payload contract.\n *\n * ## Provenance\n *\n * Nothing in this module is invented. Every field, spelling, and unit below is\n * established by one or both of:\n *\n * 1. **Cursor's published hooks reference** — `cursor.com/docs/agent/hooks` and\n * `cursor.com/docs/hooks.md` (two URLs serving the same reference; both read\n * 2026-07-29). Source of the event-name list, the shared envelope, each\n * event's input fields, each event's stdout response, the `hooks.json`\n * schema, exit-code semantics, and the statement that `duration` and\n * `duration_ms` are milliseconds while `timeout` is seconds.\n * 2. **Real redacted captures** — `colinsurprenant/director`, under\n * `hack/canary/cursor-cli/findings/`: two Cursor CLI runs (`2026.07.17-3e2a980`,\n * captured 2026-07-21 and 2026-07-22) and two Cursor IDE runs (`3.12.17`,\n * captured 2026-07-21), each registering the full agent-hook set and recording\n * the exact key list of all 54 payload files it saved. Source of the fields\n * the reference omits, of which keys are actually optional, and of the two\n * lifecycle facts in \"Surface dependence\" below.\n *\n * The redacted fixtures under `fixtures/parity/cursor/` restate those captured\n * shapes with synthetic values; their provenance sidecars name this capture set.\n * No real path, email, transcript, prompt, or credential is copied into this\n * repository — see `CLAUDE.md`.\n *\n * ## Envelope\n *\n * Keys are snake_case throughout, and there is exactly one generation of the\n * shape: no camelCase variant and no legacy alias table is documented or\n * observed, so none is modelled. **There is no timestamp field anywhere** — not\n * in the reference, and not in any captured payload's key list — so the adapter\n * reads `occurredAt` from the injected clock, as the Claude Code adapter does.\n *\n * ## Surface dependence (captured, not documented)\n *\n * The same `hooks.json` produces different event subsets on Cursor's two\n * surfaces, which is why the registration planner's default set is chosen the\n * way it is:\n *\n * - `stop` and `afterAgentResponse` fired in the IDE runs and in neither CLI\n * run; `sessionEnd` fired in both CLI runs and in neither IDE run.\n * - One shell invocation fires **four** hooks. The CLI capture's `fired.log`\n * records `preToolUse`, `beforeShellExecution`, `afterShellExecution`,\n * `postToolUse` in that order for a single `printenv` call, with\n * `afterShellExecution` and `postToolUse` reporting the identical\n * `duration` of 169.812. Registering both pairs would report one tool call\n * twice.\n *\n * ## Forward compatibility\n *\n * Event objects are `z.object` (unknown keys stripped), not `z.strictObject`:\n * Cursor adds payload fields between releases — the reference already documents\n * a `preToolUse.agent_message` that no captured payload carries — and a\n * telemetry hook that rejects a payload for gaining a field fails closed on the\n * one thing it should tolerate.\n */\n\nexport const CURSOR_PROVIDER_ID = \"cursor\" as const;\n\n/**\n * Agent-session hook events this adapter interprets, in Cursor's own spelling.\n *\n * The reference groups its hooks as \"agent\", \"tab\", and \"app lifecycle\". Only\n * the agent group is here; see {@link CURSOR_UNMODELLED_HOOK_EVENT_NAMES}.\n */\nexport const CURSOR_HOOK_EVENT_NAMES = [\n \"sessionStart\",\n \"sessionEnd\",\n \"beforeSubmitPrompt\",\n \"afterAgentResponse\",\n \"afterAgentThought\",\n \"preToolUse\",\n \"postToolUse\",\n \"postToolUseFailure\",\n \"beforeShellExecution\",\n \"afterShellExecution\",\n \"beforeMCPExecution\",\n \"afterMCPExecution\",\n \"beforeReadFile\",\n \"afterFileEdit\",\n \"subagentStart\",\n \"subagentStop\",\n \"preCompact\",\n \"stop\",\n] as const;\nexport type CursorHookEventName = (typeof CURSOR_HOOK_EVENT_NAMES)[number];\n\n/**\n * Event names Cursor documents that this adapter deliberately does not model,\n * each with the reason. Recognized by name so a payload carrying one is\n * reported as \"known, unmodelled\" rather than as an unrecognized provider.\n */\nexport const CURSOR_UNMODELLED_HOOK_EVENT_NAMES: Readonly<Record<string, string>> = Object.freeze({\n beforeTabFileRead:\n \"a Tab (inline-completion) hook, not an agent-session hook; it belongs to no generation or tool lifecycle this model expresses\",\n afterTabFileEdit: \"a Tab (inline-completion) hook, as above\",\n workspaceOpen:\n \"an app-lifecycle hook that the reference states omits conversation_id, generation_id, model, session_id, and transcript_path, so it carries no session to attribute telemetry to\",\n});\n\n/**\n * Events whose stdout Cursor reads a decision from, and the field it reads.\n *\n * Taken from the reference's per-event \"Output\" sections. `beforeSubmitPrompt`\n * is the one event keyed `continue` rather than `permission`; the shell and MCP\n * gates additionally accept `\"ask\"`, which this tool never emits.\n */\nexport const CURSOR_DECISION_EVENTS: Readonly<Record<string, \"permission\" | \"continue\">> =\n Object.freeze({\n preToolUse: \"permission\",\n beforeShellExecution: \"permission\",\n beforeMCPExecution: \"permission\",\n beforeReadFile: \"permission\",\n subagentStart: \"permission\",\n beforeSubmitPrompt: \"continue\",\n });\n\n/** `[{ id, value }]`, per the reference's shared envelope. */\nconst modelParamSchema = z.object({\n id: z.string(),\n value: z.string(),\n});\nexport type CursorModelParam = z.infer<typeof modelParamSchema>;\n\nconst attachmentSchema = z.object({\n type: z.string().optional(),\n file_path: z.string().optional(),\n});\n\n/** `{ old_string, new_string }` pairs. Content, never exported — see the adapter. */\nconst fileEditSchema = z.object({\n old_string: z.string().optional(),\n new_string: z.string().optional(),\n});\n\n/**\n * Token counters observed on `afterAgentResponse` and `stop` in the IDE\n * captures. Absent from the published reference, which is why they are all\n * optional and why {@link CURSOR_USAGE_INCLUSIVITY_NOTE} states the one reading\n * the captures do not settle.\n */\nconst usageFields = {\n input_tokens: z.number().int().min(0).optional(),\n output_tokens: z.number().int().min(0).optional(),\n cache_read_tokens: z.number().int().min(0).optional(),\n cache_write_tokens: z.number().int().min(0).optional(),\n};\n\nexport const CURSOR_USAGE_INCLUSIVITY_NOTE =\n \"Cursor does not document its token counters, so whether input_tokens already includes cache_read_tokens \" +\n \"cannot be settled from the reference. Every captured sample has cache_read_tokens strictly below \" +\n \"input_tokens (28384/43859, 7040/21033, 77920/94622) with a stable ~15-17k remainder as the cached prefix \" +\n \"grows, which is what an inclusive counter looks like; the adapter therefore reads input_tokens as the \" +\n \"canonical inclusive total and cache_read_tokens as a subset of it. Where a payload contradicts that \" +\n \"reading, the adapter drops the breakdown rather than reporting a total it cannot justify.\";\n\n/**\n * Fields the reference lists as present on every agent hook.\n *\n * `conversation_id` is the session identity every captured agent payload\n * carries, and `session_id` repeats it in every capture — see\n * {@link cursorSessionId} for why the schema no longer hard-requires the\n * former by itself. `cwd` is *not* `.min(1)` — the CLI captures report\n * `\"cwd\": \"\"` for a workspace-rooted call, and rejecting an empty string would\n * drop the whole event over a field the adapter never reads for identity.\n *\n * `user_email` and `transcript_path` are declared so they parse rather than\n * being silently stripped, and are then never read by any code path. They are a\n * real address and a real filesystem path; `tests/providers/cursor` asserts\n * neither reaches a sink.\n */\nconst envelopeShape = {\n // Not `.min(1)`: see `cursorSessionId`. A payload naming neither\n // `conversation_id` nor `session_id` is still rejected — by\n // `recognizeCursorPayload`'s post-parse check — but rejecting it here would\n // fail the whole discriminated union on a field the adapter can source from\n // either name.\n conversation_id: z.string().optional(),\n generation_id: z.string().optional(),\n session_id: z.string().optional(),\n model: z.string().optional(),\n model_id: z.string().optional(),\n model_params: z.array(modelParamSchema).max(64).optional(),\n cursor_version: z.string().optional(),\n workspace_roots: z.array(z.string()).max(64).optional(),\n cwd: z.string().optional(),\n /** Never propagated. */\n user_email: z.string().nullish(),\n /** Never propagated. */\n transcript_path: z.string().nullish(),\n};\n\nconst event = <TName extends CursorHookEventName, TShape extends z.ZodRawShape>(\n name: TName,\n shape: TShape,\n) => z.object({ ...envelopeShape, hook_event_name: z.literal(name), ...shape });\n\nconst sessionStartPayloadSchema = event(\"sessionStart\", {\n is_background_agent: z.boolean().optional(),\n composer_mode: z.string().optional(),\n});\n\n/**\n * `reason` and `final_status` are free strings rather than enums on purpose.\n * The reference lists five reasons (`completed`, `aborted`, `error`,\n * `window_close`, `user_close`) and the adapter maps exactly those; a sixth\n * Cursor adds later must degrade to `unknown`, not reject the event.\n */\nconst sessionEndPayloadSchema = event(\"sessionEnd\", {\n reason: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n is_background_agent: z.boolean().optional(),\n final_status: z.string().optional(),\n error_message: z.string().optional(),\n});\n\nconst beforeSubmitPromptPayloadSchema = event(\"beforeSubmitPrompt\", {\n prompt: z.string().optional(),\n attachments: z.array(attachmentSchema).max(256).optional(),\n composer_mode: z.string().optional(),\n});\n\nconst afterAgentResponsePayloadSchema = event(\"afterAgentResponse\", {\n text: z.string().optional(),\n ...usageFields,\n});\n\nconst afterAgentThoughtPayloadSchema = event(\"afterAgentThought\", {\n text: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n});\n\nconst preToolUsePayloadSchema = event(\"preToolUse\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n agent_message: z.string().optional(),\n});\n\n/**\n * `tool_output` is `z.unknown()` because both shapes occur: the CLI capture\n * reports an object (`{ output, exitCode }`), the IDE capture a JSON-encoded\n * string, and the reference documents the string. Neither is parsed for meaning.\n */\nconst postToolUsePayloadSchema = event(\"postToolUse\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_output: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n duration: z.number().min(0).optional(),\n});\n\nconst postToolUseFailurePayloadSchema = event(\"postToolUseFailure\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n tool_use_id: z.string().optional(),\n error_message: z.string().optional(),\n failure_type: z.string().optional(),\n duration: z.number().min(0).optional(),\n is_interrupt: z.boolean().optional(),\n});\n\nconst beforeShellExecutionPayloadSchema = event(\"beforeShellExecution\", {\n command: z.string(),\n sandbox: z.boolean().optional(),\n});\n\n/**\n * No exit status. The reference lists `command`, `output`, `duration`, and\n * `sandbox`, the captures confirm exactly those, and neither carries an exit\n * code — so the adapter reports this tool end with outcome `unknown` rather\n * than assuming success.\n */\nconst afterShellExecutionPayloadSchema = event(\"afterShellExecution\", {\n command: z.string(),\n output: z.string().optional(),\n duration: z.number().min(0).optional(),\n sandbox: z.boolean().optional(),\n});\n\nconst beforeMcpExecutionPayloadSchema = event(\"beforeMCPExecution\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n url: z.string().optional(),\n command: z.string().optional(),\n});\n\n/** As with the shell pair: `result_json` is opaque, and there is no status field. */\nconst afterMcpExecutionPayloadSchema = event(\"afterMCPExecution\", {\n tool_name: z.string().min(1),\n tool_input: z.unknown().optional(),\n result_json: z.string().optional(),\n duration: z.number().min(0).optional(),\n});\n\nconst beforeReadFilePayloadSchema = event(\"beforeReadFile\", {\n file_path: z.string(),\n content: z.string().optional(),\n attachments: z.array(attachmentSchema).max(256).optional(),\n});\n\nconst afterFileEditPayloadSchema = event(\"afterFileEdit\", {\n file_path: z.string(),\n edits: z.array(fileEditSchema).max(1024).optional(),\n});\n\nconst subagentStartPayloadSchema = event(\"subagentStart\", {\n subagent_id: z.string().optional(),\n subagent_type: z.string().optional(),\n task: z.string().optional(),\n parent_conversation_id: z.string().optional(),\n tool_call_id: z.string().optional(),\n subagent_model: z.string().optional(),\n is_parallel_worker: z.boolean().optional(),\n git_branch: z.string().optional(),\n});\n\n/**\n * Carries no subagent identifier. The reference gives `subagentStart` a\n * `subagent_id` and gives `subagentStop` only `subagent_type`, so the two\n * cannot be paired — which is why the adapter ignores both rather than emitting\n * a `subagent.start` that nothing can close. No capture contains either event.\n */\nconst subagentStopPayloadSchema = event(\"subagentStop\", {\n subagent_type: z.string().optional(),\n status: z.string().optional(),\n task: z.string().optional(),\n description: z.string().optional(),\n summary: z.string().optional(),\n duration_ms: z.number().min(0).optional(),\n message_count: z.number().int().min(0).optional(),\n tool_call_count: z.number().int().min(0).optional(),\n loop_count: z.number().int().min(0).optional(),\n modified_files: z.array(z.string()).max(1024).optional(),\n agent_transcript_path: z.string().nullish(),\n});\n\n/** `trigger` is `auto | manual` per the reference; mapped in the adapter. */\nconst preCompactPayloadSchema = event(\"preCompact\", {\n trigger: z.string().optional(),\n context_usage_percent: z.number().optional(),\n context_tokens: z.number().int().min(0).optional(),\n context_window_size: z.number().int().min(0).optional(),\n message_count: z.number().int().min(0).optional(),\n messages_to_compact: z.number().int().min(0).optional(),\n is_first_compaction: z.boolean().optional(),\n});\n\nconst stopPayloadSchema = event(\"stop\", {\n status: z.string().optional(),\n loop_count: z.number().int().min(0).optional(),\n ...usageFields,\n});\n\nexport const cursorPayloadSchema = z.discriminatedUnion(\"hook_event_name\", [\n sessionStartPayloadSchema,\n sessionEndPayloadSchema,\n beforeSubmitPromptPayloadSchema,\n afterAgentResponsePayloadSchema,\n afterAgentThoughtPayloadSchema,\n preToolUsePayloadSchema,\n postToolUsePayloadSchema,\n postToolUseFailurePayloadSchema,\n beforeShellExecutionPayloadSchema,\n afterShellExecutionPayloadSchema,\n beforeMcpExecutionPayloadSchema,\n afterMcpExecutionPayloadSchema,\n beforeReadFilePayloadSchema,\n afterFileEditPayloadSchema,\n subagentStartPayloadSchema,\n subagentStopPayloadSchema,\n preCompactPayloadSchema,\n stopPayloadSchema,\n]);\nexport type CursorPayload = z.infer<typeof cursorPayloadSchema>;\n\nexport type CursorPayloadOf<TName extends CursorHookEventName> = Extract<\n CursorPayload,\n { hook_event_name: TName }\n>;\n\nconst isPlainObject = (value: unknown): value is Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value);\n\nexport type CursorRecognition =\n /** A modelled agent hook that validated against its schema. */\n | { readonly status: \"modelled\"; readonly payload: CursorPayload }\n /** A documented Cursor event this adapter does not model, with the reason. */\n | { readonly status: \"unmodelled\"; readonly eventName: string; readonly reason: string }\n /** A modelled event name whose payload does not satisfy its schema. */\n | { readonly status: \"invalid\"; readonly eventName: string; readonly detail: string };\n\n/**\n * Recognize a raw Cursor hook payload.\n *\n * Three outcomes rather than two, so the adapter can tell \"not Cursor at all\"\n * (undefined) from \"Cursor, but nothing this adapter turns into telemetry\"\n * (`unmodelled`) from \"Cursor, and malformed\" (`invalid`) — the middle case must\n * not be reported as a parse failure, and the last must not be reported as a\n * foreign payload.\n */\nexport const recognizeCursorPayload = (payload: unknown): CursorRecognition | undefined => {\n if (!isPlainObject(payload)) {\n return undefined;\n }\n const eventName = payload.hook_event_name;\n if (typeof eventName !== \"string\") {\n return undefined;\n }\n\n const unmodelled = CURSOR_UNMODELLED_HOOK_EVENT_NAMES[eventName];\n if (unmodelled !== undefined) {\n return { status: \"unmodelled\", eventName, reason: unmodelled };\n }\n if (!(CURSOR_HOOK_EVENT_NAMES as readonly string[]).includes(eventName)) {\n return undefined;\n }\n\n const parsed = cursorPayloadSchema.safeParse(payload);\n if (!parsed.success) {\n const [issue] = parsed.error.issues;\n return {\n status: \"invalid\",\n eventName,\n detail:\n issue === undefined\n ? \"payload does not satisfy the cursor hook schema\"\n : `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n };\n }\n if (cursorSessionId(parsed.data) === undefined) {\n return {\n status: \"invalid\",\n eventName,\n detail: \"payload names neither conversation_id nor session_id, so it carries no session to attribute telemetry to\",\n };\n }\n return { status: \"modelled\", payload: parsed.data };\n};\n\n/** Validated payload, or `undefined` for anything else. Convenience for callers. */\nexport const normalizeCursorPayload = (payload: unknown): CursorPayload | undefined => {\n const recognized = recognizeCursorPayload(payload);\n return recognized?.status === \"modelled\" ? recognized.payload : undefined;\n};\n\n/**\n * The session identity to attribute a modelled payload to.\n *\n * `conversation_id` is preferred, but some live Cursor Agent-surface\n * `beforeSubmitPrompt` deliveries have been observed missing it while still\n * carrying `session_id` — which every capture in `./payload.ts`'s provenance\n * note shows repeating `conversation_id` exactly. Previously the schema\n * required `conversation_id` unconditionally, so any callback missing it —\n * this one included — failed detection outright and was silently declined as\n * `provider-unknown`, with no `prompt.submitted` ever emitted for that\n * conversation. Falling back to `session_id` is not a guess: it is reading the\n * same identity from the field Cursor's own envelope repeats it in, and\n * `recognizeCursorPayload` still rejects a payload naming neither.\n */\nexport const cursorSessionId = (payload: CursorPayload): string | undefined => {\n if (payload.conversation_id !== undefined && payload.conversation_id.length > 0) {\n return payload.conversation_id;\n }\n return payload.session_id !== undefined && payload.session_id.length > 0\n ? payload.session_id\n : undefined;\n};\n","import type { 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 { 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 {\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 { 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/** 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\n/**\n * Closed set of error codes. Adding a code is a minor change; changing what a\n * code means is a breaking change.\n */\nexport const otelHookErrorCodeSchema = z.enum([\n /** Input was not usable at all (empty stdin, unparsable JSON). */\n \"invalid-input\",\n /** Input parsed but failed canonical schema validation. */\n \"schema-validation-failed\",\n /** No adapter claimed the input with sufficient confidence. */\n \"provider-unknown\",\n /** Several adapters claimed the input at the same confidence. */\n \"provider-detection-ambiguous\",\n /** An adapter threw or returned a malformed result. */\n \"provider-adapter-failure\",\n /** Two identity claims disagreed at equal confidence. */\n \"identity-conflict\",\n /** Required identity fields were absent. */\n \"identity-incomplete\",\n /** A usage report violated the canonical usage invariants. */\n \"usage-invalid\",\n /** The state store could not be read or written. */\n \"state-store-failure\",\n /** The telemetry sink rejected or could not deliver a batch. */\n \"telemetry-export-failure\",\n /** Content reached the sink boundary in a state the policy forbids. */\n \"privacy-policy-violation\",\n /** Configuration could not be resolved. */\n \"configuration-invalid\",\n /** A configured bound (events, batch size) dropped data. */\n \"limit-exceeded\",\n /**\n * No replay-stable delivery identifier was available for a callback while\n * deduplication was required.\n */\n \"delivery-identifier-unavailable\",\n \"delivery-claim-superseded\",\n /** Anything unanticipated. Always reported, never fatal to the host. */\n \"internal-error\",\n]);\nexport type OtelHookErrorCode = z.infer<typeof otelHookErrorCodeSchema>;\n\nexport const errorSeveritySchema = z.enum([\"warning\", \"error\"]);\nexport type ErrorSeverity = z.infer<typeof errorSeveritySchema>;\n\n/** Pipeline stage where a failure occurred. */\nexport const errorPhaseSchema = z.enum([\n \"configuration\",\n \"detection\",\n \"identity\",\n \"parsing\",\n \"normalization\",\n \"privacy\",\n \"state\",\n \"export\",\n \"shutdown\",\n]);\nexport type ErrorPhase = z.infer<typeof errorPhaseSchema>;\n\n/**\n * Which of the two safety postures a code participates in.\n *\n * - `fail-open`: the hook still reports success to the host agent. Telemetry may\n * be incomplete; the coding agent is never blocked.\n * - `fail-closed-attribution`: the observation is not attributed to a session or\n * provider. Data is dropped rather than labelled with a guess.\n */\nexport const failurePostureSchema = z.enum([\"fail-open\", \"fail-closed-attribution\"]);\nexport type FailurePosture = z.infer<typeof failurePostureSchema>;\n\nexport type ErrorCodeDescriptor = {\n readonly code: OtelHookErrorCode;\n readonly severity: ErrorSeverity;\n readonly posture: FailurePosture;\n /** Whether retrying the same input could succeed. */\n readonly retryable: boolean;\n readonly summary: string;\n};\n\nexport const ERROR_TAXONOMY: Readonly<Record<OtelHookErrorCode, ErrorCodeDescriptor>> =\n Object.freeze({\n \"invalid-input\": {\n code: \"invalid-input\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Input could not be read or decoded.\",\n },\n \"schema-validation-failed\": {\n code: \"schema-validation-failed\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"A canonical event failed schema validation and was dropped.\",\n },\n \"provider-unknown\": {\n code: \"provider-unknown\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"No adapter recognized the source provider; the input stays unattributed.\",\n },\n \"provider-detection-ambiguous\": {\n code: \"provider-detection-ambiguous\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Multiple adapters claimed the input at equal confidence.\",\n },\n \"provider-adapter-failure\": {\n code: \"provider-adapter-failure\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A provider adapter failed while parsing.\",\n },\n \"identity-conflict\": {\n code: \"identity-conflict\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Identity claims disagreed; attribution was declined.\",\n },\n \"identity-incomplete\": {\n code: \"identity-incomplete\",\n severity: \"warning\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Required identity fields were missing; attribution was declined.\",\n },\n \"usage-invalid\": {\n code: \"usage-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A usage report violated the canonical usage invariants.\",\n },\n \"state-store-failure\": {\n code: \"state-store-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"State could not be read or written; derived values may be incomplete.\",\n },\n \"telemetry-export-failure\": {\n code: \"telemetry-export-failure\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: true,\n summary: \"The telemetry sink could not accept a batch.\",\n },\n \"privacy-policy-violation\": {\n code: \"privacy-policy-violation\",\n severity: \"error\",\n posture: \"fail-closed-attribution\",\n retryable: false,\n summary: \"Content violated the resolved privacy policy and was dropped.\",\n },\n \"configuration-invalid\": {\n code: \"configuration-invalid\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"Configuration could not be resolved; defaults apply.\",\n },\n \"limit-exceeded\": {\n code: \"limit-exceeded\",\n severity: \"warning\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"A configured bound was reached and data was dropped.\",\n },\n \"delivery-identifier-unavailable\": {\n code: \"delivery-identifier-unavailable\",\n severity: \"warning\",\n // Fail-open: the observation is still attributed and exported. Only the\n // at-most-once guarantee is missing, and refusing the telemetry to protect\n // a duplicate count would trade a certain loss for a possible one.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"No replay-stable delivery identifier was available; this callback was exported without deduplication.\",\n },\n \"delivery-claim-superseded\": {\n code: \"delivery-claim-superseded\",\n severity: \"warning\",\n // Fail-open, and specifically *not* silent. A peer reclaimed this callback's\n // claim while this process was still working on it, which means the\n // configured stale window is shorter than this installation's real worst\n // case. Both processes may now have exported the callback, so the\n // at-most-once guarantee did not hold for it — the only honest response is\n // to say so and let the operator raise the window.\n posture: \"fail-open\",\n retryable: false,\n summary:\n \"A delivery claim was reclaimed by another process before this one committed; the callback may have been exported twice.\",\n },\n \"internal-error\": {\n code: \"internal-error\",\n severity: \"error\",\n posture: \"fail-open\",\n retryable: false,\n summary: \"An unexpected failure was contained.\",\n },\n });\n\nexport const describeErrorCode = (code: OtelHookErrorCode): ErrorCodeDescriptor =>\n ERROR_TAXONOMY[code];\n\n/** Outcome of attributing an observation to a provider and session. */\nexport const attributionOutcomeSchema = z.enum([\n /** Identity resolved; events carry provider and session identity. */\n \"attributed\",\n /** Identity could not be established safely; nothing was attributed. */\n \"declined\",\n /** Attribution was attempted and failed unexpectedly. */\n \"failed\",\n /** Input was recognized but intentionally carried no telemetry. */\n \"not-applicable\",\n]);\nexport type AttributionOutcome = z.infer<typeof attributionOutcomeSchema>;\n\nexport const attributionReasonSchema = z.enum([\n \"provider-unknown\",\n \"provider-detection-ambiguous\",\n \"identity-conflict\",\n \"identity-incomplete\",\n \"adapter-ignored-input\",\n \"adapter-failure\",\n \"invalid-input\",\n \"internal-error\",\n]);\nexport type AttributionReason = z.infer<typeof attributionReasonSchema>;\n","import { z } from \"zod\";\n\nimport {\n attributesSchema,\n detectionConfidenceSchema,\n DETECTION_CONFIDENCE_RANK,\n epochMillisSchema,\n invocationIdSchema,\n nonEmptyStringSchema,\n resolvedProviderIdSchema,\n sessionIdSchema,\n sourceTransportSchema,\n workspaceIdSchema,\n type DetectionConfidence,\n type InvocationId,\n type SessionId,\n type WorkspaceId,\n} from \"./primitives.js\";\n\n/**\n * Where a workspace identifier came from.\n *\n * Ordered from most to least stable. The source is recorded so consumers can\n * tell a repository-scoped identity from a directory-scoped one instead of\n * assuming they are comparable.\n */\nexport const workspaceKeySourceSchema = z.enum([\n \"git-remote\",\n \"git-root\",\n \"working-directory\",\n \"explicit\",\n \"unknown\",\n]);\nexport type WorkspaceKeySource = z.infer<typeof workspaceKeySourceSchema>;\n\n/**\n * Privacy-safe workspace identity.\n *\n * Only opaque handles and explicitly allowed labels are modelled. There is no\n * field for a filesystem path, so paths cannot be exported through this type.\n */\nexport const workspaceIdentitySchema = z\n .strictObject({\n workspaceId: workspaceIdSchema,\n keySource: workspaceKeySourceSchema,\n /** Repository name only; never an owner path or URL with credentials. */\n repositoryName: nonEmptyStringSchema.optional(),\n vcsBranchName: nonEmptyStringSchema.optional(),\n /** Opaque handle for the checked-out revision. */\n vcsRevisionId: nonEmptyStringSchema.optional(),\n })\n .readonly();\nexport type WorkspaceIdentity = z.infer<typeof workspaceIdentitySchema>;\n\nexport const UNKNOWN_WORKSPACE_ID = \"unknown:0000000000000000\" as WorkspaceId;\n\nexport const unknownWorkspaceIdentity = (): WorkspaceIdentity =>\n workspaceIdentitySchema.parse({\n workspaceId: UNKNOWN_WORKSPACE_ID,\n keySource: \"unknown\",\n });\n\n/**\n * Provenance of an observation: which provider produced it and which adapter\n * interpreted it, with the confidence of that attribution.\n */\nexport const sourceProvenanceSchema = z\n .strictObject({\n providerId: resolvedProviderIdSchema,\n providerVersion: nonEmptyStringSchema.optional(),\n adapterId: nonEmptyStringSchema,\n adapterVersion: nonEmptyStringSchema,\n detectionConfidence: detectionConfidenceSchema,\n /** The provider's own name for the source event, e.g. a hook event name. */\n sourceEventName: nonEmptyStringSchema.optional(),\n transport: sourceTransportSchema,\n })\n .readonly();\nexport type SourceProvenance = z.infer<typeof sourceProvenanceSchema>;\n\n/**\n * Opaque, immutable metadata supplied by the embedding consumer.\n *\n * The library never interprets these values; it only carries and exports them.\n */\nexport const consumerAttributesSchema = attributesSchema.readonly();\nexport type ConsumerAttributes = z.infer<typeof consumerAttributesSchema>;\n\n/**\n * Immutable identity of a single hook invocation.\n *\n * Frozen on parse. There is deliberately no setter, no builder that mutates in\n * place, and no module-level instance: identity is passed explicitly so two\n * concurrent invocations can never observe each other's fields.\n */\nexport const invocationIdentitySchema = z\n .strictObject({\n invocationId: invocationIdSchema,\n sessionId: sessionIdSchema,\n /** Set when this invocation runs beneath another agent invocation. */\n parentInvocationId: invocationIdSchema.optional(),\n /** Root of the session tree when the provider exposes one. */\n rootSessionId: sessionIdSchema.optional(),\n /** Stable handle for the agent process/instance, when available. */\n agentInstanceId: nonEmptyStringSchema.optional(),\n provenance: sourceProvenanceSchema,\n workspace: workspaceIdentitySchema,\n startedAt: epochMillisSchema,\n consumerAttributes: consumerAttributesSchema,\n })\n .readonly();\nexport type InvocationIdentity = z.infer<typeof invocationIdentitySchema>;\n\n/** Fields an identity claim may contribute. */\nexport const identityClaimFieldsSchema = z.strictObject({\n invocationId: invocationIdSchema.optional(),\n sessionId: sessionIdSchema.optional(),\n parentInvocationId: invocationIdSchema.optional(),\n rootSessionId: sessionIdSchema.optional(),\n agentInstanceId: nonEmptyStringSchema.optional(),\n workspace: workspaceIdentitySchema.optional(),\n startedAt: epochMillisSchema.optional(),\n});\nexport type IdentityClaimFields = z.infer<typeof identityClaimFieldsSchema>;\n\n/**\n * A claim about invocation identity from one source.\n *\n * Claims are evidence, not truth. Resolution keeps the highest-confidence claim\n * per field and refuses to merge disagreeing peers.\n */\nexport const identityClaimSchema = z.strictObject({\n /** Non-sensitive label, e.g. `adapter:acme-cli` or `env:OTEL_HOOK_SESSION_ID`. */\n source: nonEmptyStringSchema,\n confidence: detectionConfidenceSchema,\n fields: identityClaimFieldsSchema,\n});\nexport type IdentityClaim = z.infer<typeof identityClaimSchema>;\n\nexport type IdentityConflict = {\n readonly field: keyof IdentityClaimFields;\n readonly confidence: DetectionConfidence;\n /** Rendered, non-sensitive representations of the disagreeing values. */\n readonly values: readonly string[];\n readonly sources: readonly string[];\n};\n\nexport type IdentityResolution =\n | { readonly status: \"resolved\"; readonly identity: InvocationIdentity }\n | {\n readonly status: \"conflict\";\n readonly conflicts: readonly IdentityConflict[];\n }\n | {\n readonly status: \"incomplete\";\n readonly missing: readonly (keyof IdentityClaimFields)[];\n }\n | { readonly status: \"invalid\"; readonly issues: readonly string[] };\n\nconst CLAIM_FIELDS = [\n \"invocationId\",\n \"sessionId\",\n \"parentInvocationId\",\n \"rootSessionId\",\n \"agentInstanceId\",\n \"workspace\",\n \"startedAt\",\n] as const satisfies readonly (keyof IdentityClaimFields)[];\n\nconst renderClaimValue = (value: unknown): string => {\n if (typeof value === \"string\") {\n return value;\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value !== null && typeof value === \"object\" && \"workspaceId\" in value) {\n const { workspaceId } = value;\n return typeof workspaceId === \"string\" ? workspaceId : \"<workspace>\";\n }\n return \"<opaque>\";\n};\n\nexport type ResolveIdentityInput = {\n readonly claims: readonly IdentityClaim[];\n readonly provenance: SourceProvenance;\n /** Used only for fields no claim provides and that have a safe default. */\n readonly fallback?: {\n readonly startedAt?: number;\n readonly workspace?: WorkspaceIdentity;\n };\n readonly consumerAttributes?: Readonly<Record<string, unknown>>;\n};\n\n/**\n * Resolve identity from claims, failing closed.\n *\n * Rules:\n * 1. For each field, only claims at the highest confidence that provided it are\n * considered. Lower-confidence claims never fill in or override.\n * 2. Two distinct values at that highest confidence produce a `conflict`. The\n * invocation is then not attributed at all — a mislabelled session is worse\n * than a missing one.\n * 3. `invocationId` and `sessionId` are mandatory. Missing either yields\n * `incomplete`; neither is invented here.\n * 4. `startedAt` and `workspace` may come from an explicit fallback, because a\n * clock reading and an `unknown` workspace handle assert nothing false.\n */\nexport const resolveInvocationIdentity = (input: ResolveIdentityInput): IdentityResolution => {\n const parsedClaims: IdentityClaim[] = [];\n const issues: string[] = [];\n for (const [index, claim] of input.claims.entries()) {\n const parsed = identityClaimSchema.safeParse(claim);\n if (parsed.success) {\n parsedClaims.push(parsed.data);\n } else {\n issues.push(\n `claim[${index}]: ${parsed.error.issues.map((issue) => `${issue.path.join(\".\") || \"<root>\"} ${issue.message}`).join(\", \")}`,\n );\n }\n }\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const conflicts: IdentityConflict[] = [];\n const selected: Record<string, unknown> = {};\n\n for (const field of CLAIM_FIELDS) {\n const contributors = parsedClaims.filter((claim) => claim.fields[field] !== undefined);\n if (contributors.length === 0) {\n continue;\n }\n const bestRank = Math.max(\n ...contributors.map((claim) => DETECTION_CONFIDENCE_RANK[claim.confidence]),\n );\n const best = contributors.filter(\n (claim) => DETECTION_CONFIDENCE_RANK[claim.confidence] === bestRank,\n );\n const rendered = new Map<string, string[]>();\n for (const claim of best) {\n const key = JSON.stringify(claim.fields[field]);\n const sources = rendered.get(key) ?? [];\n sources.push(claim.source);\n rendered.set(key, sources);\n }\n if (rendered.size > 1) {\n const [firstBest] = best;\n conflicts.push({\n field,\n confidence: firstBest?.confidence ?? \"none\",\n values: best.map((claim) => renderClaimValue(claim.fields[field])),\n sources: best.map((claim) => claim.source),\n });\n continue;\n }\n const [winner] = best;\n if (winner !== undefined) {\n selected[field] = winner.fields[field];\n }\n }\n\n if (conflicts.length > 0) {\n return { status: \"conflict\", conflicts };\n }\n\n const missing: (keyof IdentityClaimFields)[] = [];\n if (selected.invocationId === undefined) {\n missing.push(\"invocationId\");\n }\n if (selected.sessionId === undefined) {\n missing.push(\"sessionId\");\n }\n if (missing.length > 0) {\n return { status: \"incomplete\", missing };\n }\n\n const startedAt = (selected.startedAt as number | undefined) ?? input.fallback?.startedAt;\n if (startedAt === undefined) {\n return { status: \"incomplete\", missing: [\"startedAt\"] };\n }\n const workspace =\n (selected.workspace as WorkspaceIdentity | undefined) ??\n input.fallback?.workspace ??\n unknownWorkspaceIdentity();\n\n const candidate = {\n invocationId: selected.invocationId as InvocationId,\n sessionId: selected.sessionId as SessionId,\n ...(selected.parentInvocationId === undefined\n ? {}\n : { parentInvocationId: selected.parentInvocationId as InvocationId }),\n ...(selected.rootSessionId === undefined\n ? {}\n : { rootSessionId: selected.rootSessionId as SessionId }),\n ...(selected.agentInstanceId === undefined\n ? {}\n : { agentInstanceId: selected.agentInstanceId as string }),\n provenance: input.provenance,\n workspace,\n startedAt,\n consumerAttributes: input.consumerAttributes ?? {},\n };\n\n const parsed = invocationIdentitySchema.safeParse(candidate);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map(\n (issue) => `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n ),\n };\n }\n return { status: \"resolved\", identity: parsed.data };\n};\n","import { z } from \"zod\";\n\nimport 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 { 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 { tokenCountSchema } from \"./primitives.js\";\n\n/**\n * Whether an observation reports the change since the previous observation\n * (`delta`) or the running total for the session/generation (`cumulative`).\n *\n * The canonical model keeps temporality explicit rather than assuming one:\n * summing cumulative observations double-counts, and diffing delta observations\n * silently loses tokens.\n */\nexport const usageTemporalitySchema = z.enum([\"delta\", \"cumulative\"]);\nexport type UsageTemporality = z.infer<typeof usageTemporalitySchema>;\n\n/**\n * Whether the provider counts cache-creation tokens inside its input total or\n * reports them as a disjoint bucket.\n *\n * - `included-in-input`: `cacheCreationInputTokens` is a subset of `inputTokens`.\n * - `disjoint-from-input`: cache-creation tokens are billed in addition to\n * `inputTokens` and must be added when computing a total.\n * - `not-reported`: the provider exposes no cache-creation counter; the field is\n * pinned to zero.\n */\nexport const cacheCreationAccountingSchema = z.enum([\n \"included-in-input\",\n \"disjoint-from-input\",\n \"not-reported\",\n]);\nexport type CacheCreationAccounting = z.infer<typeof cacheCreationAccountingSchema>;\n\n/** Whether a provider-reported total agrees with the canonical computation. */\nexport const providerTotalAgreementSchema = z.enum([\"unreported\", \"agrees\", \"disagrees\"]);\nexport type ProviderTotalAgreement = z.infer<typeof providerTotalAgreementSchema>;\n\n/**\n * What an adapter reports, before normalization.\n *\n * `inputTokens` is *inclusive*: it counts every input token the provider\n * attributes to the call, including cache reads (and cache creation when the\n * provider folds it in). `outputTokens` is likewise inclusive of reasoning\n * output. Subset fields describe portions of those totals, never additions.\n */\nexport const usageReportSchema = z.strictObject({\n temporality: usageTemporalitySchema,\n /** Inclusive input tokens. */\n inputTokens: tokenCountSchema.optional(),\n /** Subset of `inputTokens` served from a prompt cache. */\n cachedInputTokens: tokenCountSchema.optional(),\n /** Tokens written to a prompt cache. */\n cacheCreationInputTokens: tokenCountSchema.optional(),\n /** Required when `cacheCreationInputTokens` is present and non-zero. */\n cacheCreationAccounting: cacheCreationAccountingSchema.optional(),\n /** Inclusive output tokens. */\n outputTokens: tokenCountSchema.optional(),\n /** Subset of `outputTokens` spent on reasoning. */\n reasoningOutputTokens: tokenCountSchema.optional(),\n /** Total exactly as the provider reported it, if it reported one. */\n providerTotalTokens: tokenCountSchema.optional(),\n});\nexport type UsageReport = z.infer<typeof usageReportSchema>;\n\n/**\n * Fully normalized usage.\n *\n * Derived fields (`uncachedInputTokens`, `totalTokens`,\n * `providerTotalAgreement`) are part of the schema and are re-checked on parse,\n * so an inconsistent object cannot exist. Construct values with\n * {@link normalizeUsage} rather than by hand.\n */\nexport const canonicalUsageSchema = z\n .strictObject({\n temporality: usageTemporalitySchema,\n inputTokens: tokenCountSchema,\n cachedInputTokens: tokenCountSchema,\n cacheCreationInputTokens: tokenCountSchema,\n cacheCreationAccounting: cacheCreationAccountingSchema,\n outputTokens: tokenCountSchema,\n reasoningOutputTokens: tokenCountSchema,\n /** Derived: input tokens that were neither cache reads nor cache writes. */\n uncachedInputTokens: tokenCountSchema,\n /** Derived: canonical billable total. */\n totalTokens: tokenCountSchema,\n providerTotalTokens: tokenCountSchema.optional(),\n providerTotalAgreement: providerTotalAgreementSchema,\n })\n .check((ctx) => {\n const usage = ctx.value;\n const push = (message: string): void => {\n ctx.issues.push({ code: \"custom\", input: usage, message });\n };\n\n if (usage.cachedInputTokens > usage.inputTokens) {\n push(\"cachedInputTokens must not exceed inputTokens (it is a subset)\");\n }\n if (usage.reasoningOutputTokens > usage.outputTokens) {\n push(\"reasoningOutputTokens must not exceed outputTokens (it is a subset)\");\n }\n if (usage.cacheCreationAccounting === \"not-reported\" && usage.cacheCreationInputTokens !== 0) {\n push(\"cacheCreationInputTokens must be 0 when cacheCreationAccounting is not-reported\");\n }\n const creationInsideInput =\n usage.cacheCreationAccounting === \"included-in-input\" ? usage.cacheCreationInputTokens : 0;\n if (usage.cachedInputTokens + creationInsideInput > usage.inputTokens) {\n push(\n \"cachedInputTokens + cacheCreationInputTokens must not exceed inputTokens when cache creation is included in input\",\n );\n }\n const expectedUncached = usage.inputTokens - usage.cachedInputTokens - creationInsideInput;\n if (expectedUncached >= 0 && usage.uncachedInputTokens !== expectedUncached) {\n push(`uncachedInputTokens must equal ${expectedUncached}`);\n }\n const creationOutsideInput =\n usage.cacheCreationAccounting === \"disjoint-from-input\" ? usage.cacheCreationInputTokens : 0;\n const expectedTotal = usage.inputTokens + creationOutsideInput + usage.outputTokens;\n if (usage.totalTokens !== expectedTotal) {\n push(`totalTokens must equal ${expectedTotal}`);\n }\n const expectedAgreement: ProviderTotalAgreement =\n usage.providerTotalTokens === undefined\n ? \"unreported\"\n : usage.providerTotalTokens === expectedTotal\n ? \"agrees\"\n : \"disagrees\";\n if (usage.providerTotalAgreement !== expectedAgreement) {\n push(`providerTotalAgreement must be ${expectedAgreement}`);\n }\n });\nexport type CanonicalUsage = z.infer<typeof canonicalUsageSchema>;\n\nexport type UsageNormalizationIssue = {\n readonly code:\n | \"invalid-report\"\n | \"cached-exceeds-input\"\n | \"reasoning-exceeds-output\"\n | \"cache-creation-exceeds-input\"\n | \"cache-creation-accounting-missing\";\n readonly message: string;\n};\n\nexport type UsageNormalizationResult =\n | { readonly status: \"ok\"; readonly usage: CanonicalUsage; readonly notes: readonly string[] }\n | { readonly status: \"invalid\"; readonly issues: readonly UsageNormalizationIssue[] };\n\n/**\n * Normalize a provider usage report into canonical usage.\n *\n * Deterministic rules:\n * 1. Absent counters default to `0`; `providerTotalTokens` stays absent.\n * 2. Non-integer, negative, or non-finite counters are rejected.\n * 3. A subset exceeding its total is rejected — never clamped — because\n * clamping would silently invent a billing story.\n * 4. `cacheCreationAccounting` defaults to `not-reported` when no cache-creation\n * tokens are reported, and is *required* when they are: guessing whether the\n * bucket is disjoint would mis-total every downstream cost calculation.\n * 5. A provider total that disagrees with the canonical total is preserved as\n * reported and flagged `disagrees`. Both numbers survive; neither is edited.\n */\nexport const normalizeUsage = (report: unknown): UsageNormalizationResult => {\n const parsed = usageReportSchema.safeParse(report);\n if (!parsed.success) {\n return {\n status: \"invalid\",\n issues: parsed.error.issues.map((issue) => ({\n code: \"invalid-report\" as const,\n message: `${issue.path.join(\".\") || \"<root>\"}: ${issue.message}`,\n })),\n };\n }\n\n const input = parsed.data;\n const issues: UsageNormalizationIssue[] = [];\n const notes: string[] = [];\n\n const inputTokens = input.inputTokens ?? 0;\n const cachedInputTokens = input.cachedInputTokens ?? 0;\n const cacheCreationInputTokens = input.cacheCreationInputTokens ?? 0;\n const outputTokens = input.outputTokens ?? 0;\n const reasoningOutputTokens = input.reasoningOutputTokens ?? 0;\n\n let accounting: CacheCreationAccounting;\n if (cacheCreationInputTokens === 0) {\n accounting = input.cacheCreationAccounting ?? \"not-reported\";\n if (accounting !== \"not-reported\") {\n notes.push(\n `cacheCreationAccounting=${accounting} retained with zero cache-creation tokens`,\n );\n }\n } else if (input.cacheCreationAccounting === undefined) {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message:\n \"cacheCreationAccounting is required when cacheCreationInputTokens is non-zero; it cannot be inferred\",\n });\n accounting = \"not-reported\";\n } else if (input.cacheCreationAccounting === \"not-reported\") {\n issues.push({\n code: \"cache-creation-accounting-missing\",\n message: \"cacheCreationAccounting=not-reported conflicts with non-zero cacheCreationInputTokens\",\n });\n accounting = \"not-reported\";\n } else {\n accounting = input.cacheCreationAccounting;\n }\n\n if (cachedInputTokens > inputTokens) {\n issues.push({\n code: \"cached-exceeds-input\",\n message: `cachedInputTokens (${cachedInputTokens}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n if (reasoningOutputTokens > outputTokens) {\n issues.push({\n code: \"reasoning-exceeds-output\",\n message: `reasoningOutputTokens (${reasoningOutputTokens}) exceeds inclusive outputTokens (${outputTokens})`,\n });\n }\n\n const creationInsideInput = accounting === \"included-in-input\" ? cacheCreationInputTokens : 0;\n if (cachedInputTokens + creationInsideInput > inputTokens) {\n issues.push({\n code: \"cache-creation-exceeds-input\",\n message: `cachedInputTokens + cacheCreationInputTokens (${cachedInputTokens + creationInsideInput}) exceeds inclusive inputTokens (${inputTokens})`,\n });\n }\n\n if (issues.length > 0) {\n return { status: \"invalid\", issues };\n }\n\n const creationOutsideInput = accounting === \"disjoint-from-input\" ? cacheCreationInputTokens : 0;\n const totalTokens = inputTokens + creationOutsideInput + outputTokens;\n const providerTotalAgreement: ProviderTotalAgreement =\n input.providerTotalTokens === undefined\n ? \"unreported\"\n : input.providerTotalTokens === totalTokens\n ? \"agrees\"\n : \"disagrees\";\n\n if (providerTotalAgreement === \"disagrees\") {\n notes.push(\n `providerTotalTokens (${input.providerTotalTokens ?? 0}) disagrees with canonical total (${totalTokens}); both retained`,\n );\n }\n\n const usage: CanonicalUsage = {\n temporality: input.temporality,\n inputTokens,\n cachedInputTokens,\n cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens,\n reasoningOutputTokens,\n uncachedInputTokens: inputTokens - cachedInputTokens - creationInsideInput,\n totalTokens,\n ...(input.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: input.providerTotalTokens }),\n providerTotalAgreement,\n };\n\n return { status: \"ok\", usage, notes };\n};\n\nexport class UsageNormalizationError extends Error {\n public readonly issues: readonly UsageNormalizationIssue[];\n\n public constructor(issues: readonly UsageNormalizationIssue[]) {\n super(`invalid usage report: ${issues.map((issue) => issue.message).join(\"; \")}`);\n this.name = \"UsageNormalizationError\";\n this.issues = issues;\n }\n}\n\n/** Convenience wrapper for call sites that treat invalid usage as a bug. */\nexport const normalizeUsageOrThrow = (report: unknown): CanonicalUsage => {\n const result = normalizeUsage(report);\n if (result.status === \"invalid\") {\n throw new UsageNormalizationError(result.issues);\n }\n return result.usage;\n};\n\nexport const EMPTY_DELTA_USAGE: CanonicalUsage = Object.freeze(\n normalizeUsageOrThrow({ temporality: \"delta\" }),\n);\n\nexport type UsageDeltaResult = {\n readonly usage: CanonicalUsage;\n /**\n * True when the current snapshot is smaller than the previous one on any\n * counter. That means the cumulative series restarted (new session, replayed\n * transcript, provider reset), so the current snapshot is emitted as the delta\n * instead of a negative difference.\n */\n readonly resetDetected: boolean;\n};\n\nconst requireCumulative = (usage: CanonicalUsage, label: string): void => {\n if (usage.temporality !== \"cumulative\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: `${label} must have cumulative temporality` },\n ]);\n }\n};\n\n/**\n * Convert two cumulative snapshots into a delta observation.\n *\n * Replay safety: re-processing the same snapshot yields an all-zero delta, and a\n * decreasing series is reported as a reset rather than a negative delta.\n * Accounting mode must match; mixing modes would make the subtraction meaningless.\n */\nexport const cumulativeToDelta = (\n previous: CanonicalUsage,\n current: CanonicalUsage,\n): UsageDeltaResult => {\n requireCumulative(previous, \"previous usage\");\n requireCumulative(current, \"current usage\");\n\n if (\n previous.cacheCreationAccounting !== current.cacheCreationAccounting &&\n previous.cacheCreationInputTokens !== 0 &&\n current.cacheCreationInputTokens !== 0\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot diff cumulative usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const resetDetected =\n current.inputTokens < previous.inputTokens ||\n current.cachedInputTokens < previous.cachedInputTokens ||\n current.cacheCreationInputTokens < previous.cacheCreationInputTokens ||\n current.outputTokens < previous.outputTokens ||\n current.reasoningOutputTokens < previous.reasoningOutputTokens;\n\n if (resetDetected) {\n return {\n usage: normalizeUsageOrThrow({ ...toReport(current), temporality: \"delta\" }),\n resetDetected: true,\n };\n }\n\n const usage = normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: current.inputTokens - previous.inputTokens,\n cachedInputTokens: current.cachedInputTokens - previous.cachedInputTokens,\n cacheCreationInputTokens:\n current.cacheCreationInputTokens - previous.cacheCreationInputTokens,\n cacheCreationAccounting: current.cacheCreationAccounting,\n outputTokens: current.outputTokens - previous.outputTokens,\n reasoningOutputTokens: current.reasoningOutputTokens - previous.reasoningOutputTokens,\n });\n\n return { usage, resetDetected: false };\n};\n\n/** Project canonical usage back onto the reported shape. */\nexport const toReport = (usage: CanonicalUsage): UsageReport => ({\n temporality: usage.temporality,\n inputTokens: usage.inputTokens,\n cachedInputTokens: usage.cachedInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n cacheCreationAccounting: usage.cacheCreationAccounting,\n outputTokens: usage.outputTokens,\n reasoningOutputTokens: usage.reasoningOutputTokens,\n ...(usage.providerTotalTokens === undefined\n ? {}\n : { providerTotalTokens: usage.providerTotalTokens }),\n});\n\n/**\n * Add two delta observations. Cumulative usage is never summed, because two\n * running totals do not compose.\n */\nexport const addUsage = (a: CanonicalUsage, b: CanonicalUsage): CanonicalUsage => {\n if (a.temporality !== \"delta\" || b.temporality !== \"delta\") {\n throw new UsageNormalizationError([\n { code: \"invalid-report\", message: \"only delta usage may be summed\" },\n ]);\n }\n const accounting =\n a.cacheCreationInputTokens === 0 && a.cacheCreationAccounting === \"not-reported\"\n ? b.cacheCreationAccounting\n : b.cacheCreationInputTokens === 0 && b.cacheCreationAccounting === \"not-reported\"\n ? a.cacheCreationAccounting\n : a.cacheCreationAccounting;\n\n if (\n a.cacheCreationInputTokens !== 0 &&\n b.cacheCreationInputTokens !== 0 &&\n a.cacheCreationAccounting !== b.cacheCreationAccounting\n ) {\n throw new UsageNormalizationError([\n {\n code: \"cache-creation-accounting-missing\",\n message: \"cannot sum usage across differing cacheCreationAccounting modes\",\n },\n ]);\n }\n\n const providerTotal =\n a.providerTotalTokens === undefined && b.providerTotalTokens === undefined\n ? undefined\n : (a.providerTotalTokens ?? 0) + (b.providerTotalTokens ?? 0);\n\n return normalizeUsageOrThrow({\n temporality: \"delta\",\n inputTokens: a.inputTokens + b.inputTokens,\n cachedInputTokens: a.cachedInputTokens + b.cachedInputTokens,\n cacheCreationInputTokens: a.cacheCreationInputTokens + b.cacheCreationInputTokens,\n cacheCreationAccounting: accounting,\n outputTokens: a.outputTokens + b.outputTokens,\n reasoningOutputTokens: a.reasoningOutputTokens + b.reasoningOutputTokens,\n ...(providerTotal === undefined ? {} : { providerTotalTokens: providerTotal }),\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Version of the canonical event model.\n *\n * Every emitted event carries this value. Consumers must treat an unknown\n * version as unreadable rather than guessing field semantics.\n *\n * Compatibility rules:\n * - Additive optional fields do not change the version.\n * - Renaming, removing, or re-interpreting a field increments the version.\n */\nexport const CANONICAL_SCHEMA_VERSION = 1 as const;\n\nexport type CanonicalSchemaVersion = typeof CANONICAL_SCHEMA_VERSION;\n\nexport const canonicalSchemaVersionSchema = z.literal(CANONICAL_SCHEMA_VERSION);\n","import 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","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 { 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","/**\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 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 { 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 { 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","/**\n * Registration lifecycle: pure planners, plus the safe application of a plan.\n *\n * Two layers, deliberately separated:\n *\n * - **Planners** (`providers/<id>/registration.ts`, re-exported here) are pure.\n * They take the *already parsed* contents of a provider's configuration\n * document and return the document to write back plus whether anything\n * changed. ADR 0003 keeps a provider adapter away from the filesystem, and a\n * pure merge is testable against every \"already registered\", \"registered with\n * an older command\", and \"unrelated hooks present\" case without a temporary\n * directory.\n * - **Lifecycle** (`lifecycle.ts`) reads and writes real files: locking a\n * third party's config for the read-merge-write, preserving its formatting,\n * writing atomically, and refusing rather than clobbering when the document\n * is not what the provider documents.\n *\n * Registration is only offered for providers whose configuration contract this\n * repository has verified. {@link PROVIDER_REGISTRATION_SUPPORT} names the\n * others and says exactly what would unblock them — an invented settings shape\n * written into a real `settings.json` is worse than no installer at all.\n */\nimport { ANTIGRAVITY_PROVIDER_ID } from \"../providers/antigravity/adapter.js\";\nimport {\n mergeAntigravityHookRegistration,\n readAntigravityHookRegistrations,\n removeAntigravityHookRegistration,\n type AntigravityHookCommandEntry,\n type MergeAntigravityHookRegistrationInput,\n type MergeAntigravityHookRegistrationResult,\n type RemoveAntigravityHookRegistrationInput,\n} from \"../providers/antigravity/registration.js\";\nimport { CLAUDE_CODE_PROVIDER_ID } from \"../providers/claude/detect.js\";\nimport {\n CLAUDE_HOOK_EVENTS_MODELLED,\n CLAUDE_REGISTRABLE_HOOK_EVENTS,\n CLAUDE_UNREGISTERED_HOOK_EVENTS,\n mergeClaudeHookRegistration,\n readClaudeHookRegistrations,\n removeClaudeHookRegistration,\n type ClaudeHookRegistrationOptions,\n type ClaudeHookRemovalOptions,\n} from \"../providers/claude/registration.js\";\nimport {\n CODEX_HOOK_EVENTS_MODELLED,\n CODEX_REGISTRABLE_HOOK_EVENTS,\n CODEX_UNREGISTERED_HOOK_EVENTS,\n mergeCodexHookRegistration,\n readCodexHookRegistrations,\n readCodexHooksFeatureFlag,\n removeCodexHookRegistration,\n type CodexHookRegistrationOptions,\n type CodexHookRemovalOptions,\n type CodexHooksFeatureFlag,\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_HOOK_EVENTS_MODELLED,\n CURSOR_HOOKS_DOCUMENT_VERSION,\n CURSOR_REGISTRABLE_HOOK_EVENTS,\n CURSOR_UNREGISTERED_HOOK_EVENTS,\n mergeCursorHookRegistration,\n readCursorHookRegistrations,\n removeCursorHookRegistration,\n type CursorHookCommandEntry,\n type CursorHookDocumentResult,\n type CursorHookRemovalInput,\n type MergeCursorHookRegistrationInput,\n} from \"../providers/cursor/registration.js\";\nimport { GEMINI_PROVIDER_ID } from \"../providers/gemini/adapter.js\";\nimport {\n mergeGeminiHookRegistration,\n readGeminiHookRegistrations,\n removeGeminiHookRegistration,\n type GeminiHookCommandEntry,\n type GeminiHookMatcherEntry,\n type GeminiHooksSettings,\n type MergeGeminiHookResult,\n type RegisterGeminiHookOptions,\n type RemoveGeminiHookOptions,\n} from \"../providers/gemini/setup.js\";\nimport {\n mergeNestedHookRegistration,\n readNestedHookRegistrations,\n removeNestedHookRegistrations,\n type CommandHookEntry,\n type HookDocumentAction,\n type HookDocumentChange,\n type HookDocumentConflict,\n type HookGroupEntry,\n type HookHandlerPredicate,\n type MergeNestedHookInput,\n type NestedHookDocumentResult,\n type RemoveNestedHookInput,\n} from \"../providers/hook-document.js\";\nimport { findRegistrationPlanner, managedHookPredicate } from \"./planners.js\";\nimport { findRegistrationSupport } from \"./support.js\";\n\nexport {\n CLAUDE_HOOK_EVENTS_MODELLED,\n CLAUDE_REGISTRABLE_HOOK_EVENTS,\n CLAUDE_UNREGISTERED_HOOK_EVENTS,\n CODEX_HOOK_EVENTS_MODELLED,\n CODEX_REGISTRABLE_HOOK_EVENTS,\n CODEX_UNREGISTERED_HOOK_EVENTS,\n CURSOR_HOOK_EVENTS_MODELLED,\n CURSOR_HOOKS_DOCUMENT_VERSION,\n CURSOR_REGISTRABLE_HOOK_EVENTS,\n CURSOR_UNREGISTERED_HOOK_EVENTS,\n mergeAntigravityHookRegistration,\n mergeClaudeHookRegistration,\n mergeCodexHookRegistration,\n mergeCursorHookRegistration,\n mergeGeminiHookRegistration,\n mergeNestedHookRegistration,\n readAntigravityHookRegistrations,\n readClaudeHookRegistrations,\n readCodexHookRegistrations,\n readCodexHooksFeatureFlag,\n readCursorHookRegistrations,\n readGeminiHookRegistrations,\n readNestedHookRegistrations,\n removeAntigravityHookRegistration,\n removeClaudeHookRegistration,\n removeCodexHookRegistration,\n removeCursorHookRegistration,\n removeGeminiHookRegistration,\n removeNestedHookRegistrations,\n type AntigravityHookCommandEntry,\n type ClaudeHookRegistrationOptions,\n type ClaudeHookRemovalOptions,\n type CodexHookRegistrationOptions,\n type CodexHookRemovalOptions,\n type CodexHooksFeatureFlag,\n type CommandHookEntry,\n type CursorHookCommandEntry,\n type CursorHookDocumentResult,\n type CursorHookRemovalInput,\n type GeminiHookCommandEntry,\n type GeminiHookMatcherEntry,\n type GeminiHooksSettings,\n type HookDocumentAction,\n type HookDocumentChange,\n type HookDocumentConflict,\n type HookGroupEntry,\n type HookHandlerPredicate,\n type MergeAntigravityHookRegistrationInput,\n type MergeAntigravityHookRegistrationResult,\n type MergeCursorHookRegistrationInput,\n type MergeGeminiHookResult,\n type MergeNestedHookInput,\n type NestedHookDocumentResult,\n type RegisterGeminiHookOptions,\n type RemoveAntigravityHookRegistrationInput,\n type RemoveGeminiHookOptions,\n type RemoveNestedHookInput,\n};\n\nexport {\n checkManagedMarker,\n DEFAULT_MANAGED_COMMAND_MARKER,\n MANAGED_HOOK_NAME,\n MANAGED_MARKER_REJECTION_DETAIL,\n MANAGED_MARKER_TOKEN,\n REGISTRATION_PLANNERS,\n findRegistrationPlanner,\n managedHookPredicate,\n type ManagedMarkerRejection,\n type ProviderRegistrationPlanner,\n type RegistrationPlanInput,\n type RegistrationRemovalInput,\n} from \"./planners.js\";\n\nexport {\n PROVIDER_REGISTRATION_SUPPORT,\n SUPPORTED_REGISTRATION_PROVIDER_IDS,\n findRegistrationSupport,\n type ProviderRegistrationSupport,\n} from \"./support.js\";\n\nexport {\n PROVIDERS_WITHOUT_VERIFIED_LOCATION,\n PROVIDERS_WITH_VERIFIED_LOCATION,\n PROVIDER_INSTALL_LOCATIONS,\n REGISTRATION_SCOPES,\n findInstallLocation,\n resolveInstallPath,\n type InstallLocation,\n type RegistrationScope,\n type ScopeRoots,\n} from \"./scopes.js\";\n\nexport {\n DEFAULT_DOCUMENT_FORMAT,\n detectDocumentFormat,\n readJsonDocument,\n renderJsonDocument,\n writeDocumentAtomically,\n type JsonDocumentFormat,\n type ReadDocumentResult,\n} from \"./document.js\";\n\nexport {\n FileLockTimeoutError,\n lockPathFor,\n withFileLock,\n type FileLockOptions,\n} from \"./file-lock.js\";\n\nexport {\n defaultHookCommand,\n runRegistrationLifecycle,\n type RegistrationAction,\n type RegistrationLifecycleRequest,\n type RegistrationOutcome,\n type RegistrationOutcomeStatus,\n type RegistrationReport,\n} from \"./lifecycle.js\";\n\nexport type PlanProviderRegistrationInput =\n | {\n readonly providerId: typeof GEMINI_PROVIDER_ID;\n /** Parsed contents of the provider's settings document, if one exists. */\n readonly existing?: unknown;\n readonly options: RegisterGeminiHookOptions;\n }\n | {\n readonly providerId: typeof ANTIGRAVITY_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<MergeAntigravityHookRegistrationInput, \"existing\">;\n }\n | {\n readonly providerId: typeof CLAUDE_CODE_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<ClaudeHookRegistrationOptions, \"existing\" | \"identifies\"> & {\n readonly identifies?: HookHandlerPredicate;\n };\n }\n | {\n readonly providerId: typeof CODEX_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<CodexHookRegistrationOptions, \"existing\" | \"identifies\"> & {\n readonly identifies?: HookHandlerPredicate;\n };\n }\n | {\n readonly providerId: typeof CURSOR_PROVIDER_ID;\n readonly existing?: unknown;\n readonly options: Omit<MergeCursorHookRegistrationInput, \"existing\" | \"identifies\"> & {\n readonly identifies?: HookHandlerPredicate;\n };\n }\n | {\n readonly providerId: string;\n readonly existing?: unknown;\n readonly options?: unknown;\n };\n\nexport type PlanProviderRegistrationResult =\n | {\n readonly status: \"planned\";\n readonly providerId: string;\n /** Write this back verbatim; unrelated keys are carried through unchanged. */\n readonly document: Record<string, unknown>;\n /** False when the document already contained exactly this registration. */\n readonly changed: boolean;\n readonly changes: readonly HookDocumentChange[];\n }\n | {\n /** The document is not the shape this provider documents; nothing was changed. */\n readonly status: \"conflict\";\n readonly providerId: string;\n readonly conflicts: readonly HookDocumentConflict[];\n }\n | { readonly status: \"unsupported\"; readonly providerId: string; readonly reason: string }\n | { readonly status: \"invalid\"; readonly providerId: string; readonly reason: string };\n\n/**\n * Plan one provider's hook registration.\n *\n * Idempotent: calling it again with the same `options` against the document it\n * returned yields `changed: false` and an identical document.\n */\nexport const planProviderRegistration = (\n input: PlanProviderRegistrationInput,\n): PlanProviderRegistrationResult => {\n const support = findRegistrationSupport(input.providerId);\n const planner = findRegistrationPlanner(input.providerId);\n if (planner === undefined || support?.supported !== true) {\n return {\n status: \"unsupported\",\n providerId: input.providerId,\n reason: support?.reason ?? `no registration planner is available for provider \"${input.providerId}\"`,\n };\n }\n\n const options = (input.options ?? {}) as {\n readonly command?: unknown;\n readonly events?: readonly string[];\n readonly matcher?: string;\n readonly timeout?: number;\n readonly timeoutSeconds?: number;\n readonly identifies?: HookHandlerPredicate;\n };\n if (typeof options.command !== \"string\" || options.command.length === 0) {\n return {\n status: \"invalid\",\n providerId: input.providerId,\n reason: `planning a \"${input.providerId}\" registration requires a non-empty options.command`,\n };\n }\n\n const timeoutSeconds = options.timeoutSeconds ?? options.timeout;\n const result = planner.merge({\n ...(input.existing === undefined ? {} : { existing: input.existing }),\n command: options.command,\n ...(options.events === undefined ? {} : { events: options.events }),\n ...(options.matcher === undefined ? {} : { matcher: options.matcher }),\n ...(timeoutSeconds === undefined ? {} : { timeoutSeconds }),\n identifies: options.identifies ?? managedHookPredicate(options.command),\n });\n\n if (result.conflicts.length > 0) {\n return { status: \"conflict\", providerId: input.providerId, conflicts: result.conflicts };\n }\n return {\n status: \"planned\",\n providerId: input.providerId,\n document: result.document,\n changed: result.changed,\n changes: result.changes,\n };\n};\n"],"mappings":";AAAA,SAAS,SAAS;AAkBX,IAAM,+BAA+B;AAAA,EAC1C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAGA,IAAM,sBAAsB,EAAE,KAAK,4BAA4B;AAMxD,IAAM,6BAA6B,EAAE,OAAO,EAAE,eAAe,oBAAoB,CAAC,EAAE,YAAY;AAEvG,IAAM,eAAe;AAAA,EACnB,gBAAgB,EAAE,OAAO,EAAE,IAAI,CAAC;AAAA,EAChC,gBAAgB,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,CAAC,EAAE,IAAI,EAA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AAA,EACF;AAEA,QAAM,iBAAiB,QAAQ,kBAAkB,QAAQ;AACzD,QAAM,SAAS,QAAQ,MAAM;AAAA,IAC3B,GAAI,MAAM,aAAa,SAAY,CAAC,IAAI,EAAE,UAAU,MAAM,SAAS;AAAA,IACnE,SAAS,QAAQ;AAAA,IACjB,GAAI,QAAQ,WAAW,SAAY,CAAC,IAAI,EAAE,QAAQ,QAAQ,OAAO;AAAA,IACjE,GAAI,QAAQ,YAAY,SAAY,CAAC,IAAI,EAAE,SAAS,QAAQ,QAAQ;AAAA,IACpE,GAAI,mBAAmB,SAAY,CAAC,IAAI,EAAE,eAAe;AAAA,IACzD,YAAY,QAAQ,cAAc,qBAAqB,QAAQ,OAAO;AAAA,EACxE,CAAC;AAED,MAAI,OAAO,UAAU,SAAS,GAAG;AAC/B,WAAO,EAAE,QAAQ,YAAY,YAAY,MAAM,YAAY,WAAW,OAAO,UAAU;AAAA,EACzF;AACA,SAAO;AAAA,IACL,QAAQ;AAAA,IACR,YAAY,MAAM;AAAA,IAClB,UAAU,OAAO;AAAA,IACjB,SAAS,OAAO;AAAA,IAChB,SAAS,OAAO;AAAA,EAClB;AACF;","names":["event","isPlainObject","event","z","commonFields","preToolUsePayloadSchema","postToolUsePayloadSchema","stopPayloadSchema","z","buildEntry","z","z","sessionStartPayloadSchema","sessionEndPayloadSchema","preToolUsePayloadSchema","postToolUsePayloadSchema","postToolUseFailurePayloadSchema","subagentStartPayloadSchema","subagentStopPayloadSchema","preCompactPayloadSchema","stopPayloadSchema","isPlainObject","buildEntry","event","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","z","event","z","isPlainObject","event","path","resolve","randomBytes","mkdir","open","readFile","rename","stat","unlink","path","isErrnoException","delay","resolve","readFile","path","readFile","event"]}
|