@ev-ai/agent-hook 1.2.6 → 1.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hook.mjs CHANGED
@@ -1,22 +1,22 @@
1
1
  import { createRequire as __createRequire } from 'node:module';
2
2
  const require = __createRequire(import.meta.url);
3
3
 
4
- var Xc=Object.create;var io=Object.defineProperty;var Zc=Object.getOwnPropertyDescriptor;var qc=Object.getOwnPropertyNames;var Qc=Object.getPrototypeOf,eu=Object.prototype.hasOwnProperty;var dn=(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 Se=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var tu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of qc(t))!eu.call(e,o)&&o!==n&&io(e,o,{get:()=>t[o],enumerable:!(r=Zc(t,o))||r.enumerable});return e};var Be=(e,t,n)=>(n=e!=null?Xc(Qc(e)):{},tu(t||!e||!e.__esModule?io(n,"default",{value:e,enumerable:!0}):n,e));var Nt=Se(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.MCP_MISSING_LAUNCH_SERIALIZED=N.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;N.foldMcpName=ws;N.buildMcpFamilyCanonicalKey=Bl;N.launchContainsCredentials=zl;N.serializeMcpLaunchIdentity=Ls;N.hashMcpLaunchIdentity=Xe;N.projectMcpMissingLaunchIdentity=Jl;N.projectMcpLaunchIdentity=Yl;N.maskMcpLaunchForDisplay=Zl;N.normalizeMcpToolNames=ql;var $l=dn("node:crypto");N.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";N.MCP_MISSING_LAUNCH_SERIALIZED=`${N.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function oe(e){return e.toLocaleLowerCase("en-US")}function ws(e){return oe(e)}function Bl(e){return`interface:${ws(e)}`}var Ms=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),Gl=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function we(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function zl(e){return e.kind==="url"?Vl(e.url):e.kind==="command"?e.arguments.some(t=>Gl.test(t)):!1}function Vl(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(Ms.has(oe(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=oe(i.split("=",1)[0]??"");return Ms.has(a)})}}function Ls(e){if(e.kind==="url")return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",we(oe(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>oe(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",we(oe(e.command)),String(t.length),...t.map(we)].join("|")}return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",we(e.installationRootExternalKey),we(e.sourcePath),we(e.nativeKey)].join("|")}function Xe(e){return(0,$l.createHash)("sha256").update(e).digest("hex")}var Wl=Xe(N.MCP_MISSING_LAUNCH_SERIALIZED);function Jl(){return{kind:"unknown",arguments:[],serialized:N.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:Wl}}function Yl(e){let t=Ls(e);return e.kind==="url"?{kind:"url",url:oe(e.url),arguments:[],serialized:t,contentHash:Xe(t)}:e.kind==="command"?{kind:"command",command:oe(e.command),arguments:[...e.arguments].map(n=>oe(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:Xe(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:Xe(t)}}var Xl=/^(https?:\/\/)([^/?#]*@)/i;function Zl(e){return e.replace(Xl,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function ql(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=Se(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.PACKAGE_FIELD_MAX=void 0;Q.npxExecBin=vs;Q.packageNameFromSpec=Mt;Q.pinnedPackageVersionFromSpec=Us;Q.pinnedPackageVersionFromNpx=ad;Q.npxPackageSpecs=Ds;Q.PACKAGE_FIELD_MAX=128;var Ql=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,ed=new Set(["-p","--package"]),td=new Set(["-c","--call"]),nd=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),rd=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),od=/^--no-/;function sd(e){return rd.has(e)||od.test(e)}function vs(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}var id=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function Mt(e){if(e.length===0||e.length>Q.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return Ql.test(n)?n:null}function Us(e){let t=Mt(e);if(t===null||!e.startsWith(`${t}@`))return;let n=e.slice(t.length+1);return id.test(n)?n:void 0}function ad(e,t){for(let n of Ds(e,t)){let r=Us(n);if(r!==void 0)return r}}function Ds(e,t){let n=vs(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(td.has(u))return[];if(ed.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||sd(u))){if(nd.has(u)){i+=1;continue}return[]}}return o.length>0?o.every(i=>Mt(i)!==null)?o:[]:s===null||Mt(s)===null?[]:[s]}});var Fs=Se(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.McpPackageEcosystem=void 0;Ce.resolveMcpPackageIdentity=yd;var cd=Nt(),Kn=wt();Ce.McpPackageEcosystem={NPM:"npm",PYPI:"pypi"};var ud=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,ld=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,dd=/^(?:\d+!)?\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\+[0-9A-Za-z]+(?:[.][0-9A-Za-z]+)*)?$/;function pd(e){let n=(e.replaceAll("\\","/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="uvx"||n==="uv"||n==="pipx"?n:null}var fd=new Set(["--from","--spec"]),md=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"]),gd=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"]),_d=/^--no-/;function hd(e,t){let n=pd(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(fd.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||gd.has(u)||_d.test(u))){if(md.has(u)){i+=1;continue}return null}}return o??s}function Sd(e){if(e.length===0||e.length>Kn.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!ld.test(r)||!dd.test(o)?null:{ecosystem:Ce.McpPackageEcosystem.PYPI,packageName:r,version:o}}function Ed(e){let t=(0,Kn.packageNameFromSpec)(e);if(t===null||!e.startsWith(`${t}@`))return null;let n=e.slice(t.length+1);return ud.test(n)?{ecosystem:Ce.McpPackageEcosystem.NPM,packageName:t,version:n}:null}function yd(e){if(e?.kind!=="command"||(0,cd.launchContainsCredentials)(e))return;for(let n of(0,Kn.npxPackageSpecs)(e.command,e.arguments)){let r=Ed(n);if(r!==null)return r}let t=hd(e.command,e.arguments);if(t!==null)return Sd(t)??void 0}});var Gs=Se(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.EMPTY_NPM_PUBLISHER=void 0;se.isNpmRegistryPublisher=Cd;se.displayPublisherName=Id;se.classifyMcpProvenance=Md;var Ks=Nt(),$n=wt();se.EMPTY_NPM_PUBLISHER="npm:";var Hs="npm:",Rd=/^[A-Za-z0-9._-]+$/;function Cd(e){return e.startsWith(Hs)&&e!==se.EMPTY_NPM_PUBLISHER&&Rd.test(e.slice(Hs.length))}function Id(e){if(!(e==null||e===""||e===se.EMPTY_NPM_PUBLISHER))return e}function js(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 Ad(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 Bn(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function Od(e){let t=Bn(e),n=Ad(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||js(t)||n!==void 0&&js(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function Td(e){let t=Bn(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function Pd(e){let t=Bn(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function $s(e){let t={kind:"url",url:e};if((0,Ks.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||Od(n.hostname))return{origin:"UNKNOWN"};let r=Td(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:Pd(n)}}catch{return{origin:"UNKNOWN"}}}var Bs="mcp-remote";function kd(e,t){if(e===Bs)return t.find(n=>/^https?:\/\//i.test(n))}function bd(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function xd(e,t,n){let r=kd(e,t);return r!==void 0?$s(r):e===Bs?{origin:"UNKNOWN"}:bd(e,n)}function Nd(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 Md(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,Ks.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return $s(t.url);let r=(0,$n.npxPackageSpecs)(t.command,t.arguments)[0];if(r!==void 0){let o=(0,$n.packageNameFromSpec)(r);if(o===null)return{origin:"UNKNOWN"};let s=xd(o,t.arguments,e.publisherName),i=typeof e.packageName=="string"?(0,$n.packageNameFromSpec)(e.packageName):null;return i!==null&&i===o&&s.packageName!==void 0?{...s,packageName:i,packageKey:i}:s}return Nd(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var zs=Se(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.parseFrontmatterField=Y.parseFrontmatterDescription=Y.usableCatalogText=void 0;var wd=/^(?:>|\|)[-+]?$/,Ld=/^(?:>|\|)[-+]?(?:\s+(.*))?$/,vd=e=>{let t=e?.trim()??"";if(!(t.length===0||wd.test(t)))return t};Y.usableCatalogText=vd;var Ud=e=>(0,Y.parseFrontmatterField)(e,"description");Y.parseFrontmatterDescription=Ud;var Dd=(e,t)=>{let n=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(n)return Hd(n[1],t)};Y.parseFrontmatterField=Dd;var Fd=e=>e.replace(/^["']|["']$/g,"");function Hd(e,t){let n=e.split(`
5
- `),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=Ld.exec(s);if(!i){let d=Fd(s).trim();return(0,Y.usableCatalogText)(d)}let a=[];for(let d=o+1;d<n.length;d+=1){let g=n[d]??"";if(g.trim()===""){a.push("");continue}if(g.length===g.trimStart().length)break;a.push(g)}let c=a.reduce((d,g)=>g.trim()===""?d:Math.min(d,g.length-g.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 f=s.startsWith(">")?u.join(`
4
+ var Xc=Object.create;var io=Object.defineProperty;var Zc=Object.getOwnPropertyDescriptor;var qc=Object.getOwnPropertyNames;var Qc=Object.getPrototypeOf,eu=Object.prototype.hasOwnProperty;var dn=(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 Se=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var tu=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of qc(t))!eu.call(e,o)&&o!==n&&io(e,o,{get:()=>t[o],enumerable:!(r=Zc(t,o))||r.enumerable});return e};var Be=(e,t,n)=>(n=e!=null?Xc(Qc(e)):{},tu(t||!e||!e.__esModule?io(n,"default",{value:e,enumerable:!0}):n,e));var Nt=Se(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.MCP_MISSING_LAUNCH_SERIALIZED=N.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;N.foldMcpName=ws;N.buildMcpFamilyCanonicalKey=Bl;N.launchContainsCredentials=zl;N.serializeMcpLaunchIdentity=Ls;N.hashMcpLaunchIdentity=Xe;N.projectMcpMissingLaunchIdentity=Jl;N.projectMcpLaunchIdentity=Yl;N.maskMcpLaunchForDisplay=Zl;N.normalizeMcpToolNames=ql;var $l=dn("node:crypto");N.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";N.MCP_MISSING_LAUNCH_SERIALIZED=`${N.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function oe(e){return e.toLocaleLowerCase("en-US")}function ws(e){return oe(e)}function Bl(e){return`interface:${ws(e)}`}var Ms=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),Gl=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function we(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function zl(e){return e.kind==="url"?Vl(e.url):e.kind==="command"?e.arguments.some(t=>Gl.test(t)):!1}function Vl(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(Ms.has(oe(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=oe(i.split("=",1)[0]??"");return Ms.has(a)})}}function Ls(e){if(e.kind==="url")return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",we(oe(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>oe(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",we(oe(e.command)),String(t.length),...t.map(we)].join("|")}return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",we(e.installationRootExternalKey),we(e.sourcePath),we(e.nativeKey)].join("|")}function Xe(e){return(0,$l.createHash)("sha256").update(e).digest("hex")}var Wl=Xe(N.MCP_MISSING_LAUNCH_SERIALIZED);function Jl(){return{kind:"unknown",arguments:[],serialized:N.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:Wl}}function Yl(e){let t=Ls(e);return e.kind==="url"?{kind:"url",url:oe(e.url),arguments:[],serialized:t,contentHash:Xe(t)}:e.kind==="command"?{kind:"command",command:oe(e.command),arguments:[...e.arguments].map(n=>oe(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:Xe(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:Xe(t)}}var Xl=/^(https?:\/\/)([^/?#]*@)/i;function Zl(e){return e.replace(Xl,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function ql(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=Se(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.PACKAGE_FIELD_MAX=void 0;Q.npxExecBin=vs;Q.packageNameFromSpec=Mt;Q.pinnedPackageVersionFromSpec=Us;Q.pinnedPackageVersionFromNpx=ad;Q.npxPackageSpecs=Ds;Q.PACKAGE_FIELD_MAX=128;var Ql=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,ed=new Set(["-p","--package"]),td=new Set(["-c","--call"]),nd=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),rd=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),od=/^--no-/;function sd(e){return rd.has(e)||od.test(e)}function vs(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}var id=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function Mt(e){if(e.length===0||e.length>Q.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return Ql.test(n)?n:null}function Us(e){let t=Mt(e);if(t===null||!e.startsWith(`${t}@`))return;let n=e.slice(t.length+1);return id.test(n)?n:void 0}function ad(e,t){for(let n of Ds(e,t)){let r=Us(n);if(r!==void 0)return r}}function Ds(e,t){let n=vs(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(td.has(l))return[];if(ed.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||sd(l))){if(nd.has(l)){i+=1;continue}return[]}}return o.length>0?o.every(i=>Mt(i)!==null)?o:[]:s===null||Mt(s)===null?[]:[s]}});var Fs=Se(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.McpPackageEcosystem=void 0;Ce.resolveMcpPackageIdentity=yd;var cd=Nt(),Kn=wt();Ce.McpPackageEcosystem={NPM:"npm",PYPI:"pypi"};var ud=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,ld=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,dd=/^(?:\d+!)?\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\+[0-9A-Za-z]+(?:[.][0-9A-Za-z]+)*)?$/;function pd(e){let n=(e.replaceAll("\\","/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="uvx"||n==="uv"||n==="pipx"?n:null}var fd=new Set(["--from","--spec"]),md=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"]),gd=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"]),_d=/^--no-/;function hd(e,t){let n=pd(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(fd.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||gd.has(l)||_d.test(l))){if(md.has(l)){i+=1;continue}return null}}return o??s}function Sd(e){if(e.length===0||e.length>Kn.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!ld.test(r)||!dd.test(o)?null:{ecosystem:Ce.McpPackageEcosystem.PYPI,packageName:r,version:o}}function Ed(e){let t=(0,Kn.packageNameFromSpec)(e);if(t===null||!e.startsWith(`${t}@`))return null;let n=e.slice(t.length+1);return ud.test(n)?{ecosystem:Ce.McpPackageEcosystem.NPM,packageName:t,version:n}:null}function yd(e){if(e?.kind!=="command"||(0,cd.launchContainsCredentials)(e))return;for(let n of(0,Kn.npxPackageSpecs)(e.command,e.arguments)){let r=Ed(n);if(r!==null)return r}let t=hd(e.command,e.arguments);if(t!==null)return Sd(t)??void 0}});var Gs=Se(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.EMPTY_NPM_PUBLISHER=void 0;se.isNpmRegistryPublisher=Cd;se.displayPublisherName=Id;se.classifyMcpProvenance=Md;var Ks=Nt(),$n=wt();se.EMPTY_NPM_PUBLISHER="npm:";var Hs="npm:",Rd=/^[A-Za-z0-9._-]+$/;function Cd(e){return e.startsWith(Hs)&&e!==se.EMPTY_NPM_PUBLISHER&&Rd.test(e.slice(Hs.length))}function Id(e){if(!(e==null||e===""||e===se.EMPTY_NPM_PUBLISHER))return e}function js(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 Ad(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 Bn(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function Od(e){let t=Bn(e),n=Ad(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||js(t)||n!==void 0&&js(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function Td(e){let t=Bn(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function Pd(e){let t=Bn(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function $s(e){let t={kind:"url",url:e};if((0,Ks.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||Od(n.hostname))return{origin:"UNKNOWN"};let r=Td(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:Pd(n)}}catch{return{origin:"UNKNOWN"}}}var Bs="mcp-remote";function kd(e,t){if(e===Bs)return t.find(n=>/^https?:\/\//i.test(n))}function bd(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function xd(e,t,n){let r=kd(e,t);return r!==void 0?$s(r):e===Bs?{origin:"UNKNOWN"}:bd(e,n)}function Nd(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 Md(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,Ks.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return $s(t.url);let r=(0,$n.npxPackageSpecs)(t.command,t.arguments)[0];if(r!==void 0){let o=(0,$n.packageNameFromSpec)(r);if(o===null)return{origin:"UNKNOWN"};let s=xd(o,t.arguments,e.publisherName),i=typeof e.packageName=="string"?(0,$n.packageNameFromSpec)(e.packageName):null;return i!==null&&i===o&&s.packageName!==void 0?{...s,packageName:i,packageKey:i}:s}return Nd(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var zs=Se(Y=>{"use strict";Object.defineProperty(Y,"__esModule",{value:!0});Y.parseFrontmatterField=Y.parseFrontmatterDescription=Y.usableCatalogText=void 0;var wd=/^(?:>|\|)[-+]?$/,Ld=/^(?:>|\|)[-+]?(?:\s+(.*))?$/,vd=e=>{let t=e?.trim()??"";if(!(t.length===0||wd.test(t)))return t};Y.usableCatalogText=vd;var Ud=e=>(0,Y.parseFrontmatterField)(e,"description");Y.parseFrontmatterDescription=Ud;var Dd=(e,t)=>{let n=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(n)return Hd(n[1],t)};Y.parseFrontmatterField=Dd;var Fd=e=>e.replace(/^["']|["']$/g,"");function Hd(e,t){let n=e.split(`
5
+ `),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=Ld.exec(s);if(!i){let d=Fd(s).trim();return(0,Y.usableCatalogText)(d)}let a=[];for(let d=o+1;d<n.length;d+=1){let g=n[d]??"";if(g.trim()===""){a.push("");continue}if(g.length===g.trimStart().length)break;a.push(g)}let c=a.reduce((d,g)=>g.trim()===""?d:Math.min(d,g.length-g.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 f=s.startsWith(">")?l.join(`
6
6
  `).split(/\n{2,}/).map(d=>d.split(`
7
7
  `).map(g=>g.trim()).filter(Boolean).join(" ")).filter(d=>d.length>0).join(`
8
8
 
9
- `):u.join(`
10
- `).trimEnd();return(0,Y.usableCatalogText)(f)}});var Ys=Se(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=P.COMPONENT_INSPECTION_TEXT_MAX_BYTES=P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;P.fitSnapshotInspectionTextBudget=jd;P.capComponentTextBytes=Ws;P.prepareComponentInspectionText=Kd;P.redactComponentSource=zn;P.componentSourceContainsRedactableSecret=np;P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER="[REDACTED]";P.COMPONENT_INSPECTION_TEXT_MAX_BYTES=256*1024;P.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=3*1024*1024;function jd(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<=P.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES?(t+=s,n):{...n,skill:{...r.skill,inspectionText:void 0}}})}function Ws(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 Kd(e){if(!(e==null||e.length===0))return Ws(zn(e),P.COMPONENT_INSPECTION_TEXT_MAX_BYTES)}var $d="(?:[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_.-]*)",Bd=new RegExp(`(\\b${$d})(\\s*[:=]\\s*)(?:(")([^"\\n]*)(")|(')([^'\\n]*)(')|([^\\s"'][^"'\\n]*))`,"gi"),Gd=[/^(?: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 Gn(e){let t=e.trim().replace(/^`+|`+$/g,"").trim();return Gd.some(n=>n.test(t))}function zd(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 Vd=[/\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],Wd=/\b[A-Za-z0-9_+/-]{32,}={0,2}\b/g,Jd=/^[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 Yd(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 Xd(e){return e.replace(Wd,t=>{if(Jd.test(t))return t;let n=/[A-Za-z]/.test(t),r=/\d/.test(t);return n&&r&&Yd(t)>=3.5?P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:t})}var Zd=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,qd=/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+):([^\s/@]*)@/gi,Qd=/([?&](?:access_token|api_key|apikey|auth|authorization|client_secret|key|password|secret|token)=)[^&\s"'<>]+/gi,ep=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,Vs=/-----END [A-Z0-9 ]*PRIVATE KEY-----/;function Js(e){return e.replace(Bd,(t,n,r,o,s,i,a,c,u,l)=>{let p=`${n}${r}`;if(o!==void 0||a!==void 0){let d=o??a??"",g=i??u??"",_=s??c??"";return _===""||_.includes(P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Gn(_)?t:`${p}${d}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${g}`}let f=l??"";if(r==="="){let d=zd(f).replace(/`+$/,""),g=Js(f.slice(d.length));return d===""||d.includes(P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Gn(d)?`${p}${d}${g}`:`${p}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${g}`}return f.includes(P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Gn(f)?t:`${p}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`})}function tp(e){let t=e.replace(qd,(n,r)=>`${r}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}:${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}@`);t=t.replace(Qd,(n,r)=>`${r}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`),t=t.replace(Zd,(n,r)=>`${r}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`);for(let n of Vd)t=t.replace(n,P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER);return Js(Xd(t))}function zn(e){if(e.length===0)return e;let t=e.split(`
9
+ `):l.join(`
10
+ `).trimEnd();return(0,Y.usableCatalogText)(f)}});var Ys=Se(P=>{"use strict";Object.defineProperty(P,"__esModule",{value:!0});P.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=P.COMPONENT_INSPECTION_TEXT_MAX_BYTES=P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;P.fitSnapshotInspectionTextBudget=jd;P.capComponentTextBytes=Ws;P.prepareComponentInspectionText=Kd;P.redactComponentSource=zn;P.componentSourceContainsRedactableSecret=np;P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER="[REDACTED]";P.COMPONENT_INSPECTION_TEXT_MAX_BYTES=256*1024;P.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=3*1024*1024;function jd(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<=P.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES?(t+=s,n):{...n,skill:{...r.skill,inspectionText:void 0}}})}function Ws(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 Kd(e){if(!(e==null||e.length===0))return Ws(zn(e),P.COMPONENT_INSPECTION_TEXT_MAX_BYTES)}var $d="(?:[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_.-]*)",Bd=new RegExp(`(\\b${$d})(\\s*[:=]\\s*)(?:(")([^"\\n]*)(")|(')([^'\\n]*)(')|([^\\s"'][^"'\\n]*))`,"gi"),Gd=[/^(?: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 Gn(e){let t=e.trim().replace(/^`+|`+$/g,"").trim();return Gd.some(n=>n.test(t))}function zd(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 Vd=[/\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],Wd=/\b[A-Za-z0-9_+/-]{32,}={0,2}\b/g,Jd=/^[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 Yd(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 Xd(e){return e.replace(Wd,t=>{if(Jd.test(t))return t;let n=/[A-Za-z]/.test(t),r=/\d/.test(t);return n&&r&&Yd(t)>=3.5?P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:t})}var Zd=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,qd=/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+):([^\s/@]*)@/gi,Qd=/([?&](?:access_token|api_key|apikey|auth|authorization|client_secret|key|password|secret|token)=)[^&\s"'<>]+/gi,ep=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,Vs=/-----END [A-Z0-9 ]*PRIVATE KEY-----/;function Js(e){return e.replace(Bd,(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??"",g=i??l??"",_=s??c??"";return _===""||_.includes(P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Gn(_)?t:`${p}${d}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${g}`}let f=u??"";if(r==="="){let d=zd(f).replace(/`+$/,""),g=Js(f.slice(d.length));return d===""||d.includes(P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Gn(d)?`${p}${d}${g}`:`${p}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${g}`}return f.includes(P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Gn(f)?t:`${p}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`})}function tp(e){let t=e.replace(qd,(n,r)=>`${r}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}:${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}@`);t=t.replace(Qd,(n,r)=>`${r}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`),t=t.replace(Zd,(n,r)=>`${r}${P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`);for(let n of Vd)t=t.replace(n,P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER);return Js(Xd(t))}function zn(e){if(e.length===0)return e;let t=e.split(`
11
11
  `),n=!1;return t.map(o=>n?Vs.test(o)?(n=!1,o):o.trim().length===0?o:P.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:ep.test(o)&&!Vs.test(o)?(n=!0,o):tp(o)).join(`
12
12
  `)}function np(e){return zn(e)!==e}});var ve=Se(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.redactComponentSource=m.prepareComponentInspectionText=m.fitSnapshotInspectionTextBudget=m.componentSourceContainsRedactableSecret=m.capComponentTextBytes=m.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=m.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=m.COMPONENT_INSPECTION_TEXT_MAX_BYTES=m.usableCatalogText=m.parseFrontmatterField=m.parseFrontmatterDescription=m.isNpmRegistryPublisher=m.EMPTY_NPM_PUBLISHER=m.displayPublisherName=m.classifyMcpProvenance=m.resolveMcpPackageIdentity=m.McpPackageEcosystem=m.pinnedPackageVersionFromSpec=m.pinnedPackageVersionFromNpx=m.packageNameFromSpec=m.npxPackageSpecs=m.npxExecBin=m.PACKAGE_FIELD_MAX=m.serializeMcpLaunchIdentity=m.projectMcpMissingLaunchIdentity=m.projectMcpLaunchIdentity=m.normalizeMcpToolNames=m.MCP_MISSING_LAUNCH_SERIALIZED=m.MCP_LAUNCH_IDENTITY_ALGORITHM=m.maskMcpLaunchForDisplay=m.launchContainsCredentials=m.hashMcpLaunchIdentity=m.foldMcpName=m.buildMcpFamilyCanonicalKey=m.ComponentKind=void 0;m.userConfigRootFromPath=pp;m.installationRootExternalKey=fp;m.normalizeRepositoryRelativePath=Xs;m.nativeKeyForSkillPath=mp;m.nativeKeyForRulePath=gp;m.nativeKeyForCommandPath=_p;m.serializeComponentIdentity=qs;m.buildComponentReference=Sp;m.validateComponentReference=Ep;var rp=dn("node:crypto"),op=dn("node:path"),sp="cmp1_",ip=/^cmp1_[A-Za-z0-9_-]{43}$/,ap=["/skills/","/skills-cursor/"],cp=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,up=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,lp=[".cursor",".claude",".codex"],dp={".claude.json":".claude",".agents":".codex"};m.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function pp(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>lp.includes(o));return n||(t.map(o=>dp[o]).find(o=>o!==void 0)??"unknown")}function fp(e,t){return`runtime-install:${e}/${t}`}function Lt(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Xs(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=op.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Lt(n,"sourcePath")}function mp(e){let t=e.replaceAll("\\","/");for(let n of ap){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Zs(e,t,n){let r=e.replaceAll("\\","/"),s=t.exec(r)?.[1];if(!s||s.split("/").includes(".."))return null;let i=s.replace(n,"");return i.length>0?i:null}function gp(e){return Zs(e,cp,/\.(mdc|md|rules)$/i)}function _p(e){return Zs(e,up,/\.(md|mdc|toml)$/i)}function hp(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function qs(e){let t=[Lt(e.installationRootExternalKey,"installationRootExternalKey"),Lt(e.installableKind,"installableKind"),Xs(e.sourcePath),Lt(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(hp).join("|")}`,"utf8")}function Sp(e){let t=(0,rp.createHash)("sha256").update(qs(e)).digest("base64url");return`${sp}${t}`}function Ep(e){return ip.test(e)}var X=Nt();Object.defineProperty(m,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return X.buildMcpFamilyCanonicalKey}});Object.defineProperty(m,"foldMcpName",{enumerable:!0,get:function(){return X.foldMcpName}});Object.defineProperty(m,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return X.hashMcpLaunchIdentity}});Object.defineProperty(m,"launchContainsCredentials",{enumerable:!0,get:function(){return X.launchContainsCredentials}});Object.defineProperty(m,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return X.maskMcpLaunchForDisplay}});Object.defineProperty(m,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return X.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(m,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return X.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(m,"normalizeMcpToolNames",{enumerable:!0,get:function(){return X.normalizeMcpToolNames}});Object.defineProperty(m,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return X.projectMcpLaunchIdentity}});Object.defineProperty(m,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return X.projectMcpMissingLaunchIdentity}});Object.defineProperty(m,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return X.serializeMcpLaunchIdentity}});var Le=wt();Object.defineProperty(m,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return Le.PACKAGE_FIELD_MAX}});Object.defineProperty(m,"npxExecBin",{enumerable:!0,get:function(){return Le.npxExecBin}});Object.defineProperty(m,"npxPackageSpecs",{enumerable:!0,get:function(){return Le.npxPackageSpecs}});Object.defineProperty(m,"packageNameFromSpec",{enumerable:!0,get:function(){return Le.packageNameFromSpec}});Object.defineProperty(m,"pinnedPackageVersionFromNpx",{enumerable:!0,get:function(){return Le.pinnedPackageVersionFromNpx}});Object.defineProperty(m,"pinnedPackageVersionFromSpec",{enumerable:!0,get:function(){return Le.pinnedPackageVersionFromSpec}});var Qs=Fs();Object.defineProperty(m,"McpPackageEcosystem",{enumerable:!0,get:function(){return Qs.McpPackageEcosystem}});Object.defineProperty(m,"resolveMcpPackageIdentity",{enumerable:!0,get:function(){return Qs.resolveMcpPackageIdentity}});var vt=Gs();Object.defineProperty(m,"classifyMcpProvenance",{enumerable:!0,get:function(){return vt.classifyMcpProvenance}});Object.defineProperty(m,"displayPublisherName",{enumerable:!0,get:function(){return vt.displayPublisherName}});Object.defineProperty(m,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return vt.EMPTY_NPM_PUBLISHER}});Object.defineProperty(m,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return vt.isNpmRegistryPublisher}});var Vn=zs();Object.defineProperty(m,"parseFrontmatterDescription",{enumerable:!0,get:function(){return Vn.parseFrontmatterDescription}});Object.defineProperty(m,"parseFrontmatterField",{enumerable:!0,get:function(){return Vn.parseFrontmatterField}});Object.defineProperty(m,"usableCatalogText",{enumerable:!0,get:function(){return Vn.usableCatalogText}});var fe=Ys();Object.defineProperty(m,"COMPONENT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return fe.COMPONENT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(m,"COMPONENT_SOURCE_REDACTION_PLACEHOLDER",{enumerable:!0,get:function(){return fe.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}});Object.defineProperty(m,"SNAPSHOT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return fe.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(m,"capComponentTextBytes",{enumerable:!0,get:function(){return fe.capComponentTextBytes}});Object.defineProperty(m,"componentSourceContainsRedactableSecret",{enumerable:!0,get:function(){return fe.componentSourceContainsRedactableSecret}});Object.defineProperty(m,"fitSnapshotInspectionTextBudget",{enumerable:!0,get:function(){return fe.fitSnapshotInspectionTextBudget}});Object.defineProperty(m,"prepareComponentInspectionText",{enumerable:!0,get:function(){return fe.prepareComponentInspectionText}});Object.defineProperty(m,"redactComponentSource",{enumerable:!0,get:function(){return fe.redactComponentSource}})});import{existsSync as pu,readFileSync as fu}from"node:fs";import{hostname as So,userInfo as mu}from"node:os";import{createHash as nu,randomBytes as ru}from"node:crypto";import{existsSync as pn,mkdirSync as ou,readdirSync as su,readFileSync as iu,renameSync as ao,statSync as po,unlinkSync as co,writeFileSync as au}from"node:fs";import{basename as cu,dirname as uo,join as fo,relative as uu}from"node:path";function h(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
13
- `)}function Ge(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1")}function ze(e){return nu("sha256").update(e).digest("hex").slice(0,32)}function Z(e,t){ou(uo(e),{recursive:!0});let n=fo(uo(e),`.${cu(e)}.${process.pid}.${ru(4).toString("hex")}.tmp`);try{au(n,t,"utf8");try{ao(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){co(e),ao(n,e);return}throw r}}catch(r){try{co(n)}catch{}throw r}}function _t(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function mo(){process.stdout.write('{"continue":true}')}function I(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function fn(){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 mn(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 J(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 w(e,t,n=3e3,r={}){let o=await J(e,t,n,r);return o.ok?o.stdout:""}async function gn(e=process.cwd()){let t=await J("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")}`;h(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=I("CURSOR_PROJECT_DIR")??I("CLAUDE_PROJECT_DIR");if(n&&pn(n)){let r=await J("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 _n(e=process.cwd()){return(await gn(e)).root}function G(e,t){try{return JSON.parse(e)}catch{return t}}var lo=new Map;function lu(e){return e.charCodeAt(0)===65279?e.slice(1):e}function du(e){let t;try{t=iu(e,"utf8")}catch{return{ok:!1,reason:"read"}}try{return{ok:!0,value:JSON.parse(lu(t))}}catch{return{ok:!1,reason:"parse"}}}function go(e){let t=lo.get(e);if(t!==void 0)return t;let n=du(e);return lo.set(e,n),n}function _o(e){return go(e)}function U(e,t){let n=go(e);return n.ok?n.value:t}function Ee(e){return typeof e=="string"?e:""}function ne(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=ne(e,t);return typeof n=="string"?n:""}var ce=500;function ho(e,t=2){if(!pn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=su(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let u=fo(s,c.name);if(c.isDirectory()){o(u,i+1);continue}if(c.isFile()){try{n.push({name:uu(e,u),size:po(u).size})}catch{continue}if(n.length>=ce){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function hn(e){return pn(e)?{present:!0,size:po(e).size}:{present:!1,size:0}}function be(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Eo(e=process.env){return be(x("CURSOR_SANDBOX",e))}var gu=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function _u(e){return gu.some(t=>!!x(t,e))}function hu(e){if(x("KUBERNETES_SERVICE_HOST",e)||be(x("REMOTE_CONTAINERS",e))||be(x("DEVCONTAINER",e)))return!0;try{if(pu("/.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=>!!x(t,e))}function Su(e,t=process.platform){return yo(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!x(n,e)):!1}function Eu(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function yu(e){return e==="linux"}function x(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return I(e)}function Ru(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Cu(x("CURSOR_VERSION",n))}function Cu(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Sn(e){if(Eu(e.sessionId))return!0;let t=e.hostname??So(),n=e.osUser??Co(e.env);return Ru(t,n,e.env)}function Iu(e){return be(x("CURSOR_AGENT",e.env))?!0:Sn(e)}function Au(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(x("TERM",e)??x("TERM_PROGRAM",e))||(x("SSH_TTY",e)??x("SSH_CONNECTION",e))||(x("__CFBundleIdentifier",e)??x("XPC_SERVICE_NAME",e))||yo(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!x(t,e))||x("SESSIONNAME",e))}function Ve(e={}){let t=e.env;if(x("GITHUB_ACTIONS",t))return"github_actions";if(be(x("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Su(t,n)&&Iu(e)&&(be(x("CURSOR_AGENT",t))||yu(n)))return"cursor_cloud";if(x("CODESPACES",t)||x("CODESPACE_NAME",t))return"codespaces";if(x("GITLAB_CI",t))return"gitlab_ci";if(_u(t))return"managed";let r=x("CI",t);return r&&r!=="false"&&r!=="0"?"managed":hu(t)?"container":Au(t)?"interactive":"unknown"}async function Ro(){return await w("systemd-detect-virt",[],1e3)}function Co(e=process.env,t=mu){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 Io(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await w("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),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 w("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await w("uname",["-r"],1e3))}else t=await w("ver",[],1e3);let n=Co(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await w("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function ht(){return So()}import{createHash as Ou}from"node:crypto";import{homedir as Tu}from"node:os";import{dirname as fS,join as Pu,parse as mS,resolve as gS}from"node:path";var Ao="EV_AI_LAUNCHER_VERSION";var Oo="EV_AI_HOOK_SOURCE",To="EV_AI_HOOK_FALLBACK_REASON",Po="EV_AI_LAUNCHER_SCOPE",En="EV_AI_LAUNCHER_READY_FD";var ko="--defer-user-spec",bo=Buffer.from([1]);var rS=1024*1024,oS=4*1024*1024,sS=64*1024,iS=64*1024,aS=64*1024;var yn=4096,cS=4*1024*1024;var No="https://hooks.ev-ai.ai",Mo=".claude/ev-ai-runtime-report.json",wo="config.json",hS=1024*1024,ku=new Set(["localhost","127.0.0.1","[::1]","::1"]),bu=["claude","cursor","codex"],Lo=[Mo,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],Rn=/^[A-Za-z0-9._~-]+$/;function Et(e){return e!==void 0&&bu.includes(e)}function St(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Cn(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=St(e,a);t=u.value,a=u.next;continue}if(c.startsWith("--runner=")){t=c.slice(9);continue}if(c==="--url"){let u=St(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=St(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=St(e,a);u.value&&(s=u.value),a=u.next;continue}if(c.startsWith("--base-url=")){s=c.slice(11);continue}if(c===ko){i=!0;continue}!c.startsWith("-")&&n===void 0&&(n=c)}}return{runner:Et(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s,...i?{deferUserSpec:!0}:{}}}function yt(e,t=No){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function In(e=Tu()){return Pu(e,".ev-ai",wo)}function vo(e,t){return{...e,...t}}function xo(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function Rt(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?ku.has(t.hostname):!1}catch{return!1}}function An(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 On(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Rt(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=An(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Rn.test(n))return`org token must match ${Rn.source} (got: ${n})`;if(xo(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(xo(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Uo(e){return new URL(e).toString()}function Tn(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?yt(n):""}function Ct(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 Do(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=yt(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=On(n);return r?{problem:r}:{url:Uo(n)}}function Fo(e){if(On(e))return;let t;try{t=new URL(e)}catch{return}let n=An(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 Ou("sha256").update(i).digest("hex").slice(0,32)}var At=2;var It="ev-ai-agent-hook";function xu(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function Ho(e){let t=xu(e);return t===It||t===`${It}.exe`}var ES=`current/${It}`,yS=`.ev-ai/agent-hook/${It}`,jo=5e3,Ko=5e3,Pn=3e3;var kn=3e3,$o=1500,Bo=4*1024,bn=256*1024,Nu=4*1024,Go=32*1024,We=840*60*1e3,xn="1.2.6",RS=`@ev-ai/agent-hook@${xn}`;import{existsSync as Zp,mkdirSync as qp,readdirSync as Qp,readFileSync as ef,unlinkSync as Oi,writeFileSync as tf}from"node:fs";import{homedir as Ti}from"node:os";import{join as nr}from"node:path";import{createHash as Yo,randomBytes as Lu}from"node:crypto";import{existsSync as Xo,mkdirSync as Nn,readFileSync as Zo,unlinkSync as qo,writeFileSync as Qo}from"node:fs";import{homedir as Mn}from"node:os";import{dirname as Ot,join as wn,resolve as vu}from"node:path";var Mu=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),wu=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function B(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||wu.has(n)||r.includes("[bot]")||Mu.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}var Uu="installation.json",Du="cloud-bootstrap.lock",Fu=6e4;function es(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function re(e=Mn()){return wn(e,".ev-ai","agent-hook")}function Hu(e=Mn()){return wn(re(e),Uu)}function ts(e){return wn(Ot(e),Du)}function ns(){return Lu(8).toString("hex")}function xe(e){return Yo("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 rs(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function ju(e=process.env){let t=A(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!rs(t)){h(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function os(e,t){return e&&rs(e)?e:(e&&h(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),ju(t))}function Ku(e){return/^[0-9a-f]{16}$/.test(e)}function $u(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 xe(`github_actions|${t}|${n}`)}if(A(e.CODESPACES)||A(e.CODESPACE_NAME)){let t=A(e.CODESPACE_NAME);if(t)return xe(`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 xe(`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 xe(`gitlab|${t}|${n}`)}return null}var Bu="cursoragent@cursor.com";function Gu(e){let t=A(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Bu?null:t}function zu(e,t){return A(e.CURSOR_PROJECT_DIR)??A(e.CLAUDE_PROJECT_DIR)??t}function Vu(e){return Ge(e).replace(/\.git$/i,"").toLowerCase()}async function Wu(e){let t=await w("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Vu(t):e}async function Ju(e){let t=A(await w("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!B(null,t))return t;let n=A(await w("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!B(null,n)?n:null}function Yu(e,t){let n=zu(e,t);return n?xe(`cursor_cloud|${n}|${Gu(e)??""}`):null}async function Xu(e,t){let n=A(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Wu(n),o=await Ju(n);return xe(`claude_remote|${r}|${o??""}`)}function zo(e,t){let n=os(e,t);if(n)return n;let r=$u(t);return r||ns()}async function Zu(e){let n=await w("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||vu(e);return Yo("sha256").update(n).digest("hex").slice(0,16)}function qu(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 Qu(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=qu(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function ye(e){if(Xo(e))try{return Qu(Zo(e,"utf8"))}catch{}}function Ln(e){return ye(e)}function ss(e,t,n){let r=ye(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Z(e,`${JSON.stringify(o,null,2)}
13
+ `)}function Ge(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1")}function ze(e){return nu("sha256").update(e).digest("hex").slice(0,32)}function Z(e,t){ou(uo(e),{recursive:!0});let n=fo(uo(e),`.${cu(e)}.${process.pid}.${ru(4).toString("hex")}.tmp`);try{au(n,t,"utf8");try{ao(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){co(e),ao(n,e);return}throw r}}catch(r){try{co(n)}catch{}throw r}}function _t(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function mo(){process.stdout.write('{"continue":true}')}function I(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function fn(){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 mn(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 J(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 w(e,t,n=3e3,r={}){let o=await J(e,t,n,r);return o.ok?o.stdout:""}async function gn(e=process.cwd()){let t=await J("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")}`;h(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=I("CURSOR_PROJECT_DIR")??I("CLAUDE_PROJECT_DIR");if(n&&pn(n)){let r=await J("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 _n(e=process.cwd()){return(await gn(e)).root}function G(e,t){try{return JSON.parse(e)}catch{return t}}var lo=new Map;function lu(e){return e.charCodeAt(0)===65279?e.slice(1):e}function du(e){let t;try{t=iu(e,"utf8")}catch{return{ok:!1,reason:"read"}}try{return{ok:!0,value:JSON.parse(lu(t))}}catch{return{ok:!1,reason:"parse"}}}function go(e){let t=lo.get(e);if(t!==void 0)return t;let n=du(e);return lo.set(e,n),n}function _o(e){return go(e)}function U(e,t){let n=go(e);return n.ok?n.value:t}function Ee(e){return typeof e=="string"?e:""}function ne(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=ne(e,t);return typeof n=="string"?n:""}var ce=500;function ho(e,t=2){if(!pn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=su(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=fo(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:uu(e,l),size:po(l).size})}catch{continue}if(n.length>=ce){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function hn(e){return pn(e)?{present:!0,size:po(e).size}:{present:!1,size:0}}function be(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Eo(e=process.env){return be(x("CURSOR_SANDBOX",e))}var gu=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function _u(e){return gu.some(t=>!!x(t,e))}function hu(e){if(x("KUBERNETES_SERVICE_HOST",e)||be(x("REMOTE_CONTAINERS",e))||be(x("DEVCONTAINER",e)))return!0;try{if(pu("/.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=>!!x(t,e))}function Su(e,t=process.platform){return yo(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!x(n,e)):!1}function Eu(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function yu(e){return e==="linux"}function x(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return I(e)}function Ru(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Cu(x("CURSOR_VERSION",n))}function Cu(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Sn(e){if(Eu(e.sessionId))return!0;let t=e.hostname??So(),n=e.osUser??Co(e.env);return Ru(t,n,e.env)}function Iu(e){return be(x("CURSOR_AGENT",e.env))?!0:Sn(e)}function Au(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(x("TERM",e)??x("TERM_PROGRAM",e))||(x("SSH_TTY",e)??x("SSH_CONNECTION",e))||(x("__CFBundleIdentifier",e)??x("XPC_SERVICE_NAME",e))||yo(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!x(t,e))||x("SESSIONNAME",e))}function Ve(e={}){let t=e.env;if(x("GITHUB_ACTIONS",t))return"github_actions";if(be(x("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Su(t,n)&&Iu(e)&&(be(x("CURSOR_AGENT",t))||yu(n)))return"cursor_cloud";if(x("CODESPACES",t)||x("CODESPACE_NAME",t))return"codespaces";if(x("GITLAB_CI",t))return"gitlab_ci";if(_u(t))return"managed";let r=x("CI",t);return r&&r!=="false"&&r!=="0"?"managed":hu(t)?"container":Au(t)?"interactive":"unknown"}async function Ro(){return await w("systemd-detect-virt",[],1e3)}function Co(e=process.env,t=mu){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 Io(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await w("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),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 w("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await w("uname",["-r"],1e3))}else t=await w("ver",[],1e3);let n=Co(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await w("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function ht(){return So()}import{createHash as Ou}from"node:crypto";import{homedir as Tu}from"node:os";import{dirname as fS,join as Pu,parse as mS,resolve as gS}from"node:path";var Ao="EV_AI_LAUNCHER_VERSION";var Oo="EV_AI_HOOK_SOURCE",To="EV_AI_HOOK_FALLBACK_REASON",Po="EV_AI_LAUNCHER_SCOPE",En="EV_AI_LAUNCHER_READY_FD";var ko="--defer-user-spec",bo=Buffer.from([1]);var rS=1024*1024,oS=4*1024*1024,sS=64*1024,iS=64*1024,aS=64*1024;var yn=4096,cS=4*1024*1024;var No="https://hooks.ev-ai.ai",Mo=".claude/ev-ai-runtime-report.json",wo="config.json",hS=1024*1024,ku=new Set(["localhost","127.0.0.1","[::1]","::1"]),bu=["claude","cursor","codex"],Lo=[Mo,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],Rn=/^[A-Za-z0-9._~-]+$/;function Et(e){return e!==void 0&&bu.includes(e)}function St(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Cn(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=St(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=St(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=St(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=St(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}a!==ko&&!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:Et(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function yt(e,t=No){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function In(e=Tu()){return Pu(e,".ev-ai",wo)}function vo(e,t){return{...e,...t}}function xo(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function Rt(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?ku.has(t.hostname):!1}catch{return!1}}function An(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 On(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Rt(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=An(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Rn.test(n))return`org token must match ${Rn.source} (got: ${n})`;if(xo(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(xo(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Uo(e){return new URL(e).toString()}function Tn(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?yt(n):""}function Ct(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 Do(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=yt(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=On(n);return r?{problem:r}:{url:Uo(n)}}function Fo(e){if(On(e))return;let t;try{t=new URL(e)}catch{return}let n=An(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 Ou("sha256").update(i).digest("hex").slice(0,32)}var At=2;var It="ev-ai-agent-hook";function xu(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function Ho(e){let t=xu(e);return t===It||t===`${It}.exe`}var ES=`current/${It}`,yS=`.ev-ai/agent-hook/${It}`,jo=5e3,Ko=5e3,Pn=3e3;var kn=3e3,$o=1500,Bo=4*1024,bn=256*1024,Nu=4*1024,Go=32*1024,We=840*60*1e3,xn="1.2.8",RS=`@ev-ai/agent-hook@${xn}`;import{existsSync as Zp,mkdirSync as qp,readdirSync as Qp,readFileSync as ef,unlinkSync as Oi,writeFileSync as tf}from"node:fs";import{homedir as Ti}from"node:os";import{join as nr}from"node:path";import{createHash as Yo,randomBytes as Lu}from"node:crypto";import{existsSync as Xo,mkdirSync as Nn,readFileSync as Zo,unlinkSync as qo,writeFileSync as Qo}from"node:fs";import{homedir as Mn}from"node:os";import{dirname as Ot,join as wn,resolve as vu}from"node:path";var Mu=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),wu=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function B(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||wu.has(n)||r.includes("[bot]")||Mu.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}var Uu="installation.json",Du="cloud-bootstrap.lock",Fu=6e4;function es(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function re(e=Mn()){return wn(e,".ev-ai","agent-hook")}function Hu(e=Mn()){return wn(re(e),Uu)}function ts(e){return wn(Ot(e),Du)}function ns(){return Lu(8).toString("hex")}function xe(e){return Yo("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 rs(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function ju(e=process.env){let t=A(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!rs(t)){h(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function os(e,t){return e&&rs(e)?e:(e&&h(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),ju(t))}function Ku(e){return/^[0-9a-f]{16}$/.test(e)}function $u(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 xe(`github_actions|${t}|${n}`)}if(A(e.CODESPACES)||A(e.CODESPACE_NAME)){let t=A(e.CODESPACE_NAME);if(t)return xe(`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 xe(`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 xe(`gitlab|${t}|${n}`)}return null}var Bu="cursoragent@cursor.com";function Gu(e){let t=A(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Bu?null:t}function zu(e,t){return A(e.CURSOR_PROJECT_DIR)??A(e.CLAUDE_PROJECT_DIR)??t}function Vu(e){return Ge(e).replace(/\.git$/i,"").toLowerCase()}async function Wu(e){let t=await w("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Vu(t):e}async function Ju(e){let t=A(await w("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!B(null,t))return t;let n=A(await w("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!B(null,n)?n:null}function Yu(e,t){let n=zu(e,t);return n?xe(`cursor_cloud|${n}|${Gu(e)??""}`):null}async function Xu(e,t){let n=A(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Wu(n),o=await Ju(n);return xe(`claude_remote|${r}|${o??""}`)}function zo(e,t){let n=os(e,t);if(n)return n;let r=$u(t);return r||ns()}async function Zu(e){let n=await w("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||vu(e);return Yo("sha256").update(n).digest("hex").slice(0,16)}function qu(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 Qu(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=qu(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function ye(e){if(Xo(e))try{return Qu(Zo(e,"utf8"))}catch{}}function Ln(e){return ye(e)}function ss(e,t,n){let r=ye(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Z(e,`${JSON.stringify(o,null,2)}
14
14
  `)}catch(s){let i=s instanceof Error?s.message:String(s);h(`WARN: operator identity cache write failed open: ${i}`)}}function is(e,t=Date.now()){if(!e)return!0;if(ye(e)?.operator_identity_hash)return!1;let n=ts(e);try{if(Xo(n)){let r=Number.NaN;try{r=Number(Zo(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Fu)return!1;try{qo(n)}catch{}}}catch{}try{return Nn(Ot(n),{recursive:!0}),Qo(n,`${t}
15
15
  `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(ls(r))return!1;let o=r instanceof Error?r.message:String(r);return h(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function as(e){if(e)try{qo(ts(e))}catch{}}function cs(e,t){let r=ye(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function us(e,t,n){if(!n)return;let r=ye(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{Z(e,`${JSON.stringify(o,null,2)}
16
16
  `)}catch(s){let i=s instanceof Error?s.message:String(s);h(`WARN: platform_agent_id cache write failed open: ${i}`)}}function ls(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function el(e,t){Nn(Ot(e),{recursive:!0}),Qo(e,`${JSON.stringify(t,null,2)}
17
17
  `,{encoding:"utf8",flag:"wx"})}function Vo(e,t){try{return el(e,t),t}catch(n){if(!ls(n))throw n;return ye(e)}}function Wo(e,t){Nn(Ot(e),{recursive:!0}),Z(e,`${JSON.stringify(t,null,2)}
18
- `)}function Jo(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function ds(e,t={}){let n=t.home??Mn(),r=t.env??process.env,o=await Zu(e),s=Hu(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=Ve(i),c=os(t.overrideId,r),u=a==="cursor_cloud"&&Sn(i)?Yu(r,e):a==="claude_remote"?await Xu(r,e):null,l=ye(s);if(l){let _=l;if(c&&c===l.installation_id&&l.pinned!==!0&&(_={...l,pinned:!0},Wo(s,_)),!!u&&u!==_.installation_id&&!c&&_.pinned!==!0&&Ku(_.installation_id)&&u){let E={installation_id:u,..._.platform_agent_ids?{platform_agent_ids:_.platform_agent_ids}:{}};return Wo(s,E),{installationId:u,storePath:s,repoKey:o}}return{installationId:_.installation_id,storePath:s,repoKey:o}}let p=c??u??zo(void 0,r),f=Vo(s,Jo(p,c));if(f)return{installationId:f.installation_id,storePath:s,repoKey:o};let d=c??u??zo(void 0,r),g=Vo(s,Jo(d===p?ns():d,c));if(g)return{installationId:g.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{open as ps,mkdir as tl,readFile as nl,readdir as rl,rename as ol,stat as sl,rmdir as il,unlink as al,utimes as cl}from"node:fs/promises";var Tt=new WeakMap;function ms(e){if(e&&typeof e=="object"&&"code"in e)return e}function vn(e){return ms(e)?.code==="ENOENT"}function gs(e){return ms(e)?.code==="EEXIST"}async function _s(e,t){try{return await e.readdir(t)}catch(n){if(vn(n))return[];throw n}}function hs(){return{async open(e,t){let n=await ps(e,t),r={path:e};return Tt.set(r,n),r},async write(e,t){let n=fs(e),r=typeof t=="string"?Buffer.from(t,"utf8"):t;await n.write(r)},async fsync(e){await fs(e).sync()},async close(e){let t=Tt.get(e);Tt.delete(e),t&&await t.close()},rename:ol,async readdir(e){return rl(e)},readFile:nl,async stat(e){let t=await sl(e);return{mtimeMs:t.mtimeMs,size:t.size,isDirectory:()=>t.isDirectory()}},async mkdir(e,t){await tl(e,t)},unlink:al,rmdir:il,utimes:cl,async fsyncDir(e){if(process.platform==="win32")return;let t=await ps(e,"r");try{await t.sync()}finally{await t.close()}}}}function fs(e){let t=Tt.get(e);if(!t)throw new Error("closed");return t}import{existsSync as Ol}from"node:fs";import{existsSync as gl}from"node:fs";import{homedir as ys}from"node:os";import{join as _l}from"node:path";import{existsSync as ul,readdirSync as Ss}from"node:fs";import{homedir as Pt}from"node:os";import{join as K}from"node:path";function ll(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 dl(e=process.platform){let t=ll(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!ul(r))return n;let o=Ss(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function Un(e=process.platform,t=Pt()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:dl(e)}}function pl(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 fl(e=process.platform,t=Pt()){let n=[K(pl(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of Ss(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function ml(e=process.platform,t=Pt()){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 kt(e,t=process.platform,n=Pt()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Un(t,n);return[r,...o]}case"cursor":return fl(t,n);default:return ml(t,n)}}function Rs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var hl={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 Es(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function Sl(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:Es(n.mcpJson,t.mcpJson),mcpToml:Es(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function Cs(e){return Object.fromEntries(Object.entries(hl).map(([t,n])=>[t,Sl(n,n[e])]))}var Ne=Cs("homeOnly"),le=Cs("projectOnly");function El(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function yl(e,t){return El(e).some(n=>gl(_l(t,n)))}function Is(e,t){for(let n of e)if(yl(n,t))return!0;return!1}function ue(e){return[...new Set(e)]}function de(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:ue(t),subagents:ue(n),commands:ue(r),rules:ue(o),memory:ue(s),settings:ue(i),mcp:ue(a)}}function Rl(e,t=ys(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...kt(o.managed,n,t));return ue(r)}var pe=de(Object.values(Ne));function As(e=ys(),t=process.platform){return Rl(Object.values(Ne),e,t)}import{existsSync as Cl}from"node:fs";import{resolve as Dn}from"node:path";function z(e){return Dn(e).replaceAll("\\","/").replace(/\/$/,"")}function Re(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function bt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var Il=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function Je(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Il.test(t)?null:t}function Me(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=z(o);n.has(s)||(n.add(s),r.push(s))}return r}function Al(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function q(e,t,n,r=Cl){for(let o of e)for(let s of t){let i=z(Dn(o,s)),a=Dn(o,s,n).replaceAll("\\","/");if(Al(i,a)&&r(a))return a}return null}var Ts=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,Ps=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Tl=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,Os=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"]),Pl=/^[a-z][a-z0-9-]{1,63}$/,kl=[".cursor/skills",".claude/skills",".agents/skills"],bl=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],xl=Re(kl,de(Object.values(le)).skills),Nl=Re(bl,de(Object.values(Ne)).skills),Ml=new Set(["read","read_file","view"]),wl=new Set(["bash","shell","zsh"]);function Fn(e){let t=e.replace(/\\/g,"/");return Ts.exec(t)?.[1]??null}function Ll(e){let t=e.replace(/\\/g,"/"),r=Ps.exec(t)?.[1];return r?r.toLowerCase():null}function vl(e){return Fn(e)??Ll(e)}function Ul(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(G(e,null)):!e||typeof e!="object"?null:Ul(e)}function ks(e){if(typeof e=="string")return ks(G(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Hn(e){let t=ks(e.tool_input);if(t)return t;let n=Ee(e.command);return n.length>0?n:null}function Dl(e){let t=e.replace(/\\/g,"/"),n=Ts.exec(t);if(n?.[1])return n[1];let o=Ps.exec(t)?.[1];return o?o.toLowerCase():null}function Fl(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function jn(e){let t=xt(e.tool_input)??Ee(e.file_path);return t.length>0?t:null}function Ye(e,t,n){let r=Fl(e).toLowerCase();if(Ml.has(r)){let o=jn(e);return o?t(o):null}if(wl.has(r)){let o=Hn(e);return o?n(o):null}return null}function bs(e){return Ye(e,vl,Dl)}function Hl(e){let t=new Set,n=[];for(let r of e.matchAll(Tl)){let o=r[1]?.toLowerCase();!o||t.has(o)||jl(o)||(t.add(o),n.push(o))}return n}function jl(e){let t=e.split("/")[0];return Os.has(e)||t!==void 0&&Os.has(t)}function xs(e){let t=e.skillId.toLowerCase();if(!Pl.test(t))return null;let n=e.exists??Ol,r=`${t}/SKILL.md`,o=q(Me(e.launchCwd,e.gitRoot),xl,r,n);return o!==null?o:e.home?q([z(e.home)],Nl,r,n):null}function Kl(e){return Ee(e.prompt)}function Ns(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=Kl(e);return n?Hl(n):[]}var Wn=Be(ve(),1);import{existsSync as Rp}from"node:fs";var Ie={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Ze(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function yp(e){if(!e)return"";let t=Ge(e).replace(/\.git$/i,""),n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return Ze(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Ze(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Ze(o[1]):Ze(t)}async function Ut(e=process.cwd()){let t=await J("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([J("git",["remote","get-url","origin"],2e3,{cwd:e}),J("git",["branch","--show-current"],2e3,{cwd:e}),J("git",["rev-parse","HEAD"],2e3,{cwd:e}),J("git",["status","--porcelain"],2e3,{cwd:e})]);return{remote:n.ok?Ge(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 ei(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ie[n];if(!a)return"";let c=es(n,e.scope_path,i);if(s){let g=cs(s,c);if(g)return g}let u=o??await Ut(r),l=u?.remote?yp(u.remote):"";if(l||(l=Ze(process.env.GITHUB_REPOSITORY??"")),!l)return"";let p=e.scope_path??"",f=p?`${p}/`:"",d=`${l}:${f}${a}`;return s&&us(s,c,d),d}var Cp=[".cursor/rules",".claude/rules",".codex/rules"],Ip=de(Object.values(le)).rules;function Ap(e){return Re(bt(e?Ie[e]:void 0,Cp),Ip)}var Op=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function ti(e){let t=Je(e.relativePath);if(!t)return null;let n=e.exists??Rp,r=Me(e.launchCwd,e.gitRoot),o=Ap(e.runnerPlatform),s=q(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=q(r,["."],t,n);if(i!==null)return i}return e.home?q([z(e.home)],o,t,n):null}function Tp(e){let t=e.replace(/\\/g,"/"),r=Op.exec(t)?.[1];return r?(0,Wn.nativeKeyForRulePath)(r):null}function ni(e){return Ye(e,Wn.nativeKeyForRulePath,Tp)}function ri(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function oi(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=Je(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var Jn=Be(ve(),1);import{existsSync as Pp}from"node:fs";var kp=[".cursor/commands",".claude/commands",".codex/prompts"],bp=de(Object.values(le)).commands;function xp(e){return Re(bt(e?Ie[e]:void 0,kp),bp)}var Np=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function si(e){let t=Je(e.commandId);if(!t)return null;let n=e.exists??Pp,r=`${t}.md`,o=xp(e.runnerPlatform),s=q(Me(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?q([z(e.home)],o,r,n):null}function Mp(e){let t=e.replace(/\\/g,"/"),r=Np.exec(t)?.[1];return r?(0,Jn.nativeKeyForCommandPath)(r):null}function ii(e){return Ye(e,Jn.nativeKeyForCommandPath,Mp)}import{existsSync as ci}from"node:fs";import{homedir as ui}from"node:os";import{join as qe,resolve as Yn,sep as ai}from"node:path";function Xn(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Zn(e,t){let n=t.toLowerCase();return Xn(e).some(r=>r.toLowerCase()===n)}function Dt(e,t,n){if(!ci(e))return;let r=U(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function wp(e,t,n){if(!ci(e))return;let r=U(e,{}),o=Yn(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Yn(a);(o===c||o.startsWith(c.endsWith(ai)?c:c+ai))&&(s===null||c.length>Yn(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"?(Dt(qe(r,".claude.json"),{source:"claude_json_user"},o),wp(qe(r,".claude.json"),t,o)):n==="cursor"&&Dt(qe(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Dt(qe(t,".mcp.json"),{source:"mcp_json"},o),Dt(qe(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function qn(e,t=process.cwd(),n="claude",r=ui()){return[...li(e,t,n,r).values()].map(o=>o.declared)}function di(e,t,n=process.cwd(),r="claude",o=ui()){let s=li(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Zn(a,e))return c.config??null;return null}function Qn(e){let t=Do(e);if(t.problem){h(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function pi(e,t){if(R(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Lp(){return!!(I("CURSOR_VERSION")??I("CURSOR_PROJECT_DIR"))}function fi(e,t,n){return e!=="claude"&&e!=="codex"?!1:pi(t,n)?!0:Lp()}var vp=new Set(["sessionstart","sessionend","stop","stopfailure","pretooluse","posttooluse","posttoolusefailure","permissiondenied","subagentstart","subagentstop","userpromptexpansion","userpromptsubmit"]);function Qe(e,t,n,r){return pi(e,t)?"cursor":Et(r)?r:Et(n)?n:R(e,"turn_id")?"codex":R(e,"session_id")||vp.has(t.toLowerCase())?"claude":"unknown"}function Ft(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Up(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 mi(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function gi(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function _i(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function et(e){return R(e,"session_id")||R(e,"conversation_id")}function er(e){return R(e,"prompt.id")||R(e,"prompt_id")||R(e,"generation_id")||R(e,"turn_id")}function tr(e){return R(e,"hook_event_name")||R(e,"event")}function hi(e,t,n){let r=et(e),o=er(e),s=tr(e),i=R(e,"source"),a=Qe(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Dp=["session_start","session_end","tool_invoked","skill_invoked"];function Fp(e){return Dp.includes(e)}function Si(e,t){return e&&Fp(e)?e:Up(t.toLowerCase())}var Hp={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Ht(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ei(e,t=""){let n=R(e,"tool_name")||R(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Ht(n)&&(n=`MCP:${n}`):n=Hp[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?Ee(o.skill)||Ee(o.skill_name):"")||R(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=bs(a);let c=ni(a),u=ii(a);return{toolName:n,skillName:i,ruleName:c,commandName:u}}var jp=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function yi(e){for(let t of["subagent_type","agent_type"]){let n=R(e,t);if(n&&jp.test(n))return n}return null}function Ri(e){let t=ne(e,"duration_ms");if(typeof t=="number")return t;let n=ne(e,"duration");return typeof n=="number"?n:null}var Kp="error",$p="interrupted",Bp="permission_denied",Gp=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function tt(e){return Gp.test(e)?e:null}function zp(e){for(let t of["failure_type","error_type"]){let n=tt(R(e,t));if(n)return n}return null}function Ci(e,t){return ne(e,"is_interrupt")===!0?$p:t.toLowerCase()==="permissiondenied"?Bp:zp(e)??Kp}function Ii(e,t){let n=null;for(let r of e)r&&t(r)&&(n===null||r.length>n.length)&&(n=r);return n}function Vp(e,t){return Ii(t,n=>e===n||e.startsWith(`${n}_`)||e.startsWith(`${n}-`))}function Wp(e,t){return Ii(t,n=>Zn(n,e))}function Jp(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of Xn(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:Wp(o[1],t)??o[1],mcpTool:o[2]}}function Yp(e,t){if(/^mcp__/i.test(e))return Jp(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:Vp(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function Xp(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function Ai(e,t=[],n=""){let r=e?Yp(e,t):{mcpServer:null,mcpTool:null},o=tt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Ht(e)&&(s=e),s&&(s=Xp(s,o)),{mcpServer:o,mcpTool:s}}var Pi=3e4,nf="claims",rf=!0,of=100,sf=new Set(["sessionstart","sessionend","stopfailure"]),af=["tool_name","tool","command","file_path","url"];function cf(e=Ti()){return nr(re(e),nf)}function ki(e,t){try{let n=ef(e,"utf8").split(`
19
- `,1)[0]??"";return t-Number(n.trim())}catch{return Number.NaN}}function uf(e){let t=[];for(let n of af){let r=R(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":ze(t.join("\0"))}function lf(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=sf.has(n);if(!a&&!c)return;let u=e.runnerPlatform.trim()||"unknown";return ze(`${u}|${t}|${n}|${r}|${o}|${i}|${s}`)}function df(e,t=Date.now()){let n;try{n=Qp(e)}catch{return}let r=0;for(let o of n){if(r>=of)break;r+=1;let s=nr(e,o),i=ki(s,t);if(!(!Number.isFinite(i)||i<Pi))try{Oi(s)}catch{}}}function pf(e,t,n=Date.now()){let r=nr(t,e);try{if(Zp(r)){let o=ki(r,n);if(Number.isFinite(o)&&o>=0&&o<Pi)return!1;try{Oi(r)}catch{}}}catch{}try{qp(t,{recursive:!0}),tf(r,`${n}
18
+ `)}function Jo(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function ds(e,t={}){let n=t.home??Mn(),r=t.env??process.env,o=await Zu(e),s=Hu(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=Ve(i),c=os(t.overrideId,r),l=a==="cursor_cloud"&&Sn(i)?Yu(r,e):a==="claude_remote"?await Xu(r,e):null,u=ye(s);if(u){let _=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(_={...u,pinned:!0},Wo(s,_)),!!l&&l!==_.installation_id&&!c&&_.pinned!==!0&&Ku(_.installation_id)&&l){let E={installation_id:l,..._.platform_agent_ids?{platform_agent_ids:_.platform_agent_ids}:{}};return Wo(s,E),{installationId:l,storePath:s,repoKey:o}}return{installationId:_.installation_id,storePath:s,repoKey:o}}let p=c??l??zo(void 0,r),f=Vo(s,Jo(p,c));if(f)return{installationId:f.installation_id,storePath:s,repoKey:o};let d=c??l??zo(void 0,r),g=Vo(s,Jo(d===p?ns():d,c));if(g)return{installationId:g.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{open as ps,mkdir as tl,readFile as nl,readdir as rl,rename as ol,stat as sl,rmdir as il,unlink as al,utimes as cl}from"node:fs/promises";var Tt=new WeakMap;function ms(e){if(e&&typeof e=="object"&&"code"in e)return e}function vn(e){return ms(e)?.code==="ENOENT"}function gs(e){return ms(e)?.code==="EEXIST"}async function _s(e,t){try{return await e.readdir(t)}catch(n){if(vn(n))return[];throw n}}function hs(){return{async open(e,t){let n=await ps(e,t),r={path:e};return Tt.set(r,n),r},async write(e,t){let n=fs(e),r=typeof t=="string"?Buffer.from(t,"utf8"):t;await n.write(r)},async fsync(e){await fs(e).sync()},async close(e){let t=Tt.get(e);Tt.delete(e),t&&await t.close()},rename:ol,async readdir(e){return rl(e)},readFile:nl,async stat(e){let t=await sl(e);return{mtimeMs:t.mtimeMs,size:t.size,isDirectory:()=>t.isDirectory()}},async mkdir(e,t){await tl(e,t)},unlink:al,rmdir:il,utimes:cl,async fsyncDir(e){if(process.platform==="win32")return;let t=await ps(e,"r");try{await t.sync()}finally{await t.close()}}}}function fs(e){let t=Tt.get(e);if(!t)throw new Error("closed");return t}import{existsSync as Ol}from"node:fs";import{existsSync as gl}from"node:fs";import{homedir as ys}from"node:os";import{join as _l}from"node:path";import{existsSync as ul,readdirSync as Ss}from"node:fs";import{homedir as Pt}from"node:os";import{join as K}from"node:path";function ll(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 dl(e=process.platform){let t=ll(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!ul(r))return n;let o=Ss(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function Un(e=process.platform,t=Pt()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:dl(e)}}function pl(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 fl(e=process.platform,t=Pt()){let n=[K(pl(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of Ss(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function ml(e=process.platform,t=Pt()){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 kt(e,t=process.platform,n=Pt()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Un(t,n);return[r,...o]}case"cursor":return fl(t,n);default:return ml(t,n)}}function Rs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var hl={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 Es(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function Sl(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:Es(n.mcpJson,t.mcpJson),mcpToml:Es(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function Cs(e){return Object.fromEntries(Object.entries(hl).map(([t,n])=>[t,Sl(n,n[e])]))}var Ne=Cs("homeOnly"),le=Cs("projectOnly");function El(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function yl(e,t){return El(e).some(n=>gl(_l(t,n)))}function Is(e,t){for(let n of e)if(yl(n,t))return!0;return!1}function ue(e){return[...new Set(e)]}function de(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:ue(t),subagents:ue(n),commands:ue(r),rules:ue(o),memory:ue(s),settings:ue(i),mcp:ue(a)}}function Rl(e,t=ys(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...kt(o.managed,n,t));return ue(r)}var pe=de(Object.values(Ne));function As(e=ys(),t=process.platform){return Rl(Object.values(Ne),e,t)}import{existsSync as Cl}from"node:fs";import{resolve as Dn}from"node:path";function z(e){return Dn(e).replaceAll("\\","/").replace(/\/$/,"")}function Re(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function bt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var Il=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function Je(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Il.test(t)?null:t}function Me(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=z(o);n.has(s)||(n.add(s),r.push(s))}return r}function Al(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function q(e,t,n,r=Cl){for(let o of e)for(let s of t){let i=z(Dn(o,s)),a=Dn(o,s,n).replaceAll("\\","/");if(Al(i,a)&&r(a))return a}return null}var Ts=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,Ps=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Tl=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,Os=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"]),Pl=/^[a-z][a-z0-9-]{1,63}$/,kl=[".cursor/skills",".claude/skills",".agents/skills"],bl=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],xl=Re(kl,de(Object.values(le)).skills),Nl=Re(bl,de(Object.values(Ne)).skills),Ml=new Set(["read","read_file","view"]),wl=new Set(["bash","shell","zsh"]);function Fn(e){let t=e.replace(/\\/g,"/");return Ts.exec(t)?.[1]??null}function Ll(e){let t=e.replace(/\\/g,"/"),r=Ps.exec(t)?.[1];return r?r.toLowerCase():null}function vl(e){return Fn(e)??Ll(e)}function Ul(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(G(e,null)):!e||typeof e!="object"?null:Ul(e)}function ks(e){if(typeof e=="string")return ks(G(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Hn(e){let t=ks(e.tool_input);if(t)return t;let n=Ee(e.command);return n.length>0?n:null}function Dl(e){let t=e.replace(/\\/g,"/"),n=Ts.exec(t);if(n?.[1])return n[1];let o=Ps.exec(t)?.[1];return o?o.toLowerCase():null}function Fl(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function jn(e){let t=xt(e.tool_input)??Ee(e.file_path);return t.length>0?t:null}function Ye(e,t,n){let r=Fl(e).toLowerCase();if(Ml.has(r)){let o=jn(e);return o?t(o):null}if(wl.has(r)){let o=Hn(e);return o?n(o):null}return null}function bs(e){return Ye(e,vl,Dl)}function Hl(e){let t=new Set,n=[];for(let r of e.matchAll(Tl)){let o=r[1]?.toLowerCase();!o||t.has(o)||jl(o)||(t.add(o),n.push(o))}return n}function jl(e){let t=e.split("/")[0];return Os.has(e)||t!==void 0&&Os.has(t)}function xs(e){let t=e.skillId.toLowerCase();if(!Pl.test(t))return null;let n=e.exists??Ol,r=`${t}/SKILL.md`,o=q(Me(e.launchCwd,e.gitRoot),xl,r,n);return o!==null?o:e.home?q([z(e.home)],Nl,r,n):null}function Kl(e){return Ee(e.prompt)}function Ns(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=Kl(e);return n?Hl(n):[]}var Wn=Be(ve(),1);import{existsSync as Rp}from"node:fs";var Ie={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Ze(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function yp(e){if(!e)return"";let t=Ge(e).replace(/\.git$/i,""),n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return Ze(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Ze(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Ze(o[1]):Ze(t)}async function Ut(e=process.cwd()){let t=await J("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([J("git",["remote","get-url","origin"],2e3,{cwd:e}),J("git",["branch","--show-current"],2e3,{cwd:e}),J("git",["rev-parse","HEAD"],2e3,{cwd:e}),J("git",["status","--porcelain"],2e3,{cwd:e})]);return{remote:n.ok?Ge(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 ei(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ie[n];if(!a)return"";let c=es(n,e.scope_path,i);if(s){let g=cs(s,c);if(g)return g}let l=o??await Ut(r),u=l?.remote?yp(l.remote):"";if(u||(u=Ze(process.env.GITHUB_REPOSITORY??"")),!u)return"";let p=e.scope_path??"",f=p?`${p}/`:"",d=`${u}:${f}${a}`;return s&&us(s,c,d),d}var Cp=[".cursor/rules",".claude/rules",".codex/rules"],Ip=de(Object.values(le)).rules;function Ap(e){return Re(bt(e?Ie[e]:void 0,Cp),Ip)}var Op=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function ti(e){let t=Je(e.relativePath);if(!t)return null;let n=e.exists??Rp,r=Me(e.launchCwd,e.gitRoot),o=Ap(e.runnerPlatform),s=q(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=q(r,["."],t,n);if(i!==null)return i}return e.home?q([z(e.home)],o,t,n):null}function Tp(e){let t=e.replace(/\\/g,"/"),r=Op.exec(t)?.[1];return r?(0,Wn.nativeKeyForRulePath)(r):null}function ni(e){return Ye(e,Wn.nativeKeyForRulePath,Tp)}function ri(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function oi(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=Je(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var Jn=Be(ve(),1);import{existsSync as Pp}from"node:fs";var kp=[".cursor/commands",".claude/commands",".codex/prompts"],bp=de(Object.values(le)).commands;function xp(e){return Re(bt(e?Ie[e]:void 0,kp),bp)}var Np=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function si(e){let t=Je(e.commandId);if(!t)return null;let n=e.exists??Pp,r=`${t}.md`,o=xp(e.runnerPlatform),s=q(Me(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?q([z(e.home)],o,r,n):null}function Mp(e){let t=e.replace(/\\/g,"/"),r=Np.exec(t)?.[1];return r?(0,Jn.nativeKeyForCommandPath)(r):null}function ii(e){return Ye(e,Jn.nativeKeyForCommandPath,Mp)}import{existsSync as ci}from"node:fs";import{homedir as ui}from"node:os";import{join as qe,resolve as Yn,sep as ai}from"node:path";function Xn(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Zn(e,t){let n=t.toLowerCase();return Xn(e).some(r=>r.toLowerCase()===n)}function Dt(e,t,n){if(!ci(e))return;let r=U(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function wp(e,t,n){if(!ci(e))return;let r=U(e,{}),o=Yn(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Yn(a);(o===c||o.startsWith(c.endsWith(ai)?c:c+ai))&&(s===null||c.length>Yn(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"?(Dt(qe(r,".claude.json"),{source:"claude_json_user"},o),wp(qe(r,".claude.json"),t,o)):n==="cursor"&&Dt(qe(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Dt(qe(t,".mcp.json"),{source:"mcp_json"},o),Dt(qe(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function qn(e,t=process.cwd(),n="claude",r=ui()){return[...li(e,t,n,r).values()].map(o=>o.declared)}function di(e,t,n=process.cwd(),r="claude",o=ui()){let s=li(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Zn(a,e))return c.config??null;return null}function Qn(e){let t=Do(e);if(t.problem){h(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function pi(e,t){if(R(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Lp(){return!!(I("CURSOR_VERSION")??I("CURSOR_PROJECT_DIR"))}function fi(e,t,n){return e!=="claude"&&e!=="codex"?!1:pi(t,n)?!0:Lp()}var vp=new Set(["sessionstart","sessionend","stop","stopfailure","pretooluse","posttooluse","posttoolusefailure","permissiondenied","subagentstart","subagentstop","userpromptexpansion","userpromptsubmit"]);function Qe(e,t,n,r){return pi(e,t)?"cursor":Et(r)?r:Et(n)?n:R(e,"turn_id")?"codex":R(e,"session_id")||vp.has(t.toLowerCase())?"claude":"unknown"}function Ft(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Up(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 mi(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function gi(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function _i(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function et(e){return R(e,"session_id")||R(e,"conversation_id")}function er(e){return R(e,"prompt.id")||R(e,"prompt_id")||R(e,"generation_id")||R(e,"turn_id")}function tr(e){return R(e,"hook_event_name")||R(e,"event")}function hi(e,t,n){let r=et(e),o=er(e),s=tr(e),i=R(e,"source"),a=Qe(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Dp=["session_start","session_end","tool_invoked","skill_invoked"];function Fp(e){return Dp.includes(e)}function Si(e,t){return e&&Fp(e)?e:Up(t.toLowerCase())}var Hp={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Ht(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ei(e,t=""){let n=R(e,"tool_name")||R(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Ht(n)&&(n=`MCP:${n}`):n=Hp[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?Ee(o.skill)||Ee(o.skill_name):"")||R(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=bs(a);let c=ni(a),l=ii(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var jp=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function yi(e){for(let t of["subagent_type","agent_type"]){let n=R(e,t);if(n&&jp.test(n))return n}return null}function Ri(e){let t=ne(e,"duration_ms");if(typeof t=="number")return t;let n=ne(e,"duration");return typeof n=="number"?n:null}var Kp="error",$p="interrupted",Bp="permission_denied",Gp=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function tt(e){return Gp.test(e)?e:null}function zp(e){for(let t of["failure_type","error_type"]){let n=tt(R(e,t));if(n)return n}return null}function Ci(e,t){return ne(e,"is_interrupt")===!0?$p:t.toLowerCase()==="permissiondenied"?Bp:zp(e)??Kp}function Ii(e,t){let n=null;for(let r of e)r&&t(r)&&(n===null||r.length>n.length)&&(n=r);return n}function Vp(e,t){return Ii(t,n=>e===n||e.startsWith(`${n}_`)||e.startsWith(`${n}-`))}function Wp(e,t){return Ii(t,n=>Zn(n,e))}function Jp(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of Xn(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:Wp(o[1],t)??o[1],mcpTool:o[2]}}function Yp(e,t){if(/^mcp__/i.test(e))return Jp(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:Vp(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function Xp(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function Ai(e,t=[],n=""){let r=e?Yp(e,t):{mcpServer:null,mcpTool:null},o=tt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Ht(e)&&(s=e),s&&(s=Xp(s,o)),{mcpServer:o,mcpTool:s}}var Pi=3e4,nf="claims",rf=!0,of=100,sf=new Set(["sessionstart","sessionend","stopfailure"]),af=["tool_name","tool","command","file_path","url"];function cf(e=Ti()){return nr(re(e),nf)}function ki(e,t){try{let n=ef(e,"utf8").split(`
19
+ `,1)[0]??"";return t-Number(n.trim())}catch{return Number.NaN}}function uf(e){let t=[];for(let n of af){let r=R(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":ze(t.join("\0"))}function lf(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=sf.has(n);if(!a&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return ze(`${l}|${t}|${n}|${r}|${o}|${i}|${s}`)}function df(e,t=Date.now()){let n;try{n=Qp(e)}catch{return}let r=0;for(let o of n){if(r>=of)break;r+=1;let s=nr(e,o),i=ki(s,t);if(!(!Number.isFinite(i)||i<Pi))try{Oi(s)}catch{}}}function pf(e,t,n=Date.now()){let r=nr(t,e);try{if(Zp(r)){let o=ki(r,n);if(Number.isFinite(o)&&o>=0&&o<Pi)return!1;try{Oi(r)}catch{}}}catch{}try{qp(t,{recursive:!0}),tf(r,`${n}
20
20
  `,{encoding:"utf8",flag:"wx"})}catch(o){if(gs(o))return!1;let s=o instanceof Error?o.message:String(o);return h(`WARN: event claim failed open: ${s}`),!0}return df(t,n),!0}function ff(e,t,n){let r=et(e),o=er(e),s=R(e,"tool_use_id"),i=R(e,"subagent_id")||R(e,"agent_id"),a=Qe(e,t,void 0,n),c=uf(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function bi(e,t,n,r=Ti(),o=Date.now()){if(!rf)return!0;let s=lf(ff(e,t,n));if(!s)return!0;let i=pf(s,cf(r),o);return!i&&I("EV_AI_HOOK_DEBUG")&&h(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{closeSync as mf,writeSync as gf}from"node:fs";function xi(e=process.env){let t=e[En];if(delete e[En],t===void 0)return;let n=Number.parseInt(t,10);if(!(!Number.isInteger(n)||n<3)){try{gf(n,bo)}catch{}try{mf(n)}catch{}}}function rr(e=process.env){let t=e[Ao];if(t)return{launcherVersion:t,hookSource:e[Oo]??"",fallbackReason:e[To],launcherScope:e[Po]}}function Ni(e,t){return(e?Fo(e):void 0)===t}import{realpathSync as sh}from"node:fs";import{homedir as ih}from"node:os";var T=Be(ve(),1);import{existsSync as _f,readFileSync as hf}from"node:fs";import{homedir as Mi}from"node:os";import{join as Sf}from"node:path";var Ef="cloud-cache.json",yf=1440*60*1e3,Rf=900*1e3;function Cf(e=Mi()){return Sf(re(e),Ef)}function If(e){if(!_f(e))return;let t=G(hf(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 Af(e,t){try{Z(e,`${JSON.stringify(t)}
21
21
  `)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: cloud cache write failed open: ${r}`)}}function Of(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Rf:yf;return n-e.probed_at<r}async function Tf(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 Pf(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 kf(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 bf(e){let t=await Promise.allSettled([Tf(e),Pf(e),kf(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function wi(e,t){if(e==="interactive")return null;let n=t?.home??Mi(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Cf(n),i=If(s);if(Of(i,e,o))return i.result;let a=await bf(r);return Af(s,{context:e,probed_at:o,result:a}),a}var xf=["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"],Nf=["CURSOR_PROJECT_DIR"],Mf=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function wf(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Mf.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Li(e=process.env){let t=xf.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:wf(e[r]??"")}:{name:r,present:!1}),n=Nf.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as um}from"node:os";import{homedir as vi}from"node:os";import{join as Lf}from"node:path";function vf(e=vi()){return Lf(e,".claude.json")}function jt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ui(e=vi()){let n=U(vf(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=jt(n.emailAddress),o=jt(n.fullName)??jt(n.displayName),s=jt(n.accountUuid),i=r??s;return!i||B(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as Hi}from"node:os";import{join as Di}from"node:path";var Uf="https://api.openai.com/auth";function Ue(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ji(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Df(e){let t=e.split(".");if(t.length!==3||t.some(r=>r.length===0))return null;let n=t[1];if(!n)return null;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return ji(r)}catch{return null}}function Fi(e,t,n){return Ue(e[n])??Ue(t?.[n])}function Ff(e=process.env,t=Hi()){let n=Ue(e.CODEX_HOME)??Di(t,".codex");return Di(n,"auth.json")}function Ki(e=process.env,t=Hi()){let n=U(Ff(e,t),{}),r=Ue(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Ue(n.OPENAI_API_KEY))return null;let o=Ue(n.tokens?.id_token);if(!o)return null;let s=Df(o);if(!s)return null;let i=ji(s[Uf]),a=Fi(s,i,"name"),c=Fi(s,i,"email");return!c||B(a,c)?null:{git_user_name:null,git_user_email:null,platform_login:c,identity_source:"codex_oauth"}}import{homedir as Bt}from"node:os";import{join as ie}from"node:path";import{join as Hf}from"node:path";var jf="cursor-ide-identity.json",Kf=We;function Bi(e){return Hf(re(e),jf)}function $i(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Gi(e){let t=U(e,{}),n=t.read_at_ms,r=t.db_path;if(!(typeof n!="number"||!Number.isFinite(n)||typeof r!="string"))return{read_at_ms:n,db_path:r,email:$i(t.email),auth_id:$i(t.auth_id)}}function zi(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<Kf}function Vi(e,t){try{Z(e,`${JSON.stringify(t)}
22
22
  `)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as $f}from"node:child_process";import{existsSync as Bf}from"node:fs";import{createRequire as Gf}from"node:module";import{pathToFileURL as zf}from"node:url";var Ji=Gf(import.meta.url),Kt=`
@@ -29,17 +29,17 @@ ORDER BY key
29
29
  `.trim(),or=new Map;function Wi(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 Yi(e){return e.toLowerCase().includes("token")}function Xi(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=Wi(r.key),s=Wi(r.value);o&&s&&!Yi(o)&&t.set(o,s)}return t}function Vf(e){let t=zf(e);return t.search="mode=ro&immutable=1",t.href}function Wf(e){try{let t=Ji("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(Kt)??n.prepare(Kt);return Xi(r.all?.())}finally{n.close?.()}}catch{return null}}function Jf(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 Yf(e){try{return Jf(()=>{let t=Ji("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return Xi(n.prepare(Kt).all?.())}finally{n.close?.()}})}catch{return null}}function Xf(e){let t=new Map;for(let n of e.split(`
30
30
  `)){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&&!Yi(s)&&t.set(s,i)}return t}function Zf(e){try{let t=$f("sqlite3",["-noheader","-batch","-separator"," ",e,Kt],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return Xf(t)}catch{return null}}function Zi(e){let t=or.get(e);if(t)return t;if(!Bf(e)){let o=new Map;return or.set(e,o),o}let n=Vf(e),r=Wf(n)??Zf(n)??Yf(n)??new Map;return or.set(e,r),r}var qf="cursorAuth/cachedEmail",Qf="cursorAuth/stripeMembershipAuthId";function $t(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function em(e=Bt(),t=process.platform,n=process.env){let r=$t(n.VSCODE_PORTABLE);if(r)return ie(r,"user-data");let o=$t(n.VSCODE_APPDATA);if(o)return ie(o,"Cursor");switch(t){case"darwin":return ie(e,"Library","Application Support","Cursor");case"win32":return ie($t(n.APPDATA)??ie(e,"AppData","Roaming"),"Cursor");default:return ie($t(n.XDG_CONFIG_HOME)??ie(e,".config"),"Cursor")}}function tm(e=Bt()){return ie(e,".cursor","cli-config.json")}function nm(e=Bt(),t=process.platform,n=process.env){return ie(em(e,t,n),"User","globalStorage","state.vscdb")}function nt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function rm(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):nt(e.userId)}function om(e){return nt(e.email)??nt(e.authId)??rm(e)}function sr(e){let t=nt(e.email),n=nt(e.displayName),r=om(e);return!r||B(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function sm(e){let n=U(tm(e),{}).authInfo;return!n||typeof n!="object"?null:sr(n)}function im(e,t,n){let r=nm(e,process.platform,t),o=Bi(e),s=Gi(o);if(zi(s,r,n))return sr({email:s?.email,authId:s?.auth_id});let i=Zi(r),a=i.get(qf)??null,c=i.get(Qf)??null;return Vi(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),sr({email:a,authId:c})}function qi(e=Bt(),t=process.env,n=Date.now()){return sm(e)??im(e,t,n)}import{createHash as am}from"node:crypto";import{resolve as cm}from"node:path";function M(e){return am("sha256").update(e).digest("hex").slice(0,16)}function ir(e){return M(cm(e))}function V(e,t){return`${e}\0${t}`}function Qi(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function rt(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(`
31
31
  `);return M(n)}function lm(e,t,n="git_config",r=null){return M(`${e??""}|${t??""}|${r??""}|${n}`)}function dm(e){let t=null,n=null;for(let r of e.split(`
32
- `)){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 pm(e,t=w){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return dm(n)}function fm(e=process.env){let t=O(e.GIT_AUTHOR_NAME),n=O(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=O(e.GIT_COMMITTER_NAME),o=O(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=O(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function ae(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 mm(e=process.env){let t=O(e.EV_AI_HOOK_OPERATOR_EMAIL),n=O(e.EV_AI_HOOK_OPERATOR_LOGIN),r=ae(O(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=O(e.GITHUB_ACTOR)??O(e.GITHUB_TRIGGERING_ACTOR)??O(e.GITHUB_USER),s=ae(o,null,"github",o);if(s)return s;let i=O(e.GITLAB_USER_LOGIN),a=O(e.GITLAB_USER_EMAIL),c=ae(O(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let u=O(e.BUILD_REQUESTEDFOREMAIL),l=ae(O(e.BUILD_REQUESTEDFOR),u,"azure_devops",u??O(e.BUILD_REQUESTEDFORID));if(l)return l;let p=O(e.BUILDKITE_BUILD_CREATOR_EMAIL),f=ae(O(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(f)return f;let d=O(e.BUILD_USER_EMAIL)??O(e.CHANGE_AUTHOR_EMAIL),g=ae(O(e.BUILD_USER)??O(e.CHANGE_AUTHOR),d,"jenkins",d??O(e.BUILD_USER_ID));if(g)return g;let _=O(e.CIRCLE_USERNAME),S=ae(_,null,"circleci",_);if(S)return S;let E=O(e.CODEBUILD_INITIATOR),y=ae(E,null,"codebuild",E);if(y)return y;let F=O(e.DRONE_COMMIT_AUTHOR_EMAIL),k=O(e.DRONE_COMMIT_AUTHOR),b=ae(k??O(e.DRONE_COMMIT_AUTHOR_NAME),F,"drone",F??k);if(b)return b;if(ea(e.CLAUDE_CODE_REMOTE)||ea(e.CURSOR_AGENT)){let D=O(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:D&&!B(null,D)?D:null,identity_source:"cloud"}}return null}function ar(e){return!!((e.git_user_name??e.git_user_email)&&!B(e.git_user_name,e.git_user_email))}function O(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ea(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function gm(e,t,n){return e==="claude"?Ui(t):e==="cursor"?qi(t,n):e==="codex"?Ki(n,t):null}async function cr(e,t=w,n=process.env,r={}){let o=await pm(e,t),s=fm(n),i=ar(o)?o:s&&ar(s)?s:null,a=gm(r.runnerPlatform,r.home??um(),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=mm(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:ar(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 ur(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??w,s=e.env??process.env,i=await cr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=lm(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),u=(n?Ln(n):void 0)?.operator_identity_hash;if(!(r||u!==void 0&&u!==a||!u))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&ss(d,a,_t())}}}function lr(e){return e?!Ln(e)?.operator_identity_hash:!0}function ta(e){return!0}import{existsSync as i_,readFileSync as a_}from"node:fs";import{homedir as cc}from"node:os";import{join as He,resolve as c_}from"node:path";import{basename as qg,join as Fe}from"node:path";import{dirname as pa,resolve as Vt}from"node:path";import{existsSync as _m}from"node:fs";import{homedir as oa}from"node:os";import{relative as sa,resolve as ee,sep as me}from"node:path";var hm=["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"],Sm=["prompt","tool_input","tool_response","last_assistant_message","command"],Em=new Set;function ym(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return Em}}function ia(e){return aa(e)==="allowlist"}function aa(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 Rm(e){let t={};for(let n of hm){let r=ne(e,n);r!==void 0&&(t[n]=r)}return t}function Gt(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=ee(e),r=ee(t),o=sa(r,n);return!o||o==="."?".":o.startsWith(`..${me}`)||o===".."||ee(r,o)!==n?null:o.split(me).join("/")}function ca(e,t){let n=sa(ee(t),ee(e)).split(me).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function ua(e){return typeof e!="string"||e.length===0?null:ee(e).split(me).join("/")}function Cm(){let e=I("CURSOR_PROJECT_DIR");if(!e)return null;let t=ee(e);return _m(t)?t.split(me).join("/"):null}function pr(e,t){return Gt(e,t)!==null}function Im(e,t){let n=ee(t??oa(),".cursor").split(me).join("/");return pr(e,n)}function Am(e,t,n){return t!==null&&pr(e,t)?!0:t!==null&&Im(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&pr(e,n.gitRoot)?!0:t===null}function la(e,t){let n=ua(e.cwd);if(n!==null)return n;let r=ee(process.cwd()).split(me).join("/"),o=Cm();return Am(r,o,t)?r:o??r}function gr(e,t={}){return la(e,t)}function _r(e,t=oa()){let n=ee(t).split(me).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function na(e,t,n){let r=ua(n.launchCwd)??la(t,n);e.cwd=_r(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?Gt(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var da="\u2026[truncated]\u2026",fr=Buffer.byteLength(da,"utf8"),Om=8;function ot(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function ra(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function Tm(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 Pm(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=fr)return ra(e,t);let r=t-fr,o=Math.ceil(r/2),s=Math.floor(r/2);return`${ra(e,o)}${da}${Tm(e,s)}`}function mr(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)=>{mr(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||mr(o,[...t,r],n)}function km(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 bm=256;function xm(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 Nm(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=ot(e);if(s<=t)return;let i=[];mr(e,[],i),i.sort((l,p)=>p.bytes-l.bytes);let a=i.filter(l=>l.bytes>n);if(a.length===0)return;let c=xm(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&&km(e,l.path,Pm(l.value,r))}}function Mm(e,t){let n=Math.max(0,t-bm),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:ot(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(ot(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function dr(e,t){let n=ot(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,Nm(r,t,fr+Om),ot(r)>t&&Mm(r,t),r}function wm(e,t,n){let r=ym(n.runnerEvent);for(let o of Sm){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function zt(e,t,n={}){let r=aa(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,na(s,e,n),dr(s,bn)}let o=Rm(e);return na(o,e,n),r==="content"?(wm(o,e,n),dr(o,bn)):dr(o,Bo)}function Lm(e){return typeof e=="string"&&e.length>0}function hr(e){let t=Vt(e.home),n=Vt(e.launchCwd),r=e.gitRoot?Vt(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Lm(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&&Gt(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let u=pa(r);for(;;){let l=Vt(u);if(l===t)break;let p=pa(l);if(p===l)break;if(e.hasProjectSpec(l)){s.push({scope:"parent",dir:l}),a=ca(l,n);break}u=p}}return{anchors:s,parentRel:a}}import{existsSync as fa,readdirSync as vm,realpathSync as Um}from"node:fs";import{basename as Dm,dirname as Fm,relative as Hm,resolve as jm,sep as Km}from"node:path";var Sr=400,Wt=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??ce}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=jm(t).split(Km).join("/");return _r(r,this.home)}let n=Hm(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${M(Fm(t))}/${Dm(t)}`:n}claimFile(t){try{let n=Um(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(!fa(t))return[];try{return vm(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(fa(t))return U(t,n)}push(t){return this.components.length>=this.maxEntries?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Er,readFileSync as $m,statSync as Bm}from"node:fs";import{basename as ga,join as st,relative as _a}from"node:path";var yr=100*1024,Gm=4;function zm(e){return e.length<=yr?e:`${e.slice(0,yr-1)}\u2026`}function Vm(e){try{let t=$m(e),n=t.toString("utf8");return{hash:M(t),length:t.length,text:zm(n)}}catch{return null}}var ma={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Wm(e){return e in ma?ma[e]:"UNSPECIFIED"}function Jt(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Vm(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=Wm(t.kind);return s&&(o.trigger=s),e.push(o)}function Jm(e,t,n){let r=_a(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?ga(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Ae(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Rr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Rr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:u}=t;if(!(o>Gm))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=st(r,l.name,c);if(Er(d)){let g=_a(n,st(r,l.name)).replace(/\\/g,"/");Jt(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:g||l.name});continue}Rr(e,{walkRoot:n,currentDir:st(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(l.isDirectory()){Rr(e,{walkRoot:n,currentDir:st(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(!l.isFile()||!u)continue;let p=l.name.toLowerCase();if(!u.some(d=>p.endsWith(d)))continue;let f=st(r,l.name);Jt(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:Jm(n,f,!0)})}}function ha(e){for(let t of e)if(Er(t))try{if(Bm(t).size>0)return t}catch{continue}return e.find(t=>Er(t))}import{existsSync as Ig,readFileSync as Ag}from"node:fs";var Yt=Be(ve(),1);var Ym="<omitted>",Xm=["package_name","package_spec","package_version","package_version_source"],Sa=100,Ea=120,Xt=[{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(Xt.map(e=>e.attr)),Zm=["enabled","disabled"],qm=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Qm=new Set(["type","command","url","args","env","envVars","headers",...Zm,...qm,...Xt.map(e=>e.raw)]),eg=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",...Xm,...ya,...[...ya].map(e=>`${e}_truncated`)]);function Ra(e,t){for(let n of t)Qm.has(n)||eg.has(n)||(e[n]=Ym)}var tg=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,ng=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,rg=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,og=/^bearer(?:\s+|$)/i;function Zt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ca(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Cr(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=Zt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Oe(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function sg(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,Yt.launchContainsCredentials)({kind:"url",url:e})||(0,Yt.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=at([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,Yt.launchContainsCredentials)({kind:"url",url:r}):!0)}function Ia(e,t,n){sg(t,n)&&(e.launch_had_credentials=!0)}function ig(e){return rg.test(e)||og.test(e)?"<redacted>":e.includes("://")?Oe(e):e}function Aa(e){if(/^https?:\/\//i.test(e))return Oe(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Aa(e.slice(t+1))}`:ig(e)}function ag(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return tg.test(t)||ng.test(t)}function at(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(ag(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Aa(r))}return t}function cg(e){let t=Ca(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ea?r.slice(0,Ea):r))].sort();if(n.length!==0)return n.length>Sa?{names:n.slice(0,Sa),truncated:!0}:{names:n,truncated:!1}}function ug(e){let t=Zt(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function Oa(e,t){let n=new Set;for(let{raw:r,attr:o}of Xt){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=cg(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function Ta(e,t){let n=Zt(e),r={transport:t};if(!n)return r;Ra(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=Ca(n.args);a&&(r.command_or_url=Oe(a));let u=at(c);u.length>0&&(r.args=u),Ia(r,a,c);let l=ug(n.env_http_headers),p=[...new Set([...Cr(n.env),...Cr(n.envVars),...Cr(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();p.length>0&&(r.env_var_names=p),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let _ of["headers","http_headers","env_http_headers"])if(n[_]!==void 0&&n[_]!==null){r.headers_present=!0;break}let f=typeof n.auth=="string"?n.auth:void 0;f&&(r.auth=f);let d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let g=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return g&&(r.default_tools_approval_mode=g),Oa(r,n),r}function Pa(e){let t=Zt(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function Or(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 De(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function it(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 Ar(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Ir(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=De(n[1]);return r.length>0?r:void 0}function lg(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],De(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
32
+ `)){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 pm(e,t=w){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return dm(n)}function fm(e=process.env){let t=O(e.GIT_AUTHOR_NAME),n=O(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=O(e.GIT_COMMITTER_NAME),o=O(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=O(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function ae(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 mm(e=process.env){let t=O(e.EV_AI_HOOK_OPERATOR_EMAIL),n=O(e.EV_AI_HOOK_OPERATOR_LOGIN),r=ae(O(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=O(e.GITHUB_ACTOR)??O(e.GITHUB_TRIGGERING_ACTOR)??O(e.GITHUB_USER),s=ae(o,null,"github",o);if(s)return s;let i=O(e.GITLAB_USER_LOGIN),a=O(e.GITLAB_USER_EMAIL),c=ae(O(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let l=O(e.BUILD_REQUESTEDFOREMAIL),u=ae(O(e.BUILD_REQUESTEDFOR),l,"azure_devops",l??O(e.BUILD_REQUESTEDFORID));if(u)return u;let p=O(e.BUILDKITE_BUILD_CREATOR_EMAIL),f=ae(O(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(f)return f;let d=O(e.BUILD_USER_EMAIL)??O(e.CHANGE_AUTHOR_EMAIL),g=ae(O(e.BUILD_USER)??O(e.CHANGE_AUTHOR),d,"jenkins",d??O(e.BUILD_USER_ID));if(g)return g;let _=O(e.CIRCLE_USERNAME),S=ae(_,null,"circleci",_);if(S)return S;let E=O(e.CODEBUILD_INITIATOR),y=ae(E,null,"codebuild",E);if(y)return y;let F=O(e.DRONE_COMMIT_AUTHOR_EMAIL),k=O(e.DRONE_COMMIT_AUTHOR),b=ae(k??O(e.DRONE_COMMIT_AUTHOR_NAME),F,"drone",F??k);if(b)return b;if(ea(e.CLAUDE_CODE_REMOTE)||ea(e.CURSOR_AGENT)){let D=O(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:D&&!B(null,D)?D:null,identity_source:"cloud"}}return null}function ar(e){return!!((e.git_user_name??e.git_user_email)&&!B(e.git_user_name,e.git_user_email))}function O(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ea(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function gm(e,t,n){return e==="claude"?Ui(t):e==="cursor"?qi(t,n):e==="codex"?Ki(n,t):null}async function cr(e,t=w,n=process.env,r={}){let o=await pm(e,t),s=fm(n),i=ar(o)?o:s&&ar(s)?s:null,a=gm(r.runnerPlatform,r.home??um(),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=mm(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:ar(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 ur(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??w,s=e.env??process.env,i=await cr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=lm(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?Ln(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&ss(d,a,_t())}}}function lr(e){return e?!Ln(e)?.operator_identity_hash:!0}function ta(e){return!0}import{existsSync as i_,readFileSync as a_}from"node:fs";import{homedir as cc}from"node:os";import{join as He,resolve as c_}from"node:path";import{basename as qg,join as Fe}from"node:path";import{dirname as pa,resolve as Vt}from"node:path";import{existsSync as _m}from"node:fs";import{homedir as oa}from"node:os";import{relative as sa,resolve as ee,sep as me}from"node:path";var hm=["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"],Sm=["prompt","tool_input","tool_response","last_assistant_message","command"],Em=new Set;function ym(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return Em}}function ia(e){return aa(e)==="allowlist"}function aa(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 Rm(e){let t={};for(let n of hm){let r=ne(e,n);r!==void 0&&(t[n]=r)}return t}function Gt(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=ee(e),r=ee(t),o=sa(r,n);return!o||o==="."?".":o.startsWith(`..${me}`)||o===".."||ee(r,o)!==n?null:o.split(me).join("/")}function ca(e,t){let n=sa(ee(t),ee(e)).split(me).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function ua(e){return typeof e!="string"||e.length===0?null:ee(e).split(me).join("/")}function Cm(){let e=I("CURSOR_PROJECT_DIR");if(!e)return null;let t=ee(e);return _m(t)?t.split(me).join("/"):null}function pr(e,t){return Gt(e,t)!==null}function Im(e,t){let n=ee(t??oa(),".cursor").split(me).join("/");return pr(e,n)}function Am(e,t,n){return t!==null&&pr(e,t)?!0:t!==null&&Im(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&pr(e,n.gitRoot)?!0:t===null}function la(e,t){let n=ua(e.cwd);if(n!==null)return n;let r=ee(process.cwd()).split(me).join("/"),o=Cm();return Am(r,o,t)?r:o??r}function gr(e,t={}){return la(e,t)}function _r(e,t=oa()){let n=ee(t).split(me).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function na(e,t,n){let r=ua(n.launchCwd)??la(t,n);e.cwd=_r(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?Gt(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var da="\u2026[truncated]\u2026",fr=Buffer.byteLength(da,"utf8"),Om=8;function ot(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function ra(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function Tm(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 Pm(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=fr)return ra(e,t);let r=t-fr,o=Math.ceil(r/2),s=Math.floor(r/2);return`${ra(e,o)}${da}${Tm(e,s)}`}function mr(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)=>{mr(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||mr(o,[...t,r],n)}function km(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 bm=256;function xm(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 Nm(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=ot(e);if(s<=t)return;let i=[];mr(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=xm(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&&km(e,u.path,Pm(u.value,r))}}function Mm(e,t){let n=Math.max(0,t-bm),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:ot(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(ot(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function dr(e,t){let n=ot(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,Nm(r,t,fr+Om),ot(r)>t&&Mm(r,t),r}function wm(e,t,n){let r=ym(n.runnerEvent);for(let o of Sm){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function zt(e,t,n={}){let r=aa(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,na(s,e,n),dr(s,bn)}let o=Rm(e);return na(o,e,n),r==="content"?(wm(o,e,n),dr(o,bn)):dr(o,Bo)}function Lm(e){return typeof e=="string"&&e.length>0}function hr(e){let t=Vt(e.home),n=Vt(e.launchCwd),r=e.gitRoot?Vt(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Lm(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&&Gt(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=pa(r);for(;;){let u=Vt(l);if(u===t)break;let p=pa(u);if(p===u)break;if(e.hasProjectSpec(u)){s.push({scope:"parent",dir:u}),a=ca(u,n);break}l=p}}return{anchors:s,parentRel:a}}import{existsSync as fa,readdirSync as vm,realpathSync as Um}from"node:fs";import{basename as Dm,dirname as Fm,relative as Hm,resolve as jm,sep as Km}from"node:path";var Sr=400,Wt=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??ce}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=jm(t).split(Km).join("/");return _r(r,this.home)}let n=Hm(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${M(Fm(t))}/${Dm(t)}`:n}claimFile(t){try{let n=Um(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(!fa(t))return[];try{return vm(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(fa(t))return U(t,n)}push(t){return this.components.length>=this.maxEntries?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Er,readFileSync as $m,statSync as Bm}from"node:fs";import{basename as ga,join as st,relative as _a}from"node:path";var yr=100*1024,Gm=4;function zm(e){return e.length<=yr?e:`${e.slice(0,yr-1)}\u2026`}function Vm(e){try{let t=$m(e),n=t.toString("utf8");return{hash:M(t),length:t.length,text:zm(n)}}catch{return null}}var ma={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Wm(e){return e in ma?ma[e]:"UNSPECIFIED"}function Jt(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Vm(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=Wm(t.kind);return s&&(o.trigger=s),e.push(o)}function Jm(e,t,n){let r=_a(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?ga(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Ae(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Rr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Rr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Gm))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=st(r,u.name,c);if(Er(d)){let g=_a(n,st(r,u.name)).replace(/\\/g,"/");Jt(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:g||u.name});continue}Rr(e,{walkRoot:n,currentDir:st(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){Rr(e,{walkRoot:n,currentDir:st(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 f=st(r,u.name);Jt(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:Jm(n,f,!0)})}}function ha(e){for(let t of e)if(Er(t))try{if(Bm(t).size>0)return t}catch{continue}return e.find(t=>Er(t))}import{existsSync as Ig,readFileSync as Ag}from"node:fs";var Yt=Be(ve(),1);var Ym="<omitted>",Xm=["package_name","package_spec","package_version","package_version_source"],Sa=100,Ea=120,Xt=[{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(Xt.map(e=>e.attr)),Zm=["enabled","disabled"],qm=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Qm=new Set(["type","command","url","args","env","envVars","headers",...Zm,...qm,...Xt.map(e=>e.raw)]),eg=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",...Xm,...ya,...[...ya].map(e=>`${e}_truncated`)]);function Ra(e,t){for(let n of t)Qm.has(n)||eg.has(n)||(e[n]=Ym)}var tg=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,ng=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,rg=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,og=/^bearer(?:\s+|$)/i;function Zt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ca(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Cr(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=Zt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Oe(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function sg(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,Yt.launchContainsCredentials)({kind:"url",url:e})||(0,Yt.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=at([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,Yt.launchContainsCredentials)({kind:"url",url:r}):!0)}function Ia(e,t,n){sg(t,n)&&(e.launch_had_credentials=!0)}function ig(e){return rg.test(e)||og.test(e)?"<redacted>":e.includes("://")?Oe(e):e}function Aa(e){if(/^https?:\/\//i.test(e))return Oe(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Aa(e.slice(t+1))}`:ig(e)}function ag(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return tg.test(t)||ng.test(t)}function at(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(ag(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Aa(r))}return t}function cg(e){let t=Ca(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ea?r.slice(0,Ea):r))].sort();if(n.length!==0)return n.length>Sa?{names:n.slice(0,Sa),truncated:!0}:{names:n,truncated:!1}}function ug(e){let t=Zt(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function Oa(e,t){let n=new Set;for(let{raw:r,attr:o}of Xt){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=cg(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function Ta(e,t){let n=Zt(e),r={transport:t};if(!n)return r;Ra(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=Ca(n.args);a&&(r.command_or_url=Oe(a));let l=at(c);l.length>0&&(r.args=l),Ia(r,a,c);let u=ug(n.env_http_headers),p=[...new Set([...Cr(n.env),...Cr(n.envVars),...Cr(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 _ of["headers","http_headers","env_http_headers"])if(n[_]!==void 0&&n[_]!==null){r.headers_present=!0;break}let f=typeof n.auth=="string"?n.auth:void 0;f&&(r.auth=f);let d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let g=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return g&&(r.default_tools_approval_mode=g),Oa(r,n),r}function Pa(e){let t=Zt(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function Or(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 De(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function it(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 Ar(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Ir(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=De(n[1]);return r.length>0?r:void 0}function lg(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],De(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
33
33
  ${e}`);return s?.[1]&&r(s[1]),n}function ka(e){return Ar(e,"enabled")===!1?!1:Ar(e,"disabled")!==!0}function dg(e,t){let n={};for(let{raw:r,attr:o}of Xt){if(o==="auto_approve"){let i=Ar(t,r);if(i!==void 0){n[r]=i;continue}}let s=it(t,r);s.length>0&&(n[r]=s)}Oa(e,n)}var pg=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,fg=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function mg(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
34
- `)){let s=pg.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(fg))o[1]&&t.add(o[1]);return[...t]}function ba(e,t){let n={transport:t};Ra(n,mg(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?De(r[1]??""):void 0,i=o?De(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=it(e,"args");a&&(n.command_or_url=Oe(a));let u=at(c);u.length>0&&(n.args=u),Ia(n,a,c);let l=new Set;for(let E of e.split(`
35
- `)){let y=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&l.add(y[1])}let p=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(p?.[1])for(let E of p[1].split(",")){let y=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&l.add(y[1])}let f=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
34
+ `)){let s=pg.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(fg))o[1]&&t.add(o[1]);return[...t]}function ba(e,t){let n={transport:t};Ra(n,mg(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?De(r[1]??""):void 0,i=o?De(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=it(e,"args");a&&(n.command_or_url=Oe(a));let l=at(c);l.length>0&&(n.args=l),Ia(n,a,c);let u=new Set;for(let E of e.split(`
35
+ `)){let y=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&u.add(y[1])}let p=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(p?.[1])for(let E of p[1].split(",")){let y=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&u.add(y[1])}let f=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
36
36
  ${e}`);if(f?.[1])for(let E of f[1].split(`
37
- `)){let y=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&l.add(y[1])}for(let E of it(e,"env_vars"))l.add(E);let d=lg(e,"env_http_headers");for(let[,E]of d)E.length>0&&l.add(E);let g=Ir(e,"bearer_token_env_var");g&&(l.add(g),n.bearer_token_env_var=g),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 _=Ir(e,"auth");_&&(n.auth=_);let S=Ir(e,"default_tools_approval_mode");return S&&(n.default_tools_approval_mode=S),dg(n,e),n}var ge=Be(ve(),1);import{createHash as Sg}from"node:crypto";import{join as ct}from"node:path";var gg=300,_g=256;function xa(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function qt(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 Na(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function hg(e){return Na(e,gg)}function Ma(e,t){let n=xa(e.trim(),t),r=qt(n);if(r.length===0)return"";let[o,...s]=r,i=Oe(o),a=at(s);return hg([i,...a].join(" "))}function wa(e,t){if(typeof e!="string")return null;let n=xa(e.trim(),t),r=qt(n)[0];if(!r)return null;let o=Oe(r);return o.length===0?null:Na(o,_g)}function Eg(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
38
- `);return Sg("sha512").update(t).digest("hex").slice(0,16)}function yg(e){let t=process.platform==="win32"?ct(I("LOCALAPPDATA")??e,"npm-cache"):ct(e,".npm"),n=I("npm_config_cache")??I("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function La(e){return typeof e=="string"&&e.length>0&&e.length<=ge.PACKAGE_FIELD_MAX?e:null}function Rg(e,t,n){let r=Eg(e);for(let o of yg(n)){let s=ct(o,"_npx",r),i=U(ct(s,"node_modules",...t.split("/"),"package.json"),{}),a=La(i.version);if(a!==null)return a;let c=U(ct(s,"package-lock.json"),{}),u=La(c.packages?.[`node_modules/${t}`]?.version);if(u!==null)return u}return null}function Cg(e){return e.length<=ge.PACKAGE_FIELD_MAX?e:`${e.slice(0,ge.PACKAGE_FIELD_MAX-1)}\u2026`}function Tr(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,ge.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,ge.packageNameFromSpec)(o);if(s===null)return null;let i=Rg(r,s,n);return{package_name:s,package_spec:Cg(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function va(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=qt(e.trim());return n===void 0?null:Tr(n,r,t)}function Qt(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 Tr(typeof n.command=="string"?n.command:null,r,t)}function Ua(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:Tr(De(n[1]??""),it(e,"args"),t)}function Og(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 Da(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=Og(a),u=Ta(a,c);Object.assign(u,Qt(a,e.home)??{});let l=Pa(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:Or(i,u,l),origin:n,enabled:l,attributes:u})}}function Fa(e,t,n){if(!Ig(t)||!e.claimFile(t))return;let r;try{r=Ag(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),p="unknown";/^\s*url\s*=/m.test(l)?p="http":/^\s*command\s*=/m.test(l)&&(p="stdio");let f=ba(l,p);Object.assign(f,Ua(l,e.home)??{});let d=ka(l);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:Or(a,f,d),origin:n,enabled:d,attributes:f})}}import{existsSync as kg,readdirSync as bg}from"node:fs";import{join as $}from"node:path";function Tg(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 Pg(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 Pr(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 Pg(c)){if(e.truncated)return;let l=u.command??u.bash??u.prompt??u.powershell??c.powershell??"",p=Tg({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}),f=typeof c.matcher=="string"?c.matcher:"",d=M(l),g=f?`${s}:${f}:${p}:${d}`:`${s}:${p}:${d}`,_=`${s}|${f}|${p}|${l}|attrs2`;e.push({kind:"HOOK",name:g,path:o,content_hash:M(_),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...f?{matcher:f}:{},action_kind:p,action_hash:d,...p!=="prompt"&&l.trim()?{command:Ma(l,e.home)}:{}}})}}}function kr(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||Pr(e,t,r.hooks,n)}var Ha=50;function br(e,t,n,r){if(!kg(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(Ha,()=>{Ae(e,{dir:$(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Ae(e,{dir:$(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Ae(e,{dir:$(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});kr(e,$(t,"hooks","hooks.json"),n),kr(e,$(t,"hooks.json"),n);let i=e.components.length-o,a=s>=Ha;return{componentCount:i,expandTruncated:a}}function xr(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 ja(e){let t=$(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson($(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let u=Array.isArray(c)?c:[c],l=u[0]??{},p=s[a]===!0,f=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof l.version=="string"?l.version:"",g=typeof l.scope=="string"?l.scope:"user",_=`plugin:${a}`,S=0,E=!1;for(let y of u)if(typeof y.installPath=="string"&&y.installPath.length>0){let F=br(e,y.installPath,_,p);S+=F.componentCount,E=E||F.expandTruncated}xr(e,{pluginKey:a,rowPath:i,enabled:p,scope:g,version:d||void 0,marketplace:f||void 0,componentCount:S,expandTruncated:E,contentHash:M(`${a}|${d}|${g}|${p}|${S}`)})}}function xg(e){let t=e,n="";try{let r=bg(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=$(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=$(e,s),n=s)}}catch{}return{installPath:t,version:n}}var Ng=/^\d+$/;function Mg(e){let t=e.filter(n=>!Ng.test(n.pluginId));return t.length>0?t:e}function Ka(e){let t=[{base:$(e.home,".cursor/plugins/local"),scope:"local"},{base:$(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=$(n,o.name),u=`plugin:${a}`,{componentCount:l,expandTruncated:p}=br(e,c,u,!0);xr(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:l,expandTruncated:p,contentHash:M(`${a}|local|${l}`)});continue}let s=o.name,i=[];for(let a of e.readEntries($(n,s))){if(!a.isDirectory())continue;let c=$(n,s,a.name),{installPath:u,version:l}=xg(c);i.push({pluginId:a.name,installPath:u,version:l})}for(let a of Mg(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,u=`plugin:${c}`,{componentCount:l,expandTruncated:p}=br(e,a.installPath,u,!0);xr(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:l,expandTruncated:p,contentHash:M(`${c}|${a.version}|${l}`)})}}}import{existsSync as vg}from"node:fs";var wg=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Nr="<path>",Lg=new RegExp(`${Nr}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function en(e){let t=e.replace(wg,Nr).replace(Lg,Nr);return t.length>200?`${t.slice(0,200)}...`:t}var $a=200,Ba=200,Mr=16*1024,Ga=6,Ug=new Set(["permissions","sandbox","enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers","disableAllHooks","disableAutoMode","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","strictPluginOnlyCustomization","disableSideloadFlags","forceLoginMethod","forceLoginOrgUUID"]),Dg=new Set(["type","additionalReadwritePaths","additionalReadonlyPaths","disableTmpWrite","enableSharedBuildCache","networkPolicy"]),Fg=new Set(["terminalAllowlist","mcpAllowlist","autoRun"]),Hg=new Set(["permissions"]),jg={claude:Ug,cursor_sandbox:Dg,cursor_permissions:Fg,cursor_cli:Hg},Kg=new Set(["allow","deny","ask"]);function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tn(e){return e.replace(/\\/g,"/")}function wr(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>wr(r)).join(",")}]`;let t=e;return`{${Object.keys(t).filter(r=>t[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${wr(t[r])}`).join(",")}}`}function $g(e){return M(`${wr(e)}|settings1`)}function Ya(e){let t=tn(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 Xa(e,t){if(e!=="claude")return{};let n=tn(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 Za(e){let t=tn(e).replace(/\/+$/,"");return t.length<=1?"":t}function qa(e){return/^[A-Za-z]:/.test(e)||e.includes("\\")}function Bg(e,t){let n=tn(e);if(n==="~"||n.startsWith("~/"))return n;let r=Za(t);if(!r)return n;let o=n.slice(0,r.length);if(!(qa(t)?o.toLowerCase()===r.toLowerCase():o===r))return n;let i=n.slice(r.length);return i===""?"~":i.startsWith("/")?`~${i}`:n}var za=new Map;function Gg(e){let t=za.get(e);if(t!==void 0)return t;let n=Za(e),r=null;if(n){let o=n.split("/").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");r=new RegExp(`(?<![\\w.-])${o}(?![\\w.-])`,qa(e)?"gi":"g")}return za.set(e,r),r}function zg(e,t){let n=Gg(t);return n?e.replace(n,"~"):e}function Va(e,t){return e.length<=Ba?e:(t.truncated=!0,e.slice(0,Ba))}function Qa(e,t){return e.length<=$a?e:(t.truncated=!0,e.slice(0,$a))}function L(e,t,n,r){if(typeof e=="string"){if(t==="path")return Va(Bg(e,n),r);let o=t==="rule"?en(e):e;return Va(zg(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=Qa(e,r),s=[];for(let i of o){let a=L(i,t,n,r);a!==void 0&&s.push(a)}return s}if(_e(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 Wa(e,t,n){if(!_e(e))return L(e,"plain",t,n);let r={};for(let[o,s]of Object.entries(e)){let i="plain";Kg.has(o)?i="rule":o==="additionalDirectories"&&(i="path");let a=L(s,i,t,n);a!==void 0&&(r[o]=a)}return r}function Vg(e,t,n){if(!_e(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=Qa(s,n);r[o]=a.map(c=>{if(!_e(c))return L(c,"plain",t,n);let u={};for(let[l,p]of Object.entries(c)){let d=L(p,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 Wg(e,t,n){if(!_e(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 Jg(e,t,n){if(!_e(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=Wg(s,t,n):o==="credentials"?i=Vg(s,t,n):i=L(s,"plain",t,n),i!==void 0&&(r[o]=i)}return r}function Yg(e,t,n,r,o){return n==="claude"?e==="permissions"?Wa(t,r,o):e==="sandbox"?Jg(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"?Wa(t,r,o):L(t,"plain",r,o)}function ut(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Lr(e,t){return e?`${e}.${t}`:t}function vr(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>=Ga?(e.splice(o,1),r.add(n)):vr(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>=Ga?(delete e[o],r.add(Lr(n,o))):vr(s,t+1,Lr(n,o),r))}function ec(e,t,n){if(Array.isArray(e)){e.length>0&&n.push({path:t,items:e,bytes:ut(e)});return}if(!(e===null||typeof e!="object"))for(let[r,o]of Object.entries(e))ec(o,Lr(t,r),n)}function Xg(e,t,n){let r=ut(e);if(r<=Mr)return;t.truncated=!0;let o=[];for(ec(e,"",o);r>Mr;){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=ut(i)+(s.items.length>0?1:0);s.bytes-=a,r-=a,n.add(s.path)}for(;ut(e)>Mr;){let s,i=-1;for(let[a,c]of Object.entries(e)){let u=ut(c);u>i&&(s=a,i=u)}if(s===void 0)break;delete e[s],n.add(s)}}function Zg(e,t,n){let r=jg[t],o={truncated:!1},s={},i=[];for(let c of Object.keys(e)){if(!r.has(c)){i.push(c);continue}let u=Yg(c,e[c],t,n,o);u!==void 0&&(s[c]=u)}i.sort();let a=new Set;return vr(s,1,"",a),a.size>0&&(o.truncated=!0),Xg(s,o,a),{settings:s,keys_omitted:i,truncated:o.truncated,trimmed_paths:[...a].sort()}}function Ja(e,t){let n={kind:t.kind,name:"settings",path:e.componentPath(t.absPath),origin:t.origin,enabled:!0,content_hash:$g(t.attributes),attributes:t.attributes};e.push(n)}function Ur(e,t,n,r){if(!e.claimFile(t)||!vg(t))return;let o=_o(t);if(!o.ok||!_e(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),Ja(e,{kind:r.kind,absPath:t,origin:n,attributes:l})}return}let s=o.value,i=s.hooks;if(_e(i)&&Pr(e,t,i,n),!r.profile)return;let a=Zg(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),Ja(e,{kind:r.kind,absPath:t,origin:n,attributes:c})}function Qg(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Ae(e,{dir:Fe(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Ae(e,{dir:Fe(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=ha(i.map(c=>Fe(r,c)));a&&Jt(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:qg(a)})}for(let i of Rs(n))Ur(e,Fe(r,i),o,{kind:"SETTINGS",profile:Ya(i)});for(let i of n.mcpJson??[])Da(e,Fe(r,i),o);for(let i of n.mcpToml??[])Fa(e,Fe(r,i),o);if(s){if(n.managed){for(let i of kt(n.managed,process.platform,e.home))if(i.toLowerCase().endsWith(".json")){let a=Xa(n.managed,i);Ur(e,i,o,{kind:"MANAGED_SETTINGS",...a})}}n.plugins==="claude"?ja(e):n.plugins==="cursor"&&Ka(e)}}function tc(e,t){try{let n=new Wt(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)Qg(n,{layout:r,levelDir:t.levelDir,origin:t.origin,includeMachineWide:t.includeMachineWide});return{scopeRef:t.scopeRef,anchor:t.levelDir,components:n.components,truncated:n.truncated}}catch{return}}function Dr(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=tc(t,{layouts:Object.values(Ne),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:ce,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(le),u=hr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:l=>Is(c,l)});i=u.parentRel;for(let l of u.anchors){let p=ir(l.dir);if(o!==void 0&&!o(l.scope,p))continue;let f=tc(t,{layouts:c,levelDir:l.dir,origin:l.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Sr,scopeRef:p});f&&(r[l.scope]=f)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function Fr(e,t,n={}){let r=n.truncated===!0,o=rt(e),s=new Set(e.map(l=>V(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 p=V(l.path,l.name);c[p]!==l.content_hash&&a.push(l)}let u=[];if(!r){for(let l of Object.keys(c))if(!s.has(l)){let p=Qi(l);p&&u.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:u,unchanged:a.length===0&&u.length===0}}var rc=2*1024*1024,e_=new Set(["HOOK","MCP_SERVER","PLUGIN","SETTINGS","MANAGED_SETTINGS"]);function Hr(e,t,n){let r=new Set(t.map(s=>V(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(V(s.path,s.name))||o.push(s));return o}function jr(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 nc(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function oc(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Kr(e,t=rc){let n=[],r=[];for(let l of e)e_.has(l.kind)?n.push(l):r.push(l);r.sort((l,p)=>(l.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,u=[];for(let l of o){let p=s.length>0?1:0,f=nc(l)+p;if(i+f<=t){s.push(l),i+=f,l.text!==void 0&&u.push(l.content_hash);continue}if(l.text!==void 0){let d=oc(l),g=nc(d)+p;if(i+g<=t){s.push(d),i+=g,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:u}}function $r(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:oc(n))}var t_=["user","cwd","repo","parent"];function Br(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let k of t_){let b=t.scopes[k];if(!b)continue;let D=n(k,b.scopeRef),H=D.components,W=Fr(b.components,H,{forceFull:H===void 0,truncated:b.truncated}),he=new Set(D.textHashes),j=Hr(b.components,W.upserts,he),v=$r([...W.upserts,...j],he);s.push({scope:k,walk:b,delta:W,outgoing:v,outgoingKeys:new Set(v.map(C=>V(C.path,C.name))),deliveredTextHashes:he,cachedComponents:H})}let i=s.flatMap(k=>k.outgoing),a=Kr(i,o),c=new Set(a.components.map(k=>V(k.path,k.name))),u=[],l=[],p=[],f=[],d=[],g=[],_=[];for(let k of s){let{scope:b,walk:D,delta:H}=k;g.push(...D.components),u.push(b);let W=a.components.filter(C=>k.outgoingKeys.has(V(C.path,C.name))),he=[...k.outgoingKeys].some(C=>!c.has(C)),j=H.truncated||he;j?p.push(b):H.full&&l.push(b),f.push(...W),!H.full&&!j&&d.push(...H.removed);let v=H.full?{}:{...k.cachedComponents??{}};if(!j)for(let C of H.removed)delete v[V(C.path,C.name)];for(let C of W)v[V(C.path,C.name)]=C.content_hash;_.push({scope:b,scopeRef:D.scopeRef,components:v,textHashes:jr(k.deliveredTextHashes,W.filter(C=>C.text!==void 0).map(C=>C.content_hash),D.components),collectedAtMs:r,included:W.length>0||H.removed.length>0&&!j||H.full})}let S={user_spec_hash:rt(g),user_spec_count:g.length,user_spec_truncated:p.length>0};u.length>0&&(S.user_spec_scopes=u,S.user_spec_full_scopes=l,S.user_spec_truncated_scopes=p,S.user_spec_cwd_in_git_repo=t.cwdInGitRepo),l.length>0&&l.length===u.length&&(S.user_spec_full=!0),f.length>0&&(S.user_spec=f),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:_}}var dt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function nn(e){return e==="cwd"||e==="repo"||e==="parent"}function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gr(e){return!lt(e)||!lt(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 sc(e){return n_(e)}function ic(e){return r_(e)}function ac(e){return o_(e)}function n_(e){if(!lt(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function r_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function zr(e,t){if(!lt(e))return;let n=e[t];return Gr(n)?n:void 0}function o_(e){if(!lt(e))return{};let t={};for(let[n,r]of Object.entries(e))Gr(r)&&(t[n]=r);return t}function Vr(e,t=20){let n=[];for(let[r,o]of Object.entries(e))Gr(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 u_=["allow","deny","ask"];function on(e){let t=U(e,{}),n=[];for(let r of u_)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:en(o),mode:r});return{model:t.model??"",permissionKeys:n}}function l_(e){let{serverManaged:t,fileBased:n}=Un(process.platform,e),r=on(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=on(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function d_(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 p_=10,f_="self-config-cache.json",uc=4;function je(){return I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function m_(){return I("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function g_(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=We}var __={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function h_(e,t=w){let n=__[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
37
+ `)){let y=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);y?.[1]&&u.add(y[1])}for(let E of it(e,"env_vars"))u.add(E);let d=lg(e,"env_http_headers");for(let[,E]of d)E.length>0&&u.add(E);let g=Ir(e,"bearer_token_env_var");g&&(u.add(g),n.bearer_token_env_var=g),u.size>0&&(n.env_var_names=[...u].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 _=Ir(e,"auth");_&&(n.auth=_);let S=Ir(e,"default_tools_approval_mode");return S&&(n.default_tools_approval_mode=S),dg(n,e),n}var ge=Be(ve(),1);import{createHash as Sg}from"node:crypto";import{join as ct}from"node:path";var gg=300,_g=256;function xa(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function qt(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 Na(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function hg(e){return Na(e,gg)}function Ma(e,t){let n=xa(e.trim(),t),r=qt(n);if(r.length===0)return"";let[o,...s]=r,i=Oe(o),a=at(s);return hg([i,...a].join(" "))}function wa(e,t){if(typeof e!="string")return null;let n=xa(e.trim(),t),r=qt(n)[0];if(!r)return null;let o=Oe(r);return o.length===0?null:Na(o,_g)}function Eg(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
38
+ `);return Sg("sha512").update(t).digest("hex").slice(0,16)}function yg(e){let t=process.platform==="win32"?ct(I("LOCALAPPDATA")??e,"npm-cache"):ct(e,".npm"),n=I("npm_config_cache")??I("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function La(e){return typeof e=="string"&&e.length>0&&e.length<=ge.PACKAGE_FIELD_MAX?e:null}function Rg(e,t,n){let r=Eg(e);for(let o of yg(n)){let s=ct(o,"_npx",r),i=U(ct(s,"node_modules",...t.split("/"),"package.json"),{}),a=La(i.version);if(a!==null)return a;let c=U(ct(s,"package-lock.json"),{}),l=La(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function Cg(e){return e.length<=ge.PACKAGE_FIELD_MAX?e:`${e.slice(0,ge.PACKAGE_FIELD_MAX-1)}\u2026`}function Tr(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,ge.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,ge.packageNameFromSpec)(o);if(s===null)return null;let i=Rg(r,s,n);return{package_name:s,package_spec:Cg(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function va(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=qt(e.trim());return n===void 0?null:Tr(n,r,t)}function Qt(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 Tr(typeof n.command=="string"?n.command:null,r,t)}function Ua(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:Tr(De(n[1]??""),it(e,"args"),t)}function Og(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 Da(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=Og(a),l=Ta(a,c);Object.assign(l,Qt(a,e.home)??{});let u=Pa(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:Or(i,l,u),origin:n,enabled:u,attributes:l})}}function Fa(e,t,n){if(!Ig(t)||!e.claimFile(t))return;let r;try{r=Ag(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 f=ba(u,p);Object.assign(f,Ua(u,e.home)??{});let d=ka(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:Or(a,f,d),origin:n,enabled:d,attributes:f})}}import{existsSync as kg,readdirSync as bg}from"node:fs";import{join as $}from"node:path";function Tg(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 Pg(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 Pr(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 Pg(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",p=Tg({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}),f=typeof c.matcher=="string"?c.matcher:"",d=M(u),g=f?`${s}:${f}:${p}:${d}`:`${s}:${p}:${d}`,_=`${s}|${f}|${p}|${u}|attrs2`;e.push({kind:"HOOK",name:g,path:o,content_hash:M(_),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...f?{matcher:f}:{},action_kind:p,action_hash:d,...p!=="prompt"&&u.trim()?{command:Ma(u,e.home)}:{}}})}}}function kr(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||Pr(e,t,r.hooks,n)}var Ha=50;function br(e,t,n,r){if(!kg(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(Ha,()=>{Ae(e,{dir:$(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Ae(e,{dir:$(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Ae(e,{dir:$(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});kr(e,$(t,"hooks","hooks.json"),n),kr(e,$(t,"hooks.json"),n);let i=e.components.length-o,a=s>=Ha;return{componentCount:i,expandTruncated:a}}function xr(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 ja(e){let t=$(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson($(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},p=s[a]===!0,f=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof u.version=="string"?u.version:"",g=typeof u.scope=="string"?u.scope:"user",_=`plugin:${a}`,S=0,E=!1;for(let y of l)if(typeof y.installPath=="string"&&y.installPath.length>0){let F=br(e,y.installPath,_,p);S+=F.componentCount,E=E||F.expandTruncated}xr(e,{pluginKey:a,rowPath:i,enabled:p,scope:g,version:d||void 0,marketplace:f||void 0,componentCount:S,expandTruncated:E,contentHash:M(`${a}|${d}|${g}|${p}|${S}`)})}}function xg(e){let t=e,n="";try{let r=bg(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=$(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=$(e,s),n=s)}}catch{}return{installPath:t,version:n}}var Ng=/^\d+$/;function Mg(e){let t=e.filter(n=>!Ng.test(n.pluginId));return t.length>0?t:e}function Ka(e){let t=[{base:$(e.home,".cursor/plugins/local"),scope:"local"},{base:$(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=$(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:p}=br(e,c,l,!0);xr(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:p,contentHash:M(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries($(n,s))){if(!a.isDirectory())continue;let c=$(n,s,a.name),{installPath:l,version:u}=xg(c);i.push({pluginId:a.name,installPath:l,version:u})}for(let a of Mg(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:p}=br(e,a.installPath,l,!0);xr(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:p,contentHash:M(`${c}|${a.version}|${u}`)})}}}import{existsSync as vg}from"node:fs";var wg=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Nr="<path>",Lg=new RegExp(`${Nr}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function en(e){let t=e.replace(wg,Nr).replace(Lg,Nr);return t.length>200?`${t.slice(0,200)}...`:t}var $a=200,Ba=200,Mr=16*1024,Ga=6,Ug=new Set(["permissions","sandbox","enableAllProjectMcpServers","enabledMcpjsonServers","disabledMcpjsonServers","disableAllHooks","disableAutoMode","allowManagedHooksOnly","allowManagedPermissionRulesOnly","allowManagedMcpServersOnly","strictKnownMarketplaces","strictPluginOnlyCustomization","disableSideloadFlags","forceLoginMethod","forceLoginOrgUUID"]),Dg=new Set(["type","additionalReadwritePaths","additionalReadonlyPaths","disableTmpWrite","enableSharedBuildCache","networkPolicy"]),Fg=new Set(["terminalAllowlist","mcpAllowlist","autoRun"]),Hg=new Set(["permissions"]),jg={claude:Ug,cursor_sandbox:Dg,cursor_permissions:Fg,cursor_cli:Hg},Kg=new Set(["allow","deny","ask"]);function _e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function tn(e){return e.replace(/\\/g,"/")}function wr(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(r=>wr(r)).join(",")}]`;let t=e;return`{${Object.keys(t).filter(r=>t[r]!==void 0).sort().map(r=>`${JSON.stringify(r)}:${wr(t[r])}`).join(",")}}`}function $g(e){return M(`${wr(e)}|settings1`)}function Ya(e){let t=tn(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 Xa(e,t){if(e!=="claude")return{};let n=tn(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 Za(e){let t=tn(e).replace(/\/+$/,"");return t.length<=1?"":t}function qa(e){return/^[A-Za-z]:/.test(e)||e.includes("\\")}function Bg(e,t){let n=tn(e);if(n==="~"||n.startsWith("~/"))return n;let r=Za(t);if(!r)return n;let o=n.slice(0,r.length);if(!(qa(t)?o.toLowerCase()===r.toLowerCase():o===r))return n;let i=n.slice(r.length);return i===""?"~":i.startsWith("/")?`~${i}`:n}var za=new Map;function Gg(e){let t=za.get(e);if(t!==void 0)return t;let n=Za(e),r=null;if(n){let o=n.split("/").map(s=>s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("[\\\\/]+");r=new RegExp(`(?<![\\w.-])${o}(?![\\w.-])`,qa(e)?"gi":"g")}return za.set(e,r),r}function zg(e,t){let n=Gg(t);return n?e.replace(n,"~"):e}function Va(e,t){return e.length<=Ba?e:(t.truncated=!0,e.slice(0,Ba))}function Qa(e,t){return e.length<=$a?e:(t.truncated=!0,e.slice(0,$a))}function L(e,t,n,r){if(typeof e=="string"){if(t==="path")return Va(Bg(e,n),r);let o=t==="rule"?en(e):e;return Va(zg(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=Qa(e,r),s=[];for(let i of o){let a=L(i,t,n,r);a!==void 0&&s.push(a)}return s}if(_e(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 Wa(e,t,n){if(!_e(e))return L(e,"plain",t,n);let r={};for(let[o,s]of Object.entries(e)){let i="plain";Kg.has(o)?i="rule":o==="additionalDirectories"&&(i="path");let a=L(s,i,t,n);a!==void 0&&(r[o]=a)}return r}function Vg(e,t,n){if(!_e(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=Qa(s,n);r[o]=a.map(c=>{if(!_e(c))return L(c,"plain",t,n);let l={};for(let[u,p]of Object.entries(c)){let d=L(p,u==="path"?"path":"plain",t,n);d!==void 0&&(l[u]=d)}return l});continue}let i=L(s,"plain",t,n);i!==void 0&&(r[o]=i)}return r}function Wg(e,t,n){if(!_e(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 Jg(e,t,n){if(!_e(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=Wg(s,t,n):o==="credentials"?i=Vg(s,t,n):i=L(s,"plain",t,n),i!==void 0&&(r[o]=i)}return r}function Yg(e,t,n,r,o){return n==="claude"?e==="permissions"?Wa(t,r,o):e==="sandbox"?Jg(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"?Wa(t,r,o):L(t,"plain",r,o)}function ut(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Lr(e,t){return e?`${e}.${t}`:t}function vr(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>=Ga?(e.splice(o,1),r.add(n)):vr(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>=Ga?(delete e[o],r.add(Lr(n,o))):vr(s,t+1,Lr(n,o),r))}function ec(e,t,n){if(Array.isArray(e)){e.length>0&&n.push({path:t,items:e,bytes:ut(e)});return}if(!(e===null||typeof e!="object"))for(let[r,o]of Object.entries(e))ec(o,Lr(t,r),n)}function Xg(e,t,n){let r=ut(e);if(r<=Mr)return;t.truncated=!0;let o=[];for(ec(e,"",o);r>Mr;){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=ut(i)+(s.items.length>0?1:0);s.bytes-=a,r-=a,n.add(s.path)}for(;ut(e)>Mr;){let s,i=-1;for(let[a,c]of Object.entries(e)){let l=ut(c);l>i&&(s=a,i=l)}if(s===void 0)break;delete e[s],n.add(s)}}function Zg(e,t,n){let r=jg[t],o={truncated:!1},s={},i=[];for(let c of Object.keys(e)){if(!r.has(c)){i.push(c);continue}let l=Yg(c,e[c],t,n,o);l!==void 0&&(s[c]=l)}i.sort();let a=new Set;return vr(s,1,"",a),a.size>0&&(o.truncated=!0),Xg(s,o,a),{settings:s,keys_omitted:i,truncated:o.truncated,trimmed_paths:[...a].sort()}}function Ja(e,t){let n={kind:t.kind,name:"settings",path:e.componentPath(t.absPath),origin:t.origin,enabled:!0,content_hash:$g(t.attributes),attributes:t.attributes};e.push(n)}function Ur(e,t,n,r){if(!e.claimFile(t)||!vg(t))return;let o=_o(t);if(!o.ok||!_e(o.value)){if(r.profile){let l=!o.ok&&o.reason==="read"?"read_error":"parse_error",u={profile:r.profile,[l]:!0};r.managedSource&&(u.managed_source=r.managedSource),Ja(e,{kind:r.kind,absPath:t,origin:n,attributes:u})}return}let s=o.value,i=s.hooks;if(_e(i)&&Pr(e,t,i,n),!r.profile)return;let a=Zg(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),Ja(e,{kind:r.kind,absPath:t,origin:n,attributes:c})}function Qg(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Ae(e,{dir:Fe(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Ae(e,{dir:Fe(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=ha(i.map(c=>Fe(r,c)));a&&Jt(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:qg(a)})}for(let i of Rs(n))Ur(e,Fe(r,i),o,{kind:"SETTINGS",profile:Ya(i)});for(let i of n.mcpJson??[])Da(e,Fe(r,i),o);for(let i of n.mcpToml??[])Fa(e,Fe(r,i),o);if(s){if(n.managed){for(let i of kt(n.managed,process.platform,e.home))if(i.toLowerCase().endsWith(".json")){let a=Xa(n.managed,i);Ur(e,i,o,{kind:"MANAGED_SETTINGS",...a})}}n.plugins==="claude"?ja(e):n.plugins==="cursor"&&Ka(e)}}function tc(e,t){try{let n=new Wt(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)Qg(n,{layout:r,levelDir:t.levelDir,origin:t.origin,includeMachineWide:t.includeMachineWide});return{scopeRef:t.scopeRef,anchor:t.levelDir,components:n.components,truncated:n.truncated}}catch{return}}function Dr(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=tc(t,{layouts:Object.values(Ne),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:ce,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(le),l=hr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>Is(c,u)});i=l.parentRel;for(let u of l.anchors){let p=ir(u.dir);if(o!==void 0&&!o(u.scope,p))continue;let f=tc(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Sr,scopeRef:p});f&&(r[u.scope]=f)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function Fr(e,t,n={}){let r=n.truncated===!0,o=rt(e),s=new Set(e.map(u=>V(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=V(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=Qi(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 rc=2*1024*1024,e_=new Set(["HOOK","MCP_SERVER","PLUGIN","SETTINGS","MANAGED_SETTINGS"]);function Hr(e,t,n){let r=new Set(t.map(s=>V(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(V(s.path,s.name))||o.push(s));return o}function jr(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 nc(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function oc(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Kr(e,t=rc){let n=[],r=[];for(let u of e)e_.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,f=nc(u)+p;if(i+f<=t){s.push(u),i+=f,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let d=oc(u),g=nc(d)+p;if(i+g<=t){s.push(d),i+=g,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function $r(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:oc(n))}var t_=["user","cwd","repo","parent"];function Br(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let k of t_){let b=t.scopes[k];if(!b)continue;let D=n(k,b.scopeRef),H=D.components,W=Fr(b.components,H,{forceFull:H===void 0,truncated:b.truncated}),he=new Set(D.textHashes),j=Hr(b.components,W.upserts,he),v=$r([...W.upserts,...j],he);s.push({scope:k,walk:b,delta:W,outgoing:v,outgoingKeys:new Set(v.map(C=>V(C.path,C.name))),deliveredTextHashes:he,cachedComponents:H})}let i=s.flatMap(k=>k.outgoing),a=Kr(i,o),c=new Set(a.components.map(k=>V(k.path,k.name))),l=[],u=[],p=[],f=[],d=[],g=[],_=[];for(let k of s){let{scope:b,walk:D,delta:H}=k;g.push(...D.components),l.push(b);let W=a.components.filter(C=>k.outgoingKeys.has(V(C.path,C.name))),he=[...k.outgoingKeys].some(C=>!c.has(C)),j=H.truncated||he;j?p.push(b):H.full&&u.push(b),f.push(...W),!H.full&&!j&&d.push(...H.removed);let v=H.full?{}:{...k.cachedComponents??{}};if(!j)for(let C of H.removed)delete v[V(C.path,C.name)];for(let C of W)v[V(C.path,C.name)]=C.content_hash;_.push({scope:b,scopeRef:D.scopeRef,components:v,textHashes:jr(k.deliveredTextHashes,W.filter(C=>C.text!==void 0).map(C=>C.content_hash),D.components),collectedAtMs:r,included:W.length>0||H.removed.length>0&&!j||H.full})}let S={user_spec_hash:rt(g),user_spec_count:g.length,user_spec_truncated:p.length>0};l.length>0&&(S.user_spec_scopes=l,S.user_spec_full_scopes=u,S.user_spec_truncated_scopes=p,S.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(S.user_spec_full=!0),f.length>0&&(S.user_spec=f),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:_}}var dt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function nn(e){return e==="cwd"||e==="repo"||e==="parent"}function lt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Gr(e){return!lt(e)||!lt(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 sc(e){return n_(e)}function ic(e){return r_(e)}function ac(e){return o_(e)}function n_(e){if(!lt(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function r_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function zr(e,t){if(!lt(e))return;let n=e[t];return Gr(n)?n:void 0}function o_(e){if(!lt(e))return{};let t={};for(let[n,r]of Object.entries(e))Gr(r)&&(t[n]=r);return t}function Vr(e,t=20){let n=[];for(let[r,o]of Object.entries(e))Gr(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 u_=["allow","deny","ask"];function on(e){let t=U(e,{}),n=[];for(let r of u_)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:en(o),mode:r});return{model:t.model??"",permissionKeys:n}}function l_(e){let{serverManaged:t,fileBased:n}=Un(process.platform,e),r=on(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=on(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function d_(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 p_=10,f_="self-config-cache.json",uc=4;function je(){return I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function m_(){return I("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function g_(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=We}var __={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function h_(e,t=w){let n=__[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(`
39
39
  `)[0]??"").trim();return a||r(o+1)};return r(0)}function S_(e=cc()){return He(e,".ev-ai","agent-hook",f_)}function E_(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
40
40
  `);return M(n)}function rn(e,t,n=!1){let r=E_(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 Wr(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>He(e,a)),...n]){let a=c_(i);if(s.has(a))continue;s.add(a);let c=hn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function y_(e){return i_(e)?G(a_(e,"utf8"),{}):{}}function R_(e,t){try{Z(e,`${JSON.stringify(t)}
41
- `)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: self-config cache write failed open: ${r}`)}}function C_(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(nn(t))return zr(e[dt[t]],n)?.collected_at_ms}function I_(e,t,n){if(t==="user")return{components:sc(e.user_spec_components),textHashes:ic(e.user_spec_text_hashes)};if(!nn(t))return{components:void 0,textHashes:[]};let r=zr(e[dt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function A_(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=uc,r.home&&(o.user_spec_collected_at_ms=r.home.collectedAtMs,r.home.included&&(o.user_spec=r.hash,o.user_spec_components=r.home.components),o.user_spec_text_hashes=r.home.textHashes);for(let s of r.project){if(!nn(s.scope))continue;let i=dt[s.scope],a=ac(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]=Vr(a)}}return o}async function lc(e,t=process.cwd(),n=cc(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await h_(e),a="",c=[];if(o){let j=l_(n),v=on(He(n,".claude/settings.json")),C=on(He(t,".claude/settings.local.json"));a=j.model||C.model||v.model,c=d_([...j.permissionKeys,...v.permissionKeys,...C.permissionKeys]).slice(0,200)}let u={present:!1,size:0},l=j=>{let v=[],C=!1;for(let te of j){let gt=ho(He(n,te));if(v=v.concat(gt.entries),C=C||gt.truncated,v.length>=ce){v=v.slice(0,ce),C=!0;break}}return{entries:v,truncated:C}},p=S_(n),f=y_(p),d=f[e]??{},g=(d.send_count??0)+1,_=g>0&&g%p_===0,S=j=>_?void 0:d[j],E=l(pe.skills),y=l(pe.subagents),F=l(pe.commands),k=l(pe.rules),b={skills:rn(E.entries,S("skills"),E.truncated),subagents:rn(y.entries,S("subagents"),y.truncated),commands:rn(F.entries,S("commands"),F.truncated),rules:rn(k.entries,S("rules"),k.truncated)},D={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:b.skills,subagents:b.subagents,commands:b.commands,rules:b.rules,memory:Wr(n,pe.memory),settings:Wr(n,pe.settings,As(n)),mcp:Wr(n,pe.mcp)},local_settings:o?hn(He(t,".claude/settings.local.json")):u},H=null,W=r.nowMs??Date.now();if(!je()&&!r.deferUserSpec){let j=d.user_spec_layout_version!==uc,v=Dr(e,n,{launchCwd:m_()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(C,te)=>j||g_(C_(d,C,te),W)});if(Object.keys(v.scopes).length>0){let C=Br({collected:v,cacheFor:(te,gt)=>j?{components:void 0,textHashes:[]}:I_(d,te,gt),nowMs:W});Object.assign(D,C.fields),H={hash:C.fields.user_spec_hash,home:C.scopes.find(te=>te.scope==="user")??null,project:C.scopes.filter(te=>te.scope!=="user")}}}let he=A_(d,b,g,H);return{config:D,commit:()=>{f[e]=he,R_(p,f)}}}import{homedir as $_}from"node:os";import{join as fc}from"node:path";function Te(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{join as sn}from"node:path";function O_(e){return sn(e,".ev-ai","agent-hook","js","signed-v1")}function T_(e){return sn(O_(e),"scopes")}function dc(e,t){return sn(T_(e),t)}function pc(e){return sn(e,"attempts")}function Jr(e){return String(e).padStart(10,"0")}var P_=/^(\d{10})$/,k_=/^(\d{10})\.done$/,b_=/^[0-9a-f]{128}$/,x_=64;async function hc(e,t,n=!1){let r=pc(t),o=await _s(e,r),s=new Map,i=new Map,a=mc(o,P_),c=mc(o,k_),u=async f=>{let d=await _c(e,fc(r,N_(f)));return d&&s.set(f,{record:w_(d.value),mtimeMs:d.mtimeMs}),d!==void 0},l=async f=>{let d=L_((await _c(e,fc(r,M_(f))))?.value);return d&&i.set(f,d),d!==void 0};if(!n)return await Promise.all([...a.map(u),...c.map(l)]),{claims:s,dones:i};await Promise.all([gc(a,u),gc(c,l)]);let p=pt(s);return p<pt(i)&&c.includes(p)&&await l(p),{claims:s,dones:i}}function mc(e,t){return e.flatMap(n=>{let r=t.exec(n);return r?[Number(r[1])]:[]})}async function gc(e,t){for(let n of[...e].sort((r,o)=>o-r))if(await t(n))return}function pt(e){let t=0;for(let n of e.keys())n>t&&(t=n);return t}function Sc(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 N_(e){return Jr(e)}function M_(e){return`${Jr(e)}.done`}async function _c(e,t){let n;try{n=await e.stat(t)}catch(o){if(vn(o))return;throw o}let r=n.mtimeMs;if(n.size===0||n.size>yn)return{mtimeMs:r};try{let o=await e.readFile(t);return o.byteLength===0||o.byteLength>yn?{mtimeMs:r}:{mtimeMs:r,value:JSON.parse(o.toString("utf8"))}}catch{return{mtimeMs:r}}}function w_(e){if(!Te(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 L_(e){if(!Te(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=v_(t.selection);if(n)return{finished_at:t.finished_at,interval_s:t.interval_s,outcome:t.outcome,selection:n}}function v_(e){if(!Te(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"&&b_.test(t.digest)&&typeof t.version=="string"&&t.version.length>0&&typeof t.sha512=="string"&&U_(t.sha512)===t.digest)return{kind:"cached",digest:t.digest,version:t.version,sha512:t.sha512}}function U_(e){if(e.length===0||!/^[A-Za-z0-9+/]+=*$/.test(e))return;let t=Buffer.from(e,"base64");if(!(t.byteLength!==x_||t.toString("base64")!==e))return t.toString("hex")}function j_(e){return e==="bootstrap"?3e3:6e4}function K_(e,t){let n=pt(e.claims);if(n===0)return;let r=pt(e.dones),o=e.claims.get(n),s=e.dones.get(n);if(o&&!s){let a=Sc(o),c=o.record==="empty"?void 0:o.record.owner,u=j_(c)+3e4;if(t-a>u)return{n,latest_claim:n,outcome:"incomplete",finished_at:null,selection_version:Ec(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:Ec(i.selection)}}async function yc(e,t,n){try{let r=await hc(hs(),dc(e,t),!0);return K_(r,n)}catch{return}}function Ec(e){return e?.kind==="cached"&&typeof e.version=="string"?e.version:null}async function Rc(e=$_()){let t=rr()?.launcherScope;if(!t)return{};let n=await yc(e,t,Date.now());return n?{launcher_scope:t,launcher_attempt:n}:{launcher_scope:t}}function Ke(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:At,event:e,timestamp:_t(),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:xn,host_arch:process.arch,node_version:process.version,correlation:r,payload:t},s=rr();return s&&(o.launcher_version=s.launcherVersion,o.hook_source=s.hookSource,o.hook_fallback_reason=s.fallbackReason??null,o.launcher_scope_match=Ni(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 Cc}from"node:fs";import{spawn as Ic}from"node:child_process";import{fileURLToPath as G_}from"node:url";import{gzipSync as B_}from"node:zlib";function Yr(e){return I("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<Go?{body:e}:{body:B_(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function an(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function Xr(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var Zr="__post",cn="__work";async function z_(e,t,n={}){if(je())return e;let r=await cr(n.gitRoot??process.cwd(),w,process.env,{runnerPlatform:t,home:n.home}),o=Te(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 V_(e,t){let n=Te(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 Ac(e){switch(e){case"session_start":return jo;case"session_end":return Ko;case"tool_invoked":case"skill_invoked":return Pn;default:return Pn}}function W_(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
41
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: self-config cache write failed open: ${r}`)}}function C_(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(nn(t))return zr(e[dt[t]],n)?.collected_at_ms}function I_(e,t,n){if(t==="user")return{components:sc(e.user_spec_components),textHashes:ic(e.user_spec_text_hashes)};if(!nn(t))return{components:void 0,textHashes:[]};let r=zr(e[dt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function A_(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=uc,r.home&&(o.user_spec_collected_at_ms=r.home.collectedAtMs,r.home.included&&(o.user_spec=r.hash,o.user_spec_components=r.home.components),o.user_spec_text_hashes=r.home.textHashes);for(let s of r.project){if(!nn(s.scope))continue;let i=dt[s.scope],a=ac(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]=Vr(a)}}return o}async function lc(e,t=process.cwd(),n=cc(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await h_(e),a="",c=[];if(o){let j=l_(n),v=on(He(n,".claude/settings.json")),C=on(He(t,".claude/settings.local.json"));a=j.model||C.model||v.model,c=d_([...j.permissionKeys,...v.permissionKeys,...C.permissionKeys]).slice(0,200)}let l={present:!1,size:0},u=j=>{let v=[],C=!1;for(let te of j){let gt=ho(He(n,te));if(v=v.concat(gt.entries),C=C||gt.truncated,v.length>=ce){v=v.slice(0,ce),C=!0;break}}return{entries:v,truncated:C}},p=S_(n),f=y_(p),d=f[e]??{},g=(d.send_count??0)+1,_=g>0&&g%p_===0,S=j=>_?void 0:d[j],E=u(pe.skills),y=u(pe.subagents),F=u(pe.commands),k=u(pe.rules),b={skills:rn(E.entries,S("skills"),E.truncated),subagents:rn(y.entries,S("subagents"),y.truncated),commands:rn(F.entries,S("commands"),F.truncated),rules:rn(k.entries,S("rules"),k.truncated)},D={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:b.skills,subagents:b.subagents,commands:b.commands,rules:b.rules,memory:Wr(n,pe.memory),settings:Wr(n,pe.settings,As(n)),mcp:Wr(n,pe.mcp)},local_settings:o?hn(He(t,".claude/settings.local.json")):l},H=null,W=r.nowMs??Date.now();if(!je()){let j=d.user_spec_layout_version!==uc,v=Dr(e,n,{launchCwd:m_()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(C,te)=>j||g_(C_(d,C,te),W)});if(Object.keys(v.scopes).length>0){let C=Br({collected:v,cacheFor:(te,gt)=>j?{components:void 0,textHashes:[]}:I_(d,te,gt),nowMs:W});Object.assign(D,C.fields),H={hash:C.fields.user_spec_hash,home:C.scopes.find(te=>te.scope==="user")??null,project:C.scopes.filter(te=>te.scope!=="user")}}}let he=A_(d,b,g,H);return{config:D,commit:()=>{f[e]=he,R_(p,f)}}}import{homedir as $_}from"node:os";import{join as fc}from"node:path";function Te(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{join as sn}from"node:path";function O_(e){return sn(e,".ev-ai","agent-hook","js","signed-v1")}function T_(e){return sn(O_(e),"scopes")}function dc(e,t){return sn(T_(e),t)}function pc(e){return sn(e,"attempts")}function Jr(e){return String(e).padStart(10,"0")}var P_=/^(\d{10})$/,k_=/^(\d{10})\.done$/,b_=/^[0-9a-f]{128}$/,x_=64;async function hc(e,t,n=!1){let r=pc(t),o=await _s(e,r),s=new Map,i=new Map,a=mc(o,P_),c=mc(o,k_),l=async f=>{let d=await _c(e,fc(r,N_(f)));return d&&s.set(f,{record:w_(d.value),mtimeMs:d.mtimeMs}),d!==void 0},u=async f=>{let d=L_((await _c(e,fc(r,M_(f))))?.value);return d&&i.set(f,d),d!==void 0};if(!n)return await Promise.all([...a.map(l),...c.map(u)]),{claims:s,dones:i};await Promise.all([gc(a,l),gc(c,u)]);let p=pt(s);return p<pt(i)&&c.includes(p)&&await u(p),{claims:s,dones:i}}function mc(e,t){return e.flatMap(n=>{let r=t.exec(n);return r?[Number(r[1])]:[]})}async function gc(e,t){for(let n of[...e].sort((r,o)=>o-r))if(await t(n))return}function pt(e){let t=0;for(let n of e.keys())n>t&&(t=n);return t}function Sc(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 N_(e){return Jr(e)}function M_(e){return`${Jr(e)}.done`}async function _c(e,t){let n;try{n=await e.stat(t)}catch(o){if(vn(o))return;throw o}let r=n.mtimeMs;if(n.size===0||n.size>yn)return{mtimeMs:r};try{let o=await e.readFile(t);return o.byteLength===0||o.byteLength>yn?{mtimeMs:r}:{mtimeMs:r,value:JSON.parse(o.toString("utf8"))}}catch{return{mtimeMs:r}}}function w_(e){if(!Te(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 L_(e){if(!Te(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=v_(t.selection);if(n)return{finished_at:t.finished_at,interval_s:t.interval_s,outcome:t.outcome,selection:n}}function v_(e){if(!Te(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"&&b_.test(t.digest)&&typeof t.version=="string"&&t.version.length>0&&typeof t.sha512=="string"&&U_(t.sha512)===t.digest)return{kind:"cached",digest:t.digest,version:t.version,sha512:t.sha512}}function U_(e){if(e.length===0||!/^[A-Za-z0-9+/]+=*$/.test(e))return;let t=Buffer.from(e,"base64");if(!(t.byteLength!==x_||t.toString("base64")!==e))return t.toString("hex")}function j_(e){return e==="bootstrap"?3e3:6e4}function K_(e,t){let n=pt(e.claims);if(n===0)return;let r=pt(e.dones),o=e.claims.get(n),s=e.dones.get(n);if(o&&!s){let a=Sc(o),c=o.record==="empty"?void 0:o.record.owner,l=j_(c)+3e4;if(t-a>l)return{n,latest_claim:n,outcome:"incomplete",finished_at:null,selection_version:Ec(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:Ec(i.selection)}}async function yc(e,t,n){try{let r=await hc(hs(),dc(e,t),!0);return K_(r,n)}catch{return}}function Ec(e){return e?.kind==="cached"&&typeof e.version=="string"?e.version:null}async function Rc(e=$_()){let t=rr()?.launcherScope;if(!t)return{};let n=await yc(e,t,Date.now());return n?{launcher_scope:t,launcher_attempt:n}:{launcher_scope:t}}function Ke(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:At,event:e,timestamp:_t(),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:xn,host_arch:process.arch,node_version:process.version,correlation:r,payload:t},s=rr();return s&&(o.launcher_version=s.launcherVersion,o.hook_source=s.hookSource,o.hook_fallback_reason=s.fallbackReason??null,o.launcher_scope_match=Ni(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 Cc}from"node:fs";import{spawn as Ic}from"node:child_process";import{fileURLToPath as G_}from"node:url";import{gzipSync as B_}from"node:zlib";function Yr(e){return I("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<Go?{body:e}:{body:B_(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function an(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function Xr(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var Zr="__post",cn="__work";async function z_(e,t,n={}){if(je())return e;let r=await cr(n.gitRoot??process.cwd(),w,process.env,{runnerPlatform:t,home:n.home}),o=Te(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 V_(e,t){let n=Te(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 Ac(e){switch(e){case"session_start":return jo;case"session_end":return Ko;case"tool_invoked":case"skill_invoked":return Pn;default:return Pn}}function W_(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
42
42
  ${n}`}function Oc(e,t=[],n=process.execPath,r=import.meta.url,o=Cc){if(Ho(n))return{command:n,args:[e,...t]};let s=G_(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function J_(e=process.execPath,t=import.meta.url,n=Cc){return Oc(Zr,[],e,t,n)}function Y_(e){let t=e.indexOf(`
43
- `);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 Tc(e,t=fetch){let n=await e(),r=Y_(n);if(!r)return;let{meta:o,body:s}=r,i=Yr(s),a=an(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function X_(e,t,n,r=fetch){let o=Ac(e),s=Yr(t),i=an(s.contentEncoding),a=Xr(s.body);h(`POST event=${e} url=${Ct(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{}h(`POST gzip rejected http=${u.status} \u2014 retrying uncompressed`),u=await r(n,{method:"POST",headers:an(),body:t,signal:AbortSignal.timeout(o)})}let l=Date.now()-c;if(u.ok)return h(`POST outcome=ok elapsed_ms=${l} http=${u.status}`),!0;let p=(await u.text()).slice(0,200).replace(/[\n\r]/g,"");return h(`POST outcome=fail elapsed_ms=${l} http=${u.status} body=${p}`),!1}catch(u){let l=Date.now()-c,p=u instanceof Error?u.message:String(u);return h(`POST outcome=fail elapsed_ms=${l} http=000 body=${p}`),!1}}async function Pc(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){h(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},$o),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 h(`WARN: ${o} spawn failed open: ${i}`),null}}async function Z_(e,t,n,r=Ic,o=J_){let s=Ac(e),i=W_(n,s,t),{command:a,args:c}=o();return Pc(a,c,i,r,"detached post")}async function kc(e,t,n=Ic,r=Oc){let{command:o,args:s}=r(cn,t);return Pc(o,s,e,n,"detached work")}async function $e(e,t,n,r,o,s,i){if(!o)return h("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Rt(o))return h(`WARN: collector URL blocked (https required): ${Ct(o)}`),!1;let a=await z_(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}
44
- `,p=I("EV_AI_HOOK_DEBUG");p==="full"?h(`DEBUG envelope=${u}`):p==="1"&&h(`DEBUG summary=${V_(c,Xr(l))}`);let f=process.argv.includes(cn),d=I("EV_AI_HOOK_SYNC")==="1";return Ft(n.runnerEvent,n.runnerPlatform)||f||d?X_(e,l,o):(await Z_(e,l,o),!1)}import{createReadStream as q_}from"node:fs";import{stat as Q_}from"node:fs/promises";import{basename as eh,resolve as th}from"node:path";import{createInterface as nh}from"node:readline";var rh=1024*1024;function oh(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&eh(t).endsWith(".jsonl")}async function bc(e){if(!e||!oh(e))return null;try{let t=th(e),n=await Q_(t);if(!n.isFile())return null;let r=Math.max(0,n.size-rh),o=[],s=nh({input:q_(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 un(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function mt(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function Qr(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function Mc(e){let t=Date.now();await _h(e);let{gitRoot:n}=e.manifest;await to(e,n);let r=Qr(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:zt(e.hookInput,e.manifest.manifest,r),envelopeFields:un(e),launchCwd:gr(e.hookInput,r),home:ih()}}function xc(e){try{return z(sh(e))}catch{return null}}function wc(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function Nc(e,t){let n=e.replaceAll("\\","/");if(!wc(n))return null;let r=z(e),o=z(t),s=xc(e)??r,i=xc(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function Lc(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=Nc(e,t)??(wc(r)?null:r),i=Nc(e,n);return{repositorySourcePath:s,userSourcePath:i}}function qr(e,t,n,r,o){return vc(e,Lc(n,t.gitRoot,t.home),r,o)}function vc(e,{repositorySourcePath:t,userSourcePath:n},r,o){let s=t??n,i=s===null?null:o(s),a=i!==null&&s!==null?ah({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 ah(e){try{let t=e.inRepository?lh(e.platformAgentId,e.sourcePath):(0,T.installationRootExternalKey)(e.installationId,(0,T.userConfigRootFromPath)(e.sourcePath));return t?(0,T.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function eo(e,t,n){return $e("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Ke,e.manifest.collectorUrl,t.buildStartedAtMs,mt(e,t.home))}function ch(e){return gi(e.runnerEvent,e.runnerPlatform)?[]:Ns(e.hookInput)}function uh(e,t){return eo(e,t,{})}var Uc=new Set([...Object.values(Ie),".github"]);function lh(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=>Uc.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}var Dc=".codex/config.toml",dh=new Map([["claude_json_user",".claude.json"],["cursor_mcp_user",".cursor/mcp.json"],["codex_toml_user",Dc]]);function ph(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()),u=c?dh.get(c.source):o==="codex"?Dc:void 0,l=c?.sourcePath??u;if((c?.scope==="user"||u!==void 0)&&l)try{let _=(0,T.userConfigRootFromPath)(l);return(0,T.buildComponentReference)({installationRootExternalKey:(0,T.installationRootExternalKey)(r,_),installableKind:T.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let f=n.indexOf(":");if(f<=0||f===n.length-1)return;let d=n.slice(f+1),g=d.replaceAll("\\","/").split("/").at(-1);if(!(g===void 0||!Uc.has(g)))try{return(0,T.buildComponentReference)({installationRootExternalKey:n,installableKind:T.ComponentKind.INTERFACE,sourcePath:d,nativeKey:t})}catch{return}}function fh(...e){for(let t of e)if(t)return t;return null}function ke(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return h(`WARN: ${n} failed open: ${r}`),t}function mh(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 gh(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Pe=new Set,ft=null;async function _h(e){if(je())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Pe.has(t))return;if(!lr(n)){Pe.add(t);return}let r=Ve({sessionId:e.sessionId,hostname:ht()});if(ta(r)){if(ft){await ft;return}ft=(async()=>{if(Pe.has(t)||!lr(n)){Pe.add(t);return}if(!is(n)){Pe.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),{operatorResolved:c,fields:u}=await Fc(e,r,Ut(i),ur({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})),l={...u,self_config:gh(a,c.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await $e("session_start",l,un(e),Ke,e.manifest.collectorUrl,s,mt(e)),o&&(c.commit(),Pe.add(t))}finally{as(n)}})().finally(()=>{ft=null}),await ft}}async function to(e,t,n){try{e.platformAgentId=await ei(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);h(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Fc(e,t,n,r){let[o,s,i,a,c]=await Promise.allSettled([n,Ro(),wi(t),Io(),r]),u=ke(o,null,"gitSnapshot"),l=ke(s,"","detectVirt"),p=ke(i,null,"probeCloud"),f=ke(a,{},"hostEnv"),d=ke(c,{commit:()=>{}},"resolveOperatorForSend");return await to(e,e.manifest.gitRoot,u),{operatorResolved:d,fields:{identity:{host:ht(),context:t,virt:l||null,cloud:p,git:u},host_env:f,env_vars:Li()}}}async function hh(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Ve({sessionId:e.sessionId,hostname:ht()}),o=String(e.runnerPlatform),s=Qr(e),i=gr(e.hookInput,s),a=Ut(n),c=Rc().catch(()=>({})),u=je()?Promise.resolve({commit:()=>{}}):ur({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),l=Fc(e,r,a,u),[p,f]=await Promise.allSettled([qn(e.manifest.manifest,n,o),a.catch(()=>null).then(D=>lc(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:D?.remote??null,deferUserSpec:e.deferUserSpec}))]),{operatorResolved:d,fields:g}=await l,_=ke(p,[],"mcpDeclared"),S=ke(f,mh(o),"selfConfig"),E=S.config,y=R(e.hookInput,"model");y&&(E.model=y);let F={...g,mcp:{declared:_},self_config:E,run_meta:{trigger:e.hookSource||"startup",...e.deferUserSpec?{user_spec_deferred:"launcher_refresh"}:{}},hook_input:zt(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},k=await c;await $e("session_start",F,{...un(e),...k},Ke,e.manifest.collectorUrl,t,mt(e))&&(S.commit(),d.commit(),Pe.add(e.manifest.installationId))}async function Sh(e){let t=Date.now(),[,n]=await Promise.all([to(e,e.manifest.gitRoot),e.runnerPlatform==="claude"?bc(R(e.hookInput,"transcript_path")):null]),r=e.runnerEvent.toLowerCase(),o=fh(R(e.hookInput,"status"),R(e.hookInput,"stop_reason"),R(e.hookInput,"reason"),tt(R(e.hookInput,"error")),r==="stop"?ne(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=zt(e.hookInput,e.manifest.manifest,Qr(e));n&&(s.model=n),r!=="stopfailure"&&!ia(e.manifest.manifest)&&s.last_assistant_message===void 0&&(s.last_assistant_message=""),await $e("session_end",{status:o,...n?{model:n}:{},hook_input:s},un(e),Ke,e.manifest.collectorUrl,t,mt(e))}async function Eh(e){let t=ch(e),n=oi(e.hookInput),r=mi(e.runnerEvent),o=r&&t.length===0&&n.length===0;if(t.length===0&&n.length===0&&!r)return;let s=await Mc(e);await Promise.all([o?uh(e,s):void 0,t.length===0?void 0:yh(e,s,t),n.length===0?void 0:Rh(e,s,n)])}function Hc(e,t,n,r){let o=r??xs({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=qr(e,t,o,T.ComponentKind.SKILL,T.nativeKeyForSkillPath);if(s.sourcePath!==null&&Fn(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??si({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=qr(e,t,i,T.ComponentKind.COMMAND,T.nativeKeyForCommandPath);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function yh(e,t,n){let r=xt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=Hc(e,t,o,r);return eo(e,t,{tool_name:"Skill",skill_name:o,...s.commandName===void 0?{}:{command_name:s.commandName},...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}function Rh(e,t,n){return Promise.all(n.map(r=>{let o=ti({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=qr(e,t,o,T.ComponentKind.RULE,T.nativeKeyForRulePath),i=s.nativeKey??ri(r);return eo(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var Ch=[{kind:T.ComponentKind.SKILL,nativeKeyFn:T.nativeKeyForSkillPath},{kind:T.ComponentKind.RULE,nativeKeyFn:T.nativeKeyForRulePath},{kind:T.ComponentKind.COMMAND,nativeKeyFn:T.nativeKeyForCommandPath}];function Ih(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=jn(e.hookInput);if(r===null)return n.skillName===null?{}:Hc(e,t,n.skillName,null);let o=Lc(r,t.gitRoot,t.home);for(let s of Ch){let i=vc(e,o,s.kind,s.nativeKeyFn);if(i.nativeKey!==null)return{...i.componentReference===void 0?{}:{componentReference:i.componentReference},...s.kind===T.ComponentKind.RULE?{ruleName:i.nativeKey}:{},...s.kind===T.ComponentKind.COMMAND?{commandName:i.nativeKey}:{}}}return{}}var Ah=/mcp/i;function Oh(e,t,n,r){let o=Ah.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?va(t,n):Qt(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 Th(e){let t=await Mc(e),n=Ei(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=Hn(e.hookInput),i=wa(s,t.home),a=Ri(e.hookInput),c=_i(e.runnerEvent),u=c===!1?Ci(e.hookInput,e.runnerEvent):null,l=tt(R(e.hookInput,"mcp_server_name")),p=l!==null||r!==null&&Ht(r)?await qn(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]):[],{mcpServer:f,mcpTool:d}=Ai(r,p.map(D=>D.name),l??""),g=ph(r,f,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),p,l),_=g===void 0?Ih(e,t,n):{},S=f===null?null:di(f,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),E=Oh(e,s,t.home,{hasMcpIdentity:!!f||!!d,declaredConfig:S}),y=g??_.componentReference,F=_.ruleName??n.ruleName,k=_.commandName??n.commandName,b=yi(e.hookInput);await $e("tool_invoked",{tool_name:r,skill_name:o,...F?{rule_name:F}:{},...k?{command_name:k}:{},success:c,duration_ms:a,...i?{executable:i}:{},...u?{failure_reason:u}:{},...f?{mcp_server:f}:{},...d?{mcp_tool:d}:{},...E,...y?{component_reference:y}:{},...b?{subagent_type:b}:{},hook_input:t.hookInput},t.envelopeFields,Ke,e.manifest.collectorUrl,t.buildStartedAtMs,mt(e,t.home))}async function jc(e){switch(e.internalEvent){case"session_start":await hh(e);return;case"session_end":await Sh(e);return;case"skill_invoked":await Eh(e);return;case"tool_invoked":await Th(e);return;default:return}}import{existsSync as ro,readFileSync as Ph}from"node:fs";import{dirname as kh,isAbsolute as bh,join as xh,relative as Nh}from"node:path";function Kc(e){for(let t of Lo){let n=xh(e,t);if(ro(n))return n}}async function Mh(e=process.cwd(),t){let n=t??await _n(e);return Kc(n)??Kc(e)}async function wh(e,t){let n=t??await _n(kh(e)),r=Nh(n,e);if(r.startsWith("..")||bh(r))return!1;let o=await J("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(h(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function no(e){let t=Ph(e,"utf8");return G(t,{})}function Lh(){return{schema_version:At,mcp_servers:[]}}function vh(e,t,n,r){!t||!n||(e.capture_hook_input==="full"&&r.has("capture_hook_input")&&(h(`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")&&(h(`WARN: ignoring debug=true in git-tracked manifest ${t}; set debug on ~/.ev-ai/config.json`),delete e.debug))}async function $c(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await gn(e),o=I("EV_AI_HOOK_MANIFEST"),s=o&&ro(o)?o:void 0,i=s?void 0:ro(In())?In():void 0,a=s?void 0:await Mh(e,n),c=i?no(i):void 0,u=a?no(a):void 0,l,p,f,d=new Set;if(s){l=no(s),p=s,f=s;for(let y of Object.keys(l))d.add(y)}else if(c&&u){l=vo(u,c),p=i,f=a;for(let y of Object.keys(u))y in c||d.add(y)}else if(c)l=c,p=i;else if(u){l=u,p=a,f=a;for(let y of Object.keys(u))d.add(y)}else l=Lh();delete l.installation_id;let g=f?await wh(f,n):!1;vh(l,f,g,d);let{installationId:_,storePath:S,repoKey:E}=await ds(n,{sessionId:t.sessionId});return{manifestPath:p??S,manifest:l,installationId:_,installationStorePath:S,repoKey:E,collectorUrl:Tn(l),platformAgentId:l.platform_agent_id??"",gitRoot:n,inGitRepo:r}}import{mkdirSync as Uh,readdirSync as Dh,readFileSync as Fh,statSync as Bc,unlinkSync as Hh,writeFileSync as jh}from"node:fs";import{homedir as ln}from"node:os";import{join as oo}from"node:path";var Kh="turns",Gc=1440*60*1e3,$h=100,Bh=new Set(["stop","stopfailure","sessionend"]);function so(e=ln()){return oo(re(e),Kh)}function zc(e,t){return oo(e,ze(t))}function Gh(e,t=Date.now()){let n;try{n=Dh(e)}catch{return}let r=0;for(let o of n){if(r>=$h)return;r+=1;try{let s=oo(e,o);t-Bc(s).mtimeMs>Gc&&Hh(s)}catch{}}}function zh(e,t,n=ln()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=so(n);Uh(s,{recursive:!0}),jh(zc(s,r),o,"utf8")}catch{}}function Vh(e,t=ln()){let n=e.trim();if(!n)return"";try{let r=zc(so(t),n);return Date.now()-Bc(r).mtimeMs>Gc?"":Fh(r,"utf8").trim()}catch{return""}}function Vc(e,t,n,r=ln()){let o=t.trim(),s=Bh.has(n.trim().toLowerCase());return s&&Gh(so(r)),o?(zh(e,o,r),o):s?Vh(e,r):""}async function Wc(e,t,n,r,o=!1){let s=t??await mn(kn),i=G(s,{}),a=await $c(process.cwd(),{sessionId:et(i)});if(!a)return;r&&(a.collectorUrl=r);let c=hi(i,a.manifest.platform,n),u=Si(e,c.runnerEvent);if(!u){h(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let l={hookInput:i,sessionId:c.sessionId,turnId:Vc(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 jc(l)}function Wh(e){if(I("EV_AI_HOOK_SYNC")==="1")return!0;let{parsed:t,hookInput:n,runnerEvent:r}=e,o=Qe(n,r,void 0,t.runner);return Ft(r,o)}function Jc(e,t){let n=Cn(e),r=G(t,{}),o=n.event??tr(r);return Eo()||fi(n.runner,r,o)?null:{parsed:n,hookInput:r,runnerEvent:o}}async function Yc(e=process.argv.slice(2)){if(xi(),e[0]===Zr){try{await Tc(fn)}catch{}return 0}if(e[0]===cn){try{let t=await fn(),n=Jc(e.slice(1),t);if(!n)return 0;let{parsed:r}=n;await Wc(r.event,t,r.runner,Qn(r),r.deferUserSpec)}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await mn(kn),n=Jc(e,t);if(!n)return 0;let{parsed:r,hookInput:o,runnerEvent:s}=n;if(!bi(o,s,r.runner))return 0;Wh(n)?await Wc(r.event,t,r.runner,Qn(r),r.deferUserSpec):await kc(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: hook failed open: ${n}`)}finally{mo()}return 0}Yc().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
43
+ `);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 Tc(e,t=fetch){let n=await e(),r=Y_(n);if(!r)return;let{meta:o,body:s}=r,i=Yr(s),a=an(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function X_(e,t,n,r=fetch){let o=Ac(e),s=Yr(t),i=an(s.contentEncoding),a=Xr(s.body);h(`POST event=${e} url=${Ct(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{}h(`POST gzip rejected http=${l.status} \u2014 retrying uncompressed`),l=await r(n,{method:"POST",headers:an(),body:t,signal:AbortSignal.timeout(o)})}let u=Date.now()-c;if(l.ok)return h(`POST outcome=ok elapsed_ms=${u} http=${l.status}`),!0;let p=(await l.text()).slice(0,200).replace(/[\n\r]/g,"");return h(`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 h(`POST outcome=fail elapsed_ms=${u} http=000 body=${p}`),!1}}async function Pc(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){h(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},$o),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 h(`WARN: ${o} spawn failed open: ${i}`),null}}async function Z_(e,t,n,r=Ic,o=J_){let s=Ac(e),i=W_(n,s,t),{command:a,args:c}=o();return Pc(a,c,i,r,"detached post")}async function kc(e,t,n=Ic,r=Oc){let{command:o,args:s}=r(cn,t);return Pc(o,s,e,n,"detached work")}async function $e(e,t,n,r,o,s,i){if(!o)return h("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Rt(o))return h(`WARN: collector URL blocked (https required): ${Ct(o)}`),!1;let a=await z_(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),u=`${l}
44
+ `,p=I("EV_AI_HOOK_DEBUG");p==="full"?h(`DEBUG envelope=${l}`):p==="1"&&h(`DEBUG summary=${V_(c,Xr(u))}`);let f=process.argv.includes(cn),d=I("EV_AI_HOOK_SYNC")==="1";return Ft(n.runnerEvent,n.runnerPlatform)||f||d?X_(e,u,o):(await Z_(e,u,o),!1)}import{createReadStream as q_}from"node:fs";import{stat as Q_}from"node:fs/promises";import{basename as eh,resolve as th}from"node:path";import{createInterface as nh}from"node:readline";var rh=1024*1024;function oh(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&eh(t).endsWith(".jsonl")}async function bc(e){if(!e||!oh(e))return null;try{let t=th(e),n=await Q_(t);if(!n.isFile())return null;let r=Math.max(0,n.size-rh),o=[],s=nh({input:q_(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 un(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function mt(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function Qr(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function Mc(e){let t=Date.now();await _h(e);let{gitRoot:n}=e.manifest;await to(e,n);let r=Qr(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:zt(e.hookInput,e.manifest.manifest,r),envelopeFields:un(e),launchCwd:gr(e.hookInput,r),home:ih()}}function xc(e){try{return z(sh(e))}catch{return null}}function wc(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function Nc(e,t){let n=e.replaceAll("\\","/");if(!wc(n))return null;let r=z(e),o=z(t),s=xc(e)??r,i=xc(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function Lc(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=Nc(e,t)??(wc(r)?null:r),i=Nc(e,n);return{repositorySourcePath:s,userSourcePath:i}}function qr(e,t,n,r,o){return vc(e,Lc(n,t.gitRoot,t.home),r,o)}function vc(e,{repositorySourcePath:t,userSourcePath:n},r,o){let s=t??n,i=s===null?null:o(s),a=i!==null&&s!==null?ah({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 ah(e){try{let t=e.inRepository?lh(e.platformAgentId,e.sourcePath):(0,T.installationRootExternalKey)(e.installationId,(0,T.userConfigRootFromPath)(e.sourcePath));return t?(0,T.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function eo(e,t,n){return $e("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Ke,e.manifest.collectorUrl,t.buildStartedAtMs,mt(e,t.home))}function ch(e){return gi(e.runnerEvent,e.runnerPlatform)?[]:Ns(e.hookInput)}function uh(e,t){return eo(e,t,{})}var Uc=new Set([...Object.values(Ie),".github"]);function lh(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=>Uc.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}var Dc=".codex/config.toml",dh=new Map([["claude_json_user",".claude.json"],["cursor_mcp_user",".cursor/mcp.json"],["codex_toml_user",Dc]]);function ph(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?dh.get(c.source):o==="codex"?Dc:void 0,u=c?.sourcePath??l;if((c?.scope==="user"||l!==void 0)&&u)try{let _=(0,T.userConfigRootFromPath)(u);return(0,T.buildComponentReference)({installationRootExternalKey:(0,T.installationRootExternalKey)(r,_),installableKind:T.ComponentKind.INTERFACE,sourcePath:u,nativeKey:c?.name??t})}catch{return}if(n===null)return;let f=n.indexOf(":");if(f<=0||f===n.length-1)return;let d=n.slice(f+1),g=d.replaceAll("\\","/").split("/").at(-1);if(!(g===void 0||!Uc.has(g)))try{return(0,T.buildComponentReference)({installationRootExternalKey:n,installableKind:T.ComponentKind.INTERFACE,sourcePath:d,nativeKey:t})}catch{return}}function fh(...e){for(let t of e)if(t)return t;return null}function ke(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return h(`WARN: ${n} failed open: ${r}`),t}function mh(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 gh(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Pe=new Set,ft=null;async function _h(e){if(je())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Pe.has(t))return;if(!lr(n)){Pe.add(t);return}let r=Ve({sessionId:e.sessionId,hostname:ht()});if(ta(r)){if(ft){await ft;return}ft=(async()=>{if(Pe.has(t)||!lr(n)){Pe.add(t);return}if(!is(n)){Pe.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),{operatorResolved:c,fields:l}=await Fc(e,r,Ut(i),ur({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})),u={...l,self_config:gh(a,c.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await $e("session_start",u,un(e),Ke,e.manifest.collectorUrl,s,mt(e)),o&&(c.commit(),Pe.add(t))}finally{as(n)}})().finally(()=>{ft=null}),await ft}}async function to(e,t,n){try{e.platformAgentId=await ei(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);h(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Fc(e,t,n,r){let[o,s,i,a,c]=await Promise.allSettled([n,Ro(),wi(t),Io(),r]),l=ke(o,null,"gitSnapshot"),u=ke(s,"","detectVirt"),p=ke(i,null,"probeCloud"),f=ke(a,{},"hostEnv"),d=ke(c,{commit:()=>{}},"resolveOperatorForSend");return await to(e,e.manifest.gitRoot,l),{operatorResolved:d,fields:{identity:{host:ht(),context:t,virt:u||null,cloud:p,git:l},host_env:f,env_vars:Li()}}}async function hh(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Ve({sessionId:e.sessionId,hostname:ht()}),o=String(e.runnerPlatform),s=Qr(e),i=gr(e.hookInput,s),a=Ut(n),c=Rc().catch(()=>({})),l=je()?Promise.resolve({commit:()=>{}}):ur({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),u=Fc(e,r,a,l),[p,f]=await Promise.allSettled([qn(e.manifest.manifest,n,o),a.catch(()=>null).then(D=>lc(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:D?.remote??null}))]),{operatorResolved:d,fields:g}=await u,_=ke(p,[],"mcpDeclared"),S=ke(f,mh(o),"selfConfig"),E=S.config,y=R(e.hookInput,"model");y&&(E.model=y);let F={...g,mcp:{declared:_},self_config:E,run_meta:{trigger:e.hookSource||"startup"},hook_input:zt(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},k=await c;await $e("session_start",F,{...un(e),...k},Ke,e.manifest.collectorUrl,t,mt(e))&&(S.commit(),d.commit(),Pe.add(e.manifest.installationId))}async function Sh(e){let t=Date.now(),[,n]=await Promise.all([to(e,e.manifest.gitRoot),e.runnerPlatform==="claude"?bc(R(e.hookInput,"transcript_path")):null]),r=e.runnerEvent.toLowerCase(),o=fh(R(e.hookInput,"status"),R(e.hookInput,"stop_reason"),R(e.hookInput,"reason"),tt(R(e.hookInput,"error")),r==="stop"?ne(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=zt(e.hookInput,e.manifest.manifest,Qr(e));n&&(s.model=n),r!=="stopfailure"&&!ia(e.manifest.manifest)&&s.last_assistant_message===void 0&&(s.last_assistant_message=""),await $e("session_end",{status:o,...n?{model:n}:{},hook_input:s},un(e),Ke,e.manifest.collectorUrl,t,mt(e))}async function Eh(e){let t=ch(e),n=oi(e.hookInput),r=mi(e.runnerEvent),o=r&&t.length===0&&n.length===0;if(t.length===0&&n.length===0&&!r)return;let s=await Mc(e);await Promise.all([o?uh(e,s):void 0,t.length===0?void 0:yh(e,s,t),n.length===0?void 0:Rh(e,s,n)])}function Hc(e,t,n,r){let o=r??xs({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=qr(e,t,o,T.ComponentKind.SKILL,T.nativeKeyForSkillPath);if(s.sourcePath!==null&&Fn(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??si({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=qr(e,t,i,T.ComponentKind.COMMAND,T.nativeKeyForCommandPath);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function yh(e,t,n){let r=xt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=Hc(e,t,o,r);return eo(e,t,{tool_name:"Skill",skill_name:o,...s.commandName===void 0?{}:{command_name:s.commandName},...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}function Rh(e,t,n){return Promise.all(n.map(r=>{let o=ti({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=qr(e,t,o,T.ComponentKind.RULE,T.nativeKeyForRulePath),i=s.nativeKey??ri(r);return eo(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var Ch=[{kind:T.ComponentKind.SKILL,nativeKeyFn:T.nativeKeyForSkillPath},{kind:T.ComponentKind.RULE,nativeKeyFn:T.nativeKeyForRulePath},{kind:T.ComponentKind.COMMAND,nativeKeyFn:T.nativeKeyForCommandPath}];function Ih(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=jn(e.hookInput);if(r===null)return n.skillName===null?{}:Hc(e,t,n.skillName,null);let o=Lc(r,t.gitRoot,t.home);for(let s of Ch){let i=vc(e,o,s.kind,s.nativeKeyFn);if(i.nativeKey!==null)return{...i.componentReference===void 0?{}:{componentReference:i.componentReference},...s.kind===T.ComponentKind.RULE?{ruleName:i.nativeKey}:{},...s.kind===T.ComponentKind.COMMAND?{commandName:i.nativeKey}:{}}}return{}}var Ah=/mcp/i;function Oh(e,t,n,r){let o=Ah.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?va(t,n):Qt(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 Th(e){let t=await Mc(e),n=Ei(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=Hn(e.hookInput),i=wa(s,t.home),a=Ri(e.hookInput),c=_i(e.runnerEvent),l=c===!1?Ci(e.hookInput,e.runnerEvent):null,u=tt(R(e.hookInput,"mcp_server_name")),p=u!==null||r!==null&&Ht(r)?await qn(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]):[],{mcpServer:f,mcpTool:d}=Ai(r,p.map(D=>D.name),u??""),g=ph(r,f,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),p,u),_=g===void 0?Ih(e,t,n):{},S=f===null?null:di(f,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),E=Oh(e,s,t.home,{hasMcpIdentity:!!f||!!d,declaredConfig:S}),y=g??_.componentReference,F=_.ruleName??n.ruleName,k=_.commandName??n.commandName,b=yi(e.hookInput);await $e("tool_invoked",{tool_name:r,skill_name:o,...F?{rule_name:F}:{},...k?{command_name:k}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...f?{mcp_server:f}:{},...d?{mcp_tool:d}:{},...E,...y?{component_reference:y}:{},...b?{subagent_type:b}:{},hook_input:t.hookInput},t.envelopeFields,Ke,e.manifest.collectorUrl,t.buildStartedAtMs,mt(e,t.home))}async function jc(e){switch(e.internalEvent){case"session_start":await hh(e);return;case"session_end":await Sh(e);return;case"skill_invoked":await Eh(e);return;case"tool_invoked":await Th(e);return;default:return}}import{existsSync as ro,readFileSync as Ph}from"node:fs";import{dirname as kh,isAbsolute as bh,join as xh,relative as Nh}from"node:path";function Kc(e){for(let t of Lo){let n=xh(e,t);if(ro(n))return n}}async function Mh(e=process.cwd(),t){let n=t??await _n(e);return Kc(n)??Kc(e)}async function wh(e,t){let n=t??await _n(kh(e)),r=Nh(n,e);if(r.startsWith("..")||bh(r))return!1;let o=await J("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(h(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function no(e){let t=Ph(e,"utf8");return G(t,{})}function Lh(){return{schema_version:At,mcp_servers:[]}}function vh(e,t,n,r){!t||!n||(e.capture_hook_input==="full"&&r.has("capture_hook_input")&&(h(`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")&&(h(`WARN: ignoring debug=true in git-tracked manifest ${t}; set debug on ~/.ev-ai/config.json`),delete e.debug))}async function $c(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await gn(e),o=I("EV_AI_HOOK_MANIFEST"),s=o&&ro(o)?o:void 0,i=s?void 0:ro(In())?In():void 0,a=s?void 0:await Mh(e,n),c=i?no(i):void 0,l=a?no(a):void 0,u,p,f,d=new Set;if(s){u=no(s),p=s,f=s;for(let y of Object.keys(u))d.add(y)}else if(c&&l){u=vo(l,c),p=i,f=a;for(let y of Object.keys(l))y in c||d.add(y)}else if(c)u=c,p=i;else if(l){u=l,p=a,f=a;for(let y of Object.keys(l))d.add(y)}else u=Lh();delete u.installation_id;let g=f?await wh(f,n):!1;vh(u,f,g,d);let{installationId:_,storePath:S,repoKey:E}=await ds(n,{sessionId:t.sessionId});return{manifestPath:p??S,manifest:u,installationId:_,installationStorePath:S,repoKey:E,collectorUrl:Tn(u),platformAgentId:u.platform_agent_id??"",gitRoot:n,inGitRepo:r}}import{mkdirSync as Uh,readdirSync as Dh,readFileSync as Fh,statSync as Bc,unlinkSync as Hh,writeFileSync as jh}from"node:fs";import{homedir as ln}from"node:os";import{join as oo}from"node:path";var Kh="turns",Gc=1440*60*1e3,$h=100,Bh=new Set(["stop","stopfailure","sessionend"]);function so(e=ln()){return oo(re(e),Kh)}function zc(e,t){return oo(e,ze(t))}function Gh(e,t=Date.now()){let n;try{n=Dh(e)}catch{return}let r=0;for(let o of n){if(r>=$h)return;r+=1;try{let s=oo(e,o);t-Bc(s).mtimeMs>Gc&&Hh(s)}catch{}}}function zh(e,t,n=ln()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=so(n);Uh(s,{recursive:!0}),jh(zc(s,r),o,"utf8")}catch{}}function Vh(e,t=ln()){let n=e.trim();if(!n)return"";try{let r=zc(so(t),n);return Date.now()-Bc(r).mtimeMs>Gc?"":Fh(r,"utf8").trim()}catch{return""}}function Vc(e,t,n,r=ln()){let o=t.trim(),s=Bh.has(n.trim().toLowerCase());return s&&Gh(so(r)),o?(zh(e,o,r),o):s?Vh(e,r):""}async function Wc(e,t,n,r){let o=t??await mn(kn),s=G(o,{}),i=await $c(process.cwd(),{sessionId:et(s)});if(!i)return;r&&(i.collectorUrl=r);let a=hi(s,i.manifest.platform,n),c=Si(e,a.runnerEvent);if(!c){h(`WARN: unknown hook event '${a.runnerEvent}'; skipping telemetry`);return}let l={hookInput:s,sessionId:a.sessionId,turnId:Vc(a.sessionId,a.turnId,a.runnerEvent),runnerEvent:a.runnerEvent,runnerPlatform:a.runnerPlatform,hookSource:a.hookSource,internalEvent:c,manifest:i,platformAgentId:i.platformAgentId};await jc(l)}function Wh(e){if(I("EV_AI_HOOK_SYNC")==="1")return!0;let{parsed:t,hookInput:n,runnerEvent:r}=e,o=Qe(n,r,void 0,t.runner);return Ft(r,o)}function Jc(e,t){let n=Cn(e),r=G(t,{}),o=n.event??tr(r);return Eo()||fi(n.runner,r,o)?null:{parsed:n,hookInput:r,runnerEvent:o}}async function Yc(e=process.argv.slice(2)){if(xi(),e[0]===Zr){try{await Tc(fn)}catch{}return 0}if(e[0]===cn){try{let t=await fn(),n=Jc(e.slice(1),t);if(!n)return 0;let{parsed:r}=n;await Wc(r.event,t,r.runner,Qn(r))}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await mn(kn),n=Jc(e,t);if(!n)return 0;let{parsed:r,hookInput:o,runnerEvent:s}=n;if(!bi(o,s,r.runner))return 0;Wh(n)?await Wc(r.event,t,r.runner,Qn(r)):await kc(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: hook failed open: ${n}`)}finally{mo()}return 0}Yc().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
45
45
  `),process.exit(1)});