@ev-ai/agent-hook 1.0.9 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -2,32 +2,33 @@
2
2
  import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
 
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
5
+ var Ji=Object.create;var hr=Object.defineProperty;var Wi=Object.getOwnPropertyDescriptor;var Vi=Object.getOwnPropertyNames;var Yi=Object.getPrototypeOf,Xi=Object.prototype.hasOwnProperty;var _r=(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 Zi=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var qi=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vi(t))!Xi.call(e,o)&&o!==n&&hr(e,o,{get:()=>t[o],enumerable:!(r=Wi(t,o))||r.enumerable});return e};var Gt=(e,t,n)=>(n=e!=null?Ji(Yi(e)):{},qi(t||!e||!e.__esModule?hr(n,"default",{value:e,enumerable:!0}):n,e));var _t=Zi($=>{"use strict";Object.defineProperty($,"__esModule",{value:!0});$.ComponentKind=void 0;$.userConfigRootFromPath=Il;$.installationRootExternalKey=Al;$.normalizeRepositoryRelativePath=Xo;$.nativeKeyForSkillPath=xl;$.nativeKeyForRulePath=vl;$.nativeKeyForCommandPath=Ol;$.serializeComponentIdentity=qo;$.buildComponentReference=bl;$.validateComponentReference=wl;var gl=_r("node:crypto"),hl=_r("node:path"),_l="cmp1_",Sl=/^cmp1_[A-Za-z0-9_-]{43}$/,El=["/skills/","/skills-cursor/"],yl=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,Rl=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,Cl=[".cursor",".claude",".codex"],kl={".claude.json":".claude",".agents":".codex"};$.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function Il(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>Cl.includes(o));return n||(t.map(o=>kl[o]).find(o=>o!==void 0)??"unknown")}function Al(e,t){return`runtime-install:${e}/${t}`}function ht(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Xo(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=hl.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return ht(n,"sourcePath")}function xl(e){let t=e.replaceAll("\\","/");for(let n of El){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Zo(e,t,n){let r=e.replaceAll("\\","/"),s=t.exec(r)?.[1];if(!s||s.split("/").includes(".."))return null;let i=s.replace(n,"");return i.length>0?i:null}function vl(e){return Zo(e,yl,/\.(mdc|md|rules)$/i)}function Ol(e){return Zo(e,Rl,/\.(md|mdc|toml)$/i)}function Pl(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function qo(e){let t=[ht(e.installationRootExternalKey,"installationRootExternalKey"),ht(e.installableKind,"installableKind"),Xo(e.sourcePath),ht(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(Pl).join("|")}`,"utf8")}function bl(e){let t=(0,gl.createHash)("sha256").update(qo(e)).digest("base64url");return`${_l}${t}`}function wl(e){return Sl.test(e)}});import{realpathSync as Of}from"node:fs";import{resolve as Pf}from"node:path";import{fileURLToPath as bf,pathToFileURL as wf}from"node:url";var Qi="https://hooks.ev-ai.ai";function tt(e,t=Qi){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var nt=".claude/ev-ai-runtime-report.json",Sr="node_modules/@ev-ai/agent-hook/dist/hook.mjs",oe="ev-ai-agent-hook",Er="https://cdn.ev-ai.ai/agent-hook",zt=`current/${oe}`,Jt=`.ev-ai/agent-hook/${oe}`,yr=5e3,Rr=5e3,Wt=3e3;var Vt=3e3,Cr=1500,kr=4*1024,Ir=32*1024,ea=4*1024,Ar=32*1024,X="1.1.0",rt=`@ev-ai/agent-hook@${X}`,xr="ev-ai runtime report",vr=["claude","cursor","codex"];import{chmodSync as ho,cpSync as _o,existsSync as ae,mkdirSync as hn,readFileSync as oc,rmSync as dt,symlinkSync as sc,writeFileSync as ic}from"node:fs";import{homedir as q}from"node:os";import{basename as ac,dirname as _n,isAbsolute as cc,join as A,relative as So,resolve as mo,sep as lc}from"node:path";import{fileURLToPath as uc}from"node:url";var ta=new Set(["localhost","127.0.0.1","[::1]","::1"]),Or=/^[A-Za-z0-9._~-]+$/;function Pr(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 ot(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?ta.has(t.hostname):!1}catch{return!1}}function Ue(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!ot(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=na(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Or.test(n))return`org token must match ${Or.source} (got: ${n})`;if(Pr(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Pr(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Ne(e){return new URL(e).toString()}function na(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 Yt(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 br(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?tt(t):""}import{existsSync as ra,readdirSync as wr}from"node:fs";import{homedir as st}from"node:os";import{join as H}from"node:path";function Tr(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return H(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function Xt(e=process.platform){let t=Tr(e),n=[H(t,"managed-settings.json")],r=H(t,"managed-settings.d");try{if(!ra(r))return n;let o=wr(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>H(r,s));n.push(...o)}catch{}return n}function Zt(e=process.platform,t=st()){return{serverManaged:H(t,".claude","remote-settings.json"),fileBased:Xt(e)}}function oa(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/Cursor";case"win32":return H(process.env.ProgramData??"C:\\ProgramData","Cursor");default:return"/etc/cursor"}}function sa(e=process.platform,t=st()){let n=[H(oa(e),"hooks.json")],r=H(t,".cursor","managed");try{for(let o of wr(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(H(r,o.name,"hooks.json"))}catch{}return n}function ia(e=process.platform,t=st()){let n=e==="win32"?H(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[H(n,"requirements.toml")];return e!=="win32"&&r.push(H(n,"managed_config.toml")),r.push(H(t,".codex","managed_config.toml"),H(n,"config.toml")),r}function it(e,t=process.platform,n=st()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Zt(t,n);return[r,...o]}case"cursor":return sa(t,n);default:return ia(t,n)}}import{createHash as Wr,randomBytes as Pa}from"node:crypto";import{existsSync as Vr,mkdirSync as cn,readFileSync as Yr,unlinkSync as Xr,writeFileSync as Zr}from"node:fs";import{homedir as ln}from"node:os";import{dirname as ct,join as un,resolve as ba}from"node:path";var aa=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),ca=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function me(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||ca.has(n)||r.includes("[bot]")||aa.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 ha,readFileSync as _a}from"node:fs";import{hostname as jr,userInfo as Sa}from"node:os";import{randomBytes as la}from"node:crypto";import{existsSync as Qt,mkdirSync as ua,readdirSync as da,readFileSync as pa,renameSync as Mr,statSync as Lr,unlinkSync as Ur,writeFileSync as fa}from"node:fs";import{basename as ma,dirname as Nr,join as Dr,relative as ga}from"node:path";function d(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
6
+ `)}function se(e,t){ua(Nr(e),{recursive:!0});let n=Dr(Nr(e),`.${ma(e)}.${process.pid}.${la(4).toString("hex")}.tmp`);try{fa(n,t,"utf8");try{Mr(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Ur(e),Mr(n,e);return}throw r}}catch(r){try{Ur(n)}catch{}throw r}}function at(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Hr(){process.stdout.write('{"continue":true}')}function k(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Le(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function en(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 z(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 b(e,t,n=3e3,r={}){let o=await z(e,t,n,r);return o.ok?o.stdout:""}async function tn(e=process.cwd()){let t=await z("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&&Qt(n)){let r=await z("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 Z(e=process.cwd()){return(await tn(e)).root}function U(e,t){try{return JSON.parse(e)}catch{return t}}var qt=new Map;function W(e,t){let n=qt.get(e);if(n!==void 0)return n;try{let r=U(pa(e,"utf8"),t);return qt.set(e,r),r}catch{return qt.set(e,t),t}}function ge(e){return typeof e=="string"?e:""}function he(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=he(e,t);return typeof n=="string"?n:""}var ie=500;function Fr(e,t=2){if(!Qt(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=da(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=Dr(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:ga(e,l),size:Lr(l).size})}catch{continue}if(n.length>=ie){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function nn(e){return Qt(e)?{present:!0,size:Lr(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"}function rn(e=process.env){return Ie(x("CURSOR_SANDBOX",e))}var Ea=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function ya(e){return Ea.some(t=>!!x(t,e))}function Ra(e){if(x("KUBERNETES_SERVICE_HOST",e)||Ie(x("REMOTE_CONTAINERS",e))||Ie(x("DEVCONTAINER",e)))return!0;try{if(ha("/.dockerenv")||_a("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function $r(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!x(t,e))}function Ca(e,t=process.platform){return $r(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!x(n,e)):!1}function ka(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Ia(e){return e==="linux"}function x(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return k(e)}function Aa(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!xa(x("CURSOR_VERSION",n))}function xa(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function on(e){if(ka(e.sessionId))return!0;let t=e.hostname??jr(),n=e.osUser??Kr(e.env);return Aa(t,n,e.env)}function va(e){return Ie(x("CURSOR_AGENT",e.env))?!0:on(e)}function Oa(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(x("TERM",e)??x("TERM_PROGRAM",e))||(x("SSH_TTY",e)??x("SSH_CONNECTION",e))||(x("__CFBundleIdentifier",e)??x("XPC_SERVICE_NAME",e))||$r(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!x(t,e))||x("SESSIONNAME",e))}function De(e={}){let t=e.env;if(x("GITHUB_ACTIONS",t))return"github_actions";if(Ie(x("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Ca(t,n)&&va(e)&&(Ie(x("CURSOR_AGENT",t))||Ia(n)))return"cursor_cloud";if(x("CODESPACES",t)||x("CODESPACE_NAME",t))return"codespaces";if(x("GITLAB_CI",t))return"gitlab_ci";if(ya(t))return"managed";let r=x("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Ra(t)?"container":Oa(t)?"interactive":"unknown"}async function sn(){return await b("systemd-detect-virt",[],1e3)}function Kr(e=process.env,t=Sa){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 an(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await b("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 b("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await b("uname",["-r"],1e3))}else t=await b("ver",[],1e3);let n=Kr(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await b("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 He(){return jr()}var wa="installation.json",Ta="cloud-bootstrap.lock",Ma=6e4;function qr(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function Fe(e=ln()){return un(e,".ev-ai","agent-hook")}function Ua(e=ln()){return un(Fe(e),wa)}function Qr(e){return un(ct(e),Ta)}function eo(){return Pa(8).toString("hex")}function Ae(e){return Wr("sha256").update(e).digest("hex").slice(0,16)}function R(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function to(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Na(e=process.env){let t=R(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!to(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 no(e,t){return e&&to(e)?e:(e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Na(t))}function La(e){return/^[0-9a-f]{16}$/.test(e)}function Da(e=process.env){if(R(e.GITHUB_ACTIONS)){let t=R(e.GITHUB_REPOSITORY_ID)??R(e.GITHUB_REPOSITORY),n=R(e.GITHUB_ACTOR)??R(e.GITHUB_TRIGGERING_ACTOR)??R(e.GITHUB_USER);if(t&&n)return Ae(`github_actions|${t}|${n}`)}if(R(e.CODESPACES)||R(e.CODESPACE_NAME)){let t=R(e.CODESPACE_NAME);if(t)return Ae(`codespaces|${t}`);let n=R(e.GITHUB_REPOSITORY_ID)??R(e.GITHUB_REPOSITORY),r=R(e.GITHUB_USER)??R(e.GITHUB_ACTOR);if(n&&r)return Ae(`codespaces|${n}|${r}`)}if(R(e.GITLAB_CI)){let t=R(e.CI_PROJECT_ID)??R(e.CI_PROJECT_PATH),n=R(e.GITLAB_USER_LOGIN)??R(e.GITLAB_USER_EMAIL)??R(e.GITLAB_USER_NAME);if(t&&n)return Ae(`gitlab|${t}|${n}`)}return null}var Ha="cursoragent@cursor.com";function Fa(e){let t=R(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Ha?null:t}function ja(e,t){return R(e.CURSOR_PROJECT_DIR)??R(e.CLAUDE_PROJECT_DIR)??t}function $a(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Ka(e){let t=await b("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?$a(t):e}async function Ba(e){let t=R(await b("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!me(null,t))return t;let n=R(await b("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!me(null,n)?n:null}function Ga(e,t){let n=ja(e,t);return n?Ae(`cursor_cloud|${n}|${Fa(e)??""}`):null}async function za(e,t){let n=R(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Ka(n),o=await Ba(n);return Ae(`claude_remote|${r}|${o??""}`)}function Br(e,t){let n=no(e,t);if(n)return n;let r=Da(t);return r||eo()}async function Ja(e){let n=await b("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||ba(e);return Wr("sha256").update(n).digest("hex").slice(0,16)}function Wa(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 Va(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Wa(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 _e(e){if(Vr(e))try{return Va(Yr(e,"utf8"))}catch{}}function dn(e){return _e(e)}function ro(e,t,n){let r=_e(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{se(e,`${JSON.stringify(o,null,2)}
7
+ `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: operator identity cache write failed open: ${i}`)}}function oo(e,t=Date.now()){if(!e)return!0;if(_e(e)?.operator_identity_hash)return!1;let n=Qr(e);try{if(Vr(n)){let r=Number.NaN;try{r=Number(Yr(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Ma)return!1;try{Xr(n)}catch{}}}catch{}try{return cn(ct(n),{recursive:!0}),Zr(n,`${t}
8
+ `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(co(r))return!1;let o=r instanceof Error?r.message:String(r);return d(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function so(e){if(e)try{Xr(Qr(e))}catch{}}function io(e,t){let r=_e(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function ao(e,t,n){if(!n)return;let r=_e(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{se(e,`${JSON.stringify(o,null,2)}
9
+ `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${i}`)}}function co(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Ya(e,t){cn(ct(e),{recursive:!0}),Zr(e,`${JSON.stringify(t,null,2)}
10
+ `,{encoding:"utf8",flag:"wx"})}function Gr(e,t){try{return Ya(e,t),t}catch(n){if(!co(n))throw n;return _e(e)}}function zr(e,t){cn(ct(e),{recursive:!0}),se(e,`${JSON.stringify(t,null,2)}
11
+ `)}function Jr(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function lt(e,t={}){let n=t.home??ln(),r=t.env??process.env,o=await Ja(e),s=Ua(n),i={sessionId:t.sessionId,hostname:R(r.HOSTNAME)??void 0,osUser:R(r.USER)??R(r.LOGNAME)??R(r.USERNAME)??void 0,env:r},a=De(i),c=no(t.overrideId,r),l=a==="cursor_cloud"&&on(i)?Ga(r,e):a==="claude_remote"?await za(r,e):null,u=_e(s);if(u){let S=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(S={...u,pinned:!0},zr(s,S)),!!l&&l!==S.installation_id&&!c&&S.pinned!==!0&&La(S.installation_id)&&l){let I={installation_id:l,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return zr(s,I),{installationId:l,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let p=c??l??Br(void 0,r),m=Gr(s,Jr(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let f=c??l??Br(void 0,r),h=Gr(s,Jr(f===p?eo():f,c));if(h)return{installationId:h.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as pn,readFileSync as Xa}from"node:fs";import{dirname as Za,join as lo,relative as qa}from"node:path";var ut=[nt,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Qa(e=process.cwd(),t){let n=k("EV_AI_HOOK_MANIFEST");if(n&&pn(n))return n;let r=t??await Z(e);for(let o of ut){let s=lo(r,o);if(pn(s))return s}for(let o of ut){let s=lo(e,o);if(pn(s))return s}}async function ec(e,t){let n=t??await Z(Za(e)),r=qa(n,e),o=await z("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 tc(e){let t=Xa(e,"utf8");return U(t,{})}function nc(){return{schema_version:2,mcp_servers:[]}}async function uo(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await tn(e),o=await Qa(e,n),s=o?tc(o):nc();delete s.installation_id;let i=o?await ec(o,n):!1;s.capture_hook_input==="full"&&o&&i&&(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:a,storePath:c,repoKey:l}=await lt(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:a,installationStorePath:c,repoKey:l,collectorUrl:br(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function po(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var rc=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"];function fn(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 fo(e=process.platform,t=process.arch){let n=fn(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${rc.join(", ")}.`);return n}function mn(e){return`compile-out/bin/${e}/ev-ai-agent-hook`}function dc(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=Ue(n);if(r)throw new Error(`collector URL rejected: ${r}`);return Ne(n)}function pc(e){let t=e.collectorUrl?.trim();if(!t)return;let n=Ue(t);if(n)throw new Error(`collector URL rejected: ${n}`);return Ne(t)}function fc(e){return dc(e,"install")}function Eo(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 yo(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 Ro(e=process.execPath){return Co(e)?"binary":"npx"}function mc(){return A(q(),".ev-ai","agent-hook")}function gc(e=q()){return A(e,".ev-ai","agent-hook",zt)}function hc(){let e=_n(uc(import.meta.url)),t=A(e,"hook.mjs");return ae(t)?t:A(e,"..","dist","hook.mjs")}function Co(e=process.execPath){return ac(e)===oe}function ko(e,t){let n=So(mo(e),mo(t));return!n.startsWith("..")&&!cc(n)}function pt(e){return e.split(lc).join("/")}function _c(e){return`node "$(git rev-parse --show-toplevel)/${pt(e)}"`}function Sc(e){return`"$(git rev-parse --show-toplevel)/${pt(e)}"`}function Ec(e){return A(e,Jt)}function Io(e,t){let n=Ec(e);hn(_n(n),{recursive:!0}),_o(t,n,{force:!0});try{ho(n,493)}catch{}return n}function yc(e){let t=A(mc(),"current");try{dt(t,{recursive:!0,force:!0})}catch{}sc(e,t,process.platform==="win32"?"junction":"dir")}function Ao(e,t=X,n=q()){let r=A(n,".ev-ai","agent-hook",t),o=A(r,oe);hn(r,{recursive:!0}),_o(e,o,{force:!0});try{ho(o,493)}catch{}return yc(r),A(n,".ev-ai","agent-hook",zt)}function xo(e){let t=fn();if(!t)return;let n=[A(e,mn(t)),A(e,"packages","agent-hook",mn(t))];for(let r of n)if(ae(r)&&ko(e,r))return r}function Rc(e=q()){let t=gc(e);return ae(t)?t:void 0}function Cc(e,t=q()){let n=Rc(t);return n||(Co()?Ao(process.execPath,X,t):xo(e))}function kc(e,t=q()){let n=xo(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=Ao(n,X,t),o=Io(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function go(e){let t=[A(e,"packages","agent-hook","dist","hook.mjs"),A(e,Sr)],n=hc();ae(n)&&ko(e,n)&&t.unshift(n);for(let r of t){if(!ae(r))continue;let o=pt(So(e,r));return{command:_c(o),hookPath:o,strategy:"dev_mjs"}}}function Ic(e=rt){return`npx -y ${e}`}function Ac(e,t=q(),n=Ro()){if(n==="npx")return{command:Ic(),hookPath:rt,strategy:"npx"};if(n==="local"){let s=go(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=Cc(e,t);if(r){Io(e,r);let s=pt(Jt);return{command:Sc(s),hookPath:s,strategy:"project_binary"}}let o=go(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
13
+ curl -fsSL ${Er}/install.sh | sh
14
14
  Or use npx delivery:
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};
15
+ npx ${rt} install`)}function vo(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(oe)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function Sn(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function ce(e,t){hn(_n(e),{recursive:!0}),ic(e,`${JSON.stringify(t,null,2)}
16
+ `,"utf8")}function Q(e){if(ae(e))try{return JSON.parse(oc(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function xc(e,t){let n=po(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 vc(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 Oo(e,t){let n=A(e,nt),r=Q(n),o=xc(r,t);return t.collectorUrl!==void 0||ae(n)||!vc(o)?(ce(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function gn(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 Oc(e){if(gn(process.env))return!0;let t=q();return[...Xt(),A(t,".claude","settings.json"),A(t,".claude","remote-settings.json"),A(e,".claude","settings.json"),A(e,".claude","settings.local.json")].some(r=>{try{let o=Q(r);return o?gn(o.env):!1}catch{return!1}})}function Pc(e){try{let t=Q(A(e,".claude","settings.json"));return t?gn(t.env):!1}catch{return!1}}function Po(e){return Array.isArray(e)?e:[]}function ft(e){let t=[],n=r=>!!r&&typeof r=="object"&&vo(r.command);for(let r of Po(e)){if(!r||typeof r!="object"){t.push(r);continue}let o=Array.isArray(r.hooks)?r.hooks:[],s=o.filter(i=>!n(i));if(!(s.length===0&&o.some(n))){if(s.length!==o.length){t.push({...r,hooks:s});continue}t.push(r)}}return t}function bo(e,t){return[...ft(e),...t]}function En(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!vo(t.command)):[]}function bc(e,t){return[...En(e),{command:t}]}function wc(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 Tc(e){let t={type:"command",command:e,statusMessage:xr},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var Mc=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","afterShellExecution","beforeReadFile","afterFileEdit","beforeMCPExecution","subagentStart","subagentStop","stop"],Uc=[];function Nc(e,t=Uc){let n={...e};for(let r of t){if(!(r in n))continue;let o=En(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function Lc(e,t,n={}){let r=A(e,".claude/settings.json"),o=Sn(t,"claude"),s=Q(r)??{};if(Oc(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let p of Object.keys(u))u[p]=ft(u[p]),Po(u[p]).length===0&&delete u[p];Object.keys(u).length===0?delete s.hooks:s.hooks=u,ce(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=wc(o),l={...a};for(let[u,p]of Object.entries(c))l[u]=bo(a[u],p);return s.hooks=l,ce(r,s),!0}function Dc(e,t){let n=A(e,".cursor/hooks.json"),r=Sn(t,"cursor"),o=Q(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=Nc({...s});for(let a of Mc)i[a]=bc(i[a],r);ce(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function Hc(e,t){let n=A(e,".codex/hooks.json"),r=Sn(t,"codex"),o=Q(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=Tc(r),a={...s};for(let[c,l]of Object.entries(i))a[c]=bo(s[c],l);ce(n,{...o,hooks:a})}function Fc(e){let t=A(e,".claude/settings.json"),n=Q(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let i=r[s],a=ft(i);JSON.stringify(i)!==JSON.stringify(a)&&(o=!0),a.length===0?delete r[s]:r[s]=a}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,ce(t,n),d(`Removed ev-ai hooks from ${t}`))}function jc(e){let t=A(e,".cursor/hooks.json"),n=Q(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=En(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks"&&a!=="version").length===0){dt(t,{force:!0}),d(`Removed ${t}`);return}ce(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function $c(e){let t=A(e,".codex/hooks.json"),n=Q(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=ft(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks").length===0){dt(t,{force:!0}),d(`Removed ${t}`);return}ce(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function yn(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)&&fo(e,t)}async function wo(e={}){let t=fc(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??Ro();yn(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await Z(i),{command:c,hookPath:l,strategy:u}=Ac(a,q(),s),{installationId:p,storePath:m}=await lt(a,{overrideId:e.installationId}),{manifestPath:f,wrote:h}=Oo(a,e),S=[];return n?d("Skipped Claude hook \u2014 --no-claude"):Lc(a,c,{force:e.force})?(S.push("Claude"),e.force&&Pc(a)&&d("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):d("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?d("Skipped Cursor hook \u2014 --no-cursor"):(Dc(a,c),S.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(Hc(a,c),S.push("Codex")),d(`Installed hook (${u}) at ${l}`),d(`Installation identity ${p} at ${m}`),h&&f?d(`Shared manifest written to ${f}`):d("Using package default collector config (no shared manifest file needed)"),d(S.length>0?`Wired ${S.join(", ")} hooks in ${a} (commands include --runner)`:`No runner hooks wired in ${a} (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)."),h&&f&&e.collectorUrl&&d("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:a,hookPath:l,manifestPath:f,installationStorePath:m,strategy:u}}async function To(e=process.cwd()){yn(process.platform,process.arch,{requireBinaryArch:!0});let t=await Z(e),{projectPath:n,globalPath:r}=kc(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function Mo(e={}){let t=pc(e);e.collectorUrl=t,yn(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await Z(n),{manifestPath:o,wrote:s}=Oo(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 Uo(e){for(let t of[()=>Fc(e),()=>jc(e),()=>$c(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function No(e=process.cwd()){let t=await Z(e);return Uo(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 Lo(e=process.cwd()){let t=await Z(e);Uo(t);for(let n of ut){let r=A(t,n);if(ae(r))try{dt(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 cu}from"node:crypto";import{existsSync as lu,mkdirSync as uu,readdirSync as du,readFileSync as Rs,unlinkSync as Cs,writeFileSync as pu}from"node:fs";import{homedir as ks}from"node:os";import{join as Un}from"node:path";import{existsSync as qc}from"node:fs";import{existsSync as Kc}from"node:fs";import{homedir as Ho}from"node:os";import{join as Bc}from"node:path";function Fo(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Gc={claude:{shared:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]},{dir:".claude/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[["CLAUDE.md"],["CLAUDE.local.md"],[".claude/CLAUDE.md"]],settings:[".claude/settings.json",".claude/settings.local.json",".claude/hooks.json"]},homeOnly:{mcpJson:[".claude.json"],plugins:"claude",managed:"claude"},projectOnly:{mcpJson:[".mcp.json","mcp.json"]}},cursor:{shared:{skillRoots:[".cursor/skills"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[["AGENTS.md"]],settings:[".cursor/hooks.json",".cursor/cli-config.json"],mcpJson:[".cursor/mcp.json"]},homeOnly:{skillRoots:[".cursor/skills-cursor"],memory:[[".cursor/AGENTS.md"]],plugins:"cursor",managed:"cursor"},projectOnly:{skillRoots:[".agents/skills"]}},codex:{shared:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]},{dir:".codex/rules",kind:"RULE",extensions:[".md",".rules"]}],memory:[["AGENTS.override.md","AGENTS.md"]],settings:[".codex/hooks.json",".codex/config.toml"],mcpToml:[".codex/config.toml"]},homeOnly:{memory:[[".codex/AGENTS.override.md",".codex/AGENTS.md"]],managed:"codex"}}};function Do(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function zc(e,t={}){let{shared:n}=e;return{skillRoots:[...n.skillRoots,...t.skillRoots??[]],dirs:n.dirs,memory:[...n.memory,...t.memory??[]],settings:[...n.settings,...t.settings??[]],mcpJson:Do(n.mcpJson,t.mcpJson),mcpToml:Do(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function jo(e){return Object.fromEntries(Object.entries(Gc).map(([t,n])=>[t,zc(n,n[e])]))}var xe=jo("homeOnly"),ue=jo("projectOnly");function Jc(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function Wc(e,t){return Jc(e).some(n=>Kc(Bc(t,n)))}function $o(e,t){for(let n of e)if(Wc(n,t))return!0;return!1}function le(e){return[...new Set(e)]}function de(e){let t=[],n=[],r=[],o=[],s=[],i=[],a=[];for(let c of e){t.push(...c.skillRoots);for(let l of c.dirs)l.kind==="SUBAGENT"?n.push(l.dir):l.kind==="COMMAND"?r.push(l.dir):o.push(l.dir);s.push(...c.memory.flat()),i.push(...c.settings),a.push(...c.mcpJson??[],...c.mcpToml??[])}return{skills:le(t),subagents:le(n),commands:le(r),rules:le(o),memory:le(s),settings:le(i),mcp:le(a)}}function Vc(e,t=Ho(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...it(o.managed,n,t));return le(r)}var pe=de(Object.values(xe));function Ko(e=Ho(),t=process.platform){return Vc(Object.values(xe),e,t)}import{existsSync as Yc}from"node:fs";import{resolve as Rn}from"node:path";function K(e){return Rn(e).replaceAll("\\","/").replace(/\/$/,"")}function Ee(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function mt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var Xc=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function je(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Xc.test(t)?null:t}function ve(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=K(o);n.has(s)||(n.add(s),r.push(s))}return r}function Zc(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function V(e,t,n,r=Yc){for(let o of e)for(let s of t){let i=K(Rn(o,s)),a=Rn(o,s,n).replaceAll("\\","/");if(Zc(i,a)&&r(a))return a}return null}var Go=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,zo=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Qc=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,Bo=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"]),el=/^[a-z][a-z0-9-]{1,63}$/,tl=[".cursor/skills",".claude/skills",".agents/skills"],nl=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],rl=Ee(tl,de(Object.values(ue)).skills),ol=Ee(nl,de(Object.values(xe)).skills),sl=new Set(["read","read_file","view"]),il=new Set(["bash","shell","zsh"]);function Cn(e){let t=e.replace(/\\/g,"/");return Go.exec(t)?.[1]??null}function al(e){let t=e.replace(/\\/g,"/"),r=zo.exec(t)?.[1];return r?r.toLowerCase():null}function cl(e){return Cn(e)??al(e)}function ll(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 gt(e){return typeof e=="string"?gt(U(e,null)):!e||typeof e!="object"?null:ll(e)}function Jo(e){if(typeof e=="string")return Jo(U(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function kn(e){let t=Jo(e.tool_input);if(t)return t;let n=ge(e.command);return n.length>0?n:null}function ul(e){let t=e.replace(/\\/g,"/"),n=Go.exec(t);if(n?.[1])return n[1];let o=zo.exec(t)?.[1];return o?o.toLowerCase():null}function dl(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function In(e){let t=gt(e.tool_input)??ge(e.file_path);return t.length>0?t:null}function $e(e,t,n){let r=dl(e).toLowerCase();if(sl.has(r)){let o=In(e);return o?t(o):null}if(il.has(r)){let o=kn(e);return o?n(o):null}return null}function Wo(e){return $e(e,cl,ul)}function pl(e){let t=new Set,n=[];for(let r of e.matchAll(Qc)){let o=r[1]?.toLowerCase();!o||t.has(o)||fl(o)||(t.add(o),n.push(o))}return n}function fl(e){let t=e.split("/")[0];return Bo.has(e)||t!==void 0&&Bo.has(t)}function Vo(e){let t=e.skillId.toLowerCase();if(!el.test(t))return null;let n=e.exists??qc,r=`${t}/SKILL.md`,o=V(ve(e.launchCwd,e.gitRoot),rl,r,n);return o!==null?o:e.home?V([K(e.home)],ol,r,n):null}function ml(e){return ge(e.prompt)}function Yo(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=ml(e);return n?pl(n):[]}var An=Gt(_t(),1);import{existsSync as Ml}from"node:fs";var ye={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Ke(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Tl(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 Ke(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Ke(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Ke(o[1]):Ke(t)}async function Be(e=process.cwd()){let t=await z("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([z("git",["remote","get-url","origin"],2e3,{cwd:e}),z("git",["branch","--show-current"],2e3,{cwd:e}),z("git",["rev-parse","HEAD"],2e3,{cwd:e}),z("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function Qo(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=ye[n];if(!a)return"";let c=qr(n,e.scope_path,i);if(s){let h=io(s,c);if(h)return h}let l=o??await Be(r),u=l?.remote?Tl(l.remote):"";if(u||(u=Ke(process.env.GITHUB_REPOSITORY??"")),!u)return"";let p=e.scope_path??"",m=p?`${p}/`:"",f=`${u}:${m}${a}`;return s&&ao(s,c,f),f}var Ul=[".cursor/rules",".claude/rules",".codex/rules"],Nl=de(Object.values(ue)).rules;function Ll(e){return Ee(mt(e?ye[e]:void 0,Ul),Nl)}var Dl=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function es(e){let t=je(e.relativePath);if(!t)return null;let n=e.exists??Ml,r=ve(e.launchCwd,e.gitRoot),o=Ll(e.runnerPlatform),s=V(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=V(r,["."],t,n);if(i!==null)return i}return e.home?V([K(e.home)],o,t,n):null}function Hl(e){let t=e.replace(/\\/g,"/"),r=Dl.exec(t)?.[1];return r?(0,An.nativeKeyForRulePath)(r):null}function ts(e){return $e(e,An.nativeKeyForRulePath,Hl)}function ns(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function rs(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=je(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var xn=Gt(_t(),1);import{existsSync as Fl}from"node:fs";var jl=[".cursor/commands",".claude/commands",".codex/prompts"],$l=de(Object.values(ue)).commands;function Kl(e){return Ee(mt(e?ye[e]:void 0,jl),$l)}var Bl=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function os(e){let t=je(e.commandId);if(!t)return null;let n=e.exists??Fl,r=`${t}.md`,o=Kl(e.runnerPlatform),s=V(ve(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?V([K(e.home)],o,r,n):null}function Gl(e){let t=e.replace(/\\/g,"/"),r=Bl.exec(t)?.[1];return r?(0,xn.nativeKeyForCommandPath)(r):null}function ss(e){return $e(e,xn.nativeKeyForCommandPath,Gl)}import{existsSync as as}from"node:fs";import{homedir as cs}from"node:os";import{join as Ge,resolve as vn,sep as is}from"node:path";function On(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Pn(e,t){let n=t.toLowerCase();return On(e).some(r=>r.toLowerCase()===n)}function St(e,t,n){if(!as(e))return;let r=W(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function zl(e,t,n){if(!as(e))return;let r=W(e,{}),o=vn(t),s=null;for(let a of Object.keys(r.projects??{})){let c=vn(a);(o===c||o.startsWith(c.endsWith(is)?c:c+is))&&(s===null||c.length>vn(s).length)&&(s=a)}if(s===null)return;let i=r.projects?.[s]?.mcpServers??{};for(let[a,c]of Object.entries(i))n.set(a,{declared:{name:a,source:"claude_json_project",sourcePath:".claude.json",scope:"user"},config:c})}function ls(e,t,n,r){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{declared:{name:s.name,source:"manifest"}});return n==="claude"?(St(Ge(r,".claude.json"),{source:"claude_json_user"},o),zl(Ge(r,".claude.json"),t,o)):n==="cursor"&&St(Ge(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),St(Ge(t,".mcp.json"),{source:"mcp_json"},o),St(Ge(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function bn(e,t=process.cwd(),n="claude",r=cs()){return[...ls(e,t,n,r).values()].map(o=>o.declared)}function us(e,t,n=process.cwd(),r="claude",o=cs()){let s=ls(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Pn(a,e))return c.config??null;return null}function wn(e){return e!==void 0&&vr.includes(e)}function Et(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function yt(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=Et(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=Et(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=Et(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=Et(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:wn(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Tn(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=tt(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=Ue(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return Ne(n)}function ds(e,t){if(g(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Jl(){return!!(k("CURSOR_VERSION")??k("CURSOR_PROJECT_DIR"))}function Mn(e,t,n){return e!=="claude"&&e!=="codex"?!1:ds(t,n)?!0:Jl()}function ze(e,t,n,r){if(ds(e,t))return"cursor";if(wn(r))return r;let o=g(e,"conversation_id"),s=g(e,"turn_id"),i=g(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),wn(n)&&(c=n),c}function Rt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Wl(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 ps(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function fs(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"),i=g(e,"source"),a=ze(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Vl=["session_start","session_end","tool_invoked","skill_invoked"];function Yl(e){return Vl.includes(e)}function ms(e,t){return e&&Yl(e)?e:Wl(t.toLowerCase())}var Xl={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function gs(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function hs(e,t=""){let n=g(e,"tool_name")||g(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!gs(n)&&(n=`MCP:${n}`):n=Xl[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?ge(o.skill)||ge(o.skill_name):"")||g(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=Wo(a);let c=ts(a),l=ss(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var Zl=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function _s(e){for(let t of["subagent_type","agent_type"]){let n=g(e,t);if(n&&Zl.test(n))return n}return null}function Ss(e){let t=he(e,"duration_ms");if(typeof t=="number")return t;let n=he(e,"duration");return typeof n=="number"?n:null}var ql="error",Ql="interrupted",eu="permission_denied",tu=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Je(e){return tu.test(e)?e:null}function nu(e){for(let t of["failure_type","error_type"]){let n=Je(g(e,t));if(n)return n}return null}function Es(e,t){return he(e,"is_interrupt")===!0?Ql:t.toLowerCase()==="permissiondenied"?eu:nu(e)??ql}function ru(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 ou(e,t){let n=null;for(let r of t)!r||!Pn(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function su(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of On(s)){let a=`${i}__`;e.length>a.length&&e.slice(0,a.length).toLowerCase()===a.toLowerCase()&&i.length>r&&(n={mcpServer:s,mcpTool:e.slice(a.length)},r=i.length)}if(n!==null)return n;let o=/^(.+?)__(.+)$/.exec(e);return!o?.[1]||!o[2]?{mcpServer:null,mcpTool:null}:{mcpServer:ou(o[1],t)??o[1],mcpTool:o[2]}}function iu(e,t){if(/^mcp__/i.test(e))return su(e.slice(5),t);if(/^MCP:/i.test(e)){let n=e.slice(4);if(!n)return{mcpServer:null,mcpTool:null};let r=n.indexOf(":");if(r>0)return{mcpServer:n.slice(0,r),mcpTool:n.slice(r+1)||null};let o=n.indexOf("__");return o>0?{mcpServer:n.slice(0,o),mcpTool:n.slice(o+2)||null}:{mcpServer:ru(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function au(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function ys(e,t=[],n=""){let r=e?iu(e,t):{mcpServer:null,mcpTool:null},o=Je(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!gs(e)&&(s=e),s&&(s=au(s,o)),{mcpServer:o,mcpTool:s}}var Is=3e4,fu="claims",mu=!0,gu=100,hu=new Set(["sessionstart","sessionend","stopfailure"]),_u=["tool_name","tool","command","file_path","url"];function Su(e=ks()){return Un(Fe(e),fu)}function As(e){let t=e.split(`
17
+ `,1)[0]??"";return Number(t.trim())}function xs(e){return cu("sha256").update(e).digest("hex").slice(0,32)}function Eu(e){let t=[];for(let n of _u){let r=g(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":xs(t.join("\0"))}function yu(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()??"",i=e.callFingerprint?.trim()??"",a=!!(o||r||s),c=hu.has(n);if(!a&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return xs(`${l}|${t}|${n}|${r}|${o}|${i}|${s}`)}function Ru(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Cu(e,t){return Un(e,t)}function ku(e,t=Date.now()){let n;try{n=du(e)}catch{return}let r=0;for(let o of n){if(r>=gu)break;r+=1;let s=Un(e,o),i=Number.NaN;try{i=As(Rs(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<Is))try{Cs(s)}catch{}}}function Iu(e,t,n=Date.now()){let r=Cu(t,e);try{if(lu(r)){let o=Number.NaN;try{o=As(Rs(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<Is)return!1;try{Cs(r)}catch{}}}catch{}try{uu(t,{recursive:!0}),pu(r,`${n}
18
+ `,{encoding:"utf8",flag:"wx"})}catch(o){if(Ru(o))return!1;let s=o instanceof Error?o.message:String(o);return d(`WARN: event claim failed open: ${s}`),!0}return ku(t,n),!0}function Au(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"),i=g(e,"subagent_id")||g(e,"agent_id"),a=ze(e,t,void 0,n),c=Eu(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function vs(e,t,n,r=ks(),o=Date.now()){if(!mu)return!0;let s=yu(Au(e,t,n));if(!s)return!0;let i=Iu(s,Su(r),o);return!i&&k("EV_AI_HOOK_DEBUG")&&d(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{realpathSync as cf}from"node:fs";import{homedir as lf}from"node:os";var C=Gt(_t(),1);import{existsSync as xu,readFileSync as vu}from"node:fs";import{homedir as Os}from"node:os";import{join as Ou}from"node:path";var Pu="cloud-cache.json",bu=1440*60*1e3,wu=900*1e3;function Tu(e=Os()){return Ou(Fe(e),Pu)}function Mu(e){if(!xu(e))return;let t=U(vu(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 Uu(e,t){try{se(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 Nu(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?wu:bu;return n-e.probed_at<r}async function Lu(e){let t=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=(await t.text()).trim();if(!n)return;let r={"X-aws-ec2-metadata-token":n},[o,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!o?.ok&&!s?.ok)return;let i=o?.ok?(await o.text()).trim():"",a=s?.ok?(await s.text()).trim():"";if(!(!i&&!a))return{provider:"aws",region:i,instance_id:a}}async function Du(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 Hu(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 Fu(e){let t=await Promise.allSettled([Lu(e),Du(e),Hu(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Nn(e,t){if(e==="interactive")return null;let n=t?.home??Os(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Tu(n),i=Mu(s);if(Nu(i,e,o))return i.result;let a=await Fu(r);return Uu(s,{context:e,probed_at:o,result:a}),a}var ju=["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"],$u=["CURSOR_PROJECT_DIR"],Ku=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Bu(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Ku.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Ln(e=process.env){let t=ju.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Bu(e[r]??"")}:{name:r,present:!1}),n=$u.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{createHash as Gu}from"node:crypto";import{resolve as zu}from"node:path";function P(e){return Gu("sha256").update(e).digest("hex").slice(0,16)}function Dn(e){return P(zu(e))}function B(e,t){return`${e}\0${t}`}function Ps(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function We(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 P(n)}function Ju(e,t,n="git_config",r=null){return P(`${e??""}|${t??""}|${r??""}|${n}`)}function Wu(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 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 Vu(e,t=b){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return Wu(n)}function Yu(e=process.env){let t=y(e.GIT_AUTHOR_NAME),n=y(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=y(e.GIT_COMMITTER_NAME),o=y(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=y(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function ee(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 Xu(e=process.env){let t=ee(y(e.EV_AI_HOOK_OPERATOR_NAME),y(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured",y(e.EV_AI_HOOK_OPERATOR_LOGIN));if(t)return t;let n=y(e.GITHUB_ACTOR)??y(e.GITHUB_TRIGGERING_ACTOR)??y(e.GITHUB_USER),r=ee(n,null,"github",n);if(r)return r;let o=y(e.GITLAB_USER_LOGIN),s=ee(y(e.GITLAB_USER_NAME)??o,y(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let i=ee(y(e.BUILD_REQUESTEDFOR),y(e.BUILD_REQUESTEDFOREMAIL),"azure_devops",y(e.BUILD_REQUESTEDFORID));if(i)return i;let a=y(e.BUILDKITE_BUILD_CREATOR_EMAIL),c=ee(y(e.BUILDKITE_BUILD_CREATOR),a,"buildkite",a);if(c)return c;let l=ee(y(e.BUILD_USER)??y(e.CHANGE_AUTHOR),y(e.BUILD_USER_EMAIL)??y(e.CHANGE_AUTHOR_EMAIL),"jenkins",y(e.BUILD_USER_ID));if(l)return l;let u=y(e.CIRCLE_USERNAME),p=ee(u,null,"circleci",u);if(p)return p;let m=y(e.CODEBUILD_INITIATOR),f=ee(m,null,"codebuild",m);if(f)return f;let h=ee(y(e.DRONE_COMMIT_AUTHOR)??y(e.DRONE_COMMIT_AUTHOR_NAME),y(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",y(e.DRONE_COMMIT_AUTHOR));if(h)return h;if(ws(e.CLAUDE_CODE_REMOTE)||ws(e.CURSOR_AGENT)){let S=y(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:S&&!me(null,S)?S:null,platform_login:null,identity_source:"cloud"}}return null}function bs(e){return!!((e.git_user_name??e.git_user_email)&&!me(e.git_user_name,e.git_user_email))}function y(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ws(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function Zu(e,t=b,n=process.env){let r=await Vu(e,t);if(bs(r))return{...r,identity_source:"git_config"};let o=Yu(n);if(o&&bs(o))return o;let s=Xu(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 Ct(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??b,s=e.env??process.env,i=await Zu(t,o,s),a=Ju(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?dn(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let f=n;return{operator:i,commit:()=>{f&&ro(f,a,at())}}}function Hn(e){return e?!dn(e)?.operator_identity_hash:!0}function Ts(e){return!0}import{existsSync as Rp,readFileSync as Cp}from"node:fs";import{homedir as ki}from"node:os";import{join as we,resolve as kp}from"node:path";import{basename as mp,join as be}from"node:path";import{dirname as js,resolve as At}from"node:path";import{existsSync as qu}from"node:fs";import{homedir as Ns}from"node:os";import{relative as Ls,resolve as Y,sep as fe}from"node:path";var Qu=["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 ed(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:k("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function td(e){let t={};for(let n of Qu){let r=he(e,n);r!==void 0&&(t[n]=r)}return t}function kt(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Y(e),r=Y(t),o=Ls(r,n);return!o||o==="."?".":o.startsWith(`..${fe}`)||o===".."||Y(r,o)!==n?null:o.split(fe).join("/")}function Ds(e,t){let n=Ls(Y(t),Y(e)).split(fe).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Hs(e){return typeof e!="string"||e.length===0?null:Y(e).split(fe).join("/")}function nd(){let e=k("CURSOR_PROJECT_DIR");if(!e)return null;let t=Y(e);return qu(t)?t.split(fe).join("/"):null}function Fn(e,t){return kt(e,t)!==null}function rd(e,t){let n=Y(t??Ns(),".cursor").split(fe).join("/");return Fn(e,n)}function od(e,t,n){return t!==null&&Fn(e,t)?!0:t!==null&&rd(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&Fn(e,n.gitRoot)?!0:t===null}function Fs(e,t){let n=Hs(e.cwd);if(n!==null)return n;let r=Y(process.cwd()).split(fe).join("/"),o=nd();return od(r,o,t)?r:o??r}function jn(e,t={}){return Fs(e,t)}function $n(e,t=Ns()){let n=Y(t).split(fe).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Ms(e,t,n){let r=Hs(n.launchCwd)??Fs(t,n);e.cwd=$n(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?kt(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function Us(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 It(e,t,n={}){if(ed(t)){let o={...e};return delete o.cwd,delete o.transcript_path,Ms(o,e,n),Us(o,Ir)}let r=td(e);return Ms(r,e,n),Us(r,kr)}function sd(e){return typeof e=="string"&&e.length>0}function Kn(e){let t=At(e.home),n=At(e.launchCwd),r=e.gitRoot?At(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&sd(e.remote)&&r!==null&&r!==t&&(i=r,o.add(r)),n!==t&&!o.has(n)&&(s.push({scope:"cwd",dir:n}),o.add(n)),i!==null&&s.push({scope:"repo",dir:i});let a=null,c=r!==null&&kt(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=js(r);for(;;){let u=At(l);if(u===t)break;let p=js(u);if(p===u)break;if(e.hasProjectSpec(u)){s.push({scope:"parent",dir:u}),a=Ds(u,n);break}l=p}}return{anchors:s,parentRel:a}}import{existsSync as $s,readdirSync as id,realpathSync as ad}from"node:fs";import{basename as cd,dirname as ld,relative as ud,resolve as dd,sep as pd}from"node:path";var Bn=400,xt=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??ie}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=dd(t).split(pd).join("/");return $n(r,this.home)}let n=ud(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${P(ld(t))}/${cd(t)}`:n}claimFile(t){try{let n=ad(t);return this.seenRealpaths.has(n)?!1:(this.seenRealpaths.add(n),!0)}catch{return this.seenRealpaths.has(t)?!1:(this.seenRealpaths.add(t),!0)}}get atGlobalCap(){return this.truncated||this.components.length>=this.maxEntries}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!$s(t))return[];try{return id(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if($s(t))return W(t,n)}push(t){return this.components.length>=this.maxEntries?(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 Gn,readFileSync as fd,statSync as md}from"node:fs";import{basename as Bs,join as Ve,relative as Gs}from"node:path";var zn=100*1024,gd=4;function hd(e){return e.length<=zn?e:`${e.slice(0,zn-1)}\u2026`}function _d(e){try{let t=fd(e),n=t.toString("utf8");return{hash:P(t),length:t.length,text:hd(n)}}catch{return null}}var Ks={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Sd(e){return e in Ks?Ks[e]:"UNSPECIFIED"}function vt(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=_d(t.absolutePath);if(!n)return!1;let r=t.name??Bs(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.componentPath(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=Sd(t.kind);return s&&(o.trigger=s),e.push(o)}function Ed(e,t,n){let r=Gs(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Bs(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Re(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Jn(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Jn(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>gd))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=Ve(r,u.name,c);if(Gn(f)){let h=Gs(n,Ve(r,u.name)).replace(/\\/g,"/");vt(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:h||u.name});continue}Jn(e,{walkRoot:n,currentDir:Ve(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){Jn(e,{walkRoot:n,currentDir:Ve(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let p=u.name.toLowerCase();if(!l.some(f=>p.endsWith(f)))continue;let m=Ve(r,u.name);vt(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:Ed(n,m,!0)})}}function zs(e){for(let t of e)if(Gn(t))try{if(md(t).size>0)return t}catch{continue}return e.find(t=>Gn(t))}var yd="<omitted>",Rd=["package_name","package_spec","package_version","package_version_source"],Js=100,Ws=120,Ot=[{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"}],Vs=new Set(Ot.map(e=>e.attr)),Cd=["enabled","disabled"],kd=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Id=new Set(["type","command","url","args","env","envVars","headers",...Cd,...kd,...Ot.map(e=>e.raw)]),Ad=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",...Rd,...Vs,...[...Vs].map(e=>`${e}_truncated`)]);function Ys(e,t){for(let n of t)Id.has(n)||Ad.has(n)||(e[n]=yd)}var xd=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,vd=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,Od=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,Pd=/^bearer(?:\s+|$)/i;function Pt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Xs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Wn(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=Pt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Ce(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function bd(e){return Od.test(e)||Pd.test(e)?"<redacted>":e.includes("://")?Ce(e):e}function Zs(e){if(/^https?:\/\//i.test(e))return Ce(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Zs(e.slice(t+1))}`:bd(e)}function wd(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return xd.test(t)||vd.test(t)}function bt(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(wd(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Zs(r))}return t}function Td(e){let t=Xs(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ws?r.slice(0,Ws):r))].sort();if(n.length!==0)return n.length>Js?{names:n.slice(0,Js),truncated:!0}:{names:n,truncated:!1}}function Md(e){let t=Pt(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 qs(e,t){let n=new Set;for(let{raw:r,attr:o}of Ot){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 i=Td(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function Qs(e,t){let n=Pt(e),r={transport:t};if(!n)return r;Ys(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.serverUrl=="string"?n.serverUrl:void 0,a=o??s??i;a&&(r.command_or_url=Ce(a));let c=bt(Xs(n.args));c.length>0&&(r.args=c);let l=Md(n.env_http_headers),u=[...new Set([...Wn(n.env),...Wn(n.envVars),...Wn(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 h of["headers","http_headers","env_http_headers"])if(n[h]!==void 0&&n[h]!==null){r.headers_present=!0;break}let p=typeof n.auth=="string"?n.auth:void 0;p&&(r.auth=p);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),qs(r,n),r}function ei(e){let t=Pt(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function Xn(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return P(JSON.stringify({name:e,attributes:r,enabled:n}))}function Oe(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Ye(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 Ud(e,t){return bt(Ye(e,t))}function Yn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Vn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=Oe(n[1]);return r.length>0?r:void 0}function Nd(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],Oe(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 ti(e){return Yn(e,"enabled")===!1?!1:Yn(e,"disabled")!==!0}function Ld(e,t){let n={};for(let{raw:r,attr:o}of Ot){if(o==="auto_approve"){let i=Yn(t,r);if(i!==void 0){n[r]=i;continue}}let s=Ye(t,r);s.length>0&&(n[r]=s)}qs(e,n)}var Dd=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,Hd=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function Fd(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=Dd.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(Hd))o[1]&&t.add(o[1]);return[...t]}function ni(e,t){let n={transport:t};Ys(n,Fd(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?Oe(r[1]??""):void 0,i=o?Oe(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i;a&&(n.command_or_url=Ce(a));let c=Ud(e,"args");c.length>0&&(n.args=c);let l=new Set;for(let _ of e.split(`
24
+ `)){let I=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(_);I?.[1]&&l.add(I[1])}let u=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(u?.[1])for(let _ of u[1].split(",")){let I=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(_);I?.[1]&&l.add(I[1])}let p=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
25
+ ${e}`);if(p?.[1])for(let _ of p[1].split(`
26
+ `)){let I=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(_);I?.[1]&&l.add(I[1])}for(let _ of Ye(e,"env_vars"))l.add(_);let m=Nd(e,"env_http_headers");for(let[,_]of m)_.length>0&&l.add(_);let f=Vn(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(([_])=>_))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let h=Vn(e,"auth");h&&(n.auth=h);let S=Vn(e,"default_tools_approval_mode");return S&&(n.default_tools_approval_mode=S),Ld(n,e),n}var jd=300,$d=256;function ri(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 wt(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 oi(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Kd(e){return oi(e,jd)}function si(e,t){let n=ri(e.trim(),t),r=wt(n);if(r.length===0)return"";let[o,...s]=r,i=Ce(o),a=bt(s);return Kd([i,...a].join(" "))}function ii(e,t){if(typeof e!="string")return null;let n=ri(e.trim(),t),r=wt(n)[0];if(!r)return null;let o=Ce(r);return o.length===0?null:oi(o,$d)}function Bd(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 Gd(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 zd(e,t,n,r){let o=e.componentPath(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 Gd(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",p=Bd({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=P(u),h=m?`${s}:${m}:${p}:${f}`:`${s}:${p}:${f}`,S=`${s}|${m}|${p}|${u}|attrs2`;e.push({kind:"HOOK",name:h,path:o,content_hash:P(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:f,...p!=="prompt"&&u.trim()?{command:si(u,e.home)}:{}}})}}}function Pe(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||zd(e,t,r.hooks,n)}import{existsSync as ip,readFileSync as ap}from"node:fs";import{createHash as Jd}from"node:crypto";import{join as Xe}from"node:path";var Tt=128,Wd=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,Vd=new Set(["-p","--package"]),Yd=new Set(["-c","--call"]),Xd=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),Zd=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),qd=/^--no-/;function Qd(e){return Zd.has(e)||qd.test(e)}function ep(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}function Zn(e){if(e.length===0||e.length>Tt)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return Wd.test(n)?n:null}function tp(e,t){let n=ep(e);if(n===null)return[];let r=[...t];if(n==="npm"){let i=r[0]?.toLowerCase();if(i!=="exec"&&i!=="x")return[];r=r.slice(1)}let o=[],s=null;for(let i=0;i<r.length;i+=1){let a=r[i]??"";if(a==="--"){s=r[i+1]??null;break}if(!a.startsWith("-")){s=a;break}let c=a.indexOf("="),l=c===-1?a:a.slice(0,c);if(Yd.has(l))return[];if(Vd.has(l)){let u=c===-1?r[i+1]:a.slice(c+1);u!==void 0&&u.length>0&&o.push(u),c===-1&&(i+=1);continue}if(!(c!==-1||Qd(l))){if(Xd.has(l)){i+=1;continue}return[]}}return o.length>0?o.every(i=>Zn(i)!==null)?o:[]:s===null||Zn(s)===null?[]:[s]}function np(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
27
+ `);return Jd("sha512").update(t).digest("hex").slice(0,16)}function rp(e){let t=process.platform==="win32"?Xe(k("LOCALAPPDATA")??e,"npm-cache"):Xe(e,".npm"),n=k("npm_config_cache")??k("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function ai(e){return typeof e=="string"&&e.length>0&&e.length<=Tt?e:null}function op(e,t,n){let r=np(e);for(let o of rp(n)){let s=Xe(o,"_npx",r),i=W(Xe(s,"node_modules",...t.split("/"),"package.json"),{}),a=ai(i.version);if(a!==null)return a;let c=W(Xe(s,"package-lock.json"),{}),l=ai(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function sp(e){return e.length<=Tt?e:`${e.slice(0,Tt-1)}\u2026`}function qn(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=tp(e,t??[]),o=r[0];if(o===void 0)return null;let s=Zn(o);if(s===null)return null;let i=op(r,s,n);return{package_name:s,package_spec:sp(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function ci(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=wt(e.trim());return n===void 0?null:qn(n,r,t)}function Mt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=Array.isArray(n.args)?n.args.filter(o=>typeof o=="string"):[];return qn(typeof n.command=="string"?n.command:null,r,t)}function li(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:qn(Oe(n[1]??""),Ye(e,"args"),t)}function cp(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 ui(e,t,n){if(!e.claimFile(t))return;let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.componentPath(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=cp(a),l=Qs(a,c);Object.assign(l,Mt(a,e.home)??{});let u=ei(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:Xn(i,l,u),origin:n,enabled:u,attributes:l})}}function di(e,t,n){if(!ip(t)||!e.claimFile(t))return;let r;try{r=ap(t,"utf8")}catch{return}let o=e.componentPath(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(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),p="unknown";/^\s*url\s*=/m.test(u)?p="http":/^\s*command\s*=/m.test(u)&&(p="stdio");let m=ni(u,p);Object.assign(m,li(u,e.home)??{});let f=ti(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:Xn(a,m,f),origin:n,enabled:f,attributes:m})}}import{existsSync as lp,readdirSync as up}from"node:fs";import{join as F}from"node:path";var pi=50;function Qn(e,t,n,r){if(!lp(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(pi,()=>{Re(e,{dir:F(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Re(e,{dir:F(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Re(e,{dir:F(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});Pe(e,F(t,"hooks","hooks.json"),n),Pe(e,F(t,"hooks.json"),n);let i=e.components.length-o,a=s>=pi;return{componentCount:i,expandTruncated:a}}function er(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 fi(e){let t=F(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(F(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",f=typeof u.version=="string"?u.version:"",h=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,_=0,I=!1;for(let w of l)if(typeof w.installPath=="string"&&w.installPath.length>0){let N=Qn(e,w.installPath,S,p);_+=N.componentCount,I=I||N.expandTruncated}er(e,{pluginKey:a,rowPath:i,enabled:p,scope:h,version:f||void 0,marketplace:m||void 0,componentCount:_,expandTruncated:I,contentHash:P(`${a}|${f}|${h}|${p}|${_}`)})}}function dp(e){let t=e,n="";try{let r=up(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=F(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=F(e,s),n=s)}}catch{}return{installPath:t,version:n}}var pp=/^\d+$/;function fp(e){let t=e.filter(n=>!pp.test(n.pluginId));return t.length>0?t:e}function mi(e){let t=[{base:F(e.home,".cursor/plugins/local"),scope:"local"},{base:F(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,c=F(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:p}=Qn(e,c,l,!0);er(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:p,contentHash:P(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(F(n,s))){if(!a.isDirectory())continue;let c=F(n,s,a.name),{installPath:l,version:u}=dp(c);i.push({pluginId:a.name,installPath:l,version:u})}for(let a of fp(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:p}=Qn(e,a.installPath,l,!0);er(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:p,contentHash:P(`${c}|${a.version}|${u}`)})}}}function gp(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Re(e,{dir:be(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Re(e,{dir:be(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=zs(i.map(c=>be(r,c)));a&&vt(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:mp(a)})}for(let i of Fo(n))Pe(e,be(r,i),o);for(let i of n.mcpJson??[])ui(e,be(r,i),o);for(let i of n.mcpToml??[])di(e,be(r,i),o);if(s){if(n.managed)for(let i of it(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&Pe(e,i,o);n.plugins==="claude"?fi(e):n.plugins==="cursor"&&mi(e)}}function gi(e,t){try{let n=new xt(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)gp(n,{layout:r,levelDir:t.levelDir,origin:t.origin,includeMachineWide:t.includeMachineWide});return{scopeRef:t.scopeRef,anchor:t.levelDir,components:n.components,truncated:n.truncated}}catch{return}}function tr(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=gi(t,{layouts:Object.values(xe),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:ie,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(ue),l=Kn({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>$o(c,u)});i=l.parentRel;for(let u of l.anchors){let p=Dn(u.dir);if(o!==void 0&&!o(u.scope,p))continue;let m=gi(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Bn,scopeRef:p});m&&(r[u.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function nr(e,t,n={}){let r=n.truncated===!0,o=We(e),s=new Set(e.map(u=>B(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 p=B(u.path,u.name);c[p]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let p=Ps(u);p&&l.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:l,unchanged:a.length===0&&l.length===0}}var _i=2*1024*1024,hp=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function rr(e,t,n){let r=new Set(t.map(s=>B(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(B(s.path,s.name))||o.push(s));return o}function or(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 hi(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Si(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function sr(e,t=_i){let n=[],r=[];for(let u of e)hp.has(u.kind)?n.push(u):r.push(u);r.sort((u,p)=>(u.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let p=s.length>0?1:0,m=hi(u)+p;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 f=Si(u),h=hi(f)+p;if(i+h<=t){s.push(f),i+=h,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function ir(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Si(n))}var _p=["user","cwd","repo","parent"];function ar(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let v of _p){let O=t.scopes[v];if(!O)continue;let L=n(v,O.scopeRef),T=L.components,j=nr(O.components,T,{forceFull:T===void 0,truncated:O.truncated}),te=new Set(L.textHashes),ne=rr(O.components,j.upserts,te),M=ir([...j.upserts,...ne],te);s.push({scope:v,walk:O,delta:j,outgoing:M,outgoingKeys:new Set(M.map(E=>B(E.path,E.name))),deliveredTextHashes:te,cachedComponents:T})}let i=s.flatMap(v=>v.outgoing),a=sr(i,o),c=new Set(a.components.map(v=>B(v.path,v.name))),l=[],u=[],p=[],m=[],f=[],h=[],S=[];for(let v of s){let{scope:O,walk:L,delta:T}=v;h.push(...L.components),l.push(O);let j=a.components.filter(E=>v.outgoingKeys.has(B(E.path,E.name))),te=[...v.outgoingKeys].some(E=>!c.has(E)),ne=T.truncated||te;ne?p.push(O):T.full&&u.push(O),m.push(...j),!T.full&&!ne&&f.push(...T.removed);let M=T.full?{}:{...v.cachedComponents??{}};if(!ne)for(let E of T.removed)delete M[B(E.path,E.name)];for(let E of j)M[B(E.path,E.name)]=E.content_hash;S.push({scope:O,scopeRef:L.scopeRef,components:M,textHashes:or(v.deliveredTextHashes,j.filter(E=>E.text!==void 0).map(E=>E.content_hash),L.components),collectedAtMs:r,included:j.length>0||T.removed.length>0&&!ne||T.full})}let _={user_spec_hash:We(h),user_spec_count:h.length,user_spec_truncated:p.length>0};l.length>0&&(_.user_spec_scopes=l,_.user_spec_full_scopes=u,_.user_spec_truncated_scopes=p,_.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(_.user_spec_full=!0),m.length>0&&(_.user_spec=m),f.length>0&&(_.user_spec_removed=f),a.textDeferredCount>0&&(_.user_spec_text_deferred=a.textDeferredCount);let I=t.scopes.cwd;I&&(_.user_spec_cwd_scope_ref=I.scopeRef);let w=t.scopes.repo;w&&(_.user_spec_repo_scope_ref=w.scopeRef);let N=t.scopes.parent;return N&&(_.user_spec_parent_scope_ref=N.scopeRef,t.parentRel&&(_.user_spec_parent_rel=t.parentRel)),{fields:_,scopes:S}}var qe={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function Ut(e){return e==="cwd"||e==="repo"||e==="parent"}function Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function cr(e){return!Ze(e)||!Ze(e.components)||!Object.values(e.components).every(t=>typeof t=="string")||!Array.isArray(e.text_hashes)||!e.text_hashes.every(t=>typeof t=="string")?!1:typeof e.collected_at_ms=="number"&&Number.isFinite(e.collected_at_ms)}function Ei(e){return Sp(e)}function yi(e){return Ep(e)}function Ri(e){return yp(e)}function Sp(e){if(!Ze(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function Ep(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function lr(e,t){if(!Ze(e))return;let n=e[t];return cr(n)?n:void 0}function yp(e){if(!Ze(e))return{};let t={};for(let[n,r]of Object.entries(e))cr(r)&&(t[n]=r);return t}function ur(e,t=20){let n=[];for(let[r,o]of Object.entries(e))cr(o)&&n.push([r,o]);return n.sort((r,o)=>o[1].collected_at_ms-r[1].collected_at_ms),Object.fromEntries(n.slice(0,t))}var Ip=200,Ci=200,Ap=["allow","deny","ask"],xp=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,pr="<path>",vp=new RegExp(`${pr}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Op(e){let t=e.replace(xp,pr).replace(vp,pr);return t.length>Ci?`${t.slice(0,Ci)}...`:t}function Lt(e){let t=W(e,{}),n=[];for(let r of Ap)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Op(o),mode:r});return{model:t.model??"",permissionKeys:n}}function Pp(e){let{serverManaged:t,fileBased:n}=Zt(process.platform,e),r=Lt(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=Lt(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function bp(e){let t=new Set,n=[];for(let r of e){let o=`${r.mode}\0${r.key}`;t.has(o)||(t.add(o),n.push(r))}return n}var wp=10,Tp=840*60*1e3,Mp="self-config-cache.json",Ii=2;function fr(){return k("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Up(){return k("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function Np(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Tp}var Lp={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Dp(e,t=b){let n=Lp[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(`
28
+ `)[0]??"").trim();return a||r(o+1)};return r(0)}function Hp(e=ki()){return we(e,".ev-ai","agent-hook",Mp)}function Fp(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
29
+ `);return P(n)}function Nt(e,t,n=!1){let r=Fp(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 dr(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>we(e,a)),...n]){let a=kp(i);if(s.has(a))continue;s.add(a);let c=nn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function jp(e){return Rp(e)?U(Cp(e,"utf8"),{}):{}}function $p(e,t){try{se(e,`${JSON.stringify(t)}
30
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: self-config cache write failed open: ${r}`)}}function Kp(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(Ut(t))return lr(e[qe[t]],n)?.collected_at_ms}function Bp(e,t,n){if(t==="user")return{components:Ei(e.user_spec_components),textHashes:yi(e.user_spec_text_hashes)};if(!Ut(t))return{components:void 0,textHashes:[]};let r=lr(e[qe[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function Gp(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}if(r){o.user_spec_layout_version=Ii,r.home&&(o.user_spec_collected_at_ms=r.home.collectedAtMs,r.home.included&&(o.user_spec=r.hash,o.user_spec_components=r.home.components),o.user_spec_text_hashes=r.home.textHashes);for(let s of r.project){if(!Ut(s.scope))continue;let i=qe[s.scope],a=Ri(o[i]),c=a[s.scopeRef];a[s.scopeRef]={components:s.included?s.components:c?.components??{},text_hashes:s.textHashes,collected_at_ms:s.collectedAtMs},o[i]=ur(a)}}return o}async function Ai(e,t=process.cwd(),n=ki(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await Dp(e),a="",c=[];if(o){let M=Pp(n),E=Lt(we(n,".claude/settings.json")),D=Lt(we(t,".claude/settings.local.json"));a=M.model||D.model||E.model,c=bp([...M.permissionKeys,...E.permissionKeys,...D.permissionKeys]).slice(0,Ip)}let l={present:!1,size:0},u=M=>{let E=[],D=!1;for(let G of M){let re=Fr(we(n,G));if(E=E.concat(re.entries),D=D||re.truncated,E.length>=ie){E=E.slice(0,ie),D=!0;break}}return{entries:E,truncated:D}},p=Hp(n),m=jp(p),f=m[e]??{},h=(f.send_count??0)+1,S=h>0&&h%wp===0,_=M=>S?void 0:f[M],I=u(pe.skills),w=u(pe.subagents),N=u(pe.commands),v=u(pe.rules),O={skills:Nt(I.entries,_("skills"),I.truncated),subagents:Nt(w.entries,_("subagents"),w.truncated),commands:Nt(N.entries,_("commands"),N.truncated),rules:Nt(v.entries,_("rules"),v.truncated)},L={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:O.skills,subagents:O.subagents,commands:O.commands,rules:O.rules,memory:dr(n,pe.memory),settings:dr(n,pe.settings,Ko(n)),mcp:dr(n,pe.mcp)},local_settings:o?nn(we(t,".claude/settings.local.json")):l},T=null,j=()=>{},te=r.nowMs??Date.now();if(!fr()){let M=f.user_spec_layout_version!==Ii,E=tr(e,n,{launchCwd:Up()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(D,G)=>M||Np(Kp(f,D,G),te)});if(Object.keys(E.scopes).length>0){let D=ar({collected:E,cacheFor:(G,re)=>M?{components:void 0,textHashes:[]}:Bp(f,G,re),nowMs:te});if(Object.assign(L,D.fields),T={hash:D.fields.user_spec_hash,home:D.scopes.find(G=>G.scope==="user")??null,project:D.scopes.filter(G=>G.scope!=="user")},E.scopes.user){let G=f.user_spec_collected_at_ms!==void 0,re=await Ct({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:G});re.operator&&(L.operator=re.operator),j=re.commit}}}let ne=Gp(f,O,h,T);return{config:L,commit:()=>{m[e]=ne,$p(p,m),j()}}}function Te(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:at(),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:X,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as vi}from"node:fs";import{spawn as Oi}from"node:child_process";import{basename as Jp}from"node:path";import{fileURLToPath as Wp}from"node:url";import{gzipSync as zp}from"node:zlib";function mr(e){return k("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<Ar?{body:e}:{body:zp(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function Dt(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function xi(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var Qe="__post",Ht="__work";function Vp(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 Pi(e){switch(e){case"session_start":return yr;case"session_end":return Rr;case"tool_invoked":case"skill_invoked":return Wt;default:return Wt}}function Yp(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
31
+ ${n}`}function bi(e,t=[],n=process.execPath,r=import.meta.url,o=vi){if(Jp(n)===oe)return{command:n,args:[e,...t]};let s=Wp(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Xp(e=process.execPath,t=import.meta.url,n=vi){return bi(Qe,[],e,t,n)}function Zp(e){let t=e.indexOf(`
32
+ `);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 Ft(e,t=fetch){let n=await e(),r=Zp(n);if(!r)return;let{meta:o,body:s}=r,i=mr(s),a=Dt(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function qp(e,t,n,r=fetch){let o=Pi(e),s=mr(t),i=Dt(s.contentEncoding),a=xi(s.body);d(`POST event=${e} url=${Yt(n)} size=${a} encoding=${s.contentEncoding??"identity"} platform=${process.platform}`);let c=Date.now();try{let l=await r(n,{method:"POST",headers:i,body:s.body,signal:AbortSignal.timeout(o)});if(!l.ok&&s.contentEncoding==="gzip"&&(l.status===400||l.status===415)){try{await l.text()}catch{}d(`POST gzip rejected http=${l.status} \u2014 retrying uncompressed`),l=await r(n,{method:"POST",headers:Dt(),body:t,signal:AbortSignal.timeout(o)})}let u=Date.now()-c;if(l.ok)return d(`POST outcome=ok elapsed_ms=${u} http=${l.status}`),!0;let p=(await l.text()).slice(0,200).replace(/[\n\r]/g,"");return d(`POST outcome=fail elapsed_ms=${u} http=${l.status} body=${p}`),!1}catch(l){let u=Date.now()-c,p=l instanceof Error?l.message:String(l);return d(`POST outcome=fail elapsed_ms=${u} http=000 body=${p}`),!1}}async function wi(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){d(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},Cr),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 d(`WARN: ${o} spawn failed open: ${i}`),null}}async function Qp(e,t,n,r=Oi,o=Xp){let s=Pi(e),i=Yp(n,s,t),{command:a,args:c}=o();return wi(a,c,i,r,"detached post")}async function Ti(e,t,n=Oi,r=bi){let{command:o,args:s}=r(Ht,t);return wi(o,s,e,n,"detached work")}async function Me(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(!ot(o))return d(`WARN: collector URL blocked (https required): ${Yt(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)}
33
+ `,c=k("EV_AI_HOOK_DEBUG");c==="full"?d(`DEBUG envelope=${JSON.stringify(i)}`):c==="1"&&d(`DEBUG summary=${Vp(i,Buffer.byteLength(a,"utf8"))}`);let l=process.argv.includes(Ht),u=k("EV_AI_HOOK_SYNC")==="1";return Rt(n.runnerEvent,n.runnerPlatform)||l||u?qp(e,a,o):(await Qp(e,a,o),!1)}import{createReadStream as ef}from"node:fs";import{stat as tf}from"node:fs/promises";import{basename as nf,resolve as rf}from"node:path";import{createInterface as of}from"node:readline";var sf=1024*1024;function af(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&nf(t).endsWith(".jsonl")}async function Mi(e){if(!e||!af(e))return null;try{let t=rf(e),n=await tf(t);if(!n.isFile())return null;let r=Math.max(0,n.size-sf),o=[],s=of({input:ef(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 $t(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function gr(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}async function Li(e){let t=Date.now();await _f(e);let{gitRoot:n}=e.manifest;await Kt(e,n);let r=gr(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:It(e.hookInput,e.manifest.manifest,r),envelopeFields:$t(e),launchCwd:jn(e.hookInput,r),home:lf()}}function Ui(e){try{return K(cf(e))}catch{return null}}function Di(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function Ni(e,t){let n=e.replaceAll("\\","/");if(!Di(n))return null;let r=K(e),o=K(t),s=Ui(e)??r,i=Ui(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function uf(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=Ni(e,t)??(Di(r)?null:r),i=Ni(e,n);return{repositorySourcePath:s,userSourcePath:i}}function jt(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=uf(e,t,n),c=i??a,l=c===null?null:o(c),u=l!==null&&c!==null?df({installableKind:r,sourcePath:c,nativeKey:l,inRepository:i!==null,platformAgentId:s.platformAgentId,installationId:s.manifest.installationId}):void 0;return{sourcePath:c,nativeKey:l,componentReference:u}}function df(e){try{let t=e.inRepository?pf(e.platformAgentId,e.sourcePath):(0,C.installationRootExternalKey)(e.installationId,(0,C.userConfigRootFromPath)(e.sourcePath));return t?(0,C.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function Hi(e,t,n){return Me("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Te,e.manifest.collectorUrl,t.buildStartedAtMs)}var Fi=new Set([...Object.values(ye),".github"]);function pf(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n),o=t.replaceAll("\\","/").split("/").filter(Boolean),s=o.findIndex(i=>Fi.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function ff(e,t,n,r,o,s,i){if(e===null||t===null||!(i!==null||/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||/^MCP:.+__.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let c=s.find(h=>h.name.toLowerCase()===t.toLowerCase()),l=c?.sourcePath??(c?.source==="claude_json_user"?".claude.json":c?.source==="cursor_mcp_user"?".cursor/mcp.json":c?.source==="codex_toml_user"||c===void 0&&o==="codex"?".codex/config.toml":void 0);if((c?.scope==="user"||c?.source==="claude_json_user"||c?.source==="cursor_mcp_user"||c?.source==="codex_toml_user"||c===void 0&&o==="codex")&&l)try{let h=(0,C.userConfigRootFromPath)(l);return(0,C.buildComponentReference)({installationRootExternalKey:(0,C.installationRootExternalKey)(r,h),installableKind:C.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),f=m.replaceAll("\\","/").split("/").at(-1);if(!(f===void 0||!Fi.has(f)))try{return(0,C.buildComponentReference)({installationRootExternalKey:n,installableKind:C.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function mf(...e){for(let t of e)if(t)return t;return null}function J(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 gf(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 hf(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var ke=new Set,et=null;async function _f(e){if(fr())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(ke.has(t))return;if(!Hn(n)){ke.add(t);return}let r=De({sessionId:e.sessionId,hostname:He()});if(Ts(r)){if(et){await et;return}et=(async()=>{if(ke.has(t)||!Hn(n)){ke.add(t);return}if(!oo(n)){ke.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,p,m]=await Promise.allSettled([Be(i),sn(),Nn(r),an(),Ct({gitRoot:i,installationStorePath:n,forceResend:!1})]),f=J(c,null,"gitSnapshot"),h=J(l,"","detectVirt"),S=J(u,null,"probeCloud"),_=J(p,{},"hostEnv"),I=J(m,{commit:()=>{}},"resolveOperatorForSend");await Kt(e,i,f);let w={identity:{host:He(),context:r,virt:h||null,cloud:S,git:f},host_env:_,env_vars:Ln(),self_config:hf(a,I.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await Me("session_start",w,$t(e),Te,e.manifest.collectorUrl,s),o&&(I.commit(),ke.add(t))}finally{so(n)}})().finally(()=>{et=null}),await et}}async function Kt(e,t,n){try{let r=n===void 0?await Be(t):n;e.platformAgentId=await Qo(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 Sf(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=De({sessionId:e.sessionId,hostname:He()}),o=String(e.runnerPlatform),s=gr(e),i=jn(e.hookInput,s),a=Be(n),[c,l,u,p,m,f]=await Promise.allSettled([a,sn(),Nn(r),an(),bn(e.manifest.manifest,n,o),a.catch(()=>null).then(j=>Ai(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:j?.remote??null}))]),h=J(c,null,"gitSnapshot"),S=J(l,"","detectVirt"),_=J(u,null,"probeCloud"),I=J(p,{},"hostEnv"),w=J(m,[],"mcpDeclared"),N=J(f,gf(o),"selfConfig"),v=N.config;await Kt(e,n,h);let O=g(e.hookInput,"model");O&&(v.model=O);let L={identity:{host:He(),context:r,virt:S||null,cloud:_,git:h},host_env:I,env_vars:Ln(),mcp:{declared:w},self_config:v,run_meta:{trigger:e.hookSource||"startup"},hook_input:It(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})};await Me("session_start",L,$t(e),Te,e.manifest.collectorUrl,t)&&(N.commit(),ke.add(e.manifest.installationId))}async function Ef(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Kt(e,n);let r=mf(g(e.hookInput,"status"),g(e.hookInput,"stop_reason"),g(e.hookInput,"reason"),Je(g(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await Mi(g(e.hookInput,"transcript_path")):null,s=It(e.hookInput,e.manifest.manifest,gr(e));o&&(s.model=o),await Me("session_end",{status:r,...o?{model:o}:{},hook_input:s},$t(e),Te,e.manifest.collectorUrl,t)}function ji(e,t,n,r){let o=r??Vo({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=jt(o,t.gitRoot,t.home,C.ComponentKind.SKILL,C.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&Cn(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??os({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=jt(i,t.gitRoot,t.home,C.ComponentKind.COMMAND,C.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function yf(e,t,n){let r=gt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=ji(e,t,o,r);return Hi(e,t,{tool_name:"Skill",skill_name:o,...s.commandName===void 0?{}:{command_name:s.commandName},...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}function Rf(e,t,n){return Promise.all(n.map(r=>{let o=es({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=jt(o,t.gitRoot,t.home,C.ComponentKind.RULE,C.nativeKeyForRulePath,e),i=s.nativeKey??ns(r);return Hi(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var Cf=[{kind:C.ComponentKind.SKILL,nativeKeyFn:C.nativeKeyForSkillPath},{kind:C.ComponentKind.RULE,nativeKeyFn:C.nativeKeyForRulePath},{kind:C.ComponentKind.COMMAND,nativeKeyFn:C.nativeKeyForCommandPath}];function kf(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=In(e.hookInput);if(r===null)return n.skillName===null?{}:ji(e,t,n.skillName,null);for(let o of Cf){let s=jt(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===C.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===C.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var If=/mcp/i;function Af(e,t,n,r){let o=If.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?ci(t,n):Mt(r.declaredConfig,n);return s===null?{}:Object.fromEntries(Object.entries(s).filter(i=>typeof i[1]=="string").map(([i,a])=>[`mcp_${i}`,a]))}async function xf(e){let t=await Li(e),n=hs(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=kn(e.hookInput),i=ii(s,t.home),a=Ss(e.hookInput),c=ps(e.runnerEvent),l=c===!1?Es(e.hookInput,e.runnerEvent):null,u=await bn(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=Je(g(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:f}=ys(r,u.map(L=>L.name),p??""),h=ff(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),u,p),S=h===void 0?kf(e,t,n):{},_=m===null?null:us(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),I=Af(e,s,t.home,{hasMcpIdentity:!!m||!!f,declaredConfig:_}),w=h??S.componentReference,N=S.ruleName??n.ruleName,v=S.commandName??n.commandName,O=_s(e.hookInput);await Me("tool_invoked",{tool_name:r,skill_name:o,...N?{rule_name:N}:{},...v?{command_name:v}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...m?{mcp_server:m}:{},...f?{mcp_tool:f}:{},...I,...w?{component_reference:w}:{},...O?{subagent_type:O}:{},hook_input:t.hookInput},t.envelopeFields,Te,e.manifest.collectorUrl,t.buildStartedAtMs)}async function $i(e){switch(e.internalEvent){case"session_start":await Sf(e);return;case"session_end":await Ef(e);return;case"skill_invoked":{let t=Yo(e.hookInput),n=rs(e.hookInput);if(t.length===0&&n.length===0)return;let r=await Li(e);await Promise.all([t.length===0?void 0:yf(e,r,t),n.length===0?void 0:Rf(e,r,n)]);return}case"tool_invoked":await xf(e);return;default:return}}function Ki(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function Bi(e,t,n,r){let o=t??await en(Vt),s=U(o,{}),i=g(s,"session_id")||g(s,"conversation_id"),a=await uo(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=fs(s,a.manifest.platform,n),l=ms(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:a,platformAgentId:a.platformAgentId};if(Ki(l)){d(`WARN: unsupported internal event '${l}'`);return}await $i(u)}function vf(e,t){if(k("EV_AI_HOOK_SYNC")==="1")return!0;let n=yt(e),r=U(t,{}),o=n.event??(g(r,"hook_event_name")||g(r,"event")),s=ze(r,o,void 0,n.runner);return Rt(o,s)}async function Gi(e=process.argv.slice(2)){if(e[0]===Qe){try{await Ft(Le)}catch{}return 0}if(e[0]===Ht){try{let t=yt(e.slice(1)),n=await Le(),r=U(n,{}),o=t.event??(g(r,"hook_event_name")||g(r,"event"));if(rn()||Mn(t.runner,r,o))return 0;await Bi(t.event,n,t.runner,Tn(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 en(Vt),n=yt(e),r=Tn(n),o=U(t,{}),s=n.event??(g(o,"hook_event_name")||g(o,"event"));if(rn()||Mn(n.runner,o,s)||!vs(o,s,n.runner))return 0;vf(e,t)?await Bi(n.event,t,n.runner,r):await Ti(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{Hr()}return 0}function Bt(){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 zi(e){return e.includes("--help")||e.includes("-h")}async function Tf(e=process.argv.slice(2)){let[t,...n]=e;if(t===Qe){try{await Ft(Le)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${X}
34
+ `),0):t==="configure"?zi(n)?(Bt(),0):(await Mo(Eo(n)),0):t==="install"?zi(n)?(Bt(),0):(await wo(yo(n)),0):t==="migrate-to-plugin"?(await No(),0):t==="update"?(await To(),0):t==="uninstall"?(await Lo(),0):t==="help"||t==="--help"||t==="-h"?(Bt(),0):t===void 0?(Bt(),1):Gi(e)}function Mf(e,t,n=Of){if(!t)return!1;try{return e===wf(Pf(t)).href?!0:n(bf(e))===n(t)}catch{return!1}}Mf(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&Tf().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);d(t),process.exit(1)});export{Mf as isCliEntrypoint,Tf as main};