@ev-ai/agent-hook 1.0.6 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/COLLECTED-DATA.md +21 -13
- package/README.md +50 -57
- package/dist/cli.mjs +25 -16
- package/dist/hook.mjs +21 -11
- package/dist/plugin-hooks.mjs +11 -6
- package/package.json +4 -26
package/dist/hook.mjs
CHANGED
|
@@ -1,12 +1,22 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);u(`WARN: cloud cache write failed open: ${r}`)}}function wn(t,e,n){if(!t||t.context!==e)return!1;let r=t.result===null?kn:En;return n-t.probed_at<r}async function An(t){let e=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(t)}).catch(()=>{});if(!e?.ok)return;let n=(await e.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(t)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(t)}).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 Cn(t){let e=await fetch("http://metadata.google.internal/computeMetadata/v1/instance/?recursive=true",{headers:{"Metadata-Flavor":"Google"},signal:AbortSignal.timeout(t)}).catch(()=>{});if(!e?.ok)return;let n=await e.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 Tn(t){let e=await fetch("http://169.254.169.254/metadata/instance?api-version=2021-02-01",{headers:{Metadata:"true"},signal:AbortSignal.timeout(t)}).catch(()=>{});if(!e?.ok)return;let n=await e.json(),r=n.compute?.location??"",o=n.compute?.vmId??"";if(!(!r&&!o))return{provider:"azure",region:r,instance_id:o}}async function xn(t){let e=await Promise.allSettled([An(t),Cn(t),Tn(t)]);for(let n of e)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Xt(t,e){if(t==="interactive")return null;let n=e?.home??Yt(),r=e?.timeoutMs??1e3,o=e?.nowMs??Date.now(),s=In(n),a=Rn(s);if(wn(a,t,o))return a.result;let i=await xn(r);return vn(s,{context:t,probed_at:o,result:i}),i}import{existsSync as Nn,readFileSync as Pn}from"node:fs";import{homedir as bn}from"node:os";import{join as it}from"node:path";function at(t,e,n){if(!Nn(t))return;let r=g(Pn(t,"utf8"),{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,source:e})}async function Zt(t,e=process.cwd(),n="claude",r=bn()){let o=new Map;for(let s of t.mcp_servers??[])s.name&&o.set(s.name,{name:s.name,source:"manifest"});return n==="claude"&&at(it(r,".claude.json"),"claude_json_user",o),at(it(e,".mcp.json"),"mcp_json",o),at(it(e,".cursor/mcp.json"),"cursor_mcp",o),[...o.values()]}var On=["CI","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","GITHUB_REPOSITORY","GITHUB_REF","GITHUB_SHA","GITHUB_RUN_ID","GITHUB_WORKFLOW","RUNNER_OS","RUNNER_ARCH","NODE_ENV","TERM_PROGRAM","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"],Ln=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Mn(t){try{let e=new URL(t);(e.username||e.password)&&(e.username="",e.password="");for(let[n]of e.searchParams)Ln.has(n.toLowerCase())&&e.searchParams.set(n,"[redacted]");return e.toString()}catch{return t}}function qt(t=process.env){return On.map(e=>Object.prototype.hasOwnProperty.call(t,e)?{name:e,present:!0,value:Mn(t[e]??"")}:{name:e,present:!1})}import{createHash as Hn}from"node:crypto";import{existsSync as ee,readFileSync as ne}from"node:fs";import{homedir as re}from"node:os";import{join as _}from"node:path";var Fn={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"],commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:".agents/skills",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},Un=200,Qt=200,Dn=["allow","deny","ask"],$n=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,ct="<path>",Kn=new RegExp(`${ct}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function jn(t){let e=t.replace($n,ct).replace(Kn,ct);return e.length>Qt?`${e.slice(0,Qt)}...`:e}function te(t){if(!ee(t))return{model:"",permissionKeys:[]};let e=g(ne(t,"utf8"),{}),n=[];for(let r of Dn)for(let o of e.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:jn(o),mode:r});return{model:e.model??"",permissionKeys:n}}var Bn=10,zn="self-config-cache.json",Wn={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Vn(t,e=m){let n=Wn[t];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let i=((await e(s,["--version"],2e3)).split(`
|
|
6
|
-
`)
|
|
7
|
-
|
|
8
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);u(`WARN: self-config cache write failed open: ${r}`)}}function Zn(t,e,n){let r={...t,send_count:n};for(let o of Object.keys(e)){let s=e[o];s.entries!==void 0&&(r[o]=s.hash)}return r}async function oe(t,e=process.cwd(),n=re()){let r=t==="claude",o=await Vn(t),s="",a=[];if(r){let h=te(_(n,".claude/settings.json")),H=te(_(e,".claude/settings.local.json"));s=H.model||h.model,a=[...h.permissionKeys,...H.permissionKeys].slice(0,Un)}let i=Fn[t]??{},c={present:!1,size:0},d=h=>{let H=Array.isArray(h)?h:h?[h]:[],v=[],F=!1;for(let $e of H){let kt=N(_(n,$e));if(v=v.concat(kt.entries),F=F||kt.truncated,v.length>=K){v=v.slice(0,K),F=!0;break}}return{entries:v,truncated:F}},f=Gn(n),k=Yn(f),y=k[t]??{},E=(y.send_count??0)+1,q=E>0&&E%Bn===0,I=h=>q?void 0:y[h],C=d(i.skills),M=i.subagents?N(_(n,i.subagents)):{entries:[],truncated:!1},yt=i.commands?N(_(n,i.commands)):{entries:[],truncated:!1},Et=i.rules?N(_(n,i.rules)):{entries:[],truncated:!1},T={skills:W(C.entries,I("skills"),C.truncated),subagents:W(M.entries,I("subagents"),M.truncated),commands:W(yt.entries,I("commands"),yt.truncated),rules:W(Et.entries,I("rules"),Et.truncated)};return k[t]=Zn(y,T,E),Xn(f,k),{runner_platform:t,config_scope:"user",cli_version:o,claude_version:r?o:null,model:r&&s||null,permission_keys:a,user_scope:{skills:T.skills,subagents:T.subagents,commands:T.commands,rules:T.rules,memory:i.memory?P(_(n,i.memory)):c,settings:i.settings?P(_(n,i.settings)):c,mcp:i.mcp?P(_(n,i.mcp)):c},local_settings:r?P(_(e,".claude/settings.local.json")):c}}function b(t,e,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:t,timestamp:Mt(),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:et,host_arch:process.arch,node_version:process.version,correlation:r,payload:e}}import{existsSync as Re}from"node:fs";import{spawn as ve}from"node:child_process";import{basename as Rr}from"node:path";import{fileURLToPath as vr}from"node:url";var qn=new Set(["localhost","127.0.0.1","[::1]","::1"]),se=/^[A-Za-z0-9._~-]+$/;function ie(t){for(let e=0;e<t.length;e++){let n=t.charCodeAt(e);if(n<=32||n===127||n===39)return!0}return!1}function V(t){try{let e=new URL(t);return e.protocol==="https:"?!0:e.protocol==="http:"?qn.has(e.hostname):!1}catch{return!1}}function ae(t){let e;try{e=new URL(t)}catch{return`invalid URL (got: ${t})`}if(!V(t))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${t})`;let n=Qn(t);if(!n)return`must end with /{orgToken}/hook (got: ${t})`;if(!se.test(n))return`org token must match ${se.source} (got: ${n})`;if(ie(t))return`must not contain whitespace, control characters, or single quotes (got: ${t})`;if(ie(e.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${t})`}function ce(t){return new URL(t).toString()}function Qn(t){try{let n=new URL(t).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function ut(t){try{let e=new URL(t),n=e.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",e.pathname=`/${n.join("/")}`),e.toString()}catch{return"<invalid-url>"}}function le(t){if(t.collector_url)return t.collector_url;let e=t.repo_ingest_token?.trim();return e?U(e):""}var ue=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,de=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,tr=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,er=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"]),nr=new Set(["read","read_file","view"]),rr=new Set(["bash","shell","zsh"]);function or(t){let e=t.replace(/\\/g,"/");return ue.exec(e)?.[1]??null}function sr(t){let e=t.replace(/\\/g,"/"),r=de.exec(e)?.[1];return r?r.toLowerCase():null}function ir(t){return or(t)??sr(t)}function ar(t){for(let e of["path","file_path","target_file"]){let n=t[e];if(typeof n=="string"&&n.length>0)return n}return null}function fe(t){if(typeof t=="string")try{let e=JSON.parse(t);return fe(e)}catch{return null}return!t||typeof t!="object"?null:ar(t)}function cr(t){if(!t||typeof t!="object")return null;let e=t.command;return typeof e=="string"&&e.length>0?e:null}function lr(t){let e=t.replace(/\\/g,"/"),n=ue.exec(e);if(n?.[1])return n[1];let o=de.exec(e)?.[1];return o?o.toLowerCase():null}function ur(t){return typeof t.tool_name=="string"?t.tool_name:typeof t.tool=="string"?t.tool:""}function pe(t){let e=ur(t).toLowerCase();if(nr.has(e)){let n=fe(t.tool_input);return n?ir(n):null}if(rr.has(e)){let n=cr(t.tool_input);return n?lr(n):null}return null}function dr(t){let e=new Set,n=[];for(let r of t.matchAll(tr)){let o=r[1]?.toLowerCase();!o||e.has(o)||er.has(o)||(e.add(o),n.push(o))}return n}function fr(t){return x(t.prompt)}function me(t){let e=l(t,"command_name");if(e){let r=l(t,"expansion_type");if(r&&r!=="slash_command")return[];let o=e.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=fr(t);return n?dr(n):[]}function dt(t){return t!==void 0&&Tt.includes(t)}function G(t,e){let n=t[e+1];return n&&!n.startsWith("--")?{value:n,next:e+1}:{next:e}}function J(t){let e,n,r,o,s;for(let a=0;a<t.length;a++){let i=t[a];if(i!==void 0){if(i==="--runner"){let c=G(t,a);e=c.value,a=c.next;continue}if(i.startsWith("--runner=")){e=i.slice(9);continue}if(i==="--url"){let c=G(t,a);c.value&&(r=c.value),a=c.next;continue}if(i.startsWith("--url=")){r=i.slice(6);continue}if(i==="--token"){let c=G(t,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=G(t,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:dt(e)?e:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function ft(t){let e=t.collectorUrl?.trim(),n;if(e)n=e;else{let o=t.orgToken?.trim();o&&(n=U(o,t.baseUrl?.trim()??void 0))}if(!n)return;let r=ae(n);if(r){u(`WARN: ignoring --url/--token collector override: ${r}`);return}return ce(n)}function pr(t,e){return l(t,"conversation_id")?!0:e!==""&&e===e.toLowerCase()}function pt(t,e,n,r){if(pr(t,e))return"cursor";if(dt(r))return r;let o=l(t,"conversation_id"),s=l(t,"turn_id"),a=l(t,"session_id"),i=e.toLowerCase(),c="unknown";return o||e===i&&e!==""?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"),dt(n)&&(c=n),c}function Y(t,e){let n=t.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&e==="codex"}function mr(t){switch(t){case"sessionstart":return"session_start";case"stop":case"sessionend":case"stopfailure":return"session_end";case"pretooluse":case"posttooluse":case"posttoolusefailure":case"permissiondenied":case"beforemcpexecution":case"beforeshellexecution":case"afterfileedit":case"subagentstart":case"subagentstop":return"tool_invoked";case"beforesubmitprompt":case"userpromptexpansion":case"userpromptsubmit":return"skill_invoked";default:return""}}function ge(t){let e=t.toLowerCase();return e==="posttooluse"?!0:e==="posttoolusefailure"||e==="permissiondenied"?!1:null}function _e(t,e,n){let r=l(t,"session_id")||l(t,"conversation_id"),o=l(t,"prompt.id")||l(t,"prompt_id")||l(t,"generation_id")||l(t,"turn_id"),s=l(t,"hook_event_name")||l(t,"event"),a=l(t,"source"),i=pt(t,s,e,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:a,runnerPlatform:i}}var gr=["session_start","session_end","tool_invoked","skill_invoked"];function _r(t){return gr.includes(t)}function he(t,e){return t&&_r(t)?t:mr(e.toLowerCase())}function Se(t){let e=l(t,"tool_name")||l(t,"tool")||null,n=t.tool_input,o=(n&&typeof n=="object"?x(n.skill)||x(n.skill_name):"")||l(t,"skill_name")||null;return o??=pe(t),{toolName:e,skillName:o}}var hr=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function ye(t){for(let e of["subagent_type","agent_type"]){let n=l(t,e);if(n&&hr.test(n))return n}return null}function Ee(t){let e=R(t,"duration_ms");if(typeof e=="number")return e;let n=R(t,"duration");return typeof n=="number"?n:null}var Sr="error",yr="interrupted",Er="permission_denied",kr=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function mt(t){return kr.test(t)?t:null}function Ir(t){for(let e of["failure_type","error_type"]){let n=mt(l(t,e));if(n)return n}return null}function ke(t,e){return R(t,"is_interrupt")===!0?yr:e.toLowerCase()==="permissiondenied"?Er:Ir(t)??Sr}function Ie(t){if(!t)return{mcpServer:null,mcpTool:null};let e=/^mcp__(.+?)__(.+)$/i.exec(t);if(e?.[1]&&e[2])return{mcpServer:e[1],mcpTool:e[2]};if(/^MCP:/i.test(t)){let n=t.slice(4);if(!n)return{mcpServer:null,mcpTool:null};let r=n.indexOf(":");return r>0?{mcpServer:n.slice(0,r),mcpTool:n.slice(r+1)||null}:{mcpServer:null,mcpTool:n}}return{mcpServer:null,mcpTool:null}}var gt="__post",_t="__work";function wr(t,e){let n=t.payload,r=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],o=t.correlation&&typeof t.correlation=="object"?Object.keys(t.correlation):[];return JSON.stringify({event:t.event,schema_version:t.schema_version,agent_hook_version:t.agent_hook_version,host_arch:t.host_arch,node_version:t.node_version,body_bytes:e,correlation_keys:o,payload_keys:r})}function we(t){switch(t){case"session_start":return Rt;case"session_end":return vt;case"tool_invoked":case"skill_invoked":return Q;default:return Q}}function Ar(t,e,n){return`${JSON.stringify({url:t,timeoutMs:e})}
|
|
9
|
-
|
|
10
|
-
`)
|
|
11
|
-
`,
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
const require = __createRequire(import.meta.url);
|
|
3
|
+
|
|
4
|
+
var Gr=Object.create;var Ft=Object.defineProperty;var jr=Object.getOwnPropertyDescriptor;var Vr=Object.getOwnPropertyNames;var zr=Object.getPrototypeOf,Jr=Object.prototype.hasOwnProperty;var Bt=(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 Wr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Vr(t))!Jr.call(e,o)&&o!==n&&Ft(e,o,{get:()=>t[o],enumerable:!(r=jr(t,o))||r.enumerable});return e};var Xr=(e,t,n)=>(n=e!=null?Gr(zr(e)):{},Yr(t||!e||!e.__esModule?Ft(n,"default",{value:e,enumerable:!0}):n,e));var Qn=Wr(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.ComponentKind=void 0;H.normalizeRepositoryRelativePath=Zn;H.nativeKeyForSkillPath=Bs;H.serializeComponentIdentity=qn;H.buildComponentReference=Ks;H.validateComponentReference=Gs;var Ls=Bt("node:crypto"),Ms=Bt("node:path"),Ds="cmp1_",Hs=/^cmp1_[A-Za-z0-9_-]{43}$/,Fs=["/skills/","/skills-cursor/"];H.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE"};function Ne(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Zn(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=Ms.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Ne(n,"sourcePath")}function Bs(e){let t=e.replaceAll("\\","/");for(let n of Fs){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function $s(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function qn(e){let t=[Ne(e.installationRootExternalKey,"installationRootExternalKey"),Ne(e.installableKind,"installableKind"),Zn(e.sourcePath),Ne(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map($s).join("|")}`,"utf8")}function Ks(e){let t=(0,Ls.createHash)("sha256").update(qn(e)).digest("base64url");return`${Ds}${t}`}function Gs(e){return Hs.test(e)}});var Zr="https://hooks.ev-ai.ai";function Ie(e,t=Zr){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var $t=".claude/ev-ai-runtime-report.json";var Re="ev-ai-agent-hook";var ja=`current/${Re}`,Va=`.ev-ai/agent-hook/${Re}`,Kt=5e3,Gt=5e3,Be=3e3;var $e=3e3,jt=1500,Vt=4*1024,zt=32*1024,qr=4*1024,Ke="1.0.8",za=`@ev-ai/agent-hook@${Ke}`;var Jt=["claude","cursor","codex"];import{createHash as _s}from"node:crypto";import{existsSync as hs,mkdirSync as Es,readdirSync as Ss,readFileSync as Gn,unlinkSync as jn,writeFileSync as Is}from"node:fs";import{homedir as Vn}from"node:os";import{join as ct}from"node:path";import{createHash as cn,randomBytes as yo}from"node:crypto";import{existsSync as ln,mkdirSync as qe,readFileSync as un,unlinkSync as dn,writeFileSync as fn}from"node:fs";import{homedir as Qe}from"node:os";import{dirname as Ce,join as et,resolve as Co}from"node:path";var Qr=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),eo=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function V(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||eo.has(n)||r.includes("[bot]")||Qr.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 co,readFileSync as lo}from"node:fs";import{hostname as en,userInfo as uo}from"node:os";import{randomBytes as to}from"node:crypto";import{existsSync as je,mkdirSync as no,readdirSync as ro,readFileSync as oo,renameSync as Wt,statSync as Zt,unlinkSync as Yt,writeFileSync as so}from"node:fs";import{basename as io,dirname as Xt,join as qt,relative as ao}from"node:path";function g(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
|
|
5
|
+
`)}function K(e,t){no(Xt(e),{recursive:!0});let n=qt(Xt(e),`.${io(e)}.${process.pid}.${to(4).toString("hex")}.tmp`);try{so(n,t,"utf8");try{Wt(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Yt(e),Wt(n,e);return}throw r}}catch(r){try{Yt(n)}catch{}throw r}}function ye(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Qt(){process.stdout.write('{"continue":true}')}function y(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Ve(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function ze(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function v(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,l=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:l,spawnFailed:l===void 0}}}async function C(e,t,n=3e3,r={}){let o=await v(e,t,n,r);return o.ok?o.stdout:""}async function Je(e=process.cwd()){let t=await v("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(y("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;g(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=y("CURSOR_PROJECT_DIR")??y("CLAUDE_PROJECT_DIR");if(n&&je(n)){let r=await v("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function We(e=process.cwd()){return(await Je(e)).root}function w(e,t){try{return JSON.parse(e)}catch{return t}}var Ge=new Map;function q(e,t){let n=Ge.get(e);if(n!==void 0)return n;try{let r=w(oo(e,"utf8"),t);return Ge.set(e,r),r}catch{return Ge.set(e,t),t}}function z(e){return typeof e=="string"?e:""}function J(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function f(e,t){let n=J(e,t);return typeof n=="string"?n:""}var M=500;function oe(e,t=2){if(!je(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=ro(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=qt(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:ao(e,l),size:Zt(l).size})}catch{continue}if(n.length>=M){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function se(e){return je(e)?{present:!0,size:Zt(e).size}:{present:!1,size:0}}function ie(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var fo=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function po(e){return fo.some(t=>!!I(t,e))}function mo(e){if(I("KUBERNETES_SERVICE_HOST",e)||ie(I("REMOTE_CONTAINERS",e))||ie(I("DEVCONTAINER",e)))return!0;try{if(co("/.dockerenv")||lo("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function tn(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!I(t,e))}function go(e,t=process.platform){return tn(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!I(n,e)):!1}function _o(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function ho(e){return e==="linux"}function I(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return y(e)}function Eo(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!So(I("CURSOR_VERSION",n))}function So(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Ye(e){if(_o(e.sessionId))return!0;let t=e.hostname??en(),n=e.osUser??nn(e.env);return Eo(t,n,e.env)}function Io(e){return ie(I("CURSOR_AGENT",e.env))?!0:Ye(e)}function Ro(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(I("TERM",e)??I("TERM_PROGRAM",e))||(I("SSH_TTY",e)??I("SSH_CONNECTION",e))||(I("__CFBundleIdentifier",e)??I("XPC_SERVICE_NAME",e))||tn(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!I(t,e))||I("SESSIONNAME",e))}function ae(e={}){let t=e.env;if(I("GITHUB_ACTIONS",t))return"github_actions";if(ie(I("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!go(t,n)&&Io(e)&&(ie(I("CURSOR_AGENT",t))||ho(n)))return"cursor_cloud";if(I("CODESPACES",t)||I("CODESPACE_NAME",t))return"codespaces";if(I("GITLAB_CI",t))return"gitlab_ci";if(po(t))return"managed";let r=I("CI",t);return r&&r!=="false"&&r!=="0"?"managed":mo(t)?"container":Ro(t)?"interactive":"unknown"}async function Xe(){return await C("systemd-detect-virt",[],1e3)}function nn(e=process.env,t=uo){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function Ze(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await C("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),i=s("/etc/os-release","utf8"),a=i.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=i.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=a??c??""}catch{t=await C("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await C("uname",["-r"],1e3))}else t=await C("ver",[],1e3);let n=nn(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await C("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function ce(){return en()}var Ao="installation.json",To="cloud-bootstrap.lock",Oo=6e4;function pn(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function le(e=Qe()){return et(e,".ev-ai","agent-hook")}function ko(e=Qe()){return et(le(e),Ao)}function mn(e){return et(Ce(e),To)}function gn(){return yo(8).toString("hex")}function Q(e){return cn("sha256").update(e).digest("hex").slice(0,16)}function E(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function _n(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function xo(e=process.env){let t=E(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!_n(t)){g(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function hn(e,t){return e&&_n(e)?e:(e&&g(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),xo(t))}function No(e){return/^[0-9a-f]{16}$/.test(e)}function wo(e=process.env){if(E(e.GITHUB_ACTIONS)){let t=E(e.GITHUB_REPOSITORY_ID)??E(e.GITHUB_REPOSITORY),n=E(e.GITHUB_ACTOR)??E(e.GITHUB_TRIGGERING_ACTOR)??E(e.GITHUB_USER);if(t&&n)return Q(`github_actions|${t}|${n}`)}if(E(e.CODESPACES)||E(e.CODESPACE_NAME)){let t=E(e.CODESPACE_NAME);if(t)return Q(`codespaces|${t}`);let n=E(e.GITHUB_REPOSITORY_ID)??E(e.GITHUB_REPOSITORY),r=E(e.GITHUB_USER)??E(e.GITHUB_ACTOR);if(n&&r)return Q(`codespaces|${n}|${r}`)}if(E(e.GITLAB_CI)){let t=E(e.CI_PROJECT_ID)??E(e.CI_PROJECT_PATH),n=E(e.GITLAB_USER_LOGIN)??E(e.GITLAB_USER_EMAIL)??E(e.GITLAB_USER_NAME);if(t&&n)return Q(`gitlab|${t}|${n}`)}return null}var bo="cursoragent@cursor.com";function Uo(e){let t=E(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===bo?null:t}function vo(e,t){return E(e.CURSOR_PROJECT_DIR)??E(e.CLAUDE_PROJECT_DIR)??t}function Po(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Lo(e){let t=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Po(t):e}async function Mo(e){let t=E(await C("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!V(null,t))return t;let n=E(await C("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!V(null,n)?n:null}function Do(e,t){let n=vo(e,t);return n?Q(`cursor_cloud|${n}|${Uo(e)??""}`):null}async function Ho(e,t){let n=E(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Lo(n),o=await Mo(n);return Q(`claude_remote|${r}|${o??""}`)}function rn(e,t){let n=hn(e,t);if(n)return n;let r=wo(t);return r||gn()}async function Fo(e){let n=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Co(e);return cn("sha256").update(n).digest("hex").slice(0,16)}function Bo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&r.length>0&&(t[n]=r);return Object.keys(t).length>0?t:void 0}function $o(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Bo(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function W(e){if(ln(e))try{return $o(un(e,"utf8"))}catch{}}function tt(e){return W(e)}function En(e,t,n){let r=W(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{K(e,`${JSON.stringify(o,null,2)}
|
|
6
|
+
`)}catch(s){let i=s instanceof Error?s.message:String(s);g(`WARN: operator identity cache write failed open: ${i}`)}}function Sn(e,t=Date.now()){if(!e)return!0;if(W(e)?.operator_identity_hash)return!1;let n=mn(e);try{if(ln(n)){let r=Number.NaN;try{r=Number(un(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Oo)return!1;try{dn(n)}catch{}}}catch{}try{return qe(Ce(n),{recursive:!0}),fn(n,`${t}
|
|
7
|
+
`,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(Cn(r))return!1;let o=r instanceof Error?r.message:String(r);return g(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function In(e){if(e)try{dn(mn(e))}catch{}}function Rn(e,t){let r=W(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function yn(e,t,n){if(!n)return;let r=W(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{K(e,`${JSON.stringify(o,null,2)}
|
|
8
|
+
`)}catch(s){let i=s instanceof Error?s.message:String(s);g(`WARN: platform_agent_id cache write failed open: ${i}`)}}function Cn(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Ko(e,t){qe(Ce(e),{recursive:!0}),fn(e,`${JSON.stringify(t,null,2)}
|
|
9
|
+
`,{encoding:"utf8",flag:"wx"})}function on(e,t){try{return Ko(e,t),t}catch(n){if(!Cn(n))throw n;return W(e)}}function sn(e,t){qe(Ce(e),{recursive:!0}),K(e,`${JSON.stringify(t,null,2)}
|
|
10
|
+
`)}function an(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function An(e,t={}){let n=t.home??Qe(),r=t.env??process.env,o=await Fo(e),s=ko(n),i={sessionId:t.sessionId,hostname:E(r.HOSTNAME)??void 0,osUser:E(r.USER)??E(r.LOGNAME)??E(r.USERNAME)??void 0,env:r},a=ae(i),c=hn(t.overrideId,r),l=a==="cursor_cloud"&&Ye(i)?Do(r,e):a==="claude_remote"?await Ho(r,e):null,u=W(s);if(u){let S=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(S={...u,pinned:!0},sn(s,S)),!!l&&l!==S.installation_id&&!c&&S.pinned!==!0&&No(S.installation_id)&&l){let T={installation_id:l,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return sn(s,T),{installationId:l,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let d=c??l??rn(void 0,r),m=on(s,an(d,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let p=c??l??rn(void 0,r),_=on(s,an(p===d?gn():p,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}var Go=new Set(["localhost","127.0.0.1","[::1]","::1"]),Tn=/^[A-Za-z0-9._~-]+$/;function On(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 Ae(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Go.has(t.hostname):!1}catch{return!1}}function kn(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Ae(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=jo(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Tn.test(n))return`org token must match ${Tn.source} (got: ${n})`;if(On(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(On(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function xn(e){return new URL(e).toString()}function jo(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 nt(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 Nn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?Ie(t):""}var wn=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,bn=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Vo=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,zo=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"]),Jo=new Set(["read","read_file","view"]),Wo=new Set(["bash","shell","zsh"]);function Yo(e){let t=e.replace(/\\/g,"/");return wn.exec(t)?.[1]??null}function Xo(e){let t=e.replace(/\\/g,"/"),r=bn.exec(t)?.[1];return r?r.toLowerCase():null}function rt(e){return Yo(e)??Xo(e)}function Zo(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 Te(e){if(typeof e=="string")try{let t=JSON.parse(e);return Te(t)}catch{return null}return!e||typeof e!="object"?null:Zo(e)}function qo(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Qo(e){let t=e.replace(/\\/g,"/"),n=wn.exec(t);if(n?.[1])return n[1];let o=bn.exec(t)?.[1];return o?o.toLowerCase():null}function es(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Un(e){let t=es(e).toLowerCase();if(Jo.has(t)){let n=Te(e.tool_input)??z(e.file_path),r=n?rt(n):null;if(r)return r}if(Wo.has(t)){let n=qo(e.tool_input)??z(e.command);return n?Qo(n):null}return null}function ts(e){let t=new Set,n=[];for(let r of e.matchAll(Vo)){let o=r[1]?.toLowerCase();!o||t.has(o)||zo.has(o)||(t.add(o),n.push(o))}return n}function ns(e){return z(e.prompt)}function vn(e){let t=f(e,"command_name");if(t){let r=f(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=ns(e);return n?ts(n):[]}function ot(e){return e!==void 0&&Jt.includes(e)}function Oe(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function ke(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=Oe(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=Oe(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=Oe(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=Oe(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:ot(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function st(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Ie(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=kn(n);if(r){g(`WARN: ignoring --url/--token collector override: ${r}`);return}return xn(n)}function Pn(e,t){if(f(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function rs(){return!!(y("CURSOR_VERSION")??y("CURSOR_PROJECT_DIR"))}function it(e,t,n){return e!=="claude"&&e!=="codex"?!1:Pn(t,n)?!0:rs()}function ue(e,t,n,r){if(Pn(e,t))return"cursor";if(ot(r))return r;let o=f(e,"conversation_id"),s=f(e,"turn_id"),i=f(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),ot(n)&&(c=n),c}function xe(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function os(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 Ln(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Mn(e,t,n){let r=f(e,"session_id")||f(e,"conversation_id"),o=f(e,"prompt.id")||f(e,"prompt_id")||f(e,"generation_id")||f(e,"turn_id"),s=f(e,"hook_event_name")||f(e,"event"),i=f(e,"source"),a=ue(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var ss=["session_start","session_end","tool_invoked","skill_invoked"];function is(e){return ss.includes(e)}function Dn(e,t){return e&&is(e)?e:os(t.toLowerCase())}var as={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function cs(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Hn(e,t=""){let n=f(e,"tool_name")||f(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!cs(n)&&(n=`MCP:${n}`):n=as[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?z(o.skill)||z(o.skill_name):"")||f(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;return i??=Un(a),{toolName:n,skillName:i}}var ls=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Fn(e){for(let t of["subagent_type","agent_type"]){let n=f(e,t);if(n&&ls.test(n))return n}return null}function Bn(e){let t=J(e,"duration_ms");if(typeof t=="number")return t;let n=J(e,"duration");return typeof n=="number"?n:null}var us="error",ds="interrupted",fs="permission_denied",ps=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function at(e){return ps.test(e)?e:null}function ms(e){for(let t of["failure_type","error_type"]){let n=at(f(e,t));if(n)return n}return null}function $n(e,t){return J(e,"is_interrupt")===!0?ds:t.toLowerCase()==="permissiondenied"?fs:ms(e)??us}function gs(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 Kn(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:gs(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var zn=3e4,Rs="claims",ys=!0,Cs=100,As=new Set(["sessionstart","sessionend","stopfailure"]),Ts=["tool_name","tool","command","file_path","url"];function Os(e=Vn()){return ct(le(e),Rs)}function Jn(e){let t=e.split(`
|
|
11
|
+
`,1)[0]??"";return Number(t.trim())}function Wn(e){return _s("sha256").update(e).digest("hex").slice(0,32)}function ks(e){let t=[];for(let n of Ts){let r=f(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":Wn(t.join("\0"))}function xs(e){let t=e.sessionId.trim();if(!t)return;let n=e.runnerEvent.trim().toLowerCase(),r=e.turnId.trim(),o=e.toolUseId.trim(),s=e.subagentId?.trim()??"",i=e.callFingerprint?.trim()??"",a=!!(o||r||s),c=As.has(n);if(!a&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return Wn(`${l}|${t}|${n}|${r}|${o}|${i}|${s}`)}function Ns(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function ws(e,t){return ct(e,t)}function bs(e,t=Date.now()){let n;try{n=Ss(e)}catch{return}let r=0;for(let o of n){if(r>=Cs)break;r+=1;let s=ct(e,o),i=Number.NaN;try{i=Jn(Gn(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<zn))try{jn(s)}catch{}}}function Us(e,t,n=Date.now()){let r=ws(t,e);try{if(hs(r)){let o=Number.NaN;try{o=Jn(Gn(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<zn)return!1;try{jn(r)}catch{}}}catch{}try{Es(t,{recursive:!0}),Is(r,`${n}
|
|
12
|
+
`,{encoding:"utf8",flag:"wx"})}catch(o){if(Ns(o))return!1;let s=o instanceof Error?o.message:String(o);return g(`WARN: event claim failed open: ${s}`),!0}return bs(t,n),!0}function vs(e,t,n){let r=f(e,"session_id")||f(e,"conversation_id"),o=f(e,"prompt.id")||f(e,"prompt_id")||f(e,"generation_id")||f(e,"turn_id"),s=f(e,"tool_use_id"),i=f(e,"subagent_id")||f(e,"agent_id"),a=ue(e,t,void 0,n),c=ks(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function Yn(e,t,n,r=Vn(),o=Date.now()){if(!ys)return!0;let s=xs(vs(e,t,n));if(!s)return!0;let i=Us(s,Os(r),o);return!i&&y("EV_AI_HOOK_DEBUG")&&g(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}var lt={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function de(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Ps(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 de(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return de(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?de(o[1]):de(t)}async function fe(e=process.cwd()){let t=await v("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([v("git",["remote","get-url","origin"],2e3,{cwd:e}),v("git",["branch","--show-current"],2e3,{cwd:e}),v("git",["rev-parse","HEAD"],2e3,{cwd:e}),v("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function Xn(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=lt[n];if(!a)return"";let c=pn(n,e.scope_path,i);if(s){let _=Rn(s,c);if(_)return _}let l=o??await fe(r),u=l?.remote?Ps(l.remote):"";if(u||(u=de(process.env.GITHUB_REPOSITORY??"")),!u)return"";let d=e.scope_path??"",m=d?`${d}/`:"",p=`${u}:${m}${a}`;return s&&yn(s,c,p),p}var G=Xr(Qn(),1);import{existsSync as js,readFileSync as Vs}from"node:fs";import{homedir as er}from"node:os";import{join as zs}from"node:path";var Js="cloud-cache.json",Ws=1440*60*1e3,Ys=900*1e3;function Xs(e=er()){return zs(le(e),Js)}function Zs(e){if(!js(e))return;let t=w(Vs(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 qs(e,t){try{K(e,`${JSON.stringify(t)}
|
|
13
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);g(`WARN: cloud cache write failed open: ${r}`)}}function Qs(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Ys:Ws;return n-e.probed_at<r}async function ei(e){let t=await fetch("http://169.254.169.254/latest/api/token",{method:"PUT",headers:{"X-aws-ec2-metadata-token-ttl-seconds":"60"},signal:AbortSignal.timeout(e)}).catch(()=>{});if(!t?.ok)return;let n=(await t.text()).trim();if(!n)return;let r={"X-aws-ec2-metadata-token":n},[o,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:r,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!o?.ok&&!s?.ok)return;let i=o?.ok?(await o.text()).trim():"",a=s?.ok?(await s.text()).trim():"";if(!(!i&&!a))return{provider:"aws",region:i,instance_id:a}}async function ti(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 ni(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 ri(e){let t=await Promise.allSettled([ei(e),ti(e),ni(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function ut(e,t){if(e==="interactive")return null;let n=t?.home??er(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Xs(n),i=Zs(s);if(Qs(i,e,o))return i.result;let a=await ri(r);return qs(s,{context:e,probed_at:o,result:a}),a}import{existsSync as oi}from"node:fs";import{homedir as si}from"node:os";import{join as dt}from"node:path";function ft(e,t,n){if(!oi(e))return;let r=q(e,{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,source:t})}async function pt(e,t=process.cwd(),n="claude",r=si()){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"&&ft(dt(r,".claude.json"),"claude_json_user",o),ft(dt(t,".mcp.json"),"mcp_json",o),ft(dt(t,".cursor/mcp.json"),"cursor_mcp",o),[...o.values()]}var ii=["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"],ai=["CURSOR_PROJECT_DIR"],ci=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function li(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)ci.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function mt(e=process.env){let t=ii.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:li(e[r]??"")}:{name:r,present:!1}),n=ai.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{createHash as ui}from"node:crypto";function A(e){return ui("sha256").update(e).digest("hex").slice(0,16)}function F(e,t){return`${e}\0${t}`}function tr(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function gt(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
|
|
14
|
+
`);return A(n)}function di(e,t,n="git_config",r=null){return A(`${e??""}|${t??""}|${r??""}|${n}`)}function fi(e){let t=null,n=null;for(let r of e.split(`
|
|
15
|
+
`)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function pi(e,t=C){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return fi(n)}function mi(e=process.env){let t=h(e.GIT_AUTHOR_NAME),n=h(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=h(e.GIT_COMMITTER_NAME),o=h(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=h(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}async function gi(e,t=C){let n=await t("git",["log","-1","--format=%an%x00%ae"],2e3,{cwd:e});if(!n)return null;let r=n.indexOf("\0"),o=(r>=0?n.slice(0,r):n).trim(),s=(r>=0?n.slice(r+1):"").trim();return!o&&!s?null:{git_user_name:o||null,git_user_email:s||null,platform_login:null,identity_source:"git_log"}}function B(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function _i(e=process.env){let t=B(h(e.EV_AI_HOOK_OPERATOR_NAME),h(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured",h(e.EV_AI_HOOK_OPERATOR_LOGIN));if(t)return t;let n=h(e.GITHUB_ACTOR)??h(e.GITHUB_TRIGGERING_ACTOR)??h(e.GITHUB_USER),r=B(n,null,"github",n);if(r)return r;let o=h(e.GITLAB_USER_LOGIN),s=B(h(e.GITLAB_USER_NAME)??o,h(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let i=B(h(e.BUILD_REQUESTEDFOR),h(e.BUILD_REQUESTEDFOREMAIL),"azure_devops",h(e.BUILD_REQUESTEDFORID));if(i)return i;let a=h(e.BUILDKITE_BUILD_CREATOR_EMAIL),c=B(h(e.BUILDKITE_BUILD_CREATOR),a,"buildkite",a);if(c)return c;let l=B(h(e.BUILD_USER)??h(e.CHANGE_AUTHOR),h(e.BUILD_USER_EMAIL)??h(e.CHANGE_AUTHOR_EMAIL),"jenkins",h(e.BUILD_USER_ID));if(l)return l;let u=h(e.CIRCLE_USERNAME),d=B(u,null,"circleci",u);if(d)return d;let m=h(e.CODEBUILD_INITIATOR),p=B(m,null,"codebuild",m);if(p)return p;let _=B(h(e.DRONE_COMMIT_AUTHOR)??h(e.DRONE_COMMIT_AUTHOR_NAME),h(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",h(e.DRONE_COMMIT_AUTHOR));if(_)return _;if(nr(e.CLAUDE_CODE_REMOTE)||nr(e.CURSOR_AGENT)){let S=h(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:S&&!V(null,S)?S:null,platform_login:null,identity_source:"cloud"}}return null}function _t(e){return!!((e.git_user_name??e.git_user_email)&&!V(e.git_user_name,e.git_user_email))}function h(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function nr(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function hi(e,t=C,n=process.env){let r=await pi(e,t);if(_t(r))return{...r,identity_source:"git_config"};let o=mi(n);if(o&&_t(o))return o;let s=_i(n);if(s&&(s.git_user_name||s.git_user_email||s.platform_login))return s;let i=await gi(e,t);return i&&_t(i)?i:s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||i||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function we(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??C,s=e.env??process.env,i=await hi(t,o,s),a=di(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?tt(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let p=n;return{operator:i,commit:()=>{p&&En(p,a,ye())}}}function ht(e){return e?!tt(e)?.operator_identity_hash:!0}function rr(e){return!0}import{existsSync as Bi,readFileSync as $i}from"node:fs";import{homedir as yr}from"node:os";import{join as P}from"node:path";import{basename as Hi,join as ee,resolve as gr}from"node:path";import{existsSync as or,readdirSync as Ei}from"node:fs";import{basename as Si,dirname as Ii,relative as Ri}from"node:path";var pe=class{constructor(t,n=""){this.home=t;this.pathPrefix=n}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=Ri(this.home,t).replace(/\\/g,"/"),r=!n||n.startsWith("..")?`external/${A(Ii(t))}/${Si(t)}`:n;return this.pathPrefix?`${this.pathPrefix}${r}`:r}get atGlobalCap(){return this.truncated||this.components.length>=M}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!or(t))return[];try{return Ei(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(or(t))return q(t,n)}push(t){return this.components.length>=M?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Et,readFileSync as yi,statSync as Ci}from"node:fs";import{basename as ir,join as me,relative as ar}from"node:path";var St=2e4,Ai=4;function Ti(e){return e.length<=St?e:`${e.slice(0,St-1)}\u2026`}function Oi(e){try{let t=yi(e),n=t.toString("utf8");return{hash:A(t),length:t.length,text:Ti(n)}}catch{return null}}var sr={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function ki(e){return e in sr?sr[e]:"UNSPECIFIED"}function be(e,t){let n=Oi(t.absolutePath);if(!n)return!1;let r=t.name??ir(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.homeRel(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=ki(t.kind);return s&&(o.trigger=s),e.push(o)}function xi(e,t,n){let r=ar(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?ir(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Y(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;It(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function It(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Ai))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let p=me(r,u.name,c);if(Et(p)){let _=ar(n,me(r,u.name)).replace(/\\/g,"/");be(e,{absolutePath:p,kind:s,origin:i,enabled:a,name:_||u.name});continue}It(e,{walkRoot:n,currentDir:me(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){It(e,{walkRoot:n,currentDir:me(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let d=u.name.toLowerCase();if(!l.some(p=>d.endsWith(p)))continue;let m=me(r,u.name);be(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:xi(n,m,!0)})}}function cr(e){for(let t of e)if(Et(t))try{if(Ci(t).size>0)return t}catch{continue}return e.find(t=>Et(t))}function Ni(e){if(e.prompt||e.type==="prompt")return"prompt";let t=e.command??e.bash??e.powershell??"";return/\bnpx\b/i.test(t)?"npx":/\.(sh|bash|zsh|js|mjs|cjs|ts|py)(\s|$|"|')/i.test(t)||/^(\.\/|~\/|\/|[A-Za-z]:[\\/])/.test(t.trim())?"script":"inline"}function wi(e){return Array.isArray(e.hooks)&&e.hooks.length>0?e.hooks:[{type:e.type,command:e.command,bash:e.bash,powershell:e.powershell,prompt:e.prompt}]}function bi(e,t,n,r){let o=e.homeRel(t);for(let[s,i]of Object.entries(n))if(!(!Array.isArray(i)||e.truncated))for(let a of i){if(!a||typeof a!="object"||e.truncated)continue;let c=a;for(let l of wi(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",d=Ni({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",p=A(u),_=m?`${s}:${m}:${d}:${p}`:`${s}:${d}:${p}`,S=`${s}|${m}|${d}|${u}`;e.push({kind:"HOOK",name:_,path:o,content_hash:A(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:d,action_hash:p}})}}}function ge(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||bi(e,t,r.hooks,n)}var lr={claude:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]}],memory:[".claude/CLAUDE.md"],hooks:[".claude/settings.json"],mcpJson:[".claude.json"],plugins:"claude"},cursor:{skillRoots:[".cursor/skills",".cursor/skills-cursor"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[".cursor/AGENTS.md"],hooks:[".cursor/hooks.json"],mcpJson:[".cursor/mcp.json"],plugins:"cursor"},codex:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]}],memory:[".codex/AGENTS.override.md",".codex/AGENTS.md"],hooks:[".codex/hooks.json"],mcpToml:[".codex/config.toml"]}};import{existsSync as Ui,readFileSync as vi}from"node:fs";function Pi(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function ur(e,t,n){let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.homeRel(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=Pi(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:A(`${i}|${c}`),origin:n,enabled:!0,attributes:{transport:c}})}}function dr(e,t,n){if(!Ui(t))return;let r;try{r=vi(t,"utf8")}catch{return}let o=e.homeRel(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),l=c.search(/^\[/m),u=l===-1?c:c.slice(0,l),d="unknown";/^\s*url\s*=/m.test(u)?d="http":/^\s*command\s*=/m.test(u)&&(d="stdio"),e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:A(`${a}|${d}`),origin:n,enabled:!0,attributes:{transport:d}})}}import{existsSync as Li,readdirSync as Mi}from"node:fs";import{join as O}from"node:path";var fr=50;function Rt(e,t,n,r){if(!Li(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(fr,()=>{Y(e,{dir:O(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Y(e,{dir:O(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Y(e,{dir:O(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});ge(e,O(t,"hooks","hooks.json"),n),ge(e,O(t,"hooks.json"),n);let i=e.components.length-o,a=s>=fr;return{componentCount:i,expandTruncated:a}}function yt(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function pr(e){let t=O(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(O(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.homeRel(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},d=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",p=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,k=0,T=!1;for(let b of l)if(typeof b.installPath=="string"&&b.installPath.length>0){let j=Rt(e,b.installPath,S,d);k+=j.componentCount,T=T||j.expandTruncated}yt(e,{pluginKey:a,rowPath:i,enabled:d,scope:_,version:p||void 0,marketplace:m||void 0,componentCount:k,expandTruncated:T,contentHash:A(`${a}|${p}|${_}|${d}|${k}`)})}}function Di(e){let t=e,n="";try{let r=Mi(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=O(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=O(e,s),n=s)}}catch{}return{installPath:t,version:n}}function mr(e){let t=[{base:O(e.home,".cursor/plugins/local"),scope:"local"},{base:O(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let i=o.name,a=O(n,o.name),c=`plugin:${i}`,{componentCount:l,expandTruncated:u}=Rt(e,a,c,!0);yt(e,{pluginKey:i,rowPath:e.homeRel(a),enabled:!0,scope:"local",componentCount:l,expandTruncated:u,contentHash:A(`${i}|local|${l}`)});continue}let s=o.name;for(let i of e.readEntries(O(n,s))){if(!i.isDirectory()||e.truncated)continue;let a=O(n,s,i.name),{installPath:c,version:l}=Di(a),u=`${i.name}@${s}`,d=`plugin:${u}`,{componentCount:m,expandTruncated:p}=Rt(e,c,d,!0);yt(e,{pluginKey:u,rowPath:e.homeRel(c),enabled:!0,scope:"cache",version:l||void 0,marketplace:s,componentCount:m,expandTruncated:p,contentHash:A(`${u}|${l}|${m}`)})}}}function _r(e,t,n,r){let o=lr[t];if(!o)return;let s=e.home;for(let a of o.skillRoots)Y(e,{dir:ee(s,a),kind:"SKILL",origin:n,enabled:!0,nested:"SKILL.md"});for(let a of o.dirs)Y(e,{dir:ee(s,a.dir),kind:a.kind,origin:n,enabled:!0,extensions:a.extensions});let i=cr(o.memory.map(a=>ee(s,a)));i&&be(e,{absolutePath:i,kind:"MEMORY",origin:n,enabled:!0,name:Hi(i)});for(let a of o.hooks)ge(e,ee(s,a),n);for(let a of o.mcpJson??[])ur(e,ee(s,a),n);for(let a of o.mcpToml??[])dr(e,ee(s,a),n);r&&(o.plugins==="claude"?pr(e):o.plugins==="cursor"&&mr(e))}function Ct(e,t,n){let r=new pe(t);if(_r(r,e,"user",!0),n===void 0||gr(n)===gr(t))return{components:r.components,truncated:r.truncated};let s=new pe(n,"cwd/");_r(s,e,"cwd",!1);let i=[...r.components,...s.components],a=r.truncated||s.truncated||i.length>M;return{components:i.slice(0,M),truncated:a}}function At(e,t,n={}){let r=n.truncated===!0,o=gt(e),s=new Set(e.map(u=>F(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let u of e){let d=F(u.path,u.name);c[d]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let d=tr(u);d&&l.push(d)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:l,unchanged:a.length===0&&l.length===0}}var Er=3e5,Fi=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Tt(e,t,n){let r=new Set(t.map(s=>F(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(F(s.path,s.name))||o.push(s));return o}function Ot(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function hr(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Sr(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function kt(e,t=Er){let n=[],r=[];for(let u of e)Fi.has(u.kind)?n.push(u):r.push(u);r.sort((u,d)=>(u.text?.length??0)-(d.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let d=s.length>0?1:0,m=hr(u)+d;if(i+m<=t){s.push(u),i+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let p=Sr(u),_=hr(p)+d;if(i+_<=t){s.push(p),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function xt(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Sr(n))}var Ki={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],subagents:".cursor/agents",commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:[".agents/skills",".codex/skills"],subagents:".codex/agents",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},Gi=200,Ir=200,ji=["allow","deny","ask"],Vi=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Nt="<path>",zi=new RegExp(`${Nt}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Ji(e){let t=e.replace(Vi,Nt).replace(zi,Nt);return t.length>Ir?`${t.slice(0,Ir)}...`:t}function Rr(e){let t=q(e,{}),n=[];for(let r of ji)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Ji(o),mode:r});return{model:t.model??"",permissionKeys:n}}var Wi=10,Yi=840*60*1e3,Xi="self-config-cache.json";function wt(){return y("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Zi(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Yi}var qi={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Qi(e,t=C){let n=qi[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
|
|
16
|
+
`)[0]??"").trim();return a||r(o+1)};return r(0)}function ea(e=yr()){return P(e,".ev-ai","agent-hook",Xi)}function ta(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
|
|
17
|
+
`);return A(n)}function Ue(e,t,n=!1){let r=ta(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 na(e){return Bi(e)?w($i(e,"utf8"),{}):{}}function ra(e,t){try{K(e,`${JSON.stringify(t)}
|
|
18
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);g(`WARN: self-config cache write failed open: ${r}`)}}function oa(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}return r&&(o.user_spec_collected_at_ms=r.collectedAtMs,r.included&&(o.user_spec=r.hash,o.user_spec_components=r.componentHashes),o.user_spec_text_hashes=r.textHashes),o}async function Cr(e,t=process.cwd(),n=yr(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await Qi(e),a="",c=[];if(o){let U=Rr(P(n,".claude/settings.json")),D=Rr(P(t,".claude/settings.local.json"));a=D.model||U.model,c=[...U.permissionKeys,...D.permissionKeys].slice(0,Gi)}let l=Ki[e]??{},u={present:!1,size:0},d=U=>{let D=Array.isArray(U)?U:U?[U]:[],R=[],$=!1;for(let De of D){let N=oe(P(n,De));if(R=R.concat(N.entries),$=$||N.truncated,R.length>=M){R=R.slice(0,M),$=!0;break}}return{entries:R,truncated:$}},m=ea(n),p=na(m),_=p[e]??{},S=(_.send_count??0)+1,k=S>0&&S%Wi===0,T=U=>k?void 0:_[U],b=d(l.skills),j=l.subagents?oe(P(n,l.subagents)):{entries:[],truncated:!1},Me=l.commands?oe(P(n,l.commands)):{entries:[],truncated:!1},Lt=l.rules?oe(P(n,l.rules)):{entries:[],truncated:!1},re={skills:Ue(b.entries,T("skills"),b.truncated),subagents:Ue(j.entries,T("subagents"),j.truncated),commands:Ue(Me.entries,T("commands"),Me.truncated),rules:Ue(Lt.entries,T("rules"),Lt.truncated)},x={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:re.skills,subagents:re.subagents,commands:re.commands,rules:re.rules,memory:l.memory?se(P(n,l.memory)):u,settings:l.settings?se(P(n,l.settings)):u,mcp:l.mcp?se(P(n,l.mcp)):u},local_settings:o?se(P(t,".claude/settings.local.json")):u},Mt=null,Dt=()=>{},Ht=r.nowMs??Date.now();if(!wt()&&Zi(_.user_spec_collected_at_ms,Ht)){let U=_.user_spec_collected_at_ms!==void 0,D=Ct(e,n),R=At(D.components,_.user_spec_components,{forceFull:!_.user_spec_components,truncated:D.truncated}),$=new Set(_.user_spec_text_hashes??[]),De=Tt(D.components,R.upserts,$),N=kt(xt([...R.upserts,...De],$));x.user_spec_hash=R.hash,x.user_spec_count=R.count,x.user_spec_truncated=R.truncated||N.droppedCount>0,(N.components.length>0||R.removed.length>0||R.full)&&(R.full&&(x.user_spec_full=!0),N.components.length>0&&(x.user_spec=N.components),R.removed.length>0&&!x.user_spec_truncated&&(x.user_spec_removed=R.removed),N.textDeferredCount>0&&(x.user_spec_text_deferred=N.textDeferredCount));let He=R.full?{}:{..._.user_spec_components??{}};if(!x.user_spec_truncated)for(let Z of R.removed)delete He[F(Z.path,Z.name)];for(let Z of N.components)He[F(Z.path,Z.name)]=Z.content_hash;Mt={hash:R.hash,componentHashes:He,textHashes:Ot($,N.textHashesSent,D.components),included:N.components.length>0||R.removed.length>0&&!x.user_spec_truncated||R.full,collectedAtMs:Ht};let Fe=await we({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:U});Fe.operator&&(x.operator=Fe.operator),Dt=Fe.commit}let Kr=oa(_,re,S,Mt);return{config:x,commit:()=>{p[e]=Kr,ra(m,p),Dt()}}}function te(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp: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:Ke,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as Ar}from"node:fs";import{spawn as Tr}from"node:child_process";import{basename as sa}from"node:path";import{fileURLToPath as ia}from"node:url";var Ut="__post",ve="__work";function aa(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 Or(e){switch(e){case"session_start":return Kt;case"session_end":return Gt;case"tool_invoked":case"skill_invoked":return Be;default:return Be}}function ca(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
|
|
19
|
+
${n}`}function kr(e,t=[],n=process.execPath,r=import.meta.url,o=Ar){if(sa(n)===Re)return{command:n,args:[e,...t]};let s=ia(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function la(e=process.execPath,t=import.meta.url,n=Ar){return kr(Ut,[],e,t,n)}function ua(e){let t=e.indexOf(`
|
|
20
|
+
`);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function xr(e,t=fetch){let n=await e(),r=ua(n);if(!r)return;let{meta:o,body:s}=r,i={"Content-Type":"application/json"};try{await t(o.url,{method:"POST",headers:i,body:s,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function da(e,t,n){let r=Or(e);g(`POST event=${e} url=${nt(n)} size=${t.length} platform=${process.platform}`);let o={"Content-Type":"application/json"},s=Date.now();try{let i=await fetch(n,{method:"POST",headers:o,body:t,signal:AbortSignal.timeout(r)}),a=Date.now()-s;if(i.ok)return g(`POST outcome=ok elapsed_ms=${a} http=${i.status}`),!0;let c=(await i.text()).slice(0,200).replace(/[\n\r]/g,"");return g(`POST outcome=fail elapsed_ms=${a} http=${i.status} body=${c}`),!1}catch(i){let a=Date.now()-s,c=i instanceof Error?i.message:String(i);return g(`POST outcome=fail elapsed_ms=${a} http=000 body=${c}`),!1}}async function Nr(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){g(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},jt),l=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return g(`WARN: ${o} spawn failed open: ${i}`),null}}async function fa(e,t,n,r=Tr,o=la){let s=Or(e),i=ca(n,s,t),{command:a,args:c}=o();return Nr(a,c,i,r,"detached post")}async function wr(e,t,n=Tr,r=kr){let{command:o,args:s}=r(ve,t);return Nr(o,s,e,n,"detached work")}async function ne(e,t,n,r,o,s){if(!o)return g("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Ae(o))return g(`WARN: collector URL blocked (https required): ${nt(o)}`),!1;let i=r(e,t,n);s!==void 0&&(i.build_ms=Math.max(0,Date.now()-s));let a=`${JSON.stringify(i)}
|
|
21
|
+
`,c=y("EV_AI_HOOK_DEBUG");c==="full"?g(`DEBUG envelope=${JSON.stringify(i)}`):c==="1"&&g(`DEBUG summary=${aa(i,Buffer.byteLength(a,"utf8"))}`);let l=process.argv.includes(ve),u=y("EV_AI_HOOK_SYNC")==="1";return xe(n.runnerEvent,n.runnerPlatform)||l||u?da(e,a,o):(await fa(e,a,o),!1)}import{relative as pa,resolve as Pe,sep as vt}from"node:path";var ma=["session_id","conversation_id","turn_id","generation_id","prompt.id","prompt_id","hook_event_name","event","source","status","stop_reason","reason","tool_name","tool","tool_use_id","skill_name","command_name","expansion_type","command_source","permission_mode","model","model_id","agent_id","agent_type","subagent_id","subagent_type","subagent_model","is_parallel_worker","effort","effort.level","duration_ms","duration","sandbox","failure_type","is_interrupt"];function ga(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:y("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function _a(e){let t={};for(let n of ma){let r=J(e,n);r!==void 0&&(t[n]=r)}return t}function ha(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Pe(e),r=Pe(t),o=pa(r,n);return!o||o==="."?".":o.startsWith(`..${vt}`)||o===".."||Pe(r,o)!==n?null:o.split(vt).join("/")}function Ea(e){return typeof e!="string"||e.length===0?null:Pe(e).split(vt).join("/")}function br(e,t,n){let r=Ea(t.cwd);r!==null&&(e.cwd=r);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?ha(t.cwd,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function Ur(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([i,a])=>!i.startsWith("_")&&(typeof a=="string"||typeof a=="number"||typeof a=="boolean")).sort((i,a)=>Buffer.byteLength(JSON.stringify(i[1]),"utf8")-Buffer.byteLength(JSON.stringify(a[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[i,a]of o){let c={...s,[i]:a};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[i]=a}return s}function _e(e,t,n={}){if(ga(t)){let o={...e};return delete o.cwd,delete o.transcript_path,br(o,e,n),Ur(o,zt)}let r=_a(e);return br(r,e,n),Ur(r,Vt)}import{createReadStream as Sa}from"node:fs";import{stat as Ia}from"node:fs/promises";import{basename as Ra,resolve as ya}from"node:path";import{createInterface as Ca}from"node:readline";var Aa=1024*1024;function Ta(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Ra(t).endsWith(".jsonl")}async function vr(e){if(!e||!Ta(e))return null;try{let t=ya(e),n=await Ia(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Aa),o=[],s=Ca({input:Sa(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let i of s)i.length!==0&&o.push(i);r>0&&o.length>0&&o.shift();for(let i=o.length-1;i>=0;i--){let a=o[i];if(a)try{let c=JSON.parse(a);if(c.type!=="assistant")continue;let l=c.message;if(!l||typeof l!="object")continue;let u=l.model;if(typeof u=="string"&&u.length>0)return u}catch{continue}}return null}catch{return null}}function Ee(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function Le(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}var Oa=new Set([...Object.values(lt),".github"]);function ka(e,t,n){if(e===null||t===null||n===null||!(/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let o=n.indexOf(":");if(o<=0||o===n.length-1)return;let s=n.slice(o+1),i=s.replaceAll("\\","/").split("/").at(-1);if(!(i===void 0||!Oa.has(i)))try{return(0,G.buildComponentReference)({installationRootExternalKey:n,installableKind:G.ComponentKind.INTERFACE,sourcePath:s,nativeKey:t})}catch{return}}function xa(...e){for(let t of e)if(t)return t;return null}function L(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return g(`WARN: ${n} failed open: ${r}`),t}function Na(e){let t={present:!1,size:0},n={hash:"",count:0};return{config:{runner_platform:e,config_scope:"user",cli_version:null,claude_version:null,model:null,permission_keys:[],user_scope:{skills:n,subagents:n,commands:n,rules:n,memory:t,settings:t,mcp:t},local_settings:t},commit:()=>{}}}function wa(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var X=new Set,he=null;async function Pr(e){if(wt())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(X.has(t))return;if(!ht(n)){X.add(t);return}let r=ae({sessionId:e.sessionId,hostname:ce()});if(rr(r)){if(he){await he;return}he=(async()=>{if(X.has(t)||!ht(n)){X.add(t);return}if(!Sn(n)){X.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,d,m]=await Promise.allSettled([fe(i),Xe(),ut(r),Ze(),we({gitRoot:i,installationStorePath:n,forceResend:!1})]),p=L(c,null,"gitSnapshot"),_=L(l,"","detectVirt"),S=L(u,null,"probeCloud"),k=L(d,{},"hostEnv"),T=L(m,{commit:()=>{}},"resolveOperatorForSend");await Se(e,i,p);let b={identity:{host:ce(),context:r,virt:_||null,cloud:S,git:p},host_env:k,env_vars:mt(),self_config:wa(a,T.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await ne("session_start",b,Ee(e),te,e.manifest.collectorUrl,s),o&&(T.commit(),X.add(t))}finally{In(n)}})().finally(()=>{he=null}),await he}}async function Se(e,t,n){try{let r=n===void 0?await fe(t):n;e.platformAgentId=await Xn(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);g(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function ba(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=ae({sessionId:e.sessionId,hostname:ce()}),o=String(e.runnerPlatform),[s,i,a,c,l,u]=await Promise.allSettled([fe(n),Xe(),ut(r),Ze(),pt(e.manifest.manifest,n,o),Cr(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),d=L(s,null,"gitSnapshot"),m=L(i,"","detectVirt"),p=L(a,null,"probeCloud"),_=L(c,{},"hostEnv"),S=L(l,[],"mcpDeclared"),k=L(u,Na(o),"selfConfig"),T=k.config;await Se(e,n,d);let b=f(e.hookInput,"model");b&&(T.model=b);let j={identity:{host:ce(),context:r,virt:m||null,cloud:p,git:d},host_env:_,env_vars:mt(),mcp:{declared:S},self_config:T,run_meta:{trigger:e.hookSource||"startup"},hook_input:_e(e.hookInput,e.manifest.manifest,Le(e))};await ne("session_start",j,Ee(e),te,e.manifest.collectorUrl,t)&&(k.commit(),X.add(e.manifest.installationId))}async function Ua(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Se(e,n);let r=xa(f(e.hookInput,"status"),f(e.hookInput,"stop_reason"),f(e.hookInput,"reason"),at(f(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await vr(f(e.hookInput,"transcript_path")):null,s=_e(e.hookInput,e.manifest.manifest,Le(e));o&&(s.model=o),await ne("session_end",{status:r,...o?{model:o}:{},hook_input:s},Ee(e),te,e.manifest.collectorUrl,t)}async function va(e){let t=Date.now(),n=vn(e.hookInput);if(n.length===0)return;await Pr(e);let{gitRoot:r}=e.manifest;await Se(e,r);let o=_e(e.hookInput,e.manifest.manifest,Le(e)),s=Ee(e),i=Te(e.hookInput.tool_input),a=r.replaceAll("\\","/").replace(/\/$/,""),c=i?.replaceAll("\\","/"),l=c===void 0?null:c.startsWith(`${a}/`)?c.slice(a.length+1):c.startsWith("/")?null:c;await Promise.all(n.map(u=>{let d;if(l!==null&&rt(l)?.toLowerCase()===u.toLowerCase()&&e.platformAgentId){let m=(0,G.nativeKeyForSkillPath)(l);if(m!==null)try{d=(0,G.buildComponentReference)({installationRootExternalKey:e.platformAgentId,installableKind:G.ComponentKind.SKILL,sourcePath:l,nativeKey:m})}catch{d=void 0}}return ne("tool_invoked",{tool_name:"Skill",skill_name:u,...d===void 0?{}:{component_reference:d},success:null,duration_ms:null,hook_input:o},s,te,e.manifest.collectorUrl,t)}))}async function Pa(e){let t=Date.now();await Pr(e);let{gitRoot:n}=e.manifest;await Se(e,n);let{toolName:r,skillName:o}=Hn(e.hookInput,e.runnerEvent),s=Bn(e.hookInput),i=Ln(e.runnerEvent),a=i===!1?$n(e.hookInput,e.runnerEvent):null,c=await pt(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=Kn(r,c.map(p=>p.name)),d=ka(r,l,e.platformAgentId),m=Fn(e.hookInput);await ne("tool_invoked",{tool_name:r,skill_name:o,success:i,duration_ms:s,...a?{failure_reason:a}:{},...l?{mcp_server:l}:{},...u?{mcp_tool:u}:{},...d?{component_reference:d}:{},...m?{subagent_type:m}:{},hook_input:_e(e.hookInput,e.manifest.manifest,Le(e))},Ee(e),te,e.manifest.collectorUrl,t)}async function Lr(e){switch(e.internalEvent){case"session_start":await ba(e);return;case"session_end":await Ua(e);return;case"skill_invoked":await va(e);return;case"tool_invoked":await Pa(e);return;default:return}}function Mr(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{existsSync as Pt,readFileSync as La}from"node:fs";import{dirname as Ma,join as Dr,relative as Da}from"node:path";var Hr=[$t,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Ha(e=process.cwd(),t){let n=y("EV_AI_HOOK_MANIFEST");if(n&&Pt(n))return n;let r=t??await We(e);for(let o of Hr){let s=Dr(r,o);if(Pt(s))return s}for(let o of Hr){let s=Dr(e,o);if(Pt(s))return s}}async function Fa(e,t){let n=t??await We(Ma(e)),r=Da(n,e),o=await v("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(g(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Ba(e){let t=La(e,"utf8");return w(t,{})}function $a(){return{schema_version:2,mcp_servers:[]}}async function Fr(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Je(e),o=await Ha(e,n),s=o?Ba(o):$a();delete s.installation_id;let i=o?await Fa(o,n):!1;s.capture_hook_input==="full"&&o&&i&&(g(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${o}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete s.capture_hook_input);let{installationId:a,storePath:c,repoKey:l}=await An(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:a,installationStorePath:c,repoKey:l,collectorUrl:Nn(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}async function Br(e,t,n,r){let o=t??await ze($e),s=w(o,{}),i=f(s,"session_id")||f(s,"conversation_id"),a=await Fr(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=Mn(s,a.manifest.platform,n),l=Dn(e,c.runnerEvent);if(!l){g(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:c.turnId,runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:a,platformAgentId:a.platformAgentId};if(Mr(l)){g(`WARN: unsupported internal event '${l}'`);return}await Lr(u)}function Ka(e,t){if(y("EV_AI_HOOK_SYNC")==="1")return!0;let n=ke(e),r=w(t,{}),o=n.event??(f(r,"hook_event_name")||f(r,"event")),s=ue(r,o,void 0,n.runner);return xe(o,s)}async function $r(e=process.argv.slice(2)){if(e[0]===Ut){try{await xr(Ve)}catch{}return 0}if(e[0]===ve){try{let t=ke(e.slice(1)),n=await Ve(),r=w(n,{}),o=t.event??(f(r,"hook_event_name")||f(r,"event"));if(it(t.runner,r,o))return 0;await Br(t.event,n,t.runner,st(t))}catch(t){let n=t instanceof Error?t.message:String(t);g(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await ze($e),n=ke(e),r=st(n),o=w(t,{}),s=n.event??(f(o,"hook_event_name")||f(o,"event"));if(it(n.runner,o,s)||!Yn(o,s,n.runner))return 0;Ka(e,t)?await Br(n.event,t,n.runner,r):await wr(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);g(`WARN: hook failed open: ${n}`)}finally{Qt()}return 0}$r().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
|
|
12
22
|
`),process.exit(1)});
|
package/dist/plugin-hooks.mjs
CHANGED
|
@@ -3,15 +3,15 @@ import { mkdirSync, writeFileSync } from "node:fs";
|
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
4
|
|
|
5
5
|
// src/constants.ts
|
|
6
|
-
var HOOK_BINARY_NAME = "
|
|
6
|
+
var HOOK_BINARY_NAME = "ev-ai-agent-hook";
|
|
7
7
|
var GLOBAL_HOOK_BINARY_RELATIVE = `current/${HOOK_BINARY_NAME}`;
|
|
8
|
-
var PROJECT_HOOK_BINARY_RELATIVE = `.
|
|
8
|
+
var PROJECT_HOOK_BINARY_RELATIVE = `.ev-ai/agent-hook/${HOOK_BINARY_NAME}`;
|
|
9
9
|
var HOOK_INPUT_ALLOWLIST_MAX_BYTES = 4 * 1024;
|
|
10
10
|
var HOOK_INPUT_FULL_MAX_BYTES = 32 * 1024;
|
|
11
11
|
var HOOK_INPUT_MCP_MAX_BYTES = 4 * 1024;
|
|
12
|
-
var PACKAGE_VERSION = "1.0.
|
|
13
|
-
var NPX_PACKAGE_SPEC = `@
|
|
14
|
-
var
|
|
12
|
+
var PACKAGE_VERSION = "1.0.8";
|
|
13
|
+
var NPX_PACKAGE_SPEC = `@ev-ai/agent-hook@${PACKAGE_VERSION}`;
|
|
14
|
+
var HOOK_STATUS_MESSAGE = "ev-ai runtime report";
|
|
15
15
|
|
|
16
16
|
// src/install.ts
|
|
17
17
|
function npxHookCommand(packageSpec = NPX_PACKAGE_SPEC) {
|
|
@@ -47,7 +47,7 @@ function desiredCodexHookGroups(command) {
|
|
|
47
47
|
const entry = {
|
|
48
48
|
type: "command",
|
|
49
49
|
command,
|
|
50
|
-
statusMessage:
|
|
50
|
+
statusMessage: HOOK_STATUS_MESSAGE
|
|
51
51
|
};
|
|
52
52
|
const commandHook = () => ({ hooks: [entry] });
|
|
53
53
|
return {
|
|
@@ -65,6 +65,11 @@ var CURSOR_WIRED_HOOK_EVENTS = [
|
|
|
65
65
|
"preToolUse",
|
|
66
66
|
"postToolUse",
|
|
67
67
|
"postToolUseFailure",
|
|
68
|
+
"beforeShellExecution",
|
|
69
|
+
"afterShellExecution",
|
|
70
|
+
"beforeReadFile",
|
|
71
|
+
"afterFileEdit",
|
|
72
|
+
"beforeMCPExecution",
|
|
68
73
|
"subagentStart",
|
|
69
74
|
"subagentStop",
|
|
70
75
|
"stop"
|
package/package.json
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ev-ai/agent-hook",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.8",
|
|
4
4
|
"description": "Cross-runner runtime telemetry hook for Claude Code, Cursor, and Codex",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
|
-
"
|
|
7
|
+
"ev-ai-agent-hook": "dist/cli.mjs"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"dist",
|
|
@@ -12,32 +12,10 @@
|
|
|
12
12
|
"COLLECTED-DATA.md"
|
|
13
13
|
],
|
|
14
14
|
"publishConfig": {
|
|
15
|
-
"registry": "https://
|
|
16
|
-
|
|
17
|
-
"scripts": {
|
|
18
|
-
"build": "node scripts/build.mjs",
|
|
19
|
-
"build:hook-binary": "node scripts/compile-hook.mjs",
|
|
20
|
-
"build:hook-binary:host": "node scripts/compile-hook.mjs --host",
|
|
21
|
-
"ensure:project-binary": "sh -c 'test -x \"$(git rev-parse --show-toplevel)/.evalon/agent-hook/evalon-agent-hook\" || (yarn build && yarn build:hook-binary:host && node dist/cli.mjs update)'",
|
|
22
|
-
"update:local": "yarn build && yarn build:hook-binary:host && node dist/cli.mjs update",
|
|
23
|
-
"clean": "rm -rf dist compile-out",
|
|
24
|
-
"lint": "eslint src",
|
|
25
|
-
"lint:fix": "eslint --fix src",
|
|
26
|
-
"test": "vitest run --config vitest.config.unit.ts",
|
|
27
|
-
"sync:hooks": "node scripts/sync-hook-events.mjs",
|
|
28
|
-
"pin:hooks": "node scripts/pin-version.mjs",
|
|
29
|
-
"pin:local": "node scripts/pin-version.mjs --local",
|
|
30
|
-
"publish:gh": "node scripts/publish-gh.mjs"
|
|
15
|
+
"registry": "https://registry.npmjs.org",
|
|
16
|
+
"access": "public"
|
|
31
17
|
},
|
|
32
18
|
"engines": {
|
|
33
19
|
"node": ">=18"
|
|
34
|
-
},
|
|
35
|
-
"devDependencies": {
|
|
36
|
-
"@types/node": "~24.10.13",
|
|
37
|
-
"esbuild": "~0.27.3",
|
|
38
|
-
"eslint": "~9.39.1",
|
|
39
|
-
"eslint-config-prettier": "~10.1.0",
|
|
40
|
-
"typescript": "~5.9.3",
|
|
41
|
-
"vitest": "~4.1.0"
|
|
42
20
|
}
|
|
43
21
|
}
|