@ev-ai/agent-hook 1.1.1 → 1.1.2

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