@ev-ai/agent-hook 1.0.8 → 1.0.10

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