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