@ev-ai/agent-hook 1.1.5 → 1.1.7

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