@ev-ai/agent-hook 1.0.8 → 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 +4 -4
- package/README.md +1 -1
- package/dist/cli.mjs +28 -23
- package/dist/hook.mjs +23 -18
- package/dist/plugin-hooks.mjs +1 -1
- package/package.json +1 -1
package/COLLECTED-DATA.md
CHANGED
|
@@ -21,8 +21,8 @@ Every event also carries: UTC timestamp, `installation_id` (per-machine under `~
|
|
|
21
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`. 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`
|
|
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,
|
|
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`, …)
|
|
@@ -64,11 +64,11 @@ Username and hostname *are* sent (per-member usage for the installing org). The
|
|
|
64
64
|
- Tool arguments, shell commands, and file / code contents
|
|
65
65
|
- Tool error messages, stderr, and result bodies (a failure **class** is sent, never the message)
|
|
66
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
|
|
67
|
-
- Hook
|
|
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
|
|
68
68
|
- API keys, tokens, and other secret env vars
|
|
69
69
|
- HTTP(S) proxy credentials and proxy env vars
|
|
70
70
|
- Embedded credentials in git remotes and gateway URLs (`user:pass@` stripped; credential-shaped query params redacted)
|
|
71
|
-
- MCP
|
|
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
|
|
72
72
|
- Plugin `installPath` / `projectPath` (absolute / home paths)
|
|
73
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)
|
|
74
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
|
package/README.md
CHANGED
|
@@ -70,7 +70,7 @@ 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
74
|
|
|
75
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).
|
|
76
76
|
|
package/dist/cli.mjs
CHANGED
|
@@ -2,27 +2,32 @@
|
|
|
2
2
|
import { createRequire as __createRequire } from 'node:module';
|
|
3
3
|
const require = __createRequire(import.meta.url);
|
|
4
4
|
|
|
5
|
-
var
|
|
6
|
-
`)}function Y(e,t){es(Tn(e),{recursive:!0});let n=bn(Tn(e),`.${os(e)}.${process.pid}.${Qo(4).toString("hex")}.tmp`);try{rs(n,t,"utf8");try{An(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){xn(e),An(n,e);return}throw r}}catch(r){try{xn(n)}catch{}throw r}}function He(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function wn(){process.stdout.write('{"continue":true}')}function k(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function ge(){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 mt(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 U(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 C(e,t,n=3e3,r={}){let o=await U(e,t,n,r);return o.ok?o.stdout:""}async function gt(e=process.cwd()){let t=await U("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(k("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=k("CURSOR_PROJECT_DIR")??k("CLAUDE_PROJECT_DIR");if(n&&pt(n)){let r=await U("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 $(e=process.cwd()){return(await gt(e)).root}function w(e,t){try{return JSON.parse(e)}catch{return t}}var ft=new Map;function ae(e,t){let n=ft.get(e);if(n!==void 0)return n;try{let r=w(ns(e,"utf8"),t);return ft.set(e,r),r}catch{return ft.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 p(e,t){let n=te(e,t);return typeof n=="string"?n:""}var H=500;function _e(e,t=2){if(!pt(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,a)=>{if(a>t||r)return;let i;try{i=ts(s,{withFileTypes:!0})}catch{return}for(let c of i){if(r)return;let l=bn(s,c.name);if(c.isDirectory()){o(l,a+1);continue}if(c.isFile()){try{n.push({name:ss(e,l),size:vn(l).size})}catch{continue}if(n.length>=H){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function he(e){return pt(e)?{present:!0,size:vn(e).size}:{present:!1,size:0}}function Ee(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var ls=["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 ls.some(t=>!!I(t,e))}function ds(e){if(I("KUBERNETES_SERVICE_HOST",e)||Ee(I("REMOTE_CONTAINERS",e))||Ee(I("DEVCONTAINER",e)))return!0;try{if(is("/.dockerenv")||as("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Nn(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!I(t,e))}function fs(e,t=process.platform){return Nn(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!I(n,e)):!1}function ps(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function ms(e){return e==="linux"}function I(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return k(e)}function gs(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!_s(I("CURSOR_VERSION",n))}function _s(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function _t(e){if(ps(e.sessionId))return!0;let t=e.hostname??Pn(),n=e.osUser??Un(e.env);return gs(t,n,e.env)}function hs(e){return Ee(I("CURSOR_AGENT",e.env))?!0:_t(e)}function Es(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(I("TERM",e)??I("TERM_PROGRAM",e))||(I("SSH_TTY",e)??I("SSH_CONNECTION",e))||(I("__CFBundleIdentifier",e)??I("XPC_SERVICE_NAME",e))||Nn(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!I(t,e))||I("SESSIONNAME",e))}function Se(e={}){let t=e.env;if(I("GITHUB_ACTIONS",t))return"github_actions";if(Ee(I("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!fs(t,n)&&hs(e)&&(Ee(I("CURSOR_AGENT",t))||ms(n)))return"cursor_cloud";if(I("CODESPACES",t)||I("CODESPACE_NAME",t))return"codespaces";if(I("GITLAB_CI",t))return"gitlab_ci";if(us(t))return"managed";let r=I("CI",t);return r&&r!=="false"&&r!=="0"?"managed":ds(t)?"container":Es(t)?"interactive":"unknown"}async function ht(){return await C("systemd-detect-virt",[],1e3)}function Un(e=process.env,t=cs){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 Et(){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"),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 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=Un(),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 ye(){return Pn()}var Is="installation.json",Rs="cloud-bootstrap.lock",ks=6e4;function Kn(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function Ie(e=yt()){return It(e,".ev-ai","agent-hook")}function Cs(e=yt()){return It(Ie(e),Is)}function Jn(e){return It(De(e),Rs)}function Vn(){return Ss(8).toString("hex")}function ce(e){return Fn("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 Wn(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Os(e=process.env){let t=S(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Wn(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 zn(e,t){return e&&Wn(e)?e:(e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Os(t))}function As(e){return/^[0-9a-f]{16}$/.test(e)}function xs(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 ce(`github_actions|${t}|${n}`)}if(S(e.CODESPACES)||S(e.CODESPACE_NAME)){let t=S(e.CODESPACE_NAME);if(t)return ce(`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 ce(`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 ce(`gitlab|${t}|${n}`)}return null}var Ts="cursoragent@cursor.com";function vs(e){let t=S(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Ts?null:t}function bs(e,t){return S(e.CURSOR_PROJECT_DIR)??S(e.CLAUDE_PROJECT_DIR)??t}function ws(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Ps(e){let t=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?ws(t):e}async function Ns(e){let t=S(await C("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!Q(null,t))return t;let n=S(await C("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!Q(null,n)?n:null}function Us(e,t){let n=bs(e,t);return n?ce(`cursor_cloud|${n}|${vs(e)??""}`):null}async function Ls(e,t){let n=S(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Ps(n),o=await Ns(n);return ce(`claude_remote|${r}|${o??""}`)}function Ln(e,t){let n=zn(e,t);if(n)return n;let r=xs(t);return r||Vn()}async function Ms(e){let n=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||ys(e);return Fn("sha256").update(n).digest("hex").slice(0,16)}function Hs(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=Hs(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($n(e))try{return Ds(Bn(e,"utf8"))}catch{}}function Rt(e){return ne(e)}function Yn(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{Y(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
|
|
8
|
-
`,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(
|
|
9
|
-
`)}catch(s){let a=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${a}`)}}function
|
|
10
|
-
`,{encoding:"utf8",flag:"wx"})}function
|
|
11
|
-
`)}function
|
|
12
|
-
To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=
|
|
13
|
-
curl -fsSL ${
|
|
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
|
|
14
14
|
Or use npx delivery:
|
|
15
|
-
npx ${
|
|
16
|
-
`,"utf8")}function G(e){if(B(e))try{return JSON.parse(Ys(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function hi(e,t){let n=rr(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 Ei(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 Sr(e,t){let n=y(e,Ue),r=G(n),o=hi(r,t);return t.collectorUrl!==void 0||B(n)||!Ei(o)?(X(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function At(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 Si(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 yi(e=process.platform){let t=Si(e),n=[y(t,"managed-settings.json")],r=y(t,"managed-settings.d");try{if(!B(r))return n;let o=zs(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>y(r,s));n.push(...o)}catch{}return n}function Ii(e){if(At(process.env))return!0;let t=j();return[...yi(),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=G(r);return o?At(o.env):!1}catch{return!1}})}function Ri(e){try{let t=G(y(e,".claude","settings.json"));return t?At(t.env):!1}catch{return!1}}function yr(e){return Array.isArray(e)?e:[]}function Ge(e){let t=[],n=r=>!!r&&typeof r=="object"&&Er(r.command);for(let r of yr(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 Ir(e,t){return[...Ge(e),...t]}function bt(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!Er(t.command)):[]}function ki(e,t){return[...bt(e),{command:t}]}function Ci(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 Oi(e){let t={type:"command",command:e,statusMessage:In},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var Ai=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","afterShellExecution","beforeReadFile","afterFileEdit","beforeMCPExecution","subagentStart","subagentStop","stop"],xi=[];function Ti(e,t=xi){let n={...e};for(let r of t){if(!(r in n))continue;let o=bt(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function vi(e,t,n={}){let r=y(e,".claude/settings.json"),o=vt(t,"claude"),s=G(r)??{};if(Ii(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]),yr(u[f]).length===0&&delete u[f];Object.keys(u).length===0?delete s.hooks:s.hooks=u,X(r,s)}return!1}let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=Ci(o),l={...i};for(let[u,f]of Object.entries(c))l[u]=Ir(i[u],f);return s.hooks=l,X(r,s),!0}function bi(e,t){let n=y(e,".cursor/hooks.json"),r=vt(t,"cursor"),o=G(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},a=Ti({...s});for(let i of Ai)a[i]=ki(a[i],r);X(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:a})}function wi(e,t){let n=y(e,".codex/hooks.json"),r=vt(t,"codex"),o=G(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},a=Oi(r),i={...s};for(let[c,l]of Object.entries(a))i[c]=Ir(s[c],l);X(n,{...o,hooks:i})}function Pi(e){let t=y(e,".claude/settings.json"),n=G(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,X(t,n),d(`Removed ev-ai hooks from ${t}`))}function Ni(e){let t=y(e,".cursor/hooks.json"),n=G(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=bt(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){Be(t,{force:!0}),d(`Removed ${t}`);return}X(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function Ui(e){let t=y(e,".codex/hooks.json"),n=G(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){Be(t,{force:!0}),d(`Removed ${t}`);return}X(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function wt(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)&&or(e,t)}async function Rr(e={}){let t=oi(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??fr();wt(process.platform,process.arch,{requireBinaryArch:s==="binary"});let a=e.cwd??process.cwd(),i=await $(a),{command:c,hookPath:l,strategy:u}=_i(i,j(),s),{installationId:f,storePath:g}=await Fe(i,{overrideId:e.installationId}),{manifestPath:m,wrote:_}=Sr(i,e),E=[];return n?d("Skipped Claude hook \u2014 --no-claude"):vi(i,c,{force:e.force})?(E.push("Claude"),e.force&&Ri(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"):(bi(i,c),E.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(wi(i,c),E.push("Codex")),d(`Installed hook (${u}) at ${l}`),d(`Installation identity ${f} at ${g}`),_&&m?d(`Shared manifest written to ${m}`):d("Using package default collector config (no shared manifest file needed)"),d(E.length>0?`Wired ${E.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)."),_&&m&&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:m,installationStorePath:g,strategy:u}}async function kr(e=process.cwd()){wt(process.platform,process.arch,{requireBinaryArch:!0});let t=await $(e),{projectPath:n,globalPath:r}=mi(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function Cr(e={}){let t=ri(e);e.collectorUrl=t,wt(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await $(n),{manifestPath:o,wrote:s}=Sr(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[()=>Pi(e),()=>Ni(e),()=>Ui(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function Ar(e=process.cwd()){let t=await $(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 xr(e=process.cwd()){let t=await $(e);Or(t);for(let n of $e){let r=y(t,n);if(B(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}`)}}}import{createHash as ia}from"node:crypto";import{existsSync as aa,mkdirSync as ca,readdirSync as la,readFileSync as Br,unlinkSync as jr,writeFileSync as ua}from"node:fs";import{homedir as Gr}from"node:os";import{join as Ht}from"node:path";var Tr=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,vr=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Li=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,Mi=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"]),Hi=new Set(["read","read_file","view"]),Di=new Set(["bash","shell","zsh"]);function Fi(e){let t=e.replace(/\\/g,"/");return Tr.exec(t)?.[1]??null}function $i(e){let t=e.replace(/\\/g,"/"),r=vr.exec(t)?.[1];return r?r.toLowerCase():null}function Pt(e){return Fi(e)??$i(e)}function Bi(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 Ke(e){if(typeof e=="string")try{let t=JSON.parse(e);return Ke(t)}catch{return null}return!e||typeof e!="object"?null:Bi(e)}function ji(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Gi(e){let t=e.replace(/\\/g,"/"),n=Tr.exec(t);if(n?.[1])return n[1];let o=vr.exec(t)?.[1];return o?o.toLowerCase():null}function Ki(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function br(e){let t=Ki(e).toLowerCase();if(Hi.has(t)){let n=Ke(e.tool_input)??ee(e.file_path),r=n?Pt(n):null;if(r)return r}if(Di.has(t)){let n=ji(e.tool_input)??ee(e.command);return n?Gi(n):null}return null}function Ji(e){let t=new Set,n=[];for(let r of e.matchAll(Li)){let o=r[1]?.toLowerCase();!o||t.has(o)||Mi.has(o)||(t.add(o),n.push(o))}return n}function Vi(e){return ee(e.prompt)}function wr(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=Vi(e);return n?Ji(n):[]}function Nt(e){return e!==void 0&&Rn.includes(e)}function Je(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ve(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=Je(e,a);t=c.value,a=c.next;continue}if(i.startsWith("--runner=")){t=i.slice(9);continue}if(i==="--url"){let c=Je(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=Je(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=Je(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:Nt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Ut(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Ne(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=pe(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return me(n)}function Pr(e,t){if(p(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Wi(){return!!(k("CURSOR_VERSION")??k("CURSOR_PROJECT_DIR"))}function Lt(e,t,n){return e!=="claude"&&e!=="codex"?!1:Pr(t,n)?!0:Wi()}function Re(e,t,n,r){if(Pr(e,t))return"cursor";if(Nt(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"),Nt(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 zi(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 Nr(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Ur(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=Re(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:a,runnerPlatform:i}}var Yi=["session_start","session_end","tool_invoked","skill_invoked"];function Xi(e){return Yi.includes(e)}function Lr(e,t){return e&&Xi(e)?e:zi(t.toLowerCase())}var qi={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Zi(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Mr(e,t=""){let n=p(e,"tool_name")||p(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Zi(n)&&(n=`MCP:${n}`):n=qi[r]??null;let o=e.tool_input,a=(o&&typeof o=="object"?ee(o.skill)||ee(o.skill_name):"")||p(e,"skill_name")||null,i=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;return a??=br(i),{toolName:n,skillName:a}}var Qi=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Hr(e){for(let t of["subagent_type","agent_type"]){let n=p(e,t);if(n&&Qi.test(n))return n}return null}function Dr(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 ea="error",ta="interrupted",na="permission_denied",ra=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Mt(e){return ra.test(e)?e:null}function oa(e){for(let t of["failure_type","error_type"]){let n=Mt(p(e,t));if(n)return n}return null}function Fr(e,t){return te(e,"is_interrupt")===!0?ta:t.toLowerCase()==="permissiondenied"?na:oa(e)??ea}function sa(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 $r(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:sa(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var Kr=3e4,da="claims",fa=!0,pa=100,ma=new Set(["sessionstart","sessionend","stopfailure"]),ga=["tool_name","tool","command","file_path","url"];function _a(e=Gr()){return Ht(Ie(e),da)}function Jr(e){let t=e.split(`
|
|
17
|
-
`,1)[0]??"";return Number(t.trim())}function
|
|
18
|
-
`,{encoding:"utf8",flag:"wx"})}catch(o){if(
|
|
19
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cloud cache write failed open: ${r}`)}}function
|
|
20
|
-
`);return O(n)}function
|
|
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 rc(e,t=C){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return nc(n)}function oc(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}async function sc(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 V(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 ic(e=process.env){let t=V(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=V(n,null,"github",n);if(r)return r;let o=h(e.GITLAB_USER_LOGIN),s=V(h(e.GITLAB_USER_NAME)??o,h(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let a=V(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=V(h(e.BUILDKITE_BUILD_CREATOR),i,"buildkite",i);if(c)return c;let l=V(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),f=V(u,null,"circleci",u);if(f)return f;let g=h(e.CODEBUILD_INITIATOR),m=V(g,null,"codebuild",g);if(m)return m;let _=V(h(e.DRONE_COMMIT_AUTHOR)??h(e.DRONE_COMMIT_AUTHOR_NAME),h(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",h(e.DRONE_COMMIT_AUTHOR));if(_)return _;if(eo(e.CLAUDE_CODE_REMOTE)||eo(e.CURSOR_AGENT)){let E=h(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:E&&!Q(null,E)?E:null,platform_login:null,identity_source:"cloud"}}return null}function Jt(e){return!!((e.git_user_name??e.git_user_email)&&!Q(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 eo(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function ac(e,t=C,n=process.env){let r=await rc(e,t);if(Jt(r))return{...r,identity_source:"git_config"};let o=oc(n);if(o&&Jt(o))return o;let s=ic(n);if(s&&(s.git_user_name||s.git_user_email||s.platform_login))return s;let a=await sc(e,t);return a&&Jt(a)?a:s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||a||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Ye(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??C,s=e.env??process.env,a=await ac(t,o,s),i=tc(a.git_user_name,a.git_user_email,a.identity_source,a.platform_login),l=(n?Rt(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==i||!l))return{commit:()=>{}};let m=n;return{operator:a,commit:()=>{m&&Yn(m,i,He())}}}function Vt(e){return e?!Rt(e)?.operator_identity_hash:!0}function to(e){return!0}import{existsSync as bc,readFileSync as wc}from"node:fs";import{homedir as Io}from"node:os";import{join as L}from"node:path";import{basename as Tc,join as le,resolve as mo}from"node:path";import{existsSync as no,readdirSync as cc}from"node:fs";import{basename as lc,dirname as uc,relative as dc}from"node:path";var Oe=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(uc(t))}/${lc(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(!no(t))return[];try{return cc(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(no(t))return ae(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 Wt,readFileSync as fc,statSync as pc}from"node:fs";import{basename as oo,join as Ae,relative as so}from"node:path";var zt=2e4,mc=4;function gc(e){return e.length<=zt?e:`${e.slice(0,zt-1)}\u2026`}function _c(e){try{let t=fc(e),n=t.toString("utf8");return{hash:O(t),length:t.length,text:gc(n)}}catch{return null}}var ro={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function hc(e){return e in ro?ro[e]:"UNSPECIFIED"}function Xe(e,t){let n=_c(t.absolutePath);if(!n)return!1;let r=t.name??oo(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=hc(t.kind);return s&&(o.trigger=s),e.push(o)}function Ec(e,t,n){let r=so(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?oo(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;Yt(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:a,extensions:i})}function Yt(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:a,enabled:i,nested:c,extensions:l}=t;if(!(o>mc))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 m=Ae(r,u.name,c);if(Wt(m)){let _=so(n,Ae(r,u.name)).replace(/\\/g,"/");Xe(e,{absolutePath:m,kind:s,origin:a,enabled:i,name:_||u.name});continue}Yt(e,{walkRoot:n,currentDir:Ae(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(u.isDirectory()){Yt(e,{walkRoot:n,currentDir:Ae(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(m=>f.endsWith(m)))continue;let g=Ae(r,u.name);Xe(e,{absolutePath:g,kind:s,origin:a,enabled:i,name:Ec(n,g,!0)})}}function io(e){for(let t of e)if(Wt(t))try{if(pc(t).size>0)return t}catch{continue}return e.find(t=>Wt(t))}function Sc(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 yc(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 Ic(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 yc(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",f=Sc({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:"",m=O(u),_=g?`${s}:${g}:${f}:${m}`:`${s}:${f}:${m}`,E=`${s}|${g}|${f}|${u}`;e.push({kind:"HOOK",name:_,path:o,content_hash:O(E),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...g?{matcher:g}:{},action_kind:f,action_hash:m}})}}}function xe(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||Ic(e,t,r.hooks,n)}var ao={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 Rc,readFileSync as kc}from"node:fs";function Cc(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 co(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=Cc(i);e.push({kind:"MCP_SERVER",name:a,path:s,content_hash:O(`${a}|${c}`),origin:n,enabled:!0,attributes:{transport:c}})}}function lo(e,t,n){if(!Rc(t))return;let r;try{r=kc(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(/^\[/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"),e.push({kind:"MCP_SERVER",name:i,path:o,content_hash:O(`${i}|${f}`),origin:n,enabled:!0,attributes:{transport:f}})}}import{existsSync as Oc,readdirSync as Ac}from"node:fs";import{join as x}from"node:path";var uo=50;function Xt(e,t,n,r){if(!Oc(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(uo,()=>{oe(e,{dir:x(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),oe(e,{dir:x(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),oe(e,{dir:x(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});xe(e,x(t,"hooks","hooks.json"),n),xe(e,x(t,"hooks.json"),n);let a=e.components.length-o,i=s>=uo;return{componentCount:a,expandTruncated:i}}function qt(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 fo(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]??{},f=s[i]===!0,g=i.includes("@")?i.split("@").slice(1).join("@"):"",m=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",E=`plugin:${i}`,T=0,A=!1;for(let P of l)if(typeof P.installPath=="string"&&P.installPath.length>0){let Z=Xt(e,P.installPath,E,f);T+=Z.componentCount,A=A||Z.expandTruncated}qt(e,{pluginKey:i,rowPath:a,enabled:f,scope:_,version:m||void 0,marketplace:g||void 0,componentCount:T,expandTruncated:A,contentHash:O(`${i}|${m}|${_}|${f}|${T}`)})}}function xc(e){let t=e,n="";try{let r=Ac(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}}function po(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 a=o.name,i=x(n,o.name),c=`plugin:${a}`,{componentCount:l,expandTruncated:u}=Xt(e,i,c,!0);qt(e,{pluginKey:a,rowPath:e.homeRel(i),enabled:!0,scope:"local",componentCount:l,expandTruncated:u,contentHash:O(`${a}|local|${l}`)});continue}let s=o.name;for(let a of e.readEntries(x(n,s))){if(!a.isDirectory()||e.truncated)continue;let i=x(n,s,a.name),{installPath:c,version:l}=xc(i),u=`${a.name}@${s}`,f=`plugin:${u}`,{componentCount:g,expandTruncated:m}=Xt(e,c,f,!0);qt(e,{pluginKey:u,rowPath:e.homeRel(c),enabled:!0,scope:"cache",version:l||void 0,marketplace:s,componentCount:g,expandTruncated:m,contentHash:O(`${u}|${l}|${g}`)})}}}function go(e,t,n,r){let o=ao[t];if(!o)return;let s=e.home;for(let i of o.skillRoots)oe(e,{dir:le(s,i),kind:"SKILL",origin:n,enabled:!0,nested:"SKILL.md"});for(let i of o.dirs)oe(e,{dir:le(s,i.dir),kind:i.kind,origin:n,enabled:!0,extensions:i.extensions});let a=io(o.memory.map(i=>le(s,i)));a&&Xe(e,{absolutePath:a,kind:"MEMORY",origin:n,enabled:!0,name:Tc(a)});for(let i of o.hooks)xe(e,le(s,i),n);for(let i of o.mcpJson??[])co(e,le(s,i),n);for(let i of o.mcpToml??[])lo(e,le(s,i),n);r&&(o.plugins==="claude"?fo(e):o.plugins==="cursor"&&po(e))}function Zt(e,t,n){let r=new Oe(t);if(go(r,e,"user",!0),n===void 0||mo(n)===mo(t))return{components:r.components,truncated:r.truncated};let s=new Oe(n,"cwd/");go(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 Qt(e,t,n={}){let r=n.truncated===!0,o=Kt(e),s=new Set(e.map(u=>J(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=J(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=Qr(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 ho=3e5,vc=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function en(e,t,n){let r=new Set(t.map(s=>J(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(J(s.path,s.name))||o.push(s));return o}function tn(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 Eo(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function nn(e,t=ho){let n=[],r=[];for(let u of e)vc.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,g=_o(u)+f;if(a+g<=t){s.push(u),a+=g,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let m=Eo(u),_=_o(m)+f;if(a+_<=t){s.push(m),a+=_,i+=1;continue}}c+=1}return{components:s,textDeferredCount:i,droppedCount:c,textHashesSent:l}}function rn(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Eo(n))}var Pc={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"}},Nc=200,So=200,Uc=["allow","deny","ask"],Lc=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,on="<path>",Mc=new RegExp(`${on}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Hc(e){let t=e.replace(Lc,on).replace(Mc,on);return t.length>So?`${t.slice(0,So)}...`:t}function yo(e){let t=ae(e,{}),n=[];for(let r of Uc)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Hc(o),mode:r});return{model:t.model??"",permissionKeys:n}}var Dc=10,Fc=840*60*1e3,$c="self-config-cache.json";function sn(){return k("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Bc(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Fc}var jc={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Gc(e,t=C){let n=jc[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(`
|
|
22
|
-
`)
|
|
23
|
-
`);
|
|
24
|
-
`)
|
|
25
|
-
${
|
|
26
|
-
`);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 Qe(e,t=fetch){let n=await e(),r=el(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 tl(e,t,n){let r=Oo(e);d(`POST event=${e} url=${dt(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 xo(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()},En),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 nl(e,t,n,r=Co,o=Qc){let s=Oo(e),a=Zc(n,s,t),{command:i,args:c}=o();return xo(i,c,a,r,"detached post")}async function To(e,t,n=Co,r=Ao){let{command:o,args:s}=r(Ze,t);return xo(o,s,e,n,"detached work")}async function de(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(!Me(o))return d(`WARN: collector URL blocked (https required): ${dt(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)}
|
|
27
|
-
`,c=k("EV_AI_HOOK_DEBUG");c==="full"?d(`DEBUG envelope=${JSON.stringify(a)}`):c==="1"&&d(`DEBUG summary=${qc(a,Buffer.byteLength(i,"utf8"))}`);let l=process.argv.includes(Ze),u=k("EV_AI_HOOK_SYNC")==="1";return We(n.runnerEvent,n.runnerPlatform)||l||u?tl(e,i,o):(await nl(e,i,o),!1)}import{relative as rl,resolve as et,sep as an}from"node:path";var ol=["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 sl(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:k("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function il(e){let t={};for(let n of ol){let r=te(e,n);r!==void 0&&(t[n]=r)}return t}function al(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=et(e),r=et(t),o=rl(r,n);return!o||o==="."?".":o.startsWith(`..${an}`)||o===".."||et(r,o)!==n?null:o.split(an).join("/")}function cl(e){return typeof e!="string"||e.length===0?null:et(e).split(an).join("/")}function vo(e,t,n){let r=cl(t.cwd);r!==null&&(e.cwd=r);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?al(t.cwd,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function bo(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 ve(e,t,n={}){if(sl(t)){let o={...e};return delete o.cwd,delete o.transcript_path,vo(o,e,n),bo(o,yn)}let r=il(e);return vo(r,e,n),bo(r,Sn)}import{createReadStream as ll}from"node:fs";import{stat as ul}from"node:fs/promises";import{basename as dl,resolve as fl}from"node:path";import{createInterface as pl}from"node:readline";var ml=1024*1024;function gl(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&dl(t).endsWith(".jsonl")}async function wo(e){if(!e||!gl(e))return null;try{let t=fl(e),n=await ul(t);if(!n.isFile())return null;let r=Math.max(0,n.size-ml),o=[],s=pl({input:ll(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 we(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function tt(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}var _l=new Set([...Object.values(Dt),".github"]);function hl(e,t,n){if(e===null||t===null||n===null||!(/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let o=n.indexOf(":");if(o<=0||o===n.length-1)return;let s=n.slice(o+1),a=s.replaceAll("\\","/").split("/").at(-1);if(!(a===void 0||!_l.has(a)))try{return(0,q.buildComponentReference)({installationRootExternalKey:n,installableKind:q.ComponentKind.INTERFACE,sourcePath:s,nativeKey:t})}catch{return}}function El(...e){for(let t of e)if(t)return t;return null}function M(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 Sl(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 yl(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var se=new Set,be=null;async function Po(e){if(sn())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(se.has(t))return;if(!Vt(n)){se.add(t);return}let r=Se({sessionId:e.sessionId,hostname:ye()});if(to(r)){if(be){await be;return}be=(async()=>{if(se.has(t)||!Vt(n)){se.add(t);return}if(!Xn(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,g]=await Promise.allSettled([Ce(a),ht(),Ft(r),Et(),Ye({gitRoot:a,installationStorePath:n,forceResend:!1})]),m=M(c,null,"gitSnapshot"),_=M(l,"","detectVirt"),E=M(u,null,"probeCloud"),T=M(f,{},"hostEnv"),A=M(g,{commit:()=>{}},"resolveOperatorForSend");await Pe(e,a,m);let P={identity:{host:ye(),context:r,virt:_||null,cloud:E,git:m},host_env:T,env_vars:Gt(),self_config:yl(i,A.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await de("session_start",P,we(e),ue,e.manifest.collectorUrl,s),o&&(A.commit(),se.add(t))}finally{qn(n)}})().finally(()=>{be=null}),await be}}async function Pe(e,t,n){try{let r=n===void 0?await Ce(t):n;e.platformAgentId=await zr(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 Il(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Se({sessionId:e.sessionId,hostname:ye()}),o=String(e.runnerPlatform),[s,a,i,c,l,u]=await Promise.allSettled([Ce(n),ht(),Ft(r),Et(),jt(e.manifest.manifest,n,o),Ro(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),f=M(s,null,"gitSnapshot"),g=M(a,"","detectVirt"),m=M(i,null,"probeCloud"),_=M(c,{},"hostEnv"),E=M(l,[],"mcpDeclared"),T=M(u,Sl(o),"selfConfig"),A=T.config;await Pe(e,n,f);let P=p(e.hookInput,"model");P&&(A.model=P);let Z={identity:{host:ye(),context:r,virt:g||null,cloud:m,git:f},host_env:_,env_vars:Gt(),mcp:{declared:E},self_config:A,run_meta:{trigger:e.hookSource||"startup"},hook_input:ve(e.hookInput,e.manifest.manifest,tt(e))};await de("session_start",Z,we(e),ue,e.manifest.collectorUrl,t)&&(T.commit(),se.add(e.manifest.installationId))}async function Rl(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Pe(e,n);let r=El(p(e.hookInput,"status"),p(e.hookInput,"stop_reason"),p(e.hookInput,"reason"),Mt(p(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await wo(p(e.hookInput,"transcript_path")):null,s=ve(e.hookInput,e.manifest.manifest,tt(e));o&&(s.model=o),await de("session_end",{status:r,...o?{model:o}:{},hook_input:s},we(e),ue,e.manifest.collectorUrl,t)}async function kl(e){let t=Date.now(),n=wr(e.hookInput);if(n.length===0)return;await Po(e);let{gitRoot:r}=e.manifest;await Pe(e,r);let o=ve(e.hookInput,e.manifest.manifest,tt(e)),s=we(e),a=Ke(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;await Promise.all(n.map(u=>{let f;if(l!==null&&Pt(l)?.toLowerCase()===u.toLowerCase()&&e.platformAgentId){let g=(0,q.nativeKeyForSkillPath)(l);if(g!==null)try{f=(0,q.buildComponentReference)({installationRootExternalKey:e.platformAgentId,installableKind:q.ComponentKind.SKILL,sourcePath:l,nativeKey:g})}catch{f=void 0}}return de("tool_invoked",{tool_name:"Skill",skill_name:u,...f===void 0?{}:{component_reference:f},success:null,duration_ms:null,hook_input:o},s,ue,e.manifest.collectorUrl,t)}))}async function Cl(e){let t=Date.now();await Po(e);let{gitRoot:n}=e.manifest;await Pe(e,n);let{toolName:r,skillName:o}=Mr(e.hookInput,e.runnerEvent),s=Dr(e.hookInput),a=Nr(e.runnerEvent),i=a===!1?Fr(e.hookInput,e.runnerEvent):null,c=await jt(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=$r(r,c.map(m=>m.name)),f=hl(r,l,e.platformAgentId),g=Hr(e.hookInput);await de("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}:{},...g?{subagent_type:g}:{},hook_input:ve(e.hookInput,e.manifest.manifest,tt(e))},we(e),ue,e.manifest.collectorUrl,t)}async function No(e){switch(e.internalEvent){case"session_start":await Il(e);return;case"session_end":await Rl(e);return;case"skill_invoked":await kl(e);return;case"tool_invoked":await Cl(e);return;default:return}}function Uo(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function Lo(e,t,n,r){let o=t??await mt(ut),s=w(o,{}),a=p(s,"session_id")||p(s,"conversation_id"),i=await nr(process.cwd(),{sessionId:a});if(!i)return;r&&(i.collectorUrl=r);let c=Ur(s,i.manifest.platform,n),l=Lr(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(Uo(l)){d(`WARN: unsupported internal event '${l}'`);return}await No(u)}function Ol(e,t){if(k("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ve(e),r=w(t,{}),o=n.event??(p(r,"hook_event_name")||p(r,"event")),s=Re(r,o,void 0,n.runner);return We(o,s)}async function Mo(e=process.argv.slice(2)){if(e[0]===Te){try{await Qe(ge)}catch{}return 0}if(e[0]===Ze){try{let t=Ve(e.slice(1)),n=await ge(),r=w(n,{}),o=t.event??(p(r,"hook_event_name")||p(r,"event"));if(Lt(t.runner,r,o))return 0;await Lo(t.event,n,t.runner,Ut(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 mt(ut),n=Ve(e),r=Ut(n),o=w(t,{}),s=n.event??(p(o,"hook_event_name")||p(o,"event"));if(Lt(n.runner,o,s)||!Wr(o,s,n.runner))return 0;Ol(e,t)?await Lo(n.event,t,n.runner,r):await To(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{wn()}return 0}function nt(){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 Ho(e){return e.includes("--help")||e.includes("-h")}async function bl(e=process.argv.slice(2)){let[t,...n]=e;if(t===Te){try{await Qe(ge)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${F}
|
|
28
|
-
`)
|
|
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,22 +1,27 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from 'node:module';
|
|
2
2
|
const require = __createRequire(import.meta.url);
|
|
3
3
|
|
|
4
|
-
var
|
|
5
|
-
`)}function K(e,t){no(Xt(e),{recursive:!0});let n=qt(Xt(e),`.${io(e)}.${process.pid}.${to(4).toString("hex")}.tmp`);try{so(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"){Yt(e),Wt(n,e);return}throw r}}catch(r){try{Yt(n)}catch{}throw r}}function ye(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Qt(){process.stdout.write('{"continue":true}')}function y(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Ve(){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 ze(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 v(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 C(e,t,n=3e3,r={}){let o=await v(e,t,n,r);return o.ok?o.stdout:""}async function Je(e=process.cwd()){let t=await v("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(y("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;g(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=y("CURSOR_PROJECT_DIR")??y("CLAUDE_PROJECT_DIR");if(n&&je(n)){let r=await v("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 We(e=process.cwd()){return(await Je(e)).root}function w(e,t){try{return JSON.parse(e)}catch{return t}}var Ge=new Map;function q(e,t){let n=Ge.get(e);if(n!==void 0)return n;try{let r=w(oo(e,"utf8"),t);return Ge.set(e,r),r}catch{return Ge.set(e,t),t}}function z(e){return typeof e=="string"?e:""}function J(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 f(e,t){let n=J(e,t);return typeof n=="string"?n:""}var M=500;function oe(e,t=2){if(!je(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=ro(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=qt(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:ao(e,l),size:Zt(l).size})}catch{continue}if(n.length>=M){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function se(e){return je(e)?{present:!0,size:Zt(e).size}:{present:!1,size:0}}function ie(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var fo=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function po(e){return fo.some(t=>!!I(t,e))}function mo(e){if(I("KUBERNETES_SERVICE_HOST",e)||ie(I("REMOTE_CONTAINERS",e))||ie(I("DEVCONTAINER",e)))return!0;try{if(co("/.dockerenv")||lo("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function tn(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!I(t,e))}function go(e,t=process.platform){return tn(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!I(n,e)):!1}function _o(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function ho(e){return e==="linux"}function I(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return y(e)}function Eo(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!So(I("CURSOR_VERSION",n))}function So(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Ye(e){if(_o(e.sessionId))return!0;let t=e.hostname??en(),n=e.osUser??nn(e.env);return Eo(t,n,e.env)}function Io(e){return ie(I("CURSOR_AGENT",e.env))?!0:Ye(e)}function Ro(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(I("TERM",e)??I("TERM_PROGRAM",e))||(I("SSH_TTY",e)??I("SSH_CONNECTION",e))||(I("__CFBundleIdentifier",e)??I("XPC_SERVICE_NAME",e))||tn(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!I(t,e))||I("SESSIONNAME",e))}function ae(e={}){let t=e.env;if(I("GITHUB_ACTIONS",t))return"github_actions";if(ie(I("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!go(t,n)&&Io(e)&&(ie(I("CURSOR_AGENT",t))||ho(n)))return"cursor_cloud";if(I("CODESPACES",t)||I("CODESPACE_NAME",t))return"codespaces";if(I("GITLAB_CI",t))return"gitlab_ci";if(po(t))return"managed";let r=I("CI",t);return r&&r!=="false"&&r!=="0"?"managed":mo(t)?"container":Ro(t)?"interactive":"unknown"}async function Xe(){return await C("systemd-detect-virt",[],1e3)}function nn(e=process.env,t=uo){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 Ze(){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=nn(),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 ce(){return en()}var Ao="installation.json",To="cloud-bootstrap.lock",Oo=6e4;function pn(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function le(e=Qe()){return et(e,".ev-ai","agent-hook")}function ko(e=Qe()){return et(le(e),Ao)}function mn(e){return et(Ce(e),To)}function gn(){return yo(8).toString("hex")}function Q(e){return cn("sha256").update(e).digest("hex").slice(0,16)}function E(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function _n(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function xo(e=process.env){let t=E(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!_n(t)){g(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function hn(e,t){return e&&_n(e)?e:(e&&g(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),xo(t))}function No(e){return/^[0-9a-f]{16}$/.test(e)}function wo(e=process.env){if(E(e.GITHUB_ACTIONS)){let t=E(e.GITHUB_REPOSITORY_ID)??E(e.GITHUB_REPOSITORY),n=E(e.GITHUB_ACTOR)??E(e.GITHUB_TRIGGERING_ACTOR)??E(e.GITHUB_USER);if(t&&n)return Q(`github_actions|${t}|${n}`)}if(E(e.CODESPACES)||E(e.CODESPACE_NAME)){let t=E(e.CODESPACE_NAME);if(t)return Q(`codespaces|${t}`);let n=E(e.GITHUB_REPOSITORY_ID)??E(e.GITHUB_REPOSITORY),r=E(e.GITHUB_USER)??E(e.GITHUB_ACTOR);if(n&&r)return Q(`codespaces|${n}|${r}`)}if(E(e.GITLAB_CI)){let t=E(e.CI_PROJECT_ID)??E(e.CI_PROJECT_PATH),n=E(e.GITLAB_USER_LOGIN)??E(e.GITLAB_USER_EMAIL)??E(e.GITLAB_USER_NAME);if(t&&n)return Q(`gitlab|${t}|${n}`)}return null}var bo="cursoragent@cursor.com";function Uo(e){let t=E(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===bo?null:t}function vo(e,t){return E(e.CURSOR_PROJECT_DIR)??E(e.CLAUDE_PROJECT_DIR)??t}function Po(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Lo(e){let t=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Po(t):e}async function Mo(e){let t=E(await C("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!V(null,t))return t;let n=E(await C("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!V(null,n)?n:null}function Do(e,t){let n=vo(e,t);return n?Q(`cursor_cloud|${n}|${Uo(e)??""}`):null}async function Ho(e,t){let n=E(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Lo(n),o=await Mo(n);return Q(`claude_remote|${r}|${o??""}`)}function rn(e,t){let n=hn(e,t);if(n)return n;let r=wo(t);return r||gn()}async function Fo(e){let n=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Co(e);return cn("sha256").update(n).digest("hex").slice(0,16)}function Bo(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 $o(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Bo(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 W(e){if(ln(e))try{return $o(un(e,"utf8"))}catch{}}function tt(e){return W(e)}function En(e,t,n){let r=W(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{K(e,`${JSON.stringify(o,null,2)}
|
|
6
|
-
`)}catch(s){let
|
|
7
|
-
`,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(
|
|
8
|
-
`)}catch(s){let
|
|
9
|
-
`,{encoding:"utf8",flag:"wx"})}function
|
|
10
|
-
`)}function
|
|
11
|
-
`,1)[0]??"";return Number(t.trim())}function
|
|
12
|
-
`,{encoding:"utf8",flag:"wx"})}catch(o){if(
|
|
13
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);
|
|
14
|
-
`);return
|
|
15
|
-
`)){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 pi(e,t=C){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return fi(n)}function mi(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}async function gi(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 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 _i(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 i=B(h(e.BUILD_REQUESTEDFOR),h(e.BUILD_REQUESTEDFOREMAIL),"azure_devops",h(e.BUILD_REQUESTEDFORID));if(i)return i;let a=h(e.BUILDKITE_BUILD_CREATOR_EMAIL),c=B(h(e.BUILDKITE_BUILD_CREATOR),a,"buildkite",a);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),p=B(m,null,"codebuild",m);if(p)return p;let _=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(_)return _;if(nr(e.CLAUDE_CODE_REMOTE)||nr(e.CURSOR_AGENT)){let S=h(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:S&&!V(null,S)?S:null,platform_login:null,identity_source:"cloud"}}return null}function _t(e){return!!((e.git_user_name??e.git_user_email)&&!V(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 nr(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function hi(e,t=C,n=process.env){let r=await pi(e,t);if(_t(r))return{...r,identity_source:"git_config"};let o=mi(n);if(o&&_t(o))return o;let s=_i(n);if(s&&(s.git_user_name||s.git_user_email||s.platform_login))return s;let i=await gi(e,t);return i&&_t(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 we(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??C,s=e.env??process.env,i=await hi(t,o,s),a=di(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?tt(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let p=n;return{operator:i,commit:()=>{p&&En(p,a,ye())}}}function ht(e){return e?!tt(e)?.operator_identity_hash:!0}function rr(e){return!0}import{existsSync as Bi,readFileSync as $i}from"node:fs";import{homedir as yr}from"node:os";import{join as P}from"node:path";import{basename as Hi,join as ee,resolve as gr}from"node:path";import{existsSync as or,readdirSync as Ei}from"node:fs";import{basename as Si,dirname as Ii,relative as Ri}from"node:path";var pe=class{constructor(t,n=""){this.home=t;this.pathPrefix=n}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=Ri(this.home,t).replace(/\\/g,"/"),r=!n||n.startsWith("..")?`external/${A(Ii(t))}/${Si(t)}`:n;return this.pathPrefix?`${this.pathPrefix}${r}`:r}get atGlobalCap(){return this.truncated||this.components.length>=M}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!or(t))return[];try{return Ei(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(or(t))return q(t,n)}push(t){return this.components.length>=M?(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 Et,readFileSync as yi,statSync as Ci}from"node:fs";import{basename as ir,join as me,relative as ar}from"node:path";var St=2e4,Ai=4;function Ti(e){return e.length<=St?e:`${e.slice(0,St-1)}\u2026`}function Oi(e){try{let t=yi(e),n=t.toString("utf8");return{hash:A(t),length:t.length,text:Ti(n)}}catch{return null}}var sr={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function ki(e){return e in sr?sr[e]:"UNSPECIFIED"}function be(e,t){let n=Oi(t.absolutePath);if(!n)return!1;let r=t.name??ir(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=ki(t.kind);return s&&(o.trigger=s),e.push(o)}function xi(e,t,n){let r=ar(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?ir(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:i,extensions:a}=t;It(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function It(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Ai))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=me(r,u.name,c);if(Et(p)){let _=ar(n,me(r,u.name)).replace(/\\/g,"/");be(e,{absolutePath:p,kind:s,origin:i,enabled:a,name:_||u.name});continue}It(e,{walkRoot:n,currentDir:me(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){It(e,{walkRoot:n,currentDir:me(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(p=>d.endsWith(p)))continue;let m=me(r,u.name);be(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:xi(n,m,!0)})}}function cr(e){for(let t of e)if(Et(t))try{if(Ci(t).size>0)return t}catch{continue}return e.find(t=>Et(t))}function Ni(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 wi(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 bi(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 wi(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",d=Ni({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=A(u),_=m?`${s}:${m}:${d}:${p}`:`${s}:${d}:${p}`,S=`${s}|${m}|${d}|${u}`;e.push({kind:"HOOK",name:_,path:o,content_hash:A(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:d,action_hash:p}})}}}function ge(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||bi(e,t,r.hooks,n)}var lr={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 Ui,readFileSync as vi}from"node:fs";function Pi(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 ur(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=Pi(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:A(`${i}|${c}`),origin:n,enabled:!0,attributes:{transport:c}})}}function dr(e,t,n){if(!Ui(t))return;let r;try{r=vi(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:A(`${a}|${d}`),origin:n,enabled:!0,attributes:{transport:d}})}}import{existsSync as Li,readdirSync as Mi}from"node:fs";import{join as O}from"node:path";var fr=50;function Rt(e,t,n,r){if(!Li(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(fr,()=>{Y(e,{dir:O(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Y(e,{dir:O(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Y(e,{dir:O(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});ge(e,O(t,"hooks","hooks.json"),n),ge(e,O(t,"hooks.json"),n);let i=e.components.length-o,a=s>=fr;return{componentCount:i,expandTruncated:a}}function yt(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 pr(e){let t=O(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(O(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,m=a.includes("@")?a.split("@").slice(1).join("@"):"",p=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,k=0,T=!1;for(let b of l)if(typeof b.installPath=="string"&&b.installPath.length>0){let j=Rt(e,b.installPath,S,d);k+=j.componentCount,T=T||j.expandTruncated}yt(e,{pluginKey:a,rowPath:i,enabled:d,scope:_,version:p||void 0,marketplace:m||void 0,componentCount:k,expandTruncated:T,contentHash:A(`${a}|${p}|${_}|${d}|${k}`)})}}function Di(e){let t=e,n="";try{let r=Mi(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=O(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=O(e,s),n=s)}}catch{}return{installPath:t,version:n}}function mr(e){let t=[{base:O(e.home,".cursor/plugins/local"),scope:"local"},{base:O(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=O(n,o.name),c=`plugin:${i}`,{componentCount:l,expandTruncated:u}=Rt(e,a,c,!0);yt(e,{pluginKey:i,rowPath:e.homeRel(a),enabled:!0,scope:"local",componentCount:l,expandTruncated:u,contentHash:A(`${i}|local|${l}`)});continue}let s=o.name;for(let i of e.readEntries(O(n,s))){if(!i.isDirectory()||e.truncated)continue;let a=O(n,s,i.name),{installPath:c,version:l}=Di(a),u=`${i.name}@${s}`,d=`plugin:${u}`,{componentCount:m,expandTruncated:p}=Rt(e,c,d,!0);yt(e,{pluginKey:u,rowPath:e.homeRel(c),enabled:!0,scope:"cache",version:l||void 0,marketplace:s,componentCount:m,expandTruncated:p,contentHash:A(`${u}|${l}|${m}`)})}}}function _r(e,t,n,r){let o=lr[t];if(!o)return;let s=e.home;for(let a of o.skillRoots)Y(e,{dir:ee(s,a),kind:"SKILL",origin:n,enabled:!0,nested:"SKILL.md"});for(let a of o.dirs)Y(e,{dir:ee(s,a.dir),kind:a.kind,origin:n,enabled:!0,extensions:a.extensions});let i=cr(o.memory.map(a=>ee(s,a)));i&&be(e,{absolutePath:i,kind:"MEMORY",origin:n,enabled:!0,name:Hi(i)});for(let a of o.hooks)ge(e,ee(s,a),n);for(let a of o.mcpJson??[])ur(e,ee(s,a),n);for(let a of o.mcpToml??[])dr(e,ee(s,a),n);r&&(o.plugins==="claude"?pr(e):o.plugins==="cursor"&&mr(e))}function Ct(e,t,n){let r=new pe(t);if(_r(r,e,"user",!0),n===void 0||gr(n)===gr(t))return{components:r.components,truncated:r.truncated};let s=new pe(n,"cwd/");_r(s,e,"cwd",!1);let i=[...r.components,...s.components],a=r.truncated||s.truncated||i.length>M;return{components:i.slice(0,M),truncated:a}}function At(e,t,n={}){let r=n.truncated===!0,o=gt(e),s=new Set(e.map(u=>F(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=F(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=tr(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 Er=3e5,Fi=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Tt(e,t,n){let r=new Set(t.map(s=>F(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(F(s.path,s.name))||o.push(s));return o}function Ot(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 hr(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Sr(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function kt(e,t=Er){let n=[],r=[];for(let u of e)Fi.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,m=hr(u)+d;if(i+m<=t){s.push(u),i+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let p=Sr(u),_=hr(p)+d;if(i+_<=t){s.push(p),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function xt(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Sr(n))}var Ki={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"}},Gi=200,Ir=200,ji=["allow","deny","ask"],Vi=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Nt="<path>",zi=new RegExp(`${Nt}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Ji(e){let t=e.replace(Vi,Nt).replace(zi,Nt);return t.length>Ir?`${t.slice(0,Ir)}...`:t}function Rr(e){let t=q(e,{}),n=[];for(let r of ji)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 Wi=10,Yi=840*60*1e3,Xi="self-config-cache.json";function wt(){return y("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Zi(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Yi}var qi={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Qi(e,t=C){let n=qi[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(`
|
|
16
|
-
`)
|
|
17
|
-
`);
|
|
18
|
-
`)
|
|
19
|
-
${
|
|
20
|
-
`);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 xr(e,t=fetch){let n=await e(),r=ua(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 da(e,t,n){let r=Or(e);g(`POST event=${e} url=${nt(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 g(`POST outcome=ok elapsed_ms=${a} http=${i.status}`),!0;let c=(await i.text()).slice(0,200).replace(/[\n\r]/g,"");return g(`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 g(`POST outcome=fail elapsed_ms=${a} http=000 body=${c}`),!1}}async function Nr(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){g(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},jt),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 g(`WARN: ${o} spawn failed open: ${i}`),null}}async function fa(e,t,n,r=Tr,o=la){let s=Or(e),i=ca(n,s,t),{command:a,args:c}=o();return Nr(a,c,i,r,"detached post")}async function wr(e,t,n=Tr,r=kr){let{command:o,args:s}=r(ve,t);return Nr(o,s,e,n,"detached work")}async function ne(e,t,n,r,o,s){if(!o)return g("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Ae(o))return g(`WARN: collector URL blocked (https required): ${nt(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)}
|
|
21
|
-
`,c=y("EV_AI_HOOK_DEBUG");c==="full"?g(`DEBUG envelope=${JSON.stringify(i)}`):c==="1"&&g(`DEBUG summary=${aa(i,Buffer.byteLength(a,"utf8"))}`);let l=process.argv.includes(ve),u=y("EV_AI_HOOK_SYNC")==="1";return xe(n.runnerEvent,n.runnerPlatform)||l||u?da(e,a,o):(await fa(e,a,o),!1)}import{relative as pa,resolve as Pe,sep as vt}from"node:path";var ma=["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 ga(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:y("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function _a(e){let t={};for(let n of ma){let r=J(e,n);r!==void 0&&(t[n]=r)}return t}function ha(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Pe(e),r=Pe(t),o=pa(r,n);return!o||o==="."?".":o.startsWith(`..${vt}`)||o===".."||Pe(r,o)!==n?null:o.split(vt).join("/")}function Ea(e){return typeof e!="string"||e.length===0?null:Pe(e).split(vt).join("/")}function br(e,t,n){let r=Ea(t.cwd);r!==null&&(e.cwd=r);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?ha(t.cwd,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function Ur(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 _e(e,t,n={}){if(ga(t)){let o={...e};return delete o.cwd,delete o.transcript_path,br(o,e,n),Ur(o,zt)}let r=_a(e);return br(r,e,n),Ur(r,Vt)}import{createReadStream as Sa}from"node:fs";import{stat as Ia}from"node:fs/promises";import{basename as Ra,resolve as ya}from"node:path";import{createInterface as Ca}from"node:readline";var Aa=1024*1024;function Ta(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Ra(t).endsWith(".jsonl")}async function vr(e){if(!e||!Ta(e))return null;try{let t=ya(e),n=await Ia(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Aa),o=[],s=Ca({input:Sa(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 Ee(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function Le(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}var Oa=new Set([...Object.values(lt),".github"]);function ka(e,t,n){if(e===null||t===null||n===null||!(/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let o=n.indexOf(":");if(o<=0||o===n.length-1)return;let s=n.slice(o+1),i=s.replaceAll("\\","/").split("/").at(-1);if(!(i===void 0||!Oa.has(i)))try{return(0,G.buildComponentReference)({installationRootExternalKey:n,installableKind:G.ComponentKind.INTERFACE,sourcePath:s,nativeKey:t})}catch{return}}function xa(...e){for(let t of e)if(t)return t;return null}function L(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return g(`WARN: ${n} failed open: ${r}`),t}function Na(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 wa(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var X=new Set,he=null;async function Pr(e){if(wt())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(X.has(t))return;if(!ht(n)){X.add(t);return}let r=ae({sessionId:e.sessionId,hostname:ce()});if(rr(r)){if(he){await he;return}he=(async()=>{if(X.has(t)||!ht(n)){X.add(t);return}if(!Sn(n)){X.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,d,m]=await Promise.allSettled([fe(i),Xe(),ut(r),Ze(),we({gitRoot:i,installationStorePath:n,forceResend:!1})]),p=L(c,null,"gitSnapshot"),_=L(l,"","detectVirt"),S=L(u,null,"probeCloud"),k=L(d,{},"hostEnv"),T=L(m,{commit:()=>{}},"resolveOperatorForSend");await Se(e,i,p);let b={identity:{host:ce(),context:r,virt:_||null,cloud:S,git:p},host_env:k,env_vars:mt(),self_config:wa(a,T.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await ne("session_start",b,Ee(e),te,e.manifest.collectorUrl,s),o&&(T.commit(),X.add(t))}finally{In(n)}})().finally(()=>{he=null}),await he}}async function Se(e,t,n){try{let r=n===void 0?await fe(t):n;e.platformAgentId=await Xn(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);g(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function ba(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=ae({sessionId:e.sessionId,hostname:ce()}),o=String(e.runnerPlatform),[s,i,a,c,l,u]=await Promise.allSettled([fe(n),Xe(),ut(r),Ze(),pt(e.manifest.manifest,n,o),Cr(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),d=L(s,null,"gitSnapshot"),m=L(i,"","detectVirt"),p=L(a,null,"probeCloud"),_=L(c,{},"hostEnv"),S=L(l,[],"mcpDeclared"),k=L(u,Na(o),"selfConfig"),T=k.config;await Se(e,n,d);let b=f(e.hookInput,"model");b&&(T.model=b);let j={identity:{host:ce(),context:r,virt:m||null,cloud:p,git:d},host_env:_,env_vars:mt(),mcp:{declared:S},self_config:T,run_meta:{trigger:e.hookSource||"startup"},hook_input:_e(e.hookInput,e.manifest.manifest,Le(e))};await ne("session_start",j,Ee(e),te,e.manifest.collectorUrl,t)&&(k.commit(),X.add(e.manifest.installationId))}async function Ua(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Se(e,n);let r=xa(f(e.hookInput,"status"),f(e.hookInput,"stop_reason"),f(e.hookInput,"reason"),at(f(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await vr(f(e.hookInput,"transcript_path")):null,s=_e(e.hookInput,e.manifest.manifest,Le(e));o&&(s.model=o),await ne("session_end",{status:r,...o?{model:o}:{},hook_input:s},Ee(e),te,e.manifest.collectorUrl,t)}async function va(e){let t=Date.now(),n=vn(e.hookInput);if(n.length===0)return;await Pr(e);let{gitRoot:r}=e.manifest;await Se(e,r);let o=_e(e.hookInput,e.manifest.manifest,Le(e)),s=Ee(e),i=Te(e.hookInput.tool_input),a=r.replaceAll("\\","/").replace(/\/$/,""),c=i?.replaceAll("\\","/"),l=c===void 0?null:c.startsWith(`${a}/`)?c.slice(a.length+1):c.startsWith("/")?null:c;await Promise.all(n.map(u=>{let d;if(l!==null&&rt(l)?.toLowerCase()===u.toLowerCase()&&e.platformAgentId){let m=(0,G.nativeKeyForSkillPath)(l);if(m!==null)try{d=(0,G.buildComponentReference)({installationRootExternalKey:e.platformAgentId,installableKind:G.ComponentKind.SKILL,sourcePath:l,nativeKey:m})}catch{d=void 0}}return ne("tool_invoked",{tool_name:"Skill",skill_name:u,...d===void 0?{}:{component_reference:d},success:null,duration_ms:null,hook_input:o},s,te,e.manifest.collectorUrl,t)}))}async function Pa(e){let t=Date.now();await Pr(e);let{gitRoot:n}=e.manifest;await Se(e,n);let{toolName:r,skillName:o}=Hn(e.hookInput,e.runnerEvent),s=Bn(e.hookInput),i=Ln(e.runnerEvent),a=i===!1?$n(e.hookInput,e.runnerEvent):null,c=await pt(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=Kn(r,c.map(p=>p.name)),d=ka(r,l,e.platformAgentId),m=Fn(e.hookInput);await ne("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?{component_reference:d}:{},...m?{subagent_type:m}:{},hook_input:_e(e.hookInput,e.manifest.manifest,Le(e))},Ee(e),te,e.manifest.collectorUrl,t)}async function Lr(e){switch(e.internalEvent){case"session_start":await ba(e);return;case"session_end":await Ua(e);return;case"skill_invoked":await va(e);return;case"tool_invoked":await Pa(e);return;default:return}}function Mr(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{existsSync as Pt,readFileSync as La}from"node:fs";import{dirname as Ma,join as Dr,relative as Da}from"node:path";var Hr=[$t,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Ha(e=process.cwd(),t){let n=y("EV_AI_HOOK_MANIFEST");if(n&&Pt(n))return n;let r=t??await We(e);for(let o of Hr){let s=Dr(r,o);if(Pt(s))return s}for(let o of Hr){let s=Dr(e,o);if(Pt(s))return s}}async function Fa(e,t){let n=t??await We(Ma(e)),r=Da(n,e),o=await v("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(g(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Ba(e){let t=La(e,"utf8");return w(t,{})}function $a(){return{schema_version:2,mcp_servers:[]}}async function Fr(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Je(e),o=await Ha(e,n),s=o?Ba(o):$a();delete s.installation_id;let i=o?await Fa(o,n):!1;s.capture_hook_input==="full"&&o&&i&&(g(`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:a,storePath:c,repoKey:l}=await An(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:a,installationStorePath:c,repoKey:l,collectorUrl:Nn(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}async function Br(e,t,n,r){let o=t??await ze($e),s=w(o,{}),i=f(s,"session_id")||f(s,"conversation_id"),a=await Fr(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=Mn(s,a.manifest.platform,n),l=Dn(e,c.runnerEvent);if(!l){g(`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:a,platformAgentId:a.platformAgentId};if(Mr(l)){g(`WARN: unsupported internal event '${l}'`);return}await Lr(u)}function Ka(e,t){if(y("EV_AI_HOOK_SYNC")==="1")return!0;let n=ke(e),r=w(t,{}),o=n.event??(f(r,"hook_event_name")||f(r,"event")),s=ue(r,o,void 0,n.runner);return xe(o,s)}async function $r(e=process.argv.slice(2)){if(e[0]===Ut){try{await xr(Ve)}catch{}return 0}if(e[0]===ve){try{let t=ke(e.slice(1)),n=await Ve(),r=w(n,{}),o=t.event??(f(r,"hook_event_name")||f(r,"event"));if(it(t.runner,r,o))return 0;await Br(t.event,n,t.runner,st(t))}catch(t){let n=t instanceof Error?t.message:String(t);g(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await ze($e),n=ke(e),r=st(n),o=w(t,{}),s=n.event??(f(o,"hook_event_name")||f(o,"event"));if(it(n.runner,o,s)||!Yn(o,s,n.runner))return 0;Ka(e,t)?await Br(n.event,t,n.runner,r):await wr(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);g(`WARN: hook failed open: ${n}`)}finally{Qt()}return 0}$r().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
|
|
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}
|
|
22
27
|
`),process.exit(1)});
|
package/dist/plugin-hooks.mjs
CHANGED
|
@@ -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.
|
|
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
|
|