@ev-ai/agent-hook 1.2.4 → 1.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -2,50 +2,50 @@
2
2
  import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
 
5
- var pu=Object.create;var Ao=Object.defineProperty;var fu=Object.getOwnPropertyDescriptor;var mu=Object.getOwnPropertyNames;var gu=Object.getPrototypeOf,_u=Object.prototype.hasOwnProperty;var Pn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Oe=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var hu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of mu(t))!_u.call(e,o)&&o!==n&&Ao(e,o,{get:()=>t[o],enumerable:!(r=fu(t,o))||r.enumerable});return e};var Xe=(e,t,n)=>(n=e!=null?pu(gu(e)):{},hu(t||!e||!e.__esModule?Ao(n,"default",{value:e,enumerable:!0}):n,e));var zt=Oe(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.MCP_MISSING_LAUNCH_SERIALIZED=w.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;w.foldMcpName=oi;w.buildMcpFamilyCanonicalKey=Gd;w.launchContainsCredentials=Vd;w.serializeMcpLaunchIdentity=si;w.hashMcpLaunchIdentity=it;w.projectMcpMissingLaunchIdentity=Yd;w.projectMcpLaunchIdentity=Xd;w.maskMcpLaunchForDisplay=qd;w.normalizeMcpToolNames=Qd;var Kd=Pn("node:crypto");w.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";w.MCP_MISSING_LAUNCH_SERIALIZED=`${w.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function de(e){return e.toLocaleLowerCase("en-US")}function oi(e){return de(e)}function Gd(e){return`interface:${oi(e)}`}var ri=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),zd=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function je(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Vd(e){return e.kind==="url"?Wd(e.url):e.kind==="command"?e.arguments.some(t=>zd.test(t)):!1}function Wd(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(ri.has(de(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=de(i.split("=",1)[0]??"");return ri.has(a)})}}function si(e){if(e.kind==="url")return[w.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",je(de(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>de(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[w.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",je(de(e.command)),String(t.length),...t.map(je)].join("|")}return[w.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",je(e.installationRootExternalKey),je(e.sourcePath),je(e.nativeKey)].join("|")}function it(e){return(0,Kd.createHash)("sha256").update(e).digest("hex")}var Jd=it(w.MCP_MISSING_LAUNCH_SERIALIZED);function Yd(){return{kind:"unknown",arguments:[],serialized:w.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:Jd}}function Xd(e){let t=si(e);return e.kind==="url"?{kind:"url",url:de(e.url),arguments:[],serialized:t,contentHash:it(t)}:e.kind==="command"?{kind:"command",command:de(e.command),arguments:[...e.arguments].map(n=>de(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:it(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:it(t)}}var Zd=/^(https?:\/\/)([^/?#]*@)/i;function qd(e){return e.replace(Zd,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function Qd(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 Wt=Oe(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.PACKAGE_FIELD_MAX=void 0;re.npxExecBin=ii;re.packageNameFromSpec=Vt;re.pinnedPackageVersionFromSpec=ai;re.pinnedPackageVersionFromNpx=cp;re.npxPackageSpecs=ci;re.PACKAGE_FIELD_MAX=128;var ep=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,tp=new Set(["-p","--package"]),np=new Set(["-c","--call"]),rp=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),op=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),sp=/^--no-/;function ip(e){return op.has(e)||sp.test(e)}function ii(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}var ap=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function Vt(e){if(e.length===0||e.length>re.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return ep.test(n)?n:null}function ai(e){let t=Vt(e);if(t===null||!e.startsWith(`${t}@`))return;let n=e.slice(t.length+1);return ap.test(n)?n:void 0}function cp(e,t){for(let n of ci(e,t)){let r=ai(n);if(r!==void 0)return r}}function ci(e,t){let n=ii(e);if(n===null)return[];let r=[...t];if(n==="npm"){let i=r[0]?.toLowerCase();if(i!=="exec"&&i!=="x")return[];r=r.slice(1)}let o=[],s=null;for(let i=0;i<r.length;i+=1){let a=r[i]??"";if(a==="--"){s=r[i+1]??null;break}if(!a.startsWith("-")){s=a;break}let c=a.indexOf("="),l=c===-1?a:a.slice(0,c);if(np.has(l))return[];if(tp.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||ip(l))){if(rp.has(l)){i+=1;continue}return[]}}return o.length>0?o.every(i=>Vt(i)!==null)?o:[]:s===null||Vt(s)===null?[]:[s]}});var ui=Oe(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.McpPackageEcosystem=void 0;Te.resolveMcpPackageIdentity=Rp;var up=zt(),fr=Wt();Te.McpPackageEcosystem={NPM:"npm",PYPI:"pypi"};var lp=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,dp=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,pp=/^(?:\d+!)?\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\+[0-9A-Za-z]+(?:[.][0-9A-Za-z]+)*)?$/;function fp(e){let n=(e.replaceAll("\\","/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="uvx"||n==="uv"||n==="pipx"?n:null}var mp=new Set(["--from","--spec"]),gp=new Set(["--python","-p","--with","--with-editable","--with-requirements","--index","--index-url","--default-index","--extra-index-url","--find-links","-f","--constraint","-c","--override","--refresh-package","--cache-dir","--directory","--project","--config-file","--color","--exclude-newer","--pip-args","--verbose-pip"]),_p=new Set(["-q","--quiet","-v","--verbose","-n","--native-tls","--offline","--isolated","--preview","--refresh","--reinstall","--upgrade","-U","--force","--system","--system-site-packages","--path","--managed-python","--progress"]),hp=/^--no-/;function Sp(e,t){let n=fp(e);if(n===null)return null;let r=[...t];if(n==="uv"){if(r[0]?.toLowerCase()!=="tool"||r[1]?.toLowerCase()!=="run")return null;r=r.slice(2)}else if(n==="pipx"){if(r[0]?.toLowerCase()!=="run")return null;r=r.slice(1)}let o=null,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(mp.has(l)){let u=c===-1?r[i+1]:a.slice(c+1);u!==void 0&&u.length>0&&(o=u),c===-1&&(i+=1);continue}if(!(c!==-1||_p.has(l)||hp.test(l))){if(gp.has(l)){i+=1;continue}return null}}return o??s}function Ep(e){if(e.length===0||e.length>fr.PACKAGE_FIELD_MAX)return null;let t=e.includes("==")?"==":e.includes("@")?"@":null;if(t===null)return null;let n=e.indexOf(t),r=e.slice(0,n),o=e.slice(n+t.length);return!dp.test(r)||!pp.test(o)?null:{ecosystem:Te.McpPackageEcosystem.PYPI,packageName:r,version:o}}function yp(e){let t=(0,fr.packageNameFromSpec)(e);if(t===null||!e.startsWith(`${t}@`))return null;let n=e.slice(t.length+1);return lp.test(n)?{ecosystem:Te.McpPackageEcosystem.NPM,packageName:t,version:n}:null}function Rp(e){if(e?.kind!=="command"||(0,up.launchContainsCredentials)(e))return;for(let n of(0,fr.npxPackageSpecs)(e.command,e.arguments)){let r=yp(n);if(r!==null)return r}let t=Sp(e.command,e.arguments);if(t!==null)return Ep(t)??void 0}});var gi=Oe(pe=>{"use strict";Object.defineProperty(pe,"__esModule",{value:!0});pe.EMPTY_NPM_PUBLISHER=void 0;pe.isNpmRegistryPublisher=Ip;pe.displayPublisherName=Ap;pe.classifyMcpProvenance=wp;var pi=zt(),mr=Wt();pe.EMPTY_NPM_PUBLISHER="npm:";var li="npm:",Cp=/^[A-Za-z0-9._-]+$/;function Ip(e){return e.startsWith(li)&&e!==pe.EMPTY_NPM_PUBLISHER&&Cp.test(e.slice(li.length))}function Ap(e){if(!(e==null||e===""||e===pe.EMPTY_NPM_PUBLISHER))return e}function di(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 kp(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 gr(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function Op(e){let t=gr(e),n=kp(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||di(t)||n!==void 0&&di(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function xp(e){let t=gr(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function Pp(e){let t=gr(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function fi(e){let t={kind:"url",url:e};if((0,pi.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||Op(n.hostname))return{origin:"UNKNOWN"};let r=xp(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:Pp(n)}}catch{return{origin:"UNKNOWN"}}}var mi="mcp-remote";function bp(e,t){if(e===mi)return t.find(n=>/^https?:\/\//i.test(n))}function Tp(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function Np(e,t,n){let r=bp(e,t);return r!==void 0?fi(r):e===mi?{origin:"UNKNOWN"}:Tp(e,n)}function vp(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 wp(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,pi.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return fi(t.url);let r=(0,mr.npxPackageSpecs)(t.command,t.arguments)[0];if(r!==void 0){let o=(0,mr.packageNameFromSpec)(r);if(o===null)return{origin:"UNKNOWN"};let s=Np(o,t.arguments,e.publisherName),i=typeof e.packageName=="string"?(0,mr.packageNameFromSpec)(e.packageName):null;return i!==null&&i===o&&s.packageName!==void 0?{...s,packageName:i,packageKey:i}:s}return vp(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var _i=Oe(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.parseFrontmatterField=Z.parseFrontmatterDescription=Z.usableCatalogText=void 0;var Mp=/^(?:>|\|)[-+]?$/,Lp=/^(?:>|\|)[-+]?(?:\s+(.*))?$/,Up=e=>{let t=e?.trim()??"";if(!(t.length===0||Mp.test(t)))return t};Z.usableCatalogText=Up;var Dp=e=>(0,Z.parseFrontmatterField)(e,"description");Z.parseFrontmatterDescription=Dp;var Hp=(e,t)=>{let n=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(n)return jp(n[1],t)};Z.parseFrontmatterField=Hp;var Fp=e=>e.replace(/^["']|["']$/g,"");function jp(e,t){let n=e.split(`
6
- `),r=`${t}:`,o=n.findIndex(d=>d===r||d.startsWith(`${r} `)||d.startsWith(`${r} `));if(o<0)return;let s=(n[o]??"").slice(r.length).trim(),i=Lp.exec(s);if(!i){let d=Fp(s).trim();return(0,Z.usableCatalogText)(d)}let a=[];for(let d=o+1;d<n.length;d+=1){let _=n[d]??"";if(_.trim()===""){a.push("");continue}if(_.length===_.trimStart().length)break;a.push(_)}let c=a.reduce((d,_)=>_.trim()===""?d:Math.min(d,_.length-_.trimStart().length),Number.POSITIVE_INFINITY),l=[],u=i[1]?.trim();u&&l.push(u);for(let d of a)l.push(d.trim()===""?"":d.slice(c));for(;l.length>0&&l[l.length-1]==="";)l.pop();let m=s.startsWith(">")?l.join(`
5
+ var Ju=Object.create;var Lo=Object.defineProperty;var Yu=Object.getOwnPropertyDescriptor;var Xu=Object.getOwnPropertyNames;var Zu=Object.getPrototypeOf,qu=Object.prototype.hasOwnProperty;var Mn=(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 be=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Qu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Xu(t))!qu.call(e,o)&&o!==n&&Lo(e,o,{get:()=>t[o],enumerable:!(r=Yu(t,o))||r.enumerable});return e};var Qe=(e,t,n)=>(n=e!=null?Ju(Zu(e)):{},Qu(t||!e||!e.__esModule?Lo(n,"default",{value:e,enumerable:!0}):n,e));var Zt=be(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.MCP_MISSING_LAUNCH_SERIALIZED=N.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;N.foldMcpName=Mi;N.buildMcpFamilyCanonicalKey=Hf;N.launchContainsCredentials=jf;N.serializeMcpLaunchIdentity=vi;N.hashMcpLaunchIdentity=ct;N.projectMcpMissingLaunchIdentity=Bf;N.projectMcpLaunchIdentity=Gf;N.maskMcpLaunchForDisplay=Vf;N.normalizeMcpToolNames=Wf;var Df=Mn("node:crypto");N.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";N.MCP_MISSING_LAUNCH_SERIALIZED=`${N.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function le(e){return e.toLocaleLowerCase("en-US")}function Mi(e){return le(e)}function Hf(e){return`interface:${Mi(e)}`}var Ni=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),Ff=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function Be(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function jf(e){return e.kind==="url"?$f(e.url):e.kind==="command"?e.arguments.some(t=>Ff.test(t)):!1}function $f(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(Ni.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 Ni.has(a)})}}function vi(e){if(e.kind==="url")return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",Be(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[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",Be(le(e.command)),String(t.length),...t.map(Be)].join("|")}return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",Be(e.installationRootExternalKey),Be(e.sourcePath),Be(e.nativeKey)].join("|")}function ct(e){return(0,Df.createHash)("sha256").update(e).digest("hex")}var Kf=ct(N.MCP_MISSING_LAUNCH_SERIALIZED);function Bf(){return{kind:"unknown",arguments:[],serialized:N.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:Kf}}function Gf(e){let t=vi(e);return e.kind==="url"?{kind:"url",url:le(e.url),arguments:[],serialized:t,contentHash:ct(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:ct(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:ct(t)}}var zf=/^(https?:\/\/)([^/?#]*@)/i;function Vf(e){return e.replace(zf,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function Wf(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 Qt=be(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.PACKAGE_FIELD_MAX=void 0;te.npxExecBin=Li;te.packageNameFromSpec=qt;te.pinnedPackageVersionFromSpec=Ui;te.pinnedPackageVersionFromNpx=np;te.npxPackageSpecs=Di;te.PACKAGE_FIELD_MAX=128;var Jf=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,Yf=new Set(["-p","--package"]),Xf=new Set(["-c","--call"]),Zf=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),qf=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),Qf=/^--no-/;function ep(e){return qf.has(e)||Qf.test(e)}function Li(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}var tp=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function qt(e){if(e.length===0||e.length>te.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return Jf.test(n)?n:null}function Ui(e){let t=qt(e);if(t===null||!e.startsWith(`${t}@`))return;let n=e.slice(t.length+1);return tp.test(n)?n:void 0}function np(e,t){for(let n of Di(e,t)){let r=Ui(n);if(r!==void 0)return r}}function Di(e,t){let n=Li(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(Xf.has(u))return[];if(Yf.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||ep(u))){if(Zf.has(u)){i+=1;continue}return[]}}return o.length>0?o.every(i=>qt(i)!==null)?o:[]:s===null||qt(s)===null?[]:[s]}});var Hi=be(we=>{"use strict";Object.defineProperty(we,"__esModule",{value:!0});we.McpPackageEcosystem=void 0;we.resolveMcpPackageIdentity=gp;var rp=Zt(),Sr=Qt();we.McpPackageEcosystem={NPM:"npm",PYPI:"pypi"};var op=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,sp=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,ip=/^(?:\d+!)?\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\+[0-9A-Za-z]+(?:[.][0-9A-Za-z]+)*)?$/;function ap(e){let n=(e.replaceAll("\\","/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="uvx"||n==="uv"||n==="pipx"?n:null}var cp=new Set(["--from","--spec"]),up=new Set(["--python","-p","--with","--with-editable","--with-requirements","--index","--index-url","--default-index","--extra-index-url","--find-links","-f","--constraint","-c","--override","--refresh-package","--cache-dir","--directory","--project","--config-file","--color","--exclude-newer","--pip-args","--verbose-pip"]),lp=new Set(["-q","--quiet","-v","--verbose","-n","--native-tls","--offline","--isolated","--preview","--refresh","--reinstall","--upgrade","-U","--force","--system","--system-site-packages","--path","--managed-python","--progress"]),dp=/^--no-/;function fp(e,t){let n=ap(e);if(n===null)return null;let r=[...t];if(n==="uv"){if(r[0]?.toLowerCase()!=="tool"||r[1]?.toLowerCase()!=="run")return null;r=r.slice(2)}else if(n==="pipx"){if(r[0]?.toLowerCase()!=="run")return null;r=r.slice(1)}let o=null,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(cp.has(u)){let l=c===-1?r[i+1]:a.slice(c+1);l!==void 0&&l.length>0&&(o=l),c===-1&&(i+=1);continue}if(!(c!==-1||lp.has(u)||dp.test(u))){if(up.has(u)){i+=1;continue}return null}}return o??s}function pp(e){if(e.length===0||e.length>Sr.PACKAGE_FIELD_MAX)return null;let t=e.includes("==")?"==":e.includes("@")?"@":null;if(t===null)return null;let n=e.indexOf(t),r=e.slice(0,n),o=e.slice(n+t.length);return!sp.test(r)||!ip.test(o)?null:{ecosystem:we.McpPackageEcosystem.PYPI,packageName:r,version:o}}function mp(e){let t=(0,Sr.packageNameFromSpec)(e);if(t===null||!e.startsWith(`${t}@`))return null;let n=e.slice(t.length+1);return op.test(n)?{ecosystem:we.McpPackageEcosystem.NPM,packageName:t,version:n}:null}function gp(e){if(e?.kind!=="command"||(0,rp.launchContainsCredentials)(e))return;for(let n of(0,Sr.npxPackageSpecs)(e.command,e.arguments)){let r=mp(n);if(r!==null)return r}let t=fp(e.command,e.arguments);if(t!==null)return pp(t)??void 0}});var Gi=be(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.EMPTY_NPM_PUBLISHER=void 0;de.isNpmRegistryPublisher=hp;de.displayPublisherName=Sp;de.classifyMcpProvenance=bp;var $i=Zt(),Er=Qt();de.EMPTY_NPM_PUBLISHER="npm:";var Fi="npm:",_p=/^[A-Za-z0-9._-]+$/;function hp(e){return e.startsWith(Fi)&&e!==de.EMPTY_NPM_PUBLISHER&&_p.test(e.slice(Fi.length))}function Sp(e){if(!(e==null||e===""||e===de.EMPTY_NPM_PUBLISHER))return e}function ji(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 Ep(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 yr(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function yp(e){let t=yr(e),n=Ep(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||ji(t)||n!==void 0&&ji(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function Rp(e){let t=yr(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function Cp(e){let t=yr(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function Ki(e){let t={kind:"url",url:e};if((0,$i.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||yp(n.hostname))return{origin:"UNKNOWN"};let r=Rp(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:Cp(n)}}catch{return{origin:"UNKNOWN"}}}var Bi="mcp-remote";function kp(e,t){if(e===Bi)return t.find(n=>/^https?:\/\//i.test(n))}function Ip(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function Ap(e,t,n){let r=kp(e,t);return r!==void 0?Ki(r):e===Bi?{origin:"UNKNOWN"}:Ip(e,n)}function Op(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 bp(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,$i.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return Ki(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=Ap(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 Op(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var zi=be(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.parseFrontmatterField=X.parseFrontmatterDescription=X.usableCatalogText=void 0;var xp=/^(?:>|\|)[-+]?$/,Pp=/^(?:>|\|)[-+]?(?:\s+(.*))?$/,Tp=e=>{let t=e?.trim()??"";if(!(t.length===0||xp.test(t)))return t};X.usableCatalogText=Tp;var wp=e=>(0,X.parseFrontmatterField)(e,"description");X.parseFrontmatterDescription=wp;var Np=(e,t)=>{let n=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(n)return vp(n[1],t)};X.parseFrontmatterField=Np;var Mp=e=>e.replace(/^["']|["']$/g,"");function vp(e,t){let n=e.split(`
6
+ `),r=`${t}:`,o=n.findIndex(d=>d===r||d.startsWith(`${r} `)||d.startsWith(`${r} `));if(o<0)return;let s=(n[o]??"").slice(r.length).trim(),i=Pp.exec(s);if(!i){let d=Mp(s).trim();return(0,X.usableCatalogText)(d)}let a=[];for(let d=o+1;d<n.length;d+=1){let _=n[d]??"";if(_.trim()===""){a.push("");continue}if(_.length===_.trimStart().length)break;a.push(_)}let c=a.reduce((d,_)=>_.trim()===""?d:Math.min(d,_.length-_.trimStart().length),Number.POSITIVE_INFINITY),u=[],l=i[1]?.trim();l&&u.push(l);for(let d of a)u.push(d.trim()===""?"":d.slice(c));for(;u.length>0&&u[u.length-1]==="";)u.pop();let m=s.startsWith(">")?u.join(`
7
7
  `).split(/\n{2,}/).map(d=>d.split(`
8
8
  `).map(_=>_.trim()).filter(Boolean).join(" ")).filter(d=>d.length>0).join(`
9
9
 
10
- `):l.join(`
11
- `).trimEnd();return(0,Z.usableCatalogText)(m)}});var yi=Oe(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=x.COMPONENT_INSPECTION_TEXT_MAX_BYTES=x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;x.fitSnapshotInspectionTextBudget=$p;x.capComponentTextBytes=Si;x.prepareComponentInspectionText=Bp;x.redactComponentSource=hr;x.componentSourceContainsRedactableSecret=rf;x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER="[REDACTED]";x.COMPONENT_INSPECTION_TEXT_MAX_BYTES=256*1024;x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=3*1024*1024;function $p(e){let t=0;return e.map(n=>{let r=n,o=r.skill?.inspectionText;if(o===void 0)return n;let s=Buffer.byteLength(o,"utf8");return t+s<=x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES?(t+=s,n):{...n,skill:{...r.skill,inspectionText:void 0}}})}function Si(e,t){if(e==null||e.length===0)return;let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return e;let r=new TextDecoder("utf-8",{fatal:!0});for(let o=t;o>0;o-=1)try{return r.decode(n.subarray(0,o))}catch{}}function Bp(e){if(!(e==null||e.length===0))return Si(hr(e),x.COMPONENT_INSPECTION_TEXT_MAX_BYTES)}var Kp="(?:[A-Za-z0-9_.-]*(?:passwd|password|secret|token|credential|credentials|apikey|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|auth|authorization|session[_-]?id)[A-Za-z0-9_.-]*)",Gp=new RegExp(`(\\b${Kp})(\\s*[:=]\\s*)(?:(")([^"\\n]*)(")|(')([^'\\n]*)(')|([^\\s"'][^"'\\n]*))`,"gi"),zp=[/^(?:none|null|nil|n\/a|empty|unset|not (?:required|needed|set)|no (?:password|token|auth))(?=$|[\s.,;:()—–-])/i,/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/,/^\$\(.*\)$/,/^\$\{\{.*\}\}$/,/^%[A-Za-z_][A-Za-z0-9_]*%$/,/^(?:process\.env|os\.environ|import\.meta\.env)\.[A-Za-z_][A-Za-z0-9_]*[,;]?$/,/^<[^<>]*>$/,/^(?:\*{3,}|\.{3,}|…|x{3,})$/i,/^your[-_ ]/i,/^(?:see|from|via|stored in|use|ask|obtain|get|fetch|run|read|provided by|generated by)\b/i];function _r(e){let t=e.trim().replace(/^`+|`+$/g,"").trim();return zp.some(n=>n.test(t))}function Vp(e){if(e.startsWith("$(")){let n=0;for(let r=1;r<e.length;r+=1)if(e[r]==="("&&(n+=1),e[r]===")"&&(n-=1,n===0))return e.slice(0,r+1);return e}return/^(?:\$\{\{[^}]*\}\}|<[^<>]*>)/.exec(e)?.[0]??/^\S+/.exec(e)?.[0]??""}var Wp=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}/g,/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,/\bgithub_pat_[A-Za-z0-9_]{20,}/g,/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bAIza[0-9A-Za-z_-]{35}\b/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g],Jp=/\b[A-Za-z0-9_+/-]{32,}={0,2}\b/g,Yp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Xp(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function Zp(e){return e.replace(Jp,t=>{if(Yp.test(t))return t;let n=/[A-Za-z]/.test(t),r=/\d/.test(t);return n&&r&&Xp(t)>=3.5?x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:t})}var qp=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,Qp=/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+):([^\s/@]*)@/gi,ef=/([?&](?:access_token|api_key|apikey|auth|authorization|client_secret|key|password|secret|token)=)[^&\s"'<>]+/gi,tf=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,hi=/-----END [A-Z0-9 ]*PRIVATE KEY-----/;function Ei(e){return e.replace(Gp,(t,n,r,o,s,i,a,c,l,u)=>{let p=`${n}${r}`;if(o!==void 0||a!==void 0){let d=o??a??"",_=i??l??"",S=s??c??"";return S===""||S.includes(x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||_r(S)?t:`${p}${d}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${_}`}let m=u??"";if(r==="="){let d=Vp(m).replace(/`+$/,""),_=Ei(m.slice(d.length));return d===""||d.includes(x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||_r(d)?`${p}${d}${_}`:`${p}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${_}`}return m.includes(x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||_r(m)?t:`${p}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`})}function nf(e){let t=e.replace(Qp,(n,r)=>`${r}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}:${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}@`);t=t.replace(ef,(n,r)=>`${r}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`),t=t.replace(qp,(n,r)=>`${r}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`);for(let n of Wp)t=t.replace(n,x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER);return Ei(Zp(t))}function hr(e){if(e.length===0)return e;let t=e.split(`
12
- `),n=!1;return t.map(o=>n?hi.test(o)?(n=!1,o):o.trim().length===0?o:x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:tf.test(o)&&!hi.test(o)?(n=!0,o):nf(o)).join(`
13
- `)}function rf(e){return hr(e)!==e}});var Be=Oe(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.redactComponentSource=g.prepareComponentInspectionText=g.fitSnapshotInspectionTextBudget=g.componentSourceContainsRedactableSecret=g.capComponentTextBytes=g.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=g.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=g.COMPONENT_INSPECTION_TEXT_MAX_BYTES=g.usableCatalogText=g.parseFrontmatterField=g.parseFrontmatterDescription=g.isNpmRegistryPublisher=g.EMPTY_NPM_PUBLISHER=g.displayPublisherName=g.classifyMcpProvenance=g.resolveMcpPackageIdentity=g.McpPackageEcosystem=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=mf;g.installationRootExternalKey=gf;g.normalizeRepositoryRelativePath=Ri;g.nativeKeyForSkillPath=_f;g.nativeKeyForRulePath=hf;g.nativeKeyForCommandPath=Sf;g.serializeComponentIdentity=Ii;g.buildComponentReference=yf;g.validateComponentReference=Rf;var of=Pn("node:crypto"),sf=Pn("node:path"),af="cmp1_",cf=/^cmp1_[A-Za-z0-9_-]{43}$/,uf=["/skills/","/skills-cursor/"],lf=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,df=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,pf=[".cursor",".claude",".codex"],ff={".claude.json":".claude",".agents":".codex"};g.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function mf(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>pf.includes(o));return n||(t.map(o=>ff[o]).find(o=>o!==void 0)??"unknown")}function gf(e,t){return`runtime-install:${e}/${t}`}function Jt(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Ri(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=sf.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Jt(n,"sourcePath")}function _f(e){let t=e.replaceAll("\\","/");for(let n of uf){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Ci(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 hf(e){return Ci(e,lf,/\.(mdc|md|rules)$/i)}function Sf(e){return Ci(e,df,/\.(md|mdc|toml)$/i)}function Ef(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Ii(e){let t=[Jt(e.installationRootExternalKey,"installationRootExternalKey"),Jt(e.installableKind,"installableKind"),Ri(e.sourcePath),Jt(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(Ef).join("|")}`,"utf8")}function yf(e){let t=(0,of.createHash)("sha256").update(Ii(e)).digest("base64url");return`${af}${t}`}function Rf(e){return cf.test(e)}var q=zt();Object.defineProperty(g,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return q.buildMcpFamilyCanonicalKey}});Object.defineProperty(g,"foldMcpName",{enumerable:!0,get:function(){return q.foldMcpName}});Object.defineProperty(g,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return q.hashMcpLaunchIdentity}});Object.defineProperty(g,"launchContainsCredentials",{enumerable:!0,get:function(){return q.launchContainsCredentials}});Object.defineProperty(g,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return q.maskMcpLaunchForDisplay}});Object.defineProperty(g,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return q.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(g,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return q.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(g,"normalizeMcpToolNames",{enumerable:!0,get:function(){return q.normalizeMcpToolNames}});Object.defineProperty(g,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return q.projectMcpLaunchIdentity}});Object.defineProperty(g,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return q.projectMcpMissingLaunchIdentity}});Object.defineProperty(g,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return q.serializeMcpLaunchIdentity}});var $e=Wt();Object.defineProperty(g,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return $e.PACKAGE_FIELD_MAX}});Object.defineProperty(g,"npxExecBin",{enumerable:!0,get:function(){return $e.npxExecBin}});Object.defineProperty(g,"npxPackageSpecs",{enumerable:!0,get:function(){return $e.npxPackageSpecs}});Object.defineProperty(g,"packageNameFromSpec",{enumerable:!0,get:function(){return $e.packageNameFromSpec}});Object.defineProperty(g,"pinnedPackageVersionFromNpx",{enumerable:!0,get:function(){return $e.pinnedPackageVersionFromNpx}});Object.defineProperty(g,"pinnedPackageVersionFromSpec",{enumerable:!0,get:function(){return $e.pinnedPackageVersionFromSpec}});var Ai=ui();Object.defineProperty(g,"McpPackageEcosystem",{enumerable:!0,get:function(){return Ai.McpPackageEcosystem}});Object.defineProperty(g,"resolveMcpPackageIdentity",{enumerable:!0,get:function(){return Ai.resolveMcpPackageIdentity}});var Yt=gi();Object.defineProperty(g,"classifyMcpProvenance",{enumerable:!0,get:function(){return Yt.classifyMcpProvenance}});Object.defineProperty(g,"displayPublisherName",{enumerable:!0,get:function(){return Yt.displayPublisherName}});Object.defineProperty(g,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return Yt.EMPTY_NPM_PUBLISHER}});Object.defineProperty(g,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return Yt.isNpmRegistryPublisher}});var Sr=_i();Object.defineProperty(g,"parseFrontmatterDescription",{enumerable:!0,get:function(){return Sr.parseFrontmatterDescription}});Object.defineProperty(g,"parseFrontmatterField",{enumerable:!0,get:function(){return Sr.parseFrontmatterField}});Object.defineProperty(g,"usableCatalogText",{enumerable:!0,get:function(){return Sr.usableCatalogText}});var Ie=yi();Object.defineProperty(g,"COMPONENT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ie.COMPONENT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"COMPONENT_SOURCE_REDACTION_PLACEHOLDER",{enumerable:!0,get:function(){return Ie.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}});Object.defineProperty(g,"SNAPSHOT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ie.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"capComponentTextBytes",{enumerable:!0,get:function(){return Ie.capComponentTextBytes}});Object.defineProperty(g,"componentSourceContainsRedactableSecret",{enumerable:!0,get:function(){return Ie.componentSourceContainsRedactableSecret}});Object.defineProperty(g,"fitSnapshotInspectionTextBudget",{enumerable:!0,get:function(){return Ie.fitSnapshotInspectionTextBudget}});Object.defineProperty(g,"prepareComponentInspectionText",{enumerable:!0,get:function(){return Ie.prepareComponentInspectionText}});Object.defineProperty(g,"redactComponentSource",{enumerable:!0,get:function(){return Ie.redactComponentSource}})});import{realpathSync as US}from"node:fs";import{resolve as DS}from"node:path";import{fileURLToPath as HS,pathToFileURL as FS}from"node:url";import{createHash as Su}from"node:crypto";import{homedir as Eu}from"node:os";import{dirname as VS,join as yu,parse as WS,resolve as JS}from"node:path";var Oo="https://hooks.ev-ai.ai",xt=".claude/ev-ai-runtime-report.json",xo="config.json",YS=1024*1024,Ru=new Set(["localhost","127.0.0.1","[::1]","::1"]),Cu=["claude","cursor","codex"],Pt=[xt,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],bn=/^[A-Za-z0-9._~-]+$/;function bt(e){return e!==void 0&&Cu.includes(e)}function Ot(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ze(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=Ot(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=Ot(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=Ot(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=Ot(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:bt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Tt(e,t=Oo){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function Tn(e=Eu()){return yu(e,".ev-ai",xo)}function Po(e,t){return{...e,...t}}function ko(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 qe(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Ru.has(t.hostname):!1}catch{return!1}}function Nn(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&&r.length>0?r:void 0}return}catch{return}}function Le(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!qe(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Nn(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!bn.test(n))return`org token must match ${bn.source} (got: ${n})`;if(ko(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(ko(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Qe(e){return new URL(e).toString()}function vn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token,n=typeof t=="string"?t.trim():void 0;return n?Tt(n):""}function Nt(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function bo(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Tt(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=Le(n);return r?{problem:r}:{url:Qe(n)}}function To(e){if(Le(e))return;let t;try{t=new URL(e)}catch{return}let n=Nn(e);if(!n)return;let o=t.pathname.split("/").filter(a=>a.length>0).slice(0,-2),s=o.length>0?`/${o.join("/")}`:"",i=`${t.origin}${s}/${n}`;return Su("sha256").update(i).digest("hex").slice(0,32)}var ge=2,No="node_modules/@ev-ai/agent-hook/dist/hook.mjs",ee="ev-ai-agent-hook";function Iu(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function vt(e){let t=Iu(e);return t===ee||t===`${ee}.exe`}var vo="https://cdn.ev-ai.ai/agent-hook";var wn=`current/${ee}`,Mn=`.ev-ai/agent-hook/${ee}`,wo=5e3,Mo=5e3,Ln=3e3;var Un=3e3,Lo=1500,Uo=4*1024,Dn=256*1024,Au=4*1024,Do=32*1024,et=840*60*1e3,se="1.2.4",wt=`@ev-ai/agent-hook@${se}`,Ho="ev-ai runtime report";import{chmodSync as Is,cpSync as As,existsSync as he,mkdirSync as or,readFileSync as Tl,rmSync as jt,symlinkSync as Nl,writeFileSync as vl}from"node:fs";import{homedir as ue}from"node:os";import{dirname as sr,isAbsolute as wl,join as P,relative as ks,resolve as Rs,sep as Ml}from"node:path";import{fileURLToPath as Ll}from"node:url";import{existsSync as ku,readdirSync as Fo}from"node:fs";import{homedir as Mt}from"node:os";import{join as K}from"node:path";function jo(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=jo(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!ku(r))return n;let o=Fo(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function Fn(e=process.platform,t=Mt()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:Hn(e)}}function Ou(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 xu(e=process.platform,t=Mt()){let n=[K(Ou(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of Fo(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function Pu(e=process.platform,t=Mt()){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 Lt(e,t=process.platform,n=Mt()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Fn(t,n);return[r,...o]}case"cursor":return xu(t,n);default:return Pu(t,n)}}import{createHash as ts,randomBytes as Zu}from"node:crypto";import{existsSync as ns,mkdirSync as Yn,readFileSync as rs,unlinkSync as os,writeFileSync as ss}from"node:fs";import{homedir as Xn}from"node:os";import{dirname as Dt,join as Zn,resolve as qu}from"node:path";var bu=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),Tu=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function z(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||Tu.has(n)||r.includes("[bot]")||bu.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 Hu,readFileSync as Fu}from"node:fs";import{hostname as Jo,userInfo as ju}from"node:os";import{randomBytes as Nu}from"node:crypto";import{existsSync as $n,mkdirSync as vu,readdirSync as wu,readFileSync as Mu,renameSync as $o,statSync as Go,unlinkSync as Bo,writeFileSync as Lu}from"node:fs";import{basename as Uu,dirname as Ko,join as zo,relative as Du}from"node:path";function f(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
14
- `)}function te(e,t){vu(Ko(e),{recursive:!0});let n=zo(Ko(e),`.${Uu(e)}.${process.pid}.${Nu(4).toString("hex")}.tmp`);try{Lu(n,t,"utf8");try{$o(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Bo(e),$o(n,e);return}throw r}}catch(r){try{Bo(n)}catch{}throw r}}function Ut(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Vo(){process.stdout.write('{"continue":true}')}function I(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function tt(){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 X(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 X(e,t,n,r);return o.ok?o.stdout:""}async function Kn(e=process.cwd()){let t=await X("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")}`;f(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=I("CURSOR_PROJECT_DIR")??I("CLAUDE_PROJECT_DIR");if(n&&$n(n)){let r=await X("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 ie(e=process.cwd()){return(await Kn(e)).root}function $(e,t){try{return JSON.parse(e)}catch{return t}}var jn=new Map;function F(e,t){let n=jn.get(e);if(n!==void 0)return n;try{let r=$(Mu(e,"utf8"),t);return jn.set(e,r),r}catch{return jn.set(e,t),t}}function xe(e){return typeof e=="string"?e:""}function ae(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 h(e,t){let n=ae(e,t);return typeof n=="string"?n:""}var _e=500;function Wo(e,t=2){if(!$n(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=wu(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=zo(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:Du(e,l),size:Go(l).size})}catch{continue}if(n.length>=_e){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Gn(e){return $n(e)?{present:!0,size:Go(e).size}:{present:!1,size:0}}function Ue(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function zn(e=process.env){return Ue(N("CURSOR_SANDBOX",e))}var $u=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Bu(e){return $u.some(t=>!!N(t,e))}function Ku(e){if(N("KUBERNETES_SERVICE_HOST",e)||Ue(N("REMOTE_CONTAINERS",e))||Ue(N("DEVCONTAINER",e)))return!0;try{if(Hu("/.dockerenv")||Fu("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Yo(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!N(t,e))}function Gu(e,t=process.platform){return Yo(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!N(n,e)):!1}function zu(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Vu(e){return e==="linux"}function N(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return I(e)}function Wu(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Ju(N("CURSOR_VERSION",n))}function Ju(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Vn(e){if(zu(e.sessionId))return!0;let t=e.hostname??Jo(),n=e.osUser??Xo(e.env);return Wu(t,n,e.env)}function Yu(e){return Ue(N("CURSOR_AGENT",e.env))?!0:Vn(e)}function Xu(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(N("TERM",e)??N("TERM_PROGRAM",e))||(N("SSH_TTY",e)??N("SSH_CONNECTION",e))||(N("__CFBundleIdentifier",e)??N("XPC_SERVICE_NAME",e))||Yo(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!N(t,e))||N("SESSIONNAME",e))}function nt(e={}){let t=e.env;if(N("GITHUB_ACTIONS",t))return"github_actions";if(Ue(N("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Gu(t,n)&&Yu(e)&&(Ue(N("CURSOR_AGENT",t))||Vu(n)))return"cursor_cloud";if(N("CODESPACES",t)||N("CODESPACE_NAME",t))return"codespaces";if(N("GITLAB_CI",t))return"gitlab_ci";if(Bu(t))return"managed";let r=N("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Ku(t)?"container":Xu(t)?"interactive":"unknown"}async function Wn(){return await M("systemd-detect-virt",[],1e3)}function Xo(e=process.env,t=ju){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 Jn(){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=Xo(),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 rt(){return Jo()}var Qu="installation.json",el="cloud-bootstrap.lock",tl=6e4;function is(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function ce(e=Xn()){return Zn(e,".ev-ai","agent-hook")}function nl(e=Xn()){return Zn(ce(e),Qu)}function as(e){return Zn(Dt(e),el)}function cs(){return Zu(8).toString("hex")}function De(e){return ts("sha256").update(e).digest("hex").slice(0,16)}function A(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function us(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function rl(e=process.env){let t=A(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!us(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 ls(e,t){return e&&us(e)?e:(e&&f(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),rl(t))}function ol(e){return/^[0-9a-f]{16}$/.test(e)}function sl(e=process.env){if(A(e.GITHUB_ACTIONS)){let t=A(e.GITHUB_REPOSITORY_ID)??A(e.GITHUB_REPOSITORY),n=A(e.GITHUB_ACTOR)??A(e.GITHUB_TRIGGERING_ACTOR)??A(e.GITHUB_USER);if(t&&n)return De(`github_actions|${t}|${n}`)}if(A(e.CODESPACES)||A(e.CODESPACE_NAME)){let t=A(e.CODESPACE_NAME);if(t)return De(`codespaces|${t}`);let n=A(e.GITHUB_REPOSITORY_ID)??A(e.GITHUB_REPOSITORY),r=A(e.GITHUB_USER)??A(e.GITHUB_ACTOR);if(n&&r)return De(`codespaces|${n}|${r}`)}if(A(e.GITLAB_CI)){let t=A(e.CI_PROJECT_ID)??A(e.CI_PROJECT_PATH),n=A(e.GITLAB_USER_LOGIN)??A(e.GITLAB_USER_EMAIL)??A(e.GITLAB_USER_NAME);if(t&&n)return De(`gitlab|${t}|${n}`)}return null}var il="cursoragent@cursor.com";function al(e){let t=A(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===il?null:t}function cl(e,t){return A(e.CURSOR_PROJECT_DIR)??A(e.CLAUDE_PROJECT_DIR)??t}function ul(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function ll(e){let t=await M("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?ul(t):e}async function dl(e){let t=A(await M("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!z(null,t))return t;let n=A(await M("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!z(null,n)?n:null}function pl(e,t){let n=cl(e,t);return n?De(`cursor_cloud|${n}|${al(e)??""}`):null}async function fl(e,t){let n=A(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await ll(n),o=await dl(n);return De(`claude_remote|${r}|${o??""}`)}function Zo(e,t){let n=ls(e,t);if(n)return n;let r=sl(t);return r||cs()}async function ml(e){let n=await M("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||qu(e);return ts("sha256").update(n).digest("hex").slice(0,16)}function gl(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 _l(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=gl(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function Pe(e){if(ns(e))try{return _l(rs(e,"utf8"))}catch{}}function qn(e){return Pe(e)}function ds(e,t,n){let r=Pe(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{te(e,`${JSON.stringify(o,null,2)}
15
- `)}catch(s){let i=s instanceof Error?s.message:String(s);f(`WARN: operator identity cache write failed open: ${i}`)}}function ps(e,t=Date.now()){if(!e)return!0;if(Pe(e)?.operator_identity_hash)return!1;let n=as(e);try{if(ns(n)){let r=Number.NaN;try{r=Number(rs(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<tl)return!1;try{os(n)}catch{}}}catch{}try{return Yn(Dt(n),{recursive:!0}),ss(n,`${t}
16
- `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(_s(r))return!1;let o=r instanceof Error?r.message:String(r);return f(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function fs(e){if(e)try{os(as(e))}catch{}}function ms(e,t){let r=Pe(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function gs(e,t,n){if(!n)return;let r=Pe(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{te(e,`${JSON.stringify(o,null,2)}
17
- `)}catch(s){let i=s instanceof Error?s.message:String(s);f(`WARN: platform_agent_id cache write failed open: ${i}`)}}function _s(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function hl(e,t){Yn(Dt(e),{recursive:!0}),ss(e,`${JSON.stringify(t,null,2)}
18
- `,{encoding:"utf8",flag:"wx"})}function qo(e,t){try{return hl(e,t),t}catch(n){if(!_s(n))throw n;return Pe(e)}}function Qo(e,t){Yn(Dt(e),{recursive:!0}),te(e,`${JSON.stringify(t,null,2)}
19
- `)}function es(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Ht(e,t={}){let n=t.home??Xn(),r=t.env??process.env,o=await ml(e),s=nl(n),i={sessionId:t.sessionId,hostname:A(r.HOSTNAME)??void 0,osUser:A(r.USER)??A(r.LOGNAME)??A(r.USERNAME)??void 0,env:r},a=nt(i),c=ls(t.overrideId,r),l=a==="cursor_cloud"&&Vn(i)?pl(r,e):a==="claude_remote"?await fl(r,e):null,u=Pe(s);if(u){let S=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(S={...u,pinned:!0},Qo(s,S)),!!l&&l!==S.installation_id&&!c&&S.pinned!==!0&&ol(S.installation_id)&&l){let y={installation_id:l,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return Qo(s,y),{installationId:l,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let p=c??l??Zo(void 0,r),m=qo(s,es(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let d=c??l??Zo(void 0,r),_=qo(s,es(d===p?cs():d,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as er,readFileSync as Sl}from"node:fs";import{dirname as El,isAbsolute as yl,join as Rl,relative as Cl}from"node:path";function hs(e){for(let t of Pt){let n=Rl(e,t);if(er(n))return n}}async function Il(e=process.cwd(),t){let n=t??await ie(e);return hs(n)??hs(e)}async function Al(e,t){let n=t??await ie(El(e)),r=Cl(n,e);if(r.startsWith("..")||yl(r))return!1;let o=await X("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 Qn(e){let t=Sl(e,"utf8");return $(t,{})}function kl(){return{schema_version:ge,mcp_servers:[]}}function Ol(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 Ss(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Kn(e),o=I("EV_AI_HOOK_MANIFEST"),s=o&&er(o)?o:void 0,i=s?void 0:er(Tn())?Tn():void 0,a=s?void 0:await Il(e,n),c=i?Qn(i):void 0,l=a?Qn(a):void 0,u,p,m,d=new Set;if(s){u=Qn(s),p=s,m=s;for(let R of Object.keys(u))d.add(R)}else if(c&&l){u=Po(l,c),p=i,m=a;for(let R of Object.keys(l))R in c||d.add(R)}else if(c)u=c,p=i;else if(l){u=l,p=a,m=a;for(let R of Object.keys(l))d.add(R)}else u=kl();delete u.installation_id;let _=m?await Al(m,n):!1;Ol(u,m,_,d);let{installationId:S,storePath:E,repoKey:y}=await Ht(n,{sessionId:t.sessionId});return{manifestPath:p??E,manifest:u,installationId:S,installationStorePath:E,repoKey:y,collectorUrl:vn(u),platformAgentId:u.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function Es(e){return{schema_version:ge,...e?{collector_url:e}:{},mcp_servers:[]}}var xl=["darwin-arm64","darwin-x64","linux-arm64","linux-x64","windows-x64","windows-arm64"];function Pl(e){return e==="windows-x64"||e==="windows-arm64"}function tr(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 ys(e=process.platform,t=process.arch){let n=tr(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${xl.join(", ")}.`);return n}function bl(e){return Pl(e)?`${ee}.exe`:ee}function nr(e){return`compile-out/bin/${e}/${bl(e)}`}function Ul(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=Le(n);if(r)throw new Error(`collector URL rejected: ${r}`);return Qe(n)}function Dl(e){let t=e.collectorUrl?.trim();if(!t)return;let n=Le(t);if(n)throw new Error(`collector URL rejected: ${n}`);return Qe(t)}function Hl(e){return Ul(e,"install")}function Os(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 xs(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 Ps(e=process.execPath){return bs(e)?"binary":"npx"}function Fl(){return P(ue(),".ev-ai","agent-hook")}function jl(e=ue()){return P(e,".ev-ai","agent-hook",wn)}function $l(){let e=sr(Ll(import.meta.url)),t=P(e,"hook.mjs");return he(t)?t:P(e,"..","dist","hook.mjs")}function bs(e=process.execPath){return vt(e)}function Ts(e,t){let n=ks(Rs(e),Rs(t));return!n.startsWith("..")&&!wl(n)}function $t(e){return e.split(Ml).join("/")}function Bl(e){return`node "$(git rev-parse --show-toplevel)/${$t(e)}"`}function Kl(e){return`"$(git rev-parse --show-toplevel)/${$t(e)}"`}function Gl(e){return P(e,Mn)}function Ns(e,t){let n=Gl(e);or(sr(n),{recursive:!0}),As(t,n,{force:!0});try{Is(n,493)}catch{}return n}function zl(e){let t=P(Fl(),"current");try{jt(t,{recursive:!0,force:!0})}catch{}Nl(e,t,process.platform==="win32"?"junction":"dir")}function vs(e,t=se,n=ue()){let r=P(n,".ev-ai","agent-hook",t),o=P(r,ee);or(r,{recursive:!0}),As(e,o,{force:!0});try{Is(o,493)}catch{}return zl(r),P(n,".ev-ai","agent-hook",wn)}function ws(e){let t=tr();if(!t)return;let n=[P(e,nr(t)),P(e,"packages","agent-hook",nr(t))];for(let r of n)if(he(r)&&Ts(e,r))return r}function Vl(e=ue()){let t=jl(e);return he(t)?t:void 0}function Wl(e,t=ue()){let n=Vl(t);return n||(bs()?vs(process.execPath,se,t):ws(e))}function Jl(e,t=ue()){let n=ws(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
20
- To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=vs(n,se,t),o=Ns(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function Cs(e){let t=[P(e,"packages","agent-hook","dist","hook.mjs"),P(e,No)],n=$l();he(n)&&Ts(e,n)&&t.unshift(n);for(let r of t){if(!he(r))continue;let o=$t(ks(e,r));return{command:Bl(o),hookPath:o,strategy:"dev_mjs"}}}function Yl(e){return e==="SessionStart"||e==="sessionStart"}function Xl(e){return e.replace(/\s+--prefer-offline\b/g,"")}function Ft(e,t){return Yl(e)?Xl(t):t}function Zl(e=wt){return`npx -y --prefer-offline ${e}`}function ql(e,t=ue(),n=Ps()){if(n==="npx")return{command:Zl(),hookPath:wt,strategy:"npx"};if(n==="local"){let s=Cs(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=Wl(e,t);if(r){Ns(e,r);let s=$t(Mn);return{command:Kl(s),hookPath:s,strategy:"project_binary"}}let o=Cs(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
21
- curl -fsSL ${vo}/install.sh | sh
10
+ `):u.join(`
11
+ `).trimEnd();return(0,X.usableCatalogText)(m)}});var Yi=be(b=>{"use strict";Object.defineProperty(b,"__esModule",{value:!0});b.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=b.COMPONENT_INSPECTION_TEXT_MAX_BYTES=b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;b.fitSnapshotInspectionTextBudget=Lp;b.capComponentTextBytes=Wi;b.prepareComponentInspectionText=Up;b.redactComponentSource=Cr;b.componentSourceContainsRedactableSecret=Zp;b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER="[REDACTED]";b.COMPONENT_INSPECTION_TEXT_MAX_BYTES=256*1024;b.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=3*1024*1024;function Lp(e){let t=0;return e.map(n=>{let r=n,o=r.skill?.inspectionText;if(o===void 0)return n;let s=Buffer.byteLength(o,"utf8");return t+s<=b.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES?(t+=s,n):{...n,skill:{...r.skill,inspectionText:void 0}}})}function Wi(e,t){if(e==null||e.length===0)return;let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return e;let r=new TextDecoder("utf-8",{fatal:!0});for(let o=t;o>0;o-=1)try{return r.decode(n.subarray(0,o))}catch{}}function Up(e){if(!(e==null||e.length===0))return Wi(Cr(e),b.COMPONENT_INSPECTION_TEXT_MAX_BYTES)}var Dp="(?:[A-Za-z0-9_.-]*(?:passwd|password|secret|token|credential|credentials|apikey|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|auth|authorization|session[_-]?id)[A-Za-z0-9_.-]*)",Hp=new RegExp(`(\\b${Dp})(\\s*[:=]\\s*)(?:(")([^"\\n]*)(")|(')([^'\\n]*)(')|([^\\s"'][^"'\\n]*))`,"gi"),Fp=[/^(?:none|null|nil|n\/a|empty|unset|not (?:required|needed|set)|no (?:password|token|auth))(?=$|[\s.,;:()—–-])/i,/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/,/^\$\(.*\)$/,/^\$\{\{.*\}\}$/,/^%[A-Za-z_][A-Za-z0-9_]*%$/,/^(?:process\.env|os\.environ|import\.meta\.env)\.[A-Za-z_][A-Za-z0-9_]*[,;]?$/,/^<[^<>]*>$/,/^(?:\*{3,}|\.{3,}|…|x{3,})$/i,/^your[-_ ]/i,/^(?:see|from|via|stored in|use|ask|obtain|get|fetch|run|read|provided by|generated by)\b/i];function Rr(e){let t=e.trim().replace(/^`+|`+$/g,"").trim();return Fp.some(n=>n.test(t))}function jp(e){if(e.startsWith("$(")){let n=0;for(let r=1;r<e.length;r+=1)if(e[r]==="("&&(n+=1),e[r]===")"&&(n-=1,n===0))return e.slice(0,r+1);return e}return/^(?:\$\{\{[^}]*\}\}|<[^<>]*>)/.exec(e)?.[0]??/^\S+/.exec(e)?.[0]??""}var $p=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}/g,/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,/\bgithub_pat_[A-Za-z0-9_]{20,}/g,/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bAIza[0-9A-Za-z_-]{35}\b/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g],Kp=/\b[A-Za-z0-9_+/-]{32,}={0,2}\b/g,Bp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Gp(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function zp(e){return e.replace(Kp,t=>{if(Bp.test(t))return t;let n=/[A-Za-z]/.test(t),r=/\d/.test(t);return n&&r&&Gp(t)>=3.5?b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:t})}var Vp=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,Wp=/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+):([^\s/@]*)@/gi,Jp=/([?&](?:access_token|api_key|apikey|auth|authorization|client_secret|key|password|secret|token)=)[^&\s"'<>]+/gi,Yp=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,Vi=/-----END [A-Z0-9 ]*PRIVATE KEY-----/;function Ji(e){return e.replace(Hp,(t,n,r,o,s,i,a,c,u,l)=>{let f=`${n}${r}`;if(o!==void 0||a!==void 0){let d=o??a??"",_=i??u??"",h=s??c??"";return h===""||h.includes(b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Rr(h)?t:`${f}${d}${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${_}`}let m=l??"";if(r==="="){let d=jp(m).replace(/`+$/,""),_=Ji(m.slice(d.length));return d===""||d.includes(b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Rr(d)?`${f}${d}${_}`:`${f}${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${_}`}return m.includes(b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Rr(m)?t:`${f}${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`})}function Xp(e){let t=e.replace(Wp,(n,r)=>`${r}${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}:${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}@`);t=t.replace(Jp,(n,r)=>`${r}${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`),t=t.replace(Vp,(n,r)=>`${r}${b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`);for(let n of $p)t=t.replace(n,b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER);return Ji(zp(t))}function Cr(e){if(e.length===0)return e;let t=e.split(`
12
+ `),n=!1;return t.map(o=>n?Vi.test(o)?(n=!1,o):o.trim().length===0?o:b.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:Yp.test(o)&&!Vi.test(o)?(n=!0,o):Xp(o)).join(`
13
+ `)}function Zp(e){return Cr(e)!==e}});var ze=be(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.redactComponentSource=g.prepareComponentInspectionText=g.fitSnapshotInspectionTextBudget=g.componentSourceContainsRedactableSecret=g.capComponentTextBytes=g.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=g.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=g.COMPONENT_INSPECTION_TEXT_MAX_BYTES=g.usableCatalogText=g.parseFrontmatterField=g.parseFrontmatterDescription=g.isNpmRegistryPublisher=g.EMPTY_NPM_PUBLISHER=g.displayPublisherName=g.classifyMcpProvenance=g.resolveMcpPackageIdentity=g.McpPackageEcosystem=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=am;g.installationRootExternalKey=cm;g.normalizeRepositoryRelativePath=Xi;g.nativeKeyForSkillPath=um;g.nativeKeyForRulePath=lm;g.nativeKeyForCommandPath=dm;g.serializeComponentIdentity=qi;g.buildComponentReference=pm;g.validateComponentReference=mm;var qp=Mn("node:crypto"),Qp=Mn("node:path"),em="cmp1_",tm=/^cmp1_[A-Za-z0-9_-]{43}$/,nm=["/skills/","/skills-cursor/"],rm=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,om=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,sm=[".cursor",".claude",".codex"],im={".claude.json":".claude",".agents":".codex"};g.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function am(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>sm.includes(o));return n||(t.map(o=>im[o]).find(o=>o!==void 0)??"unknown")}function cm(e,t){return`runtime-install:${e}/${t}`}function en(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Xi(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=Qp.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return en(n,"sourcePath")}function um(e){let t=e.replaceAll("\\","/");for(let n of nm){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Zi(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 lm(e){return Zi(e,rm,/\.(mdc|md|rules)$/i)}function dm(e){return Zi(e,om,/\.(md|mdc|toml)$/i)}function fm(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function qi(e){let t=[en(e.installationRootExternalKey,"installationRootExternalKey"),en(e.installableKind,"installableKind"),Xi(e.sourcePath),en(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(fm).join("|")}`,"utf8")}function pm(e){let t=(0,qp.createHash)("sha256").update(qi(e)).digest("base64url");return`${em}${t}`}function mm(e){return tm.test(e)}var Z=Zt();Object.defineProperty(g,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return Z.buildMcpFamilyCanonicalKey}});Object.defineProperty(g,"foldMcpName",{enumerable:!0,get:function(){return Z.foldMcpName}});Object.defineProperty(g,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.hashMcpLaunchIdentity}});Object.defineProperty(g,"launchContainsCredentials",{enumerable:!0,get:function(){return Z.launchContainsCredentials}});Object.defineProperty(g,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return Z.maskMcpLaunchForDisplay}});Object.defineProperty(g,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return Z.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(g,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return Z.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(g,"normalizeMcpToolNames",{enumerable:!0,get:function(){return Z.normalizeMcpToolNames}});Object.defineProperty(g,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.projectMcpLaunchIdentity}});Object.defineProperty(g,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return Z.projectMcpMissingLaunchIdentity}});Object.defineProperty(g,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.serializeMcpLaunchIdentity}});var Ge=Qt();Object.defineProperty(g,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return Ge.PACKAGE_FIELD_MAX}});Object.defineProperty(g,"npxExecBin",{enumerable:!0,get:function(){return Ge.npxExecBin}});Object.defineProperty(g,"npxPackageSpecs",{enumerable:!0,get:function(){return Ge.npxPackageSpecs}});Object.defineProperty(g,"packageNameFromSpec",{enumerable:!0,get:function(){return Ge.packageNameFromSpec}});Object.defineProperty(g,"pinnedPackageVersionFromNpx",{enumerable:!0,get:function(){return Ge.pinnedPackageVersionFromNpx}});Object.defineProperty(g,"pinnedPackageVersionFromSpec",{enumerable:!0,get:function(){return Ge.pinnedPackageVersionFromSpec}});var Qi=Hi();Object.defineProperty(g,"McpPackageEcosystem",{enumerable:!0,get:function(){return Qi.McpPackageEcosystem}});Object.defineProperty(g,"resolveMcpPackageIdentity",{enumerable:!0,get:function(){return Qi.resolveMcpPackageIdentity}});var tn=Gi();Object.defineProperty(g,"classifyMcpProvenance",{enumerable:!0,get:function(){return tn.classifyMcpProvenance}});Object.defineProperty(g,"displayPublisherName",{enumerable:!0,get:function(){return tn.displayPublisherName}});Object.defineProperty(g,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return tn.EMPTY_NPM_PUBLISHER}});Object.defineProperty(g,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return tn.isNpmRegistryPublisher}});var kr=zi();Object.defineProperty(g,"parseFrontmatterDescription",{enumerable:!0,get:function(){return kr.parseFrontmatterDescription}});Object.defineProperty(g,"parseFrontmatterField",{enumerable:!0,get:function(){return kr.parseFrontmatterField}});Object.defineProperty(g,"usableCatalogText",{enumerable:!0,get:function(){return kr.usableCatalogText}});var Ce=Yi();Object.defineProperty(g,"COMPONENT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ce.COMPONENT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"COMPONENT_SOURCE_REDACTION_PLACEHOLDER",{enumerable:!0,get:function(){return Ce.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}});Object.defineProperty(g,"SNAPSHOT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ce.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"capComponentTextBytes",{enumerable:!0,get:function(){return Ce.capComponentTextBytes}});Object.defineProperty(g,"componentSourceContainsRedactableSecret",{enumerable:!0,get:function(){return Ce.componentSourceContainsRedactableSecret}});Object.defineProperty(g,"fitSnapshotInspectionTextBudget",{enumerable:!0,get:function(){return Ce.fitSnapshotInspectionTextBudget}});Object.defineProperty(g,"prepareComponentInspectionText",{enumerable:!0,get:function(){return Ce.prepareComponentInspectionText}});Object.defineProperty(g,"redactComponentSource",{enumerable:!0,get:function(){return Ce.redactComponentSource}})});import{realpathSync as ME}from"node:fs";import{resolve as vE}from"node:path";import{fileURLToPath as LE,pathToFileURL as UE}from"node:url";import{createHash as el}from"node:crypto";import{homedir as tl}from"node:os";import{dirname as XE,join as nl,parse as ZE,resolve as qE}from"node:path";var Uo="EV_AI_LAUNCHER_VERSION";var Do="EV_AI_HOOK_SOURCE",Ho="EV_AI_HOOK_FALLBACK_REASON",Fo="EV_AI_LAUNCHER_SCOPE",vn="EV_AI_LAUNCHER_READY_FD";var jo="--defer-user-spec",$o=Buffer.from([1]);var jE=1024*1024,$E=4*1024*1024,KE=64*1024,BE=64*1024,GE=64*1024;var Ln=4096,zE=4*1024*1024;var Bo="https://hooks.ev-ai.ai",Tt=".claude/ev-ai-runtime-report.json",Go="config.json",ey=1024*1024,rl=new Set(["localhost","127.0.0.1","[::1]","::1"]),ol=["claude","cursor","codex"],wt=[Tt,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],Un=/^[A-Za-z0-9._~-]+$/;function Nt(e){return e!==void 0&&ol.includes(e)}function Pt(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Dn(e){let t,n,r,o,s,i=!1;for(let a=0;a<e.length;a++){let c=e[a];if(c!==void 0){if(c==="--runner"){let u=Pt(e,a);t=u.value,a=u.next;continue}if(c.startsWith("--runner=")){t=c.slice(9);continue}if(c==="--url"){let u=Pt(e,a);u.value&&(r=u.value),a=u.next;continue}if(c.startsWith("--url=")){r=c.slice(6);continue}if(c==="--token"){let u=Pt(e,a);u.value&&(o=u.value),a=u.next;continue}if(c.startsWith("--token=")){o=c.slice(8);continue}if(c==="--base-url"){let u=Pt(e,a);u.value&&(s=u.value),a=u.next;continue}if(c.startsWith("--base-url=")){s=c.slice(11);continue}if(c===jo){i=!0;continue}!c.startsWith("-")&&n===void 0&&(n=c)}}return{runner:Nt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s,...i?{deferUserSpec:!0}:{}}}function Mt(e,t=Bo){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function Hn(e=tl()){return nl(e,".ev-ai",Go)}function zo(e,t){return{...e,...t}}function Ko(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 vt(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?rl.has(t.hostname):!1}catch{return!1}}function Fn(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&&r.length>0?r:void 0}return}catch{return}}function He(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!vt(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Fn(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Un.test(n))return`org token must match ${Un.source} (got: ${n})`;if(Ko(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Ko(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function et(e){return new URL(e).toString()}function jn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token,n=typeof t=="string"?t.trim():void 0;return n?Mt(n):""}function Lt(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 Vo(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Mt(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=He(n);return r?{problem:r}:{url:et(n)}}function Wo(e){if(He(e))return;let t;try{t=new URL(e)}catch{return}let n=Fn(e);if(!n)return;let o=t.pathname.split("/").filter(a=>a.length>0).slice(0,-2),s=o.length>0?`/${o.join("/")}`:"",i=`${t.origin}${s}/${n}`;return el("sha256").update(i).digest("hex").slice(0,32)}var me=2,Jo="node_modules/@ev-ai/agent-hook/dist/hook.mjs",q="ev-ai-agent-hook";function sl(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function Ut(e){let t=sl(e);return t===q||t===`${q}.exe`}var Yo="https://cdn.ev-ai.ai/agent-hook";var $n=`current/${q}`,Kn=`.ev-ai/agent-hook/${q}`,Xo=5e3,Zo=5e3,Bn=3e3;var Gn=3e3,qo=1500,Qo=4*1024,zn=256*1024,il=4*1024,es=32*1024,tt=840*60*1e3,oe="1.2.6",Dt=`@ev-ai/agent-hook@${oe}`,ts="ev-ai runtime report";import{chmodSync as Vs,cpSync as Ws,existsSync as _e,mkdirSync as cr,readFileSync as gd,rmSync as zt,symlinkSync as _d,writeFileSync as hd}from"node:fs";import{homedir as ce}from"node:os";import{dirname as ur,isAbsolute as Sd,join as x,relative as Js,resolve as Gs,sep as Ed}from"node:path";import{fileURLToPath as yd}from"node:url";import{existsSync as al,readdirSync as ns}from"node:fs";import{homedir as Ht}from"node:os";import{join as K}from"node:path";function rs(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 Vn(e=process.platform){let t=rs(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!al(r))return n;let o=ns(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function Wn(e=process.platform,t=Ht()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:Vn(e)}}function cl(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 ul(e=process.platform,t=Ht()){let n=[K(cl(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of ns(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function ll(e=process.platform,t=Ht()){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 Ft(e,t=process.platform,n=Ht()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Wn(t,n);return[r,...o]}case"cursor":return ul(t,n);default:return ll(t,n)}}import{createHash as Is,randomBytes as Ul}from"node:crypto";import{existsSync as As,mkdirSync as Qn,readFileSync as Os,unlinkSync as bs,writeFileSync as xs}from"node:fs";import{homedir as er}from"node:os";import{dirname as Kt,join as tr,resolve as Dl}from"node:path";var dl=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),fl=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]")||fl.has(n)||r.includes("[bot]")||dl.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 kl,readFileSync as Il}from"node:fs";import{hostname as ms,userInfo as Al}from"node:os";import{createHash as pl,randomBytes as ml}from"node:crypto";import{existsSync as Jn,mkdirSync as gl,readdirSync as _l,readFileSync as hl,renameSync as os,statSync as cs,unlinkSync as ss,writeFileSync as Sl}from"node:fs";import{basename as El,dirname as is,join as us,relative as yl}from"node:path";function p(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
14
+ `)}function nt(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1")}function rt(e){return pl("sha256").update(e).digest("hex").slice(0,32)}function Q(e,t){gl(is(e),{recursive:!0});let n=us(is(e),`.${El(e)}.${process.pid}.${ml(4).toString("hex")}.tmp`);try{Sl(n,t,"utf8");try{os(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){ss(e),os(n,e);return}throw r}}catch(r){try{ss(n)}catch{}throw r}}function jt(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function ls(){process.stdout.write('{"continue":true}')}function k(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function ot(){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 Yn(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 Y(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 v(e,t,n=3e3,r={}){let o=await Y(e,t,n,r);return o.ok?o.stdout:""}async function Xn(e=process.cwd()){let t=await Y("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")}`;p(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=k("CURSOR_PROJECT_DIR")??k("CLAUDE_PROJECT_DIR");if(n&&Jn(n)){let r=await Y("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 z(e,t){try{return JSON.parse(e)}catch{return t}}var as=new Map;function Rl(e){return e.charCodeAt(0)===65279?e.slice(1):e}function Cl(e){let t;try{t=hl(e,"utf8")}catch{return{ok:!1,reason:"read"}}try{return{ok:!0,value:JSON.parse(Rl(t))}}catch{return{ok:!1,reason:"parse"}}}function ds(e){let t=as.get(e);if(t!==void 0)return t;let n=Cl(e);return as.set(e,n),n}function fs(e){return ds(e)}function D(e,t){let n=ds(e);return n.ok?n.value:t}function xe(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 R(e,t){let n=ie(e,t);return typeof n=="string"?n:""}var ge=500;function ps(e,t=2){if(!Jn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=_l(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let u=us(s,c.name);if(c.isDirectory()){o(u,i+1);continue}if(c.isFile()){try{n.push({name:yl(e,u),size:cs(u).size})}catch{continue}if(n.length>=ge){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Zn(e){return Jn(e)?{present:!0,size:cs(e).size}:{present:!1,size:0}}function Fe(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function gs(e=process.env){return Fe(w("CURSOR_SANDBOX",e))}var Ol=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function bl(e){return Ol.some(t=>!!w(t,e))}function xl(e){if(w("KUBERNETES_SERVICE_HOST",e)||Fe(w("REMOTE_CONTAINERS",e))||Fe(w("DEVCONTAINER",e)))return!0;try{if(kl("/.dockerenv")||Il("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function _s(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!w(t,e))}function Pl(e,t=process.platform){return _s(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!w(n,e)):!1}function Tl(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function wl(e){return e==="linux"}function w(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return k(e)}function Nl(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Ml(w("CURSOR_VERSION",n))}function Ml(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function qn(e){if(Tl(e.sessionId))return!0;let t=e.hostname??ms(),n=e.osUser??Ss(e.env);return Nl(t,n,e.env)}function vl(e){return Fe(w("CURSOR_AGENT",e.env))?!0:qn(e)}function Ll(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(w("TERM",e)??w("TERM_PROGRAM",e))||(w("SSH_TTY",e)??w("SSH_CONNECTION",e))||(w("__CFBundleIdentifier",e)??w("XPC_SERVICE_NAME",e))||_s(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!w(t,e))||w("SESSIONNAME",e))}function st(e={}){let t=e.env;if(w("GITHUB_ACTIONS",t))return"github_actions";if(Fe(w("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Pl(t,n)&&vl(e)&&(Fe(w("CURSOR_AGENT",t))||wl(n)))return"cursor_cloud";if(w("CODESPACES",t)||w("CODESPACE_NAME",t))return"codespaces";if(w("GITLAB_CI",t))return"gitlab_ci";if(bl(t))return"managed";let r=w("CI",t);return r&&r!=="false"&&r!=="0"?"managed":xl(t)?"container":Ll(t)?"interactive":"unknown"}async function hs(){return await v("systemd-detect-virt",[],1e3)}function Ss(e=process.env,t=Al){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 Es(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await v("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),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 v("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await v("uname",["-r"],1e3))}else t=await v("ver",[],1e3);let n=Ss(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await v("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function $t(){return ms()}var Hl="installation.json",Fl="cloud-bootstrap.lock",jl=6e4;function Ps(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function ae(e=er()){return tr(e,".ev-ai","agent-hook")}function $l(e=er()){return tr(ae(e),Hl)}function Ts(e){return tr(Kt(e),Fl)}function ws(){return Ul(8).toString("hex")}function je(e){return Is("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 Ns(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Kl(e=process.env){let t=I(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Ns(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 Ms(e,t){return e&&Ns(e)?e:(e&&p(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Kl(t))}function Bl(e){return/^[0-9a-f]{16}$/.test(e)}function Gl(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 je(`github_actions|${t}|${n}`)}if(I(e.CODESPACES)||I(e.CODESPACE_NAME)){let t=I(e.CODESPACE_NAME);if(t)return je(`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 je(`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 je(`gitlab|${t}|${n}`)}return null}var zl="cursoragent@cursor.com";function Vl(e){let t=I(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===zl?null:t}function Wl(e,t){return I(e.CURSOR_PROJECT_DIR)??I(e.CLAUDE_PROJECT_DIR)??t}function Jl(e){return nt(e).replace(/\.git$/i,"").toLowerCase()}async function Yl(e){let t=await v("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Jl(t):e}async function Xl(e){let t=I(await v("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!G(null,t))return t;let n=I(await v("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!G(null,n)?n:null}function Zl(e,t){let n=Wl(e,t);return n?je(`cursor_cloud|${n}|${Vl(e)??""}`):null}async function ql(e,t){let n=I(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Yl(n),o=await Xl(n);return je(`claude_remote|${r}|${o??""}`)}function ys(e,t){let n=Ms(e,t);if(n)return n;let r=Gl(t);return r||ws()}async function Ql(e){let n=await v("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Dl(e);return Is("sha256").update(n).digest("hex").slice(0,16)}function ed(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 td(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=ed(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function Pe(e){if(As(e))try{return td(Os(e,"utf8"))}catch{}}function nr(e){return Pe(e)}function vs(e,t,n){let r=Pe(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Q(e,`${JSON.stringify(o,null,2)}
15
+ `)}catch(s){let i=s instanceof Error?s.message:String(s);p(`WARN: operator identity cache write failed open: ${i}`)}}function Ls(e,t=Date.now()){if(!e)return!0;if(Pe(e)?.operator_identity_hash)return!1;let n=Ts(e);try{if(As(n)){let r=Number.NaN;try{r=Number(Os(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<jl)return!1;try{bs(n)}catch{}}}catch{}try{return Qn(Kt(n),{recursive:!0}),xs(n,`${t}
16
+ `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(Fs(r))return!1;let o=r instanceof Error?r.message:String(r);return p(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function Us(e){if(e)try{bs(Ts(e))}catch{}}function Ds(e,t){let r=Pe(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Hs(e,t,n){if(!n)return;let r=Pe(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{Q(e,`${JSON.stringify(o,null,2)}
17
+ `)}catch(s){let i=s instanceof Error?s.message:String(s);p(`WARN: platform_agent_id cache write failed open: ${i}`)}}function Fs(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function nd(e,t){Qn(Kt(e),{recursive:!0}),xs(e,`${JSON.stringify(t,null,2)}
18
+ `,{encoding:"utf8",flag:"wx"})}function Rs(e,t){try{return nd(e,t),t}catch(n){if(!Fs(n))throw n;return Pe(e)}}function Cs(e,t){Qn(Kt(e),{recursive:!0}),Q(e,`${JSON.stringify(t,null,2)}
19
+ `)}function ks(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Bt(e,t={}){let n=t.home??er(),r=t.env??process.env,o=await Ql(e),s=$l(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=st(i),c=Ms(t.overrideId,r),u=a==="cursor_cloud"&&qn(i)?Zl(r,e):a==="claude_remote"?await ql(r,e):null,l=Pe(s);if(l){let h=l;if(c&&c===l.installation_id&&l.pinned!==!0&&(h={...l,pinned:!0},Cs(s,h)),!!u&&u!==h.installation_id&&!c&&h.pinned!==!0&&Bl(h.installation_id)&&u){let E={installation_id:u,...h.platform_agent_ids?{platform_agent_ids:h.platform_agent_ids}:{}};return Cs(s,E),{installationId:u,storePath:s,repoKey:o}}return{installationId:h.installation_id,storePath:s,repoKey:o}}let f=c??u??ys(void 0,r),m=Rs(s,ks(f,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let d=c??u??ys(void 0,r),_=Rs(s,ks(d===f?ws():d,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as or,readFileSync as rd}from"node:fs";import{dirname as od,isAbsolute as sd,join as id,relative as ad}from"node:path";function js(e){for(let t of wt){let n=id(e,t);if(or(n))return n}}async function cd(e=process.cwd(),t){let n=t??await se(e);return js(n)??js(e)}async function ud(e,t){let n=t??await se(od(e)),r=ad(n,e);if(r.startsWith("..")||sd(r))return!1;let o=await Y("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 rr(e){let t=rd(e,"utf8");return z(t,{})}function ld(){return{schema_version:me,mcp_servers:[]}}function dd(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 $s(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Xn(e),o=k("EV_AI_HOOK_MANIFEST"),s=o&&or(o)?o:void 0,i=s?void 0:or(Hn())?Hn():void 0,a=s?void 0:await cd(e,n),c=i?rr(i):void 0,u=a?rr(a):void 0,l,f,m,d=new Set;if(s){l=rr(s),f=s,m=s;for(let y of Object.keys(l))d.add(y)}else if(c&&u){l=zo(u,c),f=i,m=a;for(let y of Object.keys(u))y in c||d.add(y)}else if(c)l=c,f=i;else if(u){l=u,f=a,m=a;for(let y of Object.keys(u))d.add(y)}else l=ld();delete l.installation_id;let _=m?await ud(m,n):!1;dd(l,m,_,d);let{installationId:h,storePath:S,repoKey:E}=await Bt(n,{sessionId:t.sessionId});return{manifestPath:f??S,manifest:l,installationId:h,installationStorePath:S,repoKey:E,collectorUrl:jn(l),platformAgentId:l.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function Ks(e){return{schema_version:me,...e?{collector_url:e}:{},mcp_servers:[]}}var fd=["darwin-arm64","darwin-x64","linux-arm64","linux-x64","windows-x64","windows-arm64"];function pd(e){return e==="windows-x64"||e==="windows-arm64"}function sr(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 Bs(e=process.platform,t=process.arch){let n=sr(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${fd.join(", ")}.`);return n}function md(e){return pd(e)?`${q}.exe`:q}function ir(e){return`compile-out/bin/${e}/${md(e)}`}function Rd(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=He(n);if(r)throw new Error(`collector URL rejected: ${r}`);return et(n)}function Cd(e){let t=e.collectorUrl?.trim();if(!t)return;let n=He(t);if(n)throw new Error(`collector URL rejected: ${n}`);return et(t)}function kd(e){return Rd(e,"install")}function Ys(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 Xs(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 Zs(e=process.execPath){return qs(e)?"binary":"npx"}function Id(){return x(ce(),".ev-ai","agent-hook")}function Ad(e=ce()){return x(e,".ev-ai","agent-hook",$n)}function Od(){let e=ur(yd(import.meta.url)),t=x(e,"hook.mjs");return _e(t)?t:x(e,"..","dist","hook.mjs")}function qs(e=process.execPath){return Ut(e)}function Qs(e,t){let n=Js(Gs(e),Gs(t));return!n.startsWith("..")&&!Sd(n)}function Vt(e){return e.split(Ed).join("/")}function bd(e){return`node "$(git rev-parse --show-toplevel)/${Vt(e)}"`}function xd(e){return`"$(git rev-parse --show-toplevel)/${Vt(e)}"`}function Pd(e){return x(e,Kn)}function ei(e,t){let n=Pd(e);cr(ur(n),{recursive:!0}),Ws(t,n,{force:!0});try{Vs(n,493)}catch{}return n}function Td(e){let t=x(Id(),"current");try{zt(t,{recursive:!0,force:!0})}catch{}_d(e,t,process.platform==="win32"?"junction":"dir")}function ti(e,t=oe,n=ce()){let r=x(n,".ev-ai","agent-hook",t),o=x(r,q);cr(r,{recursive:!0}),Ws(e,o,{force:!0});try{Vs(o,493)}catch{}return Td(r),x(n,".ev-ai","agent-hook",$n)}function ni(e){let t=sr();if(!t)return;let n=[x(e,ir(t)),x(e,"packages","agent-hook",ir(t))];for(let r of n)if(_e(r)&&Qs(e,r))return r}function wd(e=ce()){let t=Ad(e);return _e(t)?t:void 0}function Nd(e,t=ce()){let n=wd(t);return n||(qs()?ti(process.execPath,oe,t):ni(e))}function Md(e,t=ce()){let n=ni(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
20
+ To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=ti(n,oe,t),o=ei(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function zs(e){let t=[x(e,"packages","agent-hook","dist","hook.mjs"),x(e,Jo)],n=Od();_e(n)&&Qs(e,n)&&t.unshift(n);for(let r of t){if(!_e(r))continue;let o=Vt(Js(e,r));return{command:bd(o),hookPath:o,strategy:"dev_mjs"}}}function vd(e){return e==="SessionStart"||e==="sessionStart"}function Ld(e){return e.replace(/\s+--prefer-offline\b/g,"")}function Gt(e,t){return vd(e)?Ld(t):t}function Ud(e=Dt){return`npx -y --prefer-offline ${e}`}function Dd(e,t=ce(),n=Zs()){if(n==="npx")return{command:Ud(),hookPath:Dt,strategy:"npx"};if(n==="local"){let s=zs(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=Nd(e,t);if(r){ei(e,r);let s=Vt(Kn);return{command:xd(s),hookPath:s,strategy:"project_binary"}}let o=zs(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
21
+ curl -fsSL ${Yo}/install.sh | sh
22
22
  Or use npx delivery:
23
- npx ${wt} install`)}function Ms(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(ee)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function ir(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function Se(e,t){or(sr(e),{recursive:!0}),vl(e,`${JSON.stringify(t,null,2)}
24
- `,"utf8")}function le(e){if(he(e))try{return JSON.parse(Tl(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function Ql(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 ed(e){return(e.schema_version??ge)===ge&&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 Ls(e,t){let n=P(e,xt),r=le(n),o=Ql(r,t);return t.collectorUrl!==void 0||he(n)||!ed(o)?(Se(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function rr(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 td(e){if(rr(process.env))return!0;let t=ue();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=le(r);return o?rr(o.env):!1}catch{return!1}})}function nd(e){try{let t=le(P(e,".claude","settings.json"));return t?rr(t.env):!1}catch{return!1}}function Us(e){return Array.isArray(e)?e:[]}function Bt(e){let t=[],n=r=>!!r&&typeof r=="object"&&Ms(r.command);for(let r of Us(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 Ds(e,t){return[...Bt(e),...t]}function ar(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!Ms(t.command)):[]}function rd(e,t){return[...ar(e),{command:t}]}function od(e){return typeof e=="string"?[e]:e}function sd(e){let t=(n="")=>({hooks:od(e).map(r=>({type:"command",command:Ft(n,r)}))});return{SessionStart:[t("SessionStart")],UserPromptExpansion:[t()],UserPromptSubmit:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function id(e){let t=typeof e=="string"?{command:e}:e,n=(r="")=>({hooks:[{type:"command",command:Ft(r,t.command),...t.commandWindows===void 0?{}:{commandWindows:Ft(r,t.commandWindows)},statusMessage:Ho}]});return{SessionStart:[n("SessionStart")],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var ad=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","beforeReadFile","beforeMCPExecution","subagentStart","subagentStop","stop"],cd=["afterShellExecution","afterFileEdit"];function ud(e,t=cd){let n={...e};for(let r of t){if(!(r in n))continue;let o=ar(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function ld(e,t,n={}){let r=P(e,".claude/settings.json"),o=ir(t,"claude"),s=le(r)??{};if(td(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let p of Object.keys(u))u[p]=Bt(u[p]),Us(u[p]).length===0&&delete u[p];Object.keys(u).length===0?delete s.hooks:s.hooks=u,Se(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=sd(o),l={...a};for(let[u,p]of Object.entries(c))l[u]=Ds(a[u],p);return s.hooks=l,Se(r,s),!0}function dd(e,t){let n=P(e,".cursor/hooks.json"),r=ir(t,"cursor"),o=le(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=ud({...s});for(let a of ad)i[a]=rd(i[a],Ft(a,r));Se(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function pd(e,t){let n=P(e,".codex/hooks.json"),r=ir(t,"codex"),o=le(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=id(r),a={...s};for(let[c,l]of Object.entries(i))a[c]=Ds(s[c],l);Se(n,{...o,hooks:a})}function fd(e){let t=P(e,".claude/settings.json"),n=le(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=Bt(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,Se(t,n),f(`Removed ev-ai hooks from ${t}`))}function md(e){let t=P(e,".cursor/hooks.json"),n=le(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=ar(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){jt(t,{force:!0}),f(`Removed ${t}`);return}Se(t,{...n,hooks:r}),f(`Removed ev-ai hooks from ${t}`)}}function gd(e){let t=P(e,".codex/hooks.json"),n=le(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=Bt(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){jt(t,{force:!0}),f(`Removed ${t}`);return}Se(t,{...n,hooks:r}),f(`Removed ev-ai hooks from ${t}`)}}function cr(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)&&ys(e,t)}async function Hs(e={}){let t=Hl(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??Ps();cr(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await ie(i),{command:c,hookPath:l,strategy:u}=ql(a,ue(),s),{installationId:p,storePath:m}=await Ht(a,{overrideId:e.installationId}),{manifestPath:d,wrote:_}=Ls(a,e),S=[];return n?f("Skipped Claude hook \u2014 --no-claude"):ld(a,c,{force:e.force})?(S.push("Claude"),e.force&&nd(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"):(dd(a,c),S.push("Cursor")),o?f("Skipped Codex hook \u2014 --no-codex"):(pd(a,c),S.push("Codex")),f(`Installed hook (${u}) at ${l}`),f(`Installation identity ${p} at ${m}`),_&&d?f(`Shared manifest written to ${d}`):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)."),_&&d&&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:d,installationStorePath:m,strategy:u}}async function Fs(e=process.cwd()){cr(process.platform,process.arch,{requireBinaryArch:!0});let t=await ie(e),{projectPath:n,globalPath:r}=Jl(t);f(`Refreshed ${r}`),f(`Refreshed ${n}`),f("Hook configs and shared manifest left unchanged")}async function js(e={}){let t=Dl(e);e.collectorUrl=t,cr(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await ie(n),{manifestPath:o,wrote:s}=Ls(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 $s(e){for(let t of[()=>fd(e),()=>md(e),()=>gd(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: strip skipped a hook file: ${r}`)}}async function Bs(e=process.cwd()){let t=await ie(e);return $s(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 Ks(e=process.cwd()){let t=await ie(e);$s(t);for(let n of Pt){let r=P(t,n);if(he(r))try{jt(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 qf}from"node:crypto";import{existsSync as Qf,mkdirSync as em,readdirSync as tm,readFileSync as Yi,unlinkSync as Xi,writeFileSync as nm}from"node:fs";import{homedir as Zi}from"node:os";import{join as xr}from"node:path";import{existsSync as Od}from"node:fs";import{existsSync as _d}from"node:fs";import{homedir as zs}from"node:os";import{join as hd}from"node:path";function Vs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Sd={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 Ed(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 Ws(e){return Object.fromEntries(Object.entries(Sd).map(([t,n])=>[t,Ed(n,n[e])]))}var He=Ws("homeOnly"),ye=Ws("projectOnly");function yd(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function Rd(e,t){return yd(e).some(n=>_d(hd(t,n)))}function Js(e,t){for(let n of e)if(Rd(n,t))return!0;return!1}function Ee(e){return[...new Set(e)]}function Re(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:Ee(t),subagents:Ee(n),commands:Ee(r),rules:Ee(o),memory:Ee(s),settings:Ee(i),mcp:Ee(a)}}function Cd(e,t=zs(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...Lt(o.managed,n,t));return Ee(r)}var Ce=Re(Object.values(He));function Ys(e=zs(),t=process.platform){return Cd(Object.values(He),e,t)}import{existsSync as Id}from"node:fs";import{resolve as ur}from"node:path";function V(e){return ur(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 Kt(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 Ad=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function ot(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Ad.test(t)?null:t}function Fe(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=V(o);n.has(s)||(n.add(s),r.push(s))}return r}function kd(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function ne(e,t,n,r=Id){for(let o of e)for(let s of t){let i=V(ur(o,s)),a=ur(o,s,n).replaceAll("\\","/");if(kd(i,a)&&r(a))return a}return null}var Zs=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,qs=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,xd=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,Xs=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"]),Pd=/^[a-z][a-z0-9-]{1,63}$/,bd=[".cursor/skills",".claude/skills",".agents/skills"],Td=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],Nd=be(bd,Re(Object.values(ye)).skills),vd=be(Td,Re(Object.values(He)).skills),wd=new Set(["read","read_file","view"]),Md=new Set(["bash","shell","zsh"]);function lr(e){let t=e.replace(/\\/g,"/");return Zs.exec(t)?.[1]??null}function Ld(e){let t=e.replace(/\\/g,"/"),r=qs.exec(t)?.[1];return r?r.toLowerCase():null}function Ud(e){return lr(e)??Ld(e)}function Dd(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Gt(e){return typeof e=="string"?Gt($(e,null)):!e||typeof e!="object"?null:Dd(e)}function Qs(e){if(typeof e=="string")return Qs($(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function dr(e){let t=Qs(e.tool_input);if(t)return t;let n=xe(e.command);return n.length>0?n:null}function Hd(e){let t=e.replace(/\\/g,"/"),n=Zs.exec(t);if(n?.[1])return n[1];let o=qs.exec(t)?.[1];return o?o.toLowerCase():null}function Fd(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function pr(e){let t=Gt(e.tool_input)??xe(e.file_path);return t.length>0?t:null}function st(e,t,n){let r=Fd(e).toLowerCase();if(wd.has(r)){let o=pr(e);return o?t(o):null}if(Md.has(r)){let o=dr(e);return o?n(o):null}return null}function ei(e){return st(e,Ud,Hd)}function jd(e){let t=new Set,n=[];for(let r of e.matchAll(xd)){let o=r[1]?.toLowerCase();!o||t.has(o)||$d(o)||(t.add(o),n.push(o))}return n}function $d(e){let t=e.split("/")[0];return Xs.has(e)||t!==void 0&&Xs.has(t)}function ti(e){let t=e.skillId.toLowerCase();if(!Pd.test(t))return null;let n=e.exists??Od,r=`${t}/SKILL.md`,o=ne(Fe(e.launchCwd,e.gitRoot),Nd,r,n);return o!==null?o:e.home?ne([V(e.home)],vd,r,n):null}function Bd(e){return xe(e.prompt)}function ni(e){let t=h(e,"command_name");if(t){let r=h(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Bd(e);return n?jd(n):[]}var Er=Xe(Be(),1);import{existsSync as If}from"node:fs";var Ne={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function at(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Cf(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 at(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return at(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?at(o[1]):at(t)}async function ct(e=process.cwd()){let t=await X("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([X("git",["remote","get-url","origin"],2e3,{cwd:e}),X("git",["branch","--show-current"],2e3,{cwd:e}),X("git",["rev-parse","HEAD"],2e3,{cwd:e}),X("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 ki(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ne[n];if(!a)return"";let c=is(n,e.scope_path,i);if(s){let _=ms(s,c);if(_)return _}let l=o??await ct(r),u=l?.remote?Cf(l.remote):"";if(u||(u=at(process.env.GITHUB_REPOSITORY??"")),!u)return"";let p=e.scope_path??"",m=p?`${p}/`:"",d=`${u}:${m}${a}`;return s&&gs(s,c,d),d}var Af=[".cursor/rules",".claude/rules",".codex/rules"],kf=Re(Object.values(ye)).rules;function Of(e){return be(Kt(e?Ne[e]:void 0,Af),kf)}var xf=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function Oi(e){let t=ot(e.relativePath);if(!t)return null;let n=e.exists??If,r=Fe(e.launchCwd,e.gitRoot),o=Of(e.runnerPlatform),s=ne(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=ne(r,["."],t,n);if(i!==null)return i}return e.home?ne([V(e.home)],o,t,n):null}function Pf(e){let t=e.replace(/\\/g,"/"),r=xf.exec(t)?.[1];return r?(0,Er.nativeKeyForRulePath)(r):null}function xi(e){return st(e,Er.nativeKeyForRulePath,Pf)}function Pi(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function bi(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=ot(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var yr=Xe(Be(),1);import{existsSync as bf}from"node:fs";var Tf=[".cursor/commands",".claude/commands",".codex/prompts"],Nf=Re(Object.values(ye)).commands;function vf(e){return be(Kt(e?Ne[e]:void 0,Tf),Nf)}var wf=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function Ti(e){let t=ot(e.commandId);if(!t)return null;let n=e.exists??bf,r=`${t}.md`,o=vf(e.runnerPlatform),s=ne(Fe(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?ne([V(e.home)],o,r,n):null}function Mf(e){let t=e.replace(/\\/g,"/"),r=wf.exec(t)?.[1];return r?(0,yr.nativeKeyForCommandPath)(r):null}function Ni(e){return st(e,yr.nativeKeyForCommandPath,Mf)}import{existsSync as wi}from"node:fs";import{homedir as Mi}from"node:os";import{join as ut,resolve as Rr,sep as vi}from"node:path";function Cr(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Ir(e,t){let n=t.toLowerCase();return Cr(e).some(r=>r.toLowerCase()===n)}function Xt(e,t,n){if(!wi(e))return;let r=F(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function Lf(e,t,n){if(!wi(e))return;let r=F(e,{}),o=Rr(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Rr(a);(o===c||o.startsWith(c.endsWith(vi)?c:c+vi))&&(s===null||c.length>Rr(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"?(Xt(ut(r,".claude.json"),{source:"claude_json_user"},o),Lf(ut(r,".claude.json"),t,o)):n==="cursor"&&Xt(ut(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Xt(ut(t,".mcp.json"),{source:"mcp_json"},o),Xt(ut(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function Ar(e,t=process.cwd(),n="claude",r=Mi()){return[...Li(e,t,n,r).values()].map(o=>o.declared)}function Ui(e,t,n=process.cwd(),r="claude",o=Mi()){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(Ir(a,e))return c.config??null;return null}function kr(e){let t=bo(e);if(t.problem){f(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function Di(e,t){if(h(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Uf(){return!!(I("CURSOR_VERSION")??I("CURSOR_PROJECT_DIR"))}function Or(e,t,n){return e!=="claude"&&e!=="codex"?!1:Di(t,n)?!0:Uf()}function lt(e,t,n,r){if(Di(e,t))return"cursor";if(bt(r))return r;let o=h(e,"conversation_id"),s=h(e,"turn_id"),i=h(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"),bt(n)&&(c=n),c}function Zt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Df(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 Hi(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function Fi(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function ji(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function $i(e,t,n){let r=h(e,"session_id")||h(e,"conversation_id"),o=h(e,"prompt.id")||h(e,"prompt_id")||h(e,"generation_id")||h(e,"turn_id"),s=h(e,"hook_event_name")||h(e,"event"),i=h(e,"source"),a=lt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Hf=["session_start","session_end","tool_invoked","skill_invoked"];function Ff(e){return Hf.includes(e)}function Bi(e,t){return e&&Ff(e)?e:Df(t.toLowerCase())}var jf={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Ki(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Gi(e,t=""){let n=h(e,"tool_name")||h(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Ki(n)&&(n=`MCP:${n}`):n=jf[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?xe(o.skill)||xe(o.skill_name):"")||h(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=ei(a);let c=xi(a),l=Ni(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var $f=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function zi(e){for(let t of["subagent_type","agent_type"]){let n=h(e,t);if(n&&$f.test(n))return n}return null}function Vi(e){let t=ae(e,"duration_ms");if(typeof t=="number")return t;let n=ae(e,"duration");return typeof n=="number"?n:null}var Bf="error",Kf="interrupted",Gf="permission_denied",zf=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function dt(e){return zf.test(e)?e:null}function Vf(e){for(let t of["failure_type","error_type"]){let n=dt(h(e,t));if(n)return n}return null}function Wi(e,t){return ae(e,"is_interrupt")===!0?Kf:t.toLowerCase()==="permissiondenied"?Gf:Vf(e)??Bf}function Wf(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 Jf(e,t){let n=null;for(let r of t)!r||!Ir(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function Yf(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of Cr(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:Jf(o[1],t)??o[1],mcpTool:o[2]}}function Xf(e,t){if(/^mcp__/i.test(e))return Yf(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:Wf(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function Zf(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function Ji(e,t=[],n=""){let r=e?Xf(e,t):{mcpServer:null,mcpTool:null},o=dt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Ki(e)&&(s=e),s&&(s=Zf(s,o)),{mcpServer:o,mcpTool:s}}var qi=3e4,rm="claims",om=!0,sm=100,im=new Set(["sessionstart","sessionend","stopfailure"]),am=["tool_name","tool","command","file_path","url"];function cm(e=Zi()){return xr(ce(e),rm)}function Qi(e){let t=e.split(`
25
- `,1)[0]??"";return Number(t.trim())}function ea(e){return qf("sha256").update(e).digest("hex").slice(0,32)}function um(e){let t=[];for(let n of am){let r=h(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":ea(t.join("\0"))}function lm(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=im.has(n);if(!a&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return ea(`${l}|${t}|${n}|${r}|${o}|${i}|${s}`)}function dm(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function pm(e,t){return xr(e,t)}function fm(e,t=Date.now()){let n;try{n=tm(e)}catch{return}let r=0;for(let o of n){if(r>=sm)break;r+=1;let s=xr(e,o),i=Number.NaN;try{i=Qi(Yi(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<qi))try{Xi(s)}catch{}}}function mm(e,t,n=Date.now()){let r=pm(t,e);try{if(Qf(r)){let o=Number.NaN;try{o=Qi(Yi(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<qi)return!1;try{Xi(r)}catch{}}}catch{}try{em(t,{recursive:!0}),nm(r,`${n}
26
- `,{encoding:"utf8",flag:"wx"})}catch(o){if(dm(o))return!1;let s=o instanceof Error?o.message:String(o);return f(`WARN: event claim failed open: ${s}`),!0}return fm(t,n),!0}function gm(e,t,n){let r=h(e,"session_id")||h(e,"conversation_id"),o=h(e,"prompt.id")||h(e,"prompt_id")||h(e,"generation_id")||h(e,"turn_id"),s=h(e,"tool_use_id"),i=h(e,"subagent_id")||h(e,"agent_id"),a=lt(e,t,void 0,n),c=um(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function ta(e,t,n,r=Zi(),o=Date.now()){if(!om)return!0;let s=lm(gm(e,t,n));if(!s)return!0;let i=mm(s,cm(r),o);return!i&&I("EV_AI_HOOK_DEBUG")&&f(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{closeSync as _m,writeSync as hm}from"node:fs";var na="EV_AI_LAUNCHER_VERSION";var ra="EV_AI_HOOK_SOURCE",oa="EV_AI_HOOK_FALLBACK_REASON",sa="EV_AI_LAUNCHER_SCOPE",Pr="EV_AI_LAUNCHER_READY_FD";var ia=Buffer.from([1]);var Jy=1024*1024,Yy=4*1024*1024,Xy=64*1024,Zy=64*1024,qy=64*1024;var br=4096,Qy=4*1024*1024;function aa(e=process.env){let t=e[Pr];if(delete e[Pr],t===void 0)return;let n=Number.parseInt(t,10);if(!(!Number.isInteger(n)||n<3)){try{hm(n,ia)}catch{}try{_m(n)}catch{}}}function Tr(e=process.env){let t=e[na];if(t)return{launcherVersion:t,hookSource:e[ra]??"",fallbackReason:e[oa],launcherScope:e[sa]}}function ca(e,t){return(e?To(e):void 0)===t}import{realpathSync as tS}from"node:fs";import{homedir as nS}from"node:os";var O=Xe(Be(),1);import{existsSync as Sm,readFileSync as Em}from"node:fs";import{homedir as ua}from"node:os";import{join as ym}from"node:path";var Rm="cloud-cache.json",Cm=1440*60*1e3,Im=900*1e3;function Am(e=ua()){return ym(ce(e),Rm)}function km(e){if(!Sm(e))return;let t=$(Em(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 Om(e,t){try{te(e,`${JSON.stringify(t)}
27
- `)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: cloud cache write failed open: ${r}`)}}function xm(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Im:Cm;return n-e.probed_at<r}async function Pm(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 bm(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 Tm(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 Nm(e){let t=await Promise.allSettled([Pm(e),bm(e),Tm(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Nr(e,t){if(e==="interactive")return null;let n=t?.home??ua(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Am(n),i=km(s);if(xm(i,e,o))return i.result;let a=await Nm(r);return Om(s,{context:e,probed_at:o,result:a}),a}var vm=["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"],wm=["CURSOR_PROJECT_DIR"],Mm=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Lm(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Mm.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function vr(e=process.env){let t=vm.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Lm(e[r]??"")}:{name:r,present:!1}),n=wm.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as dg}from"node:os";import{homedir as la}from"node:os";import{join as Um}from"node:path";function Dm(e=la()){return Um(e,".claude.json")}function qt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function da(e=la()){let n=F(Dm(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=qt(n.emailAddress),o=qt(n.fullName)??qt(n.displayName),s=qt(n.accountUuid),i=r??s;return!i||z(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as ma}from"node:os";import{join as pa}from"node:path";var Hm="https://api.openai.com/auth";function Ke(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ga(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Fm(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 ga(r)}catch{return null}}function fa(e,t,n){return Ke(e[n])??Ke(t?.[n])}function jm(e=process.env,t=ma()){let n=Ke(e.CODEX_HOME)??pa(t,".codex");return pa(n,"auth.json")}function _a(e=process.env,t=ma()){let n=F(jm(e,t),{}),r=Ke(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Ke(n.OPENAI_API_KEY))return null;let o=Ke(n.tokens?.id_token);if(!o)return null;let s=Fm(o);if(!s)return null;let i=ga(s[Hm]),a=fa(s,i,"name"),c=fa(s,i,"email");return!c||z(a,c)?null:{git_user_name:null,git_user_email:null,platform_login:c,identity_source:"codex_oauth"}}import{homedir as tn}from"node:os";import{join as fe}from"node:path";import{join as $m}from"node:path";var Bm="cursor-ide-identity.json",Km=et;function Sa(e){return $m(ce(e),Bm)}function ha(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ea(e){let t=F(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:ha(t.email),auth_id:ha(t.auth_id)}}function ya(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<Km}function Ra(e,t){try{te(e,`${JSON.stringify(t)}
28
- `)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as Gm}from"node:child_process";import{existsSync as zm}from"node:fs";import{createRequire as Vm}from"node:module";import{pathToFileURL as Wm}from"node:url";var Ia=Vm(import.meta.url),Qt=`
23
+ npx ${Dt} install`)}function ri(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 lr(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function he(e,t){cr(ur(e),{recursive:!0}),hd(e,`${JSON.stringify(t,null,2)}
24
+ `,"utf8")}function ue(e){if(_e(e))try{return JSON.parse(gd(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function Hd(e,t){let n=Ks(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 Fd(e){return(e.schema_version??me)===me&&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 oi(e,t){let n=x(e,Tt),r=ue(n),o=Hd(r,t);return t.collectorUrl!==void 0||_e(n)||!Fd(o)?(he(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function ar(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 jd(e){if(ar(process.env))return!0;let t=ce();return[...Vn(),x(t,".claude","settings.json"),x(t,".claude","remote-settings.json"),x(e,".claude","settings.json"),x(e,".claude","settings.local.json")].some(r=>{try{let o=ue(r);return o?ar(o.env):!1}catch{return!1}})}function $d(e){try{let t=ue(x(e,".claude","settings.json"));return t?ar(t.env):!1}catch{return!1}}function si(e){return Array.isArray(e)?e:[]}function Wt(e){let t=[],n=r=>!!r&&typeof r=="object"&&ri(r.command);for(let r of si(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 ii(e,t){return[...Wt(e),...t]}function dr(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!ri(t.command)):[]}function Kd(e,t){return[...dr(e),{command:t}]}function Bd(e){return typeof e=="string"?[e]:e}function Gd(e){let t=(n="")=>({hooks:Bd(e).map(r=>({type:"command",command:Gt(n,r)}))});return{SessionStart:[t("SessionStart")],UserPromptExpansion:[t()],UserPromptSubmit:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function zd(e){let t=typeof e=="string"?{command:e}:e,n=(r="")=>({hooks:[{type:"command",command:Gt(r,t.command),...t.commandWindows===void 0?{}:{commandWindows:Gt(r,t.commandWindows)},statusMessage:ts}]});return{SessionStart:[n("SessionStart")],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var Vd=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","beforeReadFile","beforeMCPExecution","subagentStart","subagentStop","stop"],Wd=["afterShellExecution","afterFileEdit"];function Jd(e,t=Wd){let n={...e};for(let r of t){if(!(r in n))continue;let o=dr(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function Yd(e,t,n={}){let r=x(e,".claude/settings.json"),o=lr(t,"claude"),s=ue(r)??{};if(jd(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let l={...s.hooks};for(let f of Object.keys(l))l[f]=Wt(l[f]),si(l[f]).length===0&&delete l[f];Object.keys(l).length===0?delete s.hooks:s.hooks=l,he(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=Gd(o),u={...a};for(let[l,f]of Object.entries(c))u[l]=ii(a[l],f);return s.hooks=u,he(r,s),!0}function Xd(e,t){let n=x(e,".cursor/hooks.json"),r=lr(t,"cursor"),o=ue(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=Jd({...s});for(let a of Vd)i[a]=Kd(i[a],Gt(a,r));he(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function Zd(e,t){let n=x(e,".codex/hooks.json"),r=lr(t,"codex"),o=ue(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=zd(r),a={...s};for(let[c,u]of Object.entries(i))a[c]=ii(s[c],u);he(n,{...o,hooks:a})}function qd(e){let t=x(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=Wt(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),p(`Removed ev-ai hooks from ${t}`))}function Qd(e){let t=x(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=dr(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){zt(t,{force:!0}),p(`Removed ${t}`);return}he(t,{...n,hooks:r}),p(`Removed ev-ai hooks from ${t}`)}}function ef(e){let t=x(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=Wt(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){zt(t,{force:!0}),p(`Removed ${t}`);return}he(t,{...n,hooks:r}),p(`Removed ev-ai hooks from ${t}`)}}function fr(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)&&Bs(e,t)}async function ai(e={}){let t=kd(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??Zs();fr(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await se(i),{command:c,hookPath:u,strategy:l}=Dd(a,ce(),s),{installationId:f,storePath:m}=await Bt(a,{overrideId:e.installationId}),{manifestPath:d,wrote:_}=oi(a,e),h=[];return n?p("Skipped Claude hook \u2014 --no-claude"):Yd(a,c,{force:e.force})?(h.push("Claude"),e.force&&$d(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"):(Xd(a,c),h.push("Cursor")),o?p("Skipped Codex hook \u2014 --no-codex"):(Zd(a,c),h.push("Codex")),p(`Installed hook (${l}) at ${u}`),p(`Installation identity ${f} at ${m}`),_&&d?p(`Shared manifest written to ${d}`):p("Using package default collector config (no shared manifest file needed)"),p(h.length>0?`Wired ${h.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)."),_&&d&&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:d,installationStorePath:m,strategy:l}}async function ci(e=process.cwd()){fr(process.platform,process.arch,{requireBinaryArch:!0});let t=await se(e),{projectPath:n,globalPath:r}=Md(t);p(`Refreshed ${r}`),p(`Refreshed ${n}`),p("Hook configs and shared manifest left unchanged")}async function ui(e={}){let t=Cd(e);e.collectorUrl=t,fr(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await se(n),{manifestPath:o,wrote:s}=oi(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 li(e){for(let t of[()=>qd(e),()=>Qd(e),()=>ef(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);p(`WARN: strip skipped a hook file: ${r}`)}}async function di(e=process.cwd()){let t=await se(e);return li(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 fi(e=process.cwd()){let t=await se(e);li(t);for(let n of wt){let r=x(t,n);if(_e(r))try{zt(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{existsSync as Vm,mkdirSync as Wm,readdirSync as Jm,readFileSync as Ym,unlinkSync as Aa,writeFileSync as Xm}from"node:fs";import{homedir as Oa}from"node:os";import{join as Mr}from"node:path";import{open as pi,mkdir as tf,readFile as nf,readdir as rf,rename as of,stat as sf,rmdir as af,unlink as cf,utimes as uf}from"node:fs/promises";var Jt=new WeakMap;function gi(e){if(e&&typeof e=="object"&&"code"in e)return e}function pr(e){return gi(e)?.code==="ENOENT"}function _i(e){return gi(e)?.code==="EEXIST"}async function hi(e,t){try{return await e.readdir(t)}catch(n){if(pr(n))return[];throw n}}function Si(){return{async open(e,t){let n=await pi(e,t),r={path:e};return Jt.set(r,n),r},async write(e,t){let n=mi(e),r=typeof t=="string"?Buffer.from(t,"utf8"):t;await n.write(r)},async fsync(e){await mi(e).sync()},async close(e){let t=Jt.get(e);Jt.delete(e),t&&await t.close()},rename:of,async readdir(e){return rf(e)},readFile:nf,async stat(e){let t=await sf(e);return{mtimeMs:t.mtimeMs,size:t.size,isDirectory:()=>t.isDirectory()}},async mkdir(e,t){await tf(e,t)},unlink:cf,rmdir:af,utimes:uf,async fsyncDir(e){if(process.platform==="win32")return;let t=await pi(e,"r");try{await t.sync()}finally{await t.close()}}}}function mi(e){let t=Jt.get(e);if(!t)throw new Error("closed");return t}import{existsSync as yf}from"node:fs";import{existsSync as lf}from"node:fs";import{homedir as yi}from"node:os";import{join as df}from"node:path";function Ri(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var ff={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/sandbox.json",".cursor/permissions.json"],mcpJson:[".cursor/mcp.json"]},homeOnly:{skillRoots:[".cursor/skills-cursor"],memory:[[".cursor/AGENTS.md"]],settings:[".cursor/cli-config.json"],plugins:"cursor",managed:"cursor"},projectOnly:{skillRoots:[".agents/skills"],settings:[".cursor/cli.json"]}},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 Ei(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function pf(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:Ei(n.mcpJson,t.mcpJson),mcpToml:Ei(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function Ci(e){return Object.fromEntries(Object.entries(ff).map(([t,n])=>[t,pf(n,n[e])]))}var $e=Ci("homeOnly"),Ee=Ci("projectOnly");function mf(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function gf(e,t){return mf(e).some(n=>lf(df(t,n)))}function ki(e,t){for(let n of e)if(gf(n,t))return!0;return!1}function Se(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 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:Se(t),subagents:Se(n),commands:Se(r),rules:Se(o),memory:Se(s),settings:Se(i),mcp:Se(a)}}function _f(e,t=yi(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...Ft(o.managed,n,t));return Se(r)}var Re=ye(Object.values($e));function Ii(e=yi(),t=process.platform){return _f(Object.values($e),e,t)}import{existsSync as hf}from"node:fs";import{resolve as mr}from"node:path";function V(e){return mr(e).replaceAll("\\","/").replace(/\/$/,"")}function Te(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function Yt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var Sf=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function it(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Sf.test(t)?null:t}function Ke(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=V(o);n.has(s)||(n.add(s),r.push(s))}return r}function Ef(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function ee(e,t,n,r=hf){for(let o of e)for(let s of t){let i=V(mr(o,s)),a=mr(o,s,n).replaceAll("\\","/");if(Ef(i,a)&&r(a))return a}return null}var Oi=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,bi=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Rf=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,Ai=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"]),Cf=/^[a-z][a-z0-9-]{1,63}$/,kf=[".cursor/skills",".claude/skills",".agents/skills"],If=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],Af=Te(kf,ye(Object.values(Ee)).skills),Of=Te(If,ye(Object.values($e)).skills),bf=new Set(["read","read_file","view"]),xf=new Set(["bash","shell","zsh"]);function gr(e){let t=e.replace(/\\/g,"/");return Oi.exec(t)?.[1]??null}function Pf(e){let t=e.replace(/\\/g,"/"),r=bi.exec(t)?.[1];return r?r.toLowerCase():null}function Tf(e){return gr(e)??Pf(e)}function wf(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 Xt(e){return typeof e=="string"?Xt(z(e,null)):!e||typeof e!="object"?null:wf(e)}function xi(e){if(typeof e=="string")return xi(z(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function _r(e){let t=xi(e.tool_input);if(t)return t;let n=xe(e.command);return n.length>0?n:null}function Nf(e){let t=e.replace(/\\/g,"/"),n=Oi.exec(t);if(n?.[1])return n[1];let o=bi.exec(t)?.[1];return o?o.toLowerCase():null}function Mf(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function hr(e){let t=Xt(e.tool_input)??xe(e.file_path);return t.length>0?t:null}function at(e,t,n){let r=Mf(e).toLowerCase();if(bf.has(r)){let o=hr(e);return o?t(o):null}if(xf.has(r)){let o=_r(e);return o?n(o):null}return null}function Pi(e){return at(e,Tf,Nf)}function vf(e){let t=new Set,n=[];for(let r of e.matchAll(Rf)){let o=r[1]?.toLowerCase();!o||t.has(o)||Lf(o)||(t.add(o),n.push(o))}return n}function Lf(e){let t=e.split("/")[0];return Ai.has(e)||t!==void 0&&Ai.has(t)}function Ti(e){let t=e.skillId.toLowerCase();if(!Cf.test(t))return null;let n=e.exists??yf,r=`${t}/SKILL.md`,o=ee(Ke(e.launchCwd,e.gitRoot),Af,r,n);return o!==null?o:e.home?ee([V(e.home)],Of,r,n):null}function Uf(e){return xe(e.prompt)}function wi(e){let t=R(e,"command_name");if(t){let r=R(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Uf(e);return n?vf(n):[]}var Ir=Qe(ze(),1);import{existsSync as _m}from"node:fs";var Ne={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function ut(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function gm(e){if(!e)return"";let t=nt(e).replace(/\.git$/i,""),n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return ut(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return ut(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?ut(o[1]):ut(t)}async function nn(e=process.cwd()){let t=await Y("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([Y("git",["remote","get-url","origin"],2e3,{cwd:e}),Y("git",["branch","--show-current"],2e3,{cwd:e}),Y("git",["rev-parse","HEAD"],2e3,{cwd:e}),Y("git",["status","--porcelain"],2e3,{cwd:e})]);return{remote:n.ok?nt(n.stdout):null,branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function ea(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ne[n];if(!a)return"";let c=Ps(n,e.scope_path,i);if(s){let _=Ds(s,c);if(_)return _}let u=o??await nn(r),l=u?.remote?gm(u.remote):"";if(l||(l=ut(process.env.GITHUB_REPOSITORY??"")),!l)return"";let f=e.scope_path??"",m=f?`${f}/`:"",d=`${l}:${m}${a}`;return s&&Hs(s,c,d),d}var hm=[".cursor/rules",".claude/rules",".codex/rules"],Sm=ye(Object.values(Ee)).rules;function Em(e){return Te(Yt(e?Ne[e]:void 0,hm),Sm)}var ym=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function ta(e){let t=it(e.relativePath);if(!t)return null;let n=e.exists??_m,r=Ke(e.launchCwd,e.gitRoot),o=Em(e.runnerPlatform),s=ee(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=ee(r,["."],t,n);if(i!==null)return i}return e.home?ee([V(e.home)],o,t,n):null}function Rm(e){let t=e.replace(/\\/g,"/"),r=ym.exec(t)?.[1];return r?(0,Ir.nativeKeyForRulePath)(r):null}function na(e){return at(e,Ir.nativeKeyForRulePath,Rm)}function ra(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function oa(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=it(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var Ar=Qe(ze(),1);import{existsSync as Cm}from"node:fs";var km=[".cursor/commands",".claude/commands",".codex/prompts"],Im=ye(Object.values(Ee)).commands;function Am(e){return Te(Yt(e?Ne[e]:void 0,km),Im)}var Om=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function sa(e){let t=it(e.commandId);if(!t)return null;let n=e.exists??Cm,r=`${t}.md`,o=Am(e.runnerPlatform),s=ee(Ke(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?ee([V(e.home)],o,r,n):null}function bm(e){let t=e.replace(/\\/g,"/"),r=Om.exec(t)?.[1];return r?(0,Ar.nativeKeyForCommandPath)(r):null}function ia(e){return at(e,Ar.nativeKeyForCommandPath,bm)}import{existsSync as ca}from"node:fs";import{homedir as ua}from"node:os";import{join as lt,resolve as Or,sep as aa}from"node:path";function br(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function xr(e,t){let n=t.toLowerCase();return br(e).some(r=>r.toLowerCase()===n)}function rn(e,t,n){if(!ca(e))return;let r=D(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function xm(e,t,n){if(!ca(e))return;let r=D(e,{}),o=Or(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Or(a);(o===c||o.startsWith(c.endsWith(aa)?c:c+aa))&&(s===null||c.length>Or(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 la(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"?(rn(lt(r,".claude.json"),{source:"claude_json_user"},o),xm(lt(r,".claude.json"),t,o)):n==="cursor"&&rn(lt(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),rn(lt(t,".mcp.json"),{source:"mcp_json"},o),rn(lt(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function Pr(e,t=process.cwd(),n="claude",r=ua()){return[...la(e,t,n,r).values()].map(o=>o.declared)}function da(e,t,n=process.cwd(),r="claude",o=ua()){let s=la(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(xr(a,e))return c.config??null;return null}function Tr(e){let t=Vo(e);if(t.problem){p(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function fa(e,t){if(R(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Pm(){return!!(k("CURSOR_VERSION")??k("CURSOR_PROJECT_DIR"))}function pa(e,t,n){return e!=="claude"&&e!=="codex"?!1:fa(t,n)?!0:Pm()}var Tm=new Set(["sessionstart","sessionend","stop","stopfailure","pretooluse","posttooluse","posttoolusefailure","permissiondenied","subagentstart","subagentstop","userpromptexpansion","userpromptsubmit"]);function dt(e,t,n,r){return fa(e,t)?"cursor":Nt(r)?r:Nt(n)?n:R(e,"turn_id")?"codex":R(e,"session_id")||Tm.has(t.toLowerCase())?"claude":"unknown"}function on(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function wm(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 ma(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function ga(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function _a(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function ft(e){return R(e,"session_id")||R(e,"conversation_id")}function wr(e){return R(e,"prompt.id")||R(e,"prompt_id")||R(e,"generation_id")||R(e,"turn_id")}function Nr(e){return R(e,"hook_event_name")||R(e,"event")}function ha(e,t,n){let r=ft(e),o=wr(e),s=Nr(e),i=R(e,"source"),a=dt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Nm=["session_start","session_end","tool_invoked","skill_invoked"];function Mm(e){return Nm.includes(e)}function Sa(e,t){return e&&Mm(e)?e:wm(t.toLowerCase())}var vm={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function sn(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ea(e,t=""){let n=R(e,"tool_name")||R(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!sn(n)&&(n=`MCP:${n}`):n=vm[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?xe(o.skill)||xe(o.skill_name):"")||R(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=Pi(a);let c=na(a),u=ia(a);return{toolName:n,skillName:i,ruleName:c,commandName:u}}var Lm=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function ya(e){for(let t of["subagent_type","agent_type"]){let n=R(e,t);if(n&&Lm.test(n))return n}return null}function Ra(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 Um="error",Dm="interrupted",Hm="permission_denied",Fm=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function pt(e){return Fm.test(e)?e:null}function jm(e){for(let t of["failure_type","error_type"]){let n=pt(R(e,t));if(n)return n}return null}function Ca(e,t){return ie(e,"is_interrupt")===!0?Dm:t.toLowerCase()==="permissiondenied"?Hm:jm(e)??Um}function ka(e,t){let n=null;for(let r of e)r&&t(r)&&(n===null||r.length>n.length)&&(n=r);return n}function $m(e,t){return ka(t,n=>e===n||e.startsWith(`${n}_`)||e.startsWith(`${n}-`))}function Km(e,t){return ka(t,n=>xr(n,e))}function Bm(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of br(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:Km(o[1],t)??o[1],mcpTool:o[2]}}function Gm(e,t){if(/^mcp__/i.test(e))return Bm(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:$m(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function zm(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function Ia(e,t=[],n=""){let r=e?Gm(e,t):{mcpServer:null,mcpTool:null},o=pt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!sn(e)&&(s=e),s&&(s=zm(s,o)),{mcpServer:o,mcpTool:s}}var ba=3e4,Zm="claims",qm=!0,Qm=100,eg=new Set(["sessionstart","sessionend","stopfailure"]),tg=["tool_name","tool","command","file_path","url"];function ng(e=Oa()){return Mr(ae(e),Zm)}function xa(e,t){try{let n=Ym(e,"utf8").split(`
25
+ `,1)[0]??"";return t-Number(n.trim())}catch{return Number.NaN}}function rg(e){let t=[];for(let n of tg){let r=R(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":rt(t.join("\0"))}function og(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=eg.has(n);if(!a&&!c)return;let u=e.runnerPlatform.trim()||"unknown";return rt(`${u}|${t}|${n}|${r}|${o}|${i}|${s}`)}function sg(e,t=Date.now()){let n;try{n=Jm(e)}catch{return}let r=0;for(let o of n){if(r>=Qm)break;r+=1;let s=Mr(e,o),i=xa(s,t);if(!(!Number.isFinite(i)||i<ba))try{Aa(s)}catch{}}}function ig(e,t,n=Date.now()){let r=Mr(t,e);try{if(Vm(r)){let o=xa(r,n);if(Number.isFinite(o)&&o>=0&&o<ba)return!1;try{Aa(r)}catch{}}}catch{}try{Wm(t,{recursive:!0}),Xm(r,`${n}
26
+ `,{encoding:"utf8",flag:"wx"})}catch(o){if(_i(o))return!1;let s=o instanceof Error?o.message:String(o);return p(`WARN: event claim failed open: ${s}`),!0}return sg(t,n),!0}function ag(e,t,n){let r=ft(e),o=wr(e),s=R(e,"tool_use_id"),i=R(e,"subagent_id")||R(e,"agent_id"),a=dt(e,t,void 0,n),c=rg(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function Pa(e,t,n,r=Oa(),o=Date.now()){if(!qm)return!0;let s=og(ag(e,t,n));if(!s)return!0;let i=ig(s,ng(r),o);return!i&&k("EV_AI_HOOK_DEBUG")&&p(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{closeSync as cg,writeSync as ug}from"node:fs";function Ta(e=process.env){let t=e[vn];if(delete e[vn],t===void 0)return;let n=Number.parseInt(t,10);if(!(!Number.isInteger(n)||n<3)){try{ug(n,$o)}catch{}try{cg(n)}catch{}}}function vr(e=process.env){let t=e[Uo];if(t)return{launcherVersion:t,hookSource:e[Do]??"",fallbackReason:e[Ho],launcherScope:e[Fo]}}function wa(e,t){return(e?Wo(e):void 0)===t}import{realpathSync as QS}from"node:fs";import{homedir as eE}from"node:os";var O=Qe(ze(),1);import{existsSync as lg,readFileSync as dg}from"node:fs";import{homedir as Na}from"node:os";import{join as fg}from"node:path";var pg="cloud-cache.json",mg=1440*60*1e3,gg=900*1e3;function _g(e=Na()){return fg(ae(e),pg)}function hg(e){if(!lg(e))return;let t=z(dg(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 Sg(e,t){try{Q(e,`${JSON.stringify(t)}
27
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);p(`WARN: cloud cache write failed open: ${r}`)}}function Eg(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?gg:mg;return n-e.probed_at<r}async function yg(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 Rg(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 Cg(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 kg(e){let t=await Promise.allSettled([yg(e),Rg(e),Cg(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Ma(e,t){if(e==="interactive")return null;let n=t?.home??Na(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=_g(n),i=hg(s);if(Eg(i,e,o))return i.result;let a=await kg(r);return Sg(s,{context:e,probed_at:o,result:a}),a}var Ig=["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"],Ag=["CURSOR_PROJECT_DIR"],Og=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function bg(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Og.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function va(e=process.env){let t=Ig.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:bg(e[r]??"")}:{name:r,present:!1}),n=Ag.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as r_}from"node:os";import{homedir as La}from"node:os";import{join as xg}from"node:path";function Pg(e=La()){return xg(e,".claude.json")}function an(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ua(e=La()){let n=D(Pg(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=an(n.emailAddress),o=an(n.fullName)??an(n.displayName),s=an(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 Fa}from"node:os";import{join as Da}from"node:path";var Tg="https://api.openai.com/auth";function Ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ja(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function wg(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 ja(r)}catch{return null}}function Ha(e,t,n){return Ve(e[n])??Ve(t?.[n])}function Ng(e=process.env,t=Fa()){let n=Ve(e.CODEX_HOME)??Da(t,".codex");return Da(n,"auth.json")}function $a(e=process.env,t=Fa()){let n=D(Ng(e,t),{}),r=Ve(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Ve(n.OPENAI_API_KEY))return null;let o=Ve(n.tokens?.id_token);if(!o)return null;let s=wg(o);if(!s)return null;let i=ja(s[Tg]),a=Ha(s,i,"name"),c=Ha(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 ln}from"node:os";import{join as fe}from"node:path";import{join as Mg}from"node:path";var vg="cursor-ide-identity.json",Lg=tt;function Ba(e){return Mg(ae(e),vg)}function Ka(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ga(e){let t=D(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:Ka(t.email),auth_id:Ka(t.auth_id)}}function za(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<Lg}function Va(e,t){try{Q(e,`${JSON.stringify(t)}
28
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);p(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as Ug}from"node:child_process";import{existsSync as Dg}from"node:fs";import{createRequire as Hg}from"node:module";import{pathToFileURL as Fg}from"node:url";var Ja=Hg(import.meta.url),cn=`
29
29
  SELECT key, value
30
30
  FROM ItemTable
31
31
  WHERE key LIKE 'cursorAuth/%'
32
32
  AND key NOT LIKE '%Token%'
33
33
  AND key NOT LIKE '%token%'
34
34
  ORDER BY key
35
- `.trim(),wr=new Map;function Ca(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 Aa(e){return e.toLowerCase().includes("token")}function ka(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=Ca(r.key),s=Ca(r.value);o&&s&&!Aa(o)&&t.set(o,s)}return t}function Jm(e){let t=Wm(e);return t.search="mode=ro&immutable=1",t.href}function Ym(e){try{let t=Ia("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(Qt)??n.prepare(Qt);return ka(r.all?.())}finally{n.close?.()}}catch{return null}}function Xm(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 Zm(e){try{return Xm(()=>{let t=Ia("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return ka(n.prepare(Qt).all?.())}finally{n.close?.()}})}catch{return null}}function qm(e){let t=new Map;for(let n of e.split(`
36
- `)){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&&!Aa(s)&&t.set(s,i)}return t}function Qm(e){try{let t=Gm("sqlite3",["-noheader","-batch","-separator"," ",e,Qt],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return qm(t)}catch{return null}}function Oa(e){let t=wr.get(e);if(t)return t;if(!zm(e)){let o=new Map;return wr.set(e,o),o}let n=Jm(e),r=Ym(n)??Qm(n)??Zm(n)??new Map;return wr.set(e,r),r}var eg="cursorAuth/cachedEmail",tg="cursorAuth/stripeMembershipAuthId";function en(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ng(e=tn(),t=process.platform,n=process.env){let r=en(n.VSCODE_PORTABLE);if(r)return fe(r,"user-data");let o=en(n.VSCODE_APPDATA);if(o)return fe(o,"Cursor");switch(t){case"darwin":return fe(e,"Library","Application Support","Cursor");case"win32":return fe(en(n.APPDATA)??fe(e,"AppData","Roaming"),"Cursor");default:return fe(en(n.XDG_CONFIG_HOME)??fe(e,".config"),"Cursor")}}function rg(e=tn()){return fe(e,".cursor","cli-config.json")}function og(e=tn(),t=process.platform,n=process.env){return fe(ng(e,t,n),"User","globalStorage","state.vscdb")}function pt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function sg(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):pt(e.userId)}function ig(e){return pt(e.email)??pt(e.authId)??sg(e)}function Mr(e){let t=pt(e.email),n=pt(e.displayName),r=ig(e);return!r||z(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function ag(e){let n=F(rg(e),{}).authInfo;return!n||typeof n!="object"?null:Mr(n)}function cg(e,t,n){let r=og(e,process.platform,t),o=Sa(e),s=Ea(o);if(ya(s,r,n))return Mr({email:s?.email,authId:s?.auth_id});let i=Oa(r),a=i.get(eg)??null,c=i.get(tg)??null;return Ra(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),Mr({email:a,authId:c})}function xa(e=tn(),t=process.env,n=Date.now()){return ag(e)??cg(e,t,n)}import{createHash as ug}from"node:crypto";import{resolve as lg}from"node:path";function L(e){return ug("sha256").update(e).digest("hex").slice(0,16)}function Lr(e){return L(lg(e))}function W(e,t){return`${e}\0${t}`}function Pa(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function ft(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(`
37
- `);return L(n)}function pg(e,t,n="git_config",r=null){return L(`${e??""}|${t??""}|${r??""}|${n}`)}function fg(e){let t=null,n=null;for(let r of e.split(`
38
- `)){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 mg(e,t=M){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return fg(n)}function gg(e=process.env){let t=k(e.GIT_AUTHOR_NAME),n=k(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=k(e.GIT_COMMITTER_NAME),o=k(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=k(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function me(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 _g(e=process.env){let t=k(e.EV_AI_HOOK_OPERATOR_EMAIL),n=k(e.EV_AI_HOOK_OPERATOR_LOGIN),r=me(k(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=k(e.GITHUB_ACTOR)??k(e.GITHUB_TRIGGERING_ACTOR)??k(e.GITHUB_USER),s=me(o,null,"github",o);if(s)return s;let i=k(e.GITLAB_USER_LOGIN),a=k(e.GITLAB_USER_EMAIL),c=me(k(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let l=k(e.BUILD_REQUESTEDFOREMAIL),u=me(k(e.BUILD_REQUESTEDFOR),l,"azure_devops",l??k(e.BUILD_REQUESTEDFORID));if(u)return u;let p=k(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=me(k(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(m)return m;let d=k(e.BUILD_USER_EMAIL)??k(e.CHANGE_AUTHOR_EMAIL),_=me(k(e.BUILD_USER)??k(e.CHANGE_AUTHOR),d,"jenkins",d??k(e.BUILD_USER_ID));if(_)return _;let S=k(e.CIRCLE_USERNAME),E=me(S,null,"circleci",S);if(E)return E;let y=k(e.CODEBUILD_INITIATOR),R=me(y,null,"codebuild",y);if(R)return R;let j=k(e.DRONE_COMMIT_AUTHOR_EMAIL),b=k(e.DRONE_COMMIT_AUTHOR),T=me(b??k(e.DRONE_COMMIT_AUTHOR_NAME),j,"drone",j??b);if(T)return T;if(ba(e.CLAUDE_CODE_REMOTE)||ba(e.CURSOR_AGENT)){let U=k(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:U&&!z(null,U)?U:null,identity_source:"cloud"}}return null}function Ur(e){return!!((e.git_user_name??e.git_user_email)&&!z(e.git_user_name,e.git_user_email))}function k(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ba(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function hg(e,t,n){return e==="claude"?da(t):e==="cursor"?xa(t,n):e==="codex"?_a(n,t):null}async function Dr(e,t=M,n=process.env,r={}){let o=await mg(e,t),s=gg(n),i=Ur(o)?o:s&&Ur(s)?s:null,a=hg(r.runnerPlatform,r.home??dg(),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=_g(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:Ur(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 Hr(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??M,s=e.env??process.env,i=await Dr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=pg(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?qn(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&ds(d,a,Ut())}}}function Fr(e){return e?!qn(e)?.operator_identity_hash:!0}function Ta(e){return!0}import{existsSync as K_,readFileSync as G_}from"node:fs";import{homedir as kc}from"node:os";import{join as We,resolve as z_}from"node:path";import{basename as U_,join as Ve}from"node:path";import{dirname as $a,resolve as on}from"node:path";import{existsSync as Sg}from"node:fs";import{homedir as wa}from"node:os";import{relative as Ma,resolve as oe,sep as Ae}from"node:path";var Eg=["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"],yg=["prompt","tool_input","tool_response","last_assistant_message","command"],Rg=new Set;function Cg(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return Rg}}function La(e){return Ua(e)==="allowlist"}function Ua(e){return I("EV_AI_HOOK_CAPTURE_CONTENT")?.toLowerCase()==="off"||e.capture_hook_input==="allowlist"?"allowlist":e.capture_hook_input==="full"||e.debug===!0||I("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"?"full":"content"}function Ig(e){let t={};for(let n of Eg){let r=ae(e,n);r!==void 0&&(t[n]=r)}return t}function nn(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=oe(e),r=oe(t),o=Ma(r,n);return!o||o==="."?".":o.startsWith(`..${Ae}`)||o===".."||oe(r,o)!==n?null:o.split(Ae).join("/")}function Da(e,t){let n=Ma(oe(t),oe(e)).split(Ae).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Ha(e){return typeof e!="string"||e.length===0?null:oe(e).split(Ae).join("/")}function Ag(){let e=I("CURSOR_PROJECT_DIR");if(!e)return null;let t=oe(e);return Sg(t)?t.split(Ae).join("/"):null}function $r(e,t){return nn(e,t)!==null}function kg(e,t){let n=oe(t??wa(),".cursor").split(Ae).join("/");return $r(e,n)}function Og(e,t,n){return t!==null&&$r(e,t)?!0:t!==null&&kg(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&$r(e,n.gitRoot)?!0:t===null}function Fa(e,t){let n=Ha(e.cwd);if(n!==null)return n;let r=oe(process.cwd()).split(Ae).join("/"),o=Ag();return Og(r,o,t)?r:o??r}function Gr(e,t={}){return Fa(e,t)}function zr(e,t=wa()){let n=oe(t).split(Ae).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Na(e,t,n){let r=Ha(n.launchCwd)??Fa(t,n);e.cwd=zr(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?nn(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var ja="\u2026[truncated]\u2026",Br=Buffer.byteLength(ja,"utf8"),xg=8;function mt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function va(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function Pg(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 bg(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=Br)return va(e,t);let r=t-Br,o=Math.ceil(r/2),s=Math.floor(r/2);return`${va(e,o)}${ja}${Pg(e,s)}`}function Kr(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)=>{Kr(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||Kr(o,[...t,r],n)}function Tg(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 Ng=256;function vg(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 wg(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=mt(e);if(s<=t)return;let i=[];Kr(e,[],i),i.sort((u,p)=>p.bytes-u.bytes);let a=i.filter(u=>u.bytes>n);if(a.length===0)return;let c=vg(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&&Tg(e,u.path,bg(u.value,r))}}function Mg(e,t){let n=Math.max(0,t-Ng),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:mt(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(mt(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function jr(e,t){let n=mt(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,wg(r,t,Br+xg),mt(r)>t&&Mg(r,t),r}function Lg(e,t,n){let r=Cg(n.runnerEvent);for(let o of yg){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function rn(e,t,n={}){let r=Ua(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,Na(s,e,n),jr(s,Dn)}let o=Ig(e);return Na(o,e,n),r==="content"?(Lg(o,e,n),jr(o,Dn)):jr(o,Uo)}function Ug(e){return typeof e=="string"&&e.length>0}function Vr(e){let t=on(e.home),n=on(e.launchCwd),r=e.gitRoot?on(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Ug(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&&nn(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=$a(r);for(;;){let u=on(l);if(u===t)break;let p=$a(u);if(p===u)break;if(e.hasProjectSpec(u)){s.push({scope:"parent",dir:u}),a=Da(u,n);break}l=p}}return{anchors:s,parentRel:a}}import{existsSync as Ba,readdirSync as Dg,realpathSync as Hg}from"node:fs";import{basename as Fg,dirname as jg,relative as $g,resolve as Bg,sep as Kg}from"node:path";var Wr=400,sn=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??_e}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=Bg(t).split(Kg).join("/");return zr(r,this.home)}let n=$g(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${L(jg(t))}/${Fg(t)}`:n}claimFile(t){try{let n=Hg(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(!Ba(t))return[];try{return Dg(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(Ba(t))return F(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 Jr,readFileSync as Gg,statSync as zg}from"node:fs";import{basename as Ga,join as gt,relative as za}from"node:path";var Yr=100*1024,Vg=4;function Wg(e){return e.length<=Yr?e:`${e.slice(0,Yr-1)}\u2026`}function Jg(e){try{let t=Gg(e),n=t.toString("utf8");return{hash:L(t),length:t.length,text:Wg(n)}}catch{return null}}var Ka={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Yg(e){return e in Ka?Ka[e]:"UNSPECIFIED"}function an(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Jg(t.absolutePath);if(!n)return!1;let r=t.name??Ga(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=Yg(t.kind);return s&&(o.trigger=s),e.push(o)}function Xg(e,t,n){let r=za(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Ga(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function ve(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Xr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Xr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Vg))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 d=gt(r,u.name,c);if(Jr(d)){let _=za(n,gt(r,u.name)).replace(/\\/g,"/");an(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:_||u.name});continue}Xr(e,{walkRoot:n,currentDir:gt(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){Xr(e,{walkRoot:n,currentDir:gt(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let p=u.name.toLowerCase();if(!l.some(d=>p.endsWith(d)))continue;let m=gt(r,u.name);an(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:Xg(n,m,!0)})}}function Va(e){for(let t of e)if(Jr(t))try{if(zg(t).size>0)return t}catch{continue}return e.find(t=>Jr(t))}var cn=Xe(Be(),1);var Zg="<omitted>",qg=["package_name","package_spec","package_version","package_version_source"],Wa=100,Ja=120,un=[{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"}],Ya=new Set(un.map(e=>e.attr)),Qg=["enabled","disabled"],e_=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],t_=new Set(["type","command","url","args","env","envVars","headers",...Qg,...e_,...un.map(e=>e.raw)]),n_=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",...qg,...Ya,...[...Ya].map(e=>`${e}_truncated`)]);function Xa(e,t){for(let n of t)t_.has(n)||n_.has(n)||(e[n]=Zg)}var r_=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,o_=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,s_=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,i_=/^bearer(?:\s+|$)/i;function ln(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Za(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Zr(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=ln(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function we(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function a_(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,cn.launchContainsCredentials)({kind:"url",url:e})||(0,cn.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=ht([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,cn.launchContainsCredentials)({kind:"url",url:r}):!0)}function qa(e,t,n){a_(t,n)&&(e.launch_had_credentials=!0)}function c_(e){return s_.test(e)||i_.test(e)?"<redacted>":e.includes("://")?we(e):e}function Qa(e){if(/^https?:\/\//i.test(e))return we(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Qa(e.slice(t+1))}`:c_(e)}function u_(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return r_.test(t)||o_.test(t)}function ht(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(u_(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Qa(r))}return t}function l_(e){let t=Za(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ja?r.slice(0,Ja):r))].sort();if(n.length!==0)return n.length>Wa?{names:n.slice(0,Wa),truncated:!0}:{names:n,truncated:!1}}function d_(e){let t=ln(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 ec(e,t){let n=new Set;for(let{raw:r,attr:o}of un){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=l_(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function tc(e,t){let n=ln(e),r={transport:t};if(!n)return r;Xa(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=Za(n.args);a&&(r.command_or_url=we(a));let l=ht(c);l.length>0&&(r.args=l),qa(r,a,c);let u=d_(n.env_http_headers),p=[...new Set([...Zr(n.env),...Zr(n.envVars),...Zr(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();p.length>0&&(r.env_var_names=p),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 d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let _=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return _&&(r.default_tools_approval_mode=_),ec(r,n),r}function nc(e){let t=ln(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function eo(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 Ge(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function _t(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 Qr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function qr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=Ge(n[1]);return r.length>0?r:void 0}function p_(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],Ge(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(`
39
- ${e}`);return s?.[1]&&r(s[1]),n}function rc(e){return Qr(e,"enabled")===!1?!1:Qr(e,"disabled")!==!0}function f_(e,t){let n={};for(let{raw:r,attr:o}of un){if(o==="auto_approve"){let i=Qr(t,r);if(i!==void 0){n[r]=i;continue}}let s=_t(t,r);s.length>0&&(n[r]=s)}ec(e,n)}var m_=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,g_=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function __(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
40
- `)){let s=m_.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(g_))o[1]&&t.add(o[1]);return[...t]}function oc(e,t){let n={transport:t};Xa(n,__(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?Ge(r[1]??""):void 0,i=o?Ge(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=_t(e,"args");a&&(n.command_or_url=we(a));let l=ht(c);l.length>0&&(n.args=l),qa(n,a,c);let u=new Set;for(let y of e.split(`
41
- `)){let R=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}let p=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(p?.[1])for(let y of p[1].split(",")){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}let m=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
42
- ${e}`);if(m?.[1])for(let y of m[1].split(`
43
- `)){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}for(let y of _t(e,"env_vars"))u.add(y);let d=p_(e,"env_http_headers");for(let[,y]of d)y.length>0&&u.add(y);let _=qr(e,"bearer_token_env_var");_&&(u.add(_),n.bearer_token_env_var=_),u.size>0&&(n.env_var_names=[...u].sort()),d.length>0&&(n.env_http_header_names=[...new Set(d.map(([y])=>y))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let S=qr(e,"auth");S&&(n.auth=S);let E=qr(e,"default_tools_approval_mode");return E&&(n.default_tools_approval_mode=E),f_(n,e),n}var h_=300,S_=256;function sc(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 dn(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 ic(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function E_(e){return ic(e,h_)}function ac(e,t){let n=sc(e.trim(),t),r=dn(n);if(r.length===0)return"";let[o,...s]=r,i=we(o),a=ht(s);return E_([i,...a].join(" "))}function cc(e,t){if(typeof e!="string")return null;let n=sc(e.trim(),t),r=dn(n)[0];if(!r)return null;let o=we(r);return o.length===0?null:ic(o,S_)}function y_(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 R_(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 C_(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 R_(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",p=y_({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:"",d=L(u),_=m?`${s}:${m}:${p}:${d}`:`${s}:${p}:${d}`,S=`${s}|${m}|${p}|${u}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:L(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:d,...p!=="prompt"&&u.trim()?{command:ac(u,e.home)}:{}}})}}}function ze(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||C_(e,t,r.hooks,n)}import{existsSync as P_,readFileSync as b_}from"node:fs";var ke=Xe(Be(),1);import{createHash as I_}from"node:crypto";import{join as St}from"node:path";function A_(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
44
- `);return I_("sha512").update(t).digest("hex").slice(0,16)}function k_(e){let t=process.platform==="win32"?St(I("LOCALAPPDATA")??e,"npm-cache"):St(e,".npm"),n=I("npm_config_cache")??I("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function uc(e){return typeof e=="string"&&e.length>0&&e.length<=ke.PACKAGE_FIELD_MAX?e:null}function O_(e,t,n){let r=A_(e);for(let o of k_(n)){let s=St(o,"_npx",r),i=F(St(s,"node_modules",...t.split("/"),"package.json"),{}),a=uc(i.version);if(a!==null)return a;let c=F(St(s,"package-lock.json"),{}),l=uc(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function x_(e){return e.length<=ke.PACKAGE_FIELD_MAX?e:`${e.slice(0,ke.PACKAGE_FIELD_MAX-1)}\u2026`}function to(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,ke.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,ke.packageNameFromSpec)(o);if(s===null)return null;let i=O_(r,s,n);return{package_name:s,package_spec:x_(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function lc(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=dn(e.trim());return n===void 0?null:to(n,r,t)}function pn(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 to(typeof n.command=="string"?n.command:null,r,t)}function dc(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:to(Ge(n[1]??""),_t(e,"args"),t)}function T_(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 pc(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=T_(a),l=tc(a,c);Object.assign(l,pn(a,e.home)??{});let u=nc(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:eo(i,l,u),origin:n,enabled:u,attributes:l})}}function fc(e,t,n){if(!P_(t)||!e.claimFile(t))return;let r;try{r=b_(t,"utf8")}catch{return}let o=e.componentPath(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),l=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),p="unknown";/^\s*url\s*=/m.test(u)?p="http":/^\s*command\s*=/m.test(u)&&(p="stdio");let m=oc(u,p);Object.assign(m,dc(u,e.home)??{});let d=rc(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:eo(a,m,d),origin:n,enabled:d,attributes:m})}}import{existsSync as N_,readdirSync as v_}from"node:fs";import{join as G}from"node:path";var mc=50;function no(e,t,n,r){if(!N_(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(mc,()=>{ve(e,{dir:G(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),ve(e,{dir:G(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),ve(e,{dir:G(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});ze(e,G(t,"hooks","hooks.json"),n),ze(e,G(t,"hooks.json"),n);let i=e.components.length-o,a=s>=mc;return{componentCount:i,expandTruncated:a}}function ro(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 gc(e){let t=G(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(G(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,E=0,y=!1;for(let R of l)if(typeof R.installPath=="string"&&R.installPath.length>0){let j=no(e,R.installPath,S,p);E+=j.componentCount,y=y||j.expandTruncated}ro(e,{pluginKey:a,rowPath:i,enabled:p,scope:_,version:d||void 0,marketplace:m||void 0,componentCount:E,expandTruncated:y,contentHash:L(`${a}|${d}|${_}|${p}|${E}`)})}}function w_(e){let t=e,n="";try{let r=v_(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=G(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=G(e,s),n=s)}}catch{}return{installPath:t,version:n}}var M_=/^\d+$/;function L_(e){let t=e.filter(n=>!M_.test(n.pluginId));return t.length>0?t:e}function _c(e){let t=[{base:G(e.home,".cursor/plugins/local"),scope:"local"},{base:G(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=G(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:p}=no(e,c,l,!0);ro(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:p,contentHash:L(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(G(n,s))){if(!a.isDirectory())continue;let c=G(n,s,a.name),{installPath:l,version:u}=w_(c);i.push({pluginId:a.name,installPath:l,version:u})}for(let a of L_(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:p}=no(e,a.installPath,l,!0);ro(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:p,contentHash:L(`${c}|${a.version}|${u}`)})}}}function D_(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)ve(e,{dir:Ve(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)ve(e,{dir:Ve(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=Va(i.map(c=>Ve(r,c)));a&&an(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:U_(a)})}for(let i of Vs(n))ze(e,Ve(r,i),o);for(let i of n.mcpJson??[])pc(e,Ve(r,i),o);for(let i of n.mcpToml??[])fc(e,Ve(r,i),o);if(s){if(n.managed)for(let i of Lt(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&ze(e,i,o);n.plugins==="claude"?gc(e):n.plugins==="cursor"&&_c(e)}}function hc(e,t){try{let n=new sn(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)D_(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 oo(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=hc(t,{layouts:Object.values(He),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:_e,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(ye),l=Vr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>Js(c,u)});i=l.parentRel;for(let u of l.anchors){let p=Lr(u.dir);if(o!==void 0&&!o(u.scope,p))continue;let m=hc(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Wr,scopeRef:p});m&&(r[u.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function so(e,t,n={}){let r=n.truncated===!0,o=ft(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 p=W(u.path,u.name);c[p]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let p=Pa(u);p&&l.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:l,unchanged:a.length===0&&l.length===0}}var Ec=2*1024*1024,H_=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function io(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 ao(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 Sc(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function yc(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function co(e,t=Ec){let n=[],r=[];for(let u of e)H_.has(u.kind)?n.push(u):r.push(u);r.sort((u,p)=>(u.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let p=s.length>0?1:0,m=Sc(u)+p;if(i+m<=t){s.push(u),i+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let d=yc(u),_=Sc(d)+p;if(i+_<=t){s.push(d),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function uo(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:yc(n))}var F_=["user","cwd","repo","parent"];function lo(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let b of F_){let T=t.scopes[b];if(!T)continue;let U=n(b,T.scopeRef),D=U.components,B=so(T.components,D,{forceFull:D===void 0,truncated:T.truncated}),Q=new Set(U.textHashes),H=io(T.components,B.upserts,Q),v=uo([...B.upserts,...H],Q);s.push({scope:b,walk:T,delta:B,outgoing:v,outgoingKeys:new Set(v.map(C=>W(C.path,C.name))),deliveredTextHashes:Q,cachedComponents:D})}let i=s.flatMap(b=>b.outgoing),a=co(i,o),c=new Set(a.components.map(b=>W(b.path,b.name))),l=[],u=[],p=[],m=[],d=[],_=[],S=[];for(let b of s){let{scope:T,walk:U,delta:D}=b;_.push(...U.components),l.push(T);let B=a.components.filter(C=>b.outgoingKeys.has(W(C.path,C.name))),Q=[...b.outgoingKeys].some(C=>!c.has(C)),H=D.truncated||Q;H?p.push(T):D.full&&u.push(T),m.push(...B),!D.full&&!H&&d.push(...D.removed);let v=D.full?{}:{...b.cachedComponents??{}};if(!H)for(let C of D.removed)delete v[W(C.path,C.name)];for(let C of B)v[W(C.path,C.name)]=C.content_hash;S.push({scope:T,scopeRef:U.scopeRef,components:v,textHashes:ao(b.deliveredTextHashes,B.filter(C=>C.text!==void 0).map(C=>C.content_hash),U.components),collectedAtMs:r,included:B.length>0||D.removed.length>0&&!H||D.full})}let E={user_spec_hash:ft(_),user_spec_count:_.length,user_spec_truncated:p.length>0};l.length>0&&(E.user_spec_scopes=l,E.user_spec_full_scopes=u,E.user_spec_truncated_scopes=p,E.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(E.user_spec_full=!0),m.length>0&&(E.user_spec=m),d.length>0&&(E.user_spec_removed=d),a.textDeferredCount>0&&(E.user_spec_text_deferred=a.textDeferredCount);let y=t.scopes.cwd;y&&(E.user_spec_cwd_scope_ref=y.scopeRef);let R=t.scopes.repo;R&&(E.user_spec_repo_scope_ref=R.scopeRef);let j=t.scopes.parent;return j&&(E.user_spec_parent_scope_ref=j.scopeRef,t.parentRel&&(E.user_spec_parent_rel=t.parentRel)),{fields:E,scopes:S}}var yt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function fn(e){return e==="cwd"||e==="repo"||e==="parent"}function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function po(e){return!Et(e)||!Et(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 Rc(e){return j_(e)}function Cc(e){return $_(e)}function Ic(e){return B_(e)}function j_(e){if(!Et(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function $_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function fo(e,t){if(!Et(e))return;let n=e[t];return po(n)?n:void 0}function B_(e){if(!Et(e))return{};let t={};for(let[n,r]of Object.entries(e))po(r)&&(t[n]=r);return t}function mo(e,t=20){let n=[];for(let[r,o]of Object.entries(e))po(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 V_=200,Ac=200,W_=["allow","deny","ask"],J_=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,_o="<path>",Y_=new RegExp(`${_o}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function X_(e){let t=e.replace(J_,_o).replace(Y_,_o);return t.length>Ac?`${t.slice(0,Ac)}...`:t}function gn(e){let t=F(e,{}),n=[];for(let r of W_)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:X_(o),mode:r});return{model:t.model??"",permissionKeys:n}}function Z_(e){let{serverManaged:t,fileBased:n}=Fn(process.platform,e),r=gn(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=gn(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function q_(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 Q_=10,eh="self-config-cache.json",Oc=2;function _n(){return I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function th(){return I("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function nh(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=et}var rh={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function oh(e,t=M){let n=rh[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(`
45
- `)[0]??"").trim();return a||r(o+1)};return r(0)}function sh(e=kc()){return We(e,".ev-ai","agent-hook",eh)}function ih(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
46
- `);return L(n)}function mn(e,t,n=!1){let r=ih(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 go(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>We(e,a)),...n]){let a=z_(i);if(s.has(a))continue;s.add(a);let c=Gn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function ah(e){return K_(e)?$(G_(e,"utf8"),{}):{}}function ch(e,t){try{te(e,`${JSON.stringify(t)}
47
- `)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: self-config cache write failed open: ${r}`)}}function uh(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(fn(t))return fo(e[yt[t]],n)?.collected_at_ms}function lh(e,t,n){if(t==="user")return{components:Rc(e.user_spec_components),textHashes:Cc(e.user_spec_text_hashes)};if(!fn(t))return{components:void 0,textHashes:[]};let r=fo(e[yt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function dh(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=Oc,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(!fn(s.scope))continue;let i=yt[s.scope],a=Ic(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]=mo(a)}}return o}async function xc(e,t=process.cwd(),n=kc(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await oh(e),a="",c=[];if(o){let H=Z_(n),v=gn(We(n,".claude/settings.json")),C=gn(We(t,".claude/settings.local.json"));a=H.model||C.model||v.model,c=q_([...H.permissionKeys,...v.permissionKeys,...C.permissionKeys]).slice(0,V_)}let l={present:!1,size:0},u=H=>{let v=[],C=!1;for(let Y of H){let kt=Wo(We(n,Y));if(v=v.concat(kt.entries),C=C||kt.truncated,v.length>=_e){v=v.slice(0,_e),C=!0;break}}return{entries:v,truncated:C}},p=sh(n),m=ah(p),d=m[e]??{},_=(d.send_count??0)+1,S=_>0&&_%Q_===0,E=H=>S?void 0:d[H],y=u(Ce.skills),R=u(Ce.subagents),j=u(Ce.commands),b=u(Ce.rules),T={skills:mn(y.entries,E("skills"),y.truncated),subagents:mn(R.entries,E("subagents"),R.truncated),commands:mn(j.entries,E("commands"),j.truncated),rules:mn(b.entries,E("rules"),b.truncated)},U={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:T.skills,subagents:T.subagents,commands:T.commands,rules:T.rules,memory:go(n,Ce.memory),settings:go(n,Ce.settings,Ys(n)),mcp:go(n,Ce.mcp)},local_settings:o?Gn(We(t,".claude/settings.local.json")):l},D=null,B=r.nowMs??Date.now();if(!_n()){let H=d.user_spec_layout_version!==Oc,v=oo(e,n,{launchCwd:th()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(C,Y)=>H||nh(uh(d,C,Y),B)});if(Object.keys(v.scopes).length>0){let C=lo({collected:v,cacheFor:(Y,kt)=>H?{components:void 0,textHashes:[]}:lh(d,Y,kt),nowMs:B});Object.assign(U,C.fields),D={hash:C.fields.user_spec_hash,home:C.scopes.find(Y=>Y.scope==="user")??null,project:C.scopes.filter(Y=>Y.scope!=="user")}}}let Q=dh(d,T,_,D);return{config:U,commit:()=>{m[e]=Q,ch(p,m)}}}import{homedir as Hh}from"node:os";import{join as Mc}from"node:path";import{open as Pc,mkdir as ph,readFile as fh,readdir as mh,rename as gh,stat as _h,rmdir as hh,unlink as Sh,utimes as Eh}from"node:fs/promises";var hn=new WeakMap;function yh(e){if(e&&typeof e=="object"&&"code"in e)return e}function ho(e){return yh(e)?.code==="ENOENT"}async function Tc(e,t){try{return await e.readdir(t)}catch(n){if(ho(n))return[];throw n}}function Nc(){return{async open(e,t){let n=await Pc(e,t),r={path:e};return hn.set(r,n),r},async write(e,t){let n=bc(e),r=typeof t=="string"?Buffer.from(t,"utf8"):t;await n.write(r)},async fsync(e){await bc(e).sync()},async close(e){let t=hn.get(e);hn.delete(e),t&&await t.close()},rename:gh,async readdir(e){return mh(e)},readFile:fh,async stat(e){let t=await _h(e);return{mtimeMs:t.mtimeMs,size:t.size,isDirectory:()=>t.isDirectory()}},async mkdir(e,t){await ph(e,t)},unlink:Sh,rmdir:hh,utimes:Eh,async fsyncDir(e){if(process.platform==="win32")return;let t=await Pc(e,"r");try{await t.sync()}finally{await t.close()}}}}function bc(e){let t=hn.get(e);if(!t)throw new Error("closed");return t}function Sn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{join as En}from"node:path";function Rh(e){return En(e,".ev-ai","agent-hook","js","signed-v1")}function Ch(e){return En(Rh(e),"scopes")}function vc(e,t){return En(Ch(e),t)}function wc(e){return En(e,"attempts")}function So(e){return String(e).padStart(10,"0")}var Ih=/^(\d{10})$/,Ah=/^(\d{10})\.done$/,kh=/^[0-9a-f]{128}$/,Oh=64;async function Hc(e,t,n=!1){let r=wc(t),o=await Tc(e,r),s=new Map,i=new Map,a=Lc(o,Ih),c=Lc(o,Ah),l=async m=>{let d=await Dc(e,Mc(r,xh(m)));return d&&s.set(m,{record:bh(d.value),mtimeMs:d.mtimeMs}),d!==void 0},u=async m=>{let d=Th((await Dc(e,Mc(r,Ph(m))))?.value);return d&&i.set(m,d),d!==void 0};if(!n)return await Promise.all([...a.map(l),...c.map(u)]),{claims:s,dones:i};await Promise.all([Uc(a,l),Uc(c,u)]);let p=Rt(s);return p<Rt(i)&&c.includes(p)&&await u(p),{claims:s,dones:i}}function Lc(e,t){return e.flatMap(n=>{let r=t.exec(n);return r?[Number(r[1])]:[]})}async function Uc(e,t){for(let n of[...e].sort((r,o)=>o-r))if(await t(n))return}function Rt(e){let t=0;for(let n of e.keys())n>t&&(t=n);return t}function Fc(e){if(e.record!=="empty"&&e.record.started_at){let t=Date.parse(e.record.started_at);if(Number.isFinite(t))return t}return e.mtimeMs}function xh(e){return So(e)}function Ph(e){return`${So(e)}.done`}async function Dc(e,t){let n;try{n=await e.stat(t)}catch(o){if(ho(o))return;throw o}let r=n.mtimeMs;if(n.size===0||n.size>br)return{mtimeMs:r};try{let o=await e.readFile(t);return o.byteLength===0||o.byteLength>br?{mtimeMs:r}:{mtimeMs:r,value:JSON.parse(o.toString("utf8"))}}catch{return{mtimeMs:r}}}function bh(e){if(!Sn(e))return"empty";let t={};return typeof e.started_at=="string"&&(t.started_at=e.started_at),(e.owner==="bootstrap"||e.owner==="refresh")&&(t.owner=e.owner),e.resync===!0&&(t.resync=!0),t}function Th(e){if(!Sn(e))return;let t=e;if(typeof t.finished_at!="string"||typeof t.outcome!="string"||typeof t.interval_s!="number"||!Number.isFinite(t.interval_s))return;let n=Nh(t.selection);if(n)return{finished_at:t.finished_at,interval_s:t.interval_s,outcome:t.outcome,selection:n}}function Nh(e){if(!Sn(e))return;let t=e;if(t.kind==="bundled")return t.why==="server"||t.why==="bootstrap_failed"?{kind:"bundled",why:t.why}:void 0;if(t.kind==="cached"&&typeof t.digest=="string"&&kh.test(t.digest)&&typeof t.version=="string"&&t.version.length>0&&typeof t.sha512=="string"&&vh(t.sha512)===t.digest)return{kind:"cached",digest:t.digest,version:t.version,sha512:t.sha512}}function vh(e){if(e.length===0||!/^[A-Za-z0-9+/]+=*$/.test(e))return;let t=Buffer.from(e,"base64");if(!(t.byteLength!==Oh||t.toString("base64")!==e))return t.toString("hex")}function Uh(e){return e==="bootstrap"?3e3:6e4}function Dh(e,t){let n=Rt(e.claims);if(n===0)return;let r=Rt(e.dones),o=e.claims.get(n),s=e.dones.get(n);if(o&&!s){let a=Fc(o),c=o.record==="empty"?void 0:o.record.owner,l=Uh(c)+3e4;if(t-a>l)return{n,latest_claim:n,outcome:"incomplete",finished_at:null,selection_version:jc(e.dones.get(r)?.selection)}}if(r===0)return;let i=e.dones.get(r);if(i)return{n:r,latest_claim:n,outcome:i.outcome,finished_at:i.finished_at,selection_version:jc(i.selection)}}async function $c(e,t,n){try{let r=await Hc(Nc(),vc(e,t),!0);return Dh(r,n)}catch{return}}function jc(e){return e?.kind==="cached"&&typeof e.version=="string"?e.version:null}async function Bc(e=Hh()){let t=Tr()?.launcherScope;if(!t)return{};let n=await $c(e,t,Date.now());return n?{launcher_scope:t,launcher_attempt:n}:{launcher_scope:t}}function Je(e,t,n){let r={installation_id:n.installationId};n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId);let o={schema_version:ge,event:e,timestamp:Ut(),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:se,host_arch:process.arch,node_version:process.version,correlation:r,payload:t},s=Tr();return s&&(o.launcher_version=s.launcherVersion,o.hook_source=s.hookSource,o.hook_fallback_reason=s.fallbackReason??null,o.launcher_scope_match=ca(n.collectorUrl,s.launcherScope)),e==="session_start"&&(n.launcher_scope&&(o.launcher_scope=n.launcher_scope),n.launcher_attempt&&(o.launcher_attempt=n.launcher_attempt)),o}import{existsSync as Gc}from"node:fs";import{spawn as zc}from"node:child_process";import{fileURLToPath as jh}from"node:url";import{gzipSync as Fh}from"node:zlib";function Eo(e){return I("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<Do?{body:e}:{body:Fh(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function yn(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function Kc(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var Ct="__post",Rn="__work";async function $h(e,t,n={}){if(I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off")return e;let r=await Dr(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 Bh(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 Vc(e){switch(e){case"session_start":return wo;case"session_end":return Mo;case"tool_invoked":case"skill_invoked":return Ln;default:return Ln}}function Kh(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
48
- ${n}`}function Wc(e,t=[],n=process.execPath,r=import.meta.url,o=Gc){if(vt(n))return{command:n,args:[e,...t]};let s=jh(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Gh(e=process.execPath,t=import.meta.url,n=Gc){return Wc(Ct,[],e,t,n)}function zh(e){let t=e.indexOf(`
49
- `);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 Cn(e,t=fetch){let n=await e(),r=zh(n);if(!r)return;let{meta:o,body:s}=r,i=Eo(s),a=yn(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function Vh(e,t,n,r=fetch){let o=Vc(e),s=Eo(t),i=yn(s.contentEncoding),a=Kc(s.body);f(`POST event=${e} url=${Nt(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:yn(),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 p=(await l.text()).slice(0,200).replace(/[\n\r]/g,"");return f(`POST outcome=fail elapsed_ms=${u} http=${l.status} body=${p}`),!1}catch(l){let u=Date.now()-c,p=l instanceof Error?l.message:String(l);return f(`POST outcome=fail elapsed_ms=${u} http=000 body=${p}`),!1}}async function Jc(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()},Lo),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 Wh(e,t,n,r=zc,o=Gh){let s=Vc(e),i=Kh(n,s,t),{command:a,args:c}=o();return Jc(a,c,i,r,"detached post")}async function Yc(e,t,n=zc,r=Wc){let{command:o,args:s}=r(Rn,t);return Jc(o,s,e,n,"detached work")}async function Ye(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(!qe(o))return f(`WARN: collector URL blocked (https required): ${Nt(o)}`),!1;let a=await $h(t,n.runnerPlatform,i),c=r(e,a,{...n,collectorUrl:o});s!==void 0&&(c.build_ms=Math.max(0,Date.now()-s));let l=`${JSON.stringify(c)}
50
- `,u=I("EV_AI_HOOK_DEBUG");u==="full"?f(`DEBUG envelope=${JSON.stringify(c)}`):u==="1"&&f(`DEBUG summary=${Bh(c,Buffer.byteLength(l,"utf8"))}`);let p=process.argv.includes(Rn),m=I("EV_AI_HOOK_SYNC")==="1";return Zt(n.runnerEvent,n.runnerPlatform)||p||m?Vh(e,l,o):(await Wh(e,l,o),!1)}import{createReadStream as Jh}from"node:fs";import{stat as Yh}from"node:fs/promises";import{basename as Xh,resolve as Zh}from"node:path";import{createInterface as qh}from"node:readline";var Qh=1024*1024;function eS(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Xh(t).endsWith(".jsonl")}async function Xc(e){if(!e||!eS(e))return null;try{let t=Zh(e),n=await Yh(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Qh),o=[],s=qh({input:Jh(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 An(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function At(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function yo(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function Qc(e){let t=Date.now();await pS(e);let{gitRoot:n}=e.manifest;await kn(e,n);let r=yo(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:rn(e.hookInput,e.manifest.manifest,r),envelopeFields:An(e),launchCwd:Gr(e.hookInput,r),home:nS()}}function Zc(e){try{return V(tS(e))}catch{return null}}function eu(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function qc(e,t){let n=e.replaceAll("\\","/");if(!eu(n))return null;let r=V(e),o=V(t),s=Zc(e)??r,i=Zc(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function rS(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=qc(e,t)??(eu(r)?null:r),i=qc(e,n);return{repositorySourcePath:s,userSourcePath:i}}function In(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=rS(e,t,n),c=i??a,l=c===null?null:o(c),u=l!==null&&c!==null?oS({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 oS(e){try{let t=e.inRepository?aS(e.platformAgentId,e.sourcePath):(0,O.installationRootExternalKey)(e.installationId,(0,O.userConfigRootFromPath)(e.sourcePath));return t?(0,O.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function Ro(e,t,n){return Ye("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Je,e.manifest.collectorUrl,t.buildStartedAtMs,At(e,t.home))}function sS(e){return Fi(e.runnerEvent,e.runnerPlatform)?[]:ni(e.hookInput)}function iS(e,t){return Ro(e,t,{})}var tu=new Set([...Object.values(Ne),".github"]);function aS(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=>tu.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function cS(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(_=>_.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 _=(0,O.userConfigRootFromPath)(l);return(0,O.buildComponentReference)({installationRootExternalKey:(0,O.installationRootExternalKey)(r,_),installableKind:O.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),d=m.replaceAll("\\","/").split("/").at(-1);if(!(d===void 0||!tu.has(d)))try{return(0,O.buildComponentReference)({installationRootExternalKey:n,installableKind:O.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function uS(...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 lS(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 dS(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Me=new Set,It=null;async function pS(e){if(_n())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Me.has(t))return;if(!Fr(n)){Me.add(t);return}let r=nt({sessionId:e.sessionId,hostname:rt()});if(Ta(r)){if(It){await It;return}It=(async()=>{if(Me.has(t)||!Fr(n)){Me.add(t);return}if(!ps(n)){Me.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,p,m]=await Promise.allSettled([ct(i),Wn(),Nr(r),Jn(),Hr({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),d=J(c,null,"gitSnapshot"),_=J(l,"","detectVirt"),S=J(u,null,"probeCloud"),E=J(p,{},"hostEnv"),y=J(m,{commit:()=>{}},"resolveOperatorForSend");await kn(e,i,d);let R={identity:{host:rt(),context:r,virt:_||null,cloud:S,git:d},host_env:E,env_vars:vr(),self_config:dS(a,y.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await Ye("session_start",R,An(e),Je,e.manifest.collectorUrl,s,At(e)),o&&(y.commit(),Me.add(t))}finally{fs(n)}})().finally(()=>{It=null}),await It}}async function kn(e,t,n){try{let r=n===void 0?await ct(t):n;e.platformAgentId=await ki(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 fS(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=nt({sessionId:e.sessionId,hostname:rt()}),o=String(e.runnerPlatform),s=yo(e),i=Gr(e.hookInput,s),a=ct(n),c=Bc().catch(()=>({})),l=_n()?Promise.resolve({commit:()=>{}}):Hr({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[u,p,m,d,_,S,E]=await Promise.allSettled([a,Wn(),Nr(r),Jn(),Ar(e.manifest.manifest,n,o),a.catch(()=>null).then(Y=>xc(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:Y?.remote??null})),l]),y=J(u,null,"gitSnapshot"),R=J(p,"","detectVirt"),j=J(m,null,"probeCloud"),b=J(d,{},"hostEnv"),T=J(_,[],"mcpDeclared"),U=J(S,lS(o),"selfConfig"),D=J(E,{commit:()=>{}},"resolveOperatorForSend"),B=U.config;await kn(e,n,y);let Q=h(e.hookInput,"model");Q&&(B.model=Q);let H={identity:{host:rt(),context:r,virt:R||null,cloud:j,git:y},host_env:b,env_vars:vr(),mcp:{declared:T},self_config:B,run_meta:{trigger:e.hookSource||"startup"},hook_input:rn(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},v=await c;await Ye("session_start",H,{...An(e),...v},Je,e.manifest.collectorUrl,t,At(e))&&(U.commit(),D.commit(),Me.add(e.manifest.installationId))}async function mS(e){let t=Date.now(),{gitRoot:n}=e.manifest;await kn(e,n);let r=e.runnerEvent.toLowerCase(),o=uS(h(e.hookInput,"status"),h(e.hookInput,"stop_reason"),h(e.hookInput,"reason"),dt(h(e.hookInput,"error")),r==="stop"?ae(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=e.runnerPlatform==="claude"?await Xc(h(e.hookInput,"transcript_path")):null,i=rn(e.hookInput,e.manifest.manifest,yo(e));s&&(i.model=s),r!=="stopfailure"&&!La(e.manifest.manifest)&&i.last_assistant_message===void 0&&(i.last_assistant_message=""),await Ye("session_end",{status:o,...s?{model:s}:{},hook_input:i},An(e),Je,e.manifest.collectorUrl,t,At(e))}function nu(e,t,n,r){let o=r??ti({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=In(o,t.gitRoot,t.home,O.ComponentKind.SKILL,O.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&lr(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??Ti({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=In(i,t.gitRoot,t.home,O.ComponentKind.COMMAND,O.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function gS(e,t,n){let r=Gt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=nu(e,t,o,r);return Ro(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 _S(e,t,n){return Promise.all(n.map(r=>{let o=Oi({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=In(o,t.gitRoot,t.home,O.ComponentKind.RULE,O.nativeKeyForRulePath,e),i=s.nativeKey??Pi(r);return Ro(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var hS=[{kind:O.ComponentKind.SKILL,nativeKeyFn:O.nativeKeyForSkillPath},{kind:O.ComponentKind.RULE,nativeKeyFn:O.nativeKeyForRulePath},{kind:O.ComponentKind.COMMAND,nativeKeyFn:O.nativeKeyForCommandPath}];function SS(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=pr(e.hookInput);if(r===null)return n.skillName===null?{}:nu(e,t,n.skillName,null);for(let o of hS){let s=In(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===O.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===O.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var ES=/mcp/i;function yS(e,t,n,r){let o=ES.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?lc(t,n):pn(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 RS(e){let t=await Qc(e),n=Gi(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=dr(e.hookInput),i=cc(s,t.home),a=Vi(e.hookInput),c=ji(e.runnerEvent),l=c===!1?Wi(e.hookInput,e.runnerEvent):null,u=await Ar(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=dt(h(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:d}=Ji(r,u.map(U=>U.name),p??""),_=cS(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),u,p),S=_===void 0?SS(e,t,n):{},E=m===null?null:Ui(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),y=yS(e,s,t.home,{hasMcpIdentity:!!m||!!d,declaredConfig:E}),R=_??S.componentReference,j=S.ruleName??n.ruleName,b=S.commandName??n.commandName,T=zi(e.hookInput);await Ye("tool_invoked",{tool_name:r,skill_name:o,...j?{rule_name:j}:{},...b?{command_name:b}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...m?{mcp_server:m}:{},...d?{mcp_tool:d}:{},...y,...R?{component_reference:R}:{},...T?{subagent_type:T}:{},hook_input:t.hookInput},t.envelopeFields,Je,e.manifest.collectorUrl,t.buildStartedAtMs,At(e,t.home))}async function ru(e){switch(e.internalEvent){case"session_start":await fS(e);return;case"session_end":await mS(e);return;case"skill_invoked":{let t=sS(e),n=bi(e.hookInput),r=Hi(e.runnerEvent);if(t.length===0&&n.length===0&&!r)return;let o=await Qc(e);await Promise.all([r&&t.length===0&&n.length===0?iS(e,o):void 0,t.length===0?void 0:gS(e,o,t),n.length===0?void 0:_S(e,o,n)]);return}case"tool_invoked":await RS(e);return;default:return}}function ou(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{createHash as CS}from"node:crypto";import{mkdirSync as IS,readdirSync as AS,readFileSync as kS,statSync as su,unlinkSync as OS,writeFileSync as xS}from"node:fs";import{homedir as On}from"node:os";import{join as Co}from"node:path";var PS="turns",iu=1440*60*1e3,bS=100,TS=new Set(["stop","stopfailure","sessionend"]);function Io(e=On()){return Co(ce(e),PS)}function NS(e){return CS("sha256").update(e).digest("hex").slice(0,32)}function au(e,t){return Co(e,NS(t))}function vS(e,t=Date.now()){let n;try{n=AS(e)}catch{return}let r=0;for(let o of n){if(r>=bS)return;r+=1;try{let s=Co(e,o);t-su(s).mtimeMs>iu&&OS(s)}catch{}}}function wS(e,t,n=On()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=Io(n);IS(s,{recursive:!0}),xS(au(s,r),o,"utf8")}catch{}}function MS(e,t=On()){let n=e.trim();if(!n)return"";try{let r=au(Io(t),n);return Date.now()-su(r).mtimeMs>iu?"":kS(r,"utf8").trim()}catch{return""}}function cu(e,t,n,r=On()){let o=t.trim(),s=TS.has(n.trim().toLowerCase());return s&&vS(Io(r)),o?(wS(e,o,r),o):s?MS(e,r):""}async function uu(e,t,n,r){let o=t??await Bn(Un),s=$(o,{}),i=h(s,"session_id")||h(s,"conversation_id"),a=await Ss(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=$i(s,a.manifest.platform,n),l=Bi(e,c.runnerEvent);if(!l){f(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:cu(c.sessionId,c.turnId,c.runnerEvent),runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:a,platformAgentId:a.platformAgentId};if(ou(l)){f(`WARN: unsupported internal event '${l}'`);return}await ru(u)}function LS(e,t){if(I("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ze(e),r=$(t,{}),o=n.event??(h(r,"hook_event_name")||h(r,"event")),s=lt(r,o,void 0,n.runner);return Zt(o,s)}async function lu(e=process.argv.slice(2)){if(aa(),e[0]===Ct){try{await Cn(tt)}catch{}return 0}if(e[0]===Rn){try{let t=Ze(e.slice(1)),n=await tt(),r=$(n,{}),o=t.event??(h(r,"hook_event_name")||h(r,"event"));if(zn()||Or(t.runner,r,o))return 0;await uu(t.event,n,t.runner,kr(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(Un),n=Ze(e),r=kr(n),o=$(t,{}),s=n.event??(h(o,"hook_event_name")||h(o,"event"));if(zn()||Or(n.runner,o,s)||!ta(o,s,n.runner))return 0;LS(e,t)?await uu(n.event,t,n.runner,r):await Yc(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);f(`WARN: hook failed open: ${n}`)}finally{Vo()}return 0}function xn(){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 du(e){return e.includes("--help")||e.includes("-h")}async function jS(e=process.argv.slice(2)){let[t,...n]=e;if(t===Ct){try{await Cn(tt)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${se}
51
- `),0):t==="configure"?du(n)?(xn(),0):(await js(Os(n)),0):t==="install"?du(n)?(xn(),0):(await Hs(xs(n)),0):t==="migrate-to-plugin"?(await Bs(),0):t==="update"?(await Fs(),0):t==="uninstall"?(await Ks(),0):t==="help"||t==="--help"||t==="-h"?(xn(),0):t===void 0?(xn(),1):lu(e)}function $S(e,t,n=US){if(!t)return!1;try{return e===FS(DS(t)).href?!0:n(HS(e))===n(t)}catch{return!1}}$S(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&jS().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);f(t),process.exit(1)});export{$S as isCliEntrypoint,jS as main};
35
+ `.trim(),Lr=new Map;function Wa(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 Ya(e){return e.toLowerCase().includes("token")}function Xa(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=Wa(r.key),s=Wa(r.value);o&&s&&!Ya(o)&&t.set(o,s)}return t}function jg(e){let t=Fg(e);return t.search="mode=ro&immutable=1",t.href}function $g(e){try{let t=Ja("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(cn)??n.prepare(cn);return Xa(r.all?.())}finally{n.close?.()}}catch{return null}}function Kg(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 Bg(e){try{return Kg(()=>{let t=Ja("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return Xa(n.prepare(cn).all?.())}finally{n.close?.()}})}catch{return null}}function Gg(e){let t=new Map;for(let n of e.split(`
36
+ `)){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&&!Ya(s)&&t.set(s,i)}return t}function zg(e){try{let t=Ug("sqlite3",["-noheader","-batch","-separator"," ",e,cn],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return Gg(t)}catch{return null}}function Za(e){let t=Lr.get(e);if(t)return t;if(!Dg(e)){let o=new Map;return Lr.set(e,o),o}let n=jg(e),r=$g(n)??zg(n)??Bg(n)??new Map;return Lr.set(e,r),r}var Vg="cursorAuth/cachedEmail",Wg="cursorAuth/stripeMembershipAuthId";function un(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Jg(e=ln(),t=process.platform,n=process.env){let r=un(n.VSCODE_PORTABLE);if(r)return fe(r,"user-data");let o=un(n.VSCODE_APPDATA);if(o)return fe(o,"Cursor");switch(t){case"darwin":return fe(e,"Library","Application Support","Cursor");case"win32":return fe(un(n.APPDATA)??fe(e,"AppData","Roaming"),"Cursor");default:return fe(un(n.XDG_CONFIG_HOME)??fe(e,".config"),"Cursor")}}function Yg(e=ln()){return fe(e,".cursor","cli-config.json")}function Xg(e=ln(),t=process.platform,n=process.env){return fe(Jg(e,t,n),"User","globalStorage","state.vscdb")}function mt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Zg(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):mt(e.userId)}function qg(e){return mt(e.email)??mt(e.authId)??Zg(e)}function Ur(e){let t=mt(e.email),n=mt(e.displayName),r=qg(e);return!r||G(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function Qg(e){let n=D(Yg(e),{}).authInfo;return!n||typeof n!="object"?null:Ur(n)}function e_(e,t,n){let r=Xg(e,process.platform,t),o=Ba(e),s=Ga(o);if(za(s,r,n))return Ur({email:s?.email,authId:s?.auth_id});let i=Za(r),a=i.get(Vg)??null,c=i.get(Wg)??null;return Va(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),Ur({email:a,authId:c})}function qa(e=ln(),t=process.env,n=Date.now()){return Qg(e)??e_(e,t,n)}import{createHash as t_}from"node:crypto";import{resolve as n_}from"node:path";function M(e){return t_("sha256").update(e).digest("hex").slice(0,16)}function Dr(e){return M(n_(e))}function W(e,t){return`${e}\0${t}`}function Qa(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function gt(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
37
+ `);return M(n)}function o_(e,t,n="git_config",r=null){return M(`${e??""}|${t??""}|${r??""}|${n}`)}function s_(e){let t=null,n=null;for(let r of e.split(`
38
+ `)){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 i_(e,t=v){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return s_(n)}function a_(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 pe(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 c_(e=process.env){let t=A(e.EV_AI_HOOK_OPERATOR_EMAIL),n=A(e.EV_AI_HOOK_OPERATOR_LOGIN),r=pe(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=pe(o,null,"github",o);if(s)return s;let i=A(e.GITLAB_USER_LOGIN),a=A(e.GITLAB_USER_EMAIL),c=pe(A(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let u=A(e.BUILD_REQUESTEDFOREMAIL),l=pe(A(e.BUILD_REQUESTEDFOR),u,"azure_devops",u??A(e.BUILD_REQUESTEDFORID));if(l)return l;let f=A(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=pe(A(e.BUILDKITE_BUILD_CREATOR),f,"buildkite",f);if(m)return m;let d=A(e.BUILD_USER_EMAIL)??A(e.CHANGE_AUTHOR_EMAIL),_=pe(A(e.BUILD_USER)??A(e.CHANGE_AUTHOR),d,"jenkins",d??A(e.BUILD_USER_ID));if(_)return _;let h=A(e.CIRCLE_USERNAME),S=pe(h,null,"circleci",h);if(S)return S;let E=A(e.CODEBUILD_INITIATOR),y=pe(E,null,"codebuild",E);if(y)return y;let F=A(e.DRONE_COMMIT_AUTHOR_EMAIL),P=A(e.DRONE_COMMIT_AUTHOR),T=pe(P??A(e.DRONE_COMMIT_AUTHOR_NAME),F,"drone",F??P);if(T)return T;if(ec(e.CLAUDE_CODE_REMOTE)||ec(e.CURSOR_AGENT)){let H=A(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:H&&!G(null,H)?H:null,identity_source:"cloud"}}return null}function Hr(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 ec(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function u_(e,t,n){return e==="claude"?Ua(t):e==="cursor"?qa(t,n):e==="codex"?$a(n,t):null}async function Fr(e,t=v,n=process.env,r={}){let o=await i_(e,t),s=a_(n),i=Hr(o)?o:s&&Hr(s)?s:null,a=u_(r.runnerPlatform,r.home??r_(),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=c_(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:Hr(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 jr(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??v,s=e.env??process.env,i=await Fr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=o_(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),u=(n?nr(n):void 0)?.operator_identity_hash;if(!(r||u!==void 0&&u!==a||!u))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&vs(d,a,jt())}}}function $r(e){return e?!nr(e)?.operator_identity_hash:!0}function tc(e){return!0}import{existsSync as eS,readFileSync as tS}from"node:fs";import{homedir as cu}from"node:os";import{join as Ye,resolve as nS}from"node:path";import{basename as Vh,join as Je}from"node:path";import{dirname as fc,resolve as pn}from"node:path";import{existsSync as l_}from"node:fs";import{homedir as oc}from"node:os";import{relative as sc,resolve as ne,sep as ke}from"node:path";var d_=["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"],f_=["prompt","tool_input","tool_response","last_assistant_message","command"],p_=new Set;function m_(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return p_}}function ic(e){return ac(e)==="allowlist"}function ac(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 g_(e){let t={};for(let n of d_){let r=ie(e,n);r!==void 0&&(t[n]=r)}return t}function dn(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=ne(e),r=ne(t),o=sc(r,n);return!o||o==="."?".":o.startsWith(`..${ke}`)||o===".."||ne(r,o)!==n?null:o.split(ke).join("/")}function cc(e,t){let n=sc(ne(t),ne(e)).split(ke).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function uc(e){return typeof e!="string"||e.length===0?null:ne(e).split(ke).join("/")}function __(){let e=k("CURSOR_PROJECT_DIR");if(!e)return null;let t=ne(e);return l_(t)?t.split(ke).join("/"):null}function Br(e,t){return dn(e,t)!==null}function h_(e,t){let n=ne(t??oc(),".cursor").split(ke).join("/");return Br(e,n)}function S_(e,t,n){return t!==null&&Br(e,t)?!0:t!==null&&h_(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&Br(e,n.gitRoot)?!0:t===null}function lc(e,t){let n=uc(e.cwd);if(n!==null)return n;let r=ne(process.cwd()).split(ke).join("/"),o=__();return S_(r,o,t)?r:o??r}function Vr(e,t={}){return lc(e,t)}function Wr(e,t=oc()){let n=ne(t).split(ke).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function nc(e,t,n){let r=uc(n.launchCwd)??lc(t,n);e.cwd=Wr(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?dn(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var dc="\u2026[truncated]\u2026",Gr=Buffer.byteLength(dc,"utf8"),E_=8;function _t(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function rc(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function y_(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 R_(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=Gr)return rc(e,t);let r=t-Gr,o=Math.ceil(r/2),s=Math.floor(r/2);return`${rc(e,o)}${dc}${y_(e,s)}`}function zr(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)=>{zr(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||zr(o,[...t,r],n)}function C_(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 k_=256;function I_(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 A_(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=_t(e);if(s<=t)return;let i=[];zr(e,[],i),i.sort((l,f)=>f.bytes-l.bytes);let a=i.filter(l=>l.bytes>n);if(a.length===0)return;let c=I_(a,s-t,n),u=Math.max(n,Math.min(c,r-1));if(u>=r)return;r=u;for(let l of a)l.bytes>r&&C_(e,l.path,R_(l.value,r))}}function O_(e,t){let n=Math.max(0,t-k_),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:_t(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(_t(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function Kr(e,t){let n=_t(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,A_(r,t,Gr+E_),_t(r)>t&&O_(r,t),r}function b_(e,t,n){let r=m_(n.runnerEvent);for(let o of f_){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function fn(e,t,n={}){let r=ac(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,nc(s,e,n),Kr(s,zn)}let o=g_(e);return nc(o,e,n),r==="content"?(b_(o,e,n),Kr(o,zn)):Kr(o,Qo)}function x_(e){return typeof e=="string"&&e.length>0}function Jr(e){let t=pn(e.home),n=pn(e.launchCwd),r=e.gitRoot?pn(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&x_(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&&dn(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let u=fc(r);for(;;){let l=pn(u);if(l===t)break;let f=fc(l);if(f===l)break;if(e.hasProjectSpec(l)){s.push({scope:"parent",dir:l}),a=cc(l,n);break}u=f}}return{anchors:s,parentRel:a}}import{existsSync as pc,readdirSync as P_,realpathSync as T_}from"node:fs";import{basename as w_,dirname as N_,relative as M_,resolve as v_,sep as L_}from"node:path";var Yr=400,mn=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??ge}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=v_(t).split(L_).join("/");return Wr(r,this.home)}let n=M_(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${M(N_(t))}/${w_(t)}`:n}claimFile(t){try{let n=T_(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(!pc(t))return[];try{return P_(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(pc(t))return D(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 Xr,readFileSync as U_,statSync as D_}from"node:fs";import{basename as gc,join as ht,relative as _c}from"node:path";var Zr=100*1024,H_=4;function F_(e){return e.length<=Zr?e:`${e.slice(0,Zr-1)}\u2026`}function j_(e){try{let t=U_(e),n=t.toString("utf8");return{hash:M(t),length:t.length,text:F_(n)}}catch{return null}}var mc={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function $_(e){return e in mc?mc[e]:"UNSPECIFIED"}function gn(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=j_(t.absolutePath);if(!n)return!1;let r=t.name??gc(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=$_(t.kind);return s&&(o.trigger=s),e.push(o)}function K_(e,t,n){let r=_c(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?gc(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Me(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;qr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function qr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:u}=t;if(!(o>H_))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 d=ht(r,l.name,c);if(Xr(d)){let _=_c(n,ht(r,l.name)).replace(/\\/g,"/");gn(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:_||l.name});continue}qr(e,{walkRoot:n,currentDir:ht(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(l.isDirectory()){qr(e,{walkRoot:n,currentDir:ht(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(!l.isFile()||!u)continue;let f=l.name.toLowerCase();if(!u.some(d=>f.endsWith(d)))continue;let m=ht(r,l.name);gn(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:K_(n,m,!0)})}}function hc(e){for(let t of e)if(Xr(t))try{if(D_(t).size>0)return t}catch{continue}return e.find(t=>Xr(t))}import{existsSync as hh,readFileSync as Sh}from"node:fs";var _n=Qe(ze(),1);var B_="<omitted>",G_=["package_name","package_spec","package_version","package_version_source"],Sc=100,Ec=120,hn=[{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"}],yc=new Set(hn.map(e=>e.attr)),z_=["enabled","disabled"],V_=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],W_=new Set(["type","command","url","args","env","envVars","headers",...z_,...V_,...hn.map(e=>e.raw)]),J_=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",...G_,...yc,...[...yc].map(e=>`${e}_truncated`)]);function Rc(e,t){for(let n of t)W_.has(n)||J_.has(n)||(e[n]=B_)}var Y_=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,X_=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,Z_=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,q_=/^bearer(?:\s+|$)/i;function Sn(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Cc(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Qr(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=Sn(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function ve(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Q_(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,_n.launchContainsCredentials)({kind:"url",url:e})||(0,_n.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=Et([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,_n.launchContainsCredentials)({kind:"url",url:r}):!0)}function kc(e,t,n){Q_(t,n)&&(e.launch_had_credentials=!0)}function eh(e){return Z_.test(e)||q_.test(e)?"<redacted>":e.includes("://")?ve(e):e}function Ic(e){if(/^https?:\/\//i.test(e))return ve(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Ic(e.slice(t+1))}`:eh(e)}function th(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return Y_.test(t)||X_.test(t)}function Et(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(th(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Ic(r))}return t}function nh(e){let t=Cc(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ec?r.slice(0,Ec):r))].sort();if(n.length!==0)return n.length>Sc?{names:n.slice(0,Sc),truncated:!0}:{names:n,truncated:!1}}function rh(e){let t=Sn(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 Ac(e,t){let n=new Set;for(let{raw:r,attr:o}of hn){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=nh(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function Oc(e,t){let n=Sn(e),r={transport:t};if(!n)return r;Rc(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=Cc(n.args);a&&(r.command_or_url=ve(a));let u=Et(c);u.length>0&&(r.args=u),kc(r,a,c);let l=rh(n.env_http_headers),f=[...new Set([...Qr(n.env),...Qr(n.envVars),...Qr(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();f.length>0&&(r.env_var_names=f),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let h of["headers","http_headers","env_http_headers"])if(n[h]!==void 0&&n[h]!==null){r.headers_present=!0;break}let m=typeof n.auth=="string"?n.auth:void 0;m&&(r.auth=m);let d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let _=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return _&&(r.default_tools_approval_mode=_),Ac(r,n),r}function bc(e){let t=Sn(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function no(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return M(JSON.stringify({name:e,attributes:r,enabled:n}))}function We(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function St(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 to(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function eo(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=We(n[1]);return r.length>0?r:void 0}function oh(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],We(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
39
+ ${e}`);return s?.[1]&&r(s[1]),n}function xc(e){return to(e,"enabled")===!1?!1:to(e,"disabled")!==!0}function sh(e,t){let n={};for(let{raw:r,attr:o}of hn){if(o==="auto_approve"){let i=to(t,r);if(i!==void 0){n[r]=i;continue}}let s=St(t,r);s.length>0&&(n[r]=s)}Ac(e,n)}var ih=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,ah=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function ch(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
40
+ `)){let s=ih.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(ah))o[1]&&t.add(o[1]);return[...t]}function Pc(e,t){let n={transport:t};Rc(n,ch(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?We(r[1]??""):void 0,i=o?We(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=St(e,"args");a&&(n.command_or_url=ve(a));let u=Et(c);u.length>0&&(n.args=u),kc(n,a,c);let l=new Set;for(let E of e.split(`
41
+ `)){let y=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&l.add(y[1])}let f=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(f?.[1])for(let E of f[1].split(",")){let y=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&l.add(y[1])}let m=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
42
+ ${e}`);if(m?.[1])for(let E of m[1].split(`
43
+ `)){let y=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&l.add(y[1])}for(let E of St(e,"env_vars"))l.add(E);let d=oh(e,"env_http_headers");for(let[,E]of d)E.length>0&&l.add(E);let _=eo(e,"bearer_token_env_var");_&&(l.add(_),n.bearer_token_env_var=_),l.size>0&&(n.env_var_names=[...l].sort()),d.length>0&&(n.env_http_header_names=[...new Set(d.map(([E])=>E))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let h=eo(e,"auth");h&&(n.auth=h);let S=eo(e,"default_tools_approval_mode");return S&&(n.default_tools_approval_mode=S),sh(n,e),n}var Ie=Qe(ze(),1);import{createHash as fh}from"node:crypto";import{join as yt}from"node:path";var uh=300,lh=256;function Tc(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 wc(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function dh(e){return wc(e,uh)}function Nc(e,t){let n=Tc(e.trim(),t),r=En(n);if(r.length===0)return"";let[o,...s]=r,i=ve(o),a=Et(s);return dh([i,...a].join(" "))}function Mc(e,t){if(typeof e!="string")return null;let n=Tc(e.trim(),t),r=En(n)[0];if(!r)return null;let o=ve(r);return o.length===0?null:wc(o,lh)}function ph(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
44
+ `);return fh("sha512").update(t).digest("hex").slice(0,16)}function mh(e){let t=process.platform==="win32"?yt(k("LOCALAPPDATA")??e,"npm-cache"):yt(e,".npm"),n=k("npm_config_cache")??k("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function vc(e){return typeof e=="string"&&e.length>0&&e.length<=Ie.PACKAGE_FIELD_MAX?e:null}function gh(e,t,n){let r=ph(e);for(let o of mh(n)){let s=yt(o,"_npx",r),i=D(yt(s,"node_modules",...t.split("/"),"package.json"),{}),a=vc(i.version);if(a!==null)return a;let c=D(yt(s,"package-lock.json"),{}),u=vc(c.packages?.[`node_modules/${t}`]?.version);if(u!==null)return u}return null}function _h(e){return e.length<=Ie.PACKAGE_FIELD_MAX?e:`${e.slice(0,Ie.PACKAGE_FIELD_MAX-1)}\u2026`}function ro(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,Ie.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,Ie.packageNameFromSpec)(o);if(s===null)return null;let i=gh(r,s,n);return{package_name:s,package_spec:_h(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function Lc(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=En(e.trim());return n===void 0?null:ro(n,r,t)}function yn(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 ro(typeof n.command=="string"?n.command:null,r,t)}function Uc(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:ro(We(n[1]??""),St(e,"args"),t)}function Eh(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 Dc(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=Eh(a),u=Oc(a,c);Object.assign(u,yn(a,e.home)??{});let l=bc(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:no(i,u,l),origin:n,enabled:l,attributes:u})}}function Hc(e,t,n){if(!hh(t)||!e.claimFile(t))return;let r;try{r=Sh(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),f="unknown";/^\s*url\s*=/m.test(l)?f="http":/^\s*command\s*=/m.test(l)&&(f="stdio");let m=Pc(l,f);Object.assign(m,Uc(l,e.home)??{});let d=xc(l);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:no(a,m,d),origin:n,enabled:d,attributes:m})}}import{existsSync as Ch,readdirSync as kh}from"node:fs";import{join as B}from"node:path";function yh(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 Rh(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 oo(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 u of Rh(c)){if(e.truncated)return;let l=u.command??u.bash??u.prompt??u.powershell??c.powershell??"",f=yh({type:u.type??c.type,command:u.command??c.command,bash:u.bash??c.bash,powershell:u.powershell??c.powershell,prompt:u.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",d=M(l),_=m?`${s}:${m}:${f}:${d}`:`${s}:${f}:${d}`,h=`${s}|${m}|${f}|${l}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:M(h),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:f,action_hash:d,...f!=="prompt"&&l.trim()?{command:Nc(l,e.home)}:{}}})}}}function so(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||oo(e,t,r.hooks,n)}var Fc=50;function io(e,t,n,r){if(!Ch(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(Fc,()=>{Me(e,{dir:B(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Me(e,{dir:B(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Me(e,{dir:B(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});so(e,B(t,"hooks","hooks.json"),n),so(e,B(t,"hooks.json"),n);let i=e.components.length-o,a=s>=Fc;return{componentCount:i,expandTruncated:a}}function ao(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 jc(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]??{},f=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof l.version=="string"?l.version:"",_=typeof l.scope=="string"?l.scope:"user",h=`plugin:${a}`,S=0,E=!1;for(let y of u)if(typeof y.installPath=="string"&&y.installPath.length>0){let F=io(e,y.installPath,h,f);S+=F.componentCount,E=E||F.expandTruncated}ao(e,{pluginKey:a,rowPath:i,enabled:f,scope:_,version:d||void 0,marketplace:m||void 0,componentCount:S,expandTruncated:E,contentHash:M(`${a}|${d}|${_}|${f}|${S}`)})}}function Ih(e){let t=e,n="";try{let r=kh(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 Ah=/^\d+$/;function Oh(e){let t=e.filter(n=>!Ah.test(n.pluginId));return t.length>0?t:e}function $c(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:f}=io(e,c,u,!0);ao(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:l,expandTruncated:f,contentHash:M(`${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}=Ih(c);i.push({pluginId:a.name,installPath:u,version:l})}for(let a of Oh(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,u=`plugin:${c}`,{componentCount:l,expandTruncated:f}=io(e,a.installPath,u,!0);ao(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:l,expandTruncated:f,contentHash:M(`${c}|${a.version}|${l}`)})}}}import{existsSync as Ph}from"node:fs";var bh=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,co="<path>",xh=new RegExp(`${co}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Rn(e){let t=e.replace(bh,co).replace(xh,co);return t.length>200?`${t.slice(0,200)}...`:t}var Kc=200,Bc=200,uo=16*1024,Gc=6,Th=new Set(["permissions","sandbox","enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers","disableAllHooks","disableAutoMode","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","strictPluginOnlyCustomization","disableSideloadFlags","forceLoginMethod","forceLoginOrgUUID"]),wh=new Set(["type","additionalReadwritePaths","additionalReadonlyPaths","disableTmpWrite","enableSharedBuildCache","networkPolicy"]),Nh=new Set(["terminalAllowlist","mcpAllowlist","autoRun"]),Mh=new Set(["permissions"]),vh={claude:Th,cursor_sandbox:wh,cursor_permissions:Nh,cursor_cli:Mh},Lh=new Set(["allow","deny","ask"]);function Ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cn(e){return e.replace(/\\/g,"/")}function lo(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>lo(r)).join(",")}]`;let t=e;return`{${Object.keys(t).filter(r=>t[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${lo(t[r])}`).join(",")}}`}function Uh(e){return M(`${lo(e)}|settings1`)}function Yc(e){let t=Cn(e);if(t.endsWith(".claude/settings.json")||t.endsWith(".claude/settings.local.json"))return"claude";if(t.endsWith(".cursor/sandbox.json"))return"cursor_sandbox";if(t.endsWith(".cursor/permissions.json"))return"cursor_permissions";if(t.endsWith(".cursor/cli-config.json")||t.endsWith(".cursor/cli.json"))return"cursor_cli"}function Xc(e,t){if(e!=="claude")return{};let n=Cn(t);return n.endsWith("/.claude/remote-settings.json")?{profile:"claude",managedSource:"server"}:n.includes("/managed-settings.d/")&&n.endsWith(".json")?{profile:"claude",managedSource:"file_dropin"}:n.endsWith("/managed-settings.json")?{profile:"claude",managedSource:"file"}:{profile:"claude"}}function Zc(e){let t=Cn(e).replace(/\/+$/,"");return t.length<=1?"":t}function qc(e){return/^[A-Za-z]:/.test(e)||e.includes("\\")}function Dh(e,t){let n=Cn(e);if(n==="~"||n.startsWith("~/"))return n;let r=Zc(t);if(!r)return n;let o=n.slice(0,r.length);if(!(qc(t)?o.toLowerCase()===r.toLowerCase():o===r))return n;let i=n.slice(r.length);return i===""?"~":i.startsWith("/")?`~${i}`:n}var zc=new Map;function Hh(e){let t=zc.get(e);if(t!==void 0)return t;let n=Zc(e),r=null;if(n){let o=n.split("/").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");r=new RegExp(`(?<![\\w.-])${o}(?![\\w.-])`,qc(e)?"gi":"g")}return zc.set(e,r),r}function Fh(e,t){let n=Hh(t);return n?e.replace(n,"~"):e}function Vc(e,t){return e.length<=Bc?e:(t.truncated=!0,e.slice(0,Bc))}function Qc(e,t){return e.length<=Kc?e:(t.truncated=!0,e.slice(0,Kc))}function L(e,t,n,r){if(typeof e=="string"){if(t==="path")return Vc(Dh(e,n),r);let o=t==="rule"?Rn(e):e;return Vc(Fh(o,n),r)}if(typeof e=="number"||typeof e=="boolean"||e===null)return typeof e=="number"&&!Number.isFinite(e)?void 0:e;if(Array.isArray(e)){let o=Qc(e,r),s=[];for(let i of o){let a=L(i,t,n,r);a!==void 0&&s.push(a)}return s}if(Ae(e)){let o={};for(let[s,i]of Object.entries(e)){let a=L(i,t,n,r);a!==void 0&&(o[s]=a)}return o}}function Wc(e,t,n){if(!Ae(e))return L(e,"plain",t,n);let r={};for(let[o,s]of Object.entries(e)){let i="plain";Lh.has(o)?i="rule":o==="additionalDirectories"&&(i="path");let a=L(s,i,t,n);a!==void 0&&(r[o]=a)}return r}function jh(e,t,n){if(!Ae(e))return L(e,"plain",t,n);let r={};for(let[o,s]of Object.entries(e)){if(o==="files"&&Array.isArray(s)){let a=Qc(s,n);r[o]=a.map(c=>{if(!Ae(c))return L(c,"plain",t,n);let u={};for(let[l,f]of Object.entries(c)){let d=L(f,l==="path"?"path":"plain",t,n);d!==void 0&&(u[l]=d)}return u});continue}let i=L(s,"plain",t,n);i!==void 0&&(r[o]=i)}return r}function $h(e,t,n){if(!Ae(e))return L(e,"plain",t,n);let r={};for(let[o,s]of Object.entries(e)){let a=L(s,o==="allowUnixSockets"?"path":"plain",t,n);a!==void 0&&(r[o]=a)}return r}function Kh(e,t,n){if(!Ae(e))return L(e,"plain",t,n);let r={};for(let[o,s]of Object.entries(e)){let i;o==="excludedCommands"?i=L(s,"rule",t,n):o==="filesystem"?i=L(s,"path",t,n):o==="network"?i=$h(s,t,n):o==="credentials"?i=jh(s,t,n):i=L(s,"plain",t,n),i!==void 0&&(r[o]=i)}return r}function Bh(e,t,n,r,o){return n==="claude"?e==="permissions"?Wc(t,r,o):e==="sandbox"?Kh(t,r,o):L(t,"plain",r,o):n==="cursor_sandbox"?e==="additionalReadwritePaths"||e==="additionalReadonlyPaths"?L(t,"path",r,o):L(t,"plain",r,o):n==="cursor_permissions"?e==="terminalAllowlist"||e==="mcpAllowlist"?L(t,"rule",r,o):L(t,"plain",r,o):e==="permissions"?Wc(t,r,o):L(t,"plain",r,o)}function Rt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function fo(e,t){return e?`${e}.${t}`:t}function po(e,t,n,r){if(Array.isArray(e)){for(let o=e.length-1;o>=0;o-=1){let s=e[o];s!==null&&typeof s=="object"&&(t+1>=Gc?(e.splice(o,1),r.add(n)):po(s,t+1,n,r))}return}if(!(e===null||typeof e!="object"))for(let[o,s]of Object.entries(e))s!==null&&typeof s=="object"&&(t+1>=Gc?(delete e[o],r.add(fo(n,o))):po(s,t+1,fo(n,o),r))}function eu(e,t,n){if(Array.isArray(e)){e.length>0&&n.push({path:t,items:e,bytes:Rt(e)});return}if(!(e===null||typeof e!="object"))for(let[r,o]of Object.entries(e))eu(o,fo(t,r),n)}function Gh(e,t,n){let r=Rt(e);if(r<=uo)return;t.truncated=!0;let o=[];for(eu(e,"",o);r>uo;){let s;for(let c of o)c.items.length>0&&(!s||c.bytes>s.bytes)&&(s=c);if(!s)break;let i=s.items.pop(),a=Rt(i)+(s.items.length>0?1:0);s.bytes-=a,r-=a,n.add(s.path)}for(;Rt(e)>uo;){let s,i=-1;for(let[a,c]of Object.entries(e)){let u=Rt(c);u>i&&(s=a,i=u)}if(s===void 0)break;delete e[s],n.add(s)}}function zh(e,t,n){let r=vh[t],o={truncated:!1},s={},i=[];for(let c of Object.keys(e)){if(!r.has(c)){i.push(c);continue}let u=Bh(c,e[c],t,n,o);u!==void 0&&(s[c]=u)}i.sort();let a=new Set;return po(s,1,"",a),a.size>0&&(o.truncated=!0),Gh(s,o,a),{settings:s,keys_omitted:i,truncated:o.truncated,trimmed_paths:[...a].sort()}}function Jc(e,t){let n={kind:t.kind,name:"settings",path:e.componentPath(t.absPath),origin:t.origin,enabled:!0,content_hash:Uh(t.attributes),attributes:t.attributes};e.push(n)}function mo(e,t,n,r){if(!e.claimFile(t)||!Ph(t))return;let o=fs(t);if(!o.ok||!Ae(o.value)){if(r.profile){let u=!o.ok&&o.reason==="read"?"read_error":"parse_error",l={profile:r.profile,[u]:!0};r.managedSource&&(l.managed_source=r.managedSource),Jc(e,{kind:r.kind,absPath:t,origin:n,attributes:l})}return}let s=o.value,i=s.hooks;if(Ae(i)&&oo(e,t,i,n),!r.profile)return;let a=zh(s,r.profile,e.home),c={profile:r.profile,settings:a.settings,keys_omitted:a.keys_omitted};a.truncated&&(c.truncated=!0),a.trimmed_paths.length>0&&(c.trimmed_paths=a.trimmed_paths),r.managedSource&&(c.managed_source=r.managedSource),Jc(e,{kind:r.kind,absPath:t,origin:n,attributes:c})}function Wh(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Me(e,{dir:Je(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Me(e,{dir:Je(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=hc(i.map(c=>Je(r,c)));a&&gn(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:Vh(a)})}for(let i of Ri(n))mo(e,Je(r,i),o,{kind:"SETTINGS",profile:Yc(i)});for(let i of n.mcpJson??[])Dc(e,Je(r,i),o);for(let i of n.mcpToml??[])Hc(e,Je(r,i),o);if(s){if(n.managed){for(let i of Ft(n.managed,process.platform,e.home))if(i.toLowerCase().endsWith(".json")){let a=Xc(n.managed,i);mo(e,i,o,{kind:"MANAGED_SETTINGS",...a})}}n.plugins==="claude"?jc(e):n.plugins==="cursor"&&$c(e)}}function tu(e,t){try{let n=new mn(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)Wh(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 go(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=tu(t,{layouts:Object.values($e),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:ge,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(Ee),u=Jr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:l=>ki(c,l)});i=u.parentRel;for(let l of u.anchors){let f=Dr(l.dir);if(o!==void 0&&!o(l.scope,f))continue;let m=tu(t,{layouts:c,levelDir:l.dir,origin:l.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Yr,scopeRef:f});m&&(r[l.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function _o(e,t,n={}){let r=n.truncated===!0,o=gt(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 f=W(l.path,l.name);c[f]!==l.content_hash&&a.push(l)}let u=[];if(!r){for(let l of Object.keys(c))if(!s.has(l)){let f=Qa(l);f&&u.push(f)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:u,unchanged:a.length===0&&u.length===0}}var ru=2*1024*1024,Jh=new Set(["HOOK","MCP_SERVER","PLUGIN","SETTINGS","MANAGED_SETTINGS"]);function ho(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 So(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 nu(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function ou(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Eo(e,t=ru){let n=[],r=[];for(let l of e)Jh.has(l.kind)?n.push(l):r.push(l);r.sort((l,f)=>(l.text?.length??0)-(f.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,u=[];for(let l of o){let f=s.length>0?1:0,m=nu(l)+f;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 d=ou(l),_=nu(d)+f;if(i+_<=t){s.push(d),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:u}}function yo(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:ou(n))}var Yh=["user","cwd","repo","parent"];function Ro(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let P of Yh){let T=t.scopes[P];if(!T)continue;let H=n(P,T.scopeRef),j=H.components,J=_o(T.components,j,{forceFull:j===void 0,truncated:T.truncated}),Oe=new Set(H.textHashes),$=ho(T.components,J.upserts,Oe),U=yo([...J.upserts,...$],Oe);s.push({scope:P,walk:T,delta:J,outgoing:U,outgoingKeys:new Set(U.map(C=>W(C.path,C.name))),deliveredTextHashes:Oe,cachedComponents:j})}let i=s.flatMap(P=>P.outgoing),a=Eo(i,o),c=new Set(a.components.map(P=>W(P.path,P.name))),u=[],l=[],f=[],m=[],d=[],_=[],h=[];for(let P of s){let{scope:T,walk:H,delta:j}=P;_.push(...H.components),u.push(T);let J=a.components.filter(C=>P.outgoingKeys.has(W(C.path,C.name))),Oe=[...P.outgoingKeys].some(C=>!c.has(C)),$=j.truncated||Oe;$?f.push(T):j.full&&l.push(T),m.push(...J),!j.full&&!$&&d.push(...j.removed);let U=j.full?{}:{...P.cachedComponents??{}};if(!$)for(let C of j.removed)delete U[W(C.path,C.name)];for(let C of J)U[W(C.path,C.name)]=C.content_hash;h.push({scope:T,scopeRef:H.scopeRef,components:U,textHashes:So(P.deliveredTextHashes,J.filter(C=>C.text!==void 0).map(C=>C.content_hash),H.components),collectedAtMs:r,included:J.length>0||j.removed.length>0&&!$||j.full})}let S={user_spec_hash:gt(_),user_spec_count:_.length,user_spec_truncated:f.length>0};u.length>0&&(S.user_spec_scopes=u,S.user_spec_full_scopes=l,S.user_spec_truncated_scopes=f,S.user_spec_cwd_in_git_repo=t.cwdInGitRepo),l.length>0&&l.length===u.length&&(S.user_spec_full=!0),m.length>0&&(S.user_spec=m),d.length>0&&(S.user_spec_removed=d),a.textDeferredCount>0&&(S.user_spec_text_deferred=a.textDeferredCount);let E=t.scopes.cwd;E&&(S.user_spec_cwd_scope_ref=E.scopeRef);let y=t.scopes.repo;y&&(S.user_spec_repo_scope_ref=y.scopeRef);let F=t.scopes.parent;return F&&(S.user_spec_parent_scope_ref=F.scopeRef,t.parentRel&&(S.user_spec_parent_rel=t.parentRel)),{fields:S,scopes:h}}var kt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function kn(e){return e==="cwd"||e==="repo"||e==="parent"}function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Co(e){return!Ct(e)||!Ct(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 su(e){return Xh(e)}function iu(e){return Zh(e)}function au(e){return qh(e)}function Xh(e){if(!Ct(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function Zh(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function ko(e,t){if(!Ct(e))return;let n=e[t];return Co(n)?n:void 0}function qh(e){if(!Ct(e))return{};let t={};for(let[n,r]of Object.entries(e))Co(r)&&(t[n]=r);return t}function Io(e,t=20){let n=[];for(let[r,o]of Object.entries(e))Co(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 rS=["allow","deny","ask"];function An(e){let t=D(e,{}),n=[];for(let r of rS)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Rn(o),mode:r});return{model:t.model??"",permissionKeys:n}}function oS(e){let{serverManaged:t,fileBased:n}=Wn(process.platform,e),r=An(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=An(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function sS(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 iS=10,aS="self-config-cache.json",uu=4;function Xe(){return k("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function cS(){return k("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function uS(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=tt}var lS={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function dS(e,t=v){let n=lS[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(`
45
+ `)[0]??"").trim();return a||r(o+1)};return r(0)}function fS(e=cu()){return Ye(e,".ev-ai","agent-hook",aS)}function pS(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
46
+ `);return M(n)}function In(e,t,n=!1){let r=pS(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 Ao(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>Ye(e,a)),...n]){let a=nS(i);if(s.has(a))continue;s.add(a);let c=Zn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function mS(e){return eS(e)?z(tS(e,"utf8"),{}):{}}function gS(e,t){try{Q(e,`${JSON.stringify(t)}
47
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);p(`WARN: self-config cache write failed open: ${r}`)}}function _S(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(kn(t))return ko(e[kt[t]],n)?.collected_at_ms}function hS(e,t,n){if(t==="user")return{components:su(e.user_spec_components),textHashes:iu(e.user_spec_text_hashes)};if(!kn(t))return{components:void 0,textHashes:[]};let r=ko(e[kt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function SS(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=uu,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(!kn(s.scope))continue;let i=kt[s.scope],a=au(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]=Io(a)}}return o}async function lu(e,t=process.cwd(),n=cu(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await dS(e),a="",c=[];if(o){let $=oS(n),U=An(Ye(n,".claude/settings.json")),C=An(Ye(t,".claude/settings.local.json"));a=$.model||C.model||U.model,c=sS([...$.permissionKeys,...U.permissionKeys,...C.permissionKeys]).slice(0,200)}let u={present:!1,size:0},l=$=>{let U=[],C=!1;for(let re of $){let xt=ps(Ye(n,re));if(U=U.concat(xt.entries),C=C||xt.truncated,U.length>=ge){U=U.slice(0,ge),C=!0;break}}return{entries:U,truncated:C}},f=fS(n),m=mS(f),d=m[e]??{},_=(d.send_count??0)+1,h=_>0&&_%iS===0,S=$=>h?void 0:d[$],E=l(Re.skills),y=l(Re.subagents),F=l(Re.commands),P=l(Re.rules),T={skills:In(E.entries,S("skills"),E.truncated),subagents:In(y.entries,S("subagents"),y.truncated),commands:In(F.entries,S("commands"),F.truncated),rules:In(P.entries,S("rules"),P.truncated)},H={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:T.skills,subagents:T.subagents,commands:T.commands,rules:T.rules,memory:Ao(n,Re.memory),settings:Ao(n,Re.settings,Ii(n)),mcp:Ao(n,Re.mcp)},local_settings:o?Zn(Ye(t,".claude/settings.local.json")):u},j=null,J=r.nowMs??Date.now();if(!Xe()&&!r.deferUserSpec){let $=d.user_spec_layout_version!==uu,U=go(e,n,{launchCwd:cS()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(C,re)=>$||uS(_S(d,C,re),J)});if(Object.keys(U.scopes).length>0){let C=Ro({collected:U,cacheFor:(re,xt)=>$?{components:void 0,textHashes:[]}:hS(d,re,xt),nowMs:J});Object.assign(H,C.fields),j={hash:C.fields.user_spec_hash,home:C.scopes.find(re=>re.scope==="user")??null,project:C.scopes.filter(re=>re.scope!=="user")}}}let Oe=SS(d,T,_,j);return{config:H,commit:()=>{m[e]=Oe,gS(f,m)}}}import{homedir as US}from"node:os";import{join as pu}from"node:path";function Le(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{join as On}from"node:path";function ES(e){return On(e,".ev-ai","agent-hook","js","signed-v1")}function yS(e){return On(ES(e),"scopes")}function du(e,t){return On(yS(e),t)}function fu(e){return On(e,"attempts")}function Oo(e){return String(e).padStart(10,"0")}var RS=/^(\d{10})$/,CS=/^(\d{10})\.done$/,kS=/^[0-9a-f]{128}$/,IS=64;async function hu(e,t,n=!1){let r=fu(t),o=await hi(e,r),s=new Map,i=new Map,a=mu(o,RS),c=mu(o,CS),u=async m=>{let d=await _u(e,pu(r,AS(m)));return d&&s.set(m,{record:bS(d.value),mtimeMs:d.mtimeMs}),d!==void 0},l=async m=>{let d=xS((await _u(e,pu(r,OS(m))))?.value);return d&&i.set(m,d),d!==void 0};if(!n)return await Promise.all([...a.map(u),...c.map(l)]),{claims:s,dones:i};await Promise.all([gu(a,u),gu(c,l)]);let f=It(s);return f<It(i)&&c.includes(f)&&await l(f),{claims:s,dones:i}}function mu(e,t){return e.flatMap(n=>{let r=t.exec(n);return r?[Number(r[1])]:[]})}async function gu(e,t){for(let n of[...e].sort((r,o)=>o-r))if(await t(n))return}function It(e){let t=0;for(let n of e.keys())n>t&&(t=n);return t}function Su(e){if(e.record!=="empty"&&e.record.started_at){let t=Date.parse(e.record.started_at);if(Number.isFinite(t))return t}return e.mtimeMs}function AS(e){return Oo(e)}function OS(e){return`${Oo(e)}.done`}async function _u(e,t){let n;try{n=await e.stat(t)}catch(o){if(pr(o))return;throw o}let r=n.mtimeMs;if(n.size===0||n.size>Ln)return{mtimeMs:r};try{let o=await e.readFile(t);return o.byteLength===0||o.byteLength>Ln?{mtimeMs:r}:{mtimeMs:r,value:JSON.parse(o.toString("utf8"))}}catch{return{mtimeMs:r}}}function bS(e){if(!Le(e))return"empty";let t={};return typeof e.started_at=="string"&&(t.started_at=e.started_at),(e.owner==="bootstrap"||e.owner==="refresh")&&(t.owner=e.owner),e.resync===!0&&(t.resync=!0),t}function xS(e){if(!Le(e))return;let t=e;if(typeof t.finished_at!="string"||typeof t.outcome!="string"||typeof t.interval_s!="number"||!Number.isFinite(t.interval_s))return;let n=PS(t.selection);if(n)return{finished_at:t.finished_at,interval_s:t.interval_s,outcome:t.outcome,selection:n}}function PS(e){if(!Le(e))return;let t=e;if(t.kind==="bundled")return t.why==="server"||t.why==="bootstrap_failed"?{kind:"bundled",why:t.why}:void 0;if(t.kind==="cached"&&typeof t.digest=="string"&&kS.test(t.digest)&&typeof t.version=="string"&&t.version.length>0&&typeof t.sha512=="string"&&TS(t.sha512)===t.digest)return{kind:"cached",digest:t.digest,version:t.version,sha512:t.sha512}}function TS(e){if(e.length===0||!/^[A-Za-z0-9+/]+=*$/.test(e))return;let t=Buffer.from(e,"base64");if(!(t.byteLength!==IS||t.toString("base64")!==e))return t.toString("hex")}function vS(e){return e==="bootstrap"?3e3:6e4}function LS(e,t){let n=It(e.claims);if(n===0)return;let r=It(e.dones),o=e.claims.get(n),s=e.dones.get(n);if(o&&!s){let a=Su(o),c=o.record==="empty"?void 0:o.record.owner,u=vS(c)+3e4;if(t-a>u)return{n,latest_claim:n,outcome:"incomplete",finished_at:null,selection_version:Eu(e.dones.get(r)?.selection)}}if(r===0)return;let i=e.dones.get(r);if(i)return{n:r,latest_claim:n,outcome:i.outcome,finished_at:i.finished_at,selection_version:Eu(i.selection)}}async function yu(e,t,n){try{let r=await hu(Si(),du(e,t),!0);return LS(r,n)}catch{return}}function Eu(e){return e?.kind==="cached"&&typeof e.version=="string"?e.version:null}async function Ru(e=US()){let t=vr()?.launcherScope;if(!t)return{};let n=await yu(e,t,Date.now());return n?{launcher_scope:t,launcher_attempt:n}:{launcher_scope:t}}function Ze(e,t,n){let r={installation_id:n.installationId};n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId);let o={schema_version:me,event:e,timestamp:jt(),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},s=vr();return s&&(o.launcher_version=s.launcherVersion,o.hook_source=s.hookSource,o.hook_fallback_reason=s.fallbackReason??null,o.launcher_scope_match=wa(n.collectorUrl,s.launcherScope)),e==="session_start"&&(n.launcher_scope&&(o.launcher_scope=n.launcher_scope),n.launcher_attempt&&(o.launcher_attempt=n.launcher_attempt)),o}import{existsSync as Cu}from"node:fs";import{spawn as ku}from"node:child_process";import{fileURLToPath as HS}from"node:url";import{gzipSync as DS}from"node:zlib";function bo(e){return k("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<es?{body:e}:{body:DS(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function bn(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function xo(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var At="__post",xn="__work";async function FS(e,t,n={}){if(Xe())return e;let r=await Fr(n.gitRoot??process.cwd(),v,process.env,{runnerPlatform:t,home:n.home}),o=Le(e.self_config)?e.self_config:{};return{...e,self_config:{...o,runner_platform:typeof o.runner_platform=="string"?o.runner_platform:t,operator:r}}}function jS(e,t){let n=Le(e.payload)?Object.keys(e.payload):[],r=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:r,payload_keys:n})}function Iu(e){switch(e){case"session_start":return Xo;case"session_end":return Zo;case"tool_invoked":case"skill_invoked":return Bn;default:return Bn}}function $S(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
48
+ ${n}`}function Au(e,t=[],n=process.execPath,r=import.meta.url,o=Cu){if(Ut(n))return{command:n,args:[e,...t]};let s=HS(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function KS(e=process.execPath,t=import.meta.url,n=Cu){return Au(At,[],e,t,n)}function BS(e){let t=e.indexOf(`
49
+ `);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 Pn(e,t=fetch){let n=await e(),r=BS(n);if(!r)return;let{meta:o,body:s}=r,i=bo(s),a=bn(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function GS(e,t,n,r=fetch){let o=Iu(e),s=bo(t),i=bn(s.contentEncoding),a=xo(s.body);p(`POST event=${e} url=${Lt(n)} size=${a} encoding=${s.contentEncoding??"identity"} platform=${process.platform}`);let c=Date.now();try{let u=await r(n,{method:"POST",headers:i,body:s.body,signal:AbortSignal.timeout(o)});if(!u.ok&&s.contentEncoding==="gzip"&&(u.status===400||u.status===415)){try{await u.text()}catch{}p(`POST gzip rejected http=${u.status} \u2014 retrying uncompressed`),u=await r(n,{method:"POST",headers:bn(),body:t,signal:AbortSignal.timeout(o)})}let l=Date.now()-c;if(u.ok)return p(`POST outcome=ok elapsed_ms=${l} http=${u.status}`),!0;let f=(await u.text()).slice(0,200).replace(/[\n\r]/g,"");return p(`POST outcome=fail elapsed_ms=${l} http=${u.status} body=${f}`),!1}catch(u){let l=Date.now()-c,f=u instanceof Error?u.message:String(u);return p(`POST outcome=fail elapsed_ms=${l} http=000 body=${f}`),!1}}async function Ou(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){p(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},qo),u=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>u()),s.stdin.once("error",()=>u())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return p(`WARN: ${o} spawn failed open: ${i}`),null}}async function zS(e,t,n,r=ku,o=KS){let s=Iu(e),i=$S(n,s,t),{command:a,args:c}=o();return Ou(a,c,i,r,"detached post")}async function bu(e,t,n=ku,r=Au){let{command:o,args:s}=r(xn,t);return Ou(o,s,e,n,"detached work")}async function qe(e,t,n,r,o,s,i){if(!o)return p("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!vt(o))return p(`WARN: collector URL blocked (https required): ${Lt(o)}`),!1;let a=await FS(t,n.runnerPlatform,i),c=r(e,a,{...n,collectorUrl:o});s!==void 0&&(c.build_ms=Math.max(0,Date.now()-s));let u=JSON.stringify(c),l=`${u}
50
+ `,f=k("EV_AI_HOOK_DEBUG");f==="full"?p(`DEBUG envelope=${u}`):f==="1"&&p(`DEBUG summary=${jS(c,xo(l))}`);let m=process.argv.includes(xn),d=k("EV_AI_HOOK_SYNC")==="1";return on(n.runnerEvent,n.runnerPlatform)||m||d?GS(e,l,o):(await zS(e,l,o),!1)}import{createReadStream as VS}from"node:fs";import{stat as WS}from"node:fs/promises";import{basename as JS,resolve as YS}from"node:path";import{createInterface as XS}from"node:readline";var ZS=1024*1024;function qS(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&JS(t).endsWith(".jsonl")}async function xu(e){if(!e||!qS(e))return null;try{let t=YS(e),n=await WS(t);if(!n.isFile())return null;let r=Math.max(0,n.size-ZS),o=[],s=XS({input:VS(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 Tn(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function bt(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function To(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function wu(e){let t=Date.now();await lE(e);let{gitRoot:n}=e.manifest;await No(e,n);let r=To(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:fn(e.hookInput,e.manifest.manifest,r),envelopeFields:Tn(e),launchCwd:Vr(e.hookInput,r),home:eE()}}function Pu(e){try{return V(QS(e))}catch{return null}}function Nu(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function Tu(e,t){let n=e.replaceAll("\\","/");if(!Nu(n))return null;let r=V(e),o=V(t),s=Pu(e)??r,i=Pu(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function Mu(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=Tu(e,t)??(Nu(r)?null:r),i=Tu(e,n);return{repositorySourcePath:s,userSourcePath:i}}function Po(e,t,n,r,o){return vu(e,Mu(n,t.gitRoot,t.home),r,o)}function vu(e,{repositorySourcePath:t,userSourcePath:n},r,o){let s=t??n,i=s===null?null:o(s),a=i!==null&&s!==null?tE({installableKind:r,sourcePath:s,nativeKey:i,inRepository:t!==null,platformAgentId:e.platformAgentId,installationId:e.manifest.installationId}):void 0;return{sourcePath:s,nativeKey:i,componentReference:a}}function tE(e){try{let t=e.inRepository?oE(e.platformAgentId,e.sourcePath):(0,O.installationRootExternalKey)(e.installationId,(0,O.userConfigRootFromPath)(e.sourcePath));return t?(0,O.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function wo(e,t,n){return qe("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Ze,e.manifest.collectorUrl,t.buildStartedAtMs,bt(e,t.home))}function nE(e){return ga(e.runnerEvent,e.runnerPlatform)?[]:wi(e.hookInput)}function rE(e,t){return wo(e,t,{})}var Lu=new Set([...Object.values(Ne),".github"]);function oE(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=>Lu.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}var Uu=".codex/config.toml",sE=new Map([["claude_json_user",".claude.json"],["cursor_mcp_user",".cursor/mcp.json"],["codex_toml_user",Uu]]);function iE(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?sE.get(c.source):o==="codex"?Uu:void 0,l=c?.sourcePath??u;if((c?.scope==="user"||u!==void 0)&&l)try{let h=(0,O.userConfigRootFromPath)(l);return(0,O.buildComponentReference)({installationRootExternalKey:(0,O.installationRootExternalKey)(r,h),installableKind:O.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let m=n.indexOf(":");if(m<=0||m===n.length-1)return;let d=n.slice(m+1),_=d.replaceAll("\\","/").split("/").at(-1);if(!(_===void 0||!Lu.has(_)))try{return(0,O.buildComponentReference)({installationRootExternalKey:n,installableKind:O.ComponentKind.INTERFACE,sourcePath:d,nativeKey:t})}catch{return}}function aE(...e){for(let t of e)if(t)return t;return null}function De(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 cE(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 uE(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Ue=new Set,Ot=null;async function lE(e){if(Xe())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Ue.has(t))return;if(!$r(n)){Ue.add(t);return}let r=st({sessionId:e.sessionId,hostname:$t()});if(tc(r)){if(Ot){await Ot;return}Ot=(async()=>{if(Ue.has(t)||!$r(n)){Ue.add(t);return}if(!Ls(n)){Ue.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),{operatorResolved:c,fields:u}=await Du(e,r,nn(i),jr({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})),l={...u,self_config:uE(a,c.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await qe("session_start",l,Tn(e),Ze,e.manifest.collectorUrl,s,bt(e)),o&&(c.commit(),Ue.add(t))}finally{Us(n)}})().finally(()=>{Ot=null}),await Ot}}async function No(e,t,n){try{e.platformAgentId=await ea(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,n,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 Du(e,t,n,r){let[o,s,i,a,c]=await Promise.allSettled([n,hs(),Ma(t),Es(),r]),u=De(o,null,"gitSnapshot"),l=De(s,"","detectVirt"),f=De(i,null,"probeCloud"),m=De(a,{},"hostEnv"),d=De(c,{commit:()=>{}},"resolveOperatorForSend");return await No(e,e.manifest.gitRoot,u),{operatorResolved:d,fields:{identity:{host:$t(),context:t,virt:l||null,cloud:f,git:u},host_env:m,env_vars:va()}}}async function dE(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=st({sessionId:e.sessionId,hostname:$t()}),o=String(e.runnerPlatform),s=To(e),i=Vr(e.hookInput,s),a=nn(n),c=Ru().catch(()=>({})),u=Xe()?Promise.resolve({commit:()=>{}}):jr({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),l=Du(e,r,a,u),[f,m]=await Promise.allSettled([Pr(e.manifest.manifest,n,o),a.catch(()=>null).then(H=>lu(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:H?.remote??null,deferUserSpec:e.deferUserSpec}))]),{operatorResolved:d,fields:_}=await l,h=De(f,[],"mcpDeclared"),S=De(m,cE(o),"selfConfig"),E=S.config,y=R(e.hookInput,"model");y&&(E.model=y);let F={..._,mcp:{declared:h},self_config:E,run_meta:{trigger:e.hookSource||"startup",...e.deferUserSpec?{user_spec_deferred:"launcher_refresh"}:{}},hook_input:fn(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},P=await c;await qe("session_start",F,{...Tn(e),...P},Ze,e.manifest.collectorUrl,t,bt(e))&&(S.commit(),d.commit(),Ue.add(e.manifest.installationId))}async function fE(e){let t=Date.now(),[,n]=await Promise.all([No(e,e.manifest.gitRoot),e.runnerPlatform==="claude"?xu(R(e.hookInput,"transcript_path")):null]),r=e.runnerEvent.toLowerCase(),o=aE(R(e.hookInput,"status"),R(e.hookInput,"stop_reason"),R(e.hookInput,"reason"),pt(R(e.hookInput,"error")),r==="stop"?ie(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=fn(e.hookInput,e.manifest.manifest,To(e));n&&(s.model=n),r!=="stopfailure"&&!ic(e.manifest.manifest)&&s.last_assistant_message===void 0&&(s.last_assistant_message=""),await qe("session_end",{status:o,...n?{model:n}:{},hook_input:s},Tn(e),Ze,e.manifest.collectorUrl,t,bt(e))}async function pE(e){let t=nE(e),n=oa(e.hookInput),r=ma(e.runnerEvent),o=r&&t.length===0&&n.length===0;if(t.length===0&&n.length===0&&!r)return;let s=await wu(e);await Promise.all([o?rE(e,s):void 0,t.length===0?void 0:mE(e,s,t),n.length===0?void 0:gE(e,s,n)])}function Hu(e,t,n,r){let o=r??Ti({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=Po(e,t,o,O.ComponentKind.SKILL,O.nativeKeyForSkillPath);if(s.sourcePath!==null&&gr(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??sa({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=Po(e,t,i,O.ComponentKind.COMMAND,O.nativeKeyForCommandPath);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function mE(e,t,n){let r=Xt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=Hu(e,t,o,r);return wo(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 gE(e,t,n){return Promise.all(n.map(r=>{let o=ta({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=Po(e,t,o,O.ComponentKind.RULE,O.nativeKeyForRulePath),i=s.nativeKey??ra(r);return wo(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var _E=[{kind:O.ComponentKind.SKILL,nativeKeyFn:O.nativeKeyForSkillPath},{kind:O.ComponentKind.RULE,nativeKeyFn:O.nativeKeyForRulePath},{kind:O.ComponentKind.COMMAND,nativeKeyFn:O.nativeKeyForCommandPath}];function hE(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=hr(e.hookInput);if(r===null)return n.skillName===null?{}:Hu(e,t,n.skillName,null);let o=Mu(r,t.gitRoot,t.home);for(let s of _E){let i=vu(e,o,s.kind,s.nativeKeyFn);if(i.nativeKey!==null)return{...i.componentReference===void 0?{}:{componentReference:i.componentReference},...s.kind===O.ComponentKind.RULE?{ruleName:i.nativeKey}:{},...s.kind===O.ComponentKind.COMMAND?{commandName:i.nativeKey}:{}}}return{}}var SE=/mcp/i;function EE(e,t,n,r){let o=SE.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?Lc(t,n):yn(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 yE(e){let t=await wu(e),n=Ea(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=_r(e.hookInput),i=Mc(s,t.home),a=Ra(e.hookInput),c=_a(e.runnerEvent),u=c===!1?Ca(e.hookInput,e.runnerEvent):null,l=pt(R(e.hookInput,"mcp_server_name")),f=l!==null||r!==null&&sn(r)?await Pr(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]):[],{mcpServer:m,mcpTool:d}=Ia(r,f.map(H=>H.name),l??""),_=iE(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),f,l),h=_===void 0?hE(e,t,n):{},S=m===null?null:da(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),E=EE(e,s,t.home,{hasMcpIdentity:!!m||!!d,declaredConfig:S}),y=_??h.componentReference,F=h.ruleName??n.ruleName,P=h.commandName??n.commandName,T=ya(e.hookInput);await qe("tool_invoked",{tool_name:r,skill_name:o,...F?{rule_name:F}:{},...P?{command_name:P}:{},success:c,duration_ms:a,...i?{executable:i}:{},...u?{failure_reason:u}:{},...m?{mcp_server:m}:{},...d?{mcp_tool:d}:{},...E,...y?{component_reference:y}:{},...T?{subagent_type:T}:{},hook_input:t.hookInput},t.envelopeFields,Ze,e.manifest.collectorUrl,t.buildStartedAtMs,bt(e,t.home))}async function Fu(e){switch(e.internalEvent){case"session_start":await dE(e);return;case"session_end":await fE(e);return;case"skill_invoked":await pE(e);return;case"tool_invoked":await yE(e);return;default:return}}import{mkdirSync as RE,readdirSync as CE,readFileSync as kE,statSync as ju,unlinkSync as IE,writeFileSync as AE}from"node:fs";import{homedir as wn}from"node:os";import{join as Mo}from"node:path";var OE="turns",$u=1440*60*1e3,bE=100,xE=new Set(["stop","stopfailure","sessionend"]);function vo(e=wn()){return Mo(ae(e),OE)}function Ku(e,t){return Mo(e,rt(t))}function PE(e,t=Date.now()){let n;try{n=CE(e)}catch{return}let r=0;for(let o of n){if(r>=bE)return;r+=1;try{let s=Mo(e,o);t-ju(s).mtimeMs>$u&&IE(s)}catch{}}}function TE(e,t,n=wn()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=vo(n);RE(s,{recursive:!0}),AE(Ku(s,r),o,"utf8")}catch{}}function wE(e,t=wn()){let n=e.trim();if(!n)return"";try{let r=Ku(vo(t),n);return Date.now()-ju(r).mtimeMs>$u?"":kE(r,"utf8").trim()}catch{return""}}function Bu(e,t,n,r=wn()){let o=t.trim(),s=xE.has(n.trim().toLowerCase());return s&&PE(vo(r)),o?(TE(e,o,r),o):s?wE(e,r):""}async function Gu(e,t,n,r,o=!1){let s=t??await Yn(Gn),i=z(s,{}),a=await $s(process.cwd(),{sessionId:ft(i)});if(!a)return;r&&(a.collectorUrl=r);let c=ha(i,a.manifest.platform,n),u=Sa(e,c.runnerEvent);if(!u){p(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let l={hookInput:i,sessionId:c.sessionId,turnId:Bu(c.sessionId,c.turnId,c.runnerEvent),runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:u,manifest:a,platformAgentId:a.platformAgentId,deferUserSpec:o};await Fu(l)}function NE(e){if(k("EV_AI_HOOK_SYNC")==="1")return!0;let{parsed:t,hookInput:n,runnerEvent:r}=e,o=dt(n,r,void 0,t.runner);return on(r,o)}function zu(e,t){let n=Dn(e),r=z(t,{}),o=n.event??Nr(r);return gs()||pa(n.runner,r,o)?null:{parsed:n,hookInput:r,runnerEvent:o}}async function Vu(e=process.argv.slice(2)){if(Ta(),e[0]===At){try{await Pn(ot)}catch{}return 0}if(e[0]===xn){try{let t=await ot(),n=zu(e.slice(1),t);if(!n)return 0;let{parsed:r}=n;await Gu(r.event,t,r.runner,Tr(r),r.deferUserSpec)}catch(t){let n=t instanceof Error?t.message:String(t);p(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Yn(Gn),n=zu(e,t);if(!n)return 0;let{parsed:r,hookInput:o,runnerEvent:s}=n;if(!Pa(o,s,r.runner))return 0;NE(n)?await Gu(r.event,t,r.runner,Tr(r),r.deferUserSpec):await bu(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);p(`WARN: hook failed open: ${n}`)}finally{ls()}return 0}function Nn(){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 Wu(e){return e.includes("--help")||e.includes("-h")}async function DE(e=process.argv.slice(2)){let[t,...n]=e;if(t===At){try{await Pn(ot)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${oe}
51
+ `),0):t==="configure"?Wu(n)?(Nn(),0):(await ui(Ys(n)),0):t==="install"?Wu(n)?(Nn(),0):(await ai(Xs(n)),0):t==="migrate-to-plugin"?(await di(),0):t==="update"?(await ci(),0):t==="uninstall"?(await fi(),0):t==="help"||t==="--help"||t==="-h"?(Nn(),0):t===void 0?(Nn(),1):Vu(e)}function HE(e,t,n=ME){if(!t)return!1;try{return e===UE(vE(t)).href?!0:n(LE(e))===n(t)}catch{return!1}}HE(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&DE().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);p(t),process.exit(1)});export{HE as isCliEntrypoint,DE as main};