@ev-ai/agent-hook 1.1.3 → 1.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -2,42 +2,42 @@
2
2
  import { createRequire as __createRequire } from 'node:module';
3
3
  const require = __createRequire(import.meta.url);
4
4
 
5
- var wa=Object.create;var Nr=Object.defineProperty;var Pa=Object.getOwnPropertyDescriptor;var Ta=Object.getOwnPropertyNames;var Ma=Object.getPrototypeOf,Na=Object.prototype.hasOwnProperty;var rn=(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 Lr=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var La=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ta(t))!Na.call(e,o)&&o!==n&&Nr(e,o,{get:()=>t[o],enumerable:!(r=Pa(t,o))||r.enumerable});return e};var on=(e,t,n)=>(n=e!=null?wa(Ma(e)):{},La(t||!e||!e.__esModule?Nr(n,"default",{value:e,enumerable:!0}):n,e));var hs=Lr(G=>{"use strict";Object.defineProperty(G,"__esModule",{value:!0});G.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;G.launchContainsCredentials=eu;G.serializeMcpLaunchIdentity=gs;G.hashMcpLaunchIdentity=It;G.projectMcpLaunchIdentity=nu;G.maskMcpLaunchForDisplay=ou;G.normalizeMcpToolNames=su;var Zl=rn("node:crypto");G.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";var ms=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),Ql=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function me(e){return e.toLocaleLowerCase("en-US")}function Pe(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function eu(e){return e.kind==="url"?tu(e.url):e.kind==="command"?e.arguments.some(t=>Ql.test(t)):!1}function tu(e){try{let t=new URL(e);if(t.username.length>0||t.password.length>0)return!0;for(let n of t.searchParams.keys())if(ms.has(me(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=me(i.split("=",1)[0]??"");return ms.has(a)})}}function gs(e){if(e.kind==="url")return[G.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",Pe(me(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>me(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[G.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",Pe(me(e.command)),String(t.length),...t.map(Pe)].join("|")}return[G.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",Pe(e.installationRootExternalKey),Pe(e.sourcePath),Pe(e.nativeKey)].join("|")}function It(e){return(0,Zl.createHash)("sha256").update(e).digest("hex")}function nu(e){let t=gs(e);return e.kind==="url"?{kind:"url",url:me(e.url),arguments:[],serialized:t,contentHash:It(t)}:e.kind==="command"?{kind:"command",command:me(e.command),arguments:[...e.arguments].map(n=>me(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:It(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:It(t)}}var ru=/^(https?:\/\/)([^/?#]*@)/i;function ou(e){return e.replace(ru,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function su(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 xt=Lr(A=>{"use strict";Object.defineProperty(A,"__esModule",{value:!0});A.serializeMcpLaunchIdentity=A.projectMcpLaunchIdentity=A.normalizeMcpToolNames=A.MCP_LAUNCH_IDENTITY_ALGORITHM=A.maskMcpLaunchForDisplay=A.launchContainsCredentials=A.hashMcpLaunchIdentity=A.ComponentKind=void 0;A.userConfigRootFromPath=gu;A.installationRootExternalKey=hu;A.normalizeRepositoryRelativePath=_s;A.nativeKeyForSkillPath=_u;A.nativeKeyForRulePath=Su;A.nativeKeyForCommandPath=yu;A.serializeComponentIdentity=ys;A.buildComponentReference=Ru;A.validateComponentReference=Cu;var iu=rn("node:crypto"),au=rn("node:path"),cu="cmp1_",lu=/^cmp1_[A-Za-z0-9_-]{43}$/,uu=["/skills/","/skills-cursor/"],du=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,pu=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,fu=[".cursor",".claude",".codex"],mu={".claude.json":".claude",".agents":".codex"};A.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function gu(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>fu.includes(o));return n||(t.map(o=>mu[o]).find(o=>o!==void 0)??"unknown")}function hu(e,t){return`runtime-install:${e}/${t}`}function At(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function _s(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=au.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return At(n,"sourcePath")}function _u(e){let t=e.replaceAll("\\","/");for(let n of uu){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Ss(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 Su(e){return Ss(e,du,/\.(mdc|md|rules)$/i)}function yu(e){return Ss(e,pu,/\.(md|mdc|toml)$/i)}function Eu(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function ys(e){let t=[At(e.installationRootExternalKey,"installationRootExternalKey"),At(e.installableKind,"installableKind"),_s(e.sourcePath),At(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(Eu).join("|")}`,"utf8")}function Ru(e){let t=(0,iu.createHash)("sha256").update(ys(e)).digest("base64url");return`${cu}${t}`}function Cu(e){return lu.test(e)}var Ce=hs();Object.defineProperty(A,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return Ce.hashMcpLaunchIdentity}});Object.defineProperty(A,"launchContainsCredentials",{enumerable:!0,get:function(){return Ce.launchContainsCredentials}});Object.defineProperty(A,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return Ce.maskMcpLaunchForDisplay}});Object.defineProperty(A,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return Ce.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(A,"normalizeMcpToolNames",{enumerable:!0,get:function(){return Ce.normalizeMcpToolNames}});Object.defineProperty(A,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return Ce.projectMcpLaunchIdentity}});Object.defineProperty(A,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return Ce.serializeMcpLaunchIdentity}})});import{realpathSync as Wm}from"node:fs";import{resolve as Vm}from"node:path";import{fileURLToPath as Ym,pathToFileURL as qm}from"node:url";var Ua="https://hooks.ev-ai.ai";function lt(e,t=Ua){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var ut=".claude/ev-ai-runtime-report.json",Ur="node_modules/@ev-ai/agent-hook/dist/hook.mjs",ie="ev-ai-agent-hook",Dr="https://cdn.ev-ai.ai/agent-hook",sn=`current/${ie}`,an=`.ev-ai/agent-hook/${ie}`,Hr=5e3,Fr=5e3,cn=3e3;var ln=3e3,jr=1500,$r=4*1024,Kr=32*1024,Da=4*1024,Br=32*1024,Fe=840*60*1e3,ee="1.1.3",dt=`@ev-ai/agent-hook@${ee}`,Gr="ev-ai runtime report",zr=["claude","cursor","codex"];import{chmodSync as No,cpSync as Lo,existsSync as ce,mkdirSync as wn,readFileSync as $c,rmSync as yt,symlinkSync as Kc,writeFileSync as Bc}from"node:fs";import{homedir as ne}from"node:os";import{basename as Gc,dirname as Pn,isAbsolute as zc,join as O,relative as Uo,resolve as To,sep as Jc}from"node:path";import{fileURLToPath as Wc}from"node:url";var Ha=new Set(["localhost","127.0.0.1","[::1]","::1"]),Jr=/^[A-Za-z0-9._~-]+$/;function Wr(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 pt(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Ha.has(t.hostname):!1}catch{return!1}}function je(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!pt(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Fa(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!Jr.test(n))return`org token must match ${Jr.source} (got: ${n})`;if(Wr(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Wr(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function $e(e){return new URL(e).toString()}function Fa(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 un(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 Vr(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?lt(t):""}import{existsSync as ja,readdirSync as Yr}from"node:fs";import{homedir as ft}from"node:os";import{join as $}from"node:path";function qr(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return $(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function dn(e=process.platform){let t=qr(e),n=[$(t,"managed-settings.json")],r=$(t,"managed-settings.d");try{if(!ja(r))return n;let o=Yr(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>$(r,s));n.push(...o)}catch{}return n}function pn(e=process.platform,t=ft()){return{serverManaged:$(t,".claude","remote-settings.json"),fileBased:dn(e)}}function $a(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/Cursor";case"win32":return $(process.env.ProgramData??"C:\\ProgramData","Cursor");default:return"/etc/cursor"}}function Ka(e=process.platform,t=ft()){let n=[$($a(e),"hooks.json")],r=$(t,".cursor","managed");try{for(let o of Yr(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push($(r,o.name,"hooks.json"))}catch{}return n}function Ba(e=process.platform,t=ft()){let n=e==="win32"?$(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[$(n,"requirements.toml")];return e!=="win32"&&r.push($(n,"managed_config.toml")),r.push($(t,".codex","managed_config.toml"),$(n,"config.toml")),r}function mt(e,t=process.platform,n=ft()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=pn(t,n);return[r,...o]}case"cursor":return Ka(t,n);default:return Ba(t,n)}}import{createHash as po,randomBytes as pc}from"node:crypto";import{existsSync as fo,mkdirSync as Cn,readFileSync as mo,unlinkSync as go,writeFileSync as ho}from"node:fs";import{homedir as kn}from"node:os";import{dirname as ht,join as In,resolve as fc}from"node:path";var Ga=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),za=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]")||za.has(n)||r.includes("[bot]")||Ga.has(r))return!0;if(r.endsWith("@users.noreply.github.com")){let o=r.slice(0,r.indexOf("@")),s=o.includes("+")?o.slice(o.indexOf("+")+1):o;if(s.endsWith("bot")||s.includes("[bot]"))return!0}return!1}import{existsSync as Qa,readFileSync as ec}from"node:fs";import{hostname as oo,userInfo as tc}from"node:os";import{randomBytes as Ja}from"node:crypto";import{existsSync as mn,mkdirSync as Wa,readdirSync as Va,readFileSync as Ya,renameSync as Xr,statSync as eo,unlinkSync as Zr,writeFileSync as qa}from"node:fs";import{basename as Xa,dirname as Qr,join as to,relative as Za}from"node:path";function d(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
6
- `)}function Y(e,t){Wa(Qr(e),{recursive:!0});let n=to(Qr(e),`.${Xa(e)}.${process.pid}.${Ja(4).toString("hex")}.tmp`);try{qa(n,t,"utf8");try{Xr(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Zr(e),Xr(n,e);return}throw r}}catch(r){try{Zr(n)}catch{}throw r}}function gt(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function no(){process.stdout.write('{"continue":true}')}function R(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Ke(){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 gn(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 P(e,t,n=3e3,r={}){let o=await V(e,t,n,r);return o.ok?o.stdout:""}async function hn(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(R("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;d(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=R("CURSOR_PROJECT_DIR")??R("CLAUDE_PROJECT_DIR");if(n&&mn(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 te(e=process.cwd()){return(await hn(e)).root}function F(e,t){try{return JSON.parse(e)}catch{return t}}var fn=new Map;function L(e,t){let n=fn.get(e);if(n!==void 0)return n;try{let r=F(Ya(e,"utf8"),t);return fn.set(e,r),r}catch{return fn.set(e,t),t}}function he(e){return typeof e=="string"?e:""}function _e(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function g(e,t){let n=_e(e,t);return typeof n=="string"?n:""}var ae=500;function ro(e,t=2){if(!mn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=Va(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=to(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:Za(e,l),size:eo(l).size})}catch{continue}if(n.length>=ae){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function _n(e){return mn(e)?{present:!0,size:eo(e).size}:{present:!1,size:0}}function Oe(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Sn(e=process.env){return Oe(b("CURSOR_SANDBOX",e))}var nc=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function rc(e){return nc.some(t=>!!b(t,e))}function oc(e){if(b("KUBERNETES_SERVICE_HOST",e)||Oe(b("REMOTE_CONTAINERS",e))||Oe(b("DEVCONTAINER",e)))return!0;try{if(Qa("/.dockerenv")||ec("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function so(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!b(t,e))}function sc(e,t=process.platform){return so(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!b(n,e)):!1}function ic(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function ac(e){return e==="linux"}function b(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return R(e)}function cc(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!lc(b("CURSOR_VERSION",n))}function lc(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function yn(e){if(ic(e.sessionId))return!0;let t=e.hostname??oo(),n=e.osUser??io(e.env);return cc(t,n,e.env)}function uc(e){return Oe(b("CURSOR_AGENT",e.env))?!0:yn(e)}function dc(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(b("TERM",e)??b("TERM_PROGRAM",e))||(b("SSH_TTY",e)??b("SSH_CONNECTION",e))||(b("__CFBundleIdentifier",e)??b("XPC_SERVICE_NAME",e))||so(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!b(t,e))||b("SESSIONNAME",e))}function Be(e={}){let t=e.env;if(b("GITHUB_ACTIONS",t))return"github_actions";if(Oe(b("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!sc(t,n)&&uc(e)&&(Oe(b("CURSOR_AGENT",t))||ac(n)))return"cursor_cloud";if(b("CODESPACES",t)||b("CODESPACE_NAME",t))return"codespaces";if(b("GITLAB_CI",t))return"gitlab_ci";if(rc(t))return"managed";let r=b("CI",t);return r&&r!=="false"&&r!=="0"?"managed":oc(t)?"container":dc(t)?"interactive":"unknown"}async function En(){return await P("systemd-detect-virt",[],1e3)}function io(e=process.env,t=tc){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 Rn(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await P("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 P("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await P("uname",["-r"],1e3))}else t=await P("ver",[],1e3);let n=io(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await P("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 Ge(){return oo()}var mc="installation.json",gc="cloud-bootstrap.lock",hc=6e4;function _o(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function Se(e=kn()){return In(e,".ev-ai","agent-hook")}function _c(e=kn()){return In(Se(e),mc)}function So(e){return In(ht(e),gc)}function yo(){return pc(8).toString("hex")}function ve(e){return po("sha256").update(e).digest("hex").slice(0,16)}function C(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Eo(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Sc(e=process.env){let t=C(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Eo(t)){d(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function Ro(e,t){return e&&Eo(e)?e:(e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Sc(t))}function yc(e){return/^[0-9a-f]{16}$/.test(e)}function Ec(e=process.env){if(C(e.GITHUB_ACTIONS)){let t=C(e.GITHUB_REPOSITORY_ID)??C(e.GITHUB_REPOSITORY),n=C(e.GITHUB_ACTOR)??C(e.GITHUB_TRIGGERING_ACTOR)??C(e.GITHUB_USER);if(t&&n)return ve(`github_actions|${t}|${n}`)}if(C(e.CODESPACES)||C(e.CODESPACE_NAME)){let t=C(e.CODESPACE_NAME);if(t)return ve(`codespaces|${t}`);let n=C(e.GITHUB_REPOSITORY_ID)??C(e.GITHUB_REPOSITORY),r=C(e.GITHUB_USER)??C(e.GITHUB_ACTOR);if(n&&r)return ve(`codespaces|${n}|${r}`)}if(C(e.GITLAB_CI)){let t=C(e.CI_PROJECT_ID)??C(e.CI_PROJECT_PATH),n=C(e.GITLAB_USER_LOGIN)??C(e.GITLAB_USER_EMAIL)??C(e.GITLAB_USER_NAME);if(t&&n)return ve(`gitlab|${t}|${n}`)}return null}var Rc="cursoragent@cursor.com";function Cc(e){let t=C(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Rc?null:t}function kc(e,t){return C(e.CURSOR_PROJECT_DIR)??C(e.CLAUDE_PROJECT_DIR)??t}function Ic(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Ac(e){let t=await P("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Ic(t):e}async function xc(e){let t=C(await P("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!B(null,t))return t;let n=C(await P("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!B(null,n)?n:null}function Oc(e,t){let n=kc(e,t);return n?ve(`cursor_cloud|${n}|${Cc(e)??""}`):null}async function vc(e,t){let n=C(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Ac(n),o=await xc(n);return ve(`claude_remote|${r}|${o??""}`)}function ao(e,t){let n=Ro(e,t);if(n)return n;let r=Ec(t);return r||yo()}async function bc(e){let n=await P("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||fc(e);return po("sha256").update(n).digest("hex").slice(0,16)}function wc(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 Pc(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=wc(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function ye(e){if(fo(e))try{return Pc(mo(e,"utf8"))}catch{}}function An(e){return ye(e)}function Co(e,t,n){let r=ye(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Y(e,`${JSON.stringify(o,null,2)}
7
- `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: operator identity cache write failed open: ${i}`)}}function ko(e,t=Date.now()){if(!e)return!0;if(ye(e)?.operator_identity_hash)return!1;let n=So(e);try{if(fo(n)){let r=Number.NaN;try{r=Number(mo(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<hc)return!1;try{go(n)}catch{}}}catch{}try{return Cn(ht(n),{recursive:!0}),ho(n,`${t}
8
- `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(Oo(r))return!1;let o=r instanceof Error?r.message:String(r);return d(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function Io(e){if(e)try{go(So(e))}catch{}}function Ao(e,t){let r=ye(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function xo(e,t,n){if(!n)return;let r=ye(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{Y(e,`${JSON.stringify(o,null,2)}
9
- `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${i}`)}}function Oo(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Tc(e,t){Cn(ht(e),{recursive:!0}),ho(e,`${JSON.stringify(t,null,2)}
10
- `,{encoding:"utf8",flag:"wx"})}function co(e,t){try{return Tc(e,t),t}catch(n){if(!Oo(n))throw n;return ye(e)}}function lo(e,t){Cn(ht(e),{recursive:!0}),Y(e,`${JSON.stringify(t,null,2)}
11
- `)}function uo(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function _t(e,t={}){let n=t.home??kn(),r=t.env??process.env,o=await bc(e),s=_c(n),i={sessionId:t.sessionId,hostname:C(r.HOSTNAME)??void 0,osUser:C(r.USER)??C(r.LOGNAME)??C(r.USERNAME)??void 0,env:r},a=Be(i),c=Ro(t.overrideId,r),l=a==="cursor_cloud"&&yn(i)?Oc(r,e):a==="claude_remote"?await vc(r,e):null,u=ye(s);if(u){let S=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(S={...u,pinned:!0},lo(s,S)),!!l&&l!==S.installation_id&&!c&&S.pinned!==!0&&yc(S.installation_id)&&l){let E={installation_id:l,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return lo(s,E),{installationId:l,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let p=c??l??ao(void 0,r),m=co(s,uo(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let f=c??l??ao(void 0,r),_=co(s,uo(f===p?yo():f,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as xn,readFileSync as Mc}from"node:fs";import{dirname as Nc,join as vo,relative as Lc}from"node:path";var St=[ut,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Uc(e=process.cwd(),t){let n=R("EV_AI_HOOK_MANIFEST");if(n&&xn(n))return n;let r=t??await te(e);for(let o of St){let s=vo(r,o);if(xn(s))return s}for(let o of St){let s=vo(e,o);if(xn(s))return s}}async function Dc(e,t){let n=t??await te(Nc(e)),r=Lc(n,e),o=await V("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(d(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Hc(e){let t=Mc(e,"utf8");return F(t,{})}function Fc(){return{schema_version:2,mcp_servers:[]}}async function bo(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await hn(e),o=await Uc(e,n),s=o?Hc(o):Fc();delete s.installation_id;let i=o?await Dc(o,n):!1;s.capture_hook_input==="full"&&o&&i&&(d(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${o}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete s.capture_hook_input);let{installationId:a,storePath:c,repoKey:l}=await _t(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:a,installationStorePath:c,repoKey:l,collectorUrl:Vr(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function wo(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var jc=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"];function On(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0}function Po(e=process.platform,t=process.arch){let n=On(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${jc.join(", ")}.`);return n}function vn(e){return`compile-out/bin/${e}/ev-ai-agent-hook`}function Vc(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=je(n);if(r)throw new Error(`collector URL rejected: ${r}`);return $e(n)}function Yc(e){let t=e.collectorUrl?.trim();if(!t)return;let n=je(t);if(n)throw new Error(`collector URL rejected: ${n}`);return $e(t)}function qc(e){return Vc(e,"install")}function Do(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url")}return t}function Ho(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url");if(r==="--update")throw new Error("--update was removed; use the `update` command instead of `install --update`");if(r==="--delivery"){let o=e[n+1];(o==="npx"||o==="binary"||o==="local")&&(t.delivery=o,n+=1);continue}if(r==="--force"){t.force=!0;continue}if(r==="--no-claude"){t.skipClaude=!0;continue}if(r==="--no-cursor"){t.skipCursor=!0;continue}if(r==="--no-codex"){t.skipCodex=!0;continue}}return t}function Fo(e=process.execPath){return jo(e)?"binary":"npx"}function Xc(){return O(ne(),".ev-ai","agent-hook")}function Zc(e=ne()){return O(e,".ev-ai","agent-hook",sn)}function Qc(){let e=Pn(Wc(import.meta.url)),t=O(e,"hook.mjs");return ce(t)?t:O(e,"..","dist","hook.mjs")}function jo(e=process.execPath){return Gc(e)===ie}function $o(e,t){let n=Uo(To(e),To(t));return!n.startsWith("..")&&!zc(n)}function Et(e){return e.split(Jc).join("/")}function el(e){return`node "$(git rev-parse --show-toplevel)/${Et(e)}"`}function tl(e){return`"$(git rev-parse --show-toplevel)/${Et(e)}"`}function nl(e){return O(e,an)}function Ko(e,t){let n=nl(e);wn(Pn(n),{recursive:!0}),Lo(t,n,{force:!0});try{No(n,493)}catch{}return n}function rl(e){let t=O(Xc(),"current");try{yt(t,{recursive:!0,force:!0})}catch{}Kc(e,t,process.platform==="win32"?"junction":"dir")}function Bo(e,t=ee,n=ne()){let r=O(n,".ev-ai","agent-hook",t),o=O(r,ie);wn(r,{recursive:!0}),Lo(e,o,{force:!0});try{No(o,493)}catch{}return rl(r),O(n,".ev-ai","agent-hook",sn)}function Go(e){let t=On();if(!t)return;let n=[O(e,vn(t)),O(e,"packages","agent-hook",vn(t))];for(let r of n)if(ce(r)&&$o(e,r))return r}function ol(e=ne()){let t=Zc(e);return ce(t)?t:void 0}function sl(e,t=ne()){let n=ol(t);return n||(jo()?Bo(process.execPath,ee,t):Go(e))}function il(e,t=ne()){let n=Go(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
12
- To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=Bo(n,ee,t),o=Ko(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function Mo(e){let t=[O(e,"packages","agent-hook","dist","hook.mjs"),O(e,Ur)],n=Qc();ce(n)&&$o(e,n)&&t.unshift(n);for(let r of t){if(!ce(r))continue;let o=Et(Uo(e,r));return{command:el(o),hookPath:o,strategy:"dev_mjs"}}}function al(e=dt){return`npx -y --prefer-offline ${e}`}function cl(e,t=ne(),n=Fo()){if(n==="npx")return{command:al(),hookPath:dt,strategy:"npx"};if(n==="local"){let s=Mo(e);if(s)return s;throw new Error("local delivery requires packages/agent-hook/dist/hook.mjs (or node_modules/@ev-ai/agent-hook/dist/hook.mjs) under the git root \u2014 run yarn workspace @ev-ai/agent-hook build first")}let r=sl(e,t);if(r){Ko(e,r);let s=Et(an);return{command:tl(s),hookPath:s,strategy:"project_binary"}}let o=Mo(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
13
- curl -fsSL ${Dr}/install.sh | sh
5
+ var qa=Object.create;var zr=Object.defineProperty;var Xa=Object.getOwnPropertyDescriptor;var Za=Object.getOwnPropertyNames;var Qa=Object.getPrototypeOf,ec=Object.prototype.hasOwnProperty;var un=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var ht=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var tc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Za(t))!ec.call(e,o)&&o!==n&&zr(e,o,{get:()=>t[o],enumerable:!(r=Xa(t,o))||r.enumerable});return e};var Be=(e,t,n)=>(n=e!=null?qa(Qa(e)):{},tc(t||!e||!e.__esModule?zr(n,"default",{value:e,enumerable:!0}):n,e));var zn=ht(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.MCP_MISSING_LAUNCH_SERIALIZED=T.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;T.foldMcpName=Os;T.buildMcpFamilyCanonicalKey=Au;T.launchContainsCredentials=Ou;T.serializeMcpLaunchIdentity=Ps;T.hashMcpLaunchIdentity=Ze;T.projectMcpMissingLaunchIdentity=bu;T.projectMcpLaunchIdentity=wu;T.maskMcpLaunchForDisplay=Mu;T.normalizeMcpToolNames=Nu;var ku=un("node:crypto");T.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";T.MCP_MISSING_LAUNCH_SERIALIZED=`${T.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function ie(e){return e.toLocaleLowerCase("en-US")}function Os(e){return ie(e)}function Au(e){return`interface:${Os(e)}`}var xs=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),xu=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function Ne(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Ou(e){return e.kind==="url"?Pu(e.url):e.kind==="command"?e.arguments.some(t=>xu.test(t)):!1}function Pu(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(xs.has(ie(n)))return!0;return!1}catch{let t=e.split("://",2),n=t.length===2?t[1]:e,r=n.indexOf("@"),o=n.indexOf("/");if(r>0&&(o===-1||r<o))return!0;let s=e.split("?",2)[1];return s===void 0?!1:s.split("&").some(i=>{let a=ie(i.split("=",1)[0]??"");return xs.has(a)})}}function Ps(e){if(e.kind==="url")return[T.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",Ne(ie(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>ie(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[T.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",Ne(ie(e.command)),String(t.length),...t.map(Ne)].join("|")}return[T.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",Ne(e.installationRootExternalKey),Ne(e.sourcePath),Ne(e.nativeKey)].join("|")}function Ze(e){return(0,ku.createHash)("sha256").update(e).digest("hex")}var vu=Ze(T.MCP_MISSING_LAUNCH_SERIALIZED);function bu(){return{kind:"unknown",arguments:[],serialized:T.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:vu}}function wu(e){let t=Ps(e);return e.kind==="url"?{kind:"url",url:ie(e.url),arguments:[],serialized:t,contentHash:Ze(t)}:e.kind==="command"?{kind:"command",command:ie(e.command),arguments:[...e.arguments].map(n=>ie(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:Ze(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:Ze(t)}}var Tu=/^(https?:\/\/)([^/?#]*@)/i;function Mu(e){return e.replace(Tu,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function Nu(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 Jn=ht(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.PACKAGE_FIELD_MAX=void 0;he.npxExecBin=vs;he.packageNameFromSpec=Wn;he.npxPackageSpecs=Ku;he.PACKAGE_FIELD_MAX=128;var Lu=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,Uu=new Set(["-p","--package"]),Du=new Set(["-c","--call"]),Hu=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),Fu=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),ju=/^--no-/;function $u(e){return Fu.has(e)||ju.test(e)}function vs(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}function Wn(e){if(e.length===0||e.length>he.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return Lu.test(n)?n:null}function Ku(e,t){let n=vs(e);if(n===null)return[];let r=[...t];if(n==="npm"){let i=r[0]?.toLowerCase();if(i!=="exec"&&i!=="x")return[];r=r.slice(1)}let o=[],s=null;for(let i=0;i<r.length;i+=1){let a=r[i]??"";if(a==="--"){s=r[i+1]??null;break}if(!a.startsWith("-")){s=a;break}let c=a.indexOf("="),u=c===-1?a:a.slice(0,c);if(Du.has(u))return[];if(Uu.has(u)){let l=c===-1?r[i+1]:a.slice(c+1);l!==void 0&&l.length>0&&o.push(l),c===-1&&(i+=1);continue}if(!(c!==-1||$u(u))){if(Hu.has(u)){i+=1;continue}return[]}}return o.length>0?o.every(i=>Wn(i)!==null)?o:[]:s===null||Wn(s)===null?[]:[s]}});var Ls=ht(Ae=>{"use strict";Object.defineProperty(Ae,"__esModule",{value:!0});Ae.EMPTY_NPM_PUBLISHER=void 0;Ae.isNpmRegistryPublisher=Gu;Ae.classifyMcpProvenance=Qu;var Ts=zn(),Vn=Jn();Ae.EMPTY_NPM_PUBLISHER="npm:";var bs="npm:",Bu=/^[A-Za-z0-9._-]+$/;function Gu(e){return e.startsWith(bs)&&e!==Ae.EMPTY_NPM_PUBLISHER&&Bu.test(e.slice(bs.length))}function ws(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 zu(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 Yn(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function Wu(e){let t=Yn(e),n=zu(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||ws(t)||n!==void 0&&ws(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function Ju(e){let t=Yn(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function Vu(e){let t=Yn(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function Ms(e){let t={kind:"url",url:e};if((0,Ts.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||Wu(n.hostname))return{origin:"UNKNOWN"};let r=Ju(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:Vu(n)}}catch{return{origin:"UNKNOWN"}}}var Ns="mcp-remote";function Yu(e,t){if(e===Ns)return t.find(n=>/^https?:\/\//i.test(n))}function qu(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function Xu(e,t,n){let r=Yu(e,t);return r!==void 0?Ms(r):e===Ns?{origin:"UNKNOWN"}:qu(e,n)}function Zu(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 Qu(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,Ts.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return Ms(t.url);let r=(0,Vn.npxPackageSpecs)(t.command,t.arguments)[0];if(r!==void 0){let o=(0,Vn.packageNameFromSpec)(r);if(o===null)return{origin:"UNKNOWN"};let s=Xu(o,t.arguments,e.publisherName),i=typeof e.packageName=="string"?(0,Vn.packageNameFromSpec)(e.packageName):null;return i!==null&&i===o&&s.packageName!==void 0?{...s,packageName:i,packageKey:i}:s}return Zu(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var Le=ht(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.isNpmRegistryPublisher=h.EMPTY_NPM_PUBLISHER=h.classifyMcpProvenance=h.packageNameFromSpec=h.npxPackageSpecs=h.npxExecBin=h.PACKAGE_FIELD_MAX=h.serializeMcpLaunchIdentity=h.projectMcpMissingLaunchIdentity=h.projectMcpLaunchIdentity=h.normalizeMcpToolNames=h.MCP_MISSING_LAUNCH_SERIALIZED=h.MCP_LAUNCH_IDENTITY_ALGORITHM=h.maskMcpLaunchForDisplay=h.launchContainsCredentials=h.hashMcpLaunchIdentity=h.foldMcpName=h.buildMcpFamilyCanonicalKey=h.ComponentKind=void 0;h.userConfigRootFromPath=ld;h.installationRootExternalKey=ud;h.normalizeRepositoryRelativePath=Us;h.nativeKeyForSkillPath=dd;h.nativeKeyForRulePath=pd;h.nativeKeyForCommandPath=fd;h.serializeComponentIdentity=Hs;h.buildComponentReference=gd;h.validateComponentReference=hd;var ed=un("node:crypto"),td=un("node:path"),nd="cmp1_",rd=/^cmp1_[A-Za-z0-9_-]{43}$/,od=["/skills/","/skills-cursor/"],sd=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,id=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,ad=[".cursor",".claude",".codex"],cd={".claude.json":".claude",".agents":".codex"};h.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function ld(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>ad.includes(o));return n||(t.map(o=>cd[o]).find(o=>o!==void 0)??"unknown")}function ud(e,t){return`runtime-install:${e}/${t}`}function Tt(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Us(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=td.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Tt(n,"sourcePath")}function dd(e){let t=e.replaceAll("\\","/");for(let n of od){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Ds(e,t,n){let r=e.replaceAll("\\","/"),s=t.exec(r)?.[1];if(!s||s.split("/").includes(".."))return null;let i=s.replace(n,"");return i.length>0?i:null}function pd(e){return Ds(e,sd,/\.(mdc|md|rules)$/i)}function fd(e){return Ds(e,id,/\.(md|mdc|toml)$/i)}function md(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Hs(e){let t=[Tt(e.installationRootExternalKey,"installationRootExternalKey"),Tt(e.installableKind,"installableKind"),Us(e.sourcePath),Tt(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(md).join("|")}`,"utf8")}function gd(e){let t=(0,ed.createHash)("sha256").update(Hs(e)).digest("base64url");return`${nd}${t}`}function hd(e){return rd.test(e)}var Y=zn();Object.defineProperty(h,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return Y.buildMcpFamilyCanonicalKey}});Object.defineProperty(h,"foldMcpName",{enumerable:!0,get:function(){return Y.foldMcpName}});Object.defineProperty(h,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return Y.hashMcpLaunchIdentity}});Object.defineProperty(h,"launchContainsCredentials",{enumerable:!0,get:function(){return Y.launchContainsCredentials}});Object.defineProperty(h,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return Y.maskMcpLaunchForDisplay}});Object.defineProperty(h,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return Y.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(h,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return Y.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(h,"normalizeMcpToolNames",{enumerable:!0,get:function(){return Y.normalizeMcpToolNames}});Object.defineProperty(h,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return Y.projectMcpLaunchIdentity}});Object.defineProperty(h,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return Y.projectMcpMissingLaunchIdentity}});Object.defineProperty(h,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return Y.serializeMcpLaunchIdentity}});var Mt=Jn();Object.defineProperty(h,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return Mt.PACKAGE_FIELD_MAX}});Object.defineProperty(h,"npxExecBin",{enumerable:!0,get:function(){return Mt.npxExecBin}});Object.defineProperty(h,"npxPackageSpecs",{enumerable:!0,get:function(){return Mt.npxPackageSpecs}});Object.defineProperty(h,"packageNameFromSpec",{enumerable:!0,get:function(){return Mt.packageNameFromSpec}});var qn=Ls();Object.defineProperty(h,"classifyMcpProvenance",{enumerable:!0,get:function(){return qn.classifyMcpProvenance}});Object.defineProperty(h,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return qn.EMPTY_NPM_PUBLISHER}});Object.defineProperty(h,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return qn.isNpmRegistryPublisher}})});import{realpathSync as wg}from"node:fs";import{resolve as Tg}from"node:path";import{fileURLToPath as Mg,pathToFileURL as Ng}from"node:url";var nc="https://hooks.ev-ai.ai";function _t(e,t=nc){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var St=".claude/ev-ai-runtime-report.json",Wr="config.json",Jr="node_modules/@ev-ai/agent-hook/dist/hook.mjs",q="ev-ai-agent-hook";function rc(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function yt(e){let t=rc(e);return t===q||t===`${q}.exe`}var Vr="https://cdn.ev-ai.ai/agent-hook";var dn=`current/${q}`,pn=`.ev-ai/agent-hook/${q}`,Yr=5e3,qr=5e3,fn=3e3;var mn=3e3,Xr=1500,Zr=4*1024,Qr=32*1024,oc=4*1024,eo=32*1024,Ge=840*60*1e3,ne="1.1.5",Et=`@ev-ai/agent-hook@${ne}`,to="ev-ai runtime report",no=["claude","cursor","codex"];import{chmodSync as Wo,cpSync as Jo,existsSync as ue,mkdirSync as Un,readFileSync as fl,rmSync as Ot,symlinkSync as ml,writeFileSync as gl}from"node:fs";import{homedir as oe}from"node:os";import{dirname as Dn,isAbsolute as hl,join as P,relative as Vo,resolve as Go,sep as _l}from"node:path";import{fileURLToPath as Sl}from"node:url";var sc=new Set(["localhost","127.0.0.1","[::1]","::1"]),ro=/^[A-Za-z0-9._~-]+$/;function oo(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function Rt(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?sc.has(t.hostname):!1}catch{return!1}}function ze(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Rt(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=ic(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!ro.test(n))return`org token must match ${ro.source} (got: ${n})`;if(oo(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(oo(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function We(e){return new URL(e).toString()}function ic(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function gn(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function so(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?_t(t):""}import{existsSync as ac,readdirSync as io}from"node:fs";import{homedir as Ct}from"node:os";import{join as K}from"node:path";function ao(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return K(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function hn(e=process.platform){let t=ao(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!ac(r))return n;let o=io(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function _n(e=process.platform,t=Ct()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:hn(e)}}function cc(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 lc(e=process.platform,t=Ct()){let n=[K(cc(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of io(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function uc(e=process.platform,t=Ct()){let n=e==="win32"?K(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[K(n,"requirements.toml")];return e!=="win32"&&r.push(K(n,"managed_config.toml")),r.push(K(t,".codex","managed_config.toml"),K(n,"config.toml")),r}function It(e,t=process.platform,n=Ct()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=_n(t,n);return[r,...o]}case"cursor":return lc(t,n);default:return uc(t,n)}}import{createHash as Io,randomBytes as Mc}from"node:crypto";import{existsSync as ko,mkdirSync as On,readFileSync as Ao,unlinkSync as xo,writeFileSync as Oo}from"node:fs";import{homedir as Pn}from"node:os";import{dirname as At,join as vn,resolve as Nc}from"node:path";var dc=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),pc=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function G(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||pc.has(n)||r.includes("[bot]")||dc.has(r))return!0;if(r.endsWith("@users.noreply.github.com")){let o=r.slice(0,r.indexOf("@")),s=o.includes("+")?o.slice(o.indexOf("+")+1):o;if(s.endsWith("bot")||s.includes("[bot]"))return!0}return!1}import{existsSync as Ec,readFileSync as Rc}from"node:fs";import{hostname as ho,userInfo as Cc}from"node:os";import{randomBytes as fc}from"node:crypto";import{existsSync as yn,mkdirSync as mc,readdirSync as gc,readFileSync as hc,renameSync as co,statSync as po,unlinkSync as lo,writeFileSync as _c}from"node:fs";import{basename as Sc,dirname as uo,join as fo,relative as yc}from"node:path";function d(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
6
+ `)}function X(e,t){mc(uo(e),{recursive:!0});let n=fo(uo(e),`.${Sc(e)}.${process.pid}.${fc(4).toString("hex")}.tmp`);try{_c(n,t,"utf8");try{co(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){lo(e),co(n,e);return}throw r}}catch(r){try{lo(n)}catch{}throw r}}function kt(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function mo(){process.stdout.write('{"continue":true}')}function C(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function Je(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function En(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function V(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,u=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:u,spawnFailed:u===void 0}}}async function M(e,t,n=3e3,r={}){let o=await V(e,t,n,r);return o.ok?o.stdout:""}async function Rn(e=process.cwd()){let t=await V("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(C("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;d(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=C("CURSOR_PROJECT_DIR")??C("CLAUDE_PROJECT_DIR");if(n&&yn(n)){let r=await V("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function re(e=process.cwd()){return(await Rn(e)).root}function j(e,t){try{return JSON.parse(e)}catch{return t}}var Sn=new Map;function U(e,t){let n=Sn.get(e);if(n!==void 0)return n;try{let r=j(hc(e,"utf8"),t);return Sn.set(e,r),r}catch{return Sn.set(e,t),t}}function ye(e){return typeof e=="string"?e:""}function Ee(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function g(e,t){let n=Ee(e,t);return typeof n=="string"?n:""}var le=500;function go(e,t=2){if(!yn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=gc(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let u=fo(s,c.name);if(c.isDirectory()){o(u,i+1);continue}if(c.isFile()){try{n.push({name:yc(e,u),size:po(u).size})}catch{continue}if(n.length>=le){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Cn(e){return yn(e)?{present:!0,size:po(e).size}:{present:!1,size:0}}function be(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function In(e=process.env){return be(b("CURSOR_SANDBOX",e))}var Ic=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function kc(e){return Ic.some(t=>!!b(t,e))}function Ac(e){if(b("KUBERNETES_SERVICE_HOST",e)||be(b("REMOTE_CONTAINERS",e))||be(b("DEVCONTAINER",e)))return!0;try{if(Ec("/.dockerenv")||Rc("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function _o(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!b(t,e))}function xc(e,t=process.platform){return _o(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!b(n,e)):!1}function Oc(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Pc(e){return e==="linux"}function b(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return C(e)}function vc(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!bc(b("CURSOR_VERSION",n))}function bc(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function kn(e){if(Oc(e.sessionId))return!0;let t=e.hostname??ho(),n=e.osUser??So(e.env);return vc(t,n,e.env)}function wc(e){return be(b("CURSOR_AGENT",e.env))?!0:kn(e)}function Tc(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(b("TERM",e)??b("TERM_PROGRAM",e))||(b("SSH_TTY",e)??b("SSH_CONNECTION",e))||(b("__CFBundleIdentifier",e)??b("XPC_SERVICE_NAME",e))||_o(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!b(t,e))||b("SESSIONNAME",e))}function Ve(e={}){let t=e.env;if(b("GITHUB_ACTIONS",t))return"github_actions";if(be(b("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!xc(t,n)&&wc(e)&&(be(b("CURSOR_AGENT",t))||Pc(n)))return"cursor_cloud";if(b("CODESPACES",t)||b("CODESPACE_NAME",t))return"codespaces";if(b("GITLAB_CI",t))return"gitlab_ci";if(kc(t))return"managed";let r=b("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Ac(t)?"container":Tc(t)?"interactive":"unknown"}async function An(){return await M("systemd-detect-virt",[],1e3)}function So(e=process.env,t=Cc){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function xn(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await M("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),i=s("/etc/os-release","utf8"),a=i.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=i.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=a??c??""}catch{t=await M("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await M("uname",["-r"],1e3))}else t=await M("ver",[],1e3);let n=So(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await M("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function Ye(){return ho()}var Lc="installation.json",Uc="cloud-bootstrap.lock",Dc=6e4;function Po(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function Re(e=Pn()){return vn(e,".ev-ai","agent-hook")}function Hc(e=Pn()){return vn(Re(e),Lc)}function vo(e){return vn(At(e),Uc)}function bo(){return Mc(8).toString("hex")}function we(e){return Io("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 wo(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Fc(e=process.env){let t=I(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!wo(t)){d(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function To(e,t){return e&&wo(e)?e:(e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Fc(t))}function jc(e){return/^[0-9a-f]{16}$/.test(e)}function $c(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 we(`github_actions|${t}|${n}`)}if(I(e.CODESPACES)||I(e.CODESPACE_NAME)){let t=I(e.CODESPACE_NAME);if(t)return we(`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 we(`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 we(`gitlab|${t}|${n}`)}return null}var Kc="cursoragent@cursor.com";function Bc(e){let t=I(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Kc?null:t}function Gc(e,t){return I(e.CURSOR_PROJECT_DIR)??I(e.CLAUDE_PROJECT_DIR)??t}function zc(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Wc(e){let t=await M("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?zc(t):e}async function Jc(e){let t=I(await M("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!G(null,t))return t;let n=I(await M("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!G(null,n)?n:null}function Vc(e,t){let n=Gc(e,t);return n?we(`cursor_cloud|${n}|${Bc(e)??""}`):null}async function Yc(e,t){let n=I(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Wc(n),o=await Jc(n);return we(`claude_remote|${r}|${o??""}`)}function yo(e,t){let n=To(e,t);if(n)return n;let r=$c(t);return r||bo()}async function qc(e){let n=await M("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Nc(e);return Io("sha256").update(n).digest("hex").slice(0,16)}function Xc(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 Zc(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Xc(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function Ce(e){if(ko(e))try{return Zc(Ao(e,"utf8"))}catch{}}function bn(e){return Ce(e)}function Mo(e,t,n){let r=Ce(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{X(e,`${JSON.stringify(o,null,2)}
7
+ `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: operator identity cache write failed open: ${i}`)}}function No(e,t=Date.now()){if(!e)return!0;if(Ce(e)?.operator_identity_hash)return!1;let n=vo(e);try{if(ko(n)){let r=Number.NaN;try{r=Number(Ao(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<Dc)return!1;try{xo(n)}catch{}}}catch{}try{return On(At(n),{recursive:!0}),Oo(n,`${t}
8
+ `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(Ho(r))return!1;let o=r instanceof Error?r.message:String(r);return d(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function Lo(e){if(e)try{xo(vo(e))}catch{}}function Uo(e,t){let r=Ce(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Do(e,t,n){if(!n)return;let r=Ce(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)}
9
+ `)}catch(s){let i=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${i}`)}}function Ho(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Qc(e,t){On(At(e),{recursive:!0}),Oo(e,`${JSON.stringify(t,null,2)}
10
+ `,{encoding:"utf8",flag:"wx"})}function Eo(e,t){try{return Qc(e,t),t}catch(n){if(!Ho(n))throw n;return Ce(e)}}function Ro(e,t){On(At(e),{recursive:!0}),X(e,`${JSON.stringify(t,null,2)}
11
+ `)}function Co(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function xt(e,t={}){let n=t.home??Pn(),r=t.env??process.env,o=await qc(e),s=Hc(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=Ve(i),c=To(t.overrideId,r),u=a==="cursor_cloud"&&kn(i)?Vc(r,e):a==="claude_remote"?await Yc(r,e):null,l=Ce(s);if(l){let S=l;if(c&&c===l.installation_id&&l.pinned!==!0&&(S={...l,pinned:!0},Ro(s,S)),!!u&&u!==S.installation_id&&!c&&S.pinned!==!0&&jc(S.installation_id)&&u){let E={installation_id:u,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return Ro(s,E),{installationId:u,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let p=c??u??yo(void 0,r),m=Eo(s,Co(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let f=c??u??yo(void 0,r),_=Eo(s,Co(f===p?bo():f,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as wn,readFileSync as el}from"node:fs";import{homedir as tl}from"node:os";import{dirname as nl,isAbsolute as rl,join as jo,relative as ol}from"node:path";var Tn=[St,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];function sl(e=tl()){return jo(e,".ev-ai",Wr)}function Fo(e){for(let t of Tn){let n=jo(e,t);if(wn(n))return n}}async function il(e=process.cwd(),t){let n=C("EV_AI_HOOK_MANIFEST");if(n&&wn(n))return n;let r=sl();if(wn(r))return r;let o=t??await re(e);return Fo(o)??Fo(e)}async function al(e,t){let n=t??await re(nl(e)),r=ol(n,e);if(r.startsWith("..")||rl(r))return!1;let o=await V("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(d(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function cl(e){let t=el(e,"utf8");return j(t,{})}function ll(){return{schema_version:2,mcp_servers:[]}}async function $o(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Rn(e),o=await il(e,n),s=o?cl(o):ll();delete s.installation_id;let i=o?await al(o,n):!1;s.capture_hook_input==="full"&&o&&i&&(d(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${o}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete s.capture_hook_input);let{installationId:a,storePath:c,repoKey:u}=await xt(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:a,installationStorePath:c,repoKey:u,collectorUrl:so(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function Ko(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var ul=["darwin-arm64","darwin-x64","linux-arm64","linux-x64","windows-x64","windows-arm64"];function dl(e){return e==="windows-x64"||e==="windows-arm64"}function Mn(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0;if(e==="win32")return t==="x64"?"windows-x64":t==="arm64"?"windows-arm64":void 0}function Bo(e=process.platform,t=process.arch){let n=Mn(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${ul.join(", ")}.`);return n}function pl(e){return dl(e)?`${q}.exe`:q}function Nn(e){return`compile-out/bin/${e}/${pl(e)}`}function yl(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=ze(n);if(r)throw new Error(`collector URL rejected: ${r}`);return We(n)}function El(e){let t=e.collectorUrl?.trim();if(!t)return;let n=ze(t);if(n)throw new Error(`collector URL rejected: ${n}`);return We(t)}function Rl(e){return yl(e,"install")}function Yo(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url")}return t}function qo(e){let t={};for(let n=0;n<e.length;n++){let r=e[n];if(r==="--url"){let o=e[n+1];o&&!o.startsWith("--")&&(t.collectorUrl=o,n+=1);continue}if(r==="--collector-url")throw new Error("--collector-url was renamed to --url");if(r==="--update")throw new Error("--update was removed; use the `update` command instead of `install --update`");if(r==="--delivery"){let o=e[n+1];(o==="npx"||o==="binary"||o==="local")&&(t.delivery=o,n+=1);continue}if(r==="--force"){t.force=!0;continue}if(r==="--no-claude"){t.skipClaude=!0;continue}if(r==="--no-cursor"){t.skipCursor=!0;continue}if(r==="--no-codex"){t.skipCodex=!0;continue}}return t}function Xo(e=process.execPath){return Zo(e)?"binary":"npx"}function Cl(){return P(oe(),".ev-ai","agent-hook")}function Il(e=oe()){return P(e,".ev-ai","agent-hook",dn)}function kl(){let e=Dn(Sl(import.meta.url)),t=P(e,"hook.mjs");return ue(t)?t:P(e,"..","dist","hook.mjs")}function Zo(e=process.execPath){return yt(e)}function Qo(e,t){let n=Vo(Go(e),Go(t));return!n.startsWith("..")&&!hl(n)}function Pt(e){return e.split(_l).join("/")}function Al(e){return`node "$(git rev-parse --show-toplevel)/${Pt(e)}"`}function xl(e){return`"$(git rev-parse --show-toplevel)/${Pt(e)}"`}function Ol(e){return P(e,pn)}function es(e,t){let n=Ol(e);Un(Dn(n),{recursive:!0}),Jo(t,n,{force:!0});try{Wo(n,493)}catch{}return n}function Pl(e){let t=P(Cl(),"current");try{Ot(t,{recursive:!0,force:!0})}catch{}ml(e,t,process.platform==="win32"?"junction":"dir")}function ts(e,t=ne,n=oe()){let r=P(n,".ev-ai","agent-hook",t),o=P(r,q);Un(r,{recursive:!0}),Jo(e,o,{force:!0});try{Wo(o,493)}catch{}return Pl(r),P(n,".ev-ai","agent-hook",dn)}function ns(e){let t=Mn();if(!t)return;let n=[P(e,Nn(t)),P(e,"packages","agent-hook",Nn(t))];for(let r of n)if(ue(r)&&Qo(e,r))return r}function vl(e=oe()){let t=Il(e);return ue(t)?t:void 0}function bl(e,t=oe()){let n=vl(t);return n||(Zo()?ts(process.execPath,ne,t):ns(e))}function wl(e,t=oe()){let n=ns(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
12
+ To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=ts(n,ne,t),o=es(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function zo(e){let t=[P(e,"packages","agent-hook","dist","hook.mjs"),P(e,Jr)],n=kl();ue(n)&&Qo(e,n)&&t.unshift(n);for(let r of t){if(!ue(r))continue;let o=Pt(Vo(e,r));return{command:Al(o),hookPath:o,strategy:"dev_mjs"}}}function Tl(e=Et){return`npx -y --prefer-offline ${e}`}function Ml(e,t=oe(),n=Xo()){if(n==="npx")return{command:Tl(),hookPath:Et,strategy:"npx"};if(n==="local"){let s=zo(e);if(s)return s;throw new Error("local delivery requires packages/agent-hook/dist/hook.mjs (or node_modules/@ev-ai/agent-hook/dist/hook.mjs) under the git root \u2014 run yarn workspace @ev-ai/agent-hook build first")}let r=bl(e,t);if(r){es(e,r);let s=Pt(pn);return{command:xl(s),hookPath:s,strategy:"project_binary"}}let o=zo(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
13
+ curl -fsSL ${Vr}/install.sh | sh
14
14
  Or use npx delivery:
15
- npx ${dt} install`)}function zo(e){return typeof e!="string"?!1:e.includes("@ev-ai/agent-hook")||e.includes("agent-hook/dist/hook")||e.includes(".ev-ai/agent-hook")||e.includes(ie)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function Tn(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function le(e,t){wn(Pn(e),{recursive:!0}),Bc(e,`${JSON.stringify(t,null,2)}
16
- `,"utf8")}function re(e){if(ce(e))try{return JSON.parse($c(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function ll(e,t){let n=wo(t.collectorUrl),r={...e,schema_version:e?.schema_version??n.schema_version};return t.collectorUrl!==void 0?r.collector_url=t.collectorUrl:r.collector_url=e?.collector_url??n.collector_url,delete r.repo_ingest_token,delete r.installation_id,r.mcp_servers??=n.mcp_servers,r}function ul(e){return(e.schema_version??2)===2&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.repo_ingest_token===void 0}function Jo(e,t){let n=O(e,ut),r=re(n),o=ll(r,t);return t.collectorUrl!==void 0||ce(n)||!ul(o)?(le(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function bn(e){if(e===null||typeof e!="object")return!1;let t=e,n=String(t.CLAUDE_CODE_ENABLE_TELEMETRY??"").toLowerCase();return n==="1"||n==="true"?!0:Object.keys(t).some(r=>r.startsWith("OTEL_"))}function dl(e){if(bn(process.env))return!0;let t=ne();return[...dn(),O(t,".claude","settings.json"),O(t,".claude","remote-settings.json"),O(e,".claude","settings.json"),O(e,".claude","settings.local.json")].some(r=>{try{let o=re(r);return o?bn(o.env):!1}catch{return!1}})}function pl(e){try{let t=re(O(e,".claude","settings.json"));return t?bn(t.env):!1}catch{return!1}}function Wo(e){return Array.isArray(e)?e:[]}function Rt(e){let t=[],n=r=>!!r&&typeof r=="object"&&zo(r.command);for(let r of Wo(e)){if(!r||typeof r!="object"){t.push(r);continue}let o=Array.isArray(r.hooks)?r.hooks:[],s=o.filter(i=>!n(i));if(!(s.length===0&&o.some(n))){if(s.length!==o.length){t.push({...r,hooks:s});continue}t.push(r)}}return t}function Vo(e,t){return[...Rt(e),...t]}function Mn(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!zo(t.command)):[]}function fl(e,t){return[...Mn(e),{command:t}]}function ml(e){let t=()=>({hooks:[{type:"command",command:e}]});return{SessionStart:[t()],UserPromptExpansion:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function gl(e){let t={type:"command",command:e,statusMessage:Gr},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var hl=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","beforeReadFile","beforeMCPExecution","subagentStart","subagentStop","stop"],_l=["afterShellExecution","afterFileEdit"];function Sl(e,t=_l){let n={...e};for(let r of t){if(!(r in n))continue;let o=Mn(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function yl(e,t,n={}){let r=O(e,".claude/settings.json"),o=Tn(t,"claude"),s=re(r)??{};if(dl(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let p of Object.keys(u))u[p]=Rt(u[p]),Wo(u[p]).length===0&&delete u[p];Object.keys(u).length===0?delete s.hooks:s.hooks=u,le(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=ml(o),l={...a};for(let[u,p]of Object.entries(c))l[u]=Vo(a[u],p);return s.hooks=l,le(r,s),!0}function El(e,t){let n=O(e,".cursor/hooks.json"),r=Tn(t,"cursor"),o=re(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=Sl({...s});for(let a of hl)i[a]=fl(i[a],r);le(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function Rl(e,t){let n=O(e,".codex/hooks.json"),r=Tn(t,"codex"),o=re(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=gl(r),a={...s};for(let[c,l]of Object.entries(i))a[c]=Vo(s[c],l);le(n,{...o,hooks:a})}function Cl(e){let t=O(e,".claude/settings.json"),n=re(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let i=r[s],a=Rt(i);JSON.stringify(i)!==JSON.stringify(a)&&(o=!0),a.length===0?delete r[s]:r[s]=a}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,le(t,n),d(`Removed ev-ai hooks from ${t}`))}function kl(e){let t=O(e,".cursor/hooks.json"),n=re(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=Mn(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks"&&a!=="version").length===0){yt(t,{force:!0}),d(`Removed ${t}`);return}le(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function Il(e){let t=O(e,".codex/hooks.json"),n=re(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=Rt(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks").length===0){yt(t,{force:!0}),d(`Removed ${t}`);return}le(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function Nn(e=process.platform,t=process.arch,n={}){if(e==="win32")throw new Error("Windows install is not supported yet. Use macOS/Linux, or wait for phase-2 native commands.");(n.requireBinaryArch??!0)&&Po(e,t)}async function Yo(e={}){let t=qc(e);e.collectorUrl=t;let n=e.skipClaude===!0,r=e.skipCursor===!0,o=e.skipCodex===!0;if(n&&r&&o)throw new Error("at least one runner must be wired; refuse --no-claude --no-cursor --no-codex together");let s=e.delivery??Fo();Nn(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await te(i),{command:c,hookPath:l,strategy:u}=cl(a,ne(),s),{installationId:p,storePath:m}=await _t(a,{overrideId:e.installationId}),{manifestPath:f,wrote:_}=Jo(a,e),S=[];return n?d("Skipped Claude hook \u2014 --no-claude"):yl(a,c,{force:e.force})?(S.push("Claude"),e.force&&pl(a)&&d("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):d("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?d("Skipped Cursor hook \u2014 --no-cursor"):(El(a,c),S.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(Rl(a,c),S.push("Codex")),d(`Installed hook (${u}) at ${l}`),d(`Installation identity ${p} at ${m}`),_&&f?d(`Shared manifest written to ${f}`):d("Using package default collector config (no shared manifest file needed)"),d(S.length>0?`Wired ${S.join(", ")} hooks in ${a} (commands include --runner)`:`No runner hooks wired in ${a} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),u==="npx"?d("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):u==="project_binary"?d("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):u==="dev_mjs"&&d("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&f&&e.collectorUrl&&d("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:a,hookPath:l,manifestPath:f,installationStorePath:m,strategy:u}}async function qo(e=process.cwd()){Nn(process.platform,process.arch,{requireBinaryArch:!0});let t=await te(e),{projectPath:n,globalPath:r}=il(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function Xo(e={}){let t=Yc(e);e.collectorUrl=t,Nn(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await te(n),{manifestPath:o,wrote:s}=Jo(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?d(`Wrote ${o}`):t===void 0&&d("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),d("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function Zo(e){for(let t of[()=>Cl(e),()=>kl(e),()=>Il(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function Qo(e=process.cwd()){let t=await te(e);return Zo(t),d("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),d("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function es(e=process.cwd()){let t=await te(e);Zo(t);for(let n of St){let r=O(t,n);if(ce(r))try{yt(r,{force:!0}),d(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);d(`WARN: uninstall could not remove ${r}: ${s}`)}}}import{createHash as Qu}from"node:crypto";import{existsSync as ed,mkdirSync as td,readdirSync as nd,readFileSync as Ks,unlinkSync as Bs,writeFileSync as rd}from"node:fs";import{homedir as Gs}from"node:os";import{join as Vn}from"node:path";import{existsSync as Ll}from"node:fs";import{existsSync as Al}from"node:fs";import{homedir as ns}from"node:os";import{join as xl}from"node:path";function rs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Ol={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 ts(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function vl(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:ts(n.mcpJson,t.mcpJson),mcpToml:ts(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function os(e){return Object.fromEntries(Object.entries(Ol).map(([t,n])=>[t,vl(n,n[e])]))}var be=os("homeOnly"),de=os("projectOnly");function bl(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function wl(e,t){return bl(e).some(n=>Al(xl(t,n)))}function ss(e,t){for(let n of e)if(wl(n,t))return!0;return!1}function ue(e){return[...new Set(e)]}function pe(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 Pl(e,t=ns(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...mt(o.managed,n,t));return ue(r)}var fe=pe(Object.values(be));function is(e=ns(),t=process.platform){return Pl(Object.values(be),e,t)}import{existsSync as Tl}from"node:fs";import{resolve as Ln}from"node:path";function z(e){return Ln(e).replaceAll("\\","/").replace(/\/$/,"")}function Re(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function Ct(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 Ml=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function ze(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Ml.test(t)?null:t}function we(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=z(o);n.has(s)||(n.add(s),r.push(s))}return r}function Nl(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function q(e,t,n,r=Tl){for(let o of e)for(let s of t){let i=z(Ln(o,s)),a=Ln(o,s,n).replaceAll("\\","/");if(Nl(i,a)&&r(a))return a}return null}var cs=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,ls=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Ul=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,as=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"]),Dl=/^[a-z][a-z0-9-]{1,63}$/,Hl=[".cursor/skills",".claude/skills",".agents/skills"],Fl=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],jl=Re(Hl,pe(Object.values(de)).skills),$l=Re(Fl,pe(Object.values(be)).skills),Kl=new Set(["read","read_file","view"]),Bl=new Set(["bash","shell","zsh"]);function Un(e){let t=e.replace(/\\/g,"/");return cs.exec(t)?.[1]??null}function Gl(e){let t=e.replace(/\\/g,"/"),r=ls.exec(t)?.[1];return r?r.toLowerCase():null}function zl(e){return Un(e)??Gl(e)}function Jl(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 kt(e){return typeof e=="string"?kt(F(e,null)):!e||typeof e!="object"?null:Jl(e)}function us(e){if(typeof e=="string")return us(F(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Dn(e){let t=us(e.tool_input);if(t)return t;let n=he(e.command);return n.length>0?n:null}function Wl(e){let t=e.replace(/\\/g,"/"),n=cs.exec(t);if(n?.[1])return n[1];let o=ls.exec(t)?.[1];return o?o.toLowerCase():null}function Vl(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Hn(e){let t=kt(e.tool_input)??he(e.file_path);return t.length>0?t:null}function Je(e,t,n){let r=Vl(e).toLowerCase();if(Kl.has(r)){let o=Hn(e);return o?t(o):null}if(Bl.has(r)){let o=Dn(e);return o?n(o):null}return null}function ds(e){return Je(e,zl,Wl)}function Yl(e){let t=new Set,n=[];for(let r of e.matchAll(Ul)){let o=r[1]?.toLowerCase();!o||t.has(o)||ql(o)||(t.add(o),n.push(o))}return n}function ql(e){let t=e.split("/")[0];return as.has(e)||t!==void 0&&as.has(t)}function ps(e){let t=e.skillId.toLowerCase();if(!Dl.test(t))return null;let n=e.exists??Ll,r=`${t}/SKILL.md`,o=q(we(e.launchCwd,e.gitRoot),jl,r,n);return o!==null?o:e.home?q([z(e.home)],$l,r,n):null}function Xl(e){return he(e.prompt)}function fs(e){let t=g(e,"command_name");if(t){let r=g(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Xl(e);return n?Yl(n):[]}var Fn=on(xt(),1);import{existsSync as Iu}from"node:fs";var ke={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function We(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function ku(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return We(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return We(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?We(o[1]):We(t)}async function Ve(e=process.cwd()){let t=await V("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([V("git",["remote","get-url","origin"],2e3,{cwd:e}),V("git",["branch","--show-current"],2e3,{cwd:e}),V("git",["rev-parse","HEAD"],2e3,{cwd:e}),V("git",["status","--porcelain"],2e3,{cwd:e})]),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 Es(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=ke[n];if(!a)return"";let c=_o(n,e.scope_path,i);if(s){let _=Ao(s,c);if(_)return _}let l=o??await Ve(r),u=l?.remote?ku(l.remote):"";if(u||(u=We(process.env.GITHUB_REPOSITORY??"")),!u)return"";let p=e.scope_path??"",m=p?`${p}/`:"",f=`${u}:${m}${a}`;return s&&xo(s,c,f),f}var Au=[".cursor/rules",".claude/rules",".codex/rules"],xu=pe(Object.values(de)).rules;function Ou(e){return Re(Ct(e?ke[e]:void 0,Au),xu)}var vu=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function Rs(e){let t=ze(e.relativePath);if(!t)return null;let n=e.exists??Iu,r=we(e.launchCwd,e.gitRoot),o=Ou(e.runnerPlatform),s=q(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=q(r,["."],t,n);if(i!==null)return i}return e.home?q([z(e.home)],o,t,n):null}function bu(e){let t=e.replace(/\\/g,"/"),r=vu.exec(t)?.[1];return r?(0,Fn.nativeKeyForRulePath)(r):null}function Cs(e){return Je(e,Fn.nativeKeyForRulePath,bu)}function ks(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function Is(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=ze(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var jn=on(xt(),1);import{existsSync as wu}from"node:fs";var Pu=[".cursor/commands",".claude/commands",".codex/prompts"],Tu=pe(Object.values(de)).commands;function Mu(e){return Re(Ct(e?ke[e]:void 0,Pu),Tu)}var Nu=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function As(e){let t=ze(e.commandId);if(!t)return null;let n=e.exists??wu,r=`${t}.md`,o=Mu(e.runnerPlatform),s=q(we(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?q([z(e.home)],o,r,n):null}function Lu(e){let t=e.replace(/\\/g,"/"),r=Nu.exec(t)?.[1];return r?(0,jn.nativeKeyForCommandPath)(r):null}function xs(e){return Je(e,jn.nativeKeyForCommandPath,Lu)}import{existsSync as vs}from"node:fs";import{homedir as bs}from"node:os";import{join as Ye,resolve as $n,sep as Os}from"node:path";function Kn(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Bn(e,t){let n=t.toLowerCase();return Kn(e).some(r=>r.toLowerCase()===n)}function Ot(e,t,n){if(!vs(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 Uu(e,t,n){if(!vs(e))return;let r=L(e,{}),o=$n(t),s=null;for(let a of Object.keys(r.projects??{})){let c=$n(a);(o===c||o.startsWith(c.endsWith(Os)?c:c+Os))&&(s===null||c.length>$n(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 ws(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"?(Ot(Ye(r,".claude.json"),{source:"claude_json_user"},o),Uu(Ye(r,".claude.json"),t,o)):n==="cursor"&&Ot(Ye(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Ot(Ye(t,".mcp.json"),{source:"mcp_json"},o),Ot(Ye(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function Gn(e,t=process.cwd(),n="claude",r=bs()){return[...ws(e,t,n,r).values()].map(o=>o.declared)}function Ps(e,t,n=process.cwd(),r="claude",o=bs()){let s=ws(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Bn(a,e))return c.config??null;return null}function zn(e){return e!==void 0&&zr.includes(e)}function vt(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function bt(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=vt(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=vt(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=vt(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=vt(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:zn(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Jn(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=lt(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=je(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return $e(n)}function Ts(e,t){if(g(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Du(){return!!(R("CURSOR_VERSION")??R("CURSOR_PROJECT_DIR"))}function Wn(e,t,n){return e!=="claude"&&e!=="codex"?!1:Ts(t,n)?!0:Du()}function qe(e,t,n,r){if(Ts(e,t))return"cursor";if(zn(r))return r;let o=g(e,"conversation_id"),s=g(e,"turn_id"),i=g(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),zn(n)&&(c=n),c}function wt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Hu(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 Ms(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Ns(e,t,n){let r=g(e,"session_id")||g(e,"conversation_id"),o=g(e,"prompt.id")||g(e,"prompt_id")||g(e,"generation_id")||g(e,"turn_id"),s=g(e,"hook_event_name")||g(e,"event"),i=g(e,"source"),a=qe(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Fu=["session_start","session_end","tool_invoked","skill_invoked"];function ju(e){return Fu.includes(e)}function Ls(e,t){return e&&ju(e)?e:Hu(t.toLowerCase())}var $u={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Us(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ds(e,t=""){let n=g(e,"tool_name")||g(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Us(n)&&(n=`MCP:${n}`):n=$u[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?he(o.skill)||he(o.skill_name):"")||g(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=ds(a);let c=Cs(a),l=xs(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var Ku=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Hs(e){for(let t of["subagent_type","agent_type"]){let n=g(e,t);if(n&&Ku.test(n))return n}return null}function Fs(e){let t=_e(e,"duration_ms");if(typeof t=="number")return t;let n=_e(e,"duration");return typeof n=="number"?n:null}var Bu="error",Gu="interrupted",zu="permission_denied",Ju=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Xe(e){return Ju.test(e)?e:null}function Wu(e){for(let t of["failure_type","error_type"]){let n=Xe(g(e,t));if(n)return n}return null}function js(e,t){return _e(e,"is_interrupt")===!0?Gu:t.toLowerCase()==="permissiondenied"?zu:Wu(e)??Bu}function Vu(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 Yu(e,t){let n=null;for(let r of t)!r||!Bn(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function qu(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of Kn(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:Yu(o[1],t)??o[1],mcpTool:o[2]}}function Xu(e,t){if(/^mcp__/i.test(e))return qu(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:Vu(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function Zu(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function $s(e,t=[],n=""){let r=e?Xu(e,t):{mcpServer:null,mcpTool:null},o=Xe(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Us(e)&&(s=e),s&&(s=Zu(s,o)),{mcpServer:o,mcpTool:s}}var zs=3e4,od="claims",sd=!0,id=100,ad=new Set(["sessionstart","sessionend","stopfailure"]),cd=["tool_name","tool","command","file_path","url"];function ld(e=Gs()){return Vn(Se(e),od)}function Js(e){let t=e.split(`
17
- `,1)[0]??"";return Number(t.trim())}function Ws(e){return Qu("sha256").update(e).digest("hex").slice(0,32)}function ud(e){let t=[];for(let n of cd){let r=g(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":Ws(t.join("\0"))}function dd(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=ad.has(n);if(!a&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return Ws(`${l}|${t}|${n}|${r}|${o}|${i}|${s}`)}function pd(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function fd(e,t){return Vn(e,t)}function md(e,t=Date.now()){let n;try{n=nd(e)}catch{return}let r=0;for(let o of n){if(r>=id)break;r+=1;let s=Vn(e,o),i=Number.NaN;try{i=Js(Ks(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<zs))try{Bs(s)}catch{}}}function gd(e,t,n=Date.now()){let r=fd(t,e);try{if(ed(r)){let o=Number.NaN;try{o=Js(Ks(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<zs)return!1;try{Bs(r)}catch{}}}catch{}try{td(t,{recursive:!0}),rd(r,`${n}
18
- `,{encoding:"utf8",flag:"wx"})}catch(o){if(pd(o))return!1;let s=o instanceof Error?o.message:String(o);return d(`WARN: event claim failed open: ${s}`),!0}return md(t,n),!0}function hd(e,t,n){let r=g(e,"session_id")||g(e,"conversation_id"),o=g(e,"prompt.id")||g(e,"prompt_id")||g(e,"generation_id")||g(e,"turn_id"),s=g(e,"tool_use_id"),i=g(e,"subagent_id")||g(e,"agent_id"),a=qe(e,t,void 0,n),c=ud(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function Vs(e,t,n,r=Gs(),o=Date.now()){if(!sd)return!0;let s=dd(hd(e,t,n));if(!s)return!0;let i=gd(s,ld(r),o);return!i&&R("EV_AI_HOOK_DEBUG")&&d(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{realpathSync as Om}from"node:fs";import{homedir as vm}from"node:os";var I=on(xt(),1);import{existsSync as _d,readFileSync as Sd}from"node:fs";import{homedir as Ys}from"node:os";import{join as yd}from"node:path";var Ed="cloud-cache.json",Rd=1440*60*1e3,Cd=900*1e3;function kd(e=Ys()){return yd(Se(e),Ed)}function Id(e){if(!_d(e))return;let t=F(Sd(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 Ad(e,t){try{Y(e,`${JSON.stringify(t)}
19
- `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cloud cache write failed open: ${r}`)}}function xd(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Cd:Rd;return n-e.probed_at<r}async function Od(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 vd(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 bd(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 wd(e){let t=await Promise.allSettled([Od(e),vd(e),bd(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Yn(e,t){if(e==="interactive")return null;let n=t?.home??Ys(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=kd(n),i=Id(s);if(xd(i,e,o))return i.result;let a=await wd(r);return Ad(s,{context:e,probed_at:o,result:a}),a}var Pd=["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"],Td=["CURSOR_PROJECT_DIR"],Md=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Nd(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Md.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function qn(e=process.env){let t=Pd.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Nd(e[r]??"")}:{name:r,present:!1}),n=Td.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as up}from"node:os";import{homedir as qs}from"node:os";import{join as Ld}from"node:path";function Ud(e=qs()){return Ld(e,".claude.json")}function Pt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Xs(e=qs()){let n=L(Ud(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=Pt(n.emailAddress),o=Pt(n.fullName)??Pt(n.displayName),s=Pt(n.accountUuid),i=r??s;return!i||B(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as ei}from"node:os";import{join as Zs}from"node:path";var Dd="https://api.openai.com/auth";function Te(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ti(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 ti(r)}catch{return null}}function Qs(e,t,n){return Te(e[n])??Te(t?.[n])}function Fd(e=process.env,t=ei()){let n=Te(e.CODEX_HOME)??Zs(t,".codex");return Zs(n,"auth.json")}function ni(e=process.env,t=ei()){let n=L(Fd(e,t),{}),r=Te(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Te(n.OPENAI_API_KEY))return null;let o=Te(n.tokens?.id_token);if(!o)return null;let s=Hd(o);if(!s)return null;let i=ti(s[Dd]),a=Qs(s,i,"name"),c=Qs(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 Nt}from"node:os";import{join as oe}from"node:path";import{join as jd}from"node:path";var $d="cursor-ide-identity.json",Kd=Fe;function oi(e){return jd(Se(e),$d)}function ri(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function si(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:ri(t.email),auth_id:ri(t.auth_id)}}function ii(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<Kd}function ai(e,t){try{Y(e,`${JSON.stringify(t)}
20
- `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as Bd}from"node:child_process";import{existsSync as Gd}from"node:fs";import{createRequire as zd}from"node:module";import{pathToFileURL as Jd}from"node:url";var li=zd(import.meta.url),Tt=`
15
+ npx ${Et} install`)}function rs(e){return typeof e!="string"?!1:e.includes("@ev-ai/agent-hook")||e.includes("agent-hook/dist/hook")||e.includes(".ev-ai/agent-hook")||e.includes(q)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function Hn(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function de(e,t){Un(Dn(e),{recursive:!0}),gl(e,`${JSON.stringify(t,null,2)}
16
+ `,"utf8")}function se(e){if(ue(e))try{return JSON.parse(fl(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function Nl(e,t){let n=Ko(t.collectorUrl),r={...e,schema_version:e?.schema_version??n.schema_version};return t.collectorUrl!==void 0?r.collector_url=t.collectorUrl:r.collector_url=e?.collector_url??n.collector_url,delete r.repo_ingest_token,delete r.installation_id,r.mcp_servers??=n.mcp_servers,r}function Ll(e){return(e.schema_version??2)===2&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.repo_ingest_token===void 0}function os(e,t){let n=P(e,St),r=se(n),o=Nl(r,t);return t.collectorUrl!==void 0||ue(n)||!Ll(o)?(de(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function Ln(e){if(e===null||typeof e!="object")return!1;let t=e,n=String(t.CLAUDE_CODE_ENABLE_TELEMETRY??"").toLowerCase();return n==="1"||n==="true"?!0:Object.keys(t).some(r=>r.startsWith("OTEL_"))}function Ul(e){if(Ln(process.env))return!0;let t=oe();return[...hn(),P(t,".claude","settings.json"),P(t,".claude","remote-settings.json"),P(e,".claude","settings.json"),P(e,".claude","settings.local.json")].some(r=>{try{let o=se(r);return o?Ln(o.env):!1}catch{return!1}})}function Dl(e){try{let t=se(P(e,".claude","settings.json"));return t?Ln(t.env):!1}catch{return!1}}function ss(e){return Array.isArray(e)?e:[]}function vt(e){let t=[],n=r=>!!r&&typeof r=="object"&&rs(r.command);for(let r of ss(e)){if(!r||typeof r!="object"){t.push(r);continue}let o=Array.isArray(r.hooks)?r.hooks:[],s=o.filter(i=>!n(i));if(!(s.length===0&&o.some(n))){if(s.length!==o.length){t.push({...r,hooks:s});continue}t.push(r)}}return t}function is(e,t){return[...vt(e),...t]}function Fn(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!rs(t.command)):[]}function Hl(e,t){return[...Fn(e),{command:t}]}function Fl(e){return typeof e=="string"?[e]:e}function jl(e){let t=()=>({hooks:Fl(e).map(n=>({type:"command",command:n}))});return{SessionStart:[t()],UserPromptExpansion:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function $l(e){let t=typeof e=="string"?{command:e}:e,n={type:"command",command:t.command,...t.commandWindows===void 0?{}:{commandWindows:t.commandWindows},statusMessage:to},r=()=>({hooks:[n]});return{SessionStart:[r()],UserPromptSubmit:[r()],PreToolUse:[r()],PostToolUse:[r()],Stop:[r()]}}var Kl=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","beforeReadFile","beforeMCPExecution","subagentStart","subagentStop","stop"],Bl=["afterShellExecution","afterFileEdit"];function Gl(e,t=Bl){let n={...e};for(let r of t){if(!(r in n))continue;let o=Fn(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function zl(e,t,n={}){let r=P(e,".claude/settings.json"),o=Hn(t,"claude"),s=se(r)??{};if(Ul(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let l={...s.hooks};for(let p of Object.keys(l))l[p]=vt(l[p]),ss(l[p]).length===0&&delete l[p];Object.keys(l).length===0?delete s.hooks:s.hooks=l,de(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=jl(o),u={...a};for(let[l,p]of Object.entries(c))u[l]=is(a[l],p);return s.hooks=u,de(r,s),!0}function Wl(e,t){let n=P(e,".cursor/hooks.json"),r=Hn(t,"cursor"),o=se(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=Gl({...s});for(let a of Kl)i[a]=Hl(i[a],r);de(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function Jl(e,t){let n=P(e,".codex/hooks.json"),r=Hn(t,"codex"),o=se(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=$l(r),a={...s};for(let[c,u]of Object.entries(i))a[c]=is(s[c],u);de(n,{...o,hooks:a})}function Vl(e){let t=P(e,".claude/settings.json"),n=se(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let i=r[s],a=vt(i);JSON.stringify(i)!==JSON.stringify(a)&&(o=!0),a.length===0?delete r[s]:r[s]=a}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,de(t,n),d(`Removed ev-ai hooks from ${t}`))}function Yl(e){let t=P(e,".cursor/hooks.json"),n=se(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=Fn(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks"&&a!=="version").length===0){Ot(t,{force:!0}),d(`Removed ${t}`);return}de(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function ql(e){let t=P(e,".codex/hooks.json"),n=se(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=vt(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks").length===0){Ot(t,{force:!0}),d(`Removed ${t}`);return}de(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function jn(e=process.platform,t=process.arch,n={}){if(e==="win32")throw new Error("Windows install is not supported yet. Use macOS/Linux, or wait for phase-2 native commands.");(n.requireBinaryArch??!0)&&Bo(e,t)}async function as(e={}){let t=Rl(e);e.collectorUrl=t;let n=e.skipClaude===!0,r=e.skipCursor===!0,o=e.skipCodex===!0;if(n&&r&&o)throw new Error("at least one runner must be wired; refuse --no-claude --no-cursor --no-codex together");let s=e.delivery??Xo();jn(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await re(i),{command:c,hookPath:u,strategy:l}=Ml(a,oe(),s),{installationId:p,storePath:m}=await xt(a,{overrideId:e.installationId}),{manifestPath:f,wrote:_}=os(a,e),S=[];return n?d("Skipped Claude hook \u2014 --no-claude"):zl(a,c,{force:e.force})?(S.push("Claude"),e.force&&Dl(a)&&d("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):d("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?d("Skipped Cursor hook \u2014 --no-cursor"):(Wl(a,c),S.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(Jl(a,c),S.push("Codex")),d(`Installed hook (${l}) at ${u}`),d(`Installation identity ${p} at ${m}`),_&&f?d(`Shared manifest written to ${f}`):d("Using package default collector config (no shared manifest file needed)"),d(S.length>0?`Wired ${S.join(", ")} hooks in ${a} (commands include --runner)`:`No runner hooks wired in ${a} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),l==="npx"?d("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):l==="project_binary"?d("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):l==="dev_mjs"&&d("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&f&&e.collectorUrl&&d("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:a,hookPath:u,manifestPath:f,installationStorePath:m,strategy:l}}async function cs(e=process.cwd()){jn(process.platform,process.arch,{requireBinaryArch:!0});let t=await re(e),{projectPath:n,globalPath:r}=wl(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function ls(e={}){let t=El(e);e.collectorUrl=t,jn(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await re(n),{manifestPath:o,wrote:s}=os(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?d(`Wrote ${o}`):t===void 0&&d("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),d("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function us(e){for(let t of[()=>Vl(e),()=>Yl(e),()=>ql(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function ds(e=process.cwd()){let t=await re(e);return us(t),d("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),d("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function ps(e=process.cwd()){let t=await re(e);us(t);for(let n of Tn){let r=P(t,n);if(ue(r))try{Ot(r,{force:!0}),d(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);d(`WARN: uninstall could not remove ${r}: ${s}`)}}}import{createHash as Jd}from"node:crypto";import{existsSync as Vd,mkdirSync as Yd,readdirSync as qd,readFileSync as ai,unlinkSync as ci,writeFileSync as Xd}from"node:fs";import{homedir as li}from"node:os";import{join as ir}from"node:path";import{existsSync as au}from"node:fs";import{existsSync as Xl}from"node:fs";import{homedir as ms}from"node:os";import{join as Zl}from"node:path";function gs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Ql={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 fs(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function eu(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:fs(n.mcpJson,t.mcpJson),mcpToml:fs(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function hs(e){return Object.fromEntries(Object.entries(Ql).map(([t,n])=>[t,eu(n,n[e])]))}var Te=hs("homeOnly"),fe=hs("projectOnly");function tu(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function nu(e,t){return tu(e).some(n=>Xl(Zl(t,n)))}function _s(e,t){for(let n of e)if(nu(n,t))return!0;return!1}function pe(e){return[...new Set(e)]}function me(e){let t=[],n=[],r=[],o=[],s=[],i=[],a=[];for(let c of e){t.push(...c.skillRoots);for(let u of c.dirs)u.kind==="SUBAGENT"?n.push(u.dir):u.kind==="COMMAND"?r.push(u.dir):o.push(u.dir);s.push(...c.memory.flat()),i.push(...c.settings),a.push(...c.mcpJson??[],...c.mcpToml??[])}return{skills:pe(t),subagents:pe(n),commands:pe(r),rules:pe(o),memory:pe(s),settings:pe(i),mcp:pe(a)}}function ru(e,t=ms(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...It(o.managed,n,t));return pe(r)}var ge=me(Object.values(Te));function Ss(e=ms(),t=process.platform){return ru(Object.values(Te),e,t)}import{existsSync as ou}from"node:fs";import{resolve as $n}from"node:path";function z(e){return $n(e).replaceAll("\\","/").replace(/\/$/,"")}function ke(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function bt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var su=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function qe(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!su.test(t)?null:t}function Me(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=z(o);n.has(s)||(n.add(s),r.push(s))}return r}function iu(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function Z(e,t,n,r=ou){for(let o of e)for(let s of t){let i=z($n(o,s)),a=$n(o,s,n).replaceAll("\\","/");if(iu(i,a)&&r(a))return a}return null}var Es=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,Rs=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,cu=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,ys=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"]),lu=/^[a-z][a-z0-9-]{1,63}$/,uu=[".cursor/skills",".claude/skills",".agents/skills"],du=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],pu=ke(uu,me(Object.values(fe)).skills),fu=ke(du,me(Object.values(Te)).skills),mu=new Set(["read","read_file","view"]),gu=new Set(["bash","shell","zsh"]);function Kn(e){let t=e.replace(/\\/g,"/");return Es.exec(t)?.[1]??null}function hu(e){let t=e.replace(/\\/g,"/"),r=Rs.exec(t)?.[1];return r?r.toLowerCase():null}function _u(e){return Kn(e)??hu(e)}function Su(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function wt(e){return typeof e=="string"?wt(j(e,null)):!e||typeof e!="object"?null:Su(e)}function Cs(e){if(typeof e=="string")return Cs(j(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Bn(e){let t=Cs(e.tool_input);if(t)return t;let n=ye(e.command);return n.length>0?n:null}function yu(e){let t=e.replace(/\\/g,"/"),n=Es.exec(t);if(n?.[1])return n[1];let o=Rs.exec(t)?.[1];return o?o.toLowerCase():null}function Eu(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Gn(e){let t=wt(e.tool_input)??ye(e.file_path);return t.length>0?t:null}function Xe(e,t,n){let r=Eu(e).toLowerCase();if(mu.has(r)){let o=Gn(e);return o?t(o):null}if(gu.has(r)){let o=Bn(e);return o?n(o):null}return null}function Is(e){return Xe(e,_u,yu)}function Ru(e){let t=new Set,n=[];for(let r of e.matchAll(cu)){let o=r[1]?.toLowerCase();!o||t.has(o)||Cu(o)||(t.add(o),n.push(o))}return n}function Cu(e){let t=e.split("/")[0];return ys.has(e)||t!==void 0&&ys.has(t)}function ks(e){let t=e.skillId.toLowerCase();if(!lu.test(t))return null;let n=e.exists??au,r=`${t}/SKILL.md`,o=Z(Me(e.launchCwd,e.gitRoot),pu,r,n);return o!==null?o:e.home?Z([z(e.home)],fu,r,n):null}function Iu(e){return ye(e.prompt)}function As(e){let t=g(e,"command_name");if(t){let r=g(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Iu(e);return n?Ru(n):[]}var Xn=Be(Le(),1);import{existsSync as Sd}from"node:fs";var xe={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Qe(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function _d(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return Qe(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Qe(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Qe(o[1]):Qe(t)}async function et(e=process.cwd()){let t=await V("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([V("git",["remote","get-url","origin"],2e3,{cwd:e}),V("git",["branch","--show-current"],2e3,{cwd:e}),V("git",["rev-parse","HEAD"],2e3,{cwd:e}),V("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function Fs(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=xe[n];if(!a)return"";let c=Po(n,e.scope_path,i);if(s){let _=Uo(s,c);if(_)return _}let u=o??await et(r),l=u?.remote?_d(u.remote):"";if(l||(l=Qe(process.env.GITHUB_REPOSITORY??"")),!l)return"";let p=e.scope_path??"",m=p?`${p}/`:"",f=`${l}:${m}${a}`;return s&&Do(s,c,f),f}var yd=[".cursor/rules",".claude/rules",".codex/rules"],Ed=me(Object.values(fe)).rules;function Rd(e){return ke(bt(e?xe[e]:void 0,yd),Ed)}var Cd=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function js(e){let t=qe(e.relativePath);if(!t)return null;let n=e.exists??Sd,r=Me(e.launchCwd,e.gitRoot),o=Rd(e.runnerPlatform),s=Z(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=Z(r,["."],t,n);if(i!==null)return i}return e.home?Z([z(e.home)],o,t,n):null}function Id(e){let t=e.replace(/\\/g,"/"),r=Cd.exec(t)?.[1];return r?(0,Xn.nativeKeyForRulePath)(r):null}function $s(e){return Xe(e,Xn.nativeKeyForRulePath,Id)}function Ks(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function Bs(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=qe(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var Zn=Be(Le(),1);import{existsSync as kd}from"node:fs";var Ad=[".cursor/commands",".claude/commands",".codex/prompts"],xd=me(Object.values(fe)).commands;function Od(e){return ke(bt(e?xe[e]:void 0,Ad),xd)}var Pd=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function Gs(e){let t=qe(e.commandId);if(!t)return null;let n=e.exists??kd,r=`${t}.md`,o=Od(e.runnerPlatform),s=Z(Me(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?Z([z(e.home)],o,r,n):null}function vd(e){let t=e.replace(/\\/g,"/"),r=Pd.exec(t)?.[1];return r?(0,Zn.nativeKeyForCommandPath)(r):null}function zs(e){return Xe(e,Zn.nativeKeyForCommandPath,vd)}import{existsSync as Js}from"node:fs";import{homedir as Vs}from"node:os";import{join as tt,resolve as Qn,sep as Ws}from"node:path";function er(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function tr(e,t){let n=t.toLowerCase();return er(e).some(r=>r.toLowerCase()===n)}function Nt(e,t,n){if(!Js(e))return;let r=U(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function bd(e,t,n){if(!Js(e))return;let r=U(e,{}),o=Qn(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Qn(a);(o===c||o.startsWith(c.endsWith(Ws)?c:c+Ws))&&(s===null||c.length>Qn(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 Ys(e,t,n,r){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{declared:{name:s.name,source:"manifest"}});return n==="claude"?(Nt(tt(r,".claude.json"),{source:"claude_json_user"},o),bd(tt(r,".claude.json"),t,o)):n==="cursor"&&Nt(tt(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Nt(tt(t,".mcp.json"),{source:"mcp_json"},o),Nt(tt(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function nr(e,t=process.cwd(),n="claude",r=Vs()){return[...Ys(e,t,n,r).values()].map(o=>o.declared)}function qs(e,t,n=process.cwd(),r="claude",o=Vs()){let s=Ys(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(tr(a,e))return c.config??null;return null}function rr(e){return e!==void 0&&no.includes(e)}function Lt(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ut(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=Lt(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=Lt(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=Lt(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=Lt(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:rr(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function or(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=_t(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=ze(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return We(n)}function Xs(e,t){if(g(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function wd(){return!!(C("CURSOR_VERSION")??C("CURSOR_PROJECT_DIR"))}function sr(e,t,n){return e!=="claude"&&e!=="codex"?!1:Xs(t,n)?!0:wd()}function nt(e,t,n,r){if(Xs(e,t))return"cursor";if(rr(r))return r;let o=g(e,"conversation_id"),s=g(e,"turn_id"),i=g(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),rr(n)&&(c=n),c}function Dt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Td(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 Zs(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Qs(e,t,n){let r=g(e,"session_id")||g(e,"conversation_id"),o=g(e,"prompt.id")||g(e,"prompt_id")||g(e,"generation_id")||g(e,"turn_id"),s=g(e,"hook_event_name")||g(e,"event"),i=g(e,"source"),a=nt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Md=["session_start","session_end","tool_invoked","skill_invoked"];function Nd(e){return Md.includes(e)}function ei(e,t){return e&&Nd(e)?e:Td(t.toLowerCase())}var Ld={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function ti(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function ni(e,t=""){let n=g(e,"tool_name")||g(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!ti(n)&&(n=`MCP:${n}`):n=Ld[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?ye(o.skill)||ye(o.skill_name):"")||g(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=Is(a);let c=$s(a),u=zs(a);return{toolName:n,skillName:i,ruleName:c,commandName:u}}var Ud=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function ri(e){for(let t of["subagent_type","agent_type"]){let n=g(e,t);if(n&&Ud.test(n))return n}return null}function oi(e){let t=Ee(e,"duration_ms");if(typeof t=="number")return t;let n=Ee(e,"duration");return typeof n=="number"?n:null}var Dd="error",Hd="interrupted",Fd="permission_denied",jd=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function rt(e){return jd.test(e)?e:null}function $d(e){for(let t of["failure_type","error_type"]){let n=rt(g(e,t));if(n)return n}return null}function si(e,t){return Ee(e,"is_interrupt")===!0?Hd:t.toLowerCase()==="permissiondenied"?Fd:$d(e)??Dd}function Kd(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 Bd(e,t){let n=null;for(let r of t)!r||!tr(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function Gd(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of er(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:Bd(o[1],t)??o[1],mcpTool:o[2]}}function zd(e,t){if(/^mcp__/i.test(e))return Gd(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:Kd(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function Wd(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function ii(e,t=[],n=""){let r=e?zd(e,t):{mcpServer:null,mcpTool:null},o=rt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!ti(e)&&(s=e),s&&(s=Wd(s,o)),{mcpServer:o,mcpTool:s}}var ui=3e4,Zd="claims",Qd=!0,ep=100,tp=new Set(["sessionstart","sessionend","stopfailure"]),np=["tool_name","tool","command","file_path","url"];function rp(e=li()){return ir(Re(e),Zd)}function di(e){let t=e.split(`
17
+ `,1)[0]??"";return Number(t.trim())}function pi(e){return Jd("sha256").update(e).digest("hex").slice(0,32)}function op(e){let t=[];for(let n of np){let r=g(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":pi(t.join("\0"))}function sp(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=tp.has(n);if(!a&&!c)return;let u=e.runnerPlatform.trim()||"unknown";return pi(`${u}|${t}|${n}|${r}|${o}|${i}|${s}`)}function ip(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function ap(e,t){return ir(e,t)}function cp(e,t=Date.now()){let n;try{n=qd(e)}catch{return}let r=0;for(let o of n){if(r>=ep)break;r+=1;let s=ir(e,o),i=Number.NaN;try{i=di(ai(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<ui))try{ci(s)}catch{}}}function lp(e,t,n=Date.now()){let r=ap(t,e);try{if(Vd(r)){let o=Number.NaN;try{o=di(ai(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<ui)return!1;try{ci(r)}catch{}}}catch{}try{Yd(t,{recursive:!0}),Xd(r,`${n}
18
+ `,{encoding:"utf8",flag:"wx"})}catch(o){if(ip(o))return!1;let s=o instanceof Error?o.message:String(o);return d(`WARN: event claim failed open: ${s}`),!0}return cp(t,n),!0}function up(e,t,n){let r=g(e,"session_id")||g(e,"conversation_id"),o=g(e,"prompt.id")||g(e,"prompt_id")||g(e,"generation_id")||g(e,"turn_id"),s=g(e,"tool_use_id"),i=g(e,"subagent_id")||g(e,"agent_id"),a=nt(e,t,void 0,n),c=op(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function fi(e,t,n,r=li(),o=Date.now()){if(!Qd)return!0;let s=sp(up(e,t,n));if(!s)return!0;let i=lp(s,rp(r),o);return!i&&C("EV_AI_HOOK_DEBUG")&&d(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{realpathSync as dg}from"node:fs";import{homedir as pg}from"node:os";var A=Be(Le(),1);import{existsSync as dp,readFileSync as pp}from"node:fs";import{homedir as mi}from"node:os";import{join as fp}from"node:path";var mp="cloud-cache.json",gp=1440*60*1e3,hp=900*1e3;function _p(e=mi()){return fp(Re(e),mp)}function Sp(e){if(!dp(e))return;let t=j(pp(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 yp(e,t){try{X(e,`${JSON.stringify(t)}
19
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cloud cache write failed open: ${r}`)}}function Ep(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?hp:gp;return n-e.probed_at<r}async function Rp(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 Cp(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 Ip(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 kp(e){let t=await Promise.allSettled([Rp(e),Cp(e),Ip(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function ar(e,t){if(e==="interactive")return null;let n=t?.home??mi(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=_p(n),i=Sp(s);if(Ep(i,e,o))return i.result;let a=await kp(r);return yp(s,{context:e,probed_at:o,result:a}),a}var Ap=["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"],xp=["CURSOR_PROJECT_DIR"],Op=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Pp(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Op.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function cr(e=process.env){let t=Ap.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Pp(e[r]??"")}:{name:r,present:!1}),n=xp.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as of}from"node:os";import{homedir as gi}from"node:os";import{join as vp}from"node:path";function bp(e=gi()){return vp(e,".claude.json")}function Ht(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function hi(e=gi()){let n=U(bp(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=Ht(n.emailAddress),o=Ht(n.fullName)??Ht(n.displayName),s=Ht(n.accountUuid),i=r??s;return!i||G(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as yi}from"node:os";import{join as _i}from"node:path";var wp="https://api.openai.com/auth";function Ue(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ei(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Tp(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 Ei(r)}catch{return null}}function Si(e,t,n){return Ue(e[n])??Ue(t?.[n])}function Mp(e=process.env,t=yi()){let n=Ue(e.CODEX_HOME)??_i(t,".codex");return _i(n,"auth.json")}function Ri(e=process.env,t=yi()){let n=U(Mp(e,t),{}),r=Ue(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Ue(n.OPENAI_API_KEY))return null;let o=Ue(n.tokens?.id_token);if(!o)return null;let s=Tp(o);if(!s)return null;let i=Ei(s[wp]),a=Si(s,i,"name"),c=Si(s,i,"email");return!c||G(a,c)?null:{git_user_name:null,git_user_email:null,platform_login:c,identity_source:"codex_oauth"}}import{homedir as $t}from"node:os";import{join as ae}from"node:path";import{join as Np}from"node:path";var Lp="cursor-ide-identity.json",Up=Ge;function Ii(e){return Np(Re(e),Lp)}function Ci(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ki(e){let t=U(e,{}),n=t.read_at_ms,r=t.db_path;if(!(typeof n!="number"||!Number.isFinite(n)||typeof r!="string"))return{read_at_ms:n,db_path:r,email:Ci(t.email),auth_id:Ci(t.auth_id)}}function Ai(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<Up}function xi(e,t){try{X(e,`${JSON.stringify(t)}
20
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as Dp}from"node:child_process";import{existsSync as Hp}from"node:fs";import{createRequire as Fp}from"node:module";import{pathToFileURL as jp}from"node:url";var Pi=Fp(import.meta.url),Ft=`
21
21
  SELECT key, value
22
22
  FROM ItemTable
23
23
  WHERE key LIKE 'cursorAuth/%'
24
24
  AND key NOT LIKE '%Token%'
25
25
  AND key NOT LIKE '%token%'
26
26
  ORDER BY key
27
- `.trim(),Xn=new Map;function ci(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 ui(e){return e.toLowerCase().includes("token")}function di(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=ci(r.key),s=ci(r.value);o&&s&&!ui(o)&&t.set(o,s)}return t}function Wd(e){let t=Jd(e);return t.search="mode=ro&immutable=1",t.href}function Vd(e){try{let t=li("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(Tt)??n.prepare(Tt);return di(r.all?.())}finally{n.close?.()}}catch{return null}}function Yd(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 qd(e){try{return Yd(()=>{let t=li("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return di(n.prepare(Tt).all?.())}finally{n.close?.()}})}catch{return null}}function Xd(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&&!ui(s)&&t.set(s,i)}return t}function Zd(e){try{let t=Bd("sqlite3",["-noheader","-batch","-separator"," ",e,Tt],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return Xd(t)}catch{return null}}function pi(e){let t=Xn.get(e);if(t)return t;if(!Gd(e)){let o=new Map;return Xn.set(e,o),o}let n=Wd(e),r=Vd(n)??Zd(n)??qd(n)??new Map;return Xn.set(e,r),r}var Qd="cursorAuth/cachedEmail",ep="cursorAuth/stripeMembershipAuthId";function Mt(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function tp(e=Nt(),t=process.platform,n=process.env){let r=Mt(n.VSCODE_PORTABLE);if(r)return oe(r,"user-data");let o=Mt(n.VSCODE_APPDATA);if(o)return oe(o,"Cursor");switch(t){case"darwin":return oe(e,"Library","Application Support","Cursor");case"win32":return oe(Mt(n.APPDATA)??oe(e,"AppData","Roaming"),"Cursor");default:return oe(Mt(n.XDG_CONFIG_HOME)??oe(e,".config"),"Cursor")}}function np(e=Nt()){return oe(e,".cursor","cli-config.json")}function rp(e=Nt(),t=process.platform,n=process.env){return oe(tp(e,t,n),"User","globalStorage","state.vscdb")}function Ze(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function op(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):Ze(e.userId)}function sp(e){return Ze(e.email)??Ze(e.authId)??op(e)}function Zn(e){let t=Ze(e.email),n=Ze(e.displayName),r=sp(e);return!r||B(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function ip(e){let n=L(np(e),{}).authInfo;return!n||typeof n!="object"?null:Zn(n)}function ap(e,t,n){let r=rp(e,process.platform,t),o=oi(e),s=si(o);if(ii(s,r,n))return Zn({email:s?.email,authId:s?.auth_id});let i=pi(r),a=i.get(Qd)??null,c=i.get(ep)??null;return ai(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),Zn({email:a,authId:c})}function fi(e=Nt(),t=process.env,n=Date.now()){return ip(e)??ap(e,t,n)}import{createHash as cp}from"node:crypto";import{resolve as lp}from"node:path";function N(e){return cp("sha256").update(e).digest("hex").slice(0,16)}function Qn(e){return N(lp(e))}function J(e,t){return`${e}\0${t}`}function mi(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function Qe(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
29
- `);return N(n)}function dp(e,t,n="git_config",r=null){return N(`${e??""}|${t??""}|${r??""}|${n}`)}function pp(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 fp(e,t=P){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return pp(n)}function mp(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 se(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 gp(e=process.env){let t=k(e.EV_AI_HOOK_OPERATOR_EMAIL),n=k(e.EV_AI_HOOK_OPERATOR_LOGIN),r=se(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=se(o,null,"github",o);if(s)return s;let i=k(e.GITLAB_USER_LOGIN),a=k(e.GITLAB_USER_EMAIL),c=se(k(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let l=k(e.BUILD_REQUESTEDFOREMAIL),u=se(k(e.BUILD_REQUESTEDFOR),l,"azure_devops",l??k(e.BUILD_REQUESTEDFORID));if(u)return u;let p=k(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=se(k(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(m)return m;let f=k(e.BUILD_USER_EMAIL)??k(e.CHANGE_AUTHOR_EMAIL),_=se(k(e.BUILD_USER)??k(e.CHANGE_AUTHOR),f,"jenkins",f??k(e.BUILD_USER_ID));if(_)return _;let S=k(e.CIRCLE_USERNAME),h=se(S,null,"circleci",S);if(h)return h;let E=k(e.CODEBUILD_INITIATOR),T=se(E,null,"codebuild",E);if(T)return T;let H=k(e.DRONE_COMMIT_AUTHOR_EMAIL),v=k(e.DRONE_COMMIT_AUTHOR),x=se(v??k(e.DRONE_COMMIT_AUTHOR_NAME),H,"drone",H??v);if(x)return x;if(gi(e.CLAUDE_CODE_REMOTE)||gi(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 er(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 gi(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function hp(e,t,n){return e==="claude"?Xs(t):e==="cursor"?fi(t,n):e==="codex"?ni(n,t):null}async function tr(e,t=P,n=process.env,r={}){let o=await fp(e,t),s=mp(n),i=er(o)?o:s&&er(s)?s:null,a=hp(r.runnerPlatform,r.home??up(),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=gp(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:er(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 nr(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??P,s=e.env??process.env,i=await tr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=dp(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 f=n;return{operator:i,commit:()=>{f&&Co(f,a,gt())}}}function rr(e){return e?!An(e)?.operator_identity_hash:!0}function hi(e){return!0}import{existsSync as $f,readFileSync as Kf}from"node:fs";import{homedir as aa}from"node:os";import{join as Ue,resolve as Bf}from"node:path";import{basename as Nf,join as Le}from"node:path";import{dirname as Ii,resolve as Dt}from"node:path";import{existsSync as _p}from"node:fs";import{homedir as yi}from"node:os";import{relative as Ei,resolve as X,sep as ge}from"node:path";var Sp=["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 yp(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:R("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function Ep(e){let t={};for(let n of Sp){let r=_e(e,n);r!==void 0&&(t[n]=r)}return t}function Lt(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=X(e),r=X(t),o=Ei(r,n);return!o||o==="."?".":o.startsWith(`..${ge}`)||o===".."||X(r,o)!==n?null:o.split(ge).join("/")}function Ri(e,t){let n=Ei(X(t),X(e)).split(ge).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Ci(e){return typeof e!="string"||e.length===0?null:X(e).split(ge).join("/")}function Rp(){let e=R("CURSOR_PROJECT_DIR");if(!e)return null;let t=X(e);return _p(t)?t.split(ge).join("/"):null}function or(e,t){return Lt(e,t)!==null}function Cp(e,t){let n=X(t??yi(),".cursor").split(ge).join("/");return or(e,n)}function kp(e,t,n){return t!==null&&or(e,t)?!0:t!==null&&Cp(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&or(e,n.gitRoot)?!0:t===null}function ki(e,t){let n=Ci(e.cwd);if(n!==null)return n;let r=X(process.cwd()).split(ge).join("/"),o=Rp();return kp(r,o,t)?r:o??r}function sr(e,t={}){return ki(e,t)}function ir(e,t=yi()){let n=X(t).split(ge).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function _i(e,t,n){let r=Ci(n.launchCwd)??ki(t,n);e.cwd=ir(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?Lt(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function Si(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 Ut(e,t,n={}){if(yp(t)){let o={...e};return delete o.cwd,delete o.transcript_path,_i(o,e,n),Si(o,Kr)}let r=Ep(e);return _i(r,e,n),Si(r,$r)}function Ip(e){return typeof e=="string"&&e.length>0}function ar(e){let t=Dt(e.home),n=Dt(e.launchCwd),r=e.gitRoot?Dt(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Ip(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&&Lt(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=Ii(r);for(;;){let u=Dt(l);if(u===t)break;let p=Ii(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 Ai,readdirSync as Ap,realpathSync as xp}from"node:fs";import{basename as Op,dirname as vp,relative as bp,resolve as wp,sep as Pp}from"node:path";var cr=400,Ht=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??ae}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=wp(t).split(Pp).join("/");return ir(r,this.home)}let n=bp(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${N(vp(t))}/${Op(t)}`:n}claimFile(t){try{let n=xp(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(!Ai(t))return[];try{return Ap(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(Ai(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 lr,readFileSync as Tp,statSync as Mp}from"node:fs";import{basename as Oi,join as et,relative as vi}from"node:path";var ur=100*1024,Np=4;function Lp(e){return e.length<=ur?e:`${e.slice(0,ur-1)}\u2026`}function Up(e){try{let t=Tp(e),n=t.toString("utf8");return{hash:N(t),length:t.length,text:Lp(n)}}catch{return null}}var xi={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Dp(e){return e in xi?xi[e]:"UNSPECIFIED"}function Ft(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Up(t.absolutePath);if(!n)return!1;let r=t.name??Oi(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=Dp(t.kind);return s&&(o.trigger=s),e.push(o)}function Hp(e,t,n){let r=vi(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Oi(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Ie(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;dr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function dr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Np))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let f=et(r,u.name,c);if(lr(f)){let _=vi(n,et(r,u.name)).replace(/\\/g,"/");Ft(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:_||u.name});continue}dr(e,{walkRoot:n,currentDir:et(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){dr(e,{walkRoot:n,currentDir:et(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let p=u.name.toLowerCase();if(!l.some(f=>p.endsWith(f)))continue;let m=et(r,u.name);Ft(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:Hp(n,m,!0)})}}function bi(e){for(let t of e)if(lr(t))try{if(Mp(t).size>0)return t}catch{continue}return e.find(t=>lr(t))}var Fp="<omitted>",jp=["package_name","package_spec","package_version","package_version_source"],wi=100,Pi=120,jt=[{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"}],Ti=new Set(jt.map(e=>e.attr)),$p=["enabled","disabled"],Kp=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Bp=new Set(["type","command","url","args","env","envVars","headers",...$p,...Kp,...jt.map(e=>e.raw)]),Gp=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",...jp,...Ti,...[...Ti].map(e=>`${e}_truncated`)]);function Mi(e,t){for(let n of t)Bp.has(n)||Gp.has(n)||(e[n]=Fp)}var zp=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,Jp=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,Wp=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,Vp=/^bearer(?:\s+|$)/i;function $t(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Ni(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function pr(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=$t(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Ae(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Yp(e){return Wp.test(e)||Vp.test(e)?"<redacted>":e.includes("://")?Ae(e):e}function Li(e){if(/^https?:\/\//i.test(e))return Ae(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Li(e.slice(t+1))}`:Yp(e)}function qp(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return zp.test(t)||Jp.test(t)}function Kt(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(qp(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Li(r))}return t}function Xp(e){let t=Ni(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Pi?r.slice(0,Pi):r))].sort();if(n.length!==0)return n.length>wi?{names:n.slice(0,wi),truncated:!0}:{names:n,truncated:!1}}function Zp(e){let t=$t(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 Ui(e,t){let n=new Set;for(let{raw:r,attr:o}of jt){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=Xp(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function Di(e,t){let n=$t(e),r={transport:t};if(!n)return r;Mi(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.serverUrl=="string"?n.serverUrl:void 0,a=o??s??i;a&&(r.command_or_url=Ae(a));let c=Kt(Ni(n.args));c.length>0&&(r.args=c);let l=Zp(n.env_http_headers),u=[...new Set([...pr(n.env),...pr(n.envVars),...pr(n.env_vars),...l.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();u.length>0&&(r.env_var_names=u),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let _ of["headers","http_headers","env_http_headers"])if(n[_]!==void 0&&n[_]!==null){r.headers_present=!0;break}let p=typeof n.auth=="string"?n.auth:void 0;p&&(r.auth=p);let m=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;m&&(r.bearer_token_env_var=m);let f=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return f&&(r.default_tools_approval_mode=f),Ui(r,n),r}function Hi(e){let t=$t(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function gr(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 Me(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function tt(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 Qp(e,t){return Kt(tt(e,t))}function mr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function fr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=Me(n[1]);return r.length>0?r:void 0}function ef(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],Me(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
31
- ${e}`);return s?.[1]&&r(s[1]),n}function Fi(e){return mr(e,"enabled")===!1?!1:mr(e,"disabled")!==!0}function tf(e,t){let n={};for(let{raw:r,attr:o}of jt){if(o==="auto_approve"){let i=mr(t,r);if(i!==void 0){n[r]=i;continue}}let s=tt(t,r);s.length>0&&(n[r]=s)}Ui(e,n)}var nf=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,rf=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function of(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=nf.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(rf))o[1]&&t.add(o[1]);return[...t]}function ji(e,t){let n={transport:t};Mi(n,of(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?Me(r[1]??""):void 0,i=o?Me(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i;a&&(n.command_or_url=Ae(a));let c=Qp(e,"args");c.length>0&&(n.args=c);let l=new Set;for(let h of e.split(`
33
- `)){let E=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(h);E?.[1]&&l.add(E[1])}let u=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(u?.[1])for(let h of u[1].split(",")){let E=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(h);E?.[1]&&l.add(E[1])}let p=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
34
- ${e}`);if(p?.[1])for(let h of p[1].split(`
35
- `)){let E=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(h);E?.[1]&&l.add(E[1])}for(let h of tt(e,"env_vars"))l.add(h);let m=ef(e,"env_http_headers");for(let[,h]of m)h.length>0&&l.add(h);let f=fr(e,"bearer_token_env_var");f&&(l.add(f),n.bearer_token_env_var=f),l.size>0&&(n.env_var_names=[...l].sort()),m.length>0&&(n.env_http_header_names=[...new Set(m.map(([h])=>h))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let _=fr(e,"auth");_&&(n.auth=_);let S=fr(e,"default_tools_approval_mode");return S&&(n.default_tools_approval_mode=S),tf(n,e),n}var sf=300,af=256;function $i(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 Bt(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 Ki(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function cf(e){return Ki(e,sf)}function Bi(e,t){let n=$i(e.trim(),t),r=Bt(n);if(r.length===0)return"";let[o,...s]=r,i=Ae(o),a=Kt(s);return cf([i,...a].join(" "))}function Gi(e,t){if(typeof e!="string")return null;let n=$i(e.trim(),t),r=Bt(n)[0];if(!r)return null;let o=Ae(r);return o.length===0?null:Ki(o,af)}function lf(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 uf(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 df(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 uf(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",p=lf({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",f=N(u),_=m?`${s}:${m}:${p}:${f}`:`${s}:${p}:${f}`,S=`${s}|${m}|${p}|${u}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:N(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:f,...p!=="prompt"&&u.trim()?{command:Bi(u,e.home)}:{}}})}}}function Ne(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||df(e,t,r.hooks,n)}import{existsSync as xf,readFileSync as Of}from"node:fs";import{createHash as pf}from"node:crypto";import{join as nt}from"node:path";var Gt=128,ff=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,mf=new Set(["-p","--package"]),gf=new Set(["-c","--call"]),hf=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),_f=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),Sf=/^--no-/;function yf(e){return _f.has(e)||Sf.test(e)}function Ef(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}function hr(e){if(e.length===0||e.length>Gt)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return ff.test(n)?n:null}function Rf(e,t){let n=Ef(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(gf.has(l))return[];if(mf.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||yf(l))){if(hf.has(l)){i+=1;continue}return[]}}return o.length>0?o.every(i=>hr(i)!==null)?o:[]:s===null||hr(s)===null?[]:[s]}function Cf(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
36
- `);return pf("sha512").update(t).digest("hex").slice(0,16)}function kf(e){let t=process.platform==="win32"?nt(R("LOCALAPPDATA")??e,"npm-cache"):nt(e,".npm"),n=R("npm_config_cache")??R("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function zi(e){return typeof e=="string"&&e.length>0&&e.length<=Gt?e:null}function If(e,t,n){let r=Cf(e);for(let o of kf(n)){let s=nt(o,"_npx",r),i=L(nt(s,"node_modules",...t.split("/"),"package.json"),{}),a=zi(i.version);if(a!==null)return a;let c=L(nt(s,"package-lock.json"),{}),l=zi(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function Af(e){return e.length<=Gt?e:`${e.slice(0,Gt-1)}\u2026`}function _r(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=Rf(e,t??[]),o=r[0];if(o===void 0)return null;let s=hr(o);if(s===null)return null;let i=If(r,s,n);return{package_name:s,package_spec:Af(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function Ji(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=Bt(e.trim());return n===void 0?null:_r(n,r,t)}function zt(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 _r(typeof n.command=="string"?n.command:null,r,t)}function Wi(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:_r(Me(n[1]??""),tt(e,"args"),t)}function vf(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 Vi(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=vf(a),l=Di(a,c);Object.assign(l,zt(a,e.home)??{});let u=Hi(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:gr(i,l,u),origin:n,enabled:u,attributes:l})}}function Yi(e,t,n){if(!xf(t)||!e.claimFile(t))return;let r;try{r=Of(t,"utf8")}catch{return}let o=e.componentPath(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),l=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),p="unknown";/^\s*url\s*=/m.test(u)?p="http":/^\s*command\s*=/m.test(u)&&(p="stdio");let m=ji(u,p);Object.assign(m,Wi(u,e.home)??{});let f=Fi(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:gr(a,m,f),origin:n,enabled:f,attributes:m})}}import{existsSync as bf,readdirSync as wf}from"node:fs";import{join as K}from"node:path";var qi=50;function Sr(e,t,n,r){if(!bf(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(qi,()=>{Ie(e,{dir:K(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Ie(e,{dir:K(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Ie(e,{dir:K(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});Ne(e,K(t,"hooks","hooks.json"),n),Ne(e,K(t,"hooks.json"),n);let i=e.components.length-o,a=s>=qi;return{componentCount:i,expandTruncated:a}}function yr(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 Xi(e){let t=K(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(K(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",f=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,h=0,E=!1;for(let T of l)if(typeof T.installPath=="string"&&T.installPath.length>0){let H=Sr(e,T.installPath,S,p);h+=H.componentCount,E=E||H.expandTruncated}yr(e,{pluginKey:a,rowPath:i,enabled:p,scope:_,version:f||void 0,marketplace:m||void 0,componentCount:h,expandTruncated:E,contentHash:N(`${a}|${f}|${_}|${p}|${h}`)})}}function Pf(e){let t=e,n="";try{let r=wf(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=K(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=K(e,s),n=s)}}catch{}return{installPath:t,version:n}}var Tf=/^\d+$/;function Mf(e){let t=e.filter(n=>!Tf.test(n.pluginId));return t.length>0?t:e}function Zi(e){let t=[{base:K(e.home,".cursor/plugins/local"),scope:"local"},{base:K(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=K(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:p}=Sr(e,c,l,!0);yr(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:p,contentHash:N(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(K(n,s))){if(!a.isDirectory())continue;let c=K(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}=Sr(e,a.installPath,l,!0);yr(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:p,contentHash:N(`${c}|${a.version}|${u}`)})}}}function Lf(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Ie(e,{dir:Le(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Ie(e,{dir:Le(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=bi(i.map(c=>Le(r,c)));a&&Ft(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:Nf(a)})}for(let i of rs(n))Ne(e,Le(r,i),o);for(let i of n.mcpJson??[])Vi(e,Le(r,i),o);for(let i of n.mcpToml??[])Yi(e,Le(r,i),o);if(s){if(n.managed)for(let i of mt(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&Ne(e,i,o);n.plugins==="claude"?Xi(e):n.plugins==="cursor"&&Zi(e)}}function Qi(e,t){try{let n=new Ht(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)Lf(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=Qi(t,{layouts:Object.values(be),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:ae,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(de),l=ar({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>ss(c,u)});i=l.parentRel;for(let u of l.anchors){let p=Qn(u.dir);if(o!==void 0&&!o(u.scope,p))continue;let m=Qi(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:cr,scopeRef:p});m&&(r[u.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function Rr(e,t,n={}){let r=n.truncated===!0,o=Qe(e),s=new Set(e.map(u=>J(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let u of e){let p=J(u.path,u.name);c[p]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let p=mi(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 ta=2*1024*1024,Uf=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Cr(e,t,n){let r=new Set(t.map(s=>J(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(J(s.path,s.name))||o.push(s));return o}function kr(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 ea(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function na(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Ir(e,t=ta){let n=[],r=[];for(let u of e)Uf.has(u.kind)?n.push(u):r.push(u);r.sort((u,p)=>(u.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let p=s.length>0?1:0,m=ea(u)+p;if(i+m<=t){s.push(u),i+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let f=na(u),_=ea(f)+p;if(i+_<=t){s.push(f),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function Ar(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:na(n))}var Df=["user","cwd","repo","parent"];function xr(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let v of Df){let x=t.scopes[v];if(!x)continue;let U=n(v,x.scopeRef),M=U.components,j=Rr(x.components,M,{forceFull:M===void 0,truncated:x.truncated}),Z=new Set(U.textHashes),D=Cr(x.components,j.upserts,Z),w=Ar([...j.upserts,...D],Z);s.push({scope:v,walk:x,delta:j,outgoing:w,outgoingKeys:new Set(w.map(y=>J(y.path,y.name))),deliveredTextHashes:Z,cachedComponents:M})}let i=s.flatMap(v=>v.outgoing),a=Ir(i,o),c=new Set(a.components.map(v=>J(v.path,v.name))),l=[],u=[],p=[],m=[],f=[],_=[],S=[];for(let v of s){let{scope:x,walk:U,delta:M}=v;_.push(...U.components),l.push(x);let j=a.components.filter(y=>v.outgoingKeys.has(J(y.path,y.name))),Z=[...v.outgoingKeys].some(y=>!c.has(y)),D=M.truncated||Z;D?p.push(x):M.full&&u.push(x),m.push(...j),!M.full&&!D&&f.push(...M.removed);let w=M.full?{}:{...v.cachedComponents??{}};if(!D)for(let y of M.removed)delete w[J(y.path,y.name)];for(let y of j)w[J(y.path,y.name)]=y.content_hash;S.push({scope:x,scopeRef:U.scopeRef,components:w,textHashes:kr(v.deliveredTextHashes,j.filter(y=>y.text!==void 0).map(y=>y.content_hash),U.components),collectedAtMs:r,included:j.length>0||M.removed.length>0&&!D||M.full})}let h={user_spec_hash:Qe(_),user_spec_count:_.length,user_spec_truncated:p.length>0};l.length>0&&(h.user_spec_scopes=l,h.user_spec_full_scopes=u,h.user_spec_truncated_scopes=p,h.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(h.user_spec_full=!0),m.length>0&&(h.user_spec=m),f.length>0&&(h.user_spec_removed=f),a.textDeferredCount>0&&(h.user_spec_text_deferred=a.textDeferredCount);let E=t.scopes.cwd;E&&(h.user_spec_cwd_scope_ref=E.scopeRef);let T=t.scopes.repo;T&&(h.user_spec_repo_scope_ref=T.scopeRef);let H=t.scopes.parent;return H&&(h.user_spec_parent_scope_ref=H.scopeRef,t.parentRel&&(h.user_spec_parent_rel=t.parentRel)),{fields:h,scopes:S}}var ot={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function Jt(e){return e==="cwd"||e==="repo"||e==="parent"}function rt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Or(e){return!rt(e)||!rt(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 ra(e){return Hf(e)}function oa(e){return Ff(e)}function sa(e){return jf(e)}function Hf(e){if(!rt(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function Ff(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function vr(e,t){if(!rt(e))return;let n=e[t];return Or(n)?n:void 0}function jf(e){if(!rt(e))return{};let t={};for(let[n,r]of Object.entries(e))Or(r)&&(t[n]=r);return t}function br(e,t=20){let n=[];for(let[r,o]of Object.entries(e))Or(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 Gf=200,ia=200,zf=["allow","deny","ask"],Jf=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Pr="<path>",Wf=new RegExp(`${Pr}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Vf(e){let t=e.replace(Jf,Pr).replace(Wf,Pr);return t.length>ia?`${t.slice(0,ia)}...`:t}function Vt(e){let t=L(e,{}),n=[];for(let r of zf)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Vf(o),mode:r});return{model:t.model??"",permissionKeys:n}}function Yf(e){let{serverManaged:t,fileBased:n}=pn(process.platform,e),r=Vt(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=Vt(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function qf(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 Xf=10,Zf="self-config-cache.json",ca=2;function Yt(){return R("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Qf(){return R("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function em(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Fe}var tm={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function nm(e,t=P){let n=tm[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 rm(e=aa()){return Ue(e,".ev-ai","agent-hook",Zf)}function om(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
38
- `);return N(n)}function Wt(e,t,n=!1){let r=om(e),o=e.length;return t===r?n?{hash:r,count:o,truncated:n}:{hash:r,count:o}:n?{hash:r,count:o,entries:e,truncated:n}:{hash:r,count:o,entries:e}}function wr(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>Ue(e,a)),...n]){let a=Bf(i);if(s.has(a))continue;s.add(a);let c=_n(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function sm(e){return $f(e)?F(Kf(e,"utf8"),{}):{}}function im(e,t){try{Y(e,`${JSON.stringify(t)}
39
- `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: self-config cache write failed open: ${r}`)}}function am(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(Jt(t))return vr(e[ot[t]],n)?.collected_at_ms}function cm(e,t,n){if(t==="user")return{components:ra(e.user_spec_components),textHashes:oa(e.user_spec_text_hashes)};if(!Jt(t))return{components:void 0,textHashes:[]};let r=vr(e[ot[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function lm(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=ca,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(!Jt(s.scope))continue;let i=ot[s.scope],a=sa(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]=br(a)}}return o}async function la(e,t=process.cwd(),n=aa(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await nm(e),a="",c=[];if(o){let D=Yf(n),w=Vt(Ue(n,".claude/settings.json")),y=Vt(Ue(t,".claude/settings.local.json"));a=D.model||y.model||w.model,c=qf([...D.permissionKeys,...w.permissionKeys,...y.permissionKeys]).slice(0,Gf)}let l={present:!1,size:0},u=D=>{let w=[],y=!1;for(let Q of D){let ct=ro(Ue(n,Q));if(w=w.concat(ct.entries),y=y||ct.truncated,w.length>=ae){w=w.slice(0,ae),y=!0;break}}return{entries:w,truncated:y}},p=rm(n),m=sm(p),f=m[e]??{},_=(f.send_count??0)+1,S=_>0&&_%Xf===0,h=D=>S?void 0:f[D],E=u(fe.skills),T=u(fe.subagents),H=u(fe.commands),v=u(fe.rules),x={skills:Wt(E.entries,h("skills"),E.truncated),subagents:Wt(T.entries,h("subagents"),T.truncated),commands:Wt(H.entries,h("commands"),H.truncated),rules:Wt(v.entries,h("rules"),v.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:x.skills,subagents:x.subagents,commands:x.commands,rules:x.rules,memory:wr(n,fe.memory),settings:wr(n,fe.settings,is(n)),mcp:wr(n,fe.mcp)},local_settings:o?_n(Ue(t,".claude/settings.local.json")):l},M=null,j=r.nowMs??Date.now();if(!Yt()){let D=f.user_spec_layout_version!==ca,w=Er(e,n,{launchCwd:Qf()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(y,Q)=>D||em(am(f,y,Q),j)});if(Object.keys(w.scopes).length>0){let y=xr({collected:w,cacheFor:(Q,ct)=>D?{components:void 0,textHashes:[]}:cm(f,Q,ct),nowMs:j});Object.assign(U,y.fields),M={hash:y.fields.user_spec_hash,home:y.scopes.find(Q=>Q.scope==="user")??null,project:y.scopes.filter(Q=>Q.scope!=="user")}}}let Z=lm(f,x,_,M);return{config:U,commit:()=>{m[e]=Z,im(p,m)}}}function De(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp:gt(),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:ee,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as da}from"node:fs";import{spawn as pa}from"node:child_process";import{basename as dm}from"node:path";import{fileURLToPath as pm}from"node:url";import{gzipSync as um}from"node:zlib";function Tr(e){return R("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<Br?{body:e}:{body:um(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function qt(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function ua(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var st="__post",Xt="__work";async function fm(e,t,n={}){if(R("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off")return e;let r=await tr(n.gitRoot??process.cwd(),P,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 mm(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 fa(e){switch(e){case"session_start":return Hr;case"session_end":return Fr;case"tool_invoked":case"skill_invoked":return cn;default:return cn}}function gm(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
40
- ${n}`}function ma(e,t=[],n=process.execPath,r=import.meta.url,o=da){if(dm(n)===ie)return{command:n,args:[e,...t]};let s=pm(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function hm(e=process.execPath,t=import.meta.url,n=da){return ma(st,[],e,t,n)}function _m(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 Zt(e,t=fetch){let n=await e(),r=_m(n);if(!r)return;let{meta:o,body:s}=r,i=Tr(s),a=qt(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function Sm(e,t,n,r=fetch){let o=fa(e),s=Tr(t),i=qt(s.contentEncoding),a=ua(s.body);d(`POST event=${e} url=${un(n)} size=${a} encoding=${s.contentEncoding??"identity"} platform=${process.platform}`);let c=Date.now();try{let l=await r(n,{method:"POST",headers:i,body:s.body,signal:AbortSignal.timeout(o)});if(!l.ok&&s.contentEncoding==="gzip"&&(l.status===400||l.status===415)){try{await l.text()}catch{}d(`POST gzip rejected http=${l.status} \u2014 retrying uncompressed`),l=await r(n,{method:"POST",headers:qt(),body:t,signal:AbortSignal.timeout(o)})}let u=Date.now()-c;if(l.ok)return d(`POST outcome=ok elapsed_ms=${u} http=${l.status}`),!0;let p=(await l.text()).slice(0,200).replace(/[\n\r]/g,"");return d(`POST outcome=fail elapsed_ms=${u} http=${l.status} body=${p}`),!1}catch(l){let u=Date.now()-c,p=l instanceof Error?l.message:String(l);return d(`POST outcome=fail elapsed_ms=${u} http=000 body=${p}`),!1}}async function ga(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){d(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},jr),l=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return d(`WARN: ${o} spawn failed open: ${i}`),null}}async function ym(e,t,n,r=pa,o=hm){let s=fa(e),i=gm(n,s,t),{command:a,args:c}=o();return ga(a,c,i,r,"detached post")}async function ha(e,t,n=pa,r=ma){let{command:o,args:s}=r(Xt,t);return ga(o,s,e,n,"detached work")}async function He(e,t,n,r,o,s,i){if(!o)return d("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!pt(o))return d(`WARN: collector URL blocked (https required): ${un(o)}`),!1;let a=await fm(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=R("EV_AI_HOOK_DEBUG");u==="full"?d(`DEBUG envelope=${JSON.stringify(c)}`):u==="1"&&d(`DEBUG summary=${mm(c,Buffer.byteLength(l,"utf8"))}`);let p=process.argv.includes(Xt),m=R("EV_AI_HOOK_SYNC")==="1";return wt(n.runnerEvent,n.runnerPlatform)||p||m?Sm(e,l,o):(await ym(e,l,o),!1)}import{createReadStream as Em}from"node:fs";import{stat as Rm}from"node:fs/promises";import{basename as Cm,resolve as km}from"node:path";import{createInterface as Im}from"node:readline";var Am=1024*1024;function xm(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Cm(t).endsWith(".jsonl")}async function _a(e){if(!e||!xm(e))return null;try{let t=km(e),n=await Rm(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Am),o=[],s=Im({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 en(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function at(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function Mr(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}async function Ea(e){let t=Date.now();await Um(e);let{gitRoot:n}=e.manifest;await tn(e,n);let r=Mr(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:Ut(e.hookInput,e.manifest.manifest,r),envelopeFields:en(e),launchCwd:sr(e.hookInput,r),home:vm()}}function Sa(e){try{return z(Om(e))}catch{return null}}function Ra(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function ya(e,t){let n=e.replaceAll("\\","/");if(!Ra(n))return null;let r=z(e),o=z(t),s=Sa(e)??r,i=Sa(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function bm(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=ya(e,t)??(Ra(r)?null:r),i=ya(e,n);return{repositorySourcePath:s,userSourcePath:i}}function Qt(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=bm(e,t,n),c=i??a,l=c===null?null:o(c),u=l!==null&&c!==null?wm({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 wm(e){try{let t=e.inRepository?Pm(e.platformAgentId,e.sourcePath):(0,I.installationRootExternalKey)(e.installationId,(0,I.userConfigRootFromPath)(e.sourcePath));return t?(0,I.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function Ca(e,t,n){return He("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,De,e.manifest.collectorUrl,t.buildStartedAtMs,at(e,t.home))}var ka=new Set([...Object.values(ke),".github"]);function Pm(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=>ka.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function Tm(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,I.userConfigRootFromPath)(l);return(0,I.buildComponentReference)({installationRootExternalKey:(0,I.installationRootExternalKey)(r,_),installableKind:I.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),f=m.replaceAll("\\","/").split("/").at(-1);if(!(f===void 0||!ka.has(f)))try{return(0,I.buildComponentReference)({installationRootExternalKey:n,installableKind:I.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function Mm(...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 d(`WARN: ${n} failed open: ${r}`),t}function Nm(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 Lm(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var xe=new Set,it=null;async function Um(e){if(Yt())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(xe.has(t))return;if(!rr(n)){xe.add(t);return}let r=Be({sessionId:e.sessionId,hostname:Ge()});if(hi(r)){if(it){await it;return}it=(async()=>{if(xe.has(t)||!rr(n)){xe.add(t);return}if(!ko(n)){xe.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,p,m]=await Promise.allSettled([Ve(i),En(),Yn(r),Rn(),nr({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),f=W(c,null,"gitSnapshot"),_=W(l,"","detectVirt"),S=W(u,null,"probeCloud"),h=W(p,{},"hostEnv"),E=W(m,{commit:()=>{}},"resolveOperatorForSend");await tn(e,i,f);let T={identity:{host:Ge(),context:r,virt:_||null,cloud:S,git:f},host_env:h,env_vars:qn(),self_config:Lm(a,E.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await He("session_start",T,en(e),De,e.manifest.collectorUrl,s,at(e)),o&&(E.commit(),xe.add(t))}finally{Io(n)}})().finally(()=>{it=null}),await it}}async function tn(e,t,n){try{let r=n===void 0?await Ve(t):n;e.platformAgentId=await Es(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);d(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Dm(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Be({sessionId:e.sessionId,hostname:Ge()}),o=String(e.runnerPlatform),s=Mr(e),i=sr(e.hookInput,s),a=Ve(n),c=Yt()?Promise.resolve({commit:()=>{}}):nr({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[l,u,p,m,f,_,S]=await Promise.allSettled([a,En(),Yn(r),Rn(),Gn(e.manifest.manifest,n,o),a.catch(()=>null).then(w=>la(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:w?.remote??null})),c]),h=W(l,null,"gitSnapshot"),E=W(u,"","detectVirt"),T=W(p,null,"probeCloud"),H=W(m,{},"hostEnv"),v=W(f,[],"mcpDeclared"),x=W(_,Nm(o),"selfConfig"),U=W(S,{commit:()=>{}},"resolveOperatorForSend"),M=x.config;await tn(e,n,h);let j=g(e.hookInput,"model");j&&(M.model=j);let Z={identity:{host:Ge(),context:r,virt:E||null,cloud:T,git:h},host_env:H,env_vars:qn(),mcp:{declared:v},self_config:M,run_meta:{trigger:e.hookSource||"startup"},hook_input:Ut(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})};await He("session_start",Z,en(e),De,e.manifest.collectorUrl,t,at(e))&&(x.commit(),U.commit(),xe.add(e.manifest.installationId))}async function Hm(e){let t=Date.now(),{gitRoot:n}=e.manifest;await tn(e,n);let r=Mm(g(e.hookInput,"status"),g(e.hookInput,"stop_reason"),g(e.hookInput,"reason"),Xe(g(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await _a(g(e.hookInput,"transcript_path")):null,s=Ut(e.hookInput,e.manifest.manifest,Mr(e));o&&(s.model=o),await He("session_end",{status:r,...o?{model:o}:{},hook_input:s},en(e),De,e.manifest.collectorUrl,t,at(e))}function Ia(e,t,n,r){let o=r??ps({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=Qt(o,t.gitRoot,t.home,I.ComponentKind.SKILL,I.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&Un(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??As({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=Qt(i,t.gitRoot,t.home,I.ComponentKind.COMMAND,I.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function Fm(e,t,n){let r=kt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=Ia(e,t,o,r);return Ca(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 jm(e,t,n){return Promise.all(n.map(r=>{let o=Rs({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=Qt(o,t.gitRoot,t.home,I.ComponentKind.RULE,I.nativeKeyForRulePath,e),i=s.nativeKey??ks(r);return Ca(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var $m=[{kind:I.ComponentKind.SKILL,nativeKeyFn:I.nativeKeyForSkillPath},{kind:I.ComponentKind.RULE,nativeKeyFn:I.nativeKeyForRulePath},{kind:I.ComponentKind.COMMAND,nativeKeyFn:I.nativeKeyForCommandPath}];function Km(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=Hn(e.hookInput);if(r===null)return n.skillName===null?{}:Ia(e,t,n.skillName,null);for(let o of $m){let s=Qt(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===I.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===I.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var Bm=/mcp/i;function Gm(e,t,n,r){let o=Bm.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?Ji(t,n):zt(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 zm(e){let t=await Ea(e),n=Ds(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=Dn(e.hookInput),i=Gi(s,t.home),a=Fs(e.hookInput),c=Ms(e.runnerEvent),l=c===!1?js(e.hookInput,e.runnerEvent):null,u=await Gn(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=Xe(g(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:f}=$s(r,u.map(U=>U.name),p??""),_=Tm(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),u,p),S=_===void 0?Km(e,t,n):{},h=m===null?null:Ps(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),E=Gm(e,s,t.home,{hasMcpIdentity:!!m||!!f,declaredConfig:h}),T=_??S.componentReference,H=S.ruleName??n.ruleName,v=S.commandName??n.commandName,x=Hs(e.hookInput);await He("tool_invoked",{tool_name:r,skill_name:o,...H?{rule_name:H}:{},...v?{command_name:v}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...m?{mcp_server:m}:{},...f?{mcp_tool:f}:{},...E,...T?{component_reference:T}:{},...x?{subagent_type:x}:{},hook_input:t.hookInput},t.envelopeFields,De,e.manifest.collectorUrl,t.buildStartedAtMs,at(e,t.home))}async function Aa(e){switch(e.internalEvent){case"session_start":await Dm(e);return;case"session_end":await Hm(e);return;case"skill_invoked":{let t=fs(e.hookInput),n=Is(e.hookInput);if(t.length===0&&n.length===0)return;let r=await Ea(e);await Promise.all([t.length===0?void 0:Fm(e,r,t),n.length===0?void 0:jm(e,r,n)]);return}case"tool_invoked":await zm(e);return;default:return}}function xa(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function Oa(e,t,n,r){let o=t??await gn(ln),s=F(o,{}),i=g(s,"session_id")||g(s,"conversation_id"),a=await bo(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=Ns(s,a.manifest.platform,n),l=Ls(e,c.runnerEvent);if(!l){d(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:c.turnId,runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:a,platformAgentId:a.platformAgentId};if(xa(l)){d(`WARN: unsupported internal event '${l}'`);return}await Aa(u)}function Jm(e,t){if(R("EV_AI_HOOK_SYNC")==="1")return!0;let n=bt(e),r=F(t,{}),o=n.event??(g(r,"hook_event_name")||g(r,"event")),s=qe(r,o,void 0,n.runner);return wt(o,s)}async function va(e=process.argv.slice(2)){if(e[0]===st){try{await Zt(Ke)}catch{}return 0}if(e[0]===Xt){try{let t=bt(e.slice(1)),n=await Ke(),r=F(n,{}),o=t.event??(g(r,"hook_event_name")||g(r,"event"));if(Sn()||Wn(t.runner,r,o))return 0;await Oa(t.event,n,t.runner,Jn(t))}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await gn(ln),n=bt(e),r=Jn(n),o=F(t,{}),s=n.event??(g(o,"hook_event_name")||g(o,"event"));if(Sn()||Wn(n.runner,o,s)||!Vs(o,s,n.runner))return 0;Jm(e,t)?await Oa(n.event,t,n.runner,r):await ha(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{no()}return 0}function nn(){d("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),d(" configure [--url <\u2026/{orgToken}/hook>]"),d(" (manifest only \u2014 pair with marketplace plugins)"),d(" install --url <\u2026/{orgToken}/hook>"),d(" [--delivery npx|binary|local] [--force]"),d(" [--no-claude] [--no-cursor] [--no-codex]"),d(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),d(" (writes collector_url to shared manifest; hook commands use --runner only)"),d(" migrate-to-plugin"),d(" (strip ev-ai file hooks; keep collector manifest)"),d(" update (refresh binary pins from a local build; leaves hook configs alone)"),d(" uninstall"),d("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),d(" (--url/--token optional overrides; else collector_url from manifest)")}function ba(e){return e.includes("--help")||e.includes("-h")}async function Xm(e=process.argv.slice(2)){let[t,...n]=e;if(t===st){try{await Zt(Ke)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${ee}
43
- `),0):t==="configure"?ba(n)?(nn(),0):(await Xo(Do(n)),0):t==="install"?ba(n)?(nn(),0):(await Yo(Ho(n)),0):t==="migrate-to-plugin"?(await Qo(),0):t==="update"?(await qo(),0):t==="uninstall"?(await es(),0):t==="help"||t==="--help"||t==="-h"?(nn(),0):t===void 0?(nn(),1):va(e)}function Zm(e,t,n=Wm){if(!t)return!1;try{return e===qm(Vm(t)).href?!0:n(Ym(e))===n(t)}catch{return!1}}Zm(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&Xm().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);d(t),process.exit(1)});export{Zm as isCliEntrypoint,Xm as main};
27
+ `.trim(),lr=new Map;function Oi(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 vi(e){return e.toLowerCase().includes("token")}function bi(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=Oi(r.key),s=Oi(r.value);o&&s&&!vi(o)&&t.set(o,s)}return t}function $p(e){let t=jp(e);return t.search="mode=ro&immutable=1",t.href}function Kp(e){try{let t=Pi("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(Ft)??n.prepare(Ft);return bi(r.all?.())}finally{n.close?.()}}catch{return null}}function Bp(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 Gp(e){try{return Bp(()=>{let t=Pi("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return bi(n.prepare(Ft).all?.())}finally{n.close?.()}})}catch{return null}}function zp(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&&!vi(s)&&t.set(s,i)}return t}function Wp(e){try{let t=Dp("sqlite3",["-noheader","-batch","-separator"," ",e,Ft],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return zp(t)}catch{return null}}function wi(e){let t=lr.get(e);if(t)return t;if(!Hp(e)){let o=new Map;return lr.set(e,o),o}let n=$p(e),r=Kp(n)??Wp(n)??Gp(n)??new Map;return lr.set(e,r),r}var Jp="cursorAuth/cachedEmail",Vp="cursorAuth/stripeMembershipAuthId";function jt(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Yp(e=$t(),t=process.platform,n=process.env){let r=jt(n.VSCODE_PORTABLE);if(r)return ae(r,"user-data");let o=jt(n.VSCODE_APPDATA);if(o)return ae(o,"Cursor");switch(t){case"darwin":return ae(e,"Library","Application Support","Cursor");case"win32":return ae(jt(n.APPDATA)??ae(e,"AppData","Roaming"),"Cursor");default:return ae(jt(n.XDG_CONFIG_HOME)??ae(e,".config"),"Cursor")}}function qp(e=$t()){return ae(e,".cursor","cli-config.json")}function Xp(e=$t(),t=process.platform,n=process.env){return ae(Yp(e,t,n),"User","globalStorage","state.vscdb")}function ot(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Zp(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):ot(e.userId)}function Qp(e){return ot(e.email)??ot(e.authId)??Zp(e)}function ur(e){let t=ot(e.email),n=ot(e.displayName),r=Qp(e);return!r||G(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function ef(e){let n=U(qp(e),{}).authInfo;return!n||typeof n!="object"?null:ur(n)}function tf(e,t,n){let r=Xp(e,process.platform,t),o=Ii(e),s=ki(o);if(Ai(s,r,n))return ur({email:s?.email,authId:s?.auth_id});let i=wi(r),a=i.get(Jp)??null,c=i.get(Vp)??null;return xi(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),ur({email:a,authId:c})}function Ti(e=$t(),t=process.env,n=Date.now()){return ef(e)??tf(e,t,n)}import{createHash as nf}from"node:crypto";import{resolve as rf}from"node:path";function L(e){return nf("sha256").update(e).digest("hex").slice(0,16)}function dr(e){return L(rf(e))}function W(e,t){return`${e}\0${t}`}function Mi(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function st(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 L(n)}function sf(e,t,n="git_config",r=null){return L(`${e??""}|${t??""}|${r??""}|${n}`)}function af(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 cf(e,t=M){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return af(n)}function lf(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 ce(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function uf(e=process.env){let t=k(e.EV_AI_HOOK_OPERATOR_EMAIL),n=k(e.EV_AI_HOOK_OPERATOR_LOGIN),r=ce(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=ce(o,null,"github",o);if(s)return s;let i=k(e.GITLAB_USER_LOGIN),a=k(e.GITLAB_USER_EMAIL),c=ce(k(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let u=k(e.BUILD_REQUESTEDFOREMAIL),l=ce(k(e.BUILD_REQUESTEDFOR),u,"azure_devops",u??k(e.BUILD_REQUESTEDFORID));if(l)return l;let p=k(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=ce(k(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(m)return m;let f=k(e.BUILD_USER_EMAIL)??k(e.CHANGE_AUTHOR_EMAIL),_=ce(k(e.BUILD_USER)??k(e.CHANGE_AUTHOR),f,"jenkins",f??k(e.BUILD_USER_ID));if(_)return _;let S=k(e.CIRCLE_USERNAME),y=ce(S,null,"circleci",S);if(y)return y;let E=k(e.CODEBUILD_INITIATOR),x=ce(E,null,"codebuild",E);if(x)return x;let F=k(e.DRONE_COMMIT_AUTHOR_EMAIL),v=k(e.DRONE_COMMIT_AUTHOR),O=ce(v??k(e.DRONE_COMMIT_AUTHOR_NAME),F,"drone",F??v);if(O)return O;if(Ni(e.CLAUDE_CODE_REMOTE)||Ni(e.CURSOR_AGENT)){let D=k(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:D&&!G(null,D)?D:null,identity_source:"cloud"}}return null}function pr(e){return!!((e.git_user_name??e.git_user_email)&&!G(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 Ni(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function df(e,t,n){return e==="claude"?hi(t):e==="cursor"?Ti(t,n):e==="codex"?Ri(n,t):null}async function fr(e,t=M,n=process.env,r={}){let o=await cf(e,t),s=lf(n),i=pr(o)?o:s&&pr(s)?s:null,a=df(r.runnerPlatform,r.home??of(),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=uf(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:pr(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 mr(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??M,s=e.env??process.env,i=await fr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=sf(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),u=(n?bn(n):void 0)?.operator_identity_hash;if(!(r||u!==void 0&&u!==a||!u))return{commit:()=>{}};let f=n;return{operator:i,commit:()=>{f&&Mo(f,a,kt())}}}function gr(e){return e?!bn(e)?.operator_identity_hash:!0}function Li(e){return!0}import{existsSync as xm,readFileSync as Om}from"node:fs";import{homedir as Oa}from"node:os";import{join as je,resolve as Pm}from"node:path";import{basename as ym,join as Fe}from"node:path";import{dirname as Bi,resolve as Gt}from"node:path";import{existsSync as pf}from"node:fs";import{homedir as Hi}from"node:os";import{relative as Fi,resolve as Q,sep as _e}from"node:path";var ff=["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 mf(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:C("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function gf(e){let t={};for(let n of ff){let r=Ee(e,n);r!==void 0&&(t[n]=r)}return t}function Kt(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Q(e),r=Q(t),o=Fi(r,n);return!o||o==="."?".":o.startsWith(`..${_e}`)||o===".."||Q(r,o)!==n?null:o.split(_e).join("/")}function ji(e,t){let n=Fi(Q(t),Q(e)).split(_e).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function $i(e){return typeof e!="string"||e.length===0?null:Q(e).split(_e).join("/")}function hf(){let e=C("CURSOR_PROJECT_DIR");if(!e)return null;let t=Q(e);return pf(t)?t.split(_e).join("/"):null}function hr(e,t){return Kt(e,t)!==null}function _f(e,t){let n=Q(t??Hi(),".cursor").split(_e).join("/");return hr(e,n)}function Sf(e,t,n){return t!==null&&hr(e,t)?!0:t!==null&&_f(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&hr(e,n.gitRoot)?!0:t===null}function Ki(e,t){let n=$i(e.cwd);if(n!==null)return n;let r=Q(process.cwd()).split(_e).join("/"),o=hf();return Sf(r,o,t)?r:o??r}function _r(e,t={}){return Ki(e,t)}function Sr(e,t=Hi()){let n=Q(t).split(_e).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Ui(e,t,n){let r=$i(n.launchCwd)??Ki(t,n);e.cwd=Sr(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?Kt(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function Di(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([i,a])=>!i.startsWith("_")&&(typeof a=="string"||typeof a=="number"||typeof a=="boolean")).sort((i,a)=>Buffer.byteLength(JSON.stringify(i[1]),"utf8")-Buffer.byteLength(JSON.stringify(a[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[i,a]of o){let c={...s,[i]:a};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[i]=a}return s}function Bt(e,t,n={}){if(mf(t)){let o={...e};return delete o.cwd,delete o.transcript_path,Ui(o,e,n),Di(o,Qr)}let r=gf(e);return Ui(r,e,n),Di(r,Zr)}function yf(e){return typeof e=="string"&&e.length>0}function yr(e){let t=Gt(e.home),n=Gt(e.launchCwd),r=e.gitRoot?Gt(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&yf(e.remote)&&r!==null&&r!==t&&(i=r,o.add(r)),n!==t&&!o.has(n)&&(s.push({scope:"cwd",dir:n}),o.add(n)),i!==null&&s.push({scope:"repo",dir:i});let a=null,c=r!==null&&Kt(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let u=Bi(r);for(;;){let l=Gt(u);if(l===t)break;let p=Bi(l);if(p===l)break;if(e.hasProjectSpec(l)){s.push({scope:"parent",dir:l}),a=ji(l,n);break}u=p}}return{anchors:s,parentRel:a}}import{existsSync as Gi,readdirSync as Ef,realpathSync as Rf}from"node:fs";import{basename as Cf,dirname as If,relative as kf,resolve as Af,sep as xf}from"node:path";var Er=400,zt=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??le}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=Af(t).split(xf).join("/");return Sr(r,this.home)}let n=kf(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${L(If(t))}/${Cf(t)}`:n}claimFile(t){try{let n=Rf(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(!Gi(t))return[];try{return Ef(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(Gi(t))return U(t,n)}push(t){return this.components.length>=this.maxEntries?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Rr,readFileSync as Of,statSync as Pf}from"node:fs";import{basename as Wi,join as it,relative as Ji}from"node:path";var Cr=100*1024,vf=4;function bf(e){return e.length<=Cr?e:`${e.slice(0,Cr-1)}\u2026`}function wf(e){try{let t=Of(e),n=t.toString("utf8");return{hash:L(t),length:t.length,text:bf(n)}}catch{return null}}var zi={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Tf(e){return e in zi?zi[e]:"UNSPECIFIED"}function Wt(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=wf(t.absolutePath);if(!n)return!1;let r=t.name??Wi(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=Tf(t.kind);return s&&(o.trigger=s),e.push(o)}function Mf(e,t,n){let r=Ji(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Wi(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Oe(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Ir(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Ir(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:u}=t;if(!(o>vf))for(let l of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!l.isDirectory())continue;let f=it(r,l.name,c);if(Rr(f)){let _=Ji(n,it(r,l.name)).replace(/\\/g,"/");Wt(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:_||l.name});continue}Ir(e,{walkRoot:n,currentDir:it(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(l.isDirectory()){Ir(e,{walkRoot:n,currentDir:it(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(!l.isFile()||!u)continue;let p=l.name.toLowerCase();if(!u.some(f=>p.endsWith(f)))continue;let m=it(r,l.name);Wt(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:Mf(n,m,!0)})}}function Vi(e){for(let t of e)if(Rr(t))try{if(Pf(t).size>0)return t}catch{continue}return e.find(t=>Rr(t))}var Jt=Be(Le(),1);var Nf="<omitted>",Lf=["package_name","package_spec","package_version","package_version_source"],Yi=100,qi=120,Vt=[{raw:"tools",attr:"tools"},{raw:"autoApprove",attr:"auto_approve"},{raw:"auto_approve",attr:"auto_approve"},{raw:"alwaysAllow",attr:"always_allow"},{raw:"always_allow",attr:"always_allow"},{raw:"enabledTools",attr:"enabled_tools"},{raw:"enabled_tools",attr:"enabled_tools"},{raw:"disabledTools",attr:"disabled_tools"},{raw:"disabled_tools",attr:"disabled_tools"}],Xi=new Set(Vt.map(e=>e.attr)),Uf=["enabled","disabled"],Df=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Hf=new Set(["type","command","url","args","env","envVars","headers",...Uf,...Df,...Vt.map(e=>e.raw)]),Ff=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",...Lf,...Xi,...[...Xi].map(e=>`${e}_truncated`)]);function Zi(e,t){for(let n of t)Hf.has(n)||Ff.has(n)||(e[n]=Nf)}var jf=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,$f=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,Kf=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,Bf=/^bearer(?:\s+|$)/i;function Yt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Qi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function kr(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=Yt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Pe(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Gf(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,Jt.launchContainsCredentials)({kind:"url",url:e})||(0,Jt.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=ct([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,Jt.launchContainsCredentials)({kind:"url",url:r}):!0)}function ea(e,t,n){Gf(t,n)&&(e.launch_had_credentials=!0)}function zf(e){return Kf.test(e)||Bf.test(e)?"<redacted>":e.includes("://")?Pe(e):e}function ta(e){if(/^https?:\/\//i.test(e))return Pe(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${ta(e.slice(t+1))}`:zf(e)}function Wf(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return jf.test(t)||$f.test(t)}function ct(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(Wf(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(ta(r))}return t}function Jf(e){let t=Qi(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>qi?r.slice(0,qi):r))].sort();if(n.length!==0)return n.length>Yi?{names:n.slice(0,Yi),truncated:!0}:{names:n,truncated:!1}}function Vf(e){let t=Yt(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function na(e,t){let n=new Set;for(let{raw:r,attr:o}of Vt){if(n.has(o)||!(r in t))continue;let s=t[r];if(o==="auto_approve"&&typeof s=="boolean"){e.auto_approve=s,n.add(o);continue}let i=Jf(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function ra(e,t){let n=Yt(e),r={transport:t};if(!n)return r;Zi(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=Qi(n.args);a&&(r.command_or_url=Pe(a));let u=ct(c);u.length>0&&(r.args=u),ea(r,a,c);let l=Vf(n.env_http_headers),p=[...new Set([...kr(n.env),...kr(n.envVars),...kr(n.env_vars),...l.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();p.length>0&&(r.env_var_names=p),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let S of["headers","http_headers","env_http_headers"])if(n[S]!==void 0&&n[S]!==null){r.headers_present=!0;break}let m=typeof n.auth=="string"?n.auth:void 0;m&&(r.auth=m);let f=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;f&&(r.bearer_token_env_var=f);let _=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=_),na(r,n),r}function oa(e){let t=Yt(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 L(JSON.stringify({name:e,attributes:r,enabled:n}))}function De(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function at(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*\\[([^\\]]*)\\]`,"m").exec(e);return n?.[1]?[...n[1].matchAll(/"([^"]*)"|'([^']*)'/g)].map(r=>r[1]??r[2]??"").filter(r=>r.length>0):[]}function xr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Ar(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=De(n[1]);return r.length>0?r:void 0}function Yf(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],De(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
31
+ ${e}`);return s?.[1]&&r(s[1]),n}function sa(e){return xr(e,"enabled")===!1?!1:xr(e,"disabled")!==!0}function qf(e,t){let n={};for(let{raw:r,attr:o}of Vt){if(o==="auto_approve"){let i=xr(t,r);if(i!==void 0){n[r]=i;continue}}let s=at(t,r);s.length>0&&(n[r]=s)}na(e,n)}var Xf=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,Zf=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function Qf(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=Xf.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(Zf))o[1]&&t.add(o[1]);return[...t]}function ia(e,t){let n={transport:t};Zi(n,Qf(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?De(r[1]??""):void 0,i=o?De(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=at(e,"args");a&&(n.command_or_url=Pe(a));let u=ct(c);u.length>0&&(n.args=u),ea(n,a,c);let l=new Set;for(let E of e.split(`
33
+ `)){let x=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);x?.[1]&&l.add(x[1])}let p=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(p?.[1])for(let E of p[1].split(",")){let x=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);x?.[1]&&l.add(x[1])}let m=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
34
+ ${e}`);if(m?.[1])for(let E of m[1].split(`
35
+ `)){let x=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(E);x?.[1]&&l.add(x[1])}for(let E of at(e,"env_vars"))l.add(E);let f=Yf(e,"env_http_headers");for(let[,E]of f)E.length>0&&l.add(E);let _=Ar(e,"bearer_token_env_var");_&&(l.add(_),n.bearer_token_env_var=_),l.size>0&&(n.env_var_names=[...l].sort()),f.length>0&&(n.env_http_header_names=[...new Set(f.map(([E])=>E))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let S=Ar(e,"auth");S&&(n.auth=S);let y=Ar(e,"default_tools_approval_mode");return y&&(n.default_tools_approval_mode=y),qf(n,e),n}var em=300,tm=256;function aa(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function qt(e){let t=[],n="",r=null;for(let o of e){if(r){o===r?r=null:n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}function ca(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function nm(e){return ca(e,em)}function la(e,t){let n=aa(e.trim(),t),r=qt(n);if(r.length===0)return"";let[o,...s]=r,i=Pe(o),a=ct(s);return nm([i,...a].join(" "))}function ua(e,t){if(typeof e!="string")return null;let n=aa(e.trim(),t),r=qt(n)[0];if(!r)return null;let o=Pe(r);return o.length===0?null:ca(o,tm)}function rm(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 om(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 sm(e,t,n,r){let o=e.componentPath(t);for(let[s,i]of Object.entries(n))if(!(!Array.isArray(i)||e.truncated))for(let a of i){if(!a||typeof a!="object"||e.truncated)continue;let c=a;for(let u of om(c)){if(e.truncated)return;let l=u.command??u.bash??u.prompt??u.powershell??c.powershell??"",p=rm({type:u.type??c.type,command:u.command??c.command,bash:u.bash??c.bash,powershell:u.powershell??c.powershell,prompt:u.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",f=L(l),_=m?`${s}:${m}:${p}:${f}`:`${s}:${p}:${f}`,S=`${s}|${m}|${p}|${l}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:L(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:f,...p!=="prompt"&&l.trim()?{command:la(l,e.home)}:{}}})}}}function He(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||sm(e,t,r.hooks,n)}import{existsSync as dm,readFileSync as pm}from"node:fs";var Se=Be(Le(),1);import{createHash as im}from"node:crypto";import{join as lt}from"node:path";function am(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
36
+ `);return im("sha512").update(t).digest("hex").slice(0,16)}function cm(e){let t=process.platform==="win32"?lt(C("LOCALAPPDATA")??e,"npm-cache"):lt(e,".npm"),n=C("npm_config_cache")??C("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function da(e){return typeof e=="string"&&e.length>0&&e.length<=Se.PACKAGE_FIELD_MAX?e:null}function lm(e,t,n){let r=am(e);for(let o of cm(n)){let s=lt(o,"_npx",r),i=U(lt(s,"node_modules",...t.split("/"),"package.json"),{}),a=da(i.version);if(a!==null)return a;let c=U(lt(s,"package-lock.json"),{}),u=da(c.packages?.[`node_modules/${t}`]?.version);if(u!==null)return u}return null}function um(e){return e.length<=Se.PACKAGE_FIELD_MAX?e:`${e.slice(0,Se.PACKAGE_FIELD_MAX-1)}\u2026`}function Pr(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,Se.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,Se.packageNameFromSpec)(o);if(s===null)return null;let i=lm(r,s,n);return{package_name:s,package_spec:um(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function pa(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=qt(e.trim());return n===void 0?null:Pr(n,r,t)}function Xt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=Array.isArray(n.args)?n.args.filter(o=>typeof o=="string"):[];return Pr(typeof n.command=="string"?n.command:null,r,t)}function fa(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:Pr(De(n[1]??""),at(e,"args"),t)}function fm(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 ma(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=fm(a),u=ra(a,c);Object.assign(u,Xt(a,e.home)??{});let l=oa(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:Or(i,u,l),origin:n,enabled:l,attributes:u})}}function ga(e,t,n){if(!dm(t)||!e.claimFile(t))return;let r;try{r=pm(t,"utf8")}catch{return}let o=e.componentPath(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),u=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),l=u===-1?c:c.slice(0,u),p="unknown";/^\s*url\s*=/m.test(l)?p="http":/^\s*command\s*=/m.test(l)&&(p="stdio");let m=ia(l,p);Object.assign(m,fa(l,e.home)??{});let f=sa(l);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:Or(a,m,f),origin:n,enabled:f,attributes:m})}}import{existsSync as mm,readdirSync as gm}from"node:fs";import{join as B}from"node:path";var ha=50;function vr(e,t,n,r){if(!mm(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(ha,()=>{Oe(e,{dir:B(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Oe(e,{dir:B(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Oe(e,{dir:B(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});He(e,B(t,"hooks","hooks.json"),n),He(e,B(t,"hooks.json"),n);let i=e.components.length-o,a=s>=ha;return{componentCount:i,expandTruncated:a}}function br(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 _a(e){let t=B(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(B(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let u=Array.isArray(c)?c:[c],l=u[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",f=typeof l.version=="string"?l.version:"",_=typeof l.scope=="string"?l.scope:"user",S=`plugin:${a}`,y=0,E=!1;for(let x of u)if(typeof x.installPath=="string"&&x.installPath.length>0){let F=vr(e,x.installPath,S,p);y+=F.componentCount,E=E||F.expandTruncated}br(e,{pluginKey:a,rowPath:i,enabled:p,scope:_,version:f||void 0,marketplace:m||void 0,componentCount:y,expandTruncated:E,contentHash:L(`${a}|${f}|${_}|${p}|${y}`)})}}function hm(e){let t=e,n="";try{let r=gm(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=B(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=B(e,s),n=s)}}catch{}return{installPath:t,version:n}}var _m=/^\d+$/;function Sm(e){let t=e.filter(n=>!_m.test(n.pluginId));return t.length>0?t:e}function Sa(e){let t=[{base:B(e.home,".cursor/plugins/local"),scope:"local"},{base:B(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=B(n,o.name),u=`plugin:${a}`,{componentCount:l,expandTruncated:p}=vr(e,c,u,!0);br(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:l,expandTruncated:p,contentHash:L(`${a}|local|${l}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(B(n,s))){if(!a.isDirectory())continue;let c=B(n,s,a.name),{installPath:u,version:l}=hm(c);i.push({pluginId:a.name,installPath:u,version:l})}for(let a of Sm(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,u=`plugin:${c}`,{componentCount:l,expandTruncated:p}=vr(e,a.installPath,u,!0);br(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:l,expandTruncated:p,contentHash:L(`${c}|${a.version}|${l}`)})}}}function Em(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Oe(e,{dir:Fe(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Oe(e,{dir:Fe(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=Vi(i.map(c=>Fe(r,c)));a&&Wt(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:ym(a)})}for(let i of gs(n))He(e,Fe(r,i),o);for(let i of n.mcpJson??[])ma(e,Fe(r,i),o);for(let i of n.mcpToml??[])ga(e,Fe(r,i),o);if(s){if(n.managed)for(let i of It(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&He(e,i,o);n.plugins==="claude"?_a(e):n.plugins==="cursor"&&Sa(e)}}function ya(e,t){try{let n=new zt(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)Em(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 wr(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=ya(t,{layouts:Object.values(Te),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:le,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(fe),u=yr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:l=>_s(c,l)});i=u.parentRel;for(let l of u.anchors){let p=dr(l.dir);if(o!==void 0&&!o(l.scope,p))continue;let m=ya(t,{layouts:c,levelDir:l.dir,origin:l.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Er,scopeRef:p});m&&(r[l.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function Tr(e,t,n={}){let r=n.truncated===!0,o=st(e),s=new Set(e.map(l=>W(l.path,l.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let l of e){let p=W(l.path,l.name);c[p]!==l.content_hash&&a.push(l)}let u=[];if(!r){for(let l of Object.keys(c))if(!s.has(l)){let p=Mi(l);p&&u.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:u,unchanged:a.length===0&&u.length===0}}var Ra=2*1024*1024,Rm=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Mr(e,t,n){let r=new Set(t.map(s=>W(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(W(s.path,s.name))||o.push(s));return o}function Nr(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 Ea(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Ca(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function Lr(e,t=Ra){let n=[],r=[];for(let l of e)Rm.has(l.kind)?n.push(l):r.push(l);r.sort((l,p)=>(l.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,u=[];for(let l of o){let p=s.length>0?1:0,m=Ea(l)+p;if(i+m<=t){s.push(l),i+=m,l.text!==void 0&&u.push(l.content_hash);continue}if(l.text!==void 0){let f=Ca(l),_=Ea(f)+p;if(i+_<=t){s.push(f),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:u}}function Ur(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Ca(n))}var Cm=["user","cwd","repo","parent"];function Dr(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let v of Cm){let O=t.scopes[v];if(!O)continue;let D=n(v,O.scopeRef),N=D.components,$=Tr(O.components,N,{forceFull:N===void 0,truncated:O.truncated}),ee=new Set(D.textHashes),H=Mr(O.components,$.upserts,ee),w=Ur([...$.upserts,...H],ee);s.push({scope:v,walk:O,delta:$,outgoing:w,outgoingKeys:new Set(w.map(R=>W(R.path,R.name))),deliveredTextHashes:ee,cachedComponents:N})}let i=s.flatMap(v=>v.outgoing),a=Lr(i,o),c=new Set(a.components.map(v=>W(v.path,v.name))),u=[],l=[],p=[],m=[],f=[],_=[],S=[];for(let v of s){let{scope:O,walk:D,delta:N}=v;_.push(...D.components),u.push(O);let $=a.components.filter(R=>v.outgoingKeys.has(W(R.path,R.name))),ee=[...v.outgoingKeys].some(R=>!c.has(R)),H=N.truncated||ee;H?p.push(O):N.full&&l.push(O),m.push(...$),!N.full&&!H&&f.push(...N.removed);let w=N.full?{}:{...v.cachedComponents??{}};if(!H)for(let R of N.removed)delete w[W(R.path,R.name)];for(let R of $)w[W(R.path,R.name)]=R.content_hash;S.push({scope:O,scopeRef:D.scopeRef,components:w,textHashes:Nr(v.deliveredTextHashes,$.filter(R=>R.text!==void 0).map(R=>R.content_hash),D.components),collectedAtMs:r,included:$.length>0||N.removed.length>0&&!H||N.full})}let y={user_spec_hash:st(_),user_spec_count:_.length,user_spec_truncated:p.length>0};u.length>0&&(y.user_spec_scopes=u,y.user_spec_full_scopes=l,y.user_spec_truncated_scopes=p,y.user_spec_cwd_in_git_repo=t.cwdInGitRepo),l.length>0&&l.length===u.length&&(y.user_spec_full=!0),m.length>0&&(y.user_spec=m),f.length>0&&(y.user_spec_removed=f),a.textDeferredCount>0&&(y.user_spec_text_deferred=a.textDeferredCount);let E=t.scopes.cwd;E&&(y.user_spec_cwd_scope_ref=E.scopeRef);let x=t.scopes.repo;x&&(y.user_spec_repo_scope_ref=x.scopeRef);let F=t.scopes.parent;return F&&(y.user_spec_parent_scope_ref=F.scopeRef,t.parentRel&&(y.user_spec_parent_rel=t.parentRel)),{fields:y,scopes:S}}var dt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function Zt(e){return e==="cwd"||e==="repo"||e==="parent"}function ut(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Hr(e){return!ut(e)||!ut(e.components)||!Object.values(e.components).every(t=>typeof t=="string")||!Array.isArray(e.text_hashes)||!e.text_hashes.every(t=>typeof t=="string")?!1:typeof e.collected_at_ms=="number"&&Number.isFinite(e.collected_at_ms)}function Ia(e){return Im(e)}function ka(e){return km(e)}function Aa(e){return Am(e)}function Im(e){if(!ut(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function km(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function Fr(e,t){if(!ut(e))return;let n=e[t];return Hr(n)?n:void 0}function Am(e){if(!ut(e))return{};let t={};for(let[n,r]of Object.entries(e))Hr(r)&&(t[n]=r);return t}function jr(e,t=20){let n=[];for(let[r,o]of Object.entries(e))Hr(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 vm=200,xa=200,bm=["allow","deny","ask"],wm=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Kr="<path>",Tm=new RegExp(`${Kr}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Mm(e){let t=e.replace(wm,Kr).replace(Tm,Kr);return t.length>xa?`${t.slice(0,xa)}...`:t}function en(e){let t=U(e,{}),n=[];for(let r of bm)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Mm(o),mode:r});return{model:t.model??"",permissionKeys:n}}function Nm(e){let{serverManaged:t,fileBased:n}=_n(process.platform,e),r=en(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=en(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function Lm(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 Um=10,Dm="self-config-cache.json",Pa=2;function tn(){return C("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Hm(){return C("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function Fm(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Ge}var jm={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function $m(e,t=M){let n=jm[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 Km(e=Oa()){return je(e,".ev-ai","agent-hook",Dm)}function Bm(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
38
+ `);return L(n)}function Qt(e,t,n=!1){let r=Bm(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 $r(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>je(e,a)),...n]){let a=Pm(i);if(s.has(a))continue;s.add(a);let c=Cn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function Gm(e){return xm(e)?j(Om(e,"utf8"),{}):{}}function zm(e,t){try{X(e,`${JSON.stringify(t)}
39
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: self-config cache write failed open: ${r}`)}}function Wm(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(Zt(t))return Fr(e[dt[t]],n)?.collected_at_ms}function Jm(e,t,n){if(t==="user")return{components:Ia(e.user_spec_components),textHashes:ka(e.user_spec_text_hashes)};if(!Zt(t))return{components:void 0,textHashes:[]};let r=Fr(e[dt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function Vm(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=Pa,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(!Zt(s.scope))continue;let i=dt[s.scope],a=Aa(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]=jr(a)}}return o}async function va(e,t=process.cwd(),n=Oa(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await $m(e),a="",c=[];if(o){let H=Nm(n),w=en(je(n,".claude/settings.json")),R=en(je(t,".claude/settings.local.json"));a=H.model||R.model||w.model,c=Lm([...H.permissionKeys,...w.permissionKeys,...R.permissionKeys]).slice(0,vm)}let u={present:!1,size:0},l=H=>{let w=[],R=!1;for(let te of H){let gt=go(je(n,te));if(w=w.concat(gt.entries),R=R||gt.truncated,w.length>=le){w=w.slice(0,le),R=!0;break}}return{entries:w,truncated:R}},p=Km(n),m=Gm(p),f=m[e]??{},_=(f.send_count??0)+1,S=_>0&&_%Um===0,y=H=>S?void 0:f[H],E=l(ge.skills),x=l(ge.subagents),F=l(ge.commands),v=l(ge.rules),O={skills:Qt(E.entries,y("skills"),E.truncated),subagents:Qt(x.entries,y("subagents"),x.truncated),commands:Qt(F.entries,y("commands"),F.truncated),rules:Qt(v.entries,y("rules"),v.truncated)},D={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:O.skills,subagents:O.subagents,commands:O.commands,rules:O.rules,memory:$r(n,ge.memory),settings:$r(n,ge.settings,Ss(n)),mcp:$r(n,ge.mcp)},local_settings:o?Cn(je(t,".claude/settings.local.json")):u},N=null,$=r.nowMs??Date.now();if(!tn()){let H=f.user_spec_layout_version!==Pa,w=wr(e,n,{launchCwd:Hm()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(R,te)=>H||Fm(Wm(f,R,te),$)});if(Object.keys(w.scopes).length>0){let R=Dr({collected:w,cacheFor:(te,gt)=>H?{components:void 0,textHashes:[]}:Jm(f,te,gt),nowMs:$});Object.assign(D,R.fields),N={hash:R.fields.user_spec_hash,home:R.scopes.find(te=>te.scope==="user")??null,project:R.scopes.filter(te=>te.scope!=="user")}}}let ee=Vm(f,O,_,N);return{config:D,commit:()=>{m[e]=ee,zm(p,m)}}}function $e(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:kt(),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:ne,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as wa}from"node:fs";import{spawn as Ta}from"node:child_process";import{fileURLToPath as qm}from"node:url";import{gzipSync as Ym}from"node:zlib";function Br(e){return C("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<eo?{body:e}:{body:Ym(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function nn(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function ba(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var pt="__post",rn="__work";async function Xm(e,t,n={}){if(C("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off")return e;let r=await fr(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 Zm(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 Ma(e){switch(e){case"session_start":return Yr;case"session_end":return qr;case"tool_invoked":case"skill_invoked":return fn;default:return fn}}function Qm(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
40
+ ${n}`}function Na(e,t=[],n=process.execPath,r=import.meta.url,o=wa){if(yt(n))return{command:n,args:[e,...t]};let s=qm(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function eg(e=process.execPath,t=import.meta.url,n=wa){return Na(pt,[],e,t,n)}function tg(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 on(e,t=fetch){let n=await e(),r=tg(n);if(!r)return;let{meta:o,body:s}=r,i=Br(s),a=nn(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function ng(e,t,n,r=fetch){let o=Ma(e),s=Br(t),i=nn(s.contentEncoding),a=ba(s.body);d(`POST event=${e} url=${gn(n)} size=${a} encoding=${s.contentEncoding??"identity"} platform=${process.platform}`);let c=Date.now();try{let u=await r(n,{method:"POST",headers:i,body:s.body,signal:AbortSignal.timeout(o)});if(!u.ok&&s.contentEncoding==="gzip"&&(u.status===400||u.status===415)){try{await u.text()}catch{}d(`POST gzip rejected http=${u.status} \u2014 retrying uncompressed`),u=await r(n,{method:"POST",headers:nn(),body:t,signal:AbortSignal.timeout(o)})}let l=Date.now()-c;if(u.ok)return d(`POST outcome=ok elapsed_ms=${l} http=${u.status}`),!0;let p=(await u.text()).slice(0,200).replace(/[\n\r]/g,"");return d(`POST outcome=fail elapsed_ms=${l} http=${u.status} body=${p}`),!1}catch(u){let l=Date.now()-c,p=u instanceof Error?u.message:String(u);return d(`POST outcome=fail elapsed_ms=${l} http=000 body=${p}`),!1}}async function La(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){d(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},Xr),u=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>u()),s.stdin.once("error",()=>u())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return d(`WARN: ${o} spawn failed open: ${i}`),null}}async function rg(e,t,n,r=Ta,o=eg){let s=Ma(e),i=Qm(n,s,t),{command:a,args:c}=o();return La(a,c,i,r,"detached post")}async function Ua(e,t,n=Ta,r=Na){let{command:o,args:s}=r(rn,t);return La(o,s,e,n,"detached work")}async function Ke(e,t,n,r,o,s,i){if(!o)return d("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Rt(o))return d(`WARN: collector URL blocked (https required): ${gn(o)}`),!1;let a=await Xm(t,n.runnerPlatform,i),c=r(e,a,n);s!==void 0&&(c.build_ms=Math.max(0,Date.now()-s));let u=`${JSON.stringify(c)}
42
+ `,l=C("EV_AI_HOOK_DEBUG");l==="full"?d(`DEBUG envelope=${JSON.stringify(c)}`):l==="1"&&d(`DEBUG summary=${Zm(c,Buffer.byteLength(u,"utf8"))}`);let p=process.argv.includes(rn),m=C("EV_AI_HOOK_SYNC")==="1";return Dt(n.runnerEvent,n.runnerPlatform)||p||m?ng(e,u,o):(await rg(e,u,o),!1)}import{createReadStream as og}from"node:fs";import{stat as sg}from"node:fs/promises";import{basename as ig,resolve as ag}from"node:path";import{createInterface as cg}from"node:readline";var lg=1024*1024;function ug(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&ig(t).endsWith(".jsonl")}async function Da(e){if(!e||!ug(e))return null;try{let t=ag(e),n=await sg(t);if(!n.isFile())return null;let r=Math.max(0,n.size-lg),o=[],s=cg({input:og(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let i of s)i.length!==0&&o.push(i);r>0&&o.length>0&&o.shift();for(let i=o.length-1;i>=0;i--){let a=o[i];if(a)try{let c=JSON.parse(a);if(c.type!=="assistant")continue;let u=c.message;if(!u||typeof u!="object")continue;let l=u.model;if(typeof l=="string"&&l.length>0)return l}catch{continue}}return null}catch{return null}}function an(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function mt(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function Gr(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}async function ja(e){let t=Date.now();await Eg(e);let{gitRoot:n}=e.manifest;await cn(e,n);let r=Gr(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:Bt(e.hookInput,e.manifest.manifest,r),envelopeFields:an(e),launchCwd:_r(e.hookInput,r),home:pg()}}function Ha(e){try{return z(dg(e))}catch{return null}}function $a(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function Fa(e,t){let n=e.replaceAll("\\","/");if(!$a(n))return null;let r=z(e),o=z(t),s=Ha(e)??r,i=Ha(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function fg(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=Fa(e,t)??($a(r)?null:r),i=Fa(e,n);return{repositorySourcePath:s,userSourcePath:i}}function sn(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=fg(e,t,n),c=i??a,u=c===null?null:o(c),l=u!==null&&c!==null?mg({installableKind:r,sourcePath:c,nativeKey:u,inRepository:i!==null,platformAgentId:s.platformAgentId,installationId:s.manifest.installationId}):void 0;return{sourcePath:c,nativeKey:u,componentReference:l}}function mg(e){try{let t=e.inRepository?gg(e.platformAgentId,e.sourcePath):(0,A.installationRootExternalKey)(e.installationId,(0,A.userConfigRootFromPath)(e.sourcePath));return t?(0,A.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function Ka(e,t,n){return Ke("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,$e,e.manifest.collectorUrl,t.buildStartedAtMs,mt(e,t.home))}var Ba=new Set([...Object.values(xe),".github"]);function gg(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=>Ba.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function hg(e,t,n,r,o,s,i){if(e===null||t===null||!(i!==null||/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||/^MCP:.+__.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let c=s.find(_=>_.name.toLowerCase()===t.toLowerCase()),u=c?.sourcePath??(c?.source==="claude_json_user"?".claude.json":c?.source==="cursor_mcp_user"?".cursor/mcp.json":c?.source==="codex_toml_user"||c===void 0&&o==="codex"?".codex/config.toml":void 0);if((c?.scope==="user"||c?.source==="claude_json_user"||c?.source==="cursor_mcp_user"||c?.source==="codex_toml_user"||c===void 0&&o==="codex")&&u)try{let _=(0,A.userConfigRootFromPath)(u);return(0,A.buildComponentReference)({installationRootExternalKey:(0,A.installationRootExternalKey)(r,_),installableKind:A.ComponentKind.INTERFACE,sourcePath:u,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),f=m.replaceAll("\\","/").split("/").at(-1);if(!(f===void 0||!Ba.has(f)))try{return(0,A.buildComponentReference)({installationRootExternalKey:n,installableKind:A.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function _g(...e){for(let t of e)if(t)return t;return null}function J(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return d(`WARN: ${n} failed open: ${r}`),t}function Sg(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 yg(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var ve=new Set,ft=null;async function Eg(e){if(tn())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(ve.has(t))return;if(!gr(n)){ve.add(t);return}let r=Ve({sessionId:e.sessionId,hostname:Ye()});if(Li(r)){if(ft){await ft;return}ft=(async()=>{if(ve.has(t)||!gr(n)){ve.add(t);return}if(!No(n)){ve.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,u,l,p,m]=await Promise.allSettled([et(i),An(),ar(r),xn(),mr({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),f=J(c,null,"gitSnapshot"),_=J(u,"","detectVirt"),S=J(l,null,"probeCloud"),y=J(p,{},"hostEnv"),E=J(m,{commit:()=>{}},"resolveOperatorForSend");await cn(e,i,f);let x={identity:{host:Ye(),context:r,virt:_||null,cloud:S,git:f},host_env:y,env_vars:cr(),self_config:yg(a,E.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await Ke("session_start",x,an(e),$e,e.manifest.collectorUrl,s,mt(e)),o&&(E.commit(),ve.add(t))}finally{Lo(n)}})().finally(()=>{ft=null}),await ft}}async function cn(e,t,n){try{let r=n===void 0?await et(t):n;e.platformAgentId=await Fs(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);d(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Rg(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Ve({sessionId:e.sessionId,hostname:Ye()}),o=String(e.runnerPlatform),s=Gr(e),i=_r(e.hookInput,s),a=et(n),c=tn()?Promise.resolve({commit:()=>{}}):mr({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[u,l,p,m,f,_,S]=await Promise.allSettled([a,An(),ar(r),xn(),nr(e.manifest.manifest,n,o),a.catch(()=>null).then(w=>va(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:w?.remote??null})),c]),y=J(u,null,"gitSnapshot"),E=J(l,"","detectVirt"),x=J(p,null,"probeCloud"),F=J(m,{},"hostEnv"),v=J(f,[],"mcpDeclared"),O=J(_,Sg(o),"selfConfig"),D=J(S,{commit:()=>{}},"resolveOperatorForSend"),N=O.config;await cn(e,n,y);let $=g(e.hookInput,"model");$&&(N.model=$);let ee={identity:{host:Ye(),context:r,virt:E||null,cloud:x,git:y},host_env:F,env_vars:cr(),mcp:{declared:v},self_config:N,run_meta:{trigger:e.hookSource||"startup"},hook_input:Bt(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})};await Ke("session_start",ee,an(e),$e,e.manifest.collectorUrl,t,mt(e))&&(O.commit(),D.commit(),ve.add(e.manifest.installationId))}async function Cg(e){let t=Date.now(),{gitRoot:n}=e.manifest;await cn(e,n);let r=_g(g(e.hookInput,"status"),g(e.hookInput,"stop_reason"),g(e.hookInput,"reason"),rt(g(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await Da(g(e.hookInput,"transcript_path")):null,s=Bt(e.hookInput,e.manifest.manifest,Gr(e));o&&(s.model=o),await Ke("session_end",{status:r,...o?{model:o}:{},hook_input:s},an(e),$e,e.manifest.collectorUrl,t,mt(e))}function Ga(e,t,n,r){let o=r??ks({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=sn(o,t.gitRoot,t.home,A.ComponentKind.SKILL,A.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&Kn(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??Gs({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=sn(i,t.gitRoot,t.home,A.ComponentKind.COMMAND,A.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function Ig(e,t,n){let r=wt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=Ga(e,t,o,r);return Ka(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 kg(e,t,n){return Promise.all(n.map(r=>{let o=js({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=sn(o,t.gitRoot,t.home,A.ComponentKind.RULE,A.nativeKeyForRulePath,e),i=s.nativeKey??Ks(r);return Ka(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var Ag=[{kind:A.ComponentKind.SKILL,nativeKeyFn:A.nativeKeyForSkillPath},{kind:A.ComponentKind.RULE,nativeKeyFn:A.nativeKeyForRulePath},{kind:A.ComponentKind.COMMAND,nativeKeyFn:A.nativeKeyForCommandPath}];function xg(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=Gn(e.hookInput);if(r===null)return n.skillName===null?{}:Ga(e,t,n.skillName,null);for(let o of Ag){let s=sn(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===A.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===A.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var Og=/mcp/i;function Pg(e,t,n,r){let o=Og.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?pa(t,n):Xt(r.declaredConfig,n);return s===null?{}:Object.fromEntries(Object.entries(s).filter(i=>typeof i[1]=="string").map(([i,a])=>[`mcp_${i}`,a]))}async function vg(e){let t=await ja(e),n=ni(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=Bn(e.hookInput),i=ua(s,t.home),a=oi(e.hookInput),c=Zs(e.runnerEvent),u=c===!1?si(e.hookInput,e.runnerEvent):null,l=await nr(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=rt(g(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:f}=ii(r,l.map(D=>D.name),p??""),_=hg(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),l,p),S=_===void 0?xg(e,t,n):{},y=m===null?null:qs(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),E=Pg(e,s,t.home,{hasMcpIdentity:!!m||!!f,declaredConfig:y}),x=_??S.componentReference,F=S.ruleName??n.ruleName,v=S.commandName??n.commandName,O=ri(e.hookInput);await Ke("tool_invoked",{tool_name:r,skill_name:o,...F?{rule_name:F}:{},...v?{command_name:v}:{},success:c,duration_ms:a,...i?{executable:i}:{},...u?{failure_reason:u}:{},...m?{mcp_server:m}:{},...f?{mcp_tool:f}:{},...E,...x?{component_reference:x}:{},...O?{subagent_type:O}:{},hook_input:t.hookInput},t.envelopeFields,$e,e.manifest.collectorUrl,t.buildStartedAtMs,mt(e,t.home))}async function za(e){switch(e.internalEvent){case"session_start":await Rg(e);return;case"session_end":await Cg(e);return;case"skill_invoked":{let t=As(e.hookInput),n=Bs(e.hookInput);if(t.length===0&&n.length===0)return;let r=await ja(e);await Promise.all([t.length===0?void 0:Ig(e,r,t),n.length===0?void 0:kg(e,r,n)]);return}case"tool_invoked":await vg(e);return;default:return}}function Wa(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function Ja(e,t,n,r){let o=t??await En(mn),s=j(o,{}),i=g(s,"session_id")||g(s,"conversation_id"),a=await $o(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=Qs(s,a.manifest.platform,n),u=ei(e,c.runnerEvent);if(!u){d(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let l={hookInput:s,sessionId:c.sessionId,turnId:c.turnId,runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:u,manifest:a,platformAgentId:a.platformAgentId};if(Wa(u)){d(`WARN: unsupported internal event '${u}'`);return}await za(l)}function bg(e,t){if(C("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ut(e),r=j(t,{}),o=n.event??(g(r,"hook_event_name")||g(r,"event")),s=nt(r,o,void 0,n.runner);return Dt(o,s)}async function Va(e=process.argv.slice(2)){if(e[0]===pt){try{await on(Je)}catch{}return 0}if(e[0]===rn){try{let t=Ut(e.slice(1)),n=await Je(),r=j(n,{}),o=t.event??(g(r,"hook_event_name")||g(r,"event"));if(In()||sr(t.runner,r,o))return 0;await Ja(t.event,n,t.runner,or(t))}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await En(mn),n=Ut(e),r=or(n),o=j(t,{}),s=n.event??(g(o,"hook_event_name")||g(o,"event"));if(In()||sr(n.runner,o,s)||!fi(o,s,n.runner))return 0;bg(e,t)?await Ja(n.event,t,n.runner,r):await Ua(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{mo()}return 0}function ln(){d("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),d(" configure [--url <\u2026/{orgToken}/hook>]"),d(" (manifest only \u2014 pair with marketplace plugins)"),d(" install --url <\u2026/{orgToken}/hook>"),d(" [--delivery npx|binary|local] [--force]"),d(" [--no-claude] [--no-cursor] [--no-codex]"),d(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),d(" (writes collector_url to shared manifest; hook commands use --runner only)"),d(" migrate-to-plugin"),d(" (strip ev-ai file hooks; keep collector manifest)"),d(" update (refresh binary pins from a local build; leaves hook configs alone)"),d(" uninstall"),d("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),d(" (--url/--token optional overrides; else collector_url from manifest)")}function Ya(e){return e.includes("--help")||e.includes("-h")}async function Lg(e=process.argv.slice(2)){let[t,...n]=e;if(t===pt){try{await on(Je)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${ne}
43
+ `),0):t==="configure"?Ya(n)?(ln(),0):(await ls(Yo(n)),0):t==="install"?Ya(n)?(ln(),0):(await as(qo(n)),0):t==="migrate-to-plugin"?(await ds(),0):t==="update"?(await cs(),0):t==="uninstall"?(await ps(),0):t==="help"||t==="--help"||t==="-h"?(ln(),0):t===void 0?(ln(),1):Va(e)}function Ug(e,t,n=wg){if(!t)return!1;try{return e===Ng(Tg(t)).href?!0:n(Mg(e))===n(t)}catch{return!1}}Ug(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&Lg().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);d(t),process.exit(1)});export{Ug as isCliEntrypoint,Lg as main};