@ev-ai/agent-hook 1.0.7 → 1.0.9

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/COLLECTED-DATA.md CHANGED
@@ -10,19 +10,19 @@ What `@ev-ai/agent-hook` POSTs to the ev-ai collector (`POST /{orgToken}/hook`,
10
10
  | `session_end` | Session stops |
11
11
  | `tool_invoked` | Tool, skill, MCP, shell, or file-edit hook fires |
12
12
 
13
- Every event also carries: UTC timestamp, `installation_id` (per-machine under `~/.ev-ai/agent-hook/installation.json`; on ephemeral CI/cloud homes derived from platform seeds such as `GITHUB_REPOSITORY_ID`+`GITHUB_ACTOR` / `CODESPACE_NAME`, or pinned via `EV_AI_HOOK_INSTALLATION_ID`), runner `platform` (`claude` / `cursor` / `codex`), `platform_agent_id` (Layer-1 inventory join key: `{owner}/{repo}:{scopePath/}{markerDir}`, e.g. `acme/my-app:.claude` or `acme/my-app:apps/web/.cursor`), `session_id`, `turn_id`, raw `runner_event` name, `agent_hook_version`, `host_arch`, `node_version`, and `build_ms` (wall-clock milliseconds to assemble the envelope before the collector POST; not tool/session duration).
13
+ Every event also carries: UTC timestamp, `installation_id` (per-machine under `~/.ev-ai/agent-hook/installation.json`; on ephemeral CI/cloud homes derived from platform seeds such as `GITHUB_REPOSITORY_ID`+`GITHUB_ACTOR` / `CODESPACE_NAME` / Cursor Cloud `CURSOR_PROJECT_DIR`+`CURSOR_USER_EMAIL` / Claude Code remote origin remote + git author email, or pinned via `EV_AI_HOOK_INSTALLATION_ID`), runner `platform` (`claude` / `cursor` / `codex`), `platform_agent_id` (Layer-1 inventory join key: `{owner}/{repo}:{scopePath/}{markerDir}`, e.g. `acme/my-app:.claude` or `acme/my-app:apps/web/.cursor`), `session_id`, `turn_id`, raw `runner_event` name, `agent_hook_version`, `host_arch`, `node_version`, and `build_ms` (wall-clock milliseconds to assemble the envelope before the collector POST; not tool/session duration).
14
14
 
15
15
  ## Tracked data points
16
16
 
17
17
  ### On `session_start`
18
18
 
19
- - **Host** — hostname, OS / version, username, shell, TTY, runtime context (`interactive` / `github_actions` / `claude_remote` / `cursor_cloud` / `codespaces` / `managed` / `container` / `cron`). `managed` covers generic `CI=true` plus named platforms that often omit it (`TF_BUILD`, `JENKINS_URL`, `BUILDKITE`, `CIRCLECI`, `GITLAB_CI`, `CODEBUILD_BUILD_ID`, `DRONE`, …). `container` covers `/.dockerenv`, k8s (`KUBERNETES_SERVICE_HOST`), and VS Code / Codespaces-style remote containers (`REMOTE_CONTAINERS` / `DEVCONTAINER`). Optional virt and cloud provider / region / instance id. Cloud metadata is probed only for non-interactive contexts; interactive laptop sessions skip IMDS entirely. Non-interactive probes are cached locally for 24h per context.
19
+ - **Host** — hostname, OS / version, username, shell, TTY, runtime context (`interactive` / `github_actions` / `claude_remote` / `cursor_cloud` / `codespaces` / `gitlab_ci` / `managed` / `container` / `unknown`). Cloud / CI contexts require positive evidence (`GITHUB_ACTIONS`, `CLAUDE_CODE_REMOTE`, `CODESPACES`, `GITLAB_CI`, managed CI platform markers, truthy `CI`, or Cursor Cloud). Cursor Cloud is `CURSOR_AGENT` without a local IDE host, a `bc-` background-composer session id on Linux, or hostname `cursor` + os user `ubuntu` + `CURSOR_VERSION` on Linux. `CURSOR_AGENT` / those extra markers are not enough when a local Cursor / VS Code extension host is present (desktop agent shells set `CURSOR_AGENT` too). `CURSOR_CODE_REMOTE` alone is not Cursor Cloud (Remote-SSH boxes also set it). `gitlab_ci` is `GITLAB_CI`. `managed` covers generic `CI=true` plus named platforms that often omit it (`TF_BUILD`, `JENKINS_URL`, `BUILDKITE`, `CIRCLECI`, `CODEBUILD_BUILD_ID`, `DRONE`, …). `container` covers `/.dockerenv`, k8s (`KUBERNETES_SERVICE_HOST`), and VS Code / Codespaces-style remote containers (`REMOTE_CONTAINERS` / `DEVCONTAINER`). `interactive` covers TTY / `TERM` / `TERM_PROGRAM`, SSH session markers, macOS GUI launch (`__CFBundleIdentifier`, `XPC_SERVICE_NAME`), IDE host markers (`VSCODE_PID`, …), and Linux / Windows desktop session vars. Residual with no positive cloud or local evidence is `unknown` (the former `cron` catch-all for “no TTY” was removed — GUI-launched agents often have no TTY). Optional virt and cloud provider / region / instance id. Cloud metadata is probed only for non-interactive contexts; interactive laptop sessions skip IMDS entirely. Non-interactive probes are cached locally for 24h per context.
20
20
  - **Git** — origin remote (credentials stripped), branch, HEAD SHA, dirty flag
21
- - **Env (allowlist only)** — CI markers (`CI`, `GITHUB_*`, `GITLAB_CI`, `CIRCLECI`, `BUILDKITE`, `TF_BUILD`, …), actor identity markers (`GITHUB_ACTOR`, `GITLAB_USER_*`, `BUILD_REQUESTEDFOR*`, `BUILDKITE_BUILD_CREATOR*`, `BUILD_USER*`, `CHANGE_AUTHOR*`, `CIRCLE_USERNAME`, `CODEBUILD_INITIATOR`, `DRONE_COMMIT_AUTHOR*`, `EV_AI_HOOK_OPERATOR_*`, `GIT_AUTHOR_*`, `GIT_COMMITTER_*`, `EMAIL`, …), cloud session markers (`CLAUDE_CODE_REMOTE`, `CURSOR_AGENT`, `CODESPACES`), `NODE_ENV`, `TERM_PROGRAM`, vendor base-URL overrides (`ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`, …), Claude Bedrock/Vertex flags. API keys and proxy vars are never read. Gateway URLs have embedded credentials and credential-shaped query params (`key`, `api-key`, `token`, `sig`, …) redacted.
21
+ - **Env (allowlist only)** — CI markers (`CI`, `GITHUB_*`, `GITLAB_CI`, `CIRCLECI`, `BUILDKITE`, `TF_BUILD`, …), actor identity markers (`GITHUB_ACTOR`, `GITLAB_USER_*`, `BUILD_REQUESTEDFOR*`, `BUILDKITE_BUILD_CREATOR*`, `BUILD_USER*`, `CHANGE_AUTHOR*`, `CIRCLE_USERNAME`, `CODEBUILD_INITIATOR`, `DRONE_COMMIT_AUTHOR*`, `EV_AI_HOOK_OPERATOR_*`, `GIT_AUTHOR_*`, `GIT_COMMITTER_*`, `EMAIL`, …), cloud session markers (`CLAUDE_CODE_REMOTE`, `CURSOR_AGENT`, `CURSOR_VERSION`, `CURSOR_USER_EMAIL`, `CODESPACES`), `CURSOR_PROJECT_DIR` (present/absent only — the path is not shipped), `NODE_ENV`, `TERM_PROGRAM`, vendor base-URL overrides (`ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`, …), Claude Bedrock/Vertex flags. API keys and proxy vars are never read. Gateway URLs have embedded credentials and credential-shaped query params (`key`, `api-key`, `token`, `sig`, …) redacted.
22
22
  - **MCP inventory** — declared server **names** (and discovery source), not commands/URLs/env
23
23
  - **User-scope config** — `cli_version` (claude / agent|cursor-agent / codex `--version`); model (Claude; SessionStart stdin `model` preferred over settings-file), Claude-only `claude_version` mirror; presence/size of global settings / memory / MCP files; name+size listings of global skills, commands, subagents, rules (full listing when the hash changed or every 10th session start as a repair re-send; capped at 500 entries per list with `truncated: true` when capped). File **contents** are not sent.
24
- - **User spec (home-dir components)** — per-component delta of skills / commands / rules / memory / subagents / hooks / MCP servers / plugins from `~/.claude`, `~/.cursor`, `~/.codex`, `~/.agents`. Walked on the **first** `session_start` for a runner and again only after a **14-hour cooldown** (`user_spec_collected_at_ms` in `self-config-cache.json`); mid-cooldown session starts skip the home walk and omit `user_spec*` / `operator`. Each upsert row carries `kind`, path-derived `name`, home-relative `path`, capped file `text` (≤20_000 chars) for file-backed kinds, `content_hash`, `origin` (`user` or `plugin:<name>@<marketplace>`), `enabled`, optional `trigger` / `attributes`. Frontmatter fields (`name`, `description`, …) are not parsed on the client — the collector derives them from `text`. Only **changed or new** components are sent (`user_spec`); removals are explicit tombstones (`user_spec_removed: [{ path, name }]`). Unchanged scope after a cooldown refresh → hash/count/truncated scalars alone. First walk is a full authoritative snapshot (`user_spec_full: true`). File `text` is shipped **once per `content_hash`** (later sends omit the body when that hash was already delivered); under the ~300 KiB user-spec byte budget, overflowing bodies are deferred (`user_spec_text_deferred`) before rows are dropped. Self-config / operator caches commit only after a successful collector POST. Hook rows send `action_kind` + `action_hash` only — never the command string. MCP rows send name + transport only. Plugin rows never include `installPath` / `projectPath`. Disabled with `EV_AI_HOOK_USER_SPEC=off`.
25
- - **Operator identity** — on the first user-spec collect for an installation (and again when the 14-hour user-spec cooldown elapses): `git_user_name` / `git_user_email` from `git config` when set (`identity_source: "git_config"`). When unset, tries `GIT_AUTHOR_NAME`/`GIT_AUTHOR_EMAIL`, then `GIT_COMMITTER_*`, then `EMAIL` (`identity_source: "git_env"`). Bot-shaped git identity (`*[bot]*`, `action@github.com`, `noreply@anthropic.com`, `cursoragent@cursor.com`, …) is skipped so CI/cloud actor env vars can win: explicit `EV_AI_HOOK_OPERATOR_NAME` / `EV_AI_HOOK_OPERATOR_EMAIL` → `identity_source: "configured"`; then `GITHUB_ACTOR` / `GITHUB_TRIGGERING_ACTOR` / `GITHUB_USER` → `"github"`; `GITLAB_USER_*` → `"gitlab"`; Azure DevOps `BUILD_REQUESTEDFOR*` → `"azure_devops"`; Buildkite `BUILDKITE_BUILD_CREATOR*` → `"buildkite"`; Jenkins `BUILD_USER*` / `CHANGE_AUTHOR*` → `"jenkins"`; CircleCI `CIRCLE_USERNAME` → `"circleci"`; CodeBuild `CODEBUILD_INITIATOR` → `"codebuild"`; Drone/Woodpecker `DRONE_COMMIT_AUTHOR*` → `"drone"`. When those are also absent, falls back to the HEAD commit author from `git log -1` (`identity_source: "git_log"`). Claude Code remote (`CLAUDE_CODE_REMOTE`) and Cursor cloud (`CURSOR_AGENT`) without a git or CI actor are tagged `identity_source: "cloud"` with null name/email (no synthetic email). CI/cloud actor sources also set `platform_login` (GitHub/GitLab/CircleCI/CodeBuild/Jenkins `BUILD_USER_ID`/Drone login) so the collector can join installations to members without inventing a noreply email. Omitted while user-spec is on cooldown and in steady state when unchanged. Never invents an OS username. Disabled with the same `EV_AI_HOOK_USER_SPEC=off` opt-out.
24
+ - **User spec (home-dir components)** — per-component delta of skills / commands / rules / memory / subagents / hooks / MCP servers / plugins from `~/.claude`, `~/.cursor`, `~/.codex`, `~/.agents`. Project spec in the working directory is not part of this snapshot (in-repo files go through the git inventory pipeline; non-git cwd is recorded only as `hook_input.cwd`). Walked on the **first** `session_start` for a runner and again only after a **14-hour cooldown** (`user_spec_collected_at_ms` in `self-config-cache.json`); mid-cooldown session starts skip the home walk and omit `user_spec*` / `operator`. Each upsert row carries `kind`, path-derived `name`, home-relative `path`, capped file `text` (≤20_000 chars) for file-backed kinds, `content_hash`, `origin` (`user` or `plugin:<name>@<marketplace>`), `enabled`, optional `trigger` / `attributes`. Frontmatter fields (`name`, `description`, …) are not parsed on the client — the collector derives them from `text`. Only **changed or new** components are sent (`user_spec`); removals are explicit tombstones (`user_spec_removed: [{ path, name }]`). Unchanged scope after a cooldown refresh → hash/count/truncated scalars alone. First walk is a full authoritative snapshot (`user_spec_full: true`). File `text` is shipped **once per `content_hash`** (later sends omit the body when that hash was already delivered); under the ~300 KiB user-spec byte budget, overflowing bodies are deferred (`user_spec_text_deferred`) before rows are dropped. Self-config / operator caches commit only after a successful collector POST. Hook rows send `action_kind` + `action_hash` plus a sanitized `command` (home directory rewritten to `~`, URLs/tokens/secret-shaped args redacted, capped at 300 chars) — never the raw unsanitized string. Prompt-type hook actions send only `action_kind` + `action_hash`. MCP rows send name, `transport`, a credential-stripped `command_or_url` (from `command` / `url` / `serverUrl`), redacted `args`, env var **names** (from `env` / `envVars` / `env_vars` / `bearer_token_env_var` / `env_http_headers` values), `headers_present`, `env_http_header_names`, `auth`, `bearer_token_env_var`, `default_tools_approval_mode`, and declared tool allow/deny lists (`tools`, `auto_approve`, `always_allow`, `enabled_tools`, `disabled_tools` — tool names verbatim, boolean `auto_approve` when not a list, `<attr>_truncated` when a list is capped) — never env or header values; a server switched off in config (`enabled: false` / `disabled: true`) is reported with the row's `enabled` flag false rather than as live surface. Every other declared config key is surfaced by name with its value replaced by `<omitted>`, so the config shape is visible without its contents. Plugin rows never include `installPath` / `projectPath`. Disabled with `EV_AI_HOOK_USER_SPEC=off`.
25
+ - **Operator identity** — on the first user-spec collect for an installation (and again when the 14-hour user-spec cooldown elapses): `git_user_name` / `git_user_email` from `git config` when set (`identity_source: "git_config"`). When unset, tries `GIT_AUTHOR_NAME`/`GIT_AUTHOR_EMAIL`, then `GIT_COMMITTER_*`, then `EMAIL` (`identity_source: "git_env"`). Bot-shaped git identity (`*[bot]*`, `action@github.com`, `noreply@anthropic.com`, `cursoragent@cursor.com`, …) is skipped so CI/cloud actor env vars can win: explicit `EV_AI_HOOK_OPERATOR_NAME` / `EV_AI_HOOK_OPERATOR_EMAIL` / `EV_AI_HOOK_OPERATOR_LOGIN` → `identity_source: "configured"`; then `GITHUB_ACTOR` / `GITHUB_TRIGGERING_ACTOR` / `GITHUB_USER` → `"github"`; `GITLAB_USER_*` → `"gitlab"`; Azure DevOps `BUILD_REQUESTEDFOR*` → `"azure_devops"`; Buildkite `BUILDKITE_BUILD_CREATOR*` → `"buildkite"`; Jenkins `BUILD_USER*` / `CHANGE_AUTHOR*` → `"jenkins"`; CircleCI `CIRCLE_USERNAME` → `"circleci"`; CodeBuild `CODEBUILD_INITIATOR` → `"codebuild"`; Drone/Woodpecker `DRONE_COMMIT_AUTHOR*` → `"drone"`. When those are also absent, operator name/email stay unset — HEAD commit author is not used. Claude Code remote (`CLAUDE_CODE_REMOTE`) and Cursor cloud (`CURSOR_AGENT`) without a git or CI actor are tagged `identity_source: "cloud"`; Cursor cloud sets `git_user_email` from `CURSOR_USER_EMAIL` when it is not the image-baked bot address (never a session uuid). CI/cloud actor sources also set `platform_login` (GitHub/GitLab/CircleCI/CodeBuild/Jenkins `BUILD_USER_ID`/Drone login, Azure DevOps `BUILD_REQUESTEDFORID`, Buildkite creator email, or `EV_AI_HOOK_OPERATOR_LOGIN`) so the collector can join installations to members without inventing a noreply email. Omitted while user-spec is on cooldown and in steady state when unchanged. Never invents an OS username. Disabled with the same `EV_AI_HOOK_USER_SPEC=off` opt-out.
26
26
  - **Cloud identity bootstrap** — Cursor cloud agents do not fire `sessionStart`. On the first `tool_invoked` / skill event when operator identity has never been sent (any runtime context — cloud VMs with a pseudo-TTY often look `interactive`), the hook POSTs a lightweight `session_start` (`run_meta.trigger: cloud_identity_bootstrap`) with host/context/operator — no home user-spec walk, and no `cli_version` / `model` / `user_scope` / `hook_input` (those stay unset so the collector never treats bootstrap nulls as a probed empty config). Debounced in-process and across concurrent hook processes via an exclusive claim lock beside `installation.json` (`cloud-bootstrap.lock`); skipped when `EV_AI_HOOK_USER_SPEC=off`.
27
27
  - **Permission keys (Claude)** — each rule as `{ key, mode }` where `mode` is the list it came from (`allow` / `deny` / `ask`), so a blocked rule is never mistaken for a permitted one. Absolute POSIX / Windows / `~`-anchored paths inside a rule are replaced with `<path>` (`Bash(find /Users/me/repo -name x)` → `Bash(find <path> -name x)`) — the rule shape is the posture signal, the operator's home layout is not. Capped at 200 rules, 200 characters each.
28
28
  - **Allowlisted hook metadata** — see below (includes SessionStart `model`, `permission_mode`, …)
@@ -36,24 +36,25 @@ Every event also carries: UTC timestamp, `installation_id` (per-machine under `~
36
36
  ### On `tool_invoked`
37
37
 
38
38
  - `tool_name`, `skill_name`
39
- - **Cursor `skill_name` (derived, not from a native Skill tool):** slash commands via `beforeSubmitPrompt` (`/my-skill` → `tool_name: Skill`, `skill_name: my-skill`; prompt text is never POSTed); Read of `**/skills/<id>/SKILL.md` on `preToolUse` / `postToolUse` (skill id only — file path is never POSTed). Silent auto-inject with no slash and no SKILL.md Read is not observable.
39
+ - **Cursor `skill_name` (derived, not from a native Skill tool):** slash commands via `beforeSubmitPrompt` (`/my-skill` → `tool_name: Skill`, `skill_name: my-skill`; prompt text is never POSTed); Read of `**/skills/<id>/SKILL.md` on `preToolUse` / `postToolUse` / `beforeReadFile` (skill id only — file path is never POSTed); Shell whose command references a skill path on `beforeShellExecution` / `afterShellExecution` (id only — command string never POSTed). Silent auto-inject with no slash and no SKILL.md Read is not observable.
40
40
  - **Claude `skill_name` (derived):** slash commands via `UserPromptExpansion` (`command_name` → `tool_name: Skill`, `skill_name: <id>`; `prompt` / `command_args` are never POSTed). Typing `/skillname` bypasses `PreToolUse(Skill)`; Read of `**/skills/<id>/SKILL.md` on Pre/Post tool hooks is also derived when present.
41
41
  - **Codex `skill_name` (derived):** slash / custom-prompt ids via `UserPromptSubmit` (`/my-skill` → `tool_name: Skill`, `skill_name: my-skill`; prompt text is never POSTed); Bash/Shell whose `tool_input.command` references `.claude/.cursor/.agents/skills/<id>/SKILL.md` or `.codex/commands/<id>.md` (id only — command string never POSTed on allowlist); Read-like tools of those paths when present. Silent auto-inject with no slash and no skill-file touch is not observable.
42
42
  - `tool_use_id` — opaque Claude Pre/Post join key when present in stdin
43
- - `success` — `true` on Claude/Cursor `PostToolUse` / `postToolUse`, `false` on `PostToolUseFailure` / `postToolUseFailure` / Claude `PermissionDenied`, otherwise `null`
43
+ - `success` — `true` on Claude/Cursor `PostToolUse` / `postToolUse`, `false` on `PostToolUseFailure` / `postToolUseFailure` / Claude `PermissionDenied`, otherwise `null` (Cursor `afterFileEdit` / `afterShellExecution` have no exit code; Post* owns outcome)
44
44
  - `failure_reason` — when `success === false`, a **failure class, never a runner message**: `interrupted` (stdin `is_interrupt`), `permission_denied` (Claude `PermissionDenied`), an identifier-shaped `failure_type` / `error_type` (`timeout`, `ShellError`), else the fixed value `error`. Runner `error` / `error_message` strings are dropped — they carry raw tool stderr including absolute paths and whole result bodies.
45
- - `duration_ms` — from Claude `duration_ms` or Cursor `duration` on post-tool stdin
45
+ - `duration_ms` — from Claude `duration_ms` or Cursor `duration` on post-tool / `afterShellExecution` stdin
46
46
  - `mcp_server` / `mcp_tool` — derived from opaque `tool_name` when it matches Claude `mcp__<server>__<tool>` or Cursor `MCP:<server>:<tool>` / `MCP:<tool>` (no `tool_input` parsing)
47
+ - `component_reference` — an opaque exact-component identifier emitted only when the hook has complete repository-backed identity evidence. Exact skill paths map to SKILL installations; exact MCP server and MCP tool invocations map to the server INTERFACE installation, never to a tool installation. Name-only, flat/unattributed MCP, malformed scope, and missing platform-agent identity stay unmatched. Absolute local paths never leave the hook process: path evidence is normalized to the repository-relative source path before hashing, and only the opaque reference is sent.
47
48
  - `subagent_type` — on subagent start/stop hooks, which carry an agent type instead of a `tool_name`: Claude `agent_type` (`Explore`, plugin-scoped `my-plugin:reviewer`) or Cursor `subagent_type` (`generalPurpose`, `explore`). Only identifier-shaped values are sent; the neighbouring `task` / `description` / `summary` fields are free prose and are never captured
48
49
  - Allowlisted hook metadata (see below)
49
50
 
50
51
  ### Hook metadata (default)
51
52
 
52
- From runner stdin, only: session/conversation/turn ids (`prompt_id` / `prompt.id` / `generation_id` / `turn_id`), event name/source, status / `stop_reason` / SessionEnd `reason`, tool/skill name, `tool_use_id`, `permission_mode`, active `model` / Cursor `model_id`, `agent_id` / `agent_type`, Cursor `subagent_id` / `subagent_type` / `subagent_model` / `is_parallel_worker`, `effort` / `effort.level`, `duration_ms` / `duration`, failure category fields (`failure_type`, `is_interrupt` — the message fields `error`, `error_details`, `error_message` are **not** forwarded), Claude `UserPromptExpansion` metadata (`command_name`, `expansion_type`, `command_source` — never `prompt` / `command_args`), and git-root-relative `cwd_relative` (never absolute `cwd`). Session titles, tool args, prompts, shell commands, file contents, and tool result bodies are dropped unless the operator opts into full capture (`capture_hook_input: "full"` or `EV_AI_HOOK_CAPTURE_FULL_INPUT=1`).
53
+ From runner stdin, only: session/conversation/turn ids (`prompt_id` / `prompt.id` / `generation_id` / `turn_id`), event name/source, status / `stop_reason` / SessionEnd `reason`, tool/skill name, `tool_use_id`, `permission_mode`, active `model` / Cursor `model_id`, `agent_id` / `agent_type`, Cursor `subagent_id` / `subagent_type` / `subagent_model` / `is_parallel_worker`, `effort` / `effort.level`, `duration_ms` / `duration`, Cursor shell `sandbox` (boolean), failure category fields (`failure_type`, `is_interrupt` — the message fields `error`, `error_details`, `error_message` are **not** forwarded), Claude `UserPromptExpansion` metadata (`command_name`, `expansion_type`, `command_source` — never `prompt` / `command_args`), absolute `cwd` when stdin has it, and git-root-relative `cwd_relative` in addition when the session is inside a git repo and stdin cwd is under that root. Session titles, tool args, prompts, shell commands, file paths, file contents, edits, MCP spawn commands/URLs, and tool result bodies are dropped unless the operator opts into full capture (`capture_hook_input: "full"` or `EV_AI_HOOK_CAPTURE_FULL_INPUT=1`).
53
54
 
54
- Install wires Claude `SessionStart` / `UserPromptExpansion` / `PreToolUse` (all tools) / `PostToolUse` / `PostToolUseFailure` / `PermissionDenied` / `Stop` / `StopFailure` / `SessionEnd` / `SubagentStart` / `SubagentStop`; Cursor `sessionStart` / `beforeSubmitPrompt` / `preToolUse` / `postToolUse` / `postToolUseFailure` / `subagentStart` / `subagentStop` / `stop`; Codex `SessionStart` / `UserPromptSubmit` / `PreToolUse` (all tools) / `PostToolUse` / `Stop`. Re-run `install` to upgrade existing repos (Cursor upgrades strip retired `beforeShellExecution` / `afterFileEdit` / `beforeMCPExecution` ev-ai hooks).
55
+ Install wires Claude `SessionStart` / `UserPromptExpansion` / `PreToolUse` (all tools) / `PostToolUse` / `PostToolUseFailure` / `PermissionDenied` / `Stop` / `StopFailure` / `SessionEnd` / `SubagentStart` / `SubagentStop`; Cursor `sessionStart` / `beforeSubmitPrompt` / `preToolUse` / `postToolUse` / `postToolUseFailure` / `beforeShellExecution` / `afterShellExecution` / `beforeReadFile` / `afterFileEdit` / `beforeMCPExecution` / `subagentStart` / `subagentStop` / `stop`; Codex `SessionStart` / `UserPromptSubmit` / `PreToolUse` (all tools) / `PostToolUse` / `Stop`. Re-run `install` to upgrade existing repos (Cursor-specific shell/read/edit/MCP events are added beside generic pre/post tool hooks; `runner_event` distinguishes the row).
55
56
 
56
- When Cursor loads Claude (or Codex) file hooks as third-party configs alongside `.cursor/hooks.json`, the binary drops the foreign `--runner` twin so `platform` stays `cursor` and events are not duplicated. Claude Code and Codex hosts are unaffected.
57
+ When Cursor loads Claude (or Codex) file hooks as third-party configs alongside `.cursor/hooks.json`, the binary drops the foreign `--runner` twin so `platform` stays `cursor` and events are not duplicated. Claude Code and Codex hosts are unaffected. Stacked same-runner configs (user + project hooks, or plugin + file wiring) collapse to one POST via a short-lived claim lock (`EVENT_CLAIM_DEDUP_ENABLED=false` disables).
57
58
 
58
59
  ## PII we do not send
59
60
 
@@ -63,12 +64,12 @@ Username and hostname *are* sent (per-member usage for the installing org). The
63
64
  - Tool arguments, shell commands, and file / code contents
64
65
  - Tool error messages, stderr, and result bodies (a failure **class** is sent, never the message)
65
66
  - Contents of skills, rules, commands, memory, or settings files **outside** the user-spec path (user-scope name+size listings still omit bodies). User-spec file-backed components **do** send capped `text` (once per content hash; may be deferred under the byte budget); `description` is derived server-side
66
- - Hook command / prompt strings from the home directory (only `action_kind` + `action_hash`)
67
+ - Hook **prompt** strings (only `action_kind` + `action_hash` for `prompt`-type actions). Hook **command** strings (`command` / `bash` / `powershell`) *are* sent, sanitized: home directory rewritten to `~`, URLs/tokens/secret-shaped args redacted, capped at 300 chars
67
68
  - API keys, tokens, and other secret env vars
68
69
  - HTTP(S) proxy credentials and proxy env vars
69
70
  - Embedded credentials in git remotes and gateway URLs (`user:pass@` stripped; credential-shaped query params redacted)
70
- - MCP server commands, args, env blocks, and URLs (name/transport only)
71
+ - MCP env values, static `headers` / `http_headers` values (presence only), and the value of any config key outside the read set — unread keys ship as `<omitted>`. The read set is `type` / `command` / `url` / `serverUrl` / `args` / `env` / `envVars` / `env_vars` / `headers` / `http_headers` / `env_http_headers` / `bearer_token_env_var` / `auth` / `enabled` / `disabled` / `default_tools_approval_mode` / `tools` / `autoApprove` / `auto_approve` / `alwaysAllow` / `always_allow` / `enabledTools` / `enabled_tools` / `disabledTools` / `disabled_tools`. `bearer_token_env_var` and `env_http_headers` contribute variable and header **names** only, never the token or header value. Commands and URLs are sent with embedded credentials and credential-shaped query params stripped; args with auth-shaped keys and secret-shaped values redacted. Per-server `cwd`, `envFile`, and `roots` stay omitted — they carry home-directory layout
71
72
  - Plugin `installPath` / `projectPath` (absolute / home paths)
72
73
  - OS username as an identity substitute (git `user.name` / `user.email`, CI actor logins via `platform_login`, or CI emails are sent when available; OS username is still only present via the existing host username field)
73
- - Home-directory absolute paths (rewritten to home-relative before send), local IP addresses, and listening ports
74
+ - Home-directory absolute paths (rewritten to home-relative before send), local IP addresses, and listening ports. Exception: the absolute working directory is always sent as `cwd` when stdin has it; `cwd_relative` is added only inside a git repo
74
75
  - Data to any endpoint other than the org-configured collector
package/README.md CHANGED
@@ -70,7 +70,9 @@ npx @ev-ai/agent-hook@latest install \
70
70
  --no-cursor --no-codex
71
71
  ```
72
72
 
73
- Keep Claude and Cursor both wired. Cursor also loads `.claude/settings.json` as third-party hooks; the binary suppresses those Claude/Codex-tagged twin invocations when it detects a Cursor host, so each event posts once as `platform: cursor`. Real Claude Code sessions still use the Claude hooks unchanged.
73
+ Keep Claude and Cursor both wired. Cursor also loads `.claude/settings.json` as third-party hooks; the binary suppresses those Claude/Codex-tagged twin invocations when it detects a Cursor host, so each event posts once as `platform: cursor`. Real Claude Code sessions still use the Claude hooks unchanged. When the hook process itself is inside Cursor's command sandbox (`CURSOR_SANDBOX=seatbelt` on macOS, `native` on Linux), it acks the runner and does not POST — so a nested shell cannot mint a second `installation_id`. Official Cursor session/tool hooks still fire from the IDE host, where that variable is unset. The `sandbox` boolean on `beforeShellExecution` stdin is different: that is whether the upcoming command will be sandboxed, and is still collected.
74
+
75
+ Stacked configs for the **same** runner (user-level `~/.cursor/hooks.json` plus project `.cursor/hooks.json`, or plugins enabled alongside file wiring) also fire twice. The hook collapses those to one collect + POST via a short-lived cross-process claim under `~/.ev-ai/agent-hook/claims/` (keyed by platform, session, event, turn / `tool_use_id`, and a local hash of call-identifying stdin when `tool_use_id` is absent — so distinct Cursor shell/read/edit calls in one turn are not treated as duplicates). Weak payloads without a strong id fail open (both may post). Disable by setting `EVENT_CLAIM_DEDUP_ENABLED` to `false` in source — needed if two configs for the same runner intentionally target **different** collector URLs (the claim key does not include the URL, so only one would deliver).
74
76
 
75
77
  Wired command shape (auth is in the committed `collector_url`). The per-event command is **pinned to the installer's version** (not `@latest`):
76
78
 
@@ -126,7 +128,7 @@ npx @ev-ai/agent-hook@latest install \
126
128
 
127
129
  ### Identity and runtime notes
128
130
 
129
- Each developer's `installation_id` is created on first hook fire and stored once per machine under `~/.ev-ai/agent-hook/installation.json` (shared across all repos on that machine). Ephemeral CI/cloud homes (no durable `~/.ev-ai`) derive a stable id from platform seeds (e.g. GitHub Actions `GITHUB_REPOSITORY_ID` + `GITHUB_ACTOR`, Codespaces `CODESPACE_NAME`) so collector rows do not churn every run. Pin explicitly with `EV_AI_HOOK_INSTALLATION_ID` (8–64 chars `[A-Za-z0-9._-]`) when the environment has no actor seed (Claude Code remote / Cursor cloud).
131
+ Each developer's `installation_id` is created on first hook fire and stored once per machine under `~/.ev-ai/agent-hook/installation.json` (shared across all repos on that machine). Ephemeral CI/cloud homes (no durable `~/.ev-ai`) derive a stable id from platform seeds (e.g. GitHub Actions `GITHUB_REPOSITORY_ID` + `GITHUB_ACTOR`, Codespaces `CODESPACE_NAME`, Cursor Cloud `CURSOR_PROJECT_DIR` + `CURSOR_USER_EMAIL`, Claude Code remote origin remote + git author email) so collector rows do not churn every run. Cursor Cloud / Claude remote snapshot images that bake a random `installation.json` are rewritten to that derived id. Pin explicitly with `EV_AI_HOOK_INSTALLATION_ID` (8–64 chars `[A-Za-z0-9._-]`) when the environment has no actor seed.
130
132
 
131
133
  Per-event execution uses `npx` (primary) or the pinned binary (CDN path). The runner-facing process **acks immediately** (`{"continue":true}` + exit 0) after draining stdin and spawning a detached `__work` child that collects + POSTs — **except teardown events**, which stay in-process and await the HTTP POST so a runner that tears down the process tree on exit cannot kill the worker mid-flight. Teardown = Claude `SessionEnd` / `StopFailure`, Codex `Stop` (its only end signal), and `SubagentStop`. Per-turn Claude `Stop` / Cursor `stop` fire at the end of **every turn** (not teardown), so they detach like tool events and never block the runner between turns. Set `EV_AI_HOOK_SYNC=1` to keep all events in-process for debugging.
132
134
 
@@ -147,7 +149,7 @@ For the **plugin** path, do not add ev-ai per-event hooks to `.claude/settings.j
147
149
  - Teardown events stay in-process (sync POST) — Claude `SessionEnd` / `StopFailure`, Codex `Stop`, and `SubagentStop`, because the runner may kill detached children when the session/worker tree is torn down
148
150
  - POST / spawn failures log to stderr only
149
151
 
150
- Debug envelope logging: `EV_AI_HOOK_DEBUG=1` (redacted summary). Full envelope: `EV_AI_HOOK_DEBUG=full`. Force all events in-process: `EV_AI_HOOK_SYNC=1`.
152
+ Debug envelope logging: `EV_AI_HOOK_DEBUG=1` (redacted summary). Full envelope: `EV_AI_HOOK_DEBUG=full`. Force all events in-process: `EV_AI_HOOK_SYNC=1`. Disable duplicate-config claim collapsing by setting `EVENT_CLAIM_DEDUP_ENABLED` to `false` in source (use when two configs for the same runner must POST to different collectors).
151
153
 
152
154
  ## Privacy defaults
153
155
 
package/dist/cli.mjs CHANGED
@@ -1,23 +1,33 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'node:module';
3
+ const require = __createRequire(import.meta.url);
2
4
 
3
- import{realpathSync as Xa}from"node:fs";import{resolve as qa}from"node:path";import{fileURLToPath as Za,pathToFileURL as Qa}from"node:url";var io="https://hooks.ev-ai.ai";function Ie(e,t=io){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var Re=".claude/ev-ai-runtime-report.json",Xt="node_modules/@ev-ai/agent-hook/dist/hook.mjs",J="ev-ai-agent-hook",qt="https://cdn.ev-ai.ai/agent-hook",ze=`current/${J}`,Ye=`.ev-ai/agent-hook/${J}`,Zt=5e3,Qt=5e3,Xe=3e3;var qe=3e3,en=1500,tn=4*1024,nn=32*1024,ao=4*1024,H="1.0.7",Ce=`@ev-ai/agent-hook@${H}`,rn="ev-ai runtime report",on=["claude","cursor","codex"];import{chmodSync as jn,cpSync as Bn,existsSync as F,mkdirSync as ut,readdirSync as Do,readFileSync as Fo,rmSync as be,symlinkSync as jo,writeFileSync as Bo}from"node:fs";import{homedir as j}from"node:os";import{basename as $o,dirname as dt,isAbsolute as Go,join as h,relative as $n,resolve as Dn,sep as Ko}from"node:path";import{fileURLToPath as Jo}from"node:url";var co=new Set(["localhost","127.0.0.1","[::1]","::1"]),sn=/^[A-Za-z0-9._~-]+$/;function an(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function xe(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?co.has(t.hostname):!1}catch{return!1}}function ae(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!xe(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=lo(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!sn.test(n))return`org token must match ${sn.source} (got: ${n})`;if(an(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(an(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function ce(e){return new URL(e).toString()}function lo(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function Ze(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function cn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?Ie(t):""}import{createHash as Sn,randomBytes as So}from"node:crypto";import{existsSync as En,mkdirSync as yn,readFileSync as kn,unlinkSync as In,writeFileSync as Rn}from"node:fs";import{homedir as tt}from"node:os";import{dirname as nt,join as rt,resolve as Eo}from"node:path";import{randomBytes as uo}from"node:crypto";import{existsSync as fn,mkdirSync as fo,readdirSync as po,readFileSync as mo,renameSync as ln,statSync as pn,unlinkSync as un,writeFileSync as go}from"node:fs";import{basename as ho,dirname as dn,join as mn,relative as _o}from"node:path";function d(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
4
- `)}function z(e,t){fo(dn(e),{recursive:!0});let n=mn(dn(e),`.${ho(e)}.${process.pid}.${uo(4).toString("hex")}.tmp`);try{go(n,t,"utf8");try{ln(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){un(e),ln(n,e);return}throw r}}catch(r){try{un(n)}catch{}throw r}}function Ae(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function gn(){process.stdout.write('{"continue":true}')}function E(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function le(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function et(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function D(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,u=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:u,spawnFailed:u===void 0}}}async function C(e,t,n=3e3,r={}){let o=await D(e,t,n,r);return o.ok?o.stdout:""}async function M(e=process.cwd()){return await C("git",["rev-parse","--show-toplevel"],2e3,{cwd:e})||e}function v(e,t){try{return JSON.parse(e)}catch{return t}}var Qe=new Map;function ne(e,t){let n=Qe.get(e);if(n!==void 0)return n;try{let r=v(mo(e,"utf8"),t);return Qe.set(e,r),r}catch{return Qe.set(e,t),t}}function ue(e){return typeof e=="string"?e:""}function Y(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function m(e,t){let n=Y(e,t);return typeof n=="string"?n:""}var X=500;function de(e,t=2){if(!fn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=po(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let u=mn(s,c.name);if(c.isDirectory()){o(u,i+1);continue}if(c.isFile()){try{n.push({name:_o(e,u),size:pn(u).size})}catch{continue}if(n.length>=X){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function fe(e){return fn(e)?{present:!0,size:pn(e).size}:{present:!1,size:0}}var yo="installation.json",ko="cloud-bootstrap.lock",Io=6e4;function Cn(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function ot(e=tt()){return rt(e,".ev-ai","agent-hook")}function Ro(e=tt()){return rt(ot(e),yo)}function xn(e){return rt(nt(e),ko)}function An(){return So(8).toString("hex")}function Te(e){return Sn("sha256").update(e).digest("hex").slice(0,16)}function k(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Tn(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Co(e=process.env){let t=k(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Tn(t)){d(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function xo(e=process.env){if(k(e.GITHUB_ACTIONS)){let t=k(e.GITHUB_REPOSITORY_ID)??k(e.GITHUB_REPOSITORY),n=k(e.GITHUB_ACTOR)??k(e.GITHUB_TRIGGERING_ACTOR)??k(e.GITHUB_USER);if(t&&n)return Te(`github_actions|${t}|${n}`)}if(k(e.CODESPACES)||k(e.CODESPACE_NAME)){let t=k(e.CODESPACE_NAME);if(t)return Te(`codespaces|${t}`);let n=k(e.GITHUB_REPOSITORY_ID)??k(e.GITHUB_REPOSITORY),r=k(e.GITHUB_USER)??k(e.GITHUB_ACTOR);if(n&&r)return Te(`codespaces|${n}|${r}`)}if(k(e.GITLAB_CI)){let t=k(e.CI_PROJECT_ID)??k(e.CI_PROJECT_PATH),n=k(e.GITLAB_USER_LOGIN)??k(e.GITLAB_USER_EMAIL)??k(e.GITLAB_USER_NAME);if(t&&n)return Te(`gitlab|${t}|${n}`)}return null}function hn(e,t){if(e&&Tn(e))return e;e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`);let n=Co(t);if(n)return n;let r=xo(t);return r||An()}async function Ao(e){let n=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Eo(e);return Sn("sha256").update(n).digest("hex").slice(0,16)}function To(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&r.length>0&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function Oo(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=To(t.platform_agent_ids);return{installation_id:t.installation_id,...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function q(e){if(En(e))try{return Oo(kn(e,"utf8"))}catch{}}function st(e){return q(e)}function On(e,t,n){let r=q(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{z(e,`${JSON.stringify(o,null,2)}
5
- `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: operator identity cache write failed open: ${i}`)}}function vn(e,t=Date.now()){if(!e)return!0;if(q(e)?.operator_identity_hash)return!1;let n=xn(e);try{if(En(n)){let r=Number.NaN;try{r=Number(kn(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Io)return!1;try{In(n)}catch{}}}catch{}try{return yn(nt(n),{recursive:!0}),Rn(n,`${t}
6
- `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(Pn(r))return!1;let o=r instanceof Error?r.message:String(r);return d(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function bn(e){if(e)try{In(xn(e))}catch{}}function wn(e,t){let r=q(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Un(e,t,n){if(!n)return;let r=q(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{z(e,`${JSON.stringify(o,null,2)}
7
- `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${i}`)}}function Pn(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function vo(e,t){yn(nt(e),{recursive:!0}),Rn(e,`${JSON.stringify(t,null,2)}
8
- `,{encoding:"utf8",flag:"wx"})}function _n(e,t){try{return vo(e,t),t}catch(n){if(!Pn(n))throw n;return q(e)}}async function Oe(e,t={}){let n=t.home??tt(),r=t.env??process.env,o=await Ao(e),s=Ro(n),i=q(s);if(i)return{installationId:i.installation_id,storePath:s,repoKey:o};let a=hn(t.overrideId,r),c=_n(s,{installation_id:a});if(c)return{installationId:c.installation_id,storePath:s,repoKey:o};let u=hn(void 0,r),l=_n(s,{installation_id:u===a?An():u});if(l)return{installationId:l.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as it,readFileSync as bo}from"node:fs";import{dirname as wo,join as Nn,relative as Uo}from"node:path";var ve=[Re,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Po(e=process.cwd(),t){let n=E("EV_AI_HOOK_MANIFEST");if(n&&it(n))return n;let r=t??await M(e);for(let o of ve){let s=Nn(r,o);if(it(s))return s}for(let o of ve){let s=Nn(e,o);if(it(s))return s}}async function No(e,t){let n=t??await M(wo(e)),r=Uo(n,e),o=await D("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(d(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Mo(e){let t=bo(e,"utf8");return v(t,{})}function Lo(){return{schema_version:2,mcp_servers:[]}}async function Mn(e=process.cwd()){let t=await M(e),n=await Po(e,t),r=n?Mo(n):Lo();delete r.installation_id;let o=n?await No(n,t):!1;r.capture_hook_input==="full"&&n&&o&&(d(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${n}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete r.capture_hook_input);let{installationId:s,storePath:i,repoKey:a}=await Oe(t);return{manifestPath:n??i,manifest:r,installationId:s,installationStorePath:i,repoKey:a,collectorUrl:cn(r),platformAgentId:r.platform_agent_id??"",gitRoot:t}}function Ln(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var Ho=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"];function at(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0}function Hn(e=process.platform,t=process.arch){let n=at(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${Ho.join(", ")}.`);return n}function ct(e){return`compile-out/bin/${e}/ev-ai-agent-hook`}function Vo(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=ae(n);if(r)throw new Error(`collector URL rejected: ${r}`);return ce(n)}function Wo(e){let t=e.collectorUrl?.trim();if(!t)return;let n=ae(t);if(n)throw new Error(`collector URL rejected: ${n}`);return ce(t)}function zo(e){return Vo(e,"install")}function Gn(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url")}return t}function Kn(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url");if(r==="--update")throw new Error("--update was removed; use the `update` command instead of `install --update`");if(r==="--delivery"){let o=e[n+1];(o==="npx"||o==="binary"||o==="local")&&(t.delivery=o,n+=1);continue}if(r==="--force"){t.force=!0;continue}if(r==="--no-claude"){t.skipClaude=!0;continue}if(r==="--no-cursor"){t.skipCursor=!0;continue}if(r==="--no-codex"){t.skipCodex=!0;continue}}return t}function Jn(e=process.execPath){return Vn(e)?"binary":"npx"}function Yo(){return h(j(),".ev-ai","agent-hook")}function Xo(e=j()){return h(e,".ev-ai","agent-hook",ze)}function qo(){let e=dt(Jo(import.meta.url)),t=h(e,"hook.mjs");return F(t)?t:h(e,"..","dist","hook.mjs")}function Vn(e=process.execPath){return $o(e)===J}function Wn(e,t){let n=$n(Dn(e),Dn(t));return!n.startsWith("..")&&!Go(n)}function we(e){return e.split(Ko).join("/")}function Zo(e){return`node "$(git rev-parse --show-toplevel)/${we(e)}"`}function Qo(e){return`"$(git rev-parse --show-toplevel)/${we(e)}"`}function es(e){return h(e,Ye)}function zn(e,t){let n=es(e);ut(dt(n),{recursive:!0}),Bn(t,n,{force:!0});try{jn(n,493)}catch{}return n}function ts(e){let t=h(Yo(),"current");try{be(t,{recursive:!0,force:!0})}catch{}jo(e,t,process.platform==="win32"?"junction":"dir")}function Yn(e,t=H,n=j()){let r=h(n,".ev-ai","agent-hook",t),o=h(r,J);ut(r,{recursive:!0}),Bn(e,o,{force:!0});try{jn(o,493)}catch{}return ts(r),h(n,".ev-ai","agent-hook",ze)}function Xn(e){let t=at();if(!t)return;let n=[h(e,ct(t)),h(e,"packages","agent-hook",ct(t))];for(let r of n)if(F(r)&&Wn(e,r))return r}function ns(e=j()){let t=Xo(e);return F(t)?t:void 0}function rs(e,t=j()){let n=ns(t);return n||(Vn()?Yn(process.execPath,H,t):Xn(e))}function os(e,t=j()){let n=Xn(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
9
- To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=Yn(n,H,t),o=zn(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function Fn(e){let t=[h(e,"packages","agent-hook","dist","hook.mjs"),h(e,Xt)],n=qo();F(n)&&Wn(e,n)&&t.unshift(n);for(let r of t){if(!F(r))continue;let o=we($n(e,r));return{command:Zo(o),hookPath:o,strategy:"dev_mjs"}}}function ss(e=Ce){return`npx -y ${e}`}function is(e,t=j(),n=Jn()){if(n==="npx")return{command:ss(),hookPath:Ce,strategy:"npx"};if(n==="local"){let s=Fn(e);if(s)return s;throw new Error("local delivery requires packages/agent-hook/dist/hook.mjs (or node_modules/@ev-ai/agent-hook/dist/hook.mjs) under the git root \u2014 run yarn workspace @ev-ai/agent-hook build first")}let r=rs(e,t);if(r){zn(e,r);let s=we(Ye);return{command:Qo(s),hookPath:s,strategy:"project_binary"}}let o=Fn(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
10
- curl -fsSL ${qt}/install.sh | sh
5
+ var ls=Object.create;var In=Object.defineProperty;var us=Object.getOwnPropertyDescriptor;var ds=Object.getOwnPropertyNames;var fs=Object.getPrototypeOf,ps=Object.prototype.hasOwnProperty;var kn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ms=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var gs=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of ds(t))!ps.call(e,o)&&o!==n&&In(e,o,{get:()=>t[o],enumerable:!(r=us(t,o))||r.enumerable});return e};var _s=(e,t,n)=>(n=e!=null?ls(fs(e)):{},gs(t||!e||!e.__esModule?In(n,"default",{value:e,enumerable:!0}):n,e));var ao=ms(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.ComponentKind=void 0;M.userConfigRootFromPath=nc;M.installationRootExternalKey=rc;M.normalizeRepositoryRelativePath=so;M.nativeKeyForSkillPath=oc;M.serializeComponentIdentity=io;M.buildComponentReference=ic;M.validateComponentReference=ac;var Ya=kn("node:crypto"),Xa=kn("node:path"),Za="cmp1_",qa=/^cmp1_[A-Za-z0-9_-]{43}$/,Qa=["/skills/","/skills-cursor/"],ec=[".cursor",".claude",".codex"],tc={".claude.json":".claude",".agents":".codex"};M.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE"};function nc(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>ec.includes(o));return n||(t.map(o=>tc[o]).find(o=>o!==void 0)??"unknown")}function rc(e,t){return`runtime-install:${e}/${t}`}function Ye(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function so(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=Xa.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Ye(n,"sourcePath")}function oc(e){let t=e.replaceAll("\\","/");for(let n of Qa){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function sc(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function io(e){let t=[Ye(e.installationRootExternalKey,"installationRootExternalKey"),Ye(e.installableKind,"installableKind"),so(e.sourcePath),Ye(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(sc).join("|")}`,"utf8")}function ic(e){let t=(0,Ya.createHash)("sha256").update(io(e)).digest("base64url");return`${Za}${t}`}function ac(e){return qa.test(e)}});import{realpathSync as Cu}from"node:fs";import{resolve as Au}from"node:path";import{fileURLToPath as vu,pathToFileURL as Ou}from"node:url";var hs="https://hooks.ev-ai.ai";function Ue(e,t=hs){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var Le=".claude/ev-ai-runtime-report.json",Cn="node_modules/@ev-ai/agent-hook/dist/hook.mjs",Y="ev-ai-agent-hook",An="https://cdn.ev-ai.ai/agent-hook",mt=`current/${Y}`,gt=`.ev-ai/agent-hook/${Y}`,vn=5e3,On=5e3,_t=3e3;var ht=3e3,xn=1500,Tn=4*1024,bn=32*1024,Es=4*1024,B="1.0.9",Me=`@ev-ai/agent-hook@${B}`,wn="ev-ai runtime report",Pn=["claude","cursor","codex"];import{chmodSync as hr,cpSync as Er,existsSync as K,mkdirSync as Lt,readdirSync as Ei,readFileSync as Si,rmSync as je,symlinkSync as yi,writeFileSync as Ri}from"node:fs";import{homedir as G}from"node:os";import{basename as Ii,dirname as Mt,isAbsolute as ki,join as y,relative as Sr,resolve as gr,sep as Ci}from"node:path";import{fileURLToPath as Ai}from"node:url";var Ss=new Set(["localhost","127.0.0.1","[::1]","::1"]),Nn=/^[A-Za-z0-9._~-]+$/;function Un(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function He(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Ss.has(t.hostname):!1}catch{return!1}}function ge(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!He(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=ys(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Nn.test(n))return`org token must match ${Nn.source} (got: ${n})`;if(Un(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Un(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function _e(e){return new URL(e).toString()}function ys(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function Et(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function Ln(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?Ue(t):""}import{createHash as Yn,randomBytes as Ks}from"node:crypto";import{existsSync as Xn,mkdirSync as Ot,readFileSync as Zn,unlinkSync as qn,writeFileSync as Qn}from"node:fs";import{homedir as xt}from"node:os";import{dirname as Fe,join as Tt,resolve as Gs}from"node:path";var Rs=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),Is=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function Q(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||Is.has(n)||r.includes("[bot]")||Rs.has(r))return!0;if(r.endsWith("@users.noreply.github.com")){let o=r.slice(0,r.indexOf("@")),s=o.includes("+")?o.slice(o.indexOf("+")+1):o;if(s.endsWith("bot")||s.includes("[bot]"))return!0}return!1}import{existsSync as bs,readFileSync as ws}from"node:fs";import{hostname as jn,userInfo as Ps}from"node:os";import{randomBytes as ks}from"node:crypto";import{existsSync as yt,mkdirSync as Cs,readdirSync as As,readFileSync as vs,renameSync as Mn,statSync as Fn,unlinkSync as Hn,writeFileSync as Os}from"node:fs";import{basename as xs,dirname as Dn,join as $n,relative as Ts}from"node:path";function d(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
6
+ `)}function X(e,t){Cs(Dn(e),{recursive:!0});let n=$n(Dn(e),`.${xs(e)}.${process.pid}.${ks(4).toString("hex")}.tmp`);try{Os(n,t,"utf8");try{Mn(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Hn(e),Mn(n,e);return}throw r}}catch(r){try{Hn(n)}catch{}throw r}}function De(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Bn(){process.stdout.write('{"continue":true}')}function A(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function he(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function Rt(e){return new Promise(t=>{let n="",r=!1,o=a=>{r||(r=!0,clearTimeout(s),t(a||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",a=>{n+=a}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function L(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),a=s(o);try{let{stdout:i}=await a(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:i.trim()}}catch(i){let c=i,l=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:l,spawnFailed:l===void 0}}}async function v(e,t,n=3e3,r={}){let o=await L(e,t,n,r);return o.ok?o.stdout:""}async function It(e=process.cwd()){let t=await L("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(A("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;d(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=A("CURSOR_PROJECT_DIR")??A("CLAUDE_PROJECT_DIR");if(n&&yt(n)){let r=await L("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function j(e=process.cwd()){return(await It(e)).root}function P(e,t){try{return JSON.parse(e)}catch{return t}}var St=new Map;function ae(e,t){let n=St.get(e);if(n!==void 0)return n;try{let r=P(vs(e,"utf8"),t);return St.set(e,r),r}catch{return St.set(e,t),t}}function ee(e){return typeof e=="string"?e:""}function te(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function g(e,t){let n=te(e,t);return typeof n=="string"?n:""}var F=500;function Ee(e,t=2){if(!yt(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,a)=>{if(a>t||r)return;let i;try{i=As(s,{withFileTypes:!0})}catch{return}for(let c of i){if(r)return;let l=$n(s,c.name);if(c.isDirectory()){o(l,a+1);continue}if(c.isFile()){try{n.push({name:Ts(e,l),size:Fn(l).size})}catch{continue}if(n.length>=F){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Se(e){return yt(e)?{present:!0,size:Fn(e).size}:{present:!1,size:0}}function ce(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function kt(e=process.env){return ce(k("CURSOR_SANDBOX",e))}var Ns=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Us(e){return Ns.some(t=>!!k(t,e))}function Ls(e){if(k("KUBERNETES_SERVICE_HOST",e)||ce(k("REMOTE_CONTAINERS",e))||ce(k("DEVCONTAINER",e)))return!0;try{if(bs("/.dockerenv")||ws("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Kn(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!k(t,e))}function Ms(e,t=process.platform){return Kn(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!k(n,e)):!1}function Hs(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Ds(e){return e==="linux"}function k(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return A(e)}function Fs(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!$s(k("CURSOR_VERSION",n))}function $s(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Ct(e){if(Hs(e.sessionId))return!0;let t=e.hostname??jn(),n=e.osUser??Gn(e.env);return Fs(t,n,e.env)}function Bs(e){return ce(k("CURSOR_AGENT",e.env))?!0:Ct(e)}function js(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(k("TERM",e)??k("TERM_PROGRAM",e))||(k("SSH_TTY",e)??k("SSH_CONNECTION",e))||(k("__CFBundleIdentifier",e)??k("XPC_SERVICE_NAME",e))||Kn(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!k(t,e))||k("SESSIONNAME",e))}function ye(e={}){let t=e.env;if(k("GITHUB_ACTIONS",t))return"github_actions";if(ce(k("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Ms(t,n)&&Bs(e)&&(ce(k("CURSOR_AGENT",t))||Ds(n)))return"cursor_cloud";if(k("CODESPACES",t)||k("CODESPACE_NAME",t))return"codespaces";if(k("GITLAB_CI",t))return"gitlab_ci";if(Us(t))return"managed";let r=k("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Ls(t)?"container":js(t)?"interactive":"unknown"}async function At(){return await v("systemd-detect-virt",[],1e3)}function Gn(e=process.env,t=Ps){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function vt(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await v("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),a=s("/etc/os-release","utf8"),i=a.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=a.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=i??c??""}catch{t=await v("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await v("uname",["-r"],1e3))}else t=await v("ver",[],1e3);let n=Gn(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await v("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function Re(){return jn()}var Js="installation.json",Vs="cloud-bootstrap.lock",zs=6e4;function er(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function Ie(e=xt()){return Tt(e,".ev-ai","agent-hook")}function Ws(e=xt()){return Tt(Ie(e),Js)}function tr(e){return Tt(Fe(e),Vs)}function nr(){return Ks(8).toString("hex")}function le(e){return Yn("sha256").update(e).digest("hex").slice(0,16)}function S(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function rr(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Ys(e=process.env){let t=S(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!rr(t)){d(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function or(e,t){return e&&rr(e)?e:(e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Ys(t))}function Xs(e){return/^[0-9a-f]{16}$/.test(e)}function Zs(e=process.env){if(S(e.GITHUB_ACTIONS)){let t=S(e.GITHUB_REPOSITORY_ID)??S(e.GITHUB_REPOSITORY),n=S(e.GITHUB_ACTOR)??S(e.GITHUB_TRIGGERING_ACTOR)??S(e.GITHUB_USER);if(t&&n)return le(`github_actions|${t}|${n}`)}if(S(e.CODESPACES)||S(e.CODESPACE_NAME)){let t=S(e.CODESPACE_NAME);if(t)return le(`codespaces|${t}`);let n=S(e.GITHUB_REPOSITORY_ID)??S(e.GITHUB_REPOSITORY),r=S(e.GITHUB_USER)??S(e.GITHUB_ACTOR);if(n&&r)return le(`codespaces|${n}|${r}`)}if(S(e.GITLAB_CI)){let t=S(e.CI_PROJECT_ID)??S(e.CI_PROJECT_PATH),n=S(e.GITLAB_USER_LOGIN)??S(e.GITLAB_USER_EMAIL)??S(e.GITLAB_USER_NAME);if(t&&n)return le(`gitlab|${t}|${n}`)}return null}var qs="cursoragent@cursor.com";function Qs(e){let t=S(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===qs?null:t}function ei(e,t){return S(e.CURSOR_PROJECT_DIR)??S(e.CLAUDE_PROJECT_DIR)??t}function ti(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function ni(e){let t=await v("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?ti(t):e}async function ri(e){let t=S(await v("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!Q(null,t))return t;let n=S(await v("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!Q(null,n)?n:null}function oi(e,t){let n=ei(e,t);return n?le(`cursor_cloud|${n}|${Qs(e)??""}`):null}async function si(e,t){let n=S(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await ni(n),o=await ri(n);return le(`claude_remote|${r}|${o??""}`)}function Jn(e,t){let n=or(e,t);if(n)return n;let r=Zs(t);return r||nr()}async function ii(e){let n=await v("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Gs(e);return Yn("sha256").update(n).digest("hex").slice(0,16)}function ai(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&r.length>0&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function ci(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=ai(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function ne(e){if(Xn(e))try{return ci(Zn(e,"utf8"))}catch{}}function bt(e){return ne(e)}function sr(e,t,n){let r=ne(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{X(e,`${JSON.stringify(o,null,2)}
7
+ `)}catch(s){let a=s instanceof Error?s.message:String(s);d(`WARN: operator identity cache write failed open: ${a}`)}}function ir(e,t=Date.now()){if(!e)return!0;if(ne(e)?.operator_identity_hash)return!1;let n=tr(e);try{if(Xn(n)){let r=Number.NaN;try{r=Number(Zn(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<zs)return!1;try{qn(n)}catch{}}}catch{}try{return Ot(Fe(n),{recursive:!0}),Qn(n,`${t}
8
+ `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(ur(r))return!1;let o=r instanceof Error?r.message:String(r);return d(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function ar(e){if(e)try{qn(tr(e))}catch{}}function cr(e,t){let r=ne(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function lr(e,t,n){if(!n)return;let r=ne(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{X(e,`${JSON.stringify(o,null,2)}
9
+ `)}catch(s){let a=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${a}`)}}function ur(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function li(e,t){Ot(Fe(e),{recursive:!0}),Qn(e,`${JSON.stringify(t,null,2)}
10
+ `,{encoding:"utf8",flag:"wx"})}function Vn(e,t){try{return li(e,t),t}catch(n){if(!ur(n))throw n;return ne(e)}}function zn(e,t){Ot(Fe(e),{recursive:!0}),X(e,`${JSON.stringify(t,null,2)}
11
+ `)}function Wn(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function $e(e,t={}){let n=t.home??xt(),r=t.env??process.env,o=await ii(e),s=Ws(n),a={sessionId:t.sessionId,hostname:S(r.HOSTNAME)??void 0,osUser:S(r.USER)??S(r.LOGNAME)??S(r.USERNAME)??void 0,env:r},i=ye(a),c=or(t.overrideId,r),l=i==="cursor_cloud"&&Ct(a)?oi(r,e):i==="claude_remote"?await si(r,e):null,u=ne(s);if(u){let h=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(h={...u,pinned:!0},zn(s,h)),!!l&&l!==h.installation_id&&!c&&h.pinned!==!0&&Xs(h.installation_id)&&l){let I={installation_id:l,...h.platform_agent_ids?{platform_agent_ids:h.platform_agent_ids}:{}};return zn(s,I),{installationId:l,storePath:s,repoKey:o}}return{installationId:h.installation_id,storePath:s,repoKey:o}}let f=c??l??Jn(void 0,r),m=Vn(s,Wn(f,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let p=c??l??Jn(void 0,r),_=Vn(s,Wn(p===f?nr():p,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as wt,readFileSync as ui}from"node:fs";import{dirname as di,join as dr,relative as fi}from"node:path";var Be=[Le,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function pi(e=process.cwd(),t){let n=A("EV_AI_HOOK_MANIFEST");if(n&&wt(n))return n;let r=t??await j(e);for(let o of Be){let s=dr(r,o);if(wt(s))return s}for(let o of Be){let s=dr(e,o);if(wt(s))return s}}async function mi(e,t){let n=t??await j(di(e)),r=fi(n,e),o=await L("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(d(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function gi(e){let t=ui(e,"utf8");return P(t,{})}function _i(){return{schema_version:2,mcp_servers:[]}}async function fr(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await It(e),o=await pi(e,n),s=o?gi(o):_i();delete s.installation_id;let a=o?await mi(o,n):!1;s.capture_hook_input==="full"&&o&&a&&(d(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${o}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete s.capture_hook_input);let{installationId:i,storePath:c,repoKey:l}=await $e(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:i,installationStorePath:c,repoKey:l,collectorUrl:Ln(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function pr(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var hi=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"];function Pt(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0}function mr(e=process.platform,t=process.arch){let n=Pt(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${hi.join(", ")}.`);return n}function Nt(e){return`compile-out/bin/${e}/ev-ai-agent-hook`}function vi(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=ge(n);if(r)throw new Error(`collector URL rejected: ${r}`);return _e(n)}function Oi(e){let t=e.collectorUrl?.trim();if(!t)return;let n=ge(t);if(n)throw new Error(`collector URL rejected: ${n}`);return _e(t)}function xi(e){return vi(e,"install")}function yr(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url")}return t}function Rr(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url");if(r==="--update")throw new Error("--update was removed; use the `update` command instead of `install --update`");if(r==="--delivery"){let o=e[n+1];(o==="npx"||o==="binary"||o==="local")&&(t.delivery=o,n+=1);continue}if(r==="--force"){t.force=!0;continue}if(r==="--no-claude"){t.skipClaude=!0;continue}if(r==="--no-cursor"){t.skipCursor=!0;continue}if(r==="--no-codex"){t.skipCodex=!0;continue}}return t}function Ir(e=process.execPath){return kr(e)?"binary":"npx"}function Ti(){return y(G(),".ev-ai","agent-hook")}function bi(e=G()){return y(e,".ev-ai","agent-hook",mt)}function wi(){let e=Mt(Ai(import.meta.url)),t=y(e,"hook.mjs");return K(t)?t:y(e,"..","dist","hook.mjs")}function kr(e=process.execPath){return Ii(e)===Y}function Cr(e,t){let n=Sr(gr(e),gr(t));return!n.startsWith("..")&&!ki(n)}function Ke(e){return e.split(Ci).join("/")}function Pi(e){return`node "$(git rev-parse --show-toplevel)/${Ke(e)}"`}function Ni(e){return`"$(git rev-parse --show-toplevel)/${Ke(e)}"`}function Ui(e){return y(e,gt)}function Ar(e,t){let n=Ui(e);Lt(Mt(n),{recursive:!0}),Er(t,n,{force:!0});try{hr(n,493)}catch{}return n}function Li(e){let t=y(Ti(),"current");try{je(t,{recursive:!0,force:!0})}catch{}yi(e,t,process.platform==="win32"?"junction":"dir")}function vr(e,t=B,n=G()){let r=y(n,".ev-ai","agent-hook",t),o=y(r,Y);Lt(r,{recursive:!0}),Er(e,o,{force:!0});try{hr(o,493)}catch{}return Li(r),y(n,".ev-ai","agent-hook",mt)}function Or(e){let t=Pt();if(!t)return;let n=[y(e,Nt(t)),y(e,"packages","agent-hook",Nt(t))];for(let r of n)if(K(r)&&Cr(e,r))return r}function Mi(e=G()){let t=bi(e);return K(t)?t:void 0}function Hi(e,t=G()){let n=Mi(t);return n||(kr()?vr(process.execPath,B,t):Or(e))}function Di(e,t=G()){let n=Or(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
12
+ To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=vr(n,B,t),o=Ar(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function _r(e){let t=[y(e,"packages","agent-hook","dist","hook.mjs"),y(e,Cn)],n=wi();K(n)&&Cr(e,n)&&t.unshift(n);for(let r of t){if(!K(r))continue;let o=Ke(Sr(e,r));return{command:Pi(o),hookPath:o,strategy:"dev_mjs"}}}function Fi(e=Me){return`npx -y ${e}`}function $i(e,t=G(),n=Ir()){if(n==="npx")return{command:Fi(),hookPath:Me,strategy:"npx"};if(n==="local"){let s=_r(e);if(s)return s;throw new Error("local delivery requires packages/agent-hook/dist/hook.mjs (or node_modules/@ev-ai/agent-hook/dist/hook.mjs) under the git root \u2014 run yarn workspace @ev-ai/agent-hook build first")}let r=Hi(e,t);if(r){Ar(e,r);let s=Ke(gt);return{command:Ni(s),hookPath:s,strategy:"project_binary"}}let o=_r(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
13
+ curl -fsSL ${An}/install.sh | sh
11
14
  Or use npx delivery:
12
- npx ${Ce} install`)}function qn(e){return typeof e!="string"?!1:e.includes("@ev-ai/agent-hook")||e.includes("agent-hook/dist/hook")||e.includes(".ev-ai/agent-hook")||e.includes(J)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function ft(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function V(e,t){ut(dt(e),{recursive:!0}),Bo(e,`${JSON.stringify(t,null,2)}
13
- `,"utf8")}function B(e){if(F(e))try{return JSON.parse(Fo(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function as(e,t){let n=Ln(t.collectorUrl),r={...e,schema_version:e?.schema_version??n.schema_version};return t.collectorUrl!==void 0?r.collector_url=t.collectorUrl:r.collector_url=e?.collector_url??n.collector_url,delete r.repo_ingest_token,delete r.installation_id,r.mcp_servers??=n.mcp_servers,r}function cs(e){return(e.schema_version??2)===2&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.repo_ingest_token===void 0}function Zn(e,t){let n=h(e,Re),r=B(n),o=as(r,t);return t.collectorUrl!==void 0||F(n)||!cs(o)?(V(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function lt(e){if(e===null||typeof e!="object")return!1;let t=e,n=String(t.CLAUDE_CODE_ENABLE_TELEMETRY??"").toLowerCase();return n==="1"||n==="true"?!0:Object.keys(t).some(r=>r.startsWith("OTEL_"))}function ls(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return h(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function us(e=process.platform){let t=ls(e),n=[h(t,"managed-settings.json")],r=h(t,"managed-settings.d");try{if(!F(r))return n;let o=Do(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>h(r,s));n.push(...o)}catch{}return n}function ds(e){if(lt(process.env))return!0;let t=j();return[...us(),h(t,".claude","settings.json"),h(t,".claude","remote-settings.json"),h(e,".claude","settings.json"),h(e,".claude","settings.local.json")].some(r=>{try{let o=B(r);return o?lt(o.env):!1}catch{return!1}})}function fs(e){try{let t=B(h(e,".claude","settings.json"));return t?lt(t.env):!1}catch{return!1}}function Qn(e){return Array.isArray(e)?e:[]}function Ue(e){let t=[],n=r=>!!r&&typeof r=="object"&&qn(r.command);for(let r of Qn(e)){if(!r||typeof r!="object"){t.push(r);continue}let o=Array.isArray(r.hooks)?r.hooks:[],s=o.filter(i=>!n(i));if(!(s.length===0&&o.some(n))){if(s.length!==o.length){t.push({...r,hooks:s});continue}t.push(r)}}return t}function er(e,t){return[...Ue(e),...t]}function pt(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!qn(t.command)):[]}function ps(e,t){return[...pt(e),{command:t}]}function ms(e){let t=()=>({hooks:[{type:"command",command:e}]});return{SessionStart:[t()],UserPromptExpansion:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function gs(e){let t={type:"command",command:e,statusMessage:rn},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var hs=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","subagentStart","subagentStop","stop"],_s=["beforeMCPExecution","beforeShellExecution","afterFileEdit"];function Ss(e){let t={...e};for(let n of _s){if(!(n in t))continue;let r=pt(t[n]);r.length===0?delete t[n]:t[n]=r}return t}function Es(e,t,n={}){let r=h(e,".claude/settings.json"),o=ft(t,"claude"),s=B(r)??{};if(ds(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let l={...s.hooks};for(let f of Object.keys(l))l[f]=Ue(l[f]),Qn(l[f]).length===0&&delete l[f];Object.keys(l).length===0?delete s.hooks:s.hooks=l,V(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=ms(o),u={...a};for(let[l,f]of Object.entries(c))u[l]=er(a[l],f);return s.hooks=u,V(r,s),!0}function ys(e,t){let n=h(e,".cursor/hooks.json"),r=ft(t,"cursor"),o=B(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=Ss({...s});for(let a of hs)i[a]=ps(i[a],r);V(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function ks(e,t){let n=h(e,".codex/hooks.json"),r=ft(t,"codex"),o=B(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=gs(r),a={...s};for(let[c,u]of Object.entries(i))a[c]=er(s[c],u);V(n,{...o,hooks:a})}function Is(e){let t=h(e,".claude/settings.json"),n=B(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let i=r[s],a=Ue(i);JSON.stringify(i)!==JSON.stringify(a)&&(o=!0),a.length===0?delete r[s]:r[s]=a}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,V(t,n),d(`Removed ev-ai hooks from ${t}`))}function Rs(e){let t=h(e,".cursor/hooks.json"),n=B(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=pt(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks"&&a!=="version").length===0){be(t,{force:!0}),d(`Removed ${t}`);return}V(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function Cs(e){let t=h(e,".codex/hooks.json"),n=B(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=Ue(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks").length===0){be(t,{force:!0}),d(`Removed ${t}`);return}V(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function mt(e=process.platform,t=process.arch,n={}){if(e==="win32")throw new Error("Windows install is not supported yet. Use macOS/Linux, or wait for phase-2 native commands.");(n.requireBinaryArch??!0)&&Hn(e,t)}async function tr(e={}){let t=zo(e);e.collectorUrl=t;let n=e.skipClaude===!0,r=e.skipCursor===!0,o=e.skipCodex===!0;if(n&&r&&o)throw new Error("at least one runner must be wired; refuse --no-claude --no-cursor --no-codex together");let s=e.delivery??Jn();mt(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await M(i),{command:c,hookPath:u,strategy:l}=is(a,j(),s),{installationId:f,storePath:g}=await Oe(a,{overrideId:e.installationId}),{manifestPath:p,wrote:_}=Zn(a,e),R=[];return n?d("Skipped Claude hook \u2014 --no-claude"):Es(a,c,{force:e.force})?(R.push("Claude"),e.force&&fs(a)&&d("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):d("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?d("Skipped Cursor hook \u2014 --no-cursor"):(ys(a,c),R.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(ks(a,c),R.push("Codex")),d(`Installed hook (${l}) at ${u}`),d(`Installation identity ${f} at ${g}`),_&&p?d(`Shared manifest written to ${p}`):d("Using package default collector config (no shared manifest file needed)"),d(R.length>0?`Wired ${R.join(", ")} hooks in ${a} (commands include --runner)`:`No runner hooks wired in ${a} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),l==="npx"?d("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):l==="project_binary"?d("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):l==="dev_mjs"&&d("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&p&&e.collectorUrl&&d("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:a,hookPath:u,manifestPath:p,installationStorePath:g,strategy:l}}async function nr(e=process.cwd()){mt(process.platform,process.arch,{requireBinaryArch:!0});let t=await M(e),{projectPath:n,globalPath:r}=os(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function rr(e={}){let t=Wo(e);e.collectorUrl=t,mt(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await M(n),{manifestPath:o,wrote:s}=Zn(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?d(`Wrote ${o}`):t===void 0&&d("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),d("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function or(e){for(let t of[()=>Is(e),()=>Rs(e),()=>Cs(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function sr(e=process.cwd()){let t=await M(e);return or(t),d("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),d("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function ir(e=process.cwd()){let t=await M(e);or(t);for(let n of ve){let r=h(t,n);if(F(r))try{be(r,{force:!0}),d(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);d(`WARN: uninstall could not remove ${r}: ${s}`)}}}var xs={claude:".claude",cursor:".cursor",codex:".codex"};function pe(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function As(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return pe(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return pe(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?pe(o[1]):pe(t)}async function me(e=process.cwd()){let t=await D("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([D("git",["remote","get-url","origin"],2e3,{cwd:e}),D("git",["branch","--show-current"],2e3,{cwd:e}),D("git",["rev-parse","HEAD"],2e3,{cwd:e}),D("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function ar(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=xs[n];if(!a)return"";let c=Cn(n,e.scope_path,i);if(s){let _=wn(s,c);if(_)return _}let u=o??await me(r),l=u?.remote?As(u.remote):"";if(l||(l=pe(process.env.GITHUB_REPOSITORY??"")),!l)return"";let f=e.scope_path??"",g=f?`${f}/`:"",p=`${l}:${g}${a}`;return s&&Un(s,c,p),p}import{existsSync as Ts,readFileSync as Os}from"node:fs";import{hostname as vs,userInfo as bs}from"node:os";function Pe(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var ws=["GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Us(){return ws.some(e=>!!E(e))}function Ps(){if(E("KUBERNETES_SERVICE_HOST")||Pe(E("REMOTE_CONTAINERS"))||Pe(E("DEVCONTAINER")))return!0;try{if(Ts("/.dockerenv")||Os("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function gt(){if(E("GITHUB_ACTIONS"))return"github_actions";if(Pe(E("CLAUDE_CODE_REMOTE")))return"claude_remote";if(Pe(E("CURSOR_AGENT")))return"cursor_cloud";if(E("CODESPACES")||E("CODESPACE_NAME"))return"codespaces";if(Us())return"managed";let e=E("CI");return e&&e!=="false"&&e!=="0"?"managed":Ps()?"container":process.stdin.isTTY||process.stdout.isTTY||E("TERM")?"interactive":"cron"}async function ht(){return await C("systemd-detect-virt",[],1e3)}function Ns(e=process.env,t=bs){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function _t(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await C("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),i=s("/etc/os-release","utf8"),a=i.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=i.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=a??c??""}catch{t=await C("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await C("uname",["-r"],1e3))}else t=await C("ver",[],1e3);let n=Ns(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await C("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function St(){return vs()}import{existsSync as Ms,readFileSync as Ls}from"node:fs";import{homedir as cr}from"node:os";import{join as Hs}from"node:path";var Ds="cloud-cache.json",Fs=1440*60*1e3,js=900*1e3;function Bs(e=cr()){return Hs(ot(e),Ds)}function $s(e){if(!Ms(e))return;let t=v(Ls(e,"utf8"),{});if(!(typeof t.context!="string"||typeof t.probed_at!="number"||t.result!==null&&t.result!==void 0&&typeof t.result!="object"))return{context:t.context,probed_at:t.probed_at,result:t.result??null}}function Gs(e,t){try{z(e,`${JSON.stringify(t)}
14
- `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cloud cache write failed open: ${r}`)}}function Ks(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?js:Fs;return n-e.probed_at<r}async function Js(e){let t=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=(await t.text()).trim();if(!n)return;let r={"X-aws-ec2-metadata-token":n},[o,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!o?.ok&&!s?.ok)return;let i=o?.ok?(await o.text()).trim():"",a=s?.ok?(await s.text()).trim():"";if(!(!i&&!a))return{provider:"aws",region:i,instance_id:a}}async function Vs(e){let t=await fetch("http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true",{headers:{"Metadata-Flavor":"Google"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=typeof n.zone=="string"?n.zone.split("/").pop()??"":"",o=n.id===void 0?"":String(n.id);if(!(!r&&!o))return{provider:"gcp",region:r,instance_id:o}}async function Ws(e){let t=await fetch("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{headers:{Metadata:"true"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=n.compute?.location??"",o=n.compute?.vmId??"";if(!(!r&&!o))return{provider:"azure",region:r,instance_id:o}}async function zs(e){let t=await Promise.allSettled([Js(e),Vs(e),Ws(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Et(e,t){if(e==="interactive")return null;let n=t?.home??cr(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Bs(n),i=$s(s);if(Ks(i,e,o))return i.result;let a=await zs(r);return Gs(s,{context:e,probed_at:o,result:a}),a}import{existsSync as Ys}from"node:fs";import{homedir as Xs}from"node:os";import{join as yt}from"node:path";function kt(e,t,n){if(!Ys(e))return;let r=ne(e,{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,source:t})}async function It(e,t=process.cwd(),n="claude",r=Xs()){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{name:s.name,source:"manifest"});return n==="claude"&&kt(yt(r,".claude.json"),"claude_json_user",o),kt(yt(t,".mcp.json"),"mcp_json",o),kt(yt(t,".cursor/mcp.json"),"cursor_mcp",o),[...o.values()]}var qs=["CI","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER","KUBERNETES_SERVICE_HOST","REMOTE_CONTAINERS","DEVCONTAINER","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REF","GITHUB_SHA","GITHUB_RUN_ID","GITHUB_WORKFLOW","GITHUB_ACTOR","GITHUB_TRIGGERING_ACTOR","GITHUB_ACTOR_ID","GITHUB_USER","GITLAB_USER_LOGIN","GITLAB_USER_NAME","GITLAB_USER_EMAIL","BUILD_REQUESTEDFOR","BUILD_REQUESTEDFOREMAIL","BUILDKITE_BUILD_CREATOR","BUILDKITE_BUILD_CREATOR_EMAIL","BUILD_USER","BUILD_USER_ID","BUILD_USER_EMAIL","CHANGE_AUTHOR","CHANGE_AUTHOR_EMAIL","CIRCLE_USERNAME","CODEBUILD_INITIATOR","DRONE_COMMIT_AUTHOR","DRONE_COMMIT_AUTHOR_NAME","DRONE_COMMIT_AUTHOR_EMAIL","EV_AI_HOOK_OPERATOR_NAME","EV_AI_HOOK_OPERATOR_EMAIL","GIT_AUTHOR_NAME","GIT_AUTHOR_EMAIL","GIT_COMMITTER_NAME","GIT_COMMITTER_EMAIL","EMAIL","RUNNER_OS","RUNNER_ARCH","NODE_ENV","TERM_PROGRAM","CLAUDE_CODE_REMOTE","CLAUDE_CODE_REMOTE_SESSION_ID","CURSOR_AGENT","CODESPACES","CODESPACE_NAME","ANTHROPIC_BASE_URL","OPENAI_BASE_URL","OPENAI_API_BASE","AZURE_OPENAI_ENDPOINT","GOOGLE_GEMINI_BASE_URL","GEMINI_API_BASE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],Zs=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Qs(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Zs.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Rt(e=process.env){return qs.map(t=>Object.prototype.hasOwnProperty.call(e,t)?{name:t,present:!0,value:Qs(e[t]??"")}:{name:t,present:!1})}import{createHash as ei}from"node:crypto";function I(e){return ei("sha256").update(e).digest("hex").slice(0,16)}function $(e,t){return`${e}\0${t}`}function lr(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function Ct(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
15
- `);return I(n)}function ti(e,t,n="git_config",r=null){return I(`${e??""}|${t??""}|${r??""}|${n}`)}function ni(e){let t=null,n=null;for(let r of e.split(`
16
- `)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function ri(e,t=C){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return ni(n)}function oi(e=process.env){let t=S(e.GIT_AUTHOR_NAME),n=S(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=S(e.GIT_COMMITTER_NAME),o=S(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=S(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}async function si(e,t=C){let n=await t("git",["log","-1","--format=%an%x00%ae"],2e3,{cwd:e});if(!n)return null;let r=n.indexOf("\0"),o=(r>=0?n.slice(0,r):n).trim(),s=(r>=0?n.slice(r+1):"").trim();return!o&&!s?null:{git_user_name:o||null,git_user_email:s||null,platform_login:null,identity_source:"git_log"}}function G(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function ii(e=process.env){let t=G(S(e.EV_AI_HOOK_OPERATOR_NAME),S(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured");if(t)return t;let n=S(e.GITHUB_ACTOR)??S(e.GITHUB_TRIGGERING_ACTOR)??S(e.GITHUB_USER),r=G(n,null,"github",n);if(r)return r;let o=S(e.GITLAB_USER_LOGIN),s=G(S(e.GITLAB_USER_NAME)??o,S(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let i=G(S(e.BUILD_REQUESTEDFOR),S(e.BUILD_REQUESTEDFOREMAIL),"azure_devops");if(i)return i;let a=G(S(e.BUILDKITE_BUILD_CREATOR),S(e.BUILDKITE_BUILD_CREATOR_EMAIL),"buildkite");if(a)return a;let c=G(S(e.BUILD_USER)??S(e.CHANGE_AUTHOR),S(e.BUILD_USER_EMAIL)??S(e.CHANGE_AUTHOR_EMAIL),"jenkins",S(e.BUILD_USER_ID));if(c)return c;let u=S(e.CIRCLE_USERNAME),l=G(u,null,"circleci",u);if(l)return l;let f=S(e.CODEBUILD_INITIATOR),g=G(f,null,"codebuild",f);if(g)return g;let p=G(S(e.DRONE_COMMIT_AUTHOR)??S(e.DRONE_COMMIT_AUTHOR_NAME),S(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",S(e.DRONE_COMMIT_AUTHOR));return p||(ur(e.CLAUDE_CODE_REMOTE)||ur(e.CURSOR_AGENT)?{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"cloud"}:null)}function xt(e){return!!((e.git_user_name??e.git_user_email)&&!li(e.git_user_name,e.git_user_email))}function S(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ur(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var ai=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),ci=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function li(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||ci.has(n)||r.includes("[bot]")||ai.has(r))return!0;if(r.endsWith("@users.noreply.github.com")){let o=r.slice(0,r.indexOf("@")),s=o.includes("+")?o.slice(o.indexOf("+")+1):o;if(s.endsWith("bot")||s.includes("[bot]"))return!0}return!1}async function ui(e,t=C,n=process.env){let r=await ri(e,t);if(xt(r))return{...r,identity_source:"git_config"};let o=oi(n);if(o&&xt(o))return o;let s=ii(n);if(s&&(s.git_user_name||s.git_user_email||s.platform_login))return s;let i=await si(e,t);return i&&xt(i)?i:s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||i||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Ne(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??C,s=e.env??process.env,i=await ui(t,o,s),a=ti(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),u=(n?st(n):void 0)?.operator_identity_hash;if(!(r||u!==void 0&&u!==a||!u))return{commit:()=>{}};let p=n;return{operator:i,commit:()=>{p&&On(p,a,Ae())}}}function At(e){return e?!st(e)?.operator_identity_hash:!0}function dr(e){return!0}import{existsSync as Pi,readFileSync as Ni}from"node:fs";import{homedir as Or}from"node:os";import{join as P}from"node:path";import{basename as wi,join as re}from"node:path";import{existsSync as fr,readdirSync as di}from"node:fs";import{basename as fi,dirname as pi,relative as mi}from"node:path";var Me=class{constructor(t){this.home=t}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=mi(this.home,t).replace(/\\/g,"/");if(!n||n.startsWith("..")){let r=pi(t);return`external/${I(r)}/${fi(t)}`}return n}get atGlobalCap(){return this.truncated||this.components.length>=X}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!fr(t))return[];try{return di(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(fr(t))return ne(t,n)}push(t){return this.components.length>=X?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Tt,readFileSync as gi,statSync as hi}from"node:fs";import{basename as mr,join as ge,relative as gr}from"node:path";var Ot=2e4,_i=4;function Si(e){return e.length<=Ot?e:`${e.slice(0,Ot-1)}\u2026`}function Ei(e){try{let t=gi(e),n=t.toString("utf8");return{hash:I(t),length:t.length,text:Si(n)}}catch{return null}}var pr={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function yi(e){return e in pr?pr[e]:"UNSPECIFIED"}function Le(e,t){let n=Ei(t.absolutePath);if(!n)return!1;let r=t.name??mr(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.homeRel(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=yi(t.kind);return s&&(o.trigger=s),e.push(o)}function ki(e,t,n){let r=gr(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?mr(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Q(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;vt(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function vt(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:u}=t;if(!(o>_i))for(let l of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!l.isDirectory())continue;let p=ge(r,l.name,c);if(Tt(p)){let _=gr(n,ge(r,l.name)).replace(/\\/g,"/");Le(e,{absolutePath:p,kind:s,origin:i,enabled:a,name:_||l.name});continue}vt(e,{walkRoot:n,currentDir:ge(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(l.isDirectory()){vt(e,{walkRoot:n,currentDir:ge(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(!l.isFile()||!u)continue;let f=l.name.toLowerCase();if(!u.some(p=>f.endsWith(p)))continue;let g=ge(r,l.name);Le(e,{absolutePath:g,kind:s,origin:i,enabled:a,name:ki(n,g,!0)})}}function hr(e){for(let t of e)if(Tt(t))try{if(hi(t).size>0)return t}catch{continue}return e.find(t=>Tt(t))}function Ii(e){if(e.prompt||e.type==="prompt")return"prompt";let t=e.command??e.bash??e.powershell??"";return/\bnpx\b/i.test(t)?"npx":/\.(sh|bash|zsh|js|mjs|cjs|ts|py)(\s|$|"|')/i.test(t)||/^(\.\/|~\/|\/|[A-Za-z]:[\\/])/.test(t.trim())?"script":"inline"}function Ri(e){return Array.isArray(e.hooks)&&e.hooks.length>0?e.hooks:[{type:e.type,command:e.command,bash:e.bash,powershell:e.powershell,prompt:e.prompt}]}function Ci(e,t,n,r){let o=e.homeRel(t);for(let[s,i]of Object.entries(n))if(!(!Array.isArray(i)||e.truncated))for(let a of i){if(!a||typeof a!="object"||e.truncated)continue;let c=a;for(let u of Ri(c)){if(e.truncated)return;let l=u.command??u.bash??u.prompt??u.powershell??c.powershell??"",f=Ii({type:u.type??c.type,command:u.command??c.command,bash:u.bash??c.bash,powershell:u.powershell??c.powershell,prompt:u.prompt??c.prompt}),g=typeof c.matcher=="string"?c.matcher:"",p=I(l),_=g?`${s}:${g}:${f}:${p}`:`${s}:${f}:${p}`,R=`${s}|${g}|${f}|${l}`;e.push({kind:"HOOK",name:_,path:o,content_hash:I(R),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...g?{matcher:g}:{},action_kind:f,action_hash:p}})}}}function he(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||Ci(e,t,r.hooks,n)}var _r={claude:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]}],memory:[".claude/CLAUDE.md"],hooks:[".claude/settings.json"],mcpJson:[".claude.json"],plugins:"claude"},cursor:{skillRoots:[".cursor/skills",".cursor/skills-cursor"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[".cursor/AGENTS.md"],hooks:[".cursor/hooks.json"],mcpJson:[".cursor/mcp.json"],plugins:"cursor"},codex:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]}],memory:[".codex/AGENTS.override.md",".codex/AGENTS.md"],hooks:[".codex/hooks.json"],mcpToml:[".codex/config.toml"]}};import{existsSync as xi,readFileSync as Ai}from"node:fs";function Ti(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function Sr(e,t,n){let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.homeRel(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=Ti(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:I(`${i}|${c}`),origin:n,enabled:!0,attributes:{transport:c}})}}function Er(e,t,n){if(!xi(t))return;let r;try{r=Ai(t,"utf8")}catch{return}let o=e.homeRel(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),u=c.search(/^\[/m),l=u===-1?c:c.slice(0,u),f="unknown";/^\s*url\s*=/m.test(l)?f="http":/^\s*command\s*=/m.test(l)&&(f="stdio"),e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:I(`${a}|${f}`),origin:n,enabled:!0,attributes:{transport:f}})}}import{existsSync as Oi,readdirSync as vi}from"node:fs";import{join as A}from"node:path";var yr=50;function bt(e,t,n,r){if(!Oi(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(yr,()=>{Q(e,{dir:A(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Q(e,{dir:A(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Q(e,{dir:A(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});he(e,A(t,"hooks","hooks.json"),n),he(e,A(t,"hooks.json"),n);let i=e.components.length-o,a=s>=yr;return{componentCount:i,expandTruncated:a}}function wt(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function kr(e){let t=A(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(A(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.homeRel(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let u=Array.isArray(c)?c:[c],l=u[0]??{},f=s[a]===!0,g=a.includes("@")?a.split("@").slice(1).join("@"):"",p=typeof l.version=="string"?l.version:"",_=typeof l.scope=="string"?l.scope:"user",R=`plugin:${a}`,b=0,x=!1;for(let w of u)if(typeof w.installPath=="string"&&w.installPath.length>0){let W=bt(e,w.installPath,R,f);b+=W.componentCount,x=x||W.expandTruncated}wt(e,{pluginKey:a,rowPath:i,enabled:f,scope:_,version:p||void 0,marketplace:g||void 0,componentCount:b,expandTruncated:x,contentHash:I(`${a}|${p}|${_}|${f}|${b}`)})}}function bi(e){let t=e,n="";try{let r=vi(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=A(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=A(e,s),n=s)}}catch{}return{installPath:t,version:n}}function Ir(e){let t=[{base:A(e.home,".cursor/plugins/local"),scope:"local"},{base:A(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let i=o.name,a=A(n,o.name),c=`plugin:${i}`,{componentCount:u,expandTruncated:l}=bt(e,a,c,!0);wt(e,{pluginKey:i,rowPath:e.homeRel(a),enabled:!0,scope:"local",componentCount:u,expandTruncated:l,contentHash:I(`${i}|local|${u}`)});continue}let s=o.name;for(let i of e.readEntries(A(n,s))){if(!i.isDirectory()||e.truncated)continue;let a=A(n,s,i.name),{installPath:c,version:u}=bi(a),l=`${i.name}@${s}`,f=`plugin:${l}`,{componentCount:g,expandTruncated:p}=bt(e,c,f,!0);wt(e,{pluginKey:l,rowPath:e.homeRel(c),enabled:!0,scope:"cache",version:u||void 0,marketplace:s,componentCount:g,expandTruncated:p,contentHash:I(`${l}|${u}|${g}`)})}}}function Ut(e,t){let n=_r[e],r=new Me(t),o="user";if(!n)return{components:[],truncated:!1};for(let i of n.skillRoots)Q(r,{dir:re(t,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Q(r,{dir:re(t,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});let s=hr(n.memory.map(i=>re(t,i)));s&&Le(r,{absolutePath:s,kind:"MEMORY",origin:o,enabled:!0,name:wi(s)});for(let i of n.hooks)he(r,re(t,i),o);for(let i of n.mcpJson??[])Sr(r,re(t,i),o);for(let i of n.mcpToml??[])Er(r,re(t,i),o);return n.plugins==="claude"?kr(r):n.plugins==="cursor"&&Ir(r),{components:r.components,truncated:r.truncated}}function Pt(e,t,n={}){let r=n.truncated===!0,o=Ct(e),s=new Set(e.map(l=>$(l.path,l.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let l of e){let f=$(l.path,l.name);c[f]!==l.content_hash&&a.push(l)}let u=[];if(!r){for(let l of Object.keys(c))if(!s.has(l)){let f=lr(l);f&&u.push(f)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:u,unchanged:a.length===0&&u.length===0}}var Cr=3e5,Ui=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Nt(e,t,n){let r=new Set(t.map(s=>$(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has($(s.path,s.name))||o.push(s));return o}function Mt(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function Rr(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function xr(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Lt(e,t=Cr){let n=[],r=[];for(let l of e)Ui.has(l.kind)?n.push(l):r.push(l);r.sort((l,f)=>(l.text?.length??0)-(f.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,u=[];for(let l of o){let f=s.length>0?1:0,g=Rr(l)+f;if(i+g<=t){s.push(l),i+=g,l.text!==void 0&&u.push(l.content_hash);continue}if(l.text!==void 0){let p=xr(l),_=Rr(p)+f;if(i+_<=t){s.push(p),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:u}}function Ht(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:xr(n))}var Mi={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],subagents:".cursor/agents",commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:[".agents/skills",".codex/skills"],subagents:".codex/agents",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},Li=200,Ar=200,Hi=["allow","deny","ask"],Di=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Dt="<path>",Fi=new RegExp(`${Dt}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function ji(e){let t=e.replace(Di,Dt).replace(Fi,Dt);return t.length>Ar?`${t.slice(0,Ar)}...`:t}function Tr(e){let t=ne(e,{}),n=[];for(let r of Hi)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:ji(o),mode:r});return{model:t.model??"",permissionKeys:n}}var Bi=10,$i=840*60*1e3,Gi="self-config-cache.json";function Ft(){return E("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Ki(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=$i}var Ji={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Vi(e,t=C){let n=Ji[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
17
- `)[0]??"").trim();return a||r(o+1)};return r(0)}function Wi(e=Or()){return P(e,".ev-ai","agent-hook",Gi)}function zi(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
18
- `);return I(n)}function He(e,t,n=!1){let r=zi(e),o=e.length;return t===r?n?{hash:r,count:o,truncated:n}:{hash:r,count:o}:n?{hash:r,count:o,entries:e,truncated:n}:{hash:r,count:o,entries:e}}function Yi(e){return Pi(e)?v(Ni(e,"utf8"),{}):{}}function Xi(e,t){try{z(e,`${JSON.stringify(t)}
19
- `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: self-config cache write failed open: ${r}`)}}function qi(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}return r&&(o.user_spec_collected_at_ms=r.collectedAtMs,r.included&&(o.user_spec=r.hash,o.user_spec_components=r.componentHashes),o.user_spec_text_hashes=r.textHashes),o}async function vr(e,t=process.cwd(),n=Or(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await Vi(e),a="",c=[];if(o){let U=Tr(P(n,".claude/settings.json")),L=Tr(P(t,".claude/settings.local.json"));a=L.model||U.model,c=[...U.permissionKeys,...L.permissionKeys].slice(0,Li)}let u=Mi[e]??{},l={present:!1,size:0},f=U=>{let L=Array.isArray(U)?U:U?[U]:[],y=[],K=!1;for(let Je of L){let O=de(P(n,Je));if(y=y.concat(O.entries),K=K||O.truncated,y.length>=X){y=y.slice(0,X),K=!0;break}}return{entries:y,truncated:K}},g=Wi(n),p=Yi(g),_=p[e]??{},R=(_.send_count??0)+1,b=R>0&&R%Bi===0,x=U=>b?void 0:_[U],w=f(u.skills),W=u.subagents?de(P(n,u.subagents)):{entries:[],truncated:!1},Ke=u.commands?de(P(n,u.commands)):{entries:[],truncated:!1},Vt=u.rules?de(P(n,u.rules)):{entries:[],truncated:!1},ie={skills:He(w.entries,x("skills"),w.truncated),subagents:He(W.entries,x("subagents"),W.truncated),commands:He(Ke.entries,x("commands"),Ke.truncated),rules:He(Vt.entries,x("rules"),Vt.truncated)},T={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:ie.skills,subagents:ie.subagents,commands:ie.commands,rules:ie.rules,memory:u.memory?fe(P(n,u.memory)):l,settings:u.settings?fe(P(n,u.settings)):l,mcp:u.mcp?fe(P(n,u.mcp)):l},local_settings:o?fe(P(t,".claude/settings.local.json")):l},Wt=null,zt=()=>{},Yt=r.nowMs??Date.now();if(!Ft()&&Ki(_.user_spec_collected_at_ms,Yt)){let U=_.user_spec_collected_at_ms!==void 0,L=Ut(e,n),y=Pt(L.components,_.user_spec_components,{forceFull:!_.user_spec_components,truncated:L.truncated}),K=new Set(_.user_spec_text_hashes??[]),Je=Nt(L.components,y.upserts,K),O=Lt(Ht([...y.upserts,...Je],K));T.user_spec_hash=y.hash,T.user_spec_count=y.count,T.user_spec_truncated=y.truncated||O.droppedCount>0,(O.components.length>0||y.removed.length>0||y.full)&&(y.full&&(T.user_spec_full=!0),O.components.length>0&&(T.user_spec=O.components),y.removed.length>0&&!T.user_spec_truncated&&(T.user_spec_removed=y.removed),O.textDeferredCount>0&&(T.user_spec_text_deferred=O.textDeferredCount));let Ve=y.full?{}:{..._.user_spec_components??{}};if(!T.user_spec_truncated)for(let te of y.removed)delete Ve[$(te.path,te.name)];for(let te of O.components)Ve[$(te.path,te.name)]=te.content_hash;Wt={hash:y.hash,componentHashes:Ve,textHashes:Mt(K,O.textHashesSent,L.components),included:O.components.length>0||y.removed.length>0&&!T.user_spec_truncated||y.full,collectedAtMs:Yt};let We=await Ne({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:U});We.operator&&(T.operator=We.operator),zt=We.commit}let so=qi(_,ie,R,Wt);return{config:T,commit:()=>{p[e]=so,Xi(g,p),zt()}}}function oe(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp:Ae(),session_id:n.sessionId||null,turn_id:n.turnId||null,installation_id:n.installationId,platform:n.runnerPlatform,platform_agent_id:n.platformAgentId||null,runner_event:n.runnerEvent||null,agent_hook_version:H,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as Kr}from"node:fs";import{spawn as Jr}from"node:child_process";import{basename as Ia}from"node:path";import{fileURLToPath as Ra}from"node:url";var br=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,wr=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Zi=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,Qi=new Set(["applications","app","bin","boot","data","dev","etc","home","lib","media","mnt","node_modules","opt","pkg","private","proc","projects","repos","run","sbin","src","srv","sys","tmp","usr","users","var","volumes","workspace","workspaces"]),ea=new Set(["read","read_file","view"]),ta=new Set(["bash","shell","zsh"]);function na(e){let t=e.replace(/\\/g,"/");return br.exec(t)?.[1]??null}function ra(e){let t=e.replace(/\\/g,"/"),r=wr.exec(t)?.[1];return r?r.toLowerCase():null}function oa(e){return na(e)??ra(e)}function sa(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Ur(e){if(typeof e=="string")try{let t=JSON.parse(e);return Ur(t)}catch{return null}return!e||typeof e!="object"?null:sa(e)}function ia(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function aa(e){let t=e.replace(/\\/g,"/"),n=br.exec(t);if(n?.[1])return n[1];let o=wr.exec(t)?.[1];return o?o.toLowerCase():null}function ca(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Pr(e){let t=ca(e).toLowerCase();if(ea.has(t)){let n=Ur(e.tool_input);return n?oa(n):null}if(ta.has(t)){let n=ia(e.tool_input);return n?aa(n):null}return null}function la(e){let t=new Set,n=[];for(let r of e.matchAll(Zi)){let o=r[1]?.toLowerCase();!o||t.has(o)||Qi.has(o)||(t.add(o),n.push(o))}return n}function ua(e){return ue(e.prompt)}function Nr(e){let t=m(e,"command_name");if(t){let r=m(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=ua(e);return n?la(n):[]}function jt(e){return e!==void 0&&on.includes(e)}function De(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Fe(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=De(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=De(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=De(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=De(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:jt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Bt(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Ie(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=ae(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return ce(n)}function Mr(e,t){if(m(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function da(){return!!(E("CURSOR_VERSION")??E("CURSOR_PROJECT_DIR"))}function $t(e,t,n){return e!=="claude"&&e!=="codex"?!1:Mr(t,n)?!0:da()}function Gt(e,t,n,r){if(Mr(e,t))return"cursor";if(jt(r))return r;let o=m(e,"conversation_id"),s=m(e,"turn_id"),i=m(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),jt(n)&&(c=n),c}function je(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function fa(e){switch(e){case"sessionstart":return"session_start";case"stop":case"sessionend":case"stopfailure":return"session_end";case"pretooluse":case"posttooluse":case"posttoolusefailure":case"permissiondenied":case"beforemcpexecution":case"beforeshellexecution":case"afterfileedit":case"subagentstart":case"subagentstop":return"tool_invoked";case"beforesubmitprompt":case"userpromptexpansion":case"userpromptsubmit":return"skill_invoked";default:return""}}function Lr(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Hr(e,t,n){let r=m(e,"session_id")||m(e,"conversation_id"),o=m(e,"prompt.id")||m(e,"prompt_id")||m(e,"generation_id")||m(e,"turn_id"),s=m(e,"hook_event_name")||m(e,"event"),i=m(e,"source"),a=Gt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var pa=["session_start","session_end","tool_invoked","skill_invoked"];function ma(e){return pa.includes(e)}function Dr(e,t){return e&&ma(e)?e:fa(t.toLowerCase())}function Fr(e){let t=m(e,"tool_name")||m(e,"tool")||null,n=e.tool_input,o=(n&&typeof n=="object"?ue(n.skill)||ue(n.skill_name):"")||m(e,"skill_name")||null;return o??=Pr(e),{toolName:t,skillName:o}}var ga=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function jr(e){for(let t of["subagent_type","agent_type"]){let n=m(e,t);if(n&&ga.test(n))return n}return null}function Br(e){let t=Y(e,"duration_ms");if(typeof t=="number")return t;let n=Y(e,"duration");return typeof n=="number"?n:null}var ha="error",_a="interrupted",Sa="permission_denied",Ea=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Kt(e){return Ea.test(e)?e:null}function ya(e){for(let t of["failure_type","error_type"]){let n=Kt(m(e,t));if(n)return n}return null}function $r(e,t){return Y(e,"is_interrupt")===!0?_a:t.toLowerCase()==="permissiondenied"?Sa:ya(e)??ha}function ka(e,t){let n=null;for(let r of t)r&&(e===r||e.startsWith(`${r}_`)||e.startsWith(`${r}-`))&&(n===null||r.length>n.length)&&(n=r);return n}function Gr(e,t=[]){if(!e)return{mcpServer:null,mcpTool:null};let n=/^mcp__(.+?)__(.+)$/i.exec(e);if(n?.[1]&&n[2])return{mcpServer:n[1],mcpTool:n[2]};if(/^MCP:/i.test(e)){let r=e.slice(4);if(!r)return{mcpServer:null,mcpTool:null};let o=r.indexOf(":");return o>0?{mcpServer:r.slice(0,o),mcpTool:r.slice(o+1)||null}:{mcpServer:ka(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var _e="__post",Be="__work";function Ca(e,t){let n=e.payload,r=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],o=e.correlation&&typeof e.correlation=="object"?Object.keys(e.correlation):[];return JSON.stringify({event:e.event,schema_version:e.schema_version,agent_hook_version:e.agent_hook_version,host_arch:e.host_arch,node_version:e.node_version,build_ms:e.build_ms,body_bytes:t,correlation_keys:o,payload_keys:r})}function Vr(e){switch(e){case"session_start":return Zt;case"session_end":return Qt;case"tool_invoked":case"skill_invoked":return Xe;default:return Xe}}function xa(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
20
- ${n}`}function Wr(e,t=[],n=process.execPath,r=import.meta.url,o=Kr){if(Ia(n)===J)return{command:n,args:[e,...t]};let s=Ra(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Aa(e=process.execPath,t=import.meta.url,n=Kr){return Wr(_e,[],e,t,n)}function Ta(e){let t=e.indexOf(`
21
- `);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function $e(e,t=fetch){let n=await e(),r=Ta(n);if(!r)return;let{meta:o,body:s}=r,i={"Content-Type":"application/json"};try{await t(o.url,{method:"POST",headers:i,body:s,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function Oa(e,t,n){let r=Vr(e);d(`POST event=${e} url=${Ze(n)} size=${t.length} platform=${process.platform}`);let o={"Content-Type":"application/json"},s=Date.now();try{let i=await fetch(n,{method:"POST",headers:o,body:t,signal:AbortSignal.timeout(r)}),a=Date.now()-s;if(i.ok)return d(`POST outcome=ok elapsed_ms=${a} http=${i.status}`),!0;let c=(await i.text()).slice(0,200).replace(/[\n\r]/g,"");return d(`POST outcome=fail elapsed_ms=${a} http=${i.status} body=${c}`),!1}catch(i){let a=Date.now()-s,c=i instanceof Error?i.message:String(i);return d(`POST outcome=fail elapsed_ms=${a} http=000 body=${c}`),!1}}async function zr(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){d(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},en),u=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>u()),s.stdin.once("error",()=>u())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return d(`WARN: ${o} spawn failed open: ${i}`),null}}async function va(e,t,n,r=Jr,o=Aa){let s=Vr(e),i=xa(n,s,t),{command:a,args:c}=o();return zr(a,c,i,r,"detached post")}async function Yr(e,t,n=Jr,r=Wr){let{command:o,args:s}=r(Be,t);return zr(o,s,e,n,"detached work")}async function se(e,t,n,r,o,s){if(!o)return d("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!xe(o))return d(`WARN: collector URL blocked (https required): ${Ze(o)}`),!1;let i=r(e,t,n);s!==void 0&&(i.build_ms=Math.max(0,Date.now()-s));let a=`${JSON.stringify(i)}
22
- `,c=E("EV_AI_HOOK_DEBUG");c==="full"?d(`DEBUG envelope=${JSON.stringify(i)}`):c==="1"&&d(`DEBUG summary=${Ca(i,Buffer.byteLength(a,"utf8"))}`);let u=process.argv.includes(Be),l=E("EV_AI_HOOK_SYNC")==="1";return je(n.runnerEvent,n.runnerPlatform)||u||l?Oa(e,a,o):(await va(e,a,o),!1)}import{relative as ba,resolve as Jt,sep as Xr}from"node:path";var wa=["session_id","conversation_id","turn_id","generation_id","prompt.id","prompt_id","hook_event_name","event","source","status","stop_reason","reason","tool_name","tool","tool_use_id","skill_name","command_name","expansion_type","command_source","permission_mode","model","model_id","agent_id","agent_type","subagent_id","subagent_type","subagent_model","is_parallel_worker","effort","effort.level","duration_ms","duration","failure_type","is_interrupt"];function Ua(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:E("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function Pa(e){let t={};for(let n of wa){let r=Y(e,n);r!==void 0&&(t[n]=r)}return t}function Na(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Jt(e),r=Jt(t),o=ba(r,n);return!o||o==="."?".":o.startsWith(`..${Xr}`)||o===".."||Jt(r,o)!==n?null:o.split(Xr).join("/")}function qr(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([i,a])=>!i.startsWith("_")&&(typeof a=="string"||typeof a=="number"||typeof a=="boolean")).sort((i,a)=>Buffer.byteLength(JSON.stringify(i[1]),"utf8")-Buffer.byteLength(JSON.stringify(a[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[i,a]of o){let c={...s,[i]:a};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[i]=a}return s}function Se(e,t,n={}){let r=n.gitRoot!==void 0?Na(e.cwd,n.gitRoot):null;if(Ua(t)){let s={...e};return delete s.cwd,delete s.transcript_path,r!==null&&(s.cwd_relative=r),qr(s,nn)}let o=Pa(e);return r!==null&&(o.cwd_relative=r),qr(o,tn)}import{createReadStream as Ma}from"node:fs";import{stat as La}from"node:fs/promises";import{basename as Ha,resolve as Da}from"node:path";import{createInterface as Fa}from"node:readline";var ja=1024*1024;function Ba(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Ha(t).endsWith(".jsonl")}async function Zr(e){if(!e||!Ba(e))return null;try{let t=Da(e),n=await La(t);if(!n.isFile())return null;let r=Math.max(0,n.size-ja),o=[],s=Fa({input:Ma(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let i of s)i.length!==0&&o.push(i);r>0&&o.length>0&&o.shift();for(let i=o.length-1;i>=0;i--){let a=o[i];if(a)try{let c=JSON.parse(a);if(c.type!=="assistant")continue;let u=c.message;if(!u||typeof u!="object")continue;let l=u.model;if(typeof l=="string"&&l.length>0)return l}catch{continue}}return null}catch{return null}}function ye(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function $a(...e){for(let t of e)if(t)return t;return null}function N(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return d(`WARN: ${n} failed open: ${r}`),t}function Ga(e){let t={present:!1,size:0},n={hash:"",count:0};return{config:{runner_platform:e,config_scope:"user",cli_version:null,claude_version:null,model:null,permission_keys:[],user_scope:{skills:n,subagents:n,commands:n,rules:n,memory:t,settings:t,mcp:t},local_settings:t},commit:()=>{}}}function Ka(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var ee=new Set,Ee=null;async function Qr(e){if(Ft())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(ee.has(t))return;if(!At(n)){ee.add(t);return}let r=gt();if(dr(r)){if(Ee){await Ee;return}Ee=(async()=>{if(ee.has(t)||!At(n)){ee.add(t);return}if(!vn(n)){ee.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,u,l,f,g]=await Promise.allSettled([me(i),ht(),Et(r),_t(),Ne({gitRoot:i,installationStorePath:n,forceResend:!1})]),p=N(c,null,"gitSnapshot"),_=N(u,"","detectVirt"),R=N(l,null,"probeCloud"),b=N(f,{},"hostEnv"),x=N(g,{commit:()=>{}},"resolveOperatorForSend");await ke(e,i,p);let w={identity:{host:St(),context:r,virt:_||null,cloud:R,git:p},host_env:b,env_vars:Rt(),self_config:Ka(a,x.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await se("session_start",w,ye(e),oe,e.manifest.collectorUrl,s),o&&(x.commit(),ee.add(t))}finally{bn(n)}})().finally(()=>{Ee=null}),await Ee}}async function ke(e,t,n){try{let r=n===void 0?await me(t):n;e.platformAgentId=await ar(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);d(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Ja(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=gt(),o=String(e.runnerPlatform),[s,i,a,c,u,l]=await Promise.allSettled([me(n),ht(),Et(r),_t(),It(e.manifest.manifest,n,o),vr(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),f=N(s,null,"gitSnapshot"),g=N(i,"","detectVirt"),p=N(a,null,"probeCloud"),_=N(c,{},"hostEnv"),R=N(u,[],"mcpDeclared"),b=N(l,Ga(o),"selfConfig"),x=b.config;await ke(e,n,f);let w=m(e.hookInput,"model");w&&(x.model=w);let W={identity:{host:St(),context:r,virt:g||null,cloud:p,git:f},host_env:_,env_vars:Rt(),mcp:{declared:R},self_config:x,run_meta:{trigger:e.hookSource||"startup"},hook_input:Se(e.hookInput,e.manifest.manifest,{gitRoot:n})};await se("session_start",W,ye(e),oe,e.manifest.collectorUrl,t)&&(b.commit(),ee.add(e.manifest.installationId))}async function Va(e){let t=Date.now(),{gitRoot:n}=e.manifest;await ke(e,n);let r=$a(m(e.hookInput,"status"),m(e.hookInput,"stop_reason"),m(e.hookInput,"reason"),Kt(m(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await Zr(m(e.hookInput,"transcript_path")):null,s=Se(e.hookInput,e.manifest.manifest,{gitRoot:n});o&&(s.model=o),await se("session_end",{status:r,...o?{model:o}:{},hook_input:s},ye(e),oe,e.manifest.collectorUrl,t)}async function Wa(e){let t=Date.now(),n=Nr(e.hookInput);if(n.length===0)return;await Qr(e);let{gitRoot:r}=e.manifest;await ke(e,r);let o=Se(e.hookInput,e.manifest.manifest,{gitRoot:r}),s=ye(e);await Promise.all(n.map(i=>se("tool_invoked",{tool_name:"Skill",skill_name:i,success:null,duration_ms:null,hook_input:o},s,oe,e.manifest.collectorUrl,t)))}async function za(e){let t=Date.now();await Qr(e);let{gitRoot:n}=e.manifest;await ke(e,n);let{toolName:r,skillName:o}=Fr(e.hookInput),s=Br(e.hookInput),i=Lr(e.runnerEvent),a=i===!1?$r(e.hookInput,e.runnerEvent):null,c=await It(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:u,mcpTool:l}=Gr(r,c.map(g=>g.name)),f=jr(e.hookInput);await se("tool_invoked",{tool_name:r,skill_name:o,success:i,duration_ms:s,...a?{failure_reason:a}:{},...u?{mcp_server:u}:{},...l?{mcp_tool:l}:{},...f?{subagent_type:f}:{},hook_input:Se(e.hookInput,e.manifest.manifest,{gitRoot:n})},ye(e),oe,e.manifest.collectorUrl,t)}async function eo(e){switch(e.internalEvent){case"session_start":await Ja(e);return;case"session_end":await Va(e);return;case"skill_invoked":await Wa(e);return;case"tool_invoked":await za(e);return;default:return}}function to(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function no(e,t,n,r){let o=t??await et(qe),s=v(o,{}),i=await Mn();if(!i)return;r&&(i.collectorUrl=r);let a=Hr(s,i.manifest.platform,n),c=Dr(e,a.runnerEvent);if(!c){d(`WARN: unknown hook event '${a.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:a.sessionId,turnId:a.turnId,runnerEvent:a.runnerEvent,runnerPlatform:a.runnerPlatform,hookSource:a.hookSource,internalEvent:c,manifest:i,platformAgentId:i.platformAgentId};if(to(c)){d(`WARN: unsupported internal event '${c}'`);return}await eo(u)}function Ya(e,t){if(E("EV_AI_HOOK_SYNC")==="1")return!0;let n=Fe(e),r=v(t,{}),o=n.event??(m(r,"hook_event_name")||m(r,"event")),s=Gt(r,o,void 0,n.runner);return je(o,s)}async function ro(e=process.argv.slice(2)){if(e[0]===_e){try{await $e(le)}catch{}return 0}if(e[0]===Be){try{let t=Fe(e.slice(1)),n=await le(),r=v(n,{}),o=t.event??(m(r,"hook_event_name")||m(r,"event"));if($t(t.runner,r,o))return 0;await no(t.event,n,t.runner,Bt(t))}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await et(qe),n=Fe(e),r=Bt(n),o=v(t,{}),s=n.event??(m(o,"hook_event_name")||m(o,"event"));if($t(n.runner,o,s))return 0;Ya(e,t)?await no(n.event,t,n.runner,r):await Yr(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{gn()}return 0}function Ge(){d("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),d(" configure [--url <\u2026/{orgToken}/hook>]"),d(" (manifest only \u2014 pair with marketplace plugins)"),d(" install --url <\u2026/{orgToken}/hook>"),d(" [--delivery npx|binary|local] [--force]"),d(" [--no-claude] [--no-cursor] [--no-codex]"),d(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),d(" (writes collector_url to shared manifest; hook commands use --runner only)"),d(" migrate-to-plugin"),d(" (strip ev-ai file hooks; keep collector manifest)"),d(" update (refresh binary pins from a local build; leaves hook configs alone)"),d(" uninstall"),d("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),d(" (--url/--token optional overrides; else collector_url from manifest)")}function oo(e){return e.includes("--help")||e.includes("-h")}async function ec(e=process.argv.slice(2)){let[t,...n]=e;if(t===_e){try{await $e(le)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${H}
23
- `),0):t==="configure"?oo(n)?(Ge(),0):(await rr(Gn(n)),0):t==="install"?oo(n)?(Ge(),0):(await tr(Kn(n)),0):t==="migrate-to-plugin"?(await sr(),0):t==="update"?(await nr(),0):t==="uninstall"?(await ir(),0):t==="help"||t==="--help"||t==="-h"?(Ge(),0):t===void 0?(Ge(),1):ro(e)}function tc(e,t,n=Xa){if(!t)return!1;try{return e===Qa(qa(t)).href?!0:n(Za(e))===n(t)}catch{return!1}}tc(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&ec().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);d(t),process.exit(1)});export{tc as isCliEntrypoint,ec as main};
15
+ npx ${Me} install`)}function xr(e){return typeof e!="string"?!1:e.includes("@ev-ai/agent-hook")||e.includes("agent-hook/dist/hook")||e.includes(".ev-ai/agent-hook")||e.includes(Y)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function Ht(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function Z(e,t){Lt(Mt(e),{recursive:!0}),Ri(e,`${JSON.stringify(t,null,2)}
16
+ `,"utf8")}function J(e){if(K(e))try{return JSON.parse(Si(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function Bi(e,t){let n=pr(t.collectorUrl),r={...e,schema_version:e?.schema_version??n.schema_version};return t.collectorUrl!==void 0?r.collector_url=t.collectorUrl:r.collector_url=e?.collector_url??n.collector_url,delete r.repo_ingest_token,delete r.installation_id,r.mcp_servers??=n.mcp_servers,r}function ji(e){return(e.schema_version??2)===2&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.repo_ingest_token===void 0}function Tr(e,t){let n=y(e,Le),r=J(n),o=Bi(r,t);return t.collectorUrl!==void 0||K(n)||!ji(o)?(Z(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function Ut(e){if(e===null||typeof e!="object")return!1;let t=e,n=String(t.CLAUDE_CODE_ENABLE_TELEMETRY??"").toLowerCase();return n==="1"||n==="true"?!0:Object.keys(t).some(r=>r.startsWith("OTEL_"))}function Ki(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return y(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function Gi(e=process.platform){let t=Ki(e),n=[y(t,"managed-settings.json")],r=y(t,"managed-settings.d");try{if(!K(r))return n;let o=Ei(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>y(r,s));n.push(...o)}catch{}return n}function Ji(e){if(Ut(process.env))return!0;let t=G();return[...Gi(),y(t,".claude","settings.json"),y(t,".claude","remote-settings.json"),y(e,".claude","settings.json"),y(e,".claude","settings.local.json")].some(r=>{try{let o=J(r);return o?Ut(o.env):!1}catch{return!1}})}function Vi(e){try{let t=J(y(e,".claude","settings.json"));return t?Ut(t.env):!1}catch{return!1}}function br(e){return Array.isArray(e)?e:[]}function Ge(e){let t=[],n=r=>!!r&&typeof r=="object"&&xr(r.command);for(let r of br(e)){if(!r||typeof r!="object"){t.push(r);continue}let o=Array.isArray(r.hooks)?r.hooks:[],s=o.filter(a=>!n(a));if(!(s.length===0&&o.some(n))){if(s.length!==o.length){t.push({...r,hooks:s});continue}t.push(r)}}return t}function wr(e,t){return[...Ge(e),...t]}function Dt(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!xr(t.command)):[]}function zi(e,t){return[...Dt(e),{command:t}]}function Wi(e){let t=()=>({hooks:[{type:"command",command:e}]});return{SessionStart:[t()],UserPromptExpansion:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function Yi(e){let t={type:"command",command:e,statusMessage:wn},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var Xi=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","afterShellExecution","beforeReadFile","afterFileEdit","beforeMCPExecution","subagentStart","subagentStop","stop"],Zi=[];function qi(e,t=Zi){let n={...e};for(let r of t){if(!(r in n))continue;let o=Dt(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function Qi(e,t,n={}){let r=y(e,".claude/settings.json"),o=Ht(t,"claude"),s=J(r)??{};if(Ji(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let f of Object.keys(u))u[f]=Ge(u[f]),br(u[f]).length===0&&delete u[f];Object.keys(u).length===0?delete s.hooks:s.hooks=u,Z(r,s)}return!1}let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=Wi(o),l={...i};for(let[u,f]of Object.entries(c))l[u]=wr(i[u],f);return s.hooks=l,Z(r,s),!0}function ea(e,t){let n=y(e,".cursor/hooks.json"),r=Ht(t,"cursor"),o=J(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},a=qi({...s});for(let i of Xi)a[i]=zi(a[i],r);Z(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:a})}function ta(e,t){let n=y(e,".codex/hooks.json"),r=Ht(t,"codex"),o=J(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},a=Yi(r),i={...s};for(let[c,l]of Object.entries(a))i[c]=wr(s[c],l);Z(n,{...o,hooks:i})}function na(e){let t=y(e,".claude/settings.json"),n=J(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let a=r[s],i=Ge(a);JSON.stringify(a)!==JSON.stringify(i)&&(o=!0),i.length===0?delete r[s]:r[s]=i}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,Z(t,n),d(`Removed ev-ai hooks from ${t}`))}function ra(e){let t=y(e,".cursor/hooks.json"),n=J(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let a of Object.keys(r)){let i=r[a],c=Dt(i);JSON.stringify(i)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[a]:(r[a]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(i=>i!=="hooks"&&i!=="version").length===0){je(t,{force:!0}),d(`Removed ${t}`);return}Z(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function oa(e){let t=y(e,".codex/hooks.json"),n=J(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let a of Object.keys(r)){let i=r[a],c=Ge(i);JSON.stringify(i)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[a]:(r[a]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(i=>i!=="hooks").length===0){je(t,{force:!0}),d(`Removed ${t}`);return}Z(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function Ft(e=process.platform,t=process.arch,n={}){if(e==="win32")throw new Error("Windows install is not supported yet. Use macOS/Linux, or wait for phase-2 native commands.");(n.requireBinaryArch??!0)&&mr(e,t)}async function Pr(e={}){let t=xi(e);e.collectorUrl=t;let n=e.skipClaude===!0,r=e.skipCursor===!0,o=e.skipCodex===!0;if(n&&r&&o)throw new Error("at least one runner must be wired; refuse --no-claude --no-cursor --no-codex together");let s=e.delivery??Ir();Ft(process.platform,process.arch,{requireBinaryArch:s==="binary"});let a=e.cwd??process.cwd(),i=await j(a),{command:c,hookPath:l,strategy:u}=$i(i,G(),s),{installationId:f,storePath:m}=await $e(i,{overrideId:e.installationId}),{manifestPath:p,wrote:_}=Tr(i,e),h=[];return n?d("Skipped Claude hook \u2014 --no-claude"):Qi(i,c,{force:e.force})?(h.push("Claude"),e.force&&Vi(i)&&d("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):d("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?d("Skipped Cursor hook \u2014 --no-cursor"):(ea(i,c),h.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(ta(i,c),h.push("Codex")),d(`Installed hook (${u}) at ${l}`),d(`Installation identity ${f} at ${m}`),_&&p?d(`Shared manifest written to ${p}`):d("Using package default collector config (no shared manifest file needed)"),d(h.length>0?`Wired ${h.join(", ")} hooks in ${i} (commands include --runner)`:`No runner hooks wired in ${i} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),u==="npx"?d("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):u==="project_binary"?d("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):u==="dev_mjs"&&d("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&p&&e.collectorUrl&&d("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:i,hookPath:l,manifestPath:p,installationStorePath:m,strategy:u}}async function Nr(e=process.cwd()){Ft(process.platform,process.arch,{requireBinaryArch:!0});let t=await j(e),{projectPath:n,globalPath:r}=Di(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function Ur(e={}){let t=Oi(e);e.collectorUrl=t,Ft(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await j(n),{manifestPath:o,wrote:s}=Tr(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?d(`Wrote ${o}`):t===void 0&&d("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),d("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function Lr(e){for(let t of[()=>na(e),()=>ra(e),()=>oa(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function Mr(e=process.cwd()){let t=await j(e);return Lr(t),d("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),d("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function Hr(e=process.cwd()){let t=await j(e);Lr(t);for(let n of Be){let r=y(t,n);if(K(r))try{je(r,{force:!0}),d(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);d(`WARN: uninstall could not remove ${r}: ${s}`)}}}import{createHash as ba}from"node:crypto";import{existsSync as wa,mkdirSync as Pa,readdirSync as Na,readFileSync as Zr,unlinkSync as qr,writeFileSync as Ua}from"node:fs";import{homedir as Qr}from"node:os";import{join as Jt}from"node:path";var Dr=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,Fr=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,sa=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,ia=new Set(["applications","app","bin","boot","data","dev","etc","home","lib","media","mnt","node_modules","opt","pkg","private","proc","projects","repos","run","sbin","src","srv","sys","tmp","usr","users","var","volumes","workspace","workspaces"]),aa=new Set(["read","read_file","view"]),ca=new Set(["bash","shell","zsh"]);function la(e){let t=e.replace(/\\/g,"/");return Dr.exec(t)?.[1]??null}function ua(e){let t=e.replace(/\\/g,"/"),r=Fr.exec(t)?.[1];return r?r.toLowerCase():null}function $t(e){return la(e)??ua(e)}function da(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Je(e){if(typeof e=="string")try{let t=JSON.parse(e);return Je(t)}catch{return null}return!e||typeof e!="object"?null:da(e)}function fa(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function pa(e){let t=e.replace(/\\/g,"/"),n=Dr.exec(t);if(n?.[1])return n[1];let o=Fr.exec(t)?.[1];return o?o.toLowerCase():null}function ma(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function $r(e){let t=ma(e).toLowerCase();if(aa.has(t)){let n=Je(e.tool_input)??ee(e.file_path),r=n?$t(n):null;if(r)return r}if(ca.has(t)){let n=fa(e.tool_input)??ee(e.command);return n?pa(n):null}return null}function ga(e){let t=new Set,n=[];for(let r of e.matchAll(sa)){let o=r[1]?.toLowerCase();!o||t.has(o)||ia.has(o)||(t.add(o),n.push(o))}return n}function _a(e){return ee(e.prompt)}function Br(e){let t=g(e,"command_name");if(t){let r=g(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=_a(e);return n?ga(n):[]}function Bt(e){return e!==void 0&&Pn.includes(e)}function Ve(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function ze(e){let t,n,r,o,s;for(let a=0;a<e.length;a++){let i=e[a];if(i!==void 0){if(i==="--runner"){let c=Ve(e,a);t=c.value,a=c.next;continue}if(i.startsWith("--runner=")){t=i.slice(9);continue}if(i==="--url"){let c=Ve(e,a);c.value&&(r=c.value),a=c.next;continue}if(i.startsWith("--url=")){r=i.slice(6);continue}if(i==="--token"){let c=Ve(e,a);c.value&&(o=c.value),a=c.next;continue}if(i.startsWith("--token=")){o=i.slice(8);continue}if(i==="--base-url"){let c=Ve(e,a);c.value&&(s=c.value),a=c.next;continue}if(i.startsWith("--base-url=")){s=i.slice(11);continue}!i.startsWith("-")&&n===void 0&&(n=i)}}return{runner:Bt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function jt(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Ue(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=ge(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return _e(n)}function jr(e,t){if(g(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function ha(){return!!(A("CURSOR_VERSION")??A("CURSOR_PROJECT_DIR"))}function Kt(e,t,n){return e!=="claude"&&e!=="codex"?!1:jr(t,n)?!0:ha()}function ke(e,t,n,r){if(jr(e,t))return"cursor";if(Bt(r))return r;let o=g(e,"conversation_id"),s=g(e,"turn_id"),a=g(e,"session_id"),i=t.toLowerCase(),c="unknown";return o||t===i&&t!==""?c="cursor":s?c="codex":(a||i==="sessionstart"||i==="sessionend"||i==="stop"||i==="stopfailure"||i==="pretooluse"||i==="posttooluse"||i==="posttoolusefailure"||i==="permissiondenied"||i==="subagentstart"||i==="subagentstop"||i==="userpromptexpansion")&&(c="claude"),Bt(n)&&(c=n),c}function We(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Ea(e){switch(e){case"sessionstart":return"session_start";case"stop":case"sessionend":case"stopfailure":return"session_end";case"pretooluse":case"posttooluse":case"posttoolusefailure":case"permissiondenied":case"beforemcpexecution":case"beforeshellexecution":case"aftershellexecution":case"beforereadfile":case"afterfileedit":case"subagentstart":case"subagentstop":return"tool_invoked";case"beforesubmitprompt":case"userpromptexpansion":case"userpromptsubmit":return"skill_invoked";default:return""}}function Kr(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Gr(e,t,n){let r=g(e,"session_id")||g(e,"conversation_id"),o=g(e,"prompt.id")||g(e,"prompt_id")||g(e,"generation_id")||g(e,"turn_id"),s=g(e,"hook_event_name")||g(e,"event"),a=g(e,"source"),i=ke(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:a,runnerPlatform:i}}var Sa=["session_start","session_end","tool_invoked","skill_invoked"];function ya(e){return Sa.includes(e)}function Jr(e,t){return e&&ya(e)?e:Ea(t.toLowerCase())}var Ra={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Ia(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Vr(e,t=""){let n=g(e,"tool_name")||g(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Ia(n)&&(n=`MCP:${n}`):n=Ra[r]??null;let o=e.tool_input,a=(o&&typeof o=="object"?ee(o.skill)||ee(o.skill_name):"")||g(e,"skill_name")||null,i=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;return a??=$r(i),{toolName:n,skillName:a}}var ka=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function zr(e){for(let t of["subagent_type","agent_type"]){let n=g(e,t);if(n&&ka.test(n))return n}return null}function Wr(e){let t=te(e,"duration_ms");if(typeof t=="number")return t;let n=te(e,"duration");return typeof n=="number"?n:null}var Ca="error",Aa="interrupted",va="permission_denied",Oa=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Gt(e){return Oa.test(e)?e:null}function xa(e){for(let t of["failure_type","error_type"]){let n=Gt(g(e,t));if(n)return n}return null}function Yr(e,t){return te(e,"is_interrupt")===!0?Aa:t.toLowerCase()==="permissiondenied"?va:xa(e)??Ca}function Ta(e,t){let n=null;for(let r of t)r&&(e===r||e.startsWith(`${r}_`)||e.startsWith(`${r}-`))&&(n===null||r.length>n.length)&&(n=r);return n}function Xr(e,t=[]){if(!e)return{mcpServer:null,mcpTool:null};let n=/^mcp__(.+?)__(.+)$/i.exec(e);if(n?.[1]&&n[2])return{mcpServer:n[1],mcpTool:n[2]};if(/^MCP:/i.test(e)){let r=e.slice(4);if(!r)return{mcpServer:null,mcpTool:null};let o=r.indexOf(":");if(o>0)return{mcpServer:r.slice(0,o),mcpTool:r.slice(o+1)||null};let s=r.indexOf("__");return s>0?{mcpServer:r.slice(0,s),mcpTool:r.slice(s+2)||null}:{mcpServer:Ta(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var eo=3e4,La="claims",Ma=!0,Ha=100,Da=new Set(["sessionstart","sessionend","stopfailure"]),Fa=["tool_name","tool","command","file_path","url"];function $a(e=Qr()){return Jt(Ie(e),La)}function to(e){let t=e.split(`
17
+ `,1)[0]??"";return Number(t.trim())}function no(e){return ba("sha256").update(e).digest("hex").slice(0,32)}function Ba(e){let t=[];for(let n of Fa){let r=g(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":no(t.join("\0"))}function ja(e){let t=e.sessionId.trim();if(!t)return;let n=e.runnerEvent.trim().toLowerCase(),r=e.turnId.trim(),o=e.toolUseId.trim(),s=e.subagentId?.trim()??"",a=e.callFingerprint?.trim()??"",i=!!(o||r||s),c=Da.has(n);if(!i&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return no(`${l}|${t}|${n}|${r}|${o}|${a}|${s}`)}function Ka(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Ga(e,t){return Jt(e,t)}function Ja(e,t=Date.now()){let n;try{n=Na(e)}catch{return}let r=0;for(let o of n){if(r>=Ha)break;r+=1;let s=Jt(e,o),a=Number.NaN;try{a=to(Zr(s,"utf8"))}catch{continue}let i=t-a;if(!(!Number.isFinite(i)||i<0||i<eo))try{qr(s)}catch{}}}function Va(e,t,n=Date.now()){let r=Ga(t,e);try{if(wa(r)){let o=Number.NaN;try{o=to(Zr(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<eo)return!1;try{qr(r)}catch{}}}catch{}try{Pa(t,{recursive:!0}),Ua(r,`${n}
18
+ `,{encoding:"utf8",flag:"wx"})}catch(o){if(Ka(o))return!1;let s=o instanceof Error?o.message:String(o);return d(`WARN: event claim failed open: ${s}`),!0}return Ja(t,n),!0}function za(e,t,n){let r=g(e,"session_id")||g(e,"conversation_id"),o=g(e,"prompt.id")||g(e,"prompt_id")||g(e,"generation_id")||g(e,"turn_id"),s=g(e,"tool_use_id"),a=g(e,"subagent_id")||g(e,"agent_id"),i=ke(e,t,void 0,n),c=Ba(e);return{runnerPlatform:i,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:a,callFingerprint:c}}function ro(e,t,n,r=Qr(),o=Date.now()){if(!Ma)return!0;let s=ja(za(e,t,n));if(!s)return!0;let a=Va(s,$a(r),o);return!a&&A("EV_AI_HOOK_DEBUG")&&d(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),a}import{homedir as pu}from"node:os";var Vt={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Ce(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Wa(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return Ce(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Ce(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Ce(o[1]):Ce(t)}async function Ae(e=process.cwd()){let t=await L("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([L("git",["remote","get-url","origin"],2e3,{cwd:e}),L("git",["branch","--show-current"],2e3,{cwd:e}),L("git",["rev-parse","HEAD"],2e3,{cwd:e}),L("git",["status","--porcelain"],2e3,{cwd:e})]),a=n.ok?n.stdout:null;return{remote:a===null?null:a.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function oo(e,t,n,r=process.cwd(),o,s,a){if(t)return t;let i=Vt[n];if(!i)return"";let c=er(n,e.scope_path,a);if(s){let _=cr(s,c);if(_)return _}let l=o??await Ae(r),u=l?.remote?Wa(l.remote):"";if(u||(u=Ce(process.env.GITHUB_REPOSITORY??"")),!u)return"";let f=e.scope_path??"",m=f?`${f}/`:"",p=`${u}:${m}${i}`;return s&&lr(s,c,p),p}var x=_s(ao(),1);import{existsSync as cc,readFileSync as lc}from"node:fs";import{homedir as co}from"node:os";import{join as uc}from"node:path";var dc="cloud-cache.json",fc=1440*60*1e3,pc=900*1e3;function mc(e=co()){return uc(Ie(e),dc)}function gc(e){if(!cc(e))return;let t=P(lc(e,"utf8"),{});if(!(typeof t.context!="string"||typeof t.probed_at!="number"||t.result!==null&&t.result!==void 0&&typeof t.result!="object"))return{context:t.context,probed_at:t.probed_at,result:t.result??null}}function _c(e,t){try{X(e,`${JSON.stringify(t)}
19
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cloud cache write failed open: ${r}`)}}function hc(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?pc:fc;return n-e.probed_at<r}async function Ec(e){let t=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=(await t.text()).trim();if(!n)return;let r={"X-aws-ec2-metadata-token":n},[o,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!o?.ok&&!s?.ok)return;let a=o?.ok?(await o.text()).trim():"",i=s?.ok?(await s.text()).trim():"";if(!(!a&&!i))return{provider:"aws",region:a,instance_id:i}}async function Sc(e){let t=await fetch("http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true",{headers:{"Metadata-Flavor":"Google"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=typeof n.zone=="string"?n.zone.split("/").pop()??"":"",o=n.id===void 0?"":String(n.id);if(!(!r&&!o))return{provider:"gcp",region:r,instance_id:o}}async function yc(e){let t=await fetch("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{headers:{Metadata:"true"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=n.compute?.location??"",o=n.compute?.vmId??"";if(!(!r&&!o))return{provider:"azure",region:r,instance_id:o}}async function Rc(e){let t=await Promise.allSettled([Ec(e),Sc(e),yc(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function zt(e,t){if(e==="interactive")return null;let n=t?.home??co(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=mc(n),a=gc(s);if(hc(a,e,o))return a.result;let i=await Rc(r);return _c(s,{context:e,probed_at:o,result:i}),i}import{existsSync as Ic}from"node:fs";import{homedir as kc}from"node:os";import{join as Xe}from"node:path";function Ze(e,t,n){if(!Ic(e))return;let r=ae(e,{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,...t})}async function Wt(e,t=process.cwd(),n="claude",r=kc()){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{name:s.name,source:"manifest"});return n==="claude"?Ze(Xe(r,".claude.json"),{source:"claude_json_user"},o):n==="cursor"&&Ze(Xe(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Ze(Xe(t,".mcp.json"),{source:"mcp_json"},o),Ze(Xe(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),[...o.values()]}var Cc=["CI","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER","KUBERNETES_SERVICE_HOST","REMOTE_CONTAINERS","DEVCONTAINER","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REF","GITHUB_SHA","GITHUB_RUN_ID","GITHUB_WORKFLOW","GITHUB_ACTOR","GITHUB_TRIGGERING_ACTOR","GITHUB_ACTOR_ID","GITHUB_USER","GITLAB_USER_LOGIN","GITLAB_USER_NAME","GITLAB_USER_EMAIL","BUILD_REQUESTEDFOR","BUILD_REQUESTEDFOREMAIL","BUILD_REQUESTEDFORID","BUILDKITE_BUILD_CREATOR","BUILDKITE_BUILD_CREATOR_EMAIL","BUILD_USER","BUILD_USER_ID","BUILD_USER_EMAIL","CHANGE_AUTHOR","CHANGE_AUTHOR_EMAIL","CIRCLE_USERNAME","CODEBUILD_INITIATOR","DRONE_COMMIT_AUTHOR","DRONE_COMMIT_AUTHOR_NAME","DRONE_COMMIT_AUTHOR_EMAIL","EV_AI_HOOK_OPERATOR_NAME","EV_AI_HOOK_OPERATOR_EMAIL","EV_AI_HOOK_OPERATOR_LOGIN","GIT_AUTHOR_NAME","GIT_AUTHOR_EMAIL","GIT_COMMITTER_NAME","GIT_COMMITTER_EMAIL","EMAIL","RUNNER_OS","RUNNER_ARCH","NODE_ENV","TERM_PROGRAM","CLAUDE_CODE_REMOTE","CLAUDE_CODE_REMOTE_SESSION_ID","CURSOR_AGENT","CURSOR_VERSION","CURSOR_CODE_REMOTE","CURSOR_USER_EMAIL","CODESPACES","CODESPACE_NAME","ANTHROPIC_BASE_URL","OPENAI_BASE_URL","OPENAI_API_BASE","AZURE_OPENAI_ENDPOINT","GOOGLE_GEMINI_BASE_URL","GEMINI_API_BASE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],Ac=["CURSOR_PROJECT_DIR"],vc=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Oc(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)vc.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Yt(e=process.env){let t=Cc.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Oc(e[r]??"")}:{name:r,present:!1}),n=Ac.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{createHash as xc}from"node:crypto";function O(e){return xc("sha256").update(e).digest("hex").slice(0,16)}function V(e,t){return`${e}\0${t}`}function lo(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function Xt(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
20
+ `);return O(n)}function Tc(e,t,n="git_config",r=null){return O(`${e??""}|${t??""}|${r??""}|${n}`)}function bc(e){let t=null,n=null;for(let r of e.split(`
21
+ `)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let a=o.slice(0,s).toLowerCase(),i=o.slice(s+1).trim();i&&(a==="user.name"?t=i:a==="user.email"&&(n=i))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function wc(e,t=v){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return bc(n)}function Pc(e=process.env){let t=E(e.GIT_AUTHOR_NAME),n=E(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=E(e.GIT_COMMITTER_NAME),o=E(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=E(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function z(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function Nc(e=process.env){let t=z(E(e.EV_AI_HOOK_OPERATOR_NAME),E(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured",E(e.EV_AI_HOOK_OPERATOR_LOGIN));if(t)return t;let n=E(e.GITHUB_ACTOR)??E(e.GITHUB_TRIGGERING_ACTOR)??E(e.GITHUB_USER),r=z(n,null,"github",n);if(r)return r;let o=E(e.GITLAB_USER_LOGIN),s=z(E(e.GITLAB_USER_NAME)??o,E(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let a=z(E(e.BUILD_REQUESTEDFOR),E(e.BUILD_REQUESTEDFOREMAIL),"azure_devops",E(e.BUILD_REQUESTEDFORID));if(a)return a;let i=E(e.BUILDKITE_BUILD_CREATOR_EMAIL),c=z(E(e.BUILDKITE_BUILD_CREATOR),i,"buildkite",i);if(c)return c;let l=z(E(e.BUILD_USER)??E(e.CHANGE_AUTHOR),E(e.BUILD_USER_EMAIL)??E(e.CHANGE_AUTHOR_EMAIL),"jenkins",E(e.BUILD_USER_ID));if(l)return l;let u=E(e.CIRCLE_USERNAME),f=z(u,null,"circleci",u);if(f)return f;let m=E(e.CODEBUILD_INITIATOR),p=z(m,null,"codebuild",m);if(p)return p;let _=z(E(e.DRONE_COMMIT_AUTHOR)??E(e.DRONE_COMMIT_AUTHOR_NAME),E(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",E(e.DRONE_COMMIT_AUTHOR));if(_)return _;if(fo(e.CLAUDE_CODE_REMOTE)||fo(e.CURSOR_AGENT)){let h=E(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:h&&!Q(null,h)?h:null,platform_login:null,identity_source:"cloud"}}return null}function uo(e){return!!((e.git_user_name??e.git_user_email)&&!Q(e.git_user_name,e.git_user_email))}function E(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function fo(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function Uc(e,t=v,n=process.env){let r=await wc(e,t);if(uo(r))return{...r,identity_source:"git_config"};let o=Pc(n);if(o&&uo(o))return o;let s=Nc(n);return s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function qe(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??v,s=e.env??process.env,a=await Uc(t,o,s),i=Tc(a.git_user_name,a.git_user_email,a.identity_source,a.platform_login),l=(n?bt(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==i||!l))return{commit:()=>{}};let p=n;return{operator:a,commit:()=>{p&&sr(p,i,De())}}}function Zt(e){return e?!bt(e)?.operator_identity_hash:!0}function po(e){return!0}import{existsSync as Ol,readFileSync as xl}from"node:fs";import{homedir as Jo}from"node:os";import{join as H}from"node:path";import{basename as Al,join as de,resolve as Do}from"node:path";import{existsSync as mo,readdirSync as Lc}from"node:fs";import{basename as Mc,dirname as Hc,relative as Dc}from"node:path";var ve=class{constructor(t,n=""){this.home=t;this.pathPrefix=n}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=Dc(this.home,t).replace(/\\/g,"/"),r=!n||n.startsWith("..")?`external/${O(Hc(t))}/${Mc(t)}`:n;return this.pathPrefix?`${this.pathPrefix}${r}`:r}get atGlobalCap(){return this.truncated||this.components.length>=F}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!mo(t))return[];try{return Lc(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(mo(t))return ae(t,n)}push(t){return this.components.length>=F?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as qt,readFileSync as Fc,statSync as $c}from"node:fs";import{basename as _o,join as Oe,relative as ho}from"node:path";var Qt=2e4,Bc=4;function jc(e){return e.length<=Qt?e:`${e.slice(0,Qt-1)}\u2026`}function Kc(e){try{let t=Fc(e),n=t.toString("utf8");return{hash:O(t),length:t.length,text:jc(n)}}catch{return null}}var go={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Gc(e){return e in go?go[e]:"UNSPECIFIED"}function Qe(e,t){let n=Kc(t.absolutePath);if(!n)return!1;let r=t.name??_o(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.homeRel(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=Gc(t.kind);return s&&(o.trigger=s),e.push(o)}function Jc(e,t,n){let r=ho(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?_o(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function oe(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:a,extensions:i}=t;en(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:a,extensions:i})}function en(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:a,enabled:i,nested:c,extensions:l}=t;if(!(o>Bc))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let p=Oe(r,u.name,c);if(qt(p)){let _=ho(n,Oe(r,u.name)).replace(/\\/g,"/");Qe(e,{absolutePath:p,kind:s,origin:a,enabled:i,name:_||u.name});continue}en(e,{walkRoot:n,currentDir:Oe(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(u.isDirectory()){en(e,{walkRoot:n,currentDir:Oe(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let f=u.name.toLowerCase();if(!l.some(p=>f.endsWith(p)))continue;let m=Oe(r,u.name);Qe(e,{absolutePath:m,kind:s,origin:a,enabled:i,name:Jc(n,m,!0)})}}function Eo(e){for(let t of e)if(qt(t))try{if($c(t).size>0)return t}catch{continue}return e.find(t=>qt(t))}var Vc="<omitted>",So=100,yo=120,tt=[{raw:"tools",attr:"tools"},{raw:"autoApprove",attr:"auto_approve"},{raw:"auto_approve",attr:"auto_approve"},{raw:"alwaysAllow",attr:"always_allow"},{raw:"always_allow",attr:"always_allow"},{raw:"enabledTools",attr:"enabled_tools"},{raw:"enabled_tools",attr:"enabled_tools"},{raw:"disabledTools",attr:"disabled_tools"},{raw:"disabled_tools",attr:"disabled_tools"}],Ro=new Set(tt.map(e=>e.attr)),zc=["enabled","disabled"],Wc=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Yc=new Set(["type","command","url","args","env","envVars","headers",...zc,...Wc,...tt.map(e=>e.raw)]),Xc=new Set(["transport","command_or_url","args","env_var_names","headers_present","auth","bearer_token_env_var","default_tools_approval_mode","env_http_header_names",...Ro,...[...Ro].map(e=>`${e}_truncated`)]);function Io(e,t){for(let n of t)Yc.has(n)||Xc.has(n)||(e[n]=Vc)}var Zc=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,qc=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,Qc=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,el=/^bearer(?:\s+|$)/i;function nt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function ko(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function tn(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=nt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function ue(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function tl(e){return Qc.test(e)||el.test(e)?"<redacted>":e.includes("://")?ue(e):e}function Co(e){if(/^https?:\/\//i.test(e))return ue(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Co(e.slice(t+1))}`:tl(e)}function nl(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return Zc.test(t)||qc.test(t)}function rt(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(nl(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Co(r))}return t}function rl(e){let t=ko(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>yo?r.slice(0,yo):r))].sort();if(n.length!==0)return n.length>So?{names:n.slice(0,So),truncated:!0}:{names:n,truncated:!1}}function ol(e){let t=nt(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function Ao(e,t){let n=new Set;for(let{raw:r,attr:o}of tt){if(n.has(o)||!(r in t))continue;let s=t[r];if(o==="auto_approve"&&typeof s=="boolean"){e.auto_approve=s,n.add(o);continue}let a=rl(s);a&&(e[o]=a.names,a.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function vo(e,t){let n=nt(e),r={transport:t};if(!n)return r;Io(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,a=typeof n.serverUrl=="string"?n.serverUrl:void 0,i=o??s??a;i&&(r.command_or_url=ue(i));let c=rt(ko(n.args));c.length>0&&(r.args=c);let l=ol(n.env_http_headers),u=[...new Set([...tn(n.env),...tn(n.envVars),...tn(n.env_vars),...l.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();u.length>0&&(r.env_var_names=u),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let _ of["headers","http_headers","env_http_headers"])if(n[_]!==void 0&&n[_]!==null){r.headers_present=!0;break}let f=typeof n.auth=="string"?n.auth:void 0;f&&(r.auth=f);let m=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;m&&(r.bearer_token_env_var=m);let p=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return p&&(r.default_tools_approval_mode=p),Ao(r,n),r}function Oo(e){let t=nt(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function on(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return O(JSON.stringify({name:e,attributes:r,enabled:n}))}function et(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function sn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*\\[([^\\]]*)\\]`,"m").exec(e);return n?.[1]?[...n[1].matchAll(/"([^"]*)"|'([^']*)'/g)].map(r=>r[1]??r[2]??"").filter(r=>r.length>0):[]}function sl(e,t){return rt(sn(e,t))}function rn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function nn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=et(n[1]);return r.length>0?r:void 0}function il(e,t){let n=[],r=a=>{for(let i of a.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(i);c?.[1]&&n.push([c[1],et(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
22
+ ${e}`);return s?.[1]&&r(s[1]),n}function xo(e){return rn(e,"enabled")===!1?!1:rn(e,"disabled")!==!0}function al(e,t){let n={};for(let{raw:r,attr:o}of tt){if(o==="auto_approve"){let a=rn(t,r);if(a!==void 0){n[r]=a;continue}}let s=sn(t,r);s.length>0&&(n[r]=s)}Ao(e,n)}var cl=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,ll=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function ul(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
23
+ `)){let s=cl.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(ll))o[1]&&t.add(o[1]);return[...t]}function To(e,t){let n={transport:t};Io(n,ul(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?et(r[1]??""):void 0,a=o?et(o[1]??""):void 0,i=s!==void 0&&s.length>0?s:a;i&&(n.command_or_url=ue(i));let c=sl(e,"args");c.length>0&&(n.args=c);let l=new Set;for(let R of e.split(`
24
+ `)){let I=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(R);I?.[1]&&l.add(I[1])}let u=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(u?.[1])for(let R of u[1].split(",")){let I=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(R);I?.[1]&&l.add(I[1])}let f=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
25
+ ${e}`);if(f?.[1])for(let R of f[1].split(`
26
+ `)){let I=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(R);I?.[1]&&l.add(I[1])}for(let R of sn(e,"env_vars"))l.add(R);let m=il(e,"env_http_headers");for(let[,R]of m)R.length>0&&l.add(R);let p=nn(e,"bearer_token_env_var");p&&(l.add(p),n.bearer_token_env_var=p),l.size>0&&(n.env_var_names=[...l].sort()),m.length>0&&(n.env_http_header_names=[...new Set(m.map(([R])=>R))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let _=nn(e,"auth");_&&(n.auth=_);let h=nn(e,"default_tools_approval_mode");return h&&(n.default_tools_approval_mode=h),al(n,e),n}var bo=300;function dl(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function fl(e){let t=[],n="",r=null;for(let o of e){if(r){o===r?r=null:n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}function pl(e){return e.length<=bo?e:`${e.slice(0,bo-1)}\u2026`}function wo(e,t){let n=dl(e.trim(),t),r=fl(n);if(r.length===0)return"";let[o,...s]=r,a=ue(o),i=rt(s);return pl([a,...i].join(" "))}function ml(e){if(e.prompt||e.type==="prompt")return"prompt";let t=e.command??e.bash??e.powershell??"";return/\bnpx\b/i.test(t)?"npx":/\.(sh|bash|zsh|js|mjs|cjs|ts|py)(\s|$|"|')/i.test(t)||/^(\.\/|~\/|\/|[A-Za-z]:[\\/])/.test(t.trim())?"script":"inline"}function gl(e){return Array.isArray(e.hooks)&&e.hooks.length>0?e.hooks:[{type:e.type,command:e.command,bash:e.bash,powershell:e.powershell,prompt:e.prompt}]}function _l(e,t,n,r){let o=e.homeRel(t);for(let[s,a]of Object.entries(n))if(!(!Array.isArray(a)||e.truncated))for(let i of a){if(!i||typeof i!="object"||e.truncated)continue;let c=i;for(let l of gl(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",f=ml({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",p=O(u),_=m?`${s}:${m}:${f}:${p}`:`${s}:${f}:${p}`,h=`${s}|${m}|${f}|${u}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:O(h),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:f,action_hash:p,...f!=="prompt"&&u.trim()?{command:wo(u,e.home)}:{}}})}}}function xe(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||_l(e,t,r.hooks,n)}var Po={claude:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]}],memory:[".claude/CLAUDE.md"],hooks:[".claude/settings.json"],mcpJson:[".claude.json"],plugins:"claude"},cursor:{skillRoots:[".cursor/skills",".cursor/skills-cursor"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[".cursor/AGENTS.md"],hooks:[".cursor/hooks.json"],mcpJson:[".cursor/mcp.json"],plugins:"cursor"},codex:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]}],memory:[".codex/AGENTS.override.md",".codex/AGENTS.md"],hooks:[".codex/hooks.json"],mcpToml:[".codex/config.toml"]}};import{existsSync as hl,readFileSync as El}from"node:fs";function Sl(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function No(e,t,n){let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.homeRel(t);for(let[a,i]of Object.entries(o)){if(e.truncated)return;let c=Sl(i),l=vo(i,c),u=Oo(i);e.push({kind:"MCP_SERVER",name:a,path:s,content_hash:on(a,l,u),origin:n,enabled:u,attributes:l})}}function Uo(e,t,n){if(!hl(t))return;let r;try{r=El(t,"utf8")}catch{return}let o=e.homeRel(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,a;for(;(a=s.exec(r))!==null;){if(e.truncated)return;let i=a[1]??a[2]??a[3];if(!i)continue;let c=r.slice(a.index+a[0].length),l=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),f="unknown";/^\s*url\s*=/m.test(u)?f="http":/^\s*command\s*=/m.test(u)&&(f="stdio");let m=To(u,f),p=xo(u);e.push({kind:"MCP_SERVER",name:i,path:o,content_hash:on(i,m,p),origin:n,enabled:p,attributes:m})}}import{existsSync as yl,readdirSync as Rl}from"node:fs";import{join as T}from"node:path";var Lo=50;function an(e,t,n,r){if(!yl(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(Lo,()=>{oe(e,{dir:T(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),oe(e,{dir:T(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),oe(e,{dir:T(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});xe(e,T(t,"hooks","hooks.json"),n),xe(e,T(t,"hooks.json"),n);let a=e.components.length-o,i=s>=Lo;return{componentCount:a,expandTruncated:i}}function cn(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function Mo(e){let t=T(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(T(e.home,".claude/settings.json"),{})?.enabledPlugins??{},a=e.homeRel(t);for(let[i,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},f=s[i]===!0,m=i.includes("@")?i.split("@").slice(1).join("@"):"",p=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",h=`plugin:${i}`,R=0,I=!1;for(let N of l)if(typeof N.installPath=="string"&&N.installPath.length>0){let q=an(e,N.installPath,h,f);R+=q.componentCount,I=I||q.expandTruncated}cn(e,{pluginKey:i,rowPath:a,enabled:f,scope:_,version:p||void 0,marketplace:m||void 0,componentCount:R,expandTruncated:I,contentHash:O(`${i}|${p}|${_}|${f}|${R}`)})}}function Il(e){let t=e,n="";try{let r=Rl(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=T(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=T(e,s),n=s)}}catch{}return{installPath:t,version:n}}var kl=/^\d+$/;function Cl(e){let t=e.filter(n=>!kl.test(n.pluginId));return t.length>0?t:e}function Ho(e){let t=[{base:T(e.home,".cursor/plugins/local"),scope:"local"},{base:T(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let i=o.name,c=T(n,o.name),l=`plugin:${i}`,{componentCount:u,expandTruncated:f}=an(e,c,l,!0);cn(e,{pluginKey:i,rowPath:e.homeRel(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:f,contentHash:O(`${i}|local|${u}`)});continue}let s=o.name,a=[];for(let i of e.readEntries(T(n,s))){if(!i.isDirectory())continue;let c=T(n,s,i.name),{installPath:l,version:u}=Il(c);a.push({pluginId:i.name,installPath:l,version:u})}for(let i of Cl(a)){if(e.truncated)break;let c=`${i.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:f}=an(e,i.installPath,l,!0);cn(e,{pluginKey:c,rowPath:e.homeRel(i.installPath),enabled:!0,scope:"cache",version:i.version||void 0,marketplace:s,componentCount:u,expandTruncated:f,contentHash:O(`${c}|${i.version}|${u}`)})}}}function Fo(e,t,n,r){let o=Po[t];if(!o)return;let s=e.home;for(let i of o.skillRoots)oe(e,{dir:de(s,i),kind:"SKILL",origin:n,enabled:!0,nested:"SKILL.md"});for(let i of o.dirs)oe(e,{dir:de(s,i.dir),kind:i.kind,origin:n,enabled:!0,extensions:i.extensions});let a=Eo(o.memory.map(i=>de(s,i)));a&&Qe(e,{absolutePath:a,kind:"MEMORY",origin:n,enabled:!0,name:Al(a)});for(let i of o.hooks)xe(e,de(s,i),n);for(let i of o.mcpJson??[])No(e,de(s,i),n);for(let i of o.mcpToml??[])Uo(e,de(s,i),n);r&&(o.plugins==="claude"?Mo(e):o.plugins==="cursor"&&Ho(e))}function ln(e,t,n){let r=new ve(t);if(Fo(r,e,"user",!0),n===void 0||Do(n)===Do(t))return{components:r.components,truncated:r.truncated};let s=new ve(n,"cwd/");Fo(s,e,"cwd",!1);let a=[...r.components,...s.components],i=r.truncated||s.truncated||a.length>F;return{components:a.slice(0,F),truncated:i}}function un(e,t,n={}){let r=n.truncated===!0,o=Xt(e),s=new Set(e.map(u=>V(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let i=[],c=t;for(let u of e){let f=V(u.path,u.name);c[f]!==u.content_hash&&i.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let f=lo(u);f&&l.push(f)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:i,removed:l,unchanged:i.length===0&&l.length===0}}var Bo=3e5,vl=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function dn(e,t,n){let r=new Set(t.map(s=>V(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(V(s.path,s.name))||o.push(s));return o}function fn(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function $o(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function jo(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function pn(e,t=Bo){let n=[],r=[];for(let u of e)vl.has(u.kind)?n.push(u):r.push(u);r.sort((u,f)=>(u.text?.length??0)-(f.text?.length??0));let o=[...n,...r],s=[],a=2,i=0,c=0,l=[];for(let u of o){let f=s.length>0?1:0,m=$o(u)+f;if(a+m<=t){s.push(u),a+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let p=jo(u),_=$o(p)+f;if(a+_<=t){s.push(p),a+=_,i+=1;continue}}c+=1}return{components:s,textDeferredCount:i,droppedCount:c,textHashesSent:l}}function mn(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:jo(n))}var Tl={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],subagents:".cursor/agents",commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:[".agents/skills",".codex/skills"],subagents:".codex/agents",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},bl=200,Ko=200,wl=["allow","deny","ask"],Pl=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,gn="<path>",Nl=new RegExp(`${gn}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Ul(e){let t=e.replace(Pl,gn).replace(Nl,gn);return t.length>Ko?`${t.slice(0,Ko)}...`:t}function Go(e){let t=ae(e,{}),n=[];for(let r of wl)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Ul(o),mode:r});return{model:t.model??"",permissionKeys:n}}var Ll=10,Ml=840*60*1e3,Hl="self-config-cache.json";function _n(){return A("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Dl(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Ml}var Fl={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function $l(e,t=v){let n=Fl[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let i=((await t(s,["--version"],2e3)).split(`
27
+ `)[0]??"").trim();return i||r(o+1)};return r(0)}function Bl(e=Jo()){return H(e,".ev-ai","agent-hook",Hl)}function jl(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
28
+ `);return O(n)}function ot(e,t,n=!1){let r=jl(e),o=e.length;return t===r?n?{hash:r,count:o,truncated:n}:{hash:r,count:o}:n?{hash:r,count:o,entries:e,truncated:n}:{hash:r,count:o,entries:e}}function Kl(e){return Ol(e)?P(xl(e,"utf8"),{}):{}}function Gl(e,t){try{X(e,`${JSON.stringify(t)}
29
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: self-config cache write failed open: ${r}`)}}function Jl(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let a=t[s];a.entries!==void 0&&(o[s]=a.hash)}return r&&(o.user_spec_collected_at_ms=r.collectedAtMs,r.included&&(o.user_spec=r.hash,o.user_spec_components=r.componentHashes),o.user_spec_text_hashes=r.textHashes),o}async function Vo(e,t=process.cwd(),n=Jo(),r={}){let o=e==="claude",s=r.gitRoot??t,a=await $l(e),i="",c=[];if(o){let U=Go(H(n,".claude/settings.json")),$=Go(H(t,".claude/settings.local.json"));i=$.model||U.model,c=[...U.permissionKeys,...$.permissionKeys].slice(0,bl)}let l=Tl[e]??{},u={present:!1,size:0},f=U=>{let $=Array.isArray(U)?U:U?[U]:[],C=[],W=!1;for(let dt of $){let w=Ee(H(n,dt));if(C=C.concat(w.entries),W=W||w.truncated,C.length>=F){C=C.slice(0,F),W=!0;break}}return{entries:C,truncated:W}},m=Bl(n),p=Kl(m),_=p[e]??{},h=(_.send_count??0)+1,R=h>0&&h%Ll===0,I=U=>R?void 0:_[U],N=f(l.skills),q=l.subagents?Ee(H(n,l.subagents)):{entries:[],truncated:!1},ut=l.commands?Ee(H(n,l.commands)):{entries:[],truncated:!1},En=l.rules?Ee(H(n,l.rules)):{entries:[],truncated:!1},me={skills:ot(N.entries,I("skills"),N.truncated),subagents:ot(q.entries,I("subagents"),q.truncated),commands:ot(ut.entries,I("commands"),ut.truncated),rules:ot(En.entries,I("rules"),En.truncated)},b={runner_platform:e,config_scope:"user",cli_version:a,claude_version:o?a:null,model:o&&i||null,permission_keys:c,user_scope:{skills:me.skills,subagents:me.subagents,commands:me.commands,rules:me.rules,memory:l.memory?Se(H(n,l.memory)):u,settings:l.settings?Se(H(n,l.settings)):u,mcp:l.mcp?Se(H(n,l.mcp)):u},local_settings:o?Se(H(t,".claude/settings.local.json")):u},Sn=null,yn=()=>{},Rn=r.nowMs??Date.now();if(!_n()&&Dl(_.user_spec_collected_at_ms,Rn)){let U=_.user_spec_collected_at_ms!==void 0,$=ln(e,n),C=un($.components,_.user_spec_components,{forceFull:!_.user_spec_components,truncated:$.truncated}),W=new Set(_.user_spec_text_hashes??[]),dt=dn($.components,C.upserts,W),w=pn(mn([...C.upserts,...dt],W));b.user_spec_hash=C.hash,b.user_spec_count=C.count,b.user_spec_truncated=C.truncated||w.droppedCount>0,(w.components.length>0||C.removed.length>0||C.full)&&(C.full&&(b.user_spec_full=!0),w.components.length>0&&(b.user_spec=w.components),C.removed.length>0&&!b.user_spec_truncated&&(b.user_spec_removed=C.removed),w.textDeferredCount>0&&(b.user_spec_text_deferred=w.textDeferredCount));let ft=C.full?{}:{..._.user_spec_components??{}};if(!b.user_spec_truncated)for(let ie of C.removed)delete ft[V(ie.path,ie.name)];for(let ie of w.components)ft[V(ie.path,ie.name)]=ie.content_hash;Sn={hash:C.hash,componentHashes:ft,textHashes:fn(W,w.textHashesSent,$.components),included:w.components.length>0||C.removed.length>0&&!b.user_spec_truncated||C.full,collectedAtMs:Rn};let pt=await qe({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:U});pt.operator&&(b.operator=pt.operator),yn=pt.commit}let cs=Jl(_,me,h,Sn);return{config:b,commit:()=>{p[e]=cs,Gl(m,p),yn()}}}function fe(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp:De(),session_id:n.sessionId||null,turn_id:n.turnId||null,installation_id:n.installationId,platform:n.runnerPlatform,platform_agent_id:n.platformAgentId||null,runner_event:n.runnerEvent||null,agent_hook_version:B,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as zo}from"node:fs";import{spawn as Wo}from"node:child_process";import{basename as Vl}from"node:path";import{fileURLToPath as zl}from"node:url";var Te="__post",st="__work";function Wl(e,t){let n=e.payload,r=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],o=e.correlation&&typeof e.correlation=="object"?Object.keys(e.correlation):[];return JSON.stringify({event:e.event,schema_version:e.schema_version,agent_hook_version:e.agent_hook_version,host_arch:e.host_arch,node_version:e.node_version,build_ms:e.build_ms,body_bytes:t,correlation_keys:o,payload_keys:r})}function Yo(e){switch(e){case"session_start":return vn;case"session_end":return On;case"tool_invoked":case"skill_invoked":return _t;default:return _t}}function Yl(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
30
+ ${n}`}function Xo(e,t=[],n=process.execPath,r=import.meta.url,o=zo){if(Vl(n)===Y)return{command:n,args:[e,...t]};let s=zl(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Xl(e=process.execPath,t=import.meta.url,n=zo){return Xo(Te,[],e,t,n)}function Zl(e){let t=e.indexOf(`
31
+ `);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function it(e,t=fetch){let n=await e(),r=Zl(n);if(!r)return;let{meta:o,body:s}=r,a={"Content-Type":"application/json"};try{await t(o.url,{method:"POST",headers:a,body:s,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function ql(e,t,n){let r=Yo(e);d(`POST event=${e} url=${Et(n)} size=${t.length} platform=${process.platform}`);let o={"Content-Type":"application/json"},s=Date.now();try{let a=await fetch(n,{method:"POST",headers:o,body:t,signal:AbortSignal.timeout(r)}),i=Date.now()-s;if(a.ok)return d(`POST outcome=ok elapsed_ms=${i} http=${a.status}`),!0;let c=(await a.text()).slice(0,200).replace(/[\n\r]/g,"");return d(`POST outcome=fail elapsed_ms=${i} http=${a.status} body=${c}`),!1}catch(a){let i=Date.now()-s,c=a instanceof Error?a.message:String(a);return d(`POST outcome=fail elapsed_ms=${i} http=000 body=${c}`),!1}}async function Zo(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let a=!1;return await new Promise(i=>{let c=setTimeout(()=>{if(!a){d(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}i()},xn),l=()=>{a=!0,clearTimeout(c),i()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let a=s instanceof Error?s.message:String(s);return d(`WARN: ${o} spawn failed open: ${a}`),null}}async function Ql(e,t,n,r=Wo,o=Xl){let s=Yo(e),a=Yl(n,s,t),{command:i,args:c}=o();return Zo(i,c,a,r,"detached post")}async function qo(e,t,n=Wo,r=Xo){let{command:o,args:s}=r(st,t);return Zo(o,s,e,n,"detached work")}async function pe(e,t,n,r,o,s){if(!o)return d("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!He(o))return d(`WARN: collector URL blocked (https required): ${Et(o)}`),!1;let a=r(e,t,n);s!==void 0&&(a.build_ms=Math.max(0,Date.now()-s));let i=`${JSON.stringify(a)}
32
+ `,c=A("EV_AI_HOOK_DEBUG");c==="full"?d(`DEBUG envelope=${JSON.stringify(a)}`):c==="1"&&d(`DEBUG summary=${Wl(a,Buffer.byteLength(i,"utf8"))}`);let l=process.argv.includes(st),u=A("EV_AI_HOOK_SYNC")==="1";return We(n.runnerEvent,n.runnerPlatform)||l||u?ql(e,i,o):(await Ql(e,i,o),!1)}import{relative as eu,resolve as at,sep as hn}from"node:path";var tu=["session_id","conversation_id","turn_id","generation_id","prompt.id","prompt_id","hook_event_name","event","source","status","stop_reason","reason","tool_name","tool","tool_use_id","skill_name","command_name","expansion_type","command_source","permission_mode","model","model_id","agent_id","agent_type","subagent_id","subagent_type","subagent_model","is_parallel_worker","effort","effort.level","duration_ms","duration","sandbox","failure_type","is_interrupt"];function nu(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:A("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function ru(e){let t={};for(let n of tu){let r=te(e,n);r!==void 0&&(t[n]=r)}return t}function ou(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=at(e),r=at(t),o=eu(r,n);return!o||o==="."?".":o.startsWith(`..${hn}`)||o===".."||at(r,o)!==n?null:o.split(hn).join("/")}function su(e){return typeof e!="string"||e.length===0?null:at(e).split(hn).join("/")}function Qo(e,t,n){let r=su(t.cwd);r!==null&&(e.cwd=r);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?ou(t.cwd,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function es(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([a,i])=>!a.startsWith("_")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")).sort((a,i)=>Buffer.byteLength(JSON.stringify(a[1]),"utf8")-Buffer.byteLength(JSON.stringify(i[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[a,i]of o){let c={...s,[a]:i};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[a]=i}return s}function be(e,t,n={}){if(nu(t)){let o={...e};return delete o.cwd,delete o.transcript_path,Qo(o,e,n),es(o,bn)}let r=ru(e);return Qo(r,e,n),es(r,Tn)}import{createReadStream as iu}from"node:fs";import{stat as au}from"node:fs/promises";import{basename as cu,resolve as lu}from"node:path";import{createInterface as uu}from"node:readline";var du=1024*1024;function fu(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&cu(t).endsWith(".jsonl")}async function ts(e){if(!e||!fu(e))return null;try{let t=lu(e),n=await au(t);if(!n.isFile())return null;let r=Math.max(0,n.size-du),o=[],s=uu({input:iu(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let a of s)a.length!==0&&o.push(a);r>0&&o.length>0&&o.shift();for(let a=o.length-1;a>=0;a--){let i=o[a];if(i)try{let c=JSON.parse(i);if(c.type!=="assistant")continue;let l=c.message;if(!l||typeof l!="object")continue;let u=l.model;if(typeof u=="string"&&u.length>0)return u}catch{continue}}return null}catch{return null}}function Pe(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function ct(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}var mu=new Set([...Object.values(Vt),".github"]);function gu(e,t,n,r,o,s){if(e===null||t===null||!(/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let i=s.find(p=>p.name.toLowerCase()===t.toLowerCase()),c=i?.sourcePath??(i?.source==="claude_json_user"?".claude.json":i?.source==="cursor_mcp_user"?".cursor/mcp.json":i?.source==="codex_toml_user"||i===void 0&&o==="codex"?".codex/config.toml":void 0);if((i?.scope==="user"||i?.source==="claude_json_user"||i?.source==="cursor_mcp_user"||i?.source==="codex_toml_user"||i===void 0&&o==="codex")&&c)try{let p=(0,x.userConfigRootFromPath)(c);return(0,x.buildComponentReference)({installationRootExternalKey:(0,x.installationRootExternalKey)(r,p),installableKind:x.ComponentKind.INTERFACE,sourcePath:c,nativeKey:i?.name??t})}catch{return}if(n===null)return;let u=n.indexOf(":");if(u<=0||u===n.length-1)return;let f=n.slice(u+1),m=f.replaceAll("\\","/").split("/").at(-1);if(!(m===void 0||!mu.has(m)))try{return(0,x.buildComponentReference)({installationRootExternalKey:n,installableKind:x.ComponentKind.INTERFACE,sourcePath:f,nativeKey:t})}catch{return}}function _u(...e){for(let t of e)if(t)return t;return null}function D(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return d(`WARN: ${n} failed open: ${r}`),t}function hu(e){let t={present:!1,size:0},n={hash:"",count:0};return{config:{runner_platform:e,config_scope:"user",cli_version:null,claude_version:null,model:null,permission_keys:[],user_scope:{skills:n,subagents:n,commands:n,rules:n,memory:t,settings:t,mcp:t},local_settings:t},commit:()=>{}}}function Eu(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var se=new Set,we=null;async function ns(e){if(_n())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(se.has(t))return;if(!Zt(n)){se.add(t);return}let r=ye({sessionId:e.sessionId,hostname:Re()});if(po(r)){if(we){await we;return}we=(async()=>{if(se.has(t)||!Zt(n)){se.add(t);return}if(!ir(n)){se.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:a}=e.manifest,i=String(e.runnerPlatform),[c,l,u,f,m]=await Promise.allSettled([Ae(a),At(),zt(r),vt(),qe({gitRoot:a,installationStorePath:n,forceResend:!1})]),p=D(c,null,"gitSnapshot"),_=D(l,"","detectVirt"),h=D(u,null,"probeCloud"),R=D(f,{},"hostEnv"),I=D(m,{commit:()=>{}},"resolveOperatorForSend");await Ne(e,a,p);let N={identity:{host:Re(),context:r,virt:_||null,cloud:h,git:p},host_env:R,env_vars:Yt(),self_config:Eu(i,I.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await pe("session_start",N,Pe(e),fe,e.manifest.collectorUrl,s),o&&(I.commit(),se.add(t))}finally{ar(n)}})().finally(()=>{we=null}),await we}}async function Ne(e,t,n){try{let r=n===void 0?await Ae(t):n;e.platformAgentId=await oo(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);d(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Su(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=ye({sessionId:e.sessionId,hostname:Re()}),o=String(e.runnerPlatform),[s,a,i,c,l,u]=await Promise.allSettled([Ae(n),At(),zt(r),vt(),Wt(e.manifest.manifest,n,o),Vo(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),f=D(s,null,"gitSnapshot"),m=D(a,"","detectVirt"),p=D(i,null,"probeCloud"),_=D(c,{},"hostEnv"),h=D(l,[],"mcpDeclared"),R=D(u,hu(o),"selfConfig"),I=R.config;await Ne(e,n,f);let N=g(e.hookInput,"model");N&&(I.model=N);let q={identity:{host:Re(),context:r,virt:m||null,cloud:p,git:f},host_env:_,env_vars:Yt(),mcp:{declared:h},self_config:I,run_meta:{trigger:e.hookSource||"startup"},hook_input:be(e.hookInput,e.manifest.manifest,ct(e))};await pe("session_start",q,Pe(e),fe,e.manifest.collectorUrl,t)&&(R.commit(),se.add(e.manifest.installationId))}async function yu(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Ne(e,n);let r=_u(g(e.hookInput,"status"),g(e.hookInput,"stop_reason"),g(e.hookInput,"reason"),Gt(g(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await ts(g(e.hookInput,"transcript_path")):null,s=be(e.hookInput,e.manifest.manifest,ct(e));o&&(s.model=o),await pe("session_end",{status:r,...o?{model:o}:{},hook_input:s},Pe(e),fe,e.manifest.collectorUrl,t)}async function Ru(e){let t=Date.now(),n=Br(e.hookInput);if(n.length===0)return;await ns(e);let{gitRoot:r}=e.manifest;await Ne(e,r);let o=be(e.hookInput,e.manifest.manifest,ct(e)),s=Pe(e),a=Je(e.hookInput.tool_input),i=r.replaceAll("\\","/").replace(/\/$/,""),c=a?.replaceAll("\\","/"),l=c===void 0?null:c.startsWith(`${i}/`)?c.slice(i.length+1):c.startsWith("/")?null:c,u=pu().replaceAll("\\","/").replace(/\/$/,""),f=c?.startsWith(`${u}/`)===!0?c.slice(u.length+1):null;await Promise.all(n.map(m=>{let p;if((l!==null||f!==null)&&$t(l??f??"")?.toLowerCase()===m.toLowerCase()){let _=l??f,h=_===null?null:(0,x.nativeKeyForSkillPath)(_);if(h!==null)try{let R=l!==null?e.platformAgentId:(0,x.installationRootExternalKey)(e.manifest.installationId,(0,x.userConfigRootFromPath)(_));R&&(p=(0,x.buildComponentReference)({installationRootExternalKey:R,installableKind:x.ComponentKind.SKILL,sourcePath:_,nativeKey:h}))}catch{p=void 0}}return pe("tool_invoked",{tool_name:"Skill",skill_name:m,...p===void 0?{}:{component_reference:p},success:null,duration_ms:null,hook_input:o},s,fe,e.manifest.collectorUrl,t)}))}async function Iu(e){let t=Date.now();await ns(e);let{gitRoot:n}=e.manifest;await Ne(e,n);let{toolName:r,skillName:o}=Vr(e.hookInput,e.runnerEvent),s=Wr(e.hookInput),a=Kr(e.runnerEvent),i=a===!1?Yr(e.hookInput,e.runnerEvent):null,c=await Wt(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=Xr(r,c.map(p=>p.name)),f=gu(r,l,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),c),m=zr(e.hookInput);await pe("tool_invoked",{tool_name:r,skill_name:o,success:a,duration_ms:s,...i?{failure_reason:i}:{},...l?{mcp_server:l}:{},...u?{mcp_tool:u}:{},...f?{component_reference:f}:{},...m?{subagent_type:m}:{},hook_input:be(e.hookInput,e.manifest.manifest,ct(e))},Pe(e),fe,e.manifest.collectorUrl,t)}async function rs(e){switch(e.internalEvent){case"session_start":await Su(e);return;case"session_end":await yu(e);return;case"skill_invoked":await Ru(e);return;case"tool_invoked":await Iu(e);return;default:return}}function os(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function ss(e,t,n,r){let o=t??await Rt(ht),s=P(o,{}),a=g(s,"session_id")||g(s,"conversation_id"),i=await fr(process.cwd(),{sessionId:a});if(!i)return;r&&(i.collectorUrl=r);let c=Gr(s,i.manifest.platform,n),l=Jr(e,c.runnerEvent);if(!l){d(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:c.turnId,runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:i,platformAgentId:i.platformAgentId};if(os(l)){d(`WARN: unsupported internal event '${l}'`);return}await rs(u)}function ku(e,t){if(A("EV_AI_HOOK_SYNC")==="1")return!0;let n=ze(e),r=P(t,{}),o=n.event??(g(r,"hook_event_name")||g(r,"event")),s=ke(r,o,void 0,n.runner);return We(o,s)}async function is(e=process.argv.slice(2)){if(e[0]===Te){try{await it(he)}catch{}return 0}if(e[0]===st){try{let t=ze(e.slice(1)),n=await he(),r=P(n,{}),o=t.event??(g(r,"hook_event_name")||g(r,"event"));if(kt()||Kt(t.runner,r,o))return 0;await ss(t.event,n,t.runner,jt(t))}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Rt(ht),n=ze(e),r=jt(n),o=P(t,{}),s=n.event??(g(o,"hook_event_name")||g(o,"event"));if(kt()||Kt(n.runner,o,s)||!ro(o,s,n.runner))return 0;ku(e,t)?await ss(n.event,t,n.runner,r):await qo(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{Bn()}return 0}function lt(){d("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),d(" configure [--url <\u2026/{orgToken}/hook>]"),d(" (manifest only \u2014 pair with marketplace plugins)"),d(" install --url <\u2026/{orgToken}/hook>"),d(" [--delivery npx|binary|local] [--force]"),d(" [--no-claude] [--no-cursor] [--no-codex]"),d(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),d(" (writes collector_url to shared manifest; hook commands use --runner only)"),d(" migrate-to-plugin"),d(" (strip ev-ai file hooks; keep collector manifest)"),d(" update (refresh binary pins from a local build; leaves hook configs alone)"),d(" uninstall"),d("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),d(" (--url/--token optional overrides; else collector_url from manifest)")}function as(e){return e.includes("--help")||e.includes("-h")}async function xu(e=process.argv.slice(2)){let[t,...n]=e;if(t===Te){try{await it(he)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${B}
33
+ `),0):t==="configure"?as(n)?(lt(),0):(await Ur(yr(n)),0):t==="install"?as(n)?(lt(),0):(await Pr(Rr(n)),0):t==="migrate-to-plugin"?(await Mr(),0):t==="update"?(await Nr(),0):t==="uninstall"?(await Hr(),0):t==="help"||t==="--help"||t==="-h"?(lt(),0):t===void 0?(lt(),1):is(e)}function Tu(e,t,n=Cu){if(!t)return!1;try{return e===Ou(Au(t)).href?!0:n(vu(e))===n(t)}catch{return!1}}Tu(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&xu().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);d(t),process.exit(1)});export{Tu as isCliEntrypoint,xu as main};
package/dist/hook.mjs CHANGED
@@ -1,16 +1,27 @@
1
- var dr="https://hooks.ev-ai.ai";function le(e,t=dr){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var Tt=".claude/ev-ai-runtime-report.json";var ue="ev-ai-agent-hook";var fi=`current/${ue}`,mi=`.ev-ai/agent-hook/${ue}`,At=5e3,kt=5e3,xe=3e3;var Ue=3e3,Ot=1500,xt=4*1024,Ut=32*1024,pr=4*1024,be="1.0.7",gi=`@ev-ai/agent-hook@${be}`;var bt=["claude","cursor","codex"];import{createHash as Bt,randomBytes as yr}from"node:crypto";import{existsSync as $t,mkdirSync as Gt,readFileSync as Kt,unlinkSync as jt,writeFileSync as Vt}from"node:fs";import{homedir as Me}from"node:os";import{dirname as Le,join as Pe,resolve as Ir}from"node:path";import{randomBytes as fr}from"node:crypto";import{existsSync as Mt,mkdirSync as mr,readdirSync as gr,readFileSync as _r,renameSync as wt,statSync as Lt,unlinkSync as Nt,writeFileSync as hr}from"node:fs";import{basename as Er,dirname as vt,join as Pt,relative as Sr}from"node:path";function m(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
2
- `)}function B(e,t){mr(vt(e),{recursive:!0});let n=Pt(vt(e),`.${Er(e)}.${process.pid}.${fr(4).toString("hex")}.tmp`);try{hr(n,t,"utf8");try{wt(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Nt(e),wt(n,e);return}throw r}}catch(r){try{Nt(n)}catch{}throw r}}function de(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Dt(){process.stdout.write('{"continue":true}')}function E(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Ne(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function ve(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function L(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,l=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:l,spawnFailed:l===void 0}}}async function R(e,t,n=3e3,r={}){let o=await L(e,t,n,r);return o.ok?o.stdout:""}async function pe(e=process.cwd()){return await R("git",["rev-parse","--show-toplevel"],2e3,{cwd:e})||e}function O(e,t){try{return JSON.parse(e)}catch{return t}}var we=new Map;function W(e,t){let n=we.get(e);if(n!==void 0)return n;try{let r=O(_r(e,"utf8"),t);return we.set(e,r),r}catch{return we.set(e,t),t}}function Q(e){return typeof e=="string"?e:""}function $(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function p(e,t){let n=$(e,t);return typeof n=="string"?n:""}var G=500;function q(e,t=2){if(!Mt(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=gr(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=Pt(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:Sr(e,l),size:Lt(l).size})}catch{continue}if(n.length>=G){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function ee(e){return Mt(e)?{present:!0,size:Lt(e).size}:{present:!1,size:0}}var Rr="installation.json",Cr="cloud-bootstrap.lock",Tr=6e4;function zt(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function De(e=Me()){return Pe(e,".ev-ai","agent-hook")}function Ar(e=Me()){return Pe(De(e),Rr)}function Wt(e){return Pe(Le(e),Cr)}function Jt(){return yr(8).toString("hex")}function fe(e){return Bt("sha256").update(e).digest("hex").slice(0,16)}function y(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Yt(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function kr(e=process.env){let t=y(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Yt(t)){m(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function Or(e=process.env){if(y(e.GITHUB_ACTIONS)){let t=y(e.GITHUB_REPOSITORY_ID)??y(e.GITHUB_REPOSITORY),n=y(e.GITHUB_ACTOR)??y(e.GITHUB_TRIGGERING_ACTOR)??y(e.GITHUB_USER);if(t&&n)return fe(`github_actions|${t}|${n}`)}if(y(e.CODESPACES)||y(e.CODESPACE_NAME)){let t=y(e.CODESPACE_NAME);if(t)return fe(`codespaces|${t}`);let n=y(e.GITHUB_REPOSITORY_ID)??y(e.GITHUB_REPOSITORY),r=y(e.GITHUB_USER)??y(e.GITHUB_ACTOR);if(n&&r)return fe(`codespaces|${n}|${r}`)}if(y(e.GITLAB_CI)){let t=y(e.CI_PROJECT_ID)??y(e.CI_PROJECT_PATH),n=y(e.GITLAB_USER_LOGIN)??y(e.GITLAB_USER_EMAIL)??y(e.GITLAB_USER_NAME);if(t&&n)return fe(`gitlab|${t}|${n}`)}return null}function Ht(e,t){if(e&&Yt(e))return e;e&&m(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`);let n=kr(t);if(n)return n;let r=Or(t);return r||Jt()}async function xr(e){let n=await R("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Ir(e);return Bt("sha256").update(n).digest("hex").slice(0,16)}function Ur(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&r.length>0&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function br(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Ur(t.platform_agent_ids);return{installation_id:t.installation_id,...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function K(e){if($t(e))try{return br(Kt(e,"utf8"))}catch{}}function He(e){return K(e)}function Xt(e,t,n){let r=K(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{B(e,`${JSON.stringify(o,null,2)}
3
- `)}catch(s){let i=s instanceof Error?s.message:String(s);m(`WARN: operator identity cache write failed open: ${i}`)}}function Zt(e,t=Date.now()){if(!e)return!0;if(K(e)?.operator_identity_hash)return!1;let n=Wt(e);try{if($t(n)){let r=Number.NaN;try{r=Number(Kt(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Tr)return!1;try{jt(n)}catch{}}}catch{}try{return Gt(Le(n),{recursive:!0}),Vt(n,`${t}
4
- `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(tn(r))return!1;let o=r instanceof Error?r.message:String(r);return m(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function Qt(e){if(e)try{jt(Wt(e))}catch{}}function qt(e,t){let r=K(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function en(e,t,n){if(!n)return;let r=K(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{B(e,`${JSON.stringify(o,null,2)}
5
- `)}catch(s){let i=s instanceof Error?s.message:String(s);m(`WARN: platform_agent_id cache write failed open: ${i}`)}}function tn(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function wr(e,t){Gt(Le(e),{recursive:!0}),Vt(e,`${JSON.stringify(t,null,2)}
6
- `,{encoding:"utf8",flag:"wx"})}function Ft(e,t){try{return wr(e,t),t}catch(n){if(!tn(n))throw n;return K(e)}}async function nn(e,t={}){let n=t.home??Me(),r=t.env??process.env,o=await xr(e),s=Ar(n),i=K(s);if(i)return{installationId:i.installation_id,storePath:s,repoKey:o};let a=Ht(t.overrideId,r),c=Ft(s,{installation_id:a});if(c)return{installationId:c.installation_id,storePath:s,repoKey:o};let l=Ht(void 0,r),u=Ft(s,{installation_id:l===a?Jt():l});if(u)return{installationId:u.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}var Nr={claude:".claude",cursor:".cursor",codex:".codex"};function te(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function vr(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return te(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return te(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?te(o[1]):te(t)}async function ne(e=process.cwd()){let t=await L("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([L("git",["remote","get-url","origin"],2e3,{cwd:e}),L("git",["branch","--show-current"],2e3,{cwd:e}),L("git",["rev-parse","HEAD"],2e3,{cwd:e}),L("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function rn(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Nr[n];if(!a)return"";let c=zt(n,e.scope_path,i);if(s){let h=qt(s,c);if(h)return h}let l=o??await ne(r),u=l?.remote?vr(l.remote):"";if(u||(u=te(process.env.GITHUB_REPOSITORY??"")),!u)return"";let d=e.scope_path??"",g=d?`${d}/`:"",f=`${u}:${g}${a}`;return s&&en(s,c,f),f}import{existsSync as Mr,readFileSync as Lr}from"node:fs";import{hostname as Pr,userInfo as Dr}from"node:os";function me(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var Hr=["GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Fr(){return Hr.some(e=>!!E(e))}function Br(){if(E("KUBERNETES_SERVICE_HOST")||me(E("REMOTE_CONTAINERS"))||me(E("DEVCONTAINER")))return!0;try{if(Mr("/.dockerenv")||Lr("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Fe(){if(E("GITHUB_ACTIONS"))return"github_actions";if(me(E("CLAUDE_CODE_REMOTE")))return"claude_remote";if(me(E("CURSOR_AGENT")))return"cursor_cloud";if(E("CODESPACES")||E("CODESPACE_NAME"))return"codespaces";if(Fr())return"managed";let e=E("CI");return e&&e!=="false"&&e!=="0"?"managed":Br()?"container":process.stdin.isTTY||process.stdout.isTTY||E("TERM")?"interactive":"cron"}async function Be(){return await R("systemd-detect-virt",[],1e3)}function $r(e=process.env,t=Dr){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function $e(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await R("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),i=s("/etc/os-release","utf8"),a=i.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=i.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=a??c??""}catch{t=await R("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await R("uname",["-r"],1e3))}else t=await R("ver",[],1e3);let n=$r(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await R("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function Ge(){return Pr()}import{existsSync as Gr,readFileSync as Kr}from"node:fs";import{homedir as on}from"node:os";import{join as jr}from"node:path";var Vr="cloud-cache.json",zr=1440*60*1e3,Wr=900*1e3;function Jr(e=on()){return jr(De(e),Vr)}function Yr(e){if(!Gr(e))return;let t=O(Kr(e,"utf8"),{});if(!(typeof t.context!="string"||typeof t.probed_at!="number"||t.result!==null&&t.result!==void 0&&typeof t.result!="object"))return{context:t.context,probed_at:t.probed_at,result:t.result??null}}function Xr(e,t){try{B(e,`${JSON.stringify(t)}
7
- `)}catch(n){let r=n instanceof Error?n.message:String(n);m(`WARN: cloud cache write failed open: ${r}`)}}function Zr(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Wr:zr;return n-e.probed_at<r}async function Qr(e){let t=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=(await t.text()).trim();if(!n)return;let r={"X-aws-ec2-metadata-token":n},[o,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!o?.ok&&!s?.ok)return;let i=o?.ok?(await o.text()).trim():"",a=s?.ok?(await s.text()).trim():"";if(!(!i&&!a))return{provider:"aws",region:i,instance_id:a}}async function qr(e){let t=await fetch("http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true",{headers:{"Metadata-Flavor":"Google"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=typeof n.zone=="string"?n.zone.split("/").pop()??"":"",o=n.id===void 0?"":String(n.id);if(!(!r&&!o))return{provider:"gcp",region:r,instance_id:o}}async function eo(e){let t=await fetch("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{headers:{Metadata:"true"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=n.compute?.location??"",o=n.compute?.vmId??"";if(!(!r&&!o))return{provider:"azure",region:r,instance_id:o}}async function to(e){let t=await Promise.allSettled([Qr(e),qr(e),eo(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Ke(e,t){if(e==="interactive")return null;let n=t?.home??on(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Jr(n),i=Yr(s);if(Zr(i,e,o))return i.result;let a=await to(r);return Xr(s,{context:e,probed_at:o,result:a}),a}import{existsSync as no}from"node:fs";import{homedir as ro}from"node:os";import{join as je}from"node:path";function Ve(e,t,n){if(!no(e))return;let r=W(e,{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,source:t})}async function ze(e,t=process.cwd(),n="claude",r=ro()){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{name:s.name,source:"manifest"});return n==="claude"&&Ve(je(r,".claude.json"),"claude_json_user",o),Ve(je(t,".mcp.json"),"mcp_json",o),Ve(je(t,".cursor/mcp.json"),"cursor_mcp",o),[...o.values()]}var oo=["CI","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER","KUBERNETES_SERVICE_HOST","REMOTE_CONTAINERS","DEVCONTAINER","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REF","GITHUB_SHA","GITHUB_RUN_ID","GITHUB_WORKFLOW","GITHUB_ACTOR","GITHUB_TRIGGERING_ACTOR","GITHUB_ACTOR_ID","GITHUB_USER","GITLAB_USER_LOGIN","GITLAB_USER_NAME","GITLAB_USER_EMAIL","BUILD_REQUESTEDFOR","BUILD_REQUESTEDFOREMAIL","BUILDKITE_BUILD_CREATOR","BUILDKITE_BUILD_CREATOR_EMAIL","BUILD_USER","BUILD_USER_ID","BUILD_USER_EMAIL","CHANGE_AUTHOR","CHANGE_AUTHOR_EMAIL","CIRCLE_USERNAME","CODEBUILD_INITIATOR","DRONE_COMMIT_AUTHOR","DRONE_COMMIT_AUTHOR_NAME","DRONE_COMMIT_AUTHOR_EMAIL","EV_AI_HOOK_OPERATOR_NAME","EV_AI_HOOK_OPERATOR_EMAIL","GIT_AUTHOR_NAME","GIT_AUTHOR_EMAIL","GIT_COMMITTER_NAME","GIT_COMMITTER_EMAIL","EMAIL","RUNNER_OS","RUNNER_ARCH","NODE_ENV","TERM_PROGRAM","CLAUDE_CODE_REMOTE","CLAUDE_CODE_REMOTE_SESSION_ID","CURSOR_AGENT","CODESPACES","CODESPACE_NAME","ANTHROPIC_BASE_URL","OPENAI_BASE_URL","OPENAI_API_BASE","AZURE_OPENAI_ENDPOINT","GOOGLE_GEMINI_BASE_URL","GEMINI_API_BASE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],so=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function io(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)so.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function We(e=process.env){return oo.map(t=>Object.prototype.hasOwnProperty.call(e,t)?{name:t,present:!0,value:io(e[t]??"")}:{name:t,present:!1})}import{createHash as ao}from"node:crypto";function I(e){return ao("sha256").update(e).digest("hex").slice(0,16)}function P(e,t){return`${e}\0${t}`}function sn(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function Je(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
8
- `);return I(n)}function co(e,t,n="git_config",r=null){return I(`${e??""}|${t??""}|${r??""}|${n}`)}function lo(e){let t=null,n=null;for(let r of e.split(`
9
- `)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function uo(e,t=R){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return lo(n)}function po(e=process.env){let t=_(e.GIT_AUTHOR_NAME),n=_(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=_(e.GIT_COMMITTER_NAME),o=_(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=_(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}async function fo(e,t=R){let n=await t("git",["log","-1","--format=%an%x00%ae"],2e3,{cwd:e});if(!n)return null;let r=n.indexOf("\0"),o=(r>=0?n.slice(0,r):n).trim(),s=(r>=0?n.slice(r+1):"").trim();return!o&&!s?null:{git_user_name:o||null,git_user_email:s||null,platform_login:null,identity_source:"git_log"}}function D(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function mo(e=process.env){let t=D(_(e.EV_AI_HOOK_OPERATOR_NAME),_(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured");if(t)return t;let n=_(e.GITHUB_ACTOR)??_(e.GITHUB_TRIGGERING_ACTOR)??_(e.GITHUB_USER),r=D(n,null,"github",n);if(r)return r;let o=_(e.GITLAB_USER_LOGIN),s=D(_(e.GITLAB_USER_NAME)??o,_(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let i=D(_(e.BUILD_REQUESTEDFOR),_(e.BUILD_REQUESTEDFOREMAIL),"azure_devops");if(i)return i;let a=D(_(e.BUILDKITE_BUILD_CREATOR),_(e.BUILDKITE_BUILD_CREATOR_EMAIL),"buildkite");if(a)return a;let c=D(_(e.BUILD_USER)??_(e.CHANGE_AUTHOR),_(e.BUILD_USER_EMAIL)??_(e.CHANGE_AUTHOR_EMAIL),"jenkins",_(e.BUILD_USER_ID));if(c)return c;let l=_(e.CIRCLE_USERNAME),u=D(l,null,"circleci",l);if(u)return u;let d=_(e.CODEBUILD_INITIATOR),g=D(d,null,"codebuild",d);if(g)return g;let f=D(_(e.DRONE_COMMIT_AUTHOR)??_(e.DRONE_COMMIT_AUTHOR_NAME),_(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",_(e.DRONE_COMMIT_AUTHOR));return f||(an(e.CLAUDE_CODE_REMOTE)||an(e.CURSOR_AGENT)?{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"cloud"}:null)}function Ye(e){return!!((e.git_user_name??e.git_user_email)&&!ho(e.git_user_name,e.git_user_email))}function _(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function an(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var go=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),_o=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function ho(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||_o.has(n)||r.includes("[bot]")||go.has(r))return!0;if(r.endsWith("@users.noreply.github.com")){let o=r.slice(0,r.indexOf("@")),s=o.includes("+")?o.slice(o.indexOf("+")+1):o;if(s.endsWith("bot")||s.includes("[bot]"))return!0}return!1}async function Eo(e,t=R,n=process.env){let r=await uo(e,t);if(Ye(r))return{...r,identity_source:"git_config"};let o=po(n);if(o&&Ye(o))return o;let s=mo(n);if(s&&(s.git_user_name||s.git_user_email||s.platform_login))return s;let i=await fo(e,t);return i&&Ye(i)?i:s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||i||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function ge(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??R,s=e.env??process.env,i=await Eo(t,o,s),a=co(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?He(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let f=n;return{operator:i,commit:()=>{f&&Xt(f,a,de())}}}function Xe(e){return e?!He(e)?.operator_identity_hash:!0}function cn(e){return!0}import{existsSync as $o,readFileSync as Go}from"node:fs";import{homedir as An}from"node:os";import{join as w}from"node:path";import{basename as Fo,join as J}from"node:path";import{existsSync as ln,readdirSync as So}from"node:fs";import{basename as yo,dirname as Io,relative as Ro}from"node:path";var _e=class{constructor(t){this.home=t}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=Ro(this.home,t).replace(/\\/g,"/");if(!n||n.startsWith("..")){let r=Io(t);return`external/${I(r)}/${yo(t)}`}return n}get atGlobalCap(){return this.truncated||this.components.length>=G}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!ln(t))return[];try{return So(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(ln(t))return W(t,n)}push(t){return this.components.length>=G?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Ze,readFileSync as Co,statSync as To}from"node:fs";import{basename as dn,join as re,relative as pn}from"node:path";var Qe=2e4,Ao=4;function ko(e){return e.length<=Qe?e:`${e.slice(0,Qe-1)}\u2026`}function Oo(e){try{let t=Co(e),n=t.toString("utf8");return{hash:I(t),length:t.length,text:ko(n)}}catch{return null}}var un={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function xo(e){return e in un?un[e]:"UNSPECIFIED"}function he(e,t){let n=Oo(t.absolutePath);if(!n)return!1;let r=t.name??dn(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.homeRel(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=xo(t.kind);return s&&(o.trigger=s),e.push(o)}function Uo(e,t,n){let r=pn(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?dn(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function j(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;qe(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function qe(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Ao))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let f=re(r,u.name,c);if(Ze(f)){let h=pn(n,re(r,u.name)).replace(/\\/g,"/");he(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:h||u.name});continue}qe(e,{walkRoot:n,currentDir:re(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){qe(e,{walkRoot:n,currentDir:re(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let d=u.name.toLowerCase();if(!l.some(f=>d.endsWith(f)))continue;let g=re(r,u.name);he(e,{absolutePath:g,kind:s,origin:i,enabled:a,name:Uo(n,g,!0)})}}function fn(e){for(let t of e)if(Ze(t))try{if(To(t).size>0)return t}catch{continue}return e.find(t=>Ze(t))}function bo(e){if(e.prompt||e.type==="prompt")return"prompt";let t=e.command??e.bash??e.powershell??"";return/\bnpx\b/i.test(t)?"npx":/\.(sh|bash|zsh|js|mjs|cjs|ts|py)(\s|$|"|')/i.test(t)||/^(\.\/|~\/|\/|[A-Za-z]:[\\/])/.test(t.trim())?"script":"inline"}function wo(e){return Array.isArray(e.hooks)&&e.hooks.length>0?e.hooks:[{type:e.type,command:e.command,bash:e.bash,powershell:e.powershell,prompt:e.prompt}]}function No(e,t,n,r){let o=e.homeRel(t);for(let[s,i]of Object.entries(n))if(!(!Array.isArray(i)||e.truncated))for(let a of i){if(!a||typeof a!="object"||e.truncated)continue;let c=a;for(let l of wo(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",d=bo({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),g=typeof c.matcher=="string"?c.matcher:"",f=I(u),h=g?`${s}:${g}:${d}:${f}`:`${s}:${d}:${f}`,x=`${s}|${g}|${d}|${u}`;e.push({kind:"HOOK",name:h,path:o,content_hash:I(x),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...g?{matcher:g}:{},action_kind:d,action_hash:f}})}}}function oe(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||No(e,t,r.hooks,n)}var mn={claude:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]}],memory:[".claude/CLAUDE.md"],hooks:[".claude/settings.json"],mcpJson:[".claude.json"],plugins:"claude"},cursor:{skillRoots:[".cursor/skills",".cursor/skills-cursor"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[".cursor/AGENTS.md"],hooks:[".cursor/hooks.json"],mcpJson:[".cursor/mcp.json"],plugins:"cursor"},codex:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]}],memory:[".codex/AGENTS.override.md",".codex/AGENTS.md"],hooks:[".codex/hooks.json"],mcpToml:[".codex/config.toml"]}};import{existsSync as vo,readFileSync as Mo}from"node:fs";function Lo(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function gn(e,t,n){let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.homeRel(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=Lo(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:I(`${i}|${c}`),origin:n,enabled:!0,attributes:{transport:c}})}}function _n(e,t,n){if(!vo(t))return;let r;try{r=Mo(t,"utf8")}catch{return}let o=e.homeRel(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),l=c.search(/^\[/m),u=l===-1?c:c.slice(0,l),d="unknown";/^\s*url\s*=/m.test(u)?d="http":/^\s*command\s*=/m.test(u)&&(d="stdio"),e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:I(`${a}|${d}`),origin:n,enabled:!0,attributes:{transport:d}})}}import{existsSync as Po,readdirSync as Do}from"node:fs";import{join as T}from"node:path";var hn=50;function et(e,t,n,r){if(!Po(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(hn,()=>{j(e,{dir:T(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),j(e,{dir:T(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),j(e,{dir:T(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});oe(e,T(t,"hooks","hooks.json"),n),oe(e,T(t,"hooks.json"),n);let i=e.components.length-o,a=s>=hn;return{componentCount:i,expandTruncated:a}}function tt(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function En(e){let t=T(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(T(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.homeRel(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},d=s[a]===!0,g=a.includes("@")?a.split("@").slice(1).join("@"):"",f=typeof u.version=="string"?u.version:"",h=typeof u.scope=="string"?u.scope:"user",x=`plugin:${a}`,v=0,C=!1;for(let U of l)if(typeof U.installPath=="string"&&U.installPath.length>0){let F=et(e,U.installPath,x,d);v+=F.componentCount,C=C||F.expandTruncated}tt(e,{pluginKey:a,rowPath:i,enabled:d,scope:h,version:f||void 0,marketplace:g||void 0,componentCount:v,expandTruncated:C,contentHash:I(`${a}|${f}|${h}|${d}|${v}`)})}}function Ho(e){let t=e,n="";try{let r=Do(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=T(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=T(e,s),n=s)}}catch{}return{installPath:t,version:n}}function Sn(e){let t=[{base:T(e.home,".cursor/plugins/local"),scope:"local"},{base:T(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let i=o.name,a=T(n,o.name),c=`plugin:${i}`,{componentCount:l,expandTruncated:u}=et(e,a,c,!0);tt(e,{pluginKey:i,rowPath:e.homeRel(a),enabled:!0,scope:"local",componentCount:l,expandTruncated:u,contentHash:I(`${i}|local|${l}`)});continue}let s=o.name;for(let i of e.readEntries(T(n,s))){if(!i.isDirectory()||e.truncated)continue;let a=T(n,s,i.name),{installPath:c,version:l}=Ho(a),u=`${i.name}@${s}`,d=`plugin:${u}`,{componentCount:g,expandTruncated:f}=et(e,c,d,!0);tt(e,{pluginKey:u,rowPath:e.homeRel(c),enabled:!0,scope:"cache",version:l||void 0,marketplace:s,componentCount:g,expandTruncated:f,contentHash:I(`${u}|${l}|${g}`)})}}}function nt(e,t){let n=mn[e],r=new _e(t),o="user";if(!n)return{components:[],truncated:!1};for(let i of n.skillRoots)j(r,{dir:J(t,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)j(r,{dir:J(t,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});let s=fn(n.memory.map(i=>J(t,i)));s&&he(r,{absolutePath:s,kind:"MEMORY",origin:o,enabled:!0,name:Fo(s)});for(let i of n.hooks)oe(r,J(t,i),o);for(let i of n.mcpJson??[])gn(r,J(t,i),o);for(let i of n.mcpToml??[])_n(r,J(t,i),o);return n.plugins==="claude"?En(r):n.plugins==="cursor"&&Sn(r),{components:r.components,truncated:r.truncated}}function rt(e,t,n={}){let r=n.truncated===!0,o=Je(e),s=new Set(e.map(u=>P(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let u of e){let d=P(u.path,u.name);c[d]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let d=sn(u);d&&l.push(d)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:l,unchanged:a.length===0&&l.length===0}}var In=3e5,Bo=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function ot(e,t,n){let r=new Set(t.map(s=>P(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(P(s.path,s.name))||o.push(s));return o}function st(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function yn(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Rn(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function it(e,t=In){let n=[],r=[];for(let u of e)Bo.has(u.kind)?n.push(u):r.push(u);r.sort((u,d)=>(u.text?.length??0)-(d.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let d=s.length>0?1:0,g=yn(u)+d;if(i+g<=t){s.push(u),i+=g,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let f=Rn(u),h=yn(f)+d;if(i+h<=t){s.push(f),i+=h,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function at(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Rn(n))}var Ko={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],subagents:".cursor/agents",commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:[".agents/skills",".codex/skills"],subagents:".codex/agents",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},jo=200,Cn=200,Vo=["allow","deny","ask"],zo=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,ct="<path>",Wo=new RegExp(`${ct}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Jo(e){let t=e.replace(zo,ct).replace(Wo,ct);return t.length>Cn?`${t.slice(0,Cn)}...`:t}function Tn(e){let t=W(e,{}),n=[];for(let r of Vo)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Jo(o),mode:r});return{model:t.model??"",permissionKeys:n}}var Yo=10,Xo=840*60*1e3,Zo="self-config-cache.json";function lt(){return E("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Qo(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Xo}var qo={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function es(e,t=R){let n=qo[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
10
- `)[0]??"").trim();return a||r(o+1)};return r(0)}function ts(e=An()){return w(e,".ev-ai","agent-hook",Zo)}function ns(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
11
- `);return I(n)}function Ee(e,t,n=!1){let r=ns(e),o=e.length;return t===r?n?{hash:r,count:o,truncated:n}:{hash:r,count:o}:n?{hash:r,count:o,entries:e,truncated:n}:{hash:r,count:o,entries:e}}function rs(e){return $o(e)?O(Go(e,"utf8"),{}):{}}function os(e,t){try{B(e,`${JSON.stringify(t)}
12
- `)}catch(n){let r=n instanceof Error?n.message:String(n);m(`WARN: self-config cache write failed open: ${r}`)}}function ss(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}return r&&(o.user_spec_collected_at_ms=r.collectedAtMs,r.included&&(o.user_spec=r.hash,o.user_spec_components=r.componentHashes),o.user_spec_text_hashes=r.textHashes),o}async function kn(e,t=process.cwd(),n=An(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await es(e),a="",c=[];if(o){let b=Tn(w(n,".claude/settings.json")),M=Tn(w(t,".claude/settings.local.json"));a=M.model||b.model,c=[...b.permissionKeys,...M.permissionKeys].slice(0,jo)}let l=Ko[e]??{},u={present:!1,size:0},d=b=>{let M=Array.isArray(b)?b:b?[b]:[],S=[],H=!1;for(let Ae of M){let k=q(w(n,Ae));if(S=S.concat(k.entries),H=H||k.truncated,S.length>=G){S=S.slice(0,G),H=!0;break}}return{entries:S,truncated:H}},g=ts(n),f=rs(g),h=f[e]??{},x=(h.send_count??0)+1,v=x>0&&x%Yo===0,C=b=>v?void 0:h[b],U=d(l.skills),F=l.subagents?q(w(n,l.subagents)):{entries:[],truncated:!1},Te=l.commands?q(w(n,l.commands)):{entries:[],truncated:!1},yt=l.rules?q(w(n,l.rules)):{entries:[],truncated:!1},Z={skills:Ee(U.entries,C("skills"),U.truncated),subagents:Ee(F.entries,C("subagents"),F.truncated),commands:Ee(Te.entries,C("commands"),Te.truncated),rules:Ee(yt.entries,C("rules"),yt.truncated)},A={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:Z.skills,subagents:Z.subagents,commands:Z.commands,rules:Z.rules,memory:l.memory?ee(w(n,l.memory)):u,settings:l.settings?ee(w(n,l.settings)):u,mcp:l.mcp?ee(w(n,l.mcp)):u},local_settings:o?ee(w(t,".claude/settings.local.json")):u},It=null,Rt=()=>{},Ct=r.nowMs??Date.now();if(!lt()&&Qo(h.user_spec_collected_at_ms,Ct)){let b=h.user_spec_collected_at_ms!==void 0,M=nt(e,n),S=rt(M.components,h.user_spec_components,{forceFull:!h.user_spec_components,truncated:M.truncated}),H=new Set(h.user_spec_text_hashes??[]),Ae=ot(M.components,S.upserts,H),k=it(at([...S.upserts,...Ae],H));A.user_spec_hash=S.hash,A.user_spec_count=S.count,A.user_spec_truncated=S.truncated||k.droppedCount>0,(k.components.length>0||S.removed.length>0||S.full)&&(S.full&&(A.user_spec_full=!0),k.components.length>0&&(A.user_spec=k.components),S.removed.length>0&&!A.user_spec_truncated&&(A.user_spec_removed=S.removed),k.textDeferredCount>0&&(A.user_spec_text_deferred=k.textDeferredCount));let ke=S.full?{}:{...h.user_spec_components??{}};if(!A.user_spec_truncated)for(let z of S.removed)delete ke[P(z.path,z.name)];for(let z of k.components)ke[P(z.path,z.name)]=z.content_hash;It={hash:S.hash,componentHashes:ke,textHashes:st(H,k.textHashesSent,M.components),included:k.components.length>0||S.removed.length>0&&!A.user_spec_truncated||S.full,collectedAtMs:Ct};let Oe=await ge({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:b});Oe.operator&&(A.operator=Oe.operator),Rt=Oe.commit}let ur=ss(h,Z,x,It);return{config:A,commit:()=>{f[e]=ur,os(g,f),Rt()}}}function Y(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp:de(),session_id:n.sessionId||null,turn_id:n.turnId||null,installation_id:n.installationId,platform:n.runnerPlatform,platform_agent_id:n.platformAgentId||null,runner_event:n.runnerEvent||null,agent_hook_version:be,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as zn}from"node:fs";import{spawn as Wn}from"node:child_process";import{basename as Ns}from"node:path";import{fileURLToPath as vs}from"node:url";var is=new Set(["localhost","127.0.0.1","[::1]","::1"]),On=/^[A-Za-z0-9._~-]+$/;function xn(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function Se(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?is.has(t.hostname):!1}catch{return!1}}function Un(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Se(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=as(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!On.test(n))return`org token must match ${On.source} (got: ${n})`;if(xn(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(xn(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function bn(e){return new URL(e).toString()}function as(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function dt(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function wn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?le(t):""}var Nn=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,vn=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,cs=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,ls=new Set(["applications","app","bin","boot","data","dev","etc","home","lib","media","mnt","node_modules","opt","pkg","private","proc","projects","repos","run","sbin","src","srv","sys","tmp","usr","users","var","volumes","workspace","workspaces"]),us=new Set(["read","read_file","view"]),ds=new Set(["bash","shell","zsh"]);function ps(e){let t=e.replace(/\\/g,"/");return Nn.exec(t)?.[1]??null}function fs(e){let t=e.replace(/\\/g,"/"),r=vn.exec(t)?.[1];return r?r.toLowerCase():null}function ms(e){return ps(e)??fs(e)}function gs(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Mn(e){if(typeof e=="string")try{let t=JSON.parse(e);return Mn(t)}catch{return null}return!e||typeof e!="object"?null:gs(e)}function _s(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function hs(e){let t=e.replace(/\\/g,"/"),n=Nn.exec(t);if(n?.[1])return n[1];let o=vn.exec(t)?.[1];return o?o.toLowerCase():null}function Es(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Ln(e){let t=Es(e).toLowerCase();if(us.has(t)){let n=Mn(e.tool_input);return n?ms(n):null}if(ds.has(t)){let n=_s(e.tool_input);return n?hs(n):null}return null}function Ss(e){let t=new Set,n=[];for(let r of e.matchAll(cs)){let o=r[1]?.toLowerCase();!o||t.has(o)||ls.has(o)||(t.add(o),n.push(o))}return n}function ys(e){return Q(e.prompt)}function Pn(e){let t=p(e,"command_name");if(t){let r=p(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=ys(e);return n?Ss(n):[]}function pt(e){return e!==void 0&&bt.includes(e)}function ye(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ie(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=ye(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=ye(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=ye(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=ye(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:pt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function ft(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=le(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=Un(n);if(r){m(`WARN: ignoring --url/--token collector override: ${r}`);return}return bn(n)}function Dn(e,t){if(p(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Is(){return!!(E("CURSOR_VERSION")??E("CURSOR_PROJECT_DIR"))}function mt(e,t,n){return e!=="claude"&&e!=="codex"?!1:Dn(t,n)?!0:Is()}function gt(e,t,n,r){if(Dn(e,t))return"cursor";if(pt(r))return r;let o=p(e,"conversation_id"),s=p(e,"turn_id"),i=p(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),pt(n)&&(c=n),c}function Re(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Rs(e){switch(e){case"sessionstart":return"session_start";case"stop":case"sessionend":case"stopfailure":return"session_end";case"pretooluse":case"posttooluse":case"posttoolusefailure":case"permissiondenied":case"beforemcpexecution":case"beforeshellexecution":case"afterfileedit":case"subagentstart":case"subagentstop":return"tool_invoked";case"beforesubmitprompt":case"userpromptexpansion":case"userpromptsubmit":return"skill_invoked";default:return""}}function Hn(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Fn(e,t,n){let r=p(e,"session_id")||p(e,"conversation_id"),o=p(e,"prompt.id")||p(e,"prompt_id")||p(e,"generation_id")||p(e,"turn_id"),s=p(e,"hook_event_name")||p(e,"event"),i=p(e,"source"),a=gt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Cs=["session_start","session_end","tool_invoked","skill_invoked"];function Ts(e){return Cs.includes(e)}function Bn(e,t){return e&&Ts(e)?e:Rs(t.toLowerCase())}function $n(e){let t=p(e,"tool_name")||p(e,"tool")||null,n=e.tool_input,o=(n&&typeof n=="object"?Q(n.skill)||Q(n.skill_name):"")||p(e,"skill_name")||null;return o??=Ln(e),{toolName:t,skillName:o}}var As=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Gn(e){for(let t of["subagent_type","agent_type"]){let n=p(e,t);if(n&&As.test(n))return n}return null}function Kn(e){let t=$(e,"duration_ms");if(typeof t=="number")return t;let n=$(e,"duration");return typeof n=="number"?n:null}var ks="error",Os="interrupted",xs="permission_denied",Us=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function _t(e){return Us.test(e)?e:null}function bs(e){for(let t of["failure_type","error_type"]){let n=_t(p(e,t));if(n)return n}return null}function jn(e,t){return $(e,"is_interrupt")===!0?Os:t.toLowerCase()==="permissiondenied"?xs:bs(e)??ks}function ws(e,t){let n=null;for(let r of t)r&&(e===r||e.startsWith(`${r}_`)||e.startsWith(`${r}-`))&&(n===null||r.length>n.length)&&(n=r);return n}function Vn(e,t=[]){if(!e)return{mcpServer:null,mcpTool:null};let n=/^mcp__(.+?)__(.+)$/i.exec(e);if(n?.[1]&&n[2])return{mcpServer:n[1],mcpTool:n[2]};if(/^MCP:/i.test(e)){let r=e.slice(4);if(!r)return{mcpServer:null,mcpTool:null};let o=r.indexOf(":");return o>0?{mcpServer:r.slice(0,o),mcpTool:r.slice(o+1)||null}:{mcpServer:ws(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var ht="__post",Ce="__work";function Ms(e,t){let n=e.payload,r=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],o=e.correlation&&typeof e.correlation=="object"?Object.keys(e.correlation):[];return JSON.stringify({event:e.event,schema_version:e.schema_version,agent_hook_version:e.agent_hook_version,host_arch:e.host_arch,node_version:e.node_version,build_ms:e.build_ms,body_bytes:t,correlation_keys:o,payload_keys:r})}function Jn(e){switch(e){case"session_start":return At;case"session_end":return kt;case"tool_invoked":case"skill_invoked":return xe;default:return xe}}function Ls(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
13
- ${n}`}function Yn(e,t=[],n=process.execPath,r=import.meta.url,o=zn){if(Ns(n)===ue)return{command:n,args:[e,...t]};let s=vs(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Ps(e=process.execPath,t=import.meta.url,n=zn){return Yn(ht,[],e,t,n)}function Ds(e){let t=e.indexOf(`
14
- `);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function Xn(e,t=fetch){let n=await e(),r=Ds(n);if(!r)return;let{meta:o,body:s}=r,i={"Content-Type":"application/json"};try{await t(o.url,{method:"POST",headers:i,body:s,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function Hs(e,t,n){let r=Jn(e);m(`POST event=${e} url=${dt(n)} size=${t.length} platform=${process.platform}`);let o={"Content-Type":"application/json"},s=Date.now();try{let i=await fetch(n,{method:"POST",headers:o,body:t,signal:AbortSignal.timeout(r)}),a=Date.now()-s;if(i.ok)return m(`POST outcome=ok elapsed_ms=${a} http=${i.status}`),!0;let c=(await i.text()).slice(0,200).replace(/[\n\r]/g,"");return m(`POST outcome=fail elapsed_ms=${a} http=${i.status} body=${c}`),!1}catch(i){let a=Date.now()-s,c=i instanceof Error?i.message:String(i);return m(`POST outcome=fail elapsed_ms=${a} http=000 body=${c}`),!1}}async function Zn(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){m(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},Ot),l=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return m(`WARN: ${o} spawn failed open: ${i}`),null}}async function Fs(e,t,n,r=Wn,o=Ps){let s=Jn(e),i=Ls(n,s,t),{command:a,args:c}=o();return Zn(a,c,i,r,"detached post")}async function Qn(e,t,n=Wn,r=Yn){let{command:o,args:s}=r(Ce,t);return Zn(o,s,e,n,"detached work")}async function X(e,t,n,r,o,s){if(!o)return m("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Se(o))return m(`WARN: collector URL blocked (https required): ${dt(o)}`),!1;let i=r(e,t,n);s!==void 0&&(i.build_ms=Math.max(0,Date.now()-s));let a=`${JSON.stringify(i)}
15
- `,c=E("EV_AI_HOOK_DEBUG");c==="full"?m(`DEBUG envelope=${JSON.stringify(i)}`):c==="1"&&m(`DEBUG summary=${Ms(i,Buffer.byteLength(a,"utf8"))}`);let l=process.argv.includes(Ce),u=E("EV_AI_HOOK_SYNC")==="1";return Re(n.runnerEvent,n.runnerPlatform)||l||u?Hs(e,a,o):(await Fs(e,a,o),!1)}import{relative as Bs,resolve as Et,sep as qn}from"node:path";var $s=["session_id","conversation_id","turn_id","generation_id","prompt.id","prompt_id","hook_event_name","event","source","status","stop_reason","reason","tool_name","tool","tool_use_id","skill_name","command_name","expansion_type","command_source","permission_mode","model","model_id","agent_id","agent_type","subagent_id","subagent_type","subagent_model","is_parallel_worker","effort","effort.level","duration_ms","duration","failure_type","is_interrupt"];function Gs(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:E("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function Ks(e){let t={};for(let n of $s){let r=$(e,n);r!==void 0&&(t[n]=r)}return t}function js(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Et(e),r=Et(t),o=Bs(r,n);return!o||o==="."?".":o.startsWith(`..${qn}`)||o===".."||Et(r,o)!==n?null:o.split(qn).join("/")}function er(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([i,a])=>!i.startsWith("_")&&(typeof a=="string"||typeof a=="number"||typeof a=="boolean")).sort((i,a)=>Buffer.byteLength(JSON.stringify(i[1]),"utf8")-Buffer.byteLength(JSON.stringify(a[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[i,a]of o){let c={...s,[i]:a};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[i]=a}return s}function se(e,t,n={}){let r=n.gitRoot!==void 0?js(e.cwd,n.gitRoot):null;if(Gs(t)){let s={...e};return delete s.cwd,delete s.transcript_path,r!==null&&(s.cwd_relative=r),er(s,Ut)}let o=Ks(e);return r!==null&&(o.cwd_relative=r),er(o,xt)}import{createReadStream as Vs}from"node:fs";import{stat as zs}from"node:fs/promises";import{basename as Ws,resolve as Js}from"node:path";import{createInterface as Ys}from"node:readline";var Xs=1024*1024;function Zs(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Ws(t).endsWith(".jsonl")}async function tr(e){if(!e||!Zs(e))return null;try{let t=Js(e),n=await zs(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Xs),o=[],s=Ys({input:Vs(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let i of s)i.length!==0&&o.push(i);r>0&&o.length>0&&o.shift();for(let i=o.length-1;i>=0;i--){let a=o[i];if(a)try{let c=JSON.parse(a);if(c.type!=="assistant")continue;let l=c.message;if(!l||typeof l!="object")continue;let u=l.model;if(typeof u=="string"&&u.length>0)return u}catch{continue}}return null}catch{return null}}function ae(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function Qs(...e){for(let t of e)if(t)return t;return null}function N(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return m(`WARN: ${n} failed open: ${r}`),t}function qs(e){let t={present:!1,size:0},n={hash:"",count:0};return{config:{runner_platform:e,config_scope:"user",cli_version:null,claude_version:null,model:null,permission_keys:[],user_scope:{skills:n,subagents:n,commands:n,rules:n,memory:t,settings:t,mcp:t},local_settings:t},commit:()=>{}}}function ei(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var V=new Set,ie=null;async function nr(e){if(lt())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(V.has(t))return;if(!Xe(n)){V.add(t);return}let r=Fe();if(cn(r)){if(ie){await ie;return}ie=(async()=>{if(V.has(t)||!Xe(n)){V.add(t);return}if(!Zt(n)){V.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,d,g]=await Promise.allSettled([ne(i),Be(),Ke(r),$e(),ge({gitRoot:i,installationStorePath:n,forceResend:!1})]),f=N(c,null,"gitSnapshot"),h=N(l,"","detectVirt"),x=N(u,null,"probeCloud"),v=N(d,{},"hostEnv"),C=N(g,{commit:()=>{}},"resolveOperatorForSend");await ce(e,i,f);let U={identity:{host:Ge(),context:r,virt:h||null,cloud:x,git:f},host_env:v,env_vars:We(),self_config:ei(a,C.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await X("session_start",U,ae(e),Y,e.manifest.collectorUrl,s),o&&(C.commit(),V.add(t))}finally{Qt(n)}})().finally(()=>{ie=null}),await ie}}async function ce(e,t,n){try{let r=n===void 0?await ne(t):n;e.platformAgentId=await rn(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);m(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function ti(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Fe(),o=String(e.runnerPlatform),[s,i,a,c,l,u]=await Promise.allSettled([ne(n),Be(),Ke(r),$e(),ze(e.manifest.manifest,n,o),kn(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),d=N(s,null,"gitSnapshot"),g=N(i,"","detectVirt"),f=N(a,null,"probeCloud"),h=N(c,{},"hostEnv"),x=N(l,[],"mcpDeclared"),v=N(u,qs(o),"selfConfig"),C=v.config;await ce(e,n,d);let U=p(e.hookInput,"model");U&&(C.model=U);let F={identity:{host:Ge(),context:r,virt:g||null,cloud:f,git:d},host_env:h,env_vars:We(),mcp:{declared:x},self_config:C,run_meta:{trigger:e.hookSource||"startup"},hook_input:se(e.hookInput,e.manifest.manifest,{gitRoot:n})};await X("session_start",F,ae(e),Y,e.manifest.collectorUrl,t)&&(v.commit(),V.add(e.manifest.installationId))}async function ni(e){let t=Date.now(),{gitRoot:n}=e.manifest;await ce(e,n);let r=Qs(p(e.hookInput,"status"),p(e.hookInput,"stop_reason"),p(e.hookInput,"reason"),_t(p(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await tr(p(e.hookInput,"transcript_path")):null,s=se(e.hookInput,e.manifest.manifest,{gitRoot:n});o&&(s.model=o),await X("session_end",{status:r,...o?{model:o}:{},hook_input:s},ae(e),Y,e.manifest.collectorUrl,t)}async function ri(e){let t=Date.now(),n=Pn(e.hookInput);if(n.length===0)return;await nr(e);let{gitRoot:r}=e.manifest;await ce(e,r);let o=se(e.hookInput,e.manifest.manifest,{gitRoot:r}),s=ae(e);await Promise.all(n.map(i=>X("tool_invoked",{tool_name:"Skill",skill_name:i,success:null,duration_ms:null,hook_input:o},s,Y,e.manifest.collectorUrl,t)))}async function oi(e){let t=Date.now();await nr(e);let{gitRoot:n}=e.manifest;await ce(e,n);let{toolName:r,skillName:o}=$n(e.hookInput),s=Kn(e.hookInput),i=Hn(e.runnerEvent),a=i===!1?jn(e.hookInput,e.runnerEvent):null,c=await ze(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=Vn(r,c.map(g=>g.name)),d=Gn(e.hookInput);await X("tool_invoked",{tool_name:r,skill_name:o,success:i,duration_ms:s,...a?{failure_reason:a}:{},...l?{mcp_server:l}:{},...u?{mcp_tool:u}:{},...d?{subagent_type:d}:{},hook_input:se(e.hookInput,e.manifest.manifest,{gitRoot:n})},ae(e),Y,e.manifest.collectorUrl,t)}async function rr(e){switch(e.internalEvent){case"session_start":await ti(e);return;case"session_end":await ni(e);return;case"skill_invoked":await ri(e);return;case"tool_invoked":await oi(e);return;default:return}}function or(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{existsSync as St,readFileSync as si}from"node:fs";import{dirname as ii,join as sr,relative as ai}from"node:path";var ir=[Tt,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function ci(e=process.cwd(),t){let n=E("EV_AI_HOOK_MANIFEST");if(n&&St(n))return n;let r=t??await pe(e);for(let o of ir){let s=sr(r,o);if(St(s))return s}for(let o of ir){let s=sr(e,o);if(St(s))return s}}async function li(e,t){let n=t??await pe(ii(e)),r=ai(n,e),o=await L("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(m(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function ui(e){let t=si(e,"utf8");return O(t,{})}function di(){return{schema_version:2,mcp_servers:[]}}async function ar(e=process.cwd()){let t=await pe(e),n=await ci(e,t),r=n?ui(n):di();delete r.installation_id;let o=n?await li(n,t):!1;r.capture_hook_input==="full"&&n&&o&&(m(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${n}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete r.capture_hook_input);let{installationId:s,storePath:i,repoKey:a}=await nn(t);return{manifestPath:n??i,manifest:r,installationId:s,installationStorePath:i,repoKey:a,collectorUrl:wn(r),platformAgentId:r.platform_agent_id??"",gitRoot:t}}async function cr(e,t,n,r){let o=t??await ve(Ue),s=O(o,{}),i=await ar();if(!i)return;r&&(i.collectorUrl=r);let a=Fn(s,i.manifest.platform,n),c=Bn(e,a.runnerEvent);if(!c){m(`WARN: unknown hook event '${a.runnerEvent}'; skipping telemetry`);return}let l={hookInput:s,sessionId:a.sessionId,turnId:a.turnId,runnerEvent:a.runnerEvent,runnerPlatform:a.runnerPlatform,hookSource:a.hookSource,internalEvent:c,manifest:i,platformAgentId:i.platformAgentId};if(or(c)){m(`WARN: unsupported internal event '${c}'`);return}await rr(l)}function pi(e,t){if(E("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ie(e),r=O(t,{}),o=n.event??(p(r,"hook_event_name")||p(r,"event")),s=gt(r,o,void 0,n.runner);return Re(o,s)}async function lr(e=process.argv.slice(2)){if(e[0]===ht){try{await Xn(Ne)}catch{}return 0}if(e[0]===Ce){try{let t=Ie(e.slice(1)),n=await Ne(),r=O(n,{}),o=t.event??(p(r,"hook_event_name")||p(r,"event"));if(mt(t.runner,r,o))return 0;await cr(t.event,n,t.runner,ft(t))}catch(t){let n=t instanceof Error?t.message:String(t);m(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await ve(Ue),n=Ie(e),r=ft(n),o=O(t,{}),s=n.event??(p(o,"hook_event_name")||p(o,"event"));if(mt(n.runner,o,s))return 0;pi(e,t)?await cr(n.event,t,n.runner,r):await Qn(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);m(`WARN: hook failed open: ${n}`)}finally{Dt()}return 0}lr().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ const require = __createRequire(import.meta.url);
3
+
4
+ var mo=Object.create;var Yt=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var _o=Object.getOwnPropertyNames;var ho=Object.getPrototypeOf,Eo=Object.prototype.hasOwnProperty;var Xt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var So=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Ro=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _o(t))!Eo.call(e,o)&&o!==n&&Yt(e,o,{get:()=>t[o],enumerable:!(r=go(t,o))||r.enumerable});return e};var Io=(e,t,n)=>(n=e!=null?mo(ho(e)):{},Ro(t||!e||!e.__esModule?Yt(n,"default",{value:e,enumerable:!0}):n,e));var lr=So(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.ComponentKind=void 0;L.userConfigRootFromPath=fi;L.installationRootExternalKey=pi;L.normalizeRepositoryRelativePath=ar;L.nativeKeyForSkillPath=mi;L.serializeComponentIdentity=cr;L.buildComponentReference=_i;L.validateComponentReference=hi;var si=Xt("node:crypto"),ii=Xt("node:path"),ai="cmp1_",ci=/^cmp1_[A-Za-z0-9_-]{43}$/,li=["/skills/","/skills-cursor/"],ui=[".cursor",".claude",".codex"],di={".claude.json":".claude",".agents":".codex"};L.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE"};function fi(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>ui.includes(o));return n||(t.map(o=>di[o]).find(o=>o!==void 0)??"unknown")}function pi(e,t){return`runtime-install:${e}/${t}`}function we(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function ar(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=ii.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return we(n,"sourcePath")}function mi(e){let t=e.replaceAll("\\","/");for(let n of li){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function gi(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function cr(e){let t=[we(e.installationRootExternalKey,"installationRootExternalKey"),we(e.installableKind,"installableKind"),ar(e.sourcePath),we(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(gi).join("|")}`,"utf8")}function _i(e){let t=(0,si.createHash)("sha256").update(cr(e)).digest("base64url");return`${ai}${t}`}function hi(e){return ci.test(e)}});import{existsSync as vo,readFileSync as wo}from"node:fs";import{hostname as rn,userInfo as bo}from"node:os";import{randomBytes as yo}from"node:crypto";import{existsSync as Je,mkdirSync as Co,readdirSync as Ao,readFileSync as To,renameSync as Zt,statSync as en,unlinkSync as qt,writeFileSync as Oo}from"node:fs";import{basename as ko,dirname as Qt,join as tn,relative as xo}from"node:path";function _(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
5
+ `)}function G(e,t){Co(Qt(e),{recursive:!0});let n=tn(Qt(e),`.${ko(e)}.${process.pid}.${yo(4).toString("hex")}.tmp`);try{Oo(n,t,"utf8");try{Zt(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){qt(e),Zt(n,e);return}throw r}}catch(r){try{qt(n)}catch{}throw r}}function Ie(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function nn(){process.stdout.write('{"continue":true}')}function A(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Ye(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function Xe(e){return new Promise(t=>{let n="",r=!1,o=a=>{r||(r=!0,clearTimeout(s),t(a||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",a=>{n+=a}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function P(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),a=s(o);try{let{stdout:i}=await a(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:i.trim()}}catch(i){let c=i,l=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:l,spawnFailed:l===void 0}}}async function T(e,t,n=3e3,r={}){let o=await P(e,t,n,r);return o.ok?o.stdout:""}async function Ze(e=process.cwd()){let t=await P("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(A("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;_(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=A("CURSOR_PROJECT_DIR")??A("CLAUDE_PROJECT_DIR");if(n&&Je(n)){let r=await P("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function qe(e=process.cwd()){return(await Ze(e)).root}function b(e,t){try{return JSON.parse(e)}catch{return t}}var We=new Map;function q(e,t){let n=We.get(e);if(n!==void 0)return n;try{let r=b(To(e,"utf8"),t);return We.set(e,r),r}catch{return We.set(e,t),t}}function z(e){return typeof e=="string"?e:""}function V(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function p(e,t){let n=V(e,t);return typeof n=="string"?n:""}var H=500;function ie(e,t=2){if(!Je(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,a)=>{if(a>t||r)return;let i;try{i=Ao(s,{withFileTypes:!0})}catch{return}for(let c of i){if(r)return;let l=tn(s,c.name);if(c.isDirectory()){o(l,a+1);continue}if(c.isFile()){try{n.push({name:xo(e,l),size:en(l).size})}catch{continue}if(n.length>=H){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function ae(e){return Je(e)?{present:!0,size:en(e).size}:{present:!1,size:0}}function Q(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Qe(e=process.env){return Q(y("CURSOR_SANDBOX",e))}var No=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Uo(e){return No.some(t=>!!y(t,e))}function Po(e){if(y("KUBERNETES_SERVICE_HOST",e)||Q(y("REMOTE_CONTAINERS",e))||Q(y("DEVCONTAINER",e)))return!0;try{if(vo("/.dockerenv")||wo("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function on(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!y(t,e))}function Lo(e,t=process.platform){return on(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!y(n,e)):!1}function Mo(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Do(e){return e==="linux"}function y(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return A(e)}function Ho(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Fo(y("CURSOR_VERSION",n))}function Fo(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function et(e){if(Mo(e.sessionId))return!0;let t=e.hostname??rn(),n=e.osUser??sn(e.env);return Ho(t,n,e.env)}function $o(e){return Q(y("CURSOR_AGENT",e.env))?!0:et(e)}function Bo(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(y("TERM",e)??y("TERM_PROGRAM",e))||(y("SSH_TTY",e)??y("SSH_CONNECTION",e))||(y("__CFBundleIdentifier",e)??y("XPC_SERVICE_NAME",e))||on(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!y(t,e))||y("SESSIONNAME",e))}function ce(e={}){let t=e.env;if(y("GITHUB_ACTIONS",t))return"github_actions";if(Q(y("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Lo(t,n)&&$o(e)&&(Q(y("CURSOR_AGENT",t))||Do(n)))return"cursor_cloud";if(y("CODESPACES",t)||y("CODESPACE_NAME",t))return"codespaces";if(y("GITLAB_CI",t))return"gitlab_ci";if(Uo(t))return"managed";let r=y("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Po(t)?"container":Bo(t)?"interactive":"unknown"}async function tt(){return await T("systemd-detect-virt",[],1e3)}function sn(e=process.env,t=bo){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function nt(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await T("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),a=s("/etc/os-release","utf8"),i=a.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=a.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=i??c??""}catch{t=await T("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await T("uname",["-r"],1e3))}else t=await T("ver",[],1e3);let n=sn(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await T("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function le(){return rn()}var Ko="https://hooks.ev-ai.ai";function ye(e,t=Ko){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var an=".claude/ev-ai-runtime-report.json";var Ce="ev-ai-agent-hook";var Xc=`current/${Ce}`,Zc=`.ev-ai/agent-hook/${Ce}`,cn=5e3,ln=5e3,rt=3e3;var ot=3e3,un=1500,dn=4*1024,fn=32*1024,Go=4*1024,st="1.0.9",qc=`@ev-ai/agent-hook@${st}`;var pn=["claude","cursor","codex"];import{createHash as $s}from"node:crypto";import{existsSync as Bs,mkdirSync as Ks,readdirSync as Gs,readFileSync as Qn,unlinkSync as er,writeFileSync as js}from"node:fs";import{homedir as tr}from"node:os";import{join as _t}from"node:path";import{createHash as En,randomBytes as Vo}from"node:crypto";import{existsSync as Sn,mkdirSync as it,readFileSync as Rn,unlinkSync as In,writeFileSync as yn}from"node:fs";import{homedir as at}from"node:os";import{dirname as Ae,join as ct,resolve as Wo}from"node:path";var jo=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),zo=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function W(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||zo.has(n)||r.includes("[bot]")||jo.has(r))return!0;if(r.endsWith("@users.noreply.github.com")){let o=r.slice(0,r.indexOf("@")),s=o.includes("+")?o.slice(o.indexOf("+")+1):o;if(s.endsWith("bot")||s.includes("[bot]"))return!0}return!1}var Jo="installation.json",Yo="cloud-bootstrap.lock",Xo=6e4;function Cn(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function ue(e=at()){return ct(e,".ev-ai","agent-hook")}function Zo(e=at()){return ct(ue(e),Jo)}function An(e){return ct(Ae(e),Yo)}function Tn(){return Vo(8).toString("hex")}function ee(e){return En("sha256").update(e).digest("hex").slice(0,16)}function S(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function On(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function qo(e=process.env){let t=S(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!On(t)){_(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function kn(e,t){return e&&On(e)?e:(e&&_(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),qo(t))}function Qo(e){return/^[0-9a-f]{16}$/.test(e)}function es(e=process.env){if(S(e.GITHUB_ACTIONS)){let t=S(e.GITHUB_REPOSITORY_ID)??S(e.GITHUB_REPOSITORY),n=S(e.GITHUB_ACTOR)??S(e.GITHUB_TRIGGERING_ACTOR)??S(e.GITHUB_USER);if(t&&n)return ee(`github_actions|${t}|${n}`)}if(S(e.CODESPACES)||S(e.CODESPACE_NAME)){let t=S(e.CODESPACE_NAME);if(t)return ee(`codespaces|${t}`);let n=S(e.GITHUB_REPOSITORY_ID)??S(e.GITHUB_REPOSITORY),r=S(e.GITHUB_USER)??S(e.GITHUB_ACTOR);if(n&&r)return ee(`codespaces|${n}|${r}`)}if(S(e.GITLAB_CI)){let t=S(e.CI_PROJECT_ID)??S(e.CI_PROJECT_PATH),n=S(e.GITLAB_USER_LOGIN)??S(e.GITLAB_USER_EMAIL)??S(e.GITLAB_USER_NAME);if(t&&n)return ee(`gitlab|${t}|${n}`)}return null}var ts="cursoragent@cursor.com";function ns(e){let t=S(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===ts?null:t}function rs(e,t){return S(e.CURSOR_PROJECT_DIR)??S(e.CLAUDE_PROJECT_DIR)??t}function os(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function ss(e){let t=await T("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?os(t):e}async function is(e){let t=S(await T("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!W(null,t))return t;let n=S(await T("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!W(null,n)?n:null}function as(e,t){let n=rs(e,t);return n?ee(`cursor_cloud|${n}|${ns(e)??""}`):null}async function cs(e,t){let n=S(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await ss(n),o=await is(n);return ee(`claude_remote|${r}|${o??""}`)}function mn(e,t){let n=kn(e,t);if(n)return n;let r=es(t);return r||Tn()}async function ls(e){let n=await T("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Wo(e);return En("sha256").update(n).digest("hex").slice(0,16)}function us(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&r.length>0&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function ds(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=us(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function J(e){if(Sn(e))try{return ds(Rn(e,"utf8"))}catch{}}function lt(e){return J(e)}function xn(e,t,n){let r=J(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{G(e,`${JSON.stringify(o,null,2)}
6
+ `)}catch(s){let a=s instanceof Error?s.message:String(s);_(`WARN: operator identity cache write failed open: ${a}`)}}function vn(e,t=Date.now()){if(!e)return!0;if(J(e)?.operator_identity_hash)return!1;let n=An(e);try{if(Sn(n)){let r=Number.NaN;try{r=Number(Rn(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Xo)return!1;try{In(n)}catch{}}}catch{}try{return it(Ae(n),{recursive:!0}),yn(n,`${t}
7
+ `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(Un(r))return!1;let o=r instanceof Error?r.message:String(r);return _(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function wn(e){if(e)try{In(An(e))}catch{}}function bn(e,t){let r=J(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Nn(e,t,n){if(!n)return;let r=J(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{G(e,`${JSON.stringify(o,null,2)}
8
+ `)}catch(s){let a=s instanceof Error?s.message:String(s);_(`WARN: platform_agent_id cache write failed open: ${a}`)}}function Un(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function fs(e,t){it(Ae(e),{recursive:!0}),yn(e,`${JSON.stringify(t,null,2)}
9
+ `,{encoding:"utf8",flag:"wx"})}function gn(e,t){try{return fs(e,t),t}catch(n){if(!Un(n))throw n;return J(e)}}function _n(e,t){it(Ae(e),{recursive:!0}),G(e,`${JSON.stringify(t,null,2)}
10
+ `)}function hn(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Pn(e,t={}){let n=t.home??at(),r=t.env??process.env,o=await ls(e),s=Zo(n),a={sessionId:t.sessionId,hostname:S(r.HOSTNAME)??void 0,osUser:S(r.USER)??S(r.LOGNAME)??S(r.USERNAME)??void 0,env:r},i=ce(a),c=kn(t.overrideId,r),l=i==="cursor_cloud"&&et(a)?as(r,e):i==="claude_remote"?await cs(r,e):null,u=J(s);if(u){let E=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(E={...u,pinned:!0},_n(s,E)),!!l&&l!==E.installation_id&&!c&&E.pinned!==!0&&Qo(E.installation_id)&&l){let I={installation_id:l,...E.platform_agent_ids?{platform_agent_ids:E.platform_agent_ids}:{}};return _n(s,I),{installationId:l,storePath:s,repoKey:o}}return{installationId:E.installation_id,storePath:s,repoKey:o}}let d=c??l??mn(void 0,r),m=gn(s,hn(d,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let f=c??l??mn(void 0,r),g=gn(s,hn(f===d?Tn():f,c));if(g)return{installationId:g.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}var ps=new Set(["localhost","127.0.0.1","[::1]","::1"]),Ln=/^[A-Za-z0-9._~-]+$/;function Mn(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function Te(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?ps.has(t.hostname):!1}catch{return!1}}function Dn(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Te(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=ms(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Ln.test(n))return`org token must match ${Ln.source} (got: ${n})`;if(Mn(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Mn(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Hn(e){return new URL(e).toString()}function ms(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function ut(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function Fn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?ye(t):""}var $n=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,Bn=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,gs=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,_s=new Set(["applications","app","bin","boot","data","dev","etc","home","lib","media","mnt","node_modules","opt","pkg","private","proc","projects","repos","run","sbin","src","srv","sys","tmp","usr","users","var","volumes","workspace","workspaces"]),hs=new Set(["read","read_file","view"]),Es=new Set(["bash","shell","zsh"]);function Ss(e){let t=e.replace(/\\/g,"/");return $n.exec(t)?.[1]??null}function Rs(e){let t=e.replace(/\\/g,"/"),r=Bn.exec(t)?.[1];return r?r.toLowerCase():null}function dt(e){return Ss(e)??Rs(e)}function Is(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Oe(e){if(typeof e=="string")try{let t=JSON.parse(e);return Oe(t)}catch{return null}return!e||typeof e!="object"?null:Is(e)}function ys(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Cs(e){let t=e.replace(/\\/g,"/"),n=$n.exec(t);if(n?.[1])return n[1];let o=Bn.exec(t)?.[1];return o?o.toLowerCase():null}function As(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Kn(e){let t=As(e).toLowerCase();if(hs.has(t)){let n=Oe(e.tool_input)??z(e.file_path),r=n?dt(n):null;if(r)return r}if(Es.has(t)){let n=ys(e.tool_input)??z(e.command);return n?Cs(n):null}return null}function Ts(e){let t=new Set,n=[];for(let r of e.matchAll(gs)){let o=r[1]?.toLowerCase();!o||t.has(o)||_s.has(o)||(t.add(o),n.push(o))}return n}function Os(e){return z(e.prompt)}function Gn(e){let t=p(e,"command_name");if(t){let r=p(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Os(e);return n?Ts(n):[]}function ft(e){return e!==void 0&&pn.includes(e)}function ke(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function xe(e){let t,n,r,o,s;for(let a=0;a<e.length;a++){let i=e[a];if(i!==void 0){if(i==="--runner"){let c=ke(e,a);t=c.value,a=c.next;continue}if(i.startsWith("--runner=")){t=i.slice(9);continue}if(i==="--url"){let c=ke(e,a);c.value&&(r=c.value),a=c.next;continue}if(i.startsWith("--url=")){r=i.slice(6);continue}if(i==="--token"){let c=ke(e,a);c.value&&(o=c.value),a=c.next;continue}if(i.startsWith("--token=")){o=i.slice(8);continue}if(i==="--base-url"){let c=ke(e,a);c.value&&(s=c.value),a=c.next;continue}if(i.startsWith("--base-url=")){s=i.slice(11);continue}!i.startsWith("-")&&n===void 0&&(n=i)}}return{runner:ft(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function pt(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=ye(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=Dn(n);if(r){_(`WARN: ignoring --url/--token collector override: ${r}`);return}return Hn(n)}function jn(e,t){if(p(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function ks(){return!!(A("CURSOR_VERSION")??A("CURSOR_PROJECT_DIR"))}function mt(e,t,n){return e!=="claude"&&e!=="codex"?!1:jn(t,n)?!0:ks()}function de(e,t,n,r){if(jn(e,t))return"cursor";if(ft(r))return r;let o=p(e,"conversation_id"),s=p(e,"turn_id"),a=p(e,"session_id"),i=t.toLowerCase(),c="unknown";return o||t===i&&t!==""?c="cursor":s?c="codex":(a||i==="sessionstart"||i==="sessionend"||i==="stop"||i==="stopfailure"||i==="pretooluse"||i==="posttooluse"||i==="posttoolusefailure"||i==="permissiondenied"||i==="subagentstart"||i==="subagentstop"||i==="userpromptexpansion")&&(c="claude"),ft(n)&&(c=n),c}function ve(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function xs(e){switch(e){case"sessionstart":return"session_start";case"stop":case"sessionend":case"stopfailure":return"session_end";case"pretooluse":case"posttooluse":case"posttoolusefailure":case"permissiondenied":case"beforemcpexecution":case"beforeshellexecution":case"aftershellexecution":case"beforereadfile":case"afterfileedit":case"subagentstart":case"subagentstop":return"tool_invoked";case"beforesubmitprompt":case"userpromptexpansion":case"userpromptsubmit":return"skill_invoked";default:return""}}function zn(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Vn(e,t,n){let r=p(e,"session_id")||p(e,"conversation_id"),o=p(e,"prompt.id")||p(e,"prompt_id")||p(e,"generation_id")||p(e,"turn_id"),s=p(e,"hook_event_name")||p(e,"event"),a=p(e,"source"),i=de(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:a,runnerPlatform:i}}var vs=["session_start","session_end","tool_invoked","skill_invoked"];function ws(e){return vs.includes(e)}function Wn(e,t){return e&&ws(e)?e:xs(t.toLowerCase())}var bs={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Ns(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Jn(e,t=""){let n=p(e,"tool_name")||p(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Ns(n)&&(n=`MCP:${n}`):n=bs[r]??null;let o=e.tool_input,a=(o&&typeof o=="object"?z(o.skill)||z(o.skill_name):"")||p(e,"skill_name")||null,i=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;return a??=Kn(i),{toolName:n,skillName:a}}var Us=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Yn(e){for(let t of["subagent_type","agent_type"]){let n=p(e,t);if(n&&Us.test(n))return n}return null}function Xn(e){let t=V(e,"duration_ms");if(typeof t=="number")return t;let n=V(e,"duration");return typeof n=="number"?n:null}var Ps="error",Ls="interrupted",Ms="permission_denied",Ds=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function gt(e){return Ds.test(e)?e:null}function Hs(e){for(let t of["failure_type","error_type"]){let n=gt(p(e,t));if(n)return n}return null}function Zn(e,t){return V(e,"is_interrupt")===!0?Ls:t.toLowerCase()==="permissiondenied"?Ms:Hs(e)??Ps}function Fs(e,t){let n=null;for(let r of t)r&&(e===r||e.startsWith(`${r}_`)||e.startsWith(`${r}-`))&&(n===null||r.length>n.length)&&(n=r);return n}function qn(e,t=[]){if(!e)return{mcpServer:null,mcpTool:null};let n=/^mcp__(.+?)__(.+)$/i.exec(e);if(n?.[1]&&n[2])return{mcpServer:n[1],mcpTool:n[2]};if(/^MCP:/i.test(e)){let r=e.slice(4);if(!r)return{mcpServer:null,mcpTool:null};let o=r.indexOf(":");if(o>0)return{mcpServer:r.slice(0,o),mcpTool:r.slice(o+1)||null};let s=r.indexOf("__");return s>0?{mcpServer:r.slice(0,s),mcpTool:r.slice(s+2)||null}:{mcpServer:Fs(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var nr=3e4,zs="claims",Vs=!0,Ws=100,Js=new Set(["sessionstart","sessionend","stopfailure"]),Ys=["tool_name","tool","command","file_path","url"];function Xs(e=tr()){return _t(ue(e),zs)}function rr(e){let t=e.split(`
11
+ `,1)[0]??"";return Number(t.trim())}function or(e){return $s("sha256").update(e).digest("hex").slice(0,32)}function Zs(e){let t=[];for(let n of Ys){let r=p(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":or(t.join("\0"))}function qs(e){let t=e.sessionId.trim();if(!t)return;let n=e.runnerEvent.trim().toLowerCase(),r=e.turnId.trim(),o=e.toolUseId.trim(),s=e.subagentId?.trim()??"",a=e.callFingerprint?.trim()??"",i=!!(o||r||s),c=Js.has(n);if(!i&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return or(`${l}|${t}|${n}|${r}|${o}|${a}|${s}`)}function Qs(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function ei(e,t){return _t(e,t)}function ti(e,t=Date.now()){let n;try{n=Gs(e)}catch{return}let r=0;for(let o of n){if(r>=Ws)break;r+=1;let s=_t(e,o),a=Number.NaN;try{a=rr(Qn(s,"utf8"))}catch{continue}let i=t-a;if(!(!Number.isFinite(i)||i<0||i<nr))try{er(s)}catch{}}}function ni(e,t,n=Date.now()){let r=ei(t,e);try{if(Bs(r)){let o=Number.NaN;try{o=rr(Qn(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<nr)return!1;try{er(r)}catch{}}}catch{}try{Ks(t,{recursive:!0}),js(r,`${n}
12
+ `,{encoding:"utf8",flag:"wx"})}catch(o){if(Qs(o))return!1;let s=o instanceof Error?o.message:String(o);return _(`WARN: event claim failed open: ${s}`),!0}return ti(t,n),!0}function ri(e,t,n){let r=p(e,"session_id")||p(e,"conversation_id"),o=p(e,"prompt.id")||p(e,"prompt_id")||p(e,"generation_id")||p(e,"turn_id"),s=p(e,"tool_use_id"),a=p(e,"subagent_id")||p(e,"agent_id"),i=de(e,t,void 0,n),c=Zs(e);return{runnerPlatform:i,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:a,callFingerprint:c}}function sr(e,t,n,r=tr(),o=Date.now()){if(!Vs)return!0;let s=qs(ri(e,t,n));if(!s)return!0;let a=ni(s,Xs(r),o);return!a&&A("EV_AI_HOOK_DEBUG")&&_(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),a}import{homedir as Cc}from"node:os";var ht={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function fe(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function oi(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return fe(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return fe(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?fe(o[1]):fe(t)}async function pe(e=process.cwd()){let t=await P("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([P("git",["remote","get-url","origin"],2e3,{cwd:e}),P("git",["branch","--show-current"],2e3,{cwd:e}),P("git",["rev-parse","HEAD"],2e3,{cwd:e}),P("git",["status","--porcelain"],2e3,{cwd:e})]),a=n.ok?n.stdout:null;return{remote:a===null?null:a.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function ir(e,t,n,r=process.cwd(),o,s,a){if(t)return t;let i=ht[n];if(!i)return"";let c=Cn(n,e.scope_path,a);if(s){let g=bn(s,c);if(g)return g}let l=o??await pe(r),u=l?.remote?oi(l.remote):"";if(u||(u=fe(process.env.GITHUB_REPOSITORY??"")),!u)return"";let d=e.scope_path??"",m=d?`${d}/`:"",f=`${u}:${m}${i}`;return s&&Nn(s,c,f),f}var k=Io(lr(),1);import{existsSync as Ei,readFileSync as Si}from"node:fs";import{homedir as ur}from"node:os";import{join as Ri}from"node:path";var Ii="cloud-cache.json",yi=1440*60*1e3,Ci=900*1e3;function Ai(e=ur()){return Ri(ue(e),Ii)}function Ti(e){if(!Ei(e))return;let t=b(Si(e,"utf8"),{});if(!(typeof t.context!="string"||typeof t.probed_at!="number"||t.result!==null&&t.result!==void 0&&typeof t.result!="object"))return{context:t.context,probed_at:t.probed_at,result:t.result??null}}function Oi(e,t){try{G(e,`${JSON.stringify(t)}
13
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);_(`WARN: cloud cache write failed open: ${r}`)}}function ki(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Ci:yi;return n-e.probed_at<r}async function xi(e){let t=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=(await t.text()).trim();if(!n)return;let r={"X-aws-ec2-metadata-token":n},[o,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!o?.ok&&!s?.ok)return;let a=o?.ok?(await o.text()).trim():"",i=s?.ok?(await s.text()).trim():"";if(!(!a&&!i))return{provider:"aws",region:a,instance_id:i}}async function vi(e){let t=await fetch("http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true",{headers:{"Metadata-Flavor":"Google"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=typeof n.zone=="string"?n.zone.split("/").pop()??"":"",o=n.id===void 0?"":String(n.id);if(!(!r&&!o))return{provider:"gcp",region:r,instance_id:o}}async function wi(e){let t=await fetch("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{headers:{Metadata:"true"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=await t.json(),r=n.compute?.location??"",o=n.compute?.vmId??"";if(!(!r&&!o))return{provider:"azure",region:r,instance_id:o}}async function bi(e){let t=await Promise.allSettled([xi(e),vi(e),wi(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Et(e,t){if(e==="interactive")return null;let n=t?.home??ur(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Ai(n),a=Ti(s);if(ki(a,e,o))return a.result;let i=await bi(r);return Oi(s,{context:e,probed_at:o,result:i}),i}import{existsSync as Ni}from"node:fs";import{homedir as Ui}from"node:os";import{join as be}from"node:path";function Ne(e,t,n){if(!Ni(e))return;let r=q(e,{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,...t})}async function St(e,t=process.cwd(),n="claude",r=Ui()){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{name:s.name,source:"manifest"});return n==="claude"?Ne(be(r,".claude.json"),{source:"claude_json_user"},o):n==="cursor"&&Ne(be(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Ne(be(t,".mcp.json"),{source:"mcp_json"},o),Ne(be(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),[...o.values()]}var Pi=["CI","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER","KUBERNETES_SERVICE_HOST","REMOTE_CONTAINERS","DEVCONTAINER","GITHUB_REPOSITORY","GITHUB_REPOSITORY_ID","GITHUB_REF","GITHUB_SHA","GITHUB_RUN_ID","GITHUB_WORKFLOW","GITHUB_ACTOR","GITHUB_TRIGGERING_ACTOR","GITHUB_ACTOR_ID","GITHUB_USER","GITLAB_USER_LOGIN","GITLAB_USER_NAME","GITLAB_USER_EMAIL","BUILD_REQUESTEDFOR","BUILD_REQUESTEDFOREMAIL","BUILD_REQUESTEDFORID","BUILDKITE_BUILD_CREATOR","BUILDKITE_BUILD_CREATOR_EMAIL","BUILD_USER","BUILD_USER_ID","BUILD_USER_EMAIL","CHANGE_AUTHOR","CHANGE_AUTHOR_EMAIL","CIRCLE_USERNAME","CODEBUILD_INITIATOR","DRONE_COMMIT_AUTHOR","DRONE_COMMIT_AUTHOR_NAME","DRONE_COMMIT_AUTHOR_EMAIL","EV_AI_HOOK_OPERATOR_NAME","EV_AI_HOOK_OPERATOR_EMAIL","EV_AI_HOOK_OPERATOR_LOGIN","GIT_AUTHOR_NAME","GIT_AUTHOR_EMAIL","GIT_COMMITTER_NAME","GIT_COMMITTER_EMAIL","EMAIL","RUNNER_OS","RUNNER_ARCH","NODE_ENV","TERM_PROGRAM","CLAUDE_CODE_REMOTE","CLAUDE_CODE_REMOTE_SESSION_ID","CURSOR_AGENT","CURSOR_VERSION","CURSOR_CODE_REMOTE","CURSOR_USER_EMAIL","CODESPACES","CODESPACE_NAME","ANTHROPIC_BASE_URL","OPENAI_BASE_URL","OPENAI_API_BASE","AZURE_OPENAI_ENDPOINT","GOOGLE_GEMINI_BASE_URL","GEMINI_API_BASE","CLAUDE_CODE_USE_BEDROCK","CLAUDE_CODE_USE_VERTEX"],Li=["CURSOR_PROJECT_DIR"],Mi=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Di(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Mi.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Rt(e=process.env){let t=Pi.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Di(e[r]??"")}:{name:r,present:!1}),n=Li.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{createHash as Hi}from"node:crypto";function O(e){return Hi("sha256").update(e).digest("hex").slice(0,16)}function $(e,t){return`${e}\0${t}`}function dr(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function It(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
14
+ `);return O(n)}function Fi(e,t,n="git_config",r=null){return O(`${e??""}|${t??""}|${r??""}|${n}`)}function $i(e){let t=null,n=null;for(let r of e.split(`
15
+ `)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let a=o.slice(0,s).toLowerCase(),i=o.slice(s+1).trim();i&&(a==="user.name"?t=i:a==="user.email"&&(n=i))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function Bi(e,t=T){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return $i(n)}function Ki(e=process.env){let t=h(e.GIT_AUTHOR_NAME),n=h(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=h(e.GIT_COMMITTER_NAME),o=h(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=h(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function B(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function Gi(e=process.env){let t=B(h(e.EV_AI_HOOK_OPERATOR_NAME),h(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured",h(e.EV_AI_HOOK_OPERATOR_LOGIN));if(t)return t;let n=h(e.GITHUB_ACTOR)??h(e.GITHUB_TRIGGERING_ACTOR)??h(e.GITHUB_USER),r=B(n,null,"github",n);if(r)return r;let o=h(e.GITLAB_USER_LOGIN),s=B(h(e.GITLAB_USER_NAME)??o,h(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let a=B(h(e.BUILD_REQUESTEDFOR),h(e.BUILD_REQUESTEDFOREMAIL),"azure_devops",h(e.BUILD_REQUESTEDFORID));if(a)return a;let i=h(e.BUILDKITE_BUILD_CREATOR_EMAIL),c=B(h(e.BUILDKITE_BUILD_CREATOR),i,"buildkite",i);if(c)return c;let l=B(h(e.BUILD_USER)??h(e.CHANGE_AUTHOR),h(e.BUILD_USER_EMAIL)??h(e.CHANGE_AUTHOR_EMAIL),"jenkins",h(e.BUILD_USER_ID));if(l)return l;let u=h(e.CIRCLE_USERNAME),d=B(u,null,"circleci",u);if(d)return d;let m=h(e.CODEBUILD_INITIATOR),f=B(m,null,"codebuild",m);if(f)return f;let g=B(h(e.DRONE_COMMIT_AUTHOR)??h(e.DRONE_COMMIT_AUTHOR_NAME),h(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",h(e.DRONE_COMMIT_AUTHOR));if(g)return g;if(pr(e.CLAUDE_CODE_REMOTE)||pr(e.CURSOR_AGENT)){let E=h(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:E&&!W(null,E)?E:null,platform_login:null,identity_source:"cloud"}}return null}function fr(e){return!!((e.git_user_name??e.git_user_email)&&!W(e.git_user_name,e.git_user_email))}function h(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function pr(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function ji(e,t=T,n=process.env){let r=await Bi(e,t);if(fr(r))return{...r,identity_source:"git_config"};let o=Ki(n);if(o&&fr(o))return o;let s=Gi(n);return s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Ue(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??T,s=e.env??process.env,a=await ji(t,o,s),i=Fi(a.git_user_name,a.git_user_email,a.identity_source,a.platform_login),l=(n?lt(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==i||!l))return{commit:()=>{}};let f=n;return{operator:a,commit:()=>{f&&xn(f,i,Ie())}}}function yt(e){return e?!lt(e)?.operator_identity_hash:!0}function mr(e){return!0}import{existsSync as Da,readFileSync as Ha}from"node:fs";import{homedir as Vr}from"node:os";import{join as M}from"node:path";import{basename as La,join as ne,resolve as Fr}from"node:path";import{existsSync as gr,readdirSync as zi}from"node:fs";import{basename as Vi,dirname as Wi,relative as Ji}from"node:path";var me=class{constructor(t,n=""){this.home=t;this.pathPrefix=n}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=Ji(this.home,t).replace(/\\/g,"/"),r=!n||n.startsWith("..")?`external/${O(Wi(t))}/${Vi(t)}`:n;return this.pathPrefix?`${this.pathPrefix}${r}`:r}get atGlobalCap(){return this.truncated||this.components.length>=H}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!gr(t))return[];try{return zi(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(gr(t))return q(t,n)}push(t){return this.components.length>=H?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Ct,readFileSync as Yi,statSync as Xi}from"node:fs";import{basename as hr,join as ge,relative as Er}from"node:path";var At=2e4,Zi=4;function qi(e){return e.length<=At?e:`${e.slice(0,At-1)}\u2026`}function Qi(e){try{let t=Yi(e),n=t.toString("utf8");return{hash:O(t),length:t.length,text:qi(n)}}catch{return null}}var _r={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function ea(e){return e in _r?_r[e]:"UNSPECIFIED"}function Pe(e,t){let n=Qi(t.absolutePath);if(!n)return!1;let r=t.name??hr(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.homeRel(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=ea(t.kind);return s&&(o.trigger=s),e.push(o)}function ta(e,t,n){let r=Er(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?hr(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Y(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:a,extensions:i}=t;Tt(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:a,extensions:i})}function Tt(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:a,enabled:i,nested:c,extensions:l}=t;if(!(o>Zi))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let f=ge(r,u.name,c);if(Ct(f)){let g=Er(n,ge(r,u.name)).replace(/\\/g,"/");Pe(e,{absolutePath:f,kind:s,origin:a,enabled:i,name:g||u.name});continue}Tt(e,{walkRoot:n,currentDir:ge(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(u.isDirectory()){Tt(e,{walkRoot:n,currentDir:ge(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let d=u.name.toLowerCase();if(!l.some(f=>d.endsWith(f)))continue;let m=ge(r,u.name);Pe(e,{absolutePath:m,kind:s,origin:a,enabled:i,name:ta(n,m,!0)})}}function Sr(e){for(let t of e)if(Ct(t))try{if(Xi(t).size>0)return t}catch{continue}return e.find(t=>Ct(t))}var na="<omitted>",Rr=100,Ir=120,Me=[{raw:"tools",attr:"tools"},{raw:"autoApprove",attr:"auto_approve"},{raw:"auto_approve",attr:"auto_approve"},{raw:"alwaysAllow",attr:"always_allow"},{raw:"always_allow",attr:"always_allow"},{raw:"enabledTools",attr:"enabled_tools"},{raw:"enabled_tools",attr:"enabled_tools"},{raw:"disabledTools",attr:"disabled_tools"},{raw:"disabled_tools",attr:"disabled_tools"}],yr=new Set(Me.map(e=>e.attr)),ra=["enabled","disabled"],oa=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],sa=new Set(["type","command","url","args","env","envVars","headers",...ra,...oa,...Me.map(e=>e.raw)]),ia=new Set(["transport","command_or_url","args","env_var_names","headers_present","auth","bearer_token_env_var","default_tools_approval_mode","env_http_header_names",...yr,...[...yr].map(e=>`${e}_truncated`)]);function Cr(e,t){for(let n of t)sa.has(n)||ia.has(n)||(e[n]=na)}var aa=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,ca=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,la=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,ua=/^bearer(?:\s+|$)/i;function De(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ar(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Ot(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=De(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function te(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function da(e){return la.test(e)||ua.test(e)?"<redacted>":e.includes("://")?te(e):e}function Tr(e){if(/^https?:\/\//i.test(e))return te(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Tr(e.slice(t+1))}`:da(e)}function fa(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return aa.test(t)||ca.test(t)}function He(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(fa(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Tr(r))}return t}function pa(e){let t=Ar(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ir?r.slice(0,Ir):r))].sort();if(n.length!==0)return n.length>Rr?{names:n.slice(0,Rr),truncated:!0}:{names:n,truncated:!1}}function ma(e){let t=De(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function Or(e,t){let n=new Set;for(let{raw:r,attr:o}of Me){if(n.has(o)||!(r in t))continue;let s=t[r];if(o==="auto_approve"&&typeof s=="boolean"){e.auto_approve=s,n.add(o);continue}let a=pa(s);a&&(e[o]=a.names,a.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function kr(e,t){let n=De(e),r={transport:t};if(!n)return r;Cr(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,a=typeof n.serverUrl=="string"?n.serverUrl:void 0,i=o??s??a;i&&(r.command_or_url=te(i));let c=He(Ar(n.args));c.length>0&&(r.args=c);let l=ma(n.env_http_headers),u=[...new Set([...Ot(n.env),...Ot(n.envVars),...Ot(n.env_vars),...l.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();u.length>0&&(r.env_var_names=u),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let g of["headers","http_headers","env_http_headers"])if(n[g]!==void 0&&n[g]!==null){r.headers_present=!0;break}let d=typeof n.auth=="string"?n.auth:void 0;d&&(r.auth=d);let m=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;m&&(r.bearer_token_env_var=m);let f=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return f&&(r.default_tools_approval_mode=f),Or(r,n),r}function xr(e){let t=De(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function vt(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return O(JSON.stringify({name:e,attributes:r,enabled:n}))}function Le(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function wt(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*\\[([^\\]]*)\\]`,"m").exec(e);return n?.[1]?[...n[1].matchAll(/"([^"]*)"|'([^']*)'/g)].map(r=>r[1]??r[2]??"").filter(r=>r.length>0):[]}function ga(e,t){return He(wt(e,t))}function xt(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function kt(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=Le(n[1]);return r.length>0?r:void 0}function _a(e,t){let n=[],r=a=>{for(let i of a.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(i);c?.[1]&&n.push([c[1],Le(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
16
+ ${e}`);return s?.[1]&&r(s[1]),n}function vr(e){return xt(e,"enabled")===!1?!1:xt(e,"disabled")!==!0}function ha(e,t){let n={};for(let{raw:r,attr:o}of Me){if(o==="auto_approve"){let a=xt(t,r);if(a!==void 0){n[r]=a;continue}}let s=wt(t,r);s.length>0&&(n[r]=s)}Or(e,n)}var Ea=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,Sa=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function Ra(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
17
+ `)){let s=Ea.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(Sa))o[1]&&t.add(o[1]);return[...t]}function wr(e,t){let n={transport:t};Cr(n,Ra(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?Le(r[1]??""):void 0,a=o?Le(o[1]??""):void 0,i=s!==void 0&&s.length>0?s:a;i&&(n.command_or_url=te(i));let c=ga(e,"args");c.length>0&&(n.args=c);let l=new Set;for(let R of e.split(`
18
+ `)){let I=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(R);I?.[1]&&l.add(I[1])}let u=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(u?.[1])for(let R of u[1].split(",")){let I=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(R);I?.[1]&&l.add(I[1])}let d=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
19
+ ${e}`);if(d?.[1])for(let R of d[1].split(`
20
+ `)){let I=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(R);I?.[1]&&l.add(I[1])}for(let R of wt(e,"env_vars"))l.add(R);let m=_a(e,"env_http_headers");for(let[,R]of m)R.length>0&&l.add(R);let f=kt(e,"bearer_token_env_var");f&&(l.add(f),n.bearer_token_env_var=f),l.size>0&&(n.env_var_names=[...l].sort()),m.length>0&&(n.env_http_header_names=[...new Set(m.map(([R])=>R))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let g=kt(e,"auth");g&&(n.auth=g);let E=kt(e,"default_tools_approval_mode");return E&&(n.default_tools_approval_mode=E),ha(n,e),n}var br=300;function Ia(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function ya(e){let t=[],n="",r=null;for(let o of e){if(r){o===r?r=null:n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}function Ca(e){return e.length<=br?e:`${e.slice(0,br-1)}\u2026`}function Nr(e,t){let n=Ia(e.trim(),t),r=ya(n);if(r.length===0)return"";let[o,...s]=r,a=te(o),i=He(s);return Ca([a,...i].join(" "))}function Aa(e){if(e.prompt||e.type==="prompt")return"prompt";let t=e.command??e.bash??e.powershell??"";return/\bnpx\b/i.test(t)?"npx":/\.(sh|bash|zsh|js|mjs|cjs|ts|py)(\s|$|"|')/i.test(t)||/^(\.\/|~\/|\/|[A-Za-z]:[\\/])/.test(t.trim())?"script":"inline"}function Ta(e){return Array.isArray(e.hooks)&&e.hooks.length>0?e.hooks:[{type:e.type,command:e.command,bash:e.bash,powershell:e.powershell,prompt:e.prompt}]}function Oa(e,t,n,r){let o=e.homeRel(t);for(let[s,a]of Object.entries(n))if(!(!Array.isArray(a)||e.truncated))for(let i of a){if(!i||typeof i!="object"||e.truncated)continue;let c=i;for(let l of Ta(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",d=Aa({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",f=O(u),g=m?`${s}:${m}:${d}:${f}`:`${s}:${d}:${f}`,E=`${s}|${m}|${d}|${u}|attrs2`;e.push({kind:"HOOK",name:g,path:o,content_hash:O(E),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:d,action_hash:f,...d!=="prompt"&&u.trim()?{command:Nr(u,e.home)}:{}}})}}}function _e(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||Oa(e,t,r.hooks,n)}var Ur={claude:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]}],memory:[".claude/CLAUDE.md"],hooks:[".claude/settings.json"],mcpJson:[".claude.json"],plugins:"claude"},cursor:{skillRoots:[".cursor/skills",".cursor/skills-cursor"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[".cursor/AGENTS.md"],hooks:[".cursor/hooks.json"],mcpJson:[".cursor/mcp.json"],plugins:"cursor"},codex:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]}],memory:[".codex/AGENTS.override.md",".codex/AGENTS.md"],hooks:[".codex/hooks.json"],mcpToml:[".codex/config.toml"]}};import{existsSync as ka,readFileSync as xa}from"node:fs";function va(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function Pr(e,t,n){let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.homeRel(t);for(let[a,i]of Object.entries(o)){if(e.truncated)return;let c=va(i),l=kr(i,c),u=xr(i);e.push({kind:"MCP_SERVER",name:a,path:s,content_hash:vt(a,l,u),origin:n,enabled:u,attributes:l})}}function Lr(e,t,n){if(!ka(t))return;let r;try{r=xa(t,"utf8")}catch{return}let o=e.homeRel(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,a;for(;(a=s.exec(r))!==null;){if(e.truncated)return;let i=a[1]??a[2]??a[3];if(!i)continue;let c=r.slice(a.index+a[0].length),l=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),d="unknown";/^\s*url\s*=/m.test(u)?d="http":/^\s*command\s*=/m.test(u)&&(d="stdio");let m=wr(u,d),f=vr(u);e.push({kind:"MCP_SERVER",name:i,path:o,content_hash:vt(i,m,f),origin:n,enabled:f,attributes:m})}}import{existsSync as wa,readdirSync as ba}from"node:fs";import{join as x}from"node:path";var Mr=50;function bt(e,t,n,r){if(!wa(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(Mr,()=>{Y(e,{dir:x(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Y(e,{dir:x(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Y(e,{dir:x(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});_e(e,x(t,"hooks","hooks.json"),n),_e(e,x(t,"hooks.json"),n);let a=e.components.length-o,i=s>=Mr;return{componentCount:a,expandTruncated:i}}function Nt(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function Dr(e){let t=x(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(x(e.home,".claude/settings.json"),{})?.enabledPlugins??{},a=e.homeRel(t);for(let[i,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},d=s[i]===!0,m=i.includes("@")?i.split("@").slice(1).join("@"):"",f=typeof u.version=="string"?u.version:"",g=typeof u.scope=="string"?u.scope:"user",E=`plugin:${i}`,R=0,I=!1;for(let N of l)if(typeof N.installPath=="string"&&N.installPath.length>0){let j=bt(e,N.installPath,E,d);R+=j.componentCount,I=I||j.expandTruncated}Nt(e,{pluginKey:i,rowPath:a,enabled:d,scope:g,version:f||void 0,marketplace:m||void 0,componentCount:R,expandTruncated:I,contentHash:O(`${i}|${f}|${g}|${d}|${R}`)})}}function Na(e){let t=e,n="";try{let r=ba(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=x(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=x(e,s),n=s)}}catch{}return{installPath:t,version:n}}var Ua=/^\d+$/;function Pa(e){let t=e.filter(n=>!Ua.test(n.pluginId));return t.length>0?t:e}function Hr(e){let t=[{base:x(e.home,".cursor/plugins/local"),scope:"local"},{base:x(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let i=o.name,c=x(n,o.name),l=`plugin:${i}`,{componentCount:u,expandTruncated:d}=bt(e,c,l,!0);Nt(e,{pluginKey:i,rowPath:e.homeRel(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:d,contentHash:O(`${i}|local|${u}`)});continue}let s=o.name,a=[];for(let i of e.readEntries(x(n,s))){if(!i.isDirectory())continue;let c=x(n,s,i.name),{installPath:l,version:u}=Na(c);a.push({pluginId:i.name,installPath:l,version:u})}for(let i of Pa(a)){if(e.truncated)break;let c=`${i.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:d}=bt(e,i.installPath,l,!0);Nt(e,{pluginKey:c,rowPath:e.homeRel(i.installPath),enabled:!0,scope:"cache",version:i.version||void 0,marketplace:s,componentCount:u,expandTruncated:d,contentHash:O(`${c}|${i.version}|${u}`)})}}}function $r(e,t,n,r){let o=Ur[t];if(!o)return;let s=e.home;for(let i of o.skillRoots)Y(e,{dir:ne(s,i),kind:"SKILL",origin:n,enabled:!0,nested:"SKILL.md"});for(let i of o.dirs)Y(e,{dir:ne(s,i.dir),kind:i.kind,origin:n,enabled:!0,extensions:i.extensions});let a=Sr(o.memory.map(i=>ne(s,i)));a&&Pe(e,{absolutePath:a,kind:"MEMORY",origin:n,enabled:!0,name:La(a)});for(let i of o.hooks)_e(e,ne(s,i),n);for(let i of o.mcpJson??[])Pr(e,ne(s,i),n);for(let i of o.mcpToml??[])Lr(e,ne(s,i),n);r&&(o.plugins==="claude"?Dr(e):o.plugins==="cursor"&&Hr(e))}function Ut(e,t,n){let r=new me(t);if($r(r,e,"user",!0),n===void 0||Fr(n)===Fr(t))return{components:r.components,truncated:r.truncated};let s=new me(n,"cwd/");$r(s,e,"cwd",!1);let a=[...r.components,...s.components],i=r.truncated||s.truncated||a.length>H;return{components:a.slice(0,H),truncated:i}}function Pt(e,t,n={}){let r=n.truncated===!0,o=It(e),s=new Set(e.map(u=>$(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let i=[],c=t;for(let u of e){let d=$(u.path,u.name);c[d]!==u.content_hash&&i.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let d=dr(u);d&&l.push(d)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:i,removed:l,unchanged:i.length===0&&l.length===0}}var Kr=3e5,Ma=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Lt(e,t,n){let r=new Set(t.map(s=>$(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has($(s.path,s.name))||o.push(s));return o}function Mt(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function Br(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Gr(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Dt(e,t=Kr){let n=[],r=[];for(let u of e)Ma.has(u.kind)?n.push(u):r.push(u);r.sort((u,d)=>(u.text?.length??0)-(d.text?.length??0));let o=[...n,...r],s=[],a=2,i=0,c=0,l=[];for(let u of o){let d=s.length>0?1:0,m=Br(u)+d;if(a+m<=t){s.push(u),a+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let f=Gr(u),g=Br(f)+d;if(a+g<=t){s.push(f),a+=g,i+=1;continue}}c+=1}return{components:s,textDeferredCount:i,droppedCount:c,textHashesSent:l}}function Ht(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Gr(n))}var Fa={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],subagents:".cursor/agents",commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:[".agents/skills",".codex/skills"],subagents:".codex/agents",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},$a=200,jr=200,Ba=["allow","deny","ask"],Ka=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Ft="<path>",Ga=new RegExp(`${Ft}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function ja(e){let t=e.replace(Ka,Ft).replace(Ga,Ft);return t.length>jr?`${t.slice(0,jr)}...`:t}function zr(e){let t=q(e,{}),n=[];for(let r of Ba)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:ja(o),mode:r});return{model:t.model??"",permissionKeys:n}}var za=10,Va=840*60*1e3,Wa="self-config-cache.json";function $t(){return A("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Ja(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Va}var Ya={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Xa(e,t=T){let n=Ya[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let i=((await t(s,["--version"],2e3)).split(`
21
+ `)[0]??"").trim();return i||r(o+1)};return r(0)}function Za(e=Vr()){return M(e,".ev-ai","agent-hook",Wa)}function qa(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
22
+ `);return O(n)}function Fe(e,t,n=!1){let r=qa(e),o=e.length;return t===r?n?{hash:r,count:o,truncated:n}:{hash:r,count:o}:n?{hash:r,count:o,entries:e,truncated:n}:{hash:r,count:o,entries:e}}function Qa(e){return Da(e)?b(Ha(e,"utf8"),{}):{}}function ec(e,t){try{G(e,`${JSON.stringify(t)}
23
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);_(`WARN: self-config cache write failed open: ${r}`)}}function tc(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let a=t[s];a.entries!==void 0&&(o[s]=a.hash)}return r&&(o.user_spec_collected_at_ms=r.collectedAtMs,r.included&&(o.user_spec=r.hash,o.user_spec_components=r.componentHashes),o.user_spec_text_hashes=r.textHashes),o}async function Wr(e,t=process.cwd(),n=Vr(),r={}){let o=e==="claude",s=r.gitRoot??t,a=await Xa(e),i="",c=[];if(o){let U=zr(M(n,".claude/settings.json")),F=zr(M(t,".claude/settings.local.json"));i=F.model||U.model,c=[...U.permissionKeys,...F.permissionKeys].slice(0,$a)}let l=Fa[e]??{},u={present:!1,size:0},d=U=>{let F=Array.isArray(U)?U:U?[U]:[],C=[],K=!1;for(let je of F){let w=ie(M(n,je));if(C=C.concat(w.entries),K=K||w.truncated,C.length>=H){C=C.slice(0,H),K=!0;break}}return{entries:C,truncated:K}},m=Za(n),f=Qa(m),g=f[e]??{},E=(g.send_count??0)+1,R=E>0&&E%za===0,I=U=>R?void 0:g[U],N=d(l.skills),j=l.subagents?ie(M(n,l.subagents)):{entries:[],truncated:!1},Ge=l.commands?ie(M(n,l.commands)):{entries:[],truncated:!1},zt=l.rules?ie(M(n,l.rules)):{entries:[],truncated:!1},se={skills:Fe(N.entries,I("skills"),N.truncated),subagents:Fe(j.entries,I("subagents"),j.truncated),commands:Fe(Ge.entries,I("commands"),Ge.truncated),rules:Fe(zt.entries,I("rules"),zt.truncated)},v={runner_platform:e,config_scope:"user",cli_version:a,claude_version:o?a:null,model:o&&i||null,permission_keys:c,user_scope:{skills:se.skills,subagents:se.subagents,commands:se.commands,rules:se.rules,memory:l.memory?ae(M(n,l.memory)):u,settings:l.settings?ae(M(n,l.settings)):u,mcp:l.mcp?ae(M(n,l.mcp)):u},local_settings:o?ae(M(t,".claude/settings.local.json")):u},Vt=null,Wt=()=>{},Jt=r.nowMs??Date.now();if(!$t()&&Ja(g.user_spec_collected_at_ms,Jt)){let U=g.user_spec_collected_at_ms!==void 0,F=Ut(e,n),C=Pt(F.components,g.user_spec_components,{forceFull:!g.user_spec_components,truncated:F.truncated}),K=new Set(g.user_spec_text_hashes??[]),je=Lt(F.components,C.upserts,K),w=Dt(Ht([...C.upserts,...je],K));v.user_spec_hash=C.hash,v.user_spec_count=C.count,v.user_spec_truncated=C.truncated||w.droppedCount>0,(w.components.length>0||C.removed.length>0||C.full)&&(C.full&&(v.user_spec_full=!0),w.components.length>0&&(v.user_spec=w.components),C.removed.length>0&&!v.user_spec_truncated&&(v.user_spec_removed=C.removed),w.textDeferredCount>0&&(v.user_spec_text_deferred=w.textDeferredCount));let ze=C.full?{}:{...g.user_spec_components??{}};if(!v.user_spec_truncated)for(let Z of C.removed)delete ze[$(Z.path,Z.name)];for(let Z of w.components)ze[$(Z.path,Z.name)]=Z.content_hash;Vt={hash:C.hash,componentHashes:ze,textHashes:Mt(K,w.textHashesSent,F.components),included:w.components.length>0||C.removed.length>0&&!v.user_spec_truncated||C.full,collectedAtMs:Jt};let Ve=await Ue({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:U});Ve.operator&&(v.operator=Ve.operator),Wt=Ve.commit}let po=tc(g,se,E,Vt);return{config:v,commit:()=>{f[e]=po,ec(m,f),Wt()}}}function re(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp:Ie(),session_id:n.sessionId||null,turn_id:n.turnId||null,installation_id:n.installationId,platform:n.runnerPlatform,platform_agent_id:n.platformAgentId||null,runner_event:n.runnerEvent||null,agent_hook_version:st,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as Jr}from"node:fs";import{spawn as Yr}from"node:child_process";import{basename as nc}from"node:path";import{fileURLToPath as rc}from"node:url";var Kt="__post",$e="__work";function oc(e,t){let n=e.payload,r=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],o=e.correlation&&typeof e.correlation=="object"?Object.keys(e.correlation):[];return JSON.stringify({event:e.event,schema_version:e.schema_version,agent_hook_version:e.agent_hook_version,host_arch:e.host_arch,node_version:e.node_version,build_ms:e.build_ms,body_bytes:t,correlation_keys:o,payload_keys:r})}function Xr(e){switch(e){case"session_start":return cn;case"session_end":return ln;case"tool_invoked":case"skill_invoked":return rt;default:return rt}}function sc(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
24
+ ${n}`}function Zr(e,t=[],n=process.execPath,r=import.meta.url,o=Jr){if(nc(n)===Ce)return{command:n,args:[e,...t]};let s=rc(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function ic(e=process.execPath,t=import.meta.url,n=Jr){return Zr(Kt,[],e,t,n)}function ac(e){let t=e.indexOf(`
25
+ `);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function qr(e,t=fetch){let n=await e(),r=ac(n);if(!r)return;let{meta:o,body:s}=r,a={"Content-Type":"application/json"};try{await t(o.url,{method:"POST",headers:a,body:s,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function cc(e,t,n){let r=Xr(e);_(`POST event=${e} url=${ut(n)} size=${t.length} platform=${process.platform}`);let o={"Content-Type":"application/json"},s=Date.now();try{let a=await fetch(n,{method:"POST",headers:o,body:t,signal:AbortSignal.timeout(r)}),i=Date.now()-s;if(a.ok)return _(`POST outcome=ok elapsed_ms=${i} http=${a.status}`),!0;let c=(await a.text()).slice(0,200).replace(/[\n\r]/g,"");return _(`POST outcome=fail elapsed_ms=${i} http=${a.status} body=${c}`),!1}catch(a){let i=Date.now()-s,c=a instanceof Error?a.message:String(a);return _(`POST outcome=fail elapsed_ms=${i} http=000 body=${c}`),!1}}async function Qr(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let a=!1;return await new Promise(i=>{let c=setTimeout(()=>{if(!a){_(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}i()},un),l=()=>{a=!0,clearTimeout(c),i()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let a=s instanceof Error?s.message:String(s);return _(`WARN: ${o} spawn failed open: ${a}`),null}}async function lc(e,t,n,r=Yr,o=ic){let s=Xr(e),a=sc(n,s,t),{command:i,args:c}=o();return Qr(i,c,a,r,"detached post")}async function eo(e,t,n=Yr,r=Zr){let{command:o,args:s}=r($e,t);return Qr(o,s,e,n,"detached work")}async function oe(e,t,n,r,o,s){if(!o)return _("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Te(o))return _(`WARN: collector URL blocked (https required): ${ut(o)}`),!1;let a=r(e,t,n);s!==void 0&&(a.build_ms=Math.max(0,Date.now()-s));let i=`${JSON.stringify(a)}
26
+ `,c=A("EV_AI_HOOK_DEBUG");c==="full"?_(`DEBUG envelope=${JSON.stringify(a)}`):c==="1"&&_(`DEBUG summary=${oc(a,Buffer.byteLength(i,"utf8"))}`);let l=process.argv.includes($e),u=A("EV_AI_HOOK_SYNC")==="1";return ve(n.runnerEvent,n.runnerPlatform)||l||u?cc(e,i,o):(await lc(e,i,o),!1)}import{relative as uc,resolve as Be,sep as Gt}from"node:path";var dc=["session_id","conversation_id","turn_id","generation_id","prompt.id","prompt_id","hook_event_name","event","source","status","stop_reason","reason","tool_name","tool","tool_use_id","skill_name","command_name","expansion_type","command_source","permission_mode","model","model_id","agent_id","agent_type","subagent_id","subagent_type","subagent_model","is_parallel_worker","effort","effort.level","duration_ms","duration","sandbox","failure_type","is_interrupt"];function fc(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:A("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function pc(e){let t={};for(let n of dc){let r=V(e,n);r!==void 0&&(t[n]=r)}return t}function mc(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Be(e),r=Be(t),o=uc(r,n);return!o||o==="."?".":o.startsWith(`..${Gt}`)||o===".."||Be(r,o)!==n?null:o.split(Gt).join("/")}function gc(e){return typeof e!="string"||e.length===0?null:Be(e).split(Gt).join("/")}function to(e,t,n){let r=gc(t.cwd);r!==null&&(e.cwd=r);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?mc(t.cwd,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function no(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([a,i])=>!a.startsWith("_")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")).sort((a,i)=>Buffer.byteLength(JSON.stringify(a[1]),"utf8")-Buffer.byteLength(JSON.stringify(i[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[a,i]of o){let c={...s,[a]:i};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[a]=i}return s}function he(e,t,n={}){if(fc(t)){let o={...e};return delete o.cwd,delete o.transcript_path,to(o,e,n),no(o,fn)}let r=pc(e);return to(r,e,n),no(r,dn)}import{createReadStream as _c}from"node:fs";import{stat as hc}from"node:fs/promises";import{basename as Ec,resolve as Sc}from"node:path";import{createInterface as Rc}from"node:readline";var Ic=1024*1024;function yc(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Ec(t).endsWith(".jsonl")}async function ro(e){if(!e||!yc(e))return null;try{let t=Sc(e),n=await hc(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Ic),o=[],s=Rc({input:_c(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let a of s)a.length!==0&&o.push(a);r>0&&o.length>0&&o.shift();for(let a=o.length-1;a>=0;a--){let i=o[a];if(i)try{let c=JSON.parse(i);if(c.type!=="assistant")continue;let l=c.message;if(!l||typeof l!="object")continue;let u=l.model;if(typeof u=="string"&&u.length>0)return u}catch{continue}}return null}catch{return null}}function Se(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function Ke(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}var Ac=new Set([...Object.values(ht),".github"]);function Tc(e,t,n,r,o,s){if(e===null||t===null||!(/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let i=s.find(f=>f.name.toLowerCase()===t.toLowerCase()),c=i?.sourcePath??(i?.source==="claude_json_user"?".claude.json":i?.source==="cursor_mcp_user"?".cursor/mcp.json":i?.source==="codex_toml_user"||i===void 0&&o==="codex"?".codex/config.toml":void 0);if((i?.scope==="user"||i?.source==="claude_json_user"||i?.source==="cursor_mcp_user"||i?.source==="codex_toml_user"||i===void 0&&o==="codex")&&c)try{let f=(0,k.userConfigRootFromPath)(c);return(0,k.buildComponentReference)({installationRootExternalKey:(0,k.installationRootExternalKey)(r,f),installableKind:k.ComponentKind.INTERFACE,sourcePath:c,nativeKey:i?.name??t})}catch{return}if(n===null)return;let u=n.indexOf(":");if(u<=0||u===n.length-1)return;let d=n.slice(u+1),m=d.replaceAll("\\","/").split("/").at(-1);if(!(m===void 0||!Ac.has(m)))try{return(0,k.buildComponentReference)({installationRootExternalKey:n,installableKind:k.ComponentKind.INTERFACE,sourcePath:d,nativeKey:t})}catch{return}}function Oc(...e){for(let t of e)if(t)return t;return null}function D(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return _(`WARN: ${n} failed open: ${r}`),t}function kc(e){let t={present:!1,size:0},n={hash:"",count:0};return{config:{runner_platform:e,config_scope:"user",cli_version:null,claude_version:null,model:null,permission_keys:[],user_scope:{skills:n,subagents:n,commands:n,rules:n,memory:t,settings:t,mcp:t},local_settings:t},commit:()=>{}}}function xc(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var X=new Set,Ee=null;async function oo(e){if($t())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(X.has(t))return;if(!yt(n)){X.add(t);return}let r=ce({sessionId:e.sessionId,hostname:le()});if(mr(r)){if(Ee){await Ee;return}Ee=(async()=>{if(X.has(t)||!yt(n)){X.add(t);return}if(!vn(n)){X.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:a}=e.manifest,i=String(e.runnerPlatform),[c,l,u,d,m]=await Promise.allSettled([pe(a),tt(),Et(r),nt(),Ue({gitRoot:a,installationStorePath:n,forceResend:!1})]),f=D(c,null,"gitSnapshot"),g=D(l,"","detectVirt"),E=D(u,null,"probeCloud"),R=D(d,{},"hostEnv"),I=D(m,{commit:()=>{}},"resolveOperatorForSend");await Re(e,a,f);let N={identity:{host:le(),context:r,virt:g||null,cloud:E,git:f},host_env:R,env_vars:Rt(),self_config:xc(i,I.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await oe("session_start",N,Se(e),re,e.manifest.collectorUrl,s),o&&(I.commit(),X.add(t))}finally{wn(n)}})().finally(()=>{Ee=null}),await Ee}}async function Re(e,t,n){try{let r=n===void 0?await pe(t):n;e.platformAgentId=await ir(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);_(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function vc(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=ce({sessionId:e.sessionId,hostname:le()}),o=String(e.runnerPlatform),[s,a,i,c,l,u]=await Promise.allSettled([pe(n),tt(),Et(r),nt(),St(e.manifest.manifest,n,o),Wr(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),d=D(s,null,"gitSnapshot"),m=D(a,"","detectVirt"),f=D(i,null,"probeCloud"),g=D(c,{},"hostEnv"),E=D(l,[],"mcpDeclared"),R=D(u,kc(o),"selfConfig"),I=R.config;await Re(e,n,d);let N=p(e.hookInput,"model");N&&(I.model=N);let j={identity:{host:le(),context:r,virt:m||null,cloud:f,git:d},host_env:g,env_vars:Rt(),mcp:{declared:E},self_config:I,run_meta:{trigger:e.hookSource||"startup"},hook_input:he(e.hookInput,e.manifest.manifest,Ke(e))};await oe("session_start",j,Se(e),re,e.manifest.collectorUrl,t)&&(R.commit(),X.add(e.manifest.installationId))}async function wc(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Re(e,n);let r=Oc(p(e.hookInput,"status"),p(e.hookInput,"stop_reason"),p(e.hookInput,"reason"),gt(p(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await ro(p(e.hookInput,"transcript_path")):null,s=he(e.hookInput,e.manifest.manifest,Ke(e));o&&(s.model=o),await oe("session_end",{status:r,...o?{model:o}:{},hook_input:s},Se(e),re,e.manifest.collectorUrl,t)}async function bc(e){let t=Date.now(),n=Gn(e.hookInput);if(n.length===0)return;await oo(e);let{gitRoot:r}=e.manifest;await Re(e,r);let o=he(e.hookInput,e.manifest.manifest,Ke(e)),s=Se(e),a=Oe(e.hookInput.tool_input),i=r.replaceAll("\\","/").replace(/\/$/,""),c=a?.replaceAll("\\","/"),l=c===void 0?null:c.startsWith(`${i}/`)?c.slice(i.length+1):c.startsWith("/")?null:c,u=Cc().replaceAll("\\","/").replace(/\/$/,""),d=c?.startsWith(`${u}/`)===!0?c.slice(u.length+1):null;await Promise.all(n.map(m=>{let f;if((l!==null||d!==null)&&dt(l??d??"")?.toLowerCase()===m.toLowerCase()){let g=l??d,E=g===null?null:(0,k.nativeKeyForSkillPath)(g);if(E!==null)try{let R=l!==null?e.platformAgentId:(0,k.installationRootExternalKey)(e.manifest.installationId,(0,k.userConfigRootFromPath)(g));R&&(f=(0,k.buildComponentReference)({installationRootExternalKey:R,installableKind:k.ComponentKind.SKILL,sourcePath:g,nativeKey:E}))}catch{f=void 0}}return oe("tool_invoked",{tool_name:"Skill",skill_name:m,...f===void 0?{}:{component_reference:f},success:null,duration_ms:null,hook_input:o},s,re,e.manifest.collectorUrl,t)}))}async function Nc(e){let t=Date.now();await oo(e);let{gitRoot:n}=e.manifest;await Re(e,n);let{toolName:r,skillName:o}=Jn(e.hookInput,e.runnerEvent),s=Xn(e.hookInput),a=zn(e.runnerEvent),i=a===!1?Zn(e.hookInput,e.runnerEvent):null,c=await St(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=qn(r,c.map(f=>f.name)),d=Tc(r,l,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),c),m=Yn(e.hookInput);await oe("tool_invoked",{tool_name:r,skill_name:o,success:a,duration_ms:s,...i?{failure_reason:i}:{},...l?{mcp_server:l}:{},...u?{mcp_tool:u}:{},...d?{component_reference:d}:{},...m?{subagent_type:m}:{},hook_input:he(e.hookInput,e.manifest.manifest,Ke(e))},Se(e),re,e.manifest.collectorUrl,t)}async function so(e){switch(e.internalEvent){case"session_start":await vc(e);return;case"session_end":await wc(e);return;case"skill_invoked":await bc(e);return;case"tool_invoked":await Nc(e);return;default:return}}function io(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{existsSync as jt,readFileSync as Uc}from"node:fs";import{dirname as Pc,join as ao,relative as Lc}from"node:path";var co=[an,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Mc(e=process.cwd(),t){let n=A("EV_AI_HOOK_MANIFEST");if(n&&jt(n))return n;let r=t??await qe(e);for(let o of co){let s=ao(r,o);if(jt(s))return s}for(let o of co){let s=ao(e,o);if(jt(s))return s}}async function Dc(e,t){let n=t??await qe(Pc(e)),r=Lc(n,e),o=await P("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(_(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Hc(e){let t=Uc(e,"utf8");return b(t,{})}function Fc(){return{schema_version:2,mcp_servers:[]}}async function lo(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Ze(e),o=await Mc(e,n),s=o?Hc(o):Fc();delete s.installation_id;let a=o?await Dc(o,n):!1;s.capture_hook_input==="full"&&o&&a&&(_(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${o}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete s.capture_hook_input);let{installationId:i,storePath:c,repoKey:l}=await Pn(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:i,installationStorePath:c,repoKey:l,collectorUrl:Fn(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}async function uo(e,t,n,r){let o=t??await Xe(ot),s=b(o,{}),a=p(s,"session_id")||p(s,"conversation_id"),i=await lo(process.cwd(),{sessionId:a});if(!i)return;r&&(i.collectorUrl=r);let c=Vn(s,i.manifest.platform,n),l=Wn(e,c.runnerEvent);if(!l){_(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:c.turnId,runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:i,platformAgentId:i.platformAgentId};if(io(l)){_(`WARN: unsupported internal event '${l}'`);return}await so(u)}function $c(e,t){if(A("EV_AI_HOOK_SYNC")==="1")return!0;let n=xe(e),r=b(t,{}),o=n.event??(p(r,"hook_event_name")||p(r,"event")),s=de(r,o,void 0,n.runner);return ve(o,s)}async function fo(e=process.argv.slice(2)){if(e[0]===Kt){try{await qr(Ye)}catch{}return 0}if(e[0]===$e){try{let t=xe(e.slice(1)),n=await Ye(),r=b(n,{}),o=t.event??(p(r,"hook_event_name")||p(r,"event"));if(Qe()||mt(t.runner,r,o))return 0;await uo(t.event,n,t.runner,pt(t))}catch(t){let n=t instanceof Error?t.message:String(t);_(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Xe(ot),n=xe(e),r=pt(n),o=b(t,{}),s=n.event??(p(o,"hook_event_name")||p(o,"event"));if(Qe()||mt(n.runner,o,s)||!sr(o,s,n.runner))return 0;$c(e,t)?await uo(n.event,t,n.runner,r):await eo(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);_(`WARN: hook failed open: ${n}`)}finally{nn()}return 0}fo().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
16
27
  `),process.exit(1)});
@@ -9,7 +9,7 @@ var PROJECT_HOOK_BINARY_RELATIVE = `.ev-ai/agent-hook/${HOOK_BINARY_NAME}`;
9
9
  var HOOK_INPUT_ALLOWLIST_MAX_BYTES = 4 * 1024;
10
10
  var HOOK_INPUT_FULL_MAX_BYTES = 32 * 1024;
11
11
  var HOOK_INPUT_MCP_MAX_BYTES = 4 * 1024;
12
- var PACKAGE_VERSION = "1.0.7";
12
+ var PACKAGE_VERSION = "1.0.9";
13
13
  var NPX_PACKAGE_SPEC = `@ev-ai/agent-hook@${PACKAGE_VERSION}`;
14
14
  var HOOK_STATUS_MESSAGE = "ev-ai runtime report";
15
15
 
@@ -65,6 +65,11 @@ var CURSOR_WIRED_HOOK_EVENTS = [
65
65
  "preToolUse",
66
66
  "postToolUse",
67
67
  "postToolUseFailure",
68
+ "beforeShellExecution",
69
+ "afterShellExecution",
70
+ "beforeReadFile",
71
+ "afterFileEdit",
72
+ "beforeMCPExecution",
68
73
  "subagentStart",
69
74
  "subagentStop",
70
75
  "stop"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ev-ai/agent-hook",
3
- "version": "1.0.7",
3
+ "version": "1.0.9",
4
4
  "description": "Cross-runner runtime telemetry hook for Claude Code, Cursor, and Codex",
5
5
  "type": "module",
6
6
  "bin": {