@ev-ai/agent-hook 1.2.0 → 1.2.2
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/README.md +33 -2
- package/dist/cli.mjs +16 -16
- package/dist/hook.mjs +18 -18
- package/dist/launcher-update.mjs +4 -4
- package/dist/launcher.mjs +3 -2
- package/dist/managed-hooks-snippet.cjs +7 -7
- package/dist/managed-hooks-snippet.mjs +6 -6
- package/dist/plugin-hooks.mjs +6 -6
- package/package.json +2 -2
package/dist/cli.mjs
CHANGED
|
@@ -8,23 +8,23 @@ var fu=Object.create;var Ao=Object.defineProperty;var mu=Object.getOwnPropertyDe
|
|
|
8
8
|
`).map(_=>_.trim()).filter(Boolean).join(" ")).filter(d=>d.length>0).join(`
|
|
9
9
|
|
|
10
10
|
`):l.join(`
|
|
11
|
-
`).trimEnd();return(0,X.usableCatalogText)(m)}});var Ii=Oe(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=x.COMPONENT_INSPECTION_TEXT_MAX_BYTES=x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;x.fitSnapshotInspectionTextBudget=
|
|
11
|
+
`).trimEnd();return(0,X.usableCatalogText)(m)}});var Ii=Oe(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=x.COMPONENT_INSPECTION_TEXT_MAX_BYTES=x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;x.fitSnapshotInspectionTextBudget=Bp;x.capComponentTextBytes=Ci;x.prepareComponentInspectionText=Kp;x.redactComponentSource=hr;x.componentSourceContainsRedactableSecret=of;x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER="[REDACTED]";x.COMPONENT_INSPECTION_TEXT_MAX_BYTES=256*1024;x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=3*1024*1024;function Bp(e){let t=0;return e.map(n=>{let r=n,o=r.skill?.inspectionText;if(o===void 0)return n;let s=Buffer.byteLength(o,"utf8");return t+s<=x.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES?(t+=s,n):{...n,skill:{...r.skill,inspectionText:void 0}}})}function Ci(e,t){if(e==null||e.length===0)return;let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return e;let r=new TextDecoder("utf-8",{fatal:!0});for(let o=t;o>0;o-=1)try{return r.decode(n.subarray(0,o))}catch{}}function Kp(e){if(!(e==null||e.length===0))return Ci(hr(e),x.COMPONENT_INSPECTION_TEXT_MAX_BYTES)}var Gp="(?:[A-Za-z0-9_.-]*(?:passwd|password|secret|token|credential|credentials|apikey|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|auth|authorization|session[_-]?id)[A-Za-z0-9_.-]*)",zp=new RegExp(`(\\b${Gp})(\\s*[:=]\\s*)(?:(")([^"\\n]*)(")|(')([^'\\n]*)(')|([^\\s"'][^"'\\n]*))`,"gi"),Vp=[/^(?:none|null|nil|n\/a|empty|unset|not (?:required|needed|set)|no (?:password|token|auth))(?=$|[\s.,;:()—–-])/i,/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/,/^\$\(.*\)$/,/^\$\{\{.*\}\}$/,/^%[A-Za-z_][A-Za-z0-9_]*%$/,/^(?:process\.env|os\.environ|import\.meta\.env)\.[A-Za-z_][A-Za-z0-9_]*[,;]?$/,/^<[^<>]*>$/,/^(?:\*{3,}|\.{3,}|…|x{3,})$/i,/^your[-_ ]/i,/^(?:see|from|via|stored in|use|ask|obtain|get|fetch|run|read|provided by|generated by)\b/i];function _r(e){let t=e.trim().replace(/^`+|`+$/g,"").trim();return Vp.some(n=>n.test(t))}function Wp(e){if(e.startsWith("$(")){let n=0;for(let r=1;r<e.length;r+=1)if(e[r]==="("&&(n+=1),e[r]===")"&&(n-=1,n===0))return e.slice(0,r+1);return e}return/^(?:\$\{\{[^}]*\}\}|<[^<>]*>)/.exec(e)?.[0]??/^\S+/.exec(e)?.[0]??""}var Jp=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}/g,/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,/\bgithub_pat_[A-Za-z0-9_]{20,}/g,/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bAIza[0-9A-Za-z_-]{35}\b/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g],Yp=/\b[A-Za-z0-9_+/-]{32,}={0,2}\b/g,Xp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function Zp(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function qp(e){return e.replace(Yp,t=>{if(Xp.test(t))return t;let n=/[A-Za-z]/.test(t),r=/\d/.test(t);return n&&r&&Zp(t)>=3.5?x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:t})}var Qp=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,ef=/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+):([^\s/@]*)@/gi,tf=/([?&](?:access_token|api_key|apikey|auth|authorization|client_secret|key|password|secret|token)=)[^&\s"'<>]+/gi,nf=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,Ri=/-----END [A-Z0-9 ]*PRIVATE KEY-----/;function Ai(e){return e.replace(zp,(t,n,r,o,s,i,a,c,l,u)=>{let p=`${n}${r}`;if(o!==void 0||a!==void 0){let d=o??a??"",_=i??l??"",S=s??c??"";return S===""||S.includes(x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||_r(S)?t:`${p}${d}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${_}`}let m=u??"";if(r==="="){let d=Wp(m).replace(/`+$/,""),_=Ai(m.slice(d.length));return d===""||d.includes(x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||_r(d)?`${p}${d}${_}`:`${p}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${_}`}return m.includes(x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||_r(m)?t:`${p}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`})}function rf(e){let t=e.replace(ef,(n,r)=>`${r}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}:${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}@`);t=t.replace(tf,(n,r)=>`${r}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`),t=t.replace(Qp,(n,r)=>`${r}${x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`);for(let n of Jp)t=t.replace(n,x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER);return Ai(qp(t))}function hr(e){if(e.length===0)return e;let t=e.split(`
|
|
12
12
|
`),n=!1;return t.map(o=>n?Ri.test(o)?(n=!1,o):o.trim().length===0?o:x.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:nf.test(o)&&!Ri.test(o)?(n=!0,o):rf(o)).join(`
|
|
13
|
-
`)}function of(e){return hr(e)!==e}});var Ke=Oe(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.redactComponentSource=g.prepareComponentInspectionText=g.fitSnapshotInspectionTextBudget=g.componentSourceContainsRedactableSecret=g.capComponentTextBytes=g.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=g.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=g.COMPONENT_INSPECTION_TEXT_MAX_BYTES=g.usableCatalogText=g.parseFrontmatterField=g.parseFrontmatterDescription=g.isNpmRegistryPublisher=g.EMPTY_NPM_PUBLISHER=g.displayPublisherName=g.classifyMcpProvenance=g.resolveMcpPackageIdentity=g.McpPackageEcosystem=g.pinnedPackageVersionFromSpec=g.pinnedPackageVersionFromNpx=g.packageNameFromSpec=g.npxPackageSpecs=g.npxExecBin=g.PACKAGE_FIELD_MAX=g.serializeMcpLaunchIdentity=g.projectMcpMissingLaunchIdentity=g.projectMcpLaunchIdentity=g.normalizeMcpToolNames=g.MCP_MISSING_LAUNCH_SERIALIZED=g.MCP_LAUNCH_IDENTITY_ALGORITHM=g.maskMcpLaunchForDisplay=g.launchContainsCredentials=g.hashMcpLaunchIdentity=g.foldMcpName=g.buildMcpFamilyCanonicalKey=g.ComponentKind=void 0;g.userConfigRootFromPath=gf;g.installationRootExternalKey=_f;g.normalizeRepositoryRelativePath=ki;g.nativeKeyForSkillPath=hf;g.nativeKeyForRulePath=Sf;g.nativeKeyForCommandPath=Ef;g.serializeComponentIdentity=xi;g.buildComponentReference=Rf;g.validateComponentReference=Cf;var sf=Pn("node:crypto"),af=Pn("node:path"),cf="cmp1_",uf=/^cmp1_[A-Za-z0-9_-]{43}$/,lf=["/skills/","/skills-cursor/"],df=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,pf=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,ff=[".cursor",".claude",".codex"],mf={".claude.json":".claude",".agents":".codex"};g.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function gf(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>ff.includes(o));return n||(t.map(o=>mf[o]).find(o=>o!==void 0)??"unknown")}function _f(e,t){return`runtime-install:${e}/${t}`}function Jt(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function ki(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=af.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Jt(n,"sourcePath")}function hf(e){let t=e.replaceAll("\\","/");for(let n of lf){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Oi(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 Sf(e){return Oi(e,df,/\.(mdc|md|rules)$/i)}function Ef(e){return Oi(e,pf,/\.(md|mdc|toml)$/i)}function yf(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function xi(e){let t=[Jt(e.installationRootExternalKey,"installationRootExternalKey"),Jt(e.installableKind,"installableKind"),ki(e.sourcePath),Jt(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(yf).join("|")}`,"utf8")}function Rf(e){let t=(0,sf.createHash)("sha256").update(xi(e)).digest("base64url");return`${cf}${t}`}function Cf(e){return uf.test(e)}var Z=zt();Object.defineProperty(g,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return Z.buildMcpFamilyCanonicalKey}});Object.defineProperty(g,"foldMcpName",{enumerable:!0,get:function(){return Z.foldMcpName}});Object.defineProperty(g,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.hashMcpLaunchIdentity}});Object.defineProperty(g,"launchContainsCredentials",{enumerable:!0,get:function(){return Z.launchContainsCredentials}});Object.defineProperty(g,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return Z.maskMcpLaunchForDisplay}});Object.defineProperty(g,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return Z.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(g,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return Z.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(g,"normalizeMcpToolNames",{enumerable:!0,get:function(){return Z.normalizeMcpToolNames}});Object.defineProperty(g,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.projectMcpLaunchIdentity}});Object.defineProperty(g,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return Z.projectMcpMissingLaunchIdentity}});Object.defineProperty(g,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.serializeMcpLaunchIdentity}});var $e=Wt();Object.defineProperty(g,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return $e.PACKAGE_FIELD_MAX}});Object.defineProperty(g,"npxExecBin",{enumerable:!0,get:function(){return $e.npxExecBin}});Object.defineProperty(g,"npxPackageSpecs",{enumerable:!0,get:function(){return $e.npxPackageSpecs}});Object.defineProperty(g,"packageNameFromSpec",{enumerable:!0,get:function(){return $e.packageNameFromSpec}});Object.defineProperty(g,"pinnedPackageVersionFromNpx",{enumerable:!0,get:function(){return $e.pinnedPackageVersionFromNpx}});Object.defineProperty(g,"pinnedPackageVersionFromSpec",{enumerable:!0,get:function(){return $e.pinnedPackageVersionFromSpec}});var Pi=fi();Object.defineProperty(g,"McpPackageEcosystem",{enumerable:!0,get:function(){return Pi.McpPackageEcosystem}});Object.defineProperty(g,"resolveMcpPackageIdentity",{enumerable:!0,get:function(){return Pi.resolveMcpPackageIdentity}});var Yt=Ei();Object.defineProperty(g,"classifyMcpProvenance",{enumerable:!0,get:function(){return Yt.classifyMcpProvenance}});Object.defineProperty(g,"displayPublisherName",{enumerable:!0,get:function(){return Yt.displayPublisherName}});Object.defineProperty(g,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return Yt.EMPTY_NPM_PUBLISHER}});Object.defineProperty(g,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return Yt.isNpmRegistryPublisher}});var Sr=yi();Object.defineProperty(g,"parseFrontmatterDescription",{enumerable:!0,get:function(){return Sr.parseFrontmatterDescription}});Object.defineProperty(g,"parseFrontmatterField",{enumerable:!0,get:function(){return Sr.parseFrontmatterField}});Object.defineProperty(g,"usableCatalogText",{enumerable:!0,get:function(){return Sr.usableCatalogText}});var Ae=Ii();Object.defineProperty(g,"COMPONENT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ae.COMPONENT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"COMPONENT_SOURCE_REDACTION_PLACEHOLDER",{enumerable:!0,get:function(){return Ae.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}});Object.defineProperty(g,"SNAPSHOT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ae.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"capComponentTextBytes",{enumerable:!0,get:function(){return Ae.capComponentTextBytes}});Object.defineProperty(g,"componentSourceContainsRedactableSecret",{enumerable:!0,get:function(){return Ae.componentSourceContainsRedactableSecret}});Object.defineProperty(g,"fitSnapshotInspectionTextBudget",{enumerable:!0,get:function(){return Ae.fitSnapshotInspectionTextBudget}});Object.defineProperty(g,"prepareComponentInspectionText",{enumerable:!0,get:function(){return Ae.prepareComponentInspectionText}});Object.defineProperty(g,"redactComponentSource",{enumerable:!0,get:function(){return Ae.redactComponentSource}})});import{realpathSync as wS}from"node:fs";import{resolve as MS}from"node:path";import{fileURLToPath as LS,pathToFileURL as US}from"node:url";import{createHash as Eu}from"node:crypto";import{homedir as yu}from"node:os";import{dirname as BS,join as Ru,parse as GS,resolve as zS}from"node:path";var ko="https://hooks.ev-ai.ai",xt=".claude/ev-ai-runtime-report.json",Oo="config.json",VS=1024*1024,Cu=new Set(["localhost","127.0.0.1","[::1]","::1"]),Au=["claude","cursor","codex"],Pt=[xt,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],bn=/^[A-Za-z0-9._~-]+$/;function bt(e){return e!==void 0&&Au.includes(e)}function Ot(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ze(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=Ot(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=Ot(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=Ot(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=Ot(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:bt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Tt(e,t=ko){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function Tn(e=yu()){return Ru(e,".ev-ai",Oo)}function xo(e,t){return{...e,...t}}function Io(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function qe(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Cu.has(t.hostname):!1}catch{return!1}}function Nn(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r&&r.length>0?r:void 0}return}catch{return}}function Le(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!qe(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Nn(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!bn.test(n))return`org token must match ${bn.source} (got: ${n})`;if(Io(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Io(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Qe(e){return new URL(e).toString()}function vn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token,n=typeof t=="string"?t.trim():void 0;return n?Tt(n):""}function Nt(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function Po(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Tt(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=Le(n);return r?{problem:r}:{url:Qe(n)}}function bo(e){if(Le(e))return;let t;try{t=new URL(e)}catch{return}let n=Nn(e);if(!n)return;let o=t.pathname.split("/").filter(a=>a.length>0).slice(0,-2),s=o.length>0?`/${o.join("/")}`:"",i=`${t.origin}${s}/${n}`;return Eu("sha256").update(i).digest("hex").slice(0,32)}var ge=2;var To="EV_AI_LAUNCHER_VERSION";var No="EV_AI_HOOK_SOURCE",vo="EV_AI_HOOK_FALLBACK_REASON",wo="EV_AI_LAUNCHER_SCOPE",Mo="EV_AI_LAUNCHER_READY_FD",Lo="node_modules/@ev-ai/agent-hook/dist/hook.mjs",q="ev-ai-agent-hook";function Iu(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function vt(e){let t=Iu(e);return t===q||t===`${q}.exe`}var Uo="https://cdn.ev-ai.ai/agent-hook";var wn=`current/${q}`,Mn=`.ev-ai/agent-hook/${q}`,Do=5e3,Ho=5e3,Ln=3e3;var Un=3e3,Fo=1500,jo=4*1024,Dn=256*1024,ku=4*1024,$o=32*1024,et=840*60*1e3,se="1.2.0",wt=`@ev-ai/agent-hook@${se}`,Ko="ev-ai runtime report";import{chmodSync as xs,cpSync as Ps,existsSync as he,mkdirSync as or,readFileSync as Nl,rmSync as jt,symlinkSync as vl,writeFileSync as wl}from"node:fs";import{homedir as ue}from"node:os";import{dirname as sr,isAbsolute as Ml,join as b,relative as bs,resolve as ks,sep as Ll}from"node:path";import{fileURLToPath as Ul}from"node:url";import{existsSync as Ou,readdirSync as Bo}from"node:fs";import{homedir as Mt}from"node:os";import{join as B}from"node:path";function Go(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return B(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function Hn(e=process.platform){let t=Go(e),n=[B(t,"managed-settings.json")],r=B(t,"managed-settings.d");try{if(!Ou(r))return n;let o=Bo(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>B(r,s));n.push(...o)}catch{}return n}function Fn(e=process.platform,t=Mt()){return{serverManaged:B(t,".claude","remote-settings.json"),fileBased:Hn(e)}}function xu(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/Cursor";case"win32":return B(process.env.ProgramData??"C:\\ProgramData","Cursor");default:return"/etc/cursor"}}function Pu(e=process.platform,t=Mt()){let n=[B(xu(e),"hooks.json")],r=B(t,".cursor","managed");try{for(let o of Bo(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(B(r,o.name,"hooks.json"))}catch{}return n}function bu(e=process.platform,t=Mt()){let n=e==="win32"?B(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[B(n,"requirements.toml")];return e!=="win32"&&r.push(B(n,"managed_config.toml")),r.push(B(t,".codex","managed_config.toml"),B(n,"config.toml")),r}function Lt(e,t=process.platform,n=Mt()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Fn(t,n);return[r,...o]}case"cursor":return Pu(t,n);default:return bu(t,n)}}import{createHash as ss,randomBytes as qu}from"node:crypto";import{existsSync as is,mkdirSync as Yn,readFileSync as as,unlinkSync as cs,writeFileSync as us}from"node:fs";import{homedir as Xn}from"node:os";import{dirname as Dt,join as Zn,resolve as Qu}from"node:path";var Tu=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),Nu=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function z(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||Nu.has(n)||r.includes("[bot]")||Tu.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 Fu,readFileSync as ju}from"node:fs";import{hostname as qo,userInfo as $u}from"node:os";import{randomBytes as vu}from"node:crypto";import{existsSync as $n,mkdirSync as wu,readdirSync as Mu,readFileSync as Lu,renameSync as zo,statSync as Jo,unlinkSync as Vo,writeFileSync as Uu}from"node:fs";import{basename as Du,dirname as Wo,join as Yo,relative as Hu}from"node:path";function f(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
|
|
14
|
-
`)}function Q(e,t){wu(Wo(e),{recursive:!0});let n=Yo(Wo(e),`.${Du(e)}.${process.pid}.${vu(4).toString("hex")}.tmp`);try{Uu(n,t,"utf8");try{zo(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Vo(e),zo(n,e);return}throw r}}catch(r){try{Vo(n)}catch{}throw r}}function Ut(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Xo(){process.stdout.write('{"continue":true}')}function A(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function tt(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function Kn(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function Y(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,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 L(e,t,n=3e3,r={}){let o=await Y(e,t,n,r);return o.ok?o.stdout:""}async function Bn(e=process.cwd()){let t=await Y("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(A("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;f(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=A("CURSOR_PROJECT_DIR")??A("CLAUDE_PROJECT_DIR");if(n&&$n(n)){let r=await Y("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function ie(e=process.cwd()){return(await Bn(e)).root}function $(e,t){try{return JSON.parse(e)}catch{return t}}var jn=new Map;function H(e,t){let n=jn.get(e);if(n!==void 0)return n;try{let r=$(Lu(e,"utf8"),t);return jn.set(e,r),r}catch{return jn.set(e,t),t}}function xe(e){return typeof e=="string"?e:""}function ae(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function h(e,t){let n=ae(e,t);return typeof n=="string"?n:""}var _e=500;function Zo(e,t=2){if(!$n(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=Mu(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=Yo(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:Hu(e,l),size:Jo(l).size})}catch{continue}if(n.length>=_e){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Gn(e){return $n(e)?{present:!0,size:Jo(e).size}:{present:!1,size:0}}function Ue(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function zn(e=process.env){return Ue(N("CURSOR_SANDBOX",e))}var Ku=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Bu(e){return Ku.some(t=>!!N(t,e))}function Gu(e){if(N("KUBERNETES_SERVICE_HOST",e)||Ue(N("REMOTE_CONTAINERS",e))||Ue(N("DEVCONTAINER",e)))return!0;try{if(Fu("/.dockerenv")||ju("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Qo(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!N(t,e))}function zu(e,t=process.platform){return Qo(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!N(n,e)):!1}function Vu(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Wu(e){return e==="linux"}function N(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return A(e)}function Ju(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Yu(N("CURSOR_VERSION",n))}function Yu(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Vn(e){if(Vu(e.sessionId))return!0;let t=e.hostname??qo(),n=e.osUser??es(e.env);return Ju(t,n,e.env)}function Xu(e){return Ue(N("CURSOR_AGENT",e.env))?!0:Vn(e)}function Zu(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(N("TERM",e)??N("TERM_PROGRAM",e))||(N("SSH_TTY",e)??N("SSH_CONNECTION",e))||(N("__CFBundleIdentifier",e)??N("XPC_SERVICE_NAME",e))||Qo(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!N(t,e))||N("SESSIONNAME",e))}function nt(e={}){let t=e.env;if(N("GITHUB_ACTIONS",t))return"github_actions";if(Ue(N("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!zu(t,n)&&Xu(e)&&(Ue(N("CURSOR_AGENT",t))||Wu(n)))return"cursor_cloud";if(N("CODESPACES",t)||N("CODESPACE_NAME",t))return"codespaces";if(N("GITLAB_CI",t))return"gitlab_ci";if(Bu(t))return"managed";let r=N("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Gu(t)?"container":Zu(t)?"interactive":"unknown"}async function Wn(){return await L("systemd-detect-virt",[],1e3)}function es(e=process.env,t=$u){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function Jn(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await L("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 L("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await L("uname",["-r"],1e3))}else t=await L("ver",[],1e3);let n=es(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await L("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function rt(){return qo()}var el="installation.json",tl="cloud-bootstrap.lock",nl=6e4;function ls(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function ce(e=Xn()){return Zn(e,".ev-ai","agent-hook")}function rl(e=Xn()){return Zn(ce(e),el)}function ds(e){return Zn(Dt(e),tl)}function ps(){return qu(8).toString("hex")}function De(e){return ss("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 fs(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function ol(e=process.env){let t=I(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!fs(t)){f(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function ms(e,t){return e&&fs(e)?e:(e&&f(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),ol(t))}function sl(e){return/^[0-9a-f]{16}$/.test(e)}function il(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 De(`github_actions|${t}|${n}`)}if(I(e.CODESPACES)||I(e.CODESPACE_NAME)){let t=I(e.CODESPACE_NAME);if(t)return De(`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 De(`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 De(`gitlab|${t}|${n}`)}return null}var al="cursoragent@cursor.com";function cl(e){let t=I(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===al?null:t}function ul(e,t){return I(e.CURSOR_PROJECT_DIR)??I(e.CLAUDE_PROJECT_DIR)??t}function ll(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function dl(e){let t=await L("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?ll(t):e}async function pl(e){let t=I(await L("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!z(null,t))return t;let n=I(await L("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!z(null,n)?n:null}function fl(e,t){let n=ul(e,t);return n?De(`cursor_cloud|${n}|${cl(e)??""}`):null}async function ml(e,t){let n=I(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await dl(n),o=await pl(n);return De(`claude_remote|${r}|${o??""}`)}function ts(e,t){let n=ms(e,t);if(n)return n;let r=il(t);return r||ps()}async function gl(e){let n=await L("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Qu(e);return ss("sha256").update(n).digest("hex").slice(0,16)}function _l(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 hl(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=_l(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function Pe(e){if(is(e))try{return hl(as(e,"utf8"))}catch{}}function qn(e){return Pe(e)}function gs(e,t,n){let r=Pe(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Q(e,`${JSON.stringify(o,null,2)}
|
|
13
|
+
`)}function of(e){return hr(e)!==e}});var Be=Oe(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.redactComponentSource=g.prepareComponentInspectionText=g.fitSnapshotInspectionTextBudget=g.componentSourceContainsRedactableSecret=g.capComponentTextBytes=g.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=g.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=g.COMPONENT_INSPECTION_TEXT_MAX_BYTES=g.usableCatalogText=g.parseFrontmatterField=g.parseFrontmatterDescription=g.isNpmRegistryPublisher=g.EMPTY_NPM_PUBLISHER=g.displayPublisherName=g.classifyMcpProvenance=g.resolveMcpPackageIdentity=g.McpPackageEcosystem=g.pinnedPackageVersionFromSpec=g.pinnedPackageVersionFromNpx=g.packageNameFromSpec=g.npxPackageSpecs=g.npxExecBin=g.PACKAGE_FIELD_MAX=g.serializeMcpLaunchIdentity=g.projectMcpMissingLaunchIdentity=g.projectMcpLaunchIdentity=g.normalizeMcpToolNames=g.MCP_MISSING_LAUNCH_SERIALIZED=g.MCP_LAUNCH_IDENTITY_ALGORITHM=g.maskMcpLaunchForDisplay=g.launchContainsCredentials=g.hashMcpLaunchIdentity=g.foldMcpName=g.buildMcpFamilyCanonicalKey=g.ComponentKind=void 0;g.userConfigRootFromPath=gf;g.installationRootExternalKey=_f;g.normalizeRepositoryRelativePath=ki;g.nativeKeyForSkillPath=hf;g.nativeKeyForRulePath=Sf;g.nativeKeyForCommandPath=Ef;g.serializeComponentIdentity=xi;g.buildComponentReference=Rf;g.validateComponentReference=Cf;var sf=Pn("node:crypto"),af=Pn("node:path"),cf="cmp1_",uf=/^cmp1_[A-Za-z0-9_-]{43}$/,lf=["/skills/","/skills-cursor/"],df=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,pf=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,ff=[".cursor",".claude",".codex"],mf={".claude.json":".claude",".agents":".codex"};g.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function gf(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>ff.includes(o));return n||(t.map(o=>mf[o]).find(o=>o!==void 0)??"unknown")}function _f(e,t){return`runtime-install:${e}/${t}`}function Jt(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function ki(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=af.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return Jt(n,"sourcePath")}function hf(e){let t=e.replaceAll("\\","/");for(let n of lf){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Oi(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 Sf(e){return Oi(e,df,/\.(mdc|md|rules)$/i)}function Ef(e){return Oi(e,pf,/\.(md|mdc|toml)$/i)}function yf(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function xi(e){let t=[Jt(e.installationRootExternalKey,"installationRootExternalKey"),Jt(e.installableKind,"installableKind"),ki(e.sourcePath),Jt(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(yf).join("|")}`,"utf8")}function Rf(e){let t=(0,sf.createHash)("sha256").update(xi(e)).digest("base64url");return`${cf}${t}`}function Cf(e){return uf.test(e)}var Z=zt();Object.defineProperty(g,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return Z.buildMcpFamilyCanonicalKey}});Object.defineProperty(g,"foldMcpName",{enumerable:!0,get:function(){return Z.foldMcpName}});Object.defineProperty(g,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.hashMcpLaunchIdentity}});Object.defineProperty(g,"launchContainsCredentials",{enumerable:!0,get:function(){return Z.launchContainsCredentials}});Object.defineProperty(g,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return Z.maskMcpLaunchForDisplay}});Object.defineProperty(g,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return Z.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(g,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return Z.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(g,"normalizeMcpToolNames",{enumerable:!0,get:function(){return Z.normalizeMcpToolNames}});Object.defineProperty(g,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.projectMcpLaunchIdentity}});Object.defineProperty(g,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return Z.projectMcpMissingLaunchIdentity}});Object.defineProperty(g,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return Z.serializeMcpLaunchIdentity}});var $e=Wt();Object.defineProperty(g,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return $e.PACKAGE_FIELD_MAX}});Object.defineProperty(g,"npxExecBin",{enumerable:!0,get:function(){return $e.npxExecBin}});Object.defineProperty(g,"npxPackageSpecs",{enumerable:!0,get:function(){return $e.npxPackageSpecs}});Object.defineProperty(g,"packageNameFromSpec",{enumerable:!0,get:function(){return $e.packageNameFromSpec}});Object.defineProperty(g,"pinnedPackageVersionFromNpx",{enumerable:!0,get:function(){return $e.pinnedPackageVersionFromNpx}});Object.defineProperty(g,"pinnedPackageVersionFromSpec",{enumerable:!0,get:function(){return $e.pinnedPackageVersionFromSpec}});var Pi=fi();Object.defineProperty(g,"McpPackageEcosystem",{enumerable:!0,get:function(){return Pi.McpPackageEcosystem}});Object.defineProperty(g,"resolveMcpPackageIdentity",{enumerable:!0,get:function(){return Pi.resolveMcpPackageIdentity}});var Yt=Ei();Object.defineProperty(g,"classifyMcpProvenance",{enumerable:!0,get:function(){return Yt.classifyMcpProvenance}});Object.defineProperty(g,"displayPublisherName",{enumerable:!0,get:function(){return Yt.displayPublisherName}});Object.defineProperty(g,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return Yt.EMPTY_NPM_PUBLISHER}});Object.defineProperty(g,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return Yt.isNpmRegistryPublisher}});var Sr=yi();Object.defineProperty(g,"parseFrontmatterDescription",{enumerable:!0,get:function(){return Sr.parseFrontmatterDescription}});Object.defineProperty(g,"parseFrontmatterField",{enumerable:!0,get:function(){return Sr.parseFrontmatterField}});Object.defineProperty(g,"usableCatalogText",{enumerable:!0,get:function(){return Sr.usableCatalogText}});var Ae=Ii();Object.defineProperty(g,"COMPONENT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ae.COMPONENT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"COMPONENT_SOURCE_REDACTION_PLACEHOLDER",{enumerable:!0,get:function(){return Ae.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}});Object.defineProperty(g,"SNAPSHOT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return Ae.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(g,"capComponentTextBytes",{enumerable:!0,get:function(){return Ae.capComponentTextBytes}});Object.defineProperty(g,"componentSourceContainsRedactableSecret",{enumerable:!0,get:function(){return Ae.componentSourceContainsRedactableSecret}});Object.defineProperty(g,"fitSnapshotInspectionTextBudget",{enumerable:!0,get:function(){return Ae.fitSnapshotInspectionTextBudget}});Object.defineProperty(g,"prepareComponentInspectionText",{enumerable:!0,get:function(){return Ae.prepareComponentInspectionText}});Object.defineProperty(g,"redactComponentSource",{enumerable:!0,get:function(){return Ae.redactComponentSource}})});import{realpathSync as US}from"node:fs";import{resolve as DS}from"node:path";import{fileURLToPath as HS,pathToFileURL as FS}from"node:url";import{createHash as Eu}from"node:crypto";import{homedir as yu}from"node:os";import{dirname as VS,join as Ru,parse as WS,resolve as JS}from"node:path";var ko="https://hooks.ev-ai.ai",xt=".claude/ev-ai-runtime-report.json",Oo="config.json",YS=1024*1024,Cu=new Set(["localhost","127.0.0.1","[::1]","::1"]),Au=["claude","cursor","codex"],Pt=[xt,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],bn=/^[A-Za-z0-9._~-]+$/;function bt(e){return e!==void 0&&Au.includes(e)}function Ot(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ze(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=Ot(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=Ot(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=Ot(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=Ot(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:bt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Tt(e,t=ko){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function Tn(e=yu()){return Ru(e,".ev-ai",Oo)}function xo(e,t){return{...e,...t}}function Io(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function qe(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Cu.has(t.hostname):!1}catch{return!1}}function Nn(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r&&r.length>0?r:void 0}return}catch{return}}function Le(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!qe(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Nn(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!bn.test(n))return`org token must match ${bn.source} (got: ${n})`;if(Io(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Io(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function Qe(e){return new URL(e).toString()}function vn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token,n=typeof t=="string"?t.trim():void 0;return n?Tt(n):""}function Nt(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function Po(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Tt(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=Le(n);return r?{problem:r}:{url:Qe(n)}}function bo(e){if(Le(e))return;let t;try{t=new URL(e)}catch{return}let n=Nn(e);if(!n)return;let o=t.pathname.split("/").filter(a=>a.length>0).slice(0,-2),s=o.length>0?`/${o.join("/")}`:"",i=`${t.origin}${s}/${n}`;return Eu("sha256").update(i).digest("hex").slice(0,32)}var ge=2;var To="EV_AI_LAUNCHER_VERSION";var No="EV_AI_HOOK_SOURCE",vo="EV_AI_HOOK_FALLBACK_REASON",wo="EV_AI_LAUNCHER_SCOPE",Mo="EV_AI_LAUNCHER_READY_FD",Lo="node_modules/@ev-ai/agent-hook/dist/hook.mjs",q="ev-ai-agent-hook";function Iu(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function vt(e){let t=Iu(e);return t===q||t===`${q}.exe`}var Uo="https://cdn.ev-ai.ai/agent-hook";var wn=`current/${q}`,Mn=`.ev-ai/agent-hook/${q}`,Do=5e3,Ho=5e3,Ln=3e3;var Un=3e3,Fo=1500,jo=4*1024,Dn=256*1024,ku=4*1024,$o=32*1024,et=840*60*1e3,se="1.2.2",wt=`@ev-ai/agent-hook@${se}`,Bo="ev-ai runtime report";import{chmodSync as xs,cpSync as Ps,existsSync as he,mkdirSync as or,readFileSync as Nl,rmSync as jt,symlinkSync as vl,writeFileSync as wl}from"node:fs";import{homedir as ue}from"node:os";import{dirname as sr,isAbsolute as Ml,join as b,relative as bs,resolve as ks,sep as Ll}from"node:path";import{fileURLToPath as Ul}from"node:url";import{existsSync as Ou,readdirSync as Ko}from"node:fs";import{homedir as Mt}from"node:os";import{join as K}from"node:path";function Go(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=Go(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!Ou(r))return n;let o=Ko(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function Fn(e=process.platform,t=Mt()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:Hn(e)}}function xu(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 Pu(e=process.platform,t=Mt()){let n=[K(xu(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of Ko(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function bu(e=process.platform,t=Mt()){let n=e==="win32"?K(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[K(n,"requirements.toml")];return e!=="win32"&&r.push(K(n,"managed_config.toml")),r.push(K(t,".codex","managed_config.toml"),K(n,"config.toml")),r}function Lt(e,t=process.platform,n=Mt()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Fn(t,n);return[r,...o]}case"cursor":return Pu(t,n);default:return bu(t,n)}}import{createHash as ss,randomBytes as qu}from"node:crypto";import{existsSync as is,mkdirSync as Yn,readFileSync as as,unlinkSync as cs,writeFileSync as us}from"node:fs";import{homedir as Xn}from"node:os";import{dirname as Dt,join as Zn,resolve as Qu}from"node:path";var Tu=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),Nu=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function z(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||Nu.has(n)||r.includes("[bot]")||Tu.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 Fu,readFileSync as ju}from"node:fs";import{hostname as qo,userInfo as $u}from"node:os";import{randomBytes as vu}from"node:crypto";import{existsSync as $n,mkdirSync as wu,readdirSync as Mu,readFileSync as Lu,renameSync as zo,statSync as Jo,unlinkSync as Vo,writeFileSync as Uu}from"node:fs";import{basename as Du,dirname as Wo,join as Yo,relative as Hu}from"node:path";function f(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
|
|
14
|
+
`)}function Q(e,t){wu(Wo(e),{recursive:!0});let n=Yo(Wo(e),`.${Du(e)}.${process.pid}.${vu(4).toString("hex")}.tmp`);try{Uu(n,t,"utf8");try{zo(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Vo(e),zo(n,e);return}throw r}}catch(r){try{Vo(n)}catch{}throw r}}function Ut(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Xo(){process.stdout.write('{"continue":true}')}function A(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function tt(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function Bn(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function Y(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,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 L(e,t,n=3e3,r={}){let o=await Y(e,t,n,r);return o.ok?o.stdout:""}async function Kn(e=process.cwd()){let t=await Y("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(A("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;f(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=A("CURSOR_PROJECT_DIR")??A("CLAUDE_PROJECT_DIR");if(n&&$n(n)){let r=await Y("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function ie(e=process.cwd()){return(await Kn(e)).root}function $(e,t){try{return JSON.parse(e)}catch{return t}}var jn=new Map;function H(e,t){let n=jn.get(e);if(n!==void 0)return n;try{let r=$(Lu(e,"utf8"),t);return jn.set(e,r),r}catch{return jn.set(e,t),t}}function xe(e){return typeof e=="string"?e:""}function ae(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function h(e,t){let n=ae(e,t);return typeof n=="string"?n:""}var _e=500;function Zo(e,t=2){if(!$n(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=Mu(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=Yo(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:Hu(e,l),size:Jo(l).size})}catch{continue}if(n.length>=_e){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Gn(e){return $n(e)?{present:!0,size:Jo(e).size}:{present:!1,size:0}}function Ue(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function zn(e=process.env){return Ue(N("CURSOR_SANDBOX",e))}var Bu=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Ku(e){return Bu.some(t=>!!N(t,e))}function Gu(e){if(N("KUBERNETES_SERVICE_HOST",e)||Ue(N("REMOTE_CONTAINERS",e))||Ue(N("DEVCONTAINER",e)))return!0;try{if(Fu("/.dockerenv")||ju("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Qo(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!N(t,e))}function zu(e,t=process.platform){return Qo(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!N(n,e)):!1}function Vu(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Wu(e){return e==="linux"}function N(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return A(e)}function Ju(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Yu(N("CURSOR_VERSION",n))}function Yu(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Vn(e){if(Vu(e.sessionId))return!0;let t=e.hostname??qo(),n=e.osUser??es(e.env);return Ju(t,n,e.env)}function Xu(e){return Ue(N("CURSOR_AGENT",e.env))?!0:Vn(e)}function Zu(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(N("TERM",e)??N("TERM_PROGRAM",e))||(N("SSH_TTY",e)??N("SSH_CONNECTION",e))||(N("__CFBundleIdentifier",e)??N("XPC_SERVICE_NAME",e))||Qo(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!N(t,e))||N("SESSIONNAME",e))}function nt(e={}){let t=e.env;if(N("GITHUB_ACTIONS",t))return"github_actions";if(Ue(N("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!zu(t,n)&&Xu(e)&&(Ue(N("CURSOR_AGENT",t))||Wu(n)))return"cursor_cloud";if(N("CODESPACES",t)||N("CODESPACE_NAME",t))return"codespaces";if(N("GITLAB_CI",t))return"gitlab_ci";if(Ku(t))return"managed";let r=N("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Gu(t)?"container":Zu(t)?"interactive":"unknown"}async function Wn(){return await L("systemd-detect-virt",[],1e3)}function es(e=process.env,t=$u){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function Jn(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await L("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 L("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await L("uname",["-r"],1e3))}else t=await L("ver",[],1e3);let n=es(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await L("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function rt(){return qo()}var el="installation.json",tl="cloud-bootstrap.lock",nl=6e4;function ls(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function ce(e=Xn()){return Zn(e,".ev-ai","agent-hook")}function rl(e=Xn()){return Zn(ce(e),el)}function ds(e){return Zn(Dt(e),tl)}function ps(){return qu(8).toString("hex")}function De(e){return ss("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 fs(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function ol(e=process.env){let t=I(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!fs(t)){f(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function ms(e,t){return e&&fs(e)?e:(e&&f(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),ol(t))}function sl(e){return/^[0-9a-f]{16}$/.test(e)}function il(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 De(`github_actions|${t}|${n}`)}if(I(e.CODESPACES)||I(e.CODESPACE_NAME)){let t=I(e.CODESPACE_NAME);if(t)return De(`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 De(`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 De(`gitlab|${t}|${n}`)}return null}var al="cursoragent@cursor.com";function cl(e){let t=I(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===al?null:t}function ul(e,t){return I(e.CURSOR_PROJECT_DIR)??I(e.CLAUDE_PROJECT_DIR)??t}function ll(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function dl(e){let t=await L("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?ll(t):e}async function pl(e){let t=I(await L("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!z(null,t))return t;let n=I(await L("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!z(null,n)?n:null}function fl(e,t){let n=ul(e,t);return n?De(`cursor_cloud|${n}|${cl(e)??""}`):null}async function ml(e,t){let n=I(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await dl(n),o=await pl(n);return De(`claude_remote|${r}|${o??""}`)}function ts(e,t){let n=ms(e,t);if(n)return n;let r=il(t);return r||ps()}async function gl(e){let n=await L("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Qu(e);return ss("sha256").update(n).digest("hex").slice(0,16)}function _l(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 hl(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=_l(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function Pe(e){if(is(e))try{return hl(as(e,"utf8"))}catch{}}function qn(e){return Pe(e)}function gs(e,t,n){let r=Pe(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Q(e,`${JSON.stringify(o,null,2)}
|
|
15
15
|
`)}catch(s){let i=s instanceof Error?s.message:String(s);f(`WARN: operator identity cache write failed open: ${i}`)}}function _s(e,t=Date.now()){if(!e)return!0;if(Pe(e)?.operator_identity_hash)return!1;let n=ds(e);try{if(is(n)){let r=Number.NaN;try{r=Number(as(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<nl)return!1;try{cs(n)}catch{}}}catch{}try{return Yn(Dt(n),{recursive:!0}),us(n,`${t}
|
|
16
16
|
`,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(ys(r))return!1;let o=r instanceof Error?r.message:String(r);return f(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function hs(e){if(e)try{cs(ds(e))}catch{}}function Ss(e,t){let r=Pe(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Es(e,t,n){if(!n)return;let r=Pe(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{Q(e,`${JSON.stringify(o,null,2)}
|
|
17
17
|
`)}catch(s){let i=s instanceof Error?s.message:String(s);f(`WARN: platform_agent_id cache write failed open: ${i}`)}}function ys(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Sl(e,t){Yn(Dt(e),{recursive:!0}),us(e,`${JSON.stringify(t,null,2)}
|
|
18
18
|
`,{encoding:"utf8",flag:"wx"})}function ns(e,t){try{return Sl(e,t),t}catch(n){if(!ys(n))throw n;return Pe(e)}}function rs(e,t){Yn(Dt(e),{recursive:!0}),Q(e,`${JSON.stringify(t,null,2)}
|
|
19
|
-
`)}function os(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Ht(e,t={}){let n=t.home??Xn(),r=t.env??process.env,o=await gl(e),s=rl(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=nt(i),c=ms(t.overrideId,r),l=a==="cursor_cloud"&&Vn(i)?fl(r,e):a==="claude_remote"?await ml(r,e):null,u=Pe(s);if(u){let S=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(S={...u,pinned:!0},rs(s,S)),!!l&&l!==S.installation_id&&!c&&S.pinned!==!0&&sl(S.installation_id)&&l){let y={installation_id:l,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return rs(s,y),{installationId:l,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let p=c??l??ts(void 0,r),m=ns(s,os(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let d=c??l??ts(void 0,r),_=ns(s,os(d===p?ps():d,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as er,readFileSync as El}from"node:fs";import{dirname as yl,isAbsolute as Rl,join as Cl,relative as Al}from"node:path";function Rs(e){for(let t of Pt){let n=Cl(e,t);if(er(n))return n}}async function Il(e=process.cwd(),t){let n=t??await ie(e);return Rs(n)??Rs(e)}async function kl(e,t){let n=t??await ie(yl(e)),r=Al(n,e);if(r.startsWith("..")||Rl(r))return!1;let o=await Y("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(f(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Qn(e){let t=El(e,"utf8");return $(t,{})}function Ol(){return{schema_version:ge,mcp_servers:[]}}function xl(e,t,n,r){!t||!n||(e.capture_hook_input==="full"&&r.has("capture_hook_input")&&(f(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${t}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete e.capture_hook_input),e.debug===!0&&r.has("debug")&&(f(`WARN: ignoring debug=true in git-tracked manifest ${t}; set debug on ~/.ev-ai/config.json`),delete e.debug))}async function Cs(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await
|
|
20
|
-
To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=Us(n,se,t),o=Ls(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function Os(e){let t=[b(e,"packages","agent-hook","dist","hook.mjs"),b(e,Lo)],n=
|
|
19
|
+
`)}function os(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Ht(e,t={}){let n=t.home??Xn(),r=t.env??process.env,o=await gl(e),s=rl(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=nt(i),c=ms(t.overrideId,r),l=a==="cursor_cloud"&&Vn(i)?fl(r,e):a==="claude_remote"?await ml(r,e):null,u=Pe(s);if(u){let S=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(S={...u,pinned:!0},rs(s,S)),!!l&&l!==S.installation_id&&!c&&S.pinned!==!0&&sl(S.installation_id)&&l){let y={installation_id:l,...S.platform_agent_ids?{platform_agent_ids:S.platform_agent_ids}:{}};return rs(s,y),{installationId:l,storePath:s,repoKey:o}}return{installationId:S.installation_id,storePath:s,repoKey:o}}let p=c??l??ts(void 0,r),m=ns(s,os(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let d=c??l??ts(void 0,r),_=ns(s,os(d===p?ps():d,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as er,readFileSync as El}from"node:fs";import{dirname as yl,isAbsolute as Rl,join as Cl,relative as Al}from"node:path";function Rs(e){for(let t of Pt){let n=Cl(e,t);if(er(n))return n}}async function Il(e=process.cwd(),t){let n=t??await ie(e);return Rs(n)??Rs(e)}async function kl(e,t){let n=t??await ie(yl(e)),r=Al(n,e);if(r.startsWith("..")||Rl(r))return!1;let o=await Y("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(f(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Qn(e){let t=El(e,"utf8");return $(t,{})}function Ol(){return{schema_version:ge,mcp_servers:[]}}function xl(e,t,n,r){!t||!n||(e.capture_hook_input==="full"&&r.has("capture_hook_input")&&(f(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${t}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete e.capture_hook_input),e.debug===!0&&r.has("debug")&&(f(`WARN: ignoring debug=true in git-tracked manifest ${t}; set debug on ~/.ev-ai/config.json`),delete e.debug))}async function Cs(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Kn(e),o=A("EV_AI_HOOK_MANIFEST"),s=o&&er(o)?o:void 0,i=s?void 0:er(Tn())?Tn():void 0,a=s?void 0:await Il(e,n),c=i?Qn(i):void 0,l=a?Qn(a):void 0,u,p,m,d=new Set;if(s){u=Qn(s),p=s,m=s;for(let R of Object.keys(u))d.add(R)}else if(c&&l){u=xo(l,c),p=i,m=a;for(let R of Object.keys(l))R in c||d.add(R)}else if(c)u=c,p=i;else if(l){u=l,p=a,m=a;for(let R of Object.keys(l))d.add(R)}else u=Ol();delete u.installation_id;let _=m?await kl(m,n):!1;xl(u,m,_,d);let{installationId:S,storePath:E,repoKey:y}=await Ht(n,{sessionId:t.sessionId});return{manifestPath:p??E,manifest:u,installationId:S,installationStorePath:E,repoKey:y,collectorUrl:vn(u),platformAgentId:u.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function As(e){return{schema_version:ge,...e?{collector_url:e}:{},mcp_servers:[]}}var Pl=["darwin-arm64","darwin-x64","linux-arm64","linux-x64","windows-x64","windows-arm64"];function bl(e){return e==="windows-x64"||e==="windows-arm64"}function tr(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0;if(e==="win32")return t==="x64"?"windows-x64":t==="arm64"?"windows-arm64":void 0}function Is(e=process.platform,t=process.arch){let n=tr(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${Pl.join(", ")}.`);return n}function Tl(e){return bl(e)?`${q}.exe`:q}function nr(e){return`compile-out/bin/${e}/${Tl(e)}`}function Dl(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=Le(n);if(r)throw new Error(`collector URL rejected: ${r}`);return Qe(n)}function Hl(e){let t=e.collectorUrl?.trim();if(!t)return;let n=Le(t);if(n)throw new Error(`collector URL rejected: ${n}`);return Qe(t)}function Fl(e){return Dl(e,"install")}function Ts(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 Ns(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 vs(e=process.execPath){return ws(e)?"binary":"npx"}function jl(){return b(ue(),".ev-ai","agent-hook")}function $l(e=ue()){return b(e,".ev-ai","agent-hook",wn)}function Bl(){let e=sr(Ul(import.meta.url)),t=b(e,"hook.mjs");return he(t)?t:b(e,"..","dist","hook.mjs")}function ws(e=process.execPath){return vt(e)}function Ms(e,t){let n=bs(ks(e),ks(t));return!n.startsWith("..")&&!Ml(n)}function $t(e){return e.split(Ll).join("/")}function Kl(e){return`node "$(git rev-parse --show-toplevel)/${$t(e)}"`}function Gl(e){return`"$(git rev-parse --show-toplevel)/${$t(e)}"`}function zl(e){return b(e,Mn)}function Ls(e,t){let n=zl(e);or(sr(n),{recursive:!0}),Ps(t,n,{force:!0});try{xs(n,493)}catch{}return n}function Vl(e){let t=b(jl(),"current");try{jt(t,{recursive:!0,force:!0})}catch{}vl(e,t,process.platform==="win32"?"junction":"dir")}function Us(e,t=se,n=ue()){let r=b(n,".ev-ai","agent-hook",t),o=b(r,q);or(r,{recursive:!0}),Ps(e,o,{force:!0});try{xs(o,493)}catch{}return Vl(r),b(n,".ev-ai","agent-hook",wn)}function Ds(e){let t=tr();if(!t)return;let n=[b(e,nr(t)),b(e,"packages","agent-hook",nr(t))];for(let r of n)if(he(r)&&Ms(e,r))return r}function Wl(e=ue()){let t=$l(e);return he(t)?t:void 0}function Jl(e,t=ue()){let n=Wl(t);return n||(ws()?Us(process.execPath,se,t):Ds(e))}function Yl(e,t=ue()){let n=Ds(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
|
|
20
|
+
To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=Us(n,se,t),o=Ls(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function Os(e){let t=[b(e,"packages","agent-hook","dist","hook.mjs"),b(e,Lo)],n=Bl();he(n)&&Ms(e,n)&&t.unshift(n);for(let r of t){if(!he(r))continue;let o=$t(bs(e,r));return{command:Kl(o),hookPath:o,strategy:"dev_mjs"}}}function Xl(e){return e==="SessionStart"||e==="sessionStart"}function Zl(e){return e.replace(/\s+--prefer-offline\b/g,"")}function Ft(e,t){return Xl(e)?Zl(t):t}function ql(e=wt){return`npx -y --prefer-offline ${e}`}function Ql(e,t=ue(),n=vs()){if(n==="npx")return{command:ql(),hookPath:wt,strategy:"npx"};if(n==="local"){let s=Os(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=Jl(e,t);if(r){Ls(e,r);let s=$t(Mn);return{command:Gl(s),hookPath:s,strategy:"project_binary"}}let o=Os(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
|
|
21
21
|
curl -fsSL ${Uo}/install.sh | sh
|
|
22
22
|
Or use npx delivery:
|
|
23
23
|
npx ${wt} install`)}function Hs(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 ir(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function Se(e,t){or(sr(e),{recursive:!0}),wl(e,`${JSON.stringify(t,null,2)}
|
|
24
|
-
`,"utf8")}function le(e){if(he(e))try{return JSON.parse(Nl(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function ed(e,t){let n=As(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 td(e){return(e.schema_version??ge)===ge&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.debug===void 0&&e.repo_ingest_token===void 0}function Fs(e,t){let n=b(e,xt),r=le(n),o=ed(r,t);return t.collectorUrl!==void 0||he(n)||!td(o)?(Se(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function rr(e){if(e===null||typeof e!="object")return!1;let t=e,n=String(t.CLAUDE_CODE_ENABLE_TELEMETRY??"").toLowerCase();return n==="1"||n==="true"?!0:Object.keys(t).some(r=>r.startsWith("OTEL_"))}function nd(e){if(rr(process.env))return!0;let t=ue();return[...Hn(),b(t,".claude","settings.json"),b(t,".claude","remote-settings.json"),b(e,".claude","settings.json"),b(e,".claude","settings.local.json")].some(r=>{try{let o=le(r);return o?rr(o.env):!1}catch{return!1}})}function rd(e){try{let t=le(b(e,".claude","settings.json"));return t?rr(t.env):!1}catch{return!1}}function js(e){return Array.isArray(e)?e:[]}function Kt(e){let t=[],n=r=>!!r&&typeof r=="object"&&Hs(r.command);for(let r of js(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 $s(e,t){return[...Kt(e),...t]}function ar(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!Hs(t.command)):[]}function od(e,t){return[...ar(e),{command:t}]}function sd(e){return typeof e=="string"?[e]:e}function id(e){let t=(n="")=>({hooks:sd(e).map(r=>({type:"command",command:Ft(n,r)}))});return{SessionStart:[t("SessionStart")],UserPromptExpansion:[t()],UserPromptSubmit:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function ad(e){let t=typeof e=="string"?{command:e}:e,n=(r="")=>({hooks:[{type:"command",command:Ft(r,t.command),...t.commandWindows===void 0?{}:{commandWindows:Ft(r,t.commandWindows)},statusMessage:Ko}]});return{SessionStart:[n("SessionStart")],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var cd=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","beforeReadFile","beforeMCPExecution","subagentStart","subagentStop","stop"],ud=["afterShellExecution","afterFileEdit"];function ld(e,t=ud){let n={...e};for(let r of t){if(!(r in n))continue;let o=ar(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function dd(e,t,n={}){let r=b(e,".claude/settings.json"),o=ir(t,"claude"),s=le(r)??{};if(nd(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let p of Object.keys(u))u[p]=Kt(u[p]),js(u[p]).length===0&&delete u[p];Object.keys(u).length===0?delete s.hooks:s.hooks=u,Se(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=id(o),l={...a};for(let[u,p]of Object.entries(c))l[u]=$s(a[u],p);return s.hooks=l,Se(r,s),!0}function pd(e,t){let n=b(e,".cursor/hooks.json"),r=ir(t,"cursor"),o=le(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=ld({...s});for(let a of cd)i[a]=od(i[a],Ft(a,r));Se(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function fd(e,t){let n=b(e,".codex/hooks.json"),r=ir(t,"codex"),o=le(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=ad(r),a={...s};for(let[c,l]of Object.entries(i))a[c]=$s(s[c],l);Se(n,{...o,hooks:a})}function md(e){let t=b(e,".claude/settings.json"),n=le(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let i=r[s],a=Kt(i);JSON.stringify(i)!==JSON.stringify(a)&&(o=!0),a.length===0?delete r[s]:r[s]=a}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,Se(t,n),f(`Removed ev-ai hooks from ${t}`))}function gd(e){let t=b(e,".cursor/hooks.json"),n=le(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=ar(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks"&&a!=="version").length===0){jt(t,{force:!0}),f(`Removed ${t}`);return}Se(t,{...n,hooks:r}),f(`Removed ev-ai hooks from ${t}`)}}function _d(e){let t=b(e,".codex/hooks.json"),n=le(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=Kt(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks").length===0){jt(t,{force:!0}),f(`Removed ${t}`);return}Se(t,{...n,hooks:r}),f(`Removed ev-ai hooks from ${t}`)}}function cr(e=process.platform,t=process.arch,n={}){if(e==="win32")throw new Error("Windows install is not supported yet. Use macOS/Linux, or wait for phase-2 native commands.");(n.requireBinaryArch??!0)&&Is(e,t)}async function Ks(e={}){let t=Fl(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??vs();cr(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await ie(i),{command:c,hookPath:l,strategy:u}=Ql(a,ue(),s),{installationId:p,storePath:m}=await Ht(a,{overrideId:e.installationId}),{manifestPath:d,wrote:_}=Fs(a,e),S=[];return n?f("Skipped Claude hook \u2014 --no-claude"):dd(a,c,{force:e.force})?(S.push("Claude"),e.force&&rd(a)&&f("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):f("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?f("Skipped Cursor hook \u2014 --no-cursor"):(pd(a,c),S.push("Cursor")),o?f("Skipped Codex hook \u2014 --no-codex"):(fd(a,c),S.push("Codex")),f(`Installed hook (${u}) at ${l}`),f(`Installation identity ${p} at ${m}`),_&&d?f(`Shared manifest written to ${d}`):f("Using package default collector config (no shared manifest file needed)"),f(S.length>0?`Wired ${S.join(", ")} hooks in ${a} (commands include --runner)`:`No runner hooks wired in ${a} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),u==="npx"?f("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):u==="project_binary"?f("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):u==="dev_mjs"&&f("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&d&&e.collectorUrl&&f("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:a,hookPath:l,manifestPath:d,installationStorePath:m,strategy:u}}async function Bs(e=process.cwd()){cr(process.platform,process.arch,{requireBinaryArch:!0});let t=await ie(e),{projectPath:n,globalPath:r}=Yl(t);f(`Refreshed ${r}`),f(`Refreshed ${n}`),f("Hook configs and shared manifest left unchanged")}async function Gs(e={}){let t=Hl(e);e.collectorUrl=t,cr(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await ie(n),{manifestPath:o,wrote:s}=Fs(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?f(`Wrote ${o}`):t===void 0&&f("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),f("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function zs(e){for(let t of[()=>md(e),()=>gd(e),()=>_d(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: strip skipped a hook file: ${r}`)}}async function Vs(e=process.cwd()){let t=await ie(e);return zs(t),f("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),f("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function Ws(e=process.cwd()){let t=await ie(e);zs(t);for(let n of Pt){let r=b(t,n);if(he(r))try{jt(r,{force:!0}),f(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);f(`WARN: uninstall could not remove ${r}: ${s}`)}}}import{createHash as Qf}from"node:crypto";import{existsSync as em,mkdirSync as tm,readdirSync as nm,readFileSync as Qi,unlinkSync as ea,writeFileSync as rm}from"node:fs";import{homedir as ta}from"node:os";import{join as xr}from"node:path";import{existsSync as xd}from"node:fs";import{existsSync as hd}from"node:fs";import{homedir as Ys}from"node:os";import{join as Sd}from"node:path";function Xs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Ed={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 Js(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function yd(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:Js(n.mcpJson,t.mcpJson),mcpToml:Js(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function Zs(e){return Object.fromEntries(Object.entries(Ed).map(([t,n])=>[t,yd(n,n[e])]))}var He=Zs("homeOnly"),ye=Zs("projectOnly");function Rd(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function Cd(e,t){return Rd(e).some(n=>hd(Sd(t,n)))}function qs(e,t){for(let n of e)if(Cd(n,t))return!0;return!1}function Ee(e){return[...new Set(e)]}function Re(e){let t=[],n=[],r=[],o=[],s=[],i=[],a=[];for(let c of e){t.push(...c.skillRoots);for(let l of c.dirs)l.kind==="SUBAGENT"?n.push(l.dir):l.kind==="COMMAND"?r.push(l.dir):o.push(l.dir);s.push(...c.memory.flat()),i.push(...c.settings),a.push(...c.mcpJson??[],...c.mcpToml??[])}return{skills:Ee(t),subagents:Ee(n),commands:Ee(r),rules:Ee(o),memory:Ee(s),settings:Ee(i),mcp:Ee(a)}}function Ad(e,t=Ys(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...Lt(o.managed,n,t));return Ee(r)}var Ce=Re(Object.values(He));function Qs(e=Ys(),t=process.platform){return Ad(Object.values(He),e,t)}import{existsSync as Id}from"node:fs";import{resolve as ur}from"node:path";function V(e){return ur(e).replaceAll("\\","/").replace(/\/$/,"")}function be(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function 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 kd=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function ot(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!kd.test(t)?null:t}function Fe(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=V(o);n.has(s)||(n.add(s),r.push(s))}return r}function Od(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function ee(e,t,n,r=Id){for(let o of e)for(let s of t){let i=V(ur(o,s)),a=ur(o,s,n).replaceAll("\\","/");if(Od(i,a)&&r(a))return a}return null}var ti=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,ni=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Pd=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,ei=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"]),bd=/^[a-z][a-z0-9-]{1,63}$/,Td=[".cursor/skills",".claude/skills",".agents/skills"],Nd=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],vd=be(Td,Re(Object.values(ye)).skills),wd=be(Nd,Re(Object.values(He)).skills),Md=new Set(["read","read_file","view"]),Ld=new Set(["bash","shell","zsh"]);function lr(e){let t=e.replace(/\\/g,"/");return ti.exec(t)?.[1]??null}function Ud(e){let t=e.replace(/\\/g,"/"),r=ni.exec(t)?.[1];return r?r.toLowerCase():null}function Dd(e){return lr(e)??Ud(e)}function Hd(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Gt(e){return typeof e=="string"?Gt($(e,null)):!e||typeof e!="object"?null:Hd(e)}function ri(e){if(typeof e=="string")return ri($(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function dr(e){let t=ri(e.tool_input);if(t)return t;let n=xe(e.command);return n.length>0?n:null}function Fd(e){let t=e.replace(/\\/g,"/"),n=ti.exec(t);if(n?.[1])return n[1];let o=ni.exec(t)?.[1];return o?o.toLowerCase():null}function jd(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function pr(e){let t=Gt(e.tool_input)??xe(e.file_path);return t.length>0?t:null}function st(e,t,n){let r=jd(e).toLowerCase();if(Md.has(r)){let o=pr(e);return o?t(o):null}if(Ld.has(r)){let o=dr(e);return o?n(o):null}return null}function oi(e){return st(e,Dd,Fd)}function $d(e){let t=new Set,n=[];for(let r of e.matchAll(Pd)){let o=r[1]?.toLowerCase();!o||t.has(o)||Kd(o)||(t.add(o),n.push(o))}return n}function Kd(e){let t=e.split("/")[0];return ei.has(e)||t!==void 0&&ei.has(t)}function si(e){let t=e.skillId.toLowerCase();if(!bd.test(t))return null;let n=e.exists??xd,r=`${t}/SKILL.md`,o=ee(Fe(e.launchCwd,e.gitRoot),vd,r,n);return o!==null?o:e.home?ee([V(e.home)],wd,r,n):null}function Bd(e){return xe(e.prompt)}function ii(e){let t=h(e,"command_name");if(t){let r=h(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Bd(e);return n?$d(n):[]}var Er=Xe(Ke(),1);import{existsSync as If}from"node:fs";var Ne={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function at(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Af(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return at(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return at(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?at(o[1]):at(t)}async function ct(e=process.cwd()){let t=await Y("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([Y("git",["remote","get-url","origin"],2e3,{cwd:e}),Y("git",["branch","--show-current"],2e3,{cwd:e}),Y("git",["rev-parse","HEAD"],2e3,{cwd:e}),Y("git",["status","--porcelain"],2e3,{cwd:e})]),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 bi(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ne[n];if(!a)return"";let c=ls(n,e.scope_path,i);if(s){let _=Ss(s,c);if(_)return _}let l=o??await ct(r),u=l?.remote?Af(l.remote):"";if(u||(u=at(process.env.GITHUB_REPOSITORY??"")),!u)return"";let p=e.scope_path??"",m=p?`${p}/`:"",d=`${u}:${m}${a}`;return s&&Es(s,c,d),d}var kf=[".cursor/rules",".claude/rules",".codex/rules"],Of=Re(Object.values(ye)).rules;function xf(e){return be(Bt(e?Ne[e]:void 0,kf),Of)}var Pf=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function Ti(e){let t=ot(e.relativePath);if(!t)return null;let n=e.exists??If,r=Fe(e.launchCwd,e.gitRoot),o=xf(e.runnerPlatform),s=ee(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=ee(r,["."],t,n);if(i!==null)return i}return e.home?ee([V(e.home)],o,t,n):null}function bf(e){let t=e.replace(/\\/g,"/"),r=Pf.exec(t)?.[1];return r?(0,Er.nativeKeyForRulePath)(r):null}function Ni(e){return st(e,Er.nativeKeyForRulePath,bf)}function vi(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function wi(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=ot(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var yr=Xe(Ke(),1);import{existsSync as Tf}from"node:fs";var Nf=[".cursor/commands",".claude/commands",".codex/prompts"],vf=Re(Object.values(ye)).commands;function wf(e){return be(Bt(e?Ne[e]:void 0,Nf),vf)}var Mf=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function Mi(e){let t=ot(e.commandId);if(!t)return null;let n=e.exists??Tf,r=`${t}.md`,o=wf(e.runnerPlatform),s=ee(Fe(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?ee([V(e.home)],o,r,n):null}function Lf(e){let t=e.replace(/\\/g,"/"),r=Mf.exec(t)?.[1];return r?(0,yr.nativeKeyForCommandPath)(r):null}function Li(e){return st(e,yr.nativeKeyForCommandPath,Lf)}import{existsSync as Di}from"node:fs";import{homedir as Hi}from"node:os";import{join as ut,resolve as Rr,sep as Ui}from"node:path";function Cr(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Ar(e,t){let n=t.toLowerCase();return Cr(e).some(r=>r.toLowerCase()===n)}function Xt(e,t,n){if(!Di(e))return;let r=H(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function Uf(e,t,n){if(!Di(e))return;let r=H(e,{}),o=Rr(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Rr(a);(o===c||o.startsWith(c.endsWith(Ui)?c:c+Ui))&&(s===null||c.length>Rr(s).length)&&(s=a)}if(s===null)return;let i=r.projects?.[s]?.mcpServers??{};for(let[a,c]of Object.entries(i))n.set(a,{declared:{name:a,source:"claude_json_project",sourcePath:".claude.json",scope:"user"},config:c})}function Fi(e,t,n,r){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{declared:{name:s.name,source:"manifest"}});return n==="claude"?(Xt(ut(r,".claude.json"),{source:"claude_json_user"},o),Uf(ut(r,".claude.json"),t,o)):n==="cursor"&&Xt(ut(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Xt(ut(t,".mcp.json"),{source:"mcp_json"},o),Xt(ut(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function Ir(e,t=process.cwd(),n="claude",r=Hi()){return[...Fi(e,t,n,r).values()].map(o=>o.declared)}function ji(e,t,n=process.cwd(),r="claude",o=Hi()){let s=Fi(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Ar(a,e))return c.config??null;return null}function kr(e){let t=Po(e);if(t.problem){f(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function $i(e,t){if(h(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Df(){return!!(A("CURSOR_VERSION")??A("CURSOR_PROJECT_DIR"))}function Or(e,t,n){return e!=="claude"&&e!=="codex"?!1:$i(t,n)?!0:Df()}function lt(e,t,n,r){if($i(e,t))return"cursor";if(bt(r))return r;let o=h(e,"conversation_id"),s=h(e,"turn_id"),i=h(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion"||a==="userpromptsubmit")&&(c="claude"),bt(n)&&(c=n),c}function Zt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Hf(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 Ki(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function Bi(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function Gi(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function zi(e,t,n){let r=h(e,"session_id")||h(e,"conversation_id"),o=h(e,"prompt.id")||h(e,"prompt_id")||h(e,"generation_id")||h(e,"turn_id"),s=h(e,"hook_event_name")||h(e,"event"),i=h(e,"source"),a=lt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Ff=["session_start","session_end","tool_invoked","skill_invoked"];function jf(e){return Ff.includes(e)}function Vi(e,t){return e&&jf(e)?e:Hf(t.toLowerCase())}var $f={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Wi(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ji(e,t=""){let n=h(e,"tool_name")||h(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Wi(n)&&(n=`MCP:${n}`):n=$f[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?xe(o.skill)||xe(o.skill_name):"")||h(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=oi(a);let c=Ni(a),l=Li(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var Kf=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Yi(e){for(let t of["subagent_type","agent_type"]){let n=h(e,t);if(n&&Kf.test(n))return n}return null}function Xi(e){let t=ae(e,"duration_ms");if(typeof t=="number")return t;let n=ae(e,"duration");return typeof n=="number"?n:null}var Bf="error",Gf="interrupted",zf="permission_denied",Vf=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function dt(e){return Vf.test(e)?e:null}function Wf(e){for(let t of["failure_type","error_type"]){let n=dt(h(e,t));if(n)return n}return null}function Zi(e,t){return ae(e,"is_interrupt")===!0?Gf:t.toLowerCase()==="permissiondenied"?zf:Wf(e)??Bf}function Jf(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 Yf(e,t){let n=null;for(let r of t)!r||!Ar(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function Xf(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of Cr(s)){let a=`${i}__`;e.length>a.length&&e.slice(0,a.length).toLowerCase()===a.toLowerCase()&&i.length>r&&(n={mcpServer:s,mcpTool:e.slice(a.length)},r=i.length)}if(n!==null)return n;let o=/^(.+?)__(.+)$/.exec(e);return!o?.[1]||!o[2]?{mcpServer:null,mcpTool:null}:{mcpServer:Yf(o[1],t)??o[1],mcpTool:o[2]}}function Zf(e,t){if(/^mcp__/i.test(e))return Xf(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:Jf(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function qf(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function qi(e,t=[],n=""){let r=e?Zf(e,t):{mcpServer:null,mcpTool:null},o=dt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Wi(e)&&(s=e),s&&(s=qf(s,o)),{mcpServer:o,mcpTool:s}}var na=3e4,om="claims",sm=!0,im=100,am=new Set(["sessionstart","sessionend","stopfailure"]),cm=["tool_name","tool","command","file_path","url"];function um(e=ta()){return xr(ce(e),om)}function ra(e){let t=e.split(`
|
|
24
|
+
`,"utf8")}function le(e){if(he(e))try{return JSON.parse(Nl(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function ed(e,t){let n=As(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 td(e){return(e.schema_version??ge)===ge&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.debug===void 0&&e.repo_ingest_token===void 0}function Fs(e,t){let n=b(e,xt),r=le(n),o=ed(r,t);return t.collectorUrl!==void 0||he(n)||!td(o)?(Se(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function rr(e){if(e===null||typeof e!="object")return!1;let t=e,n=String(t.CLAUDE_CODE_ENABLE_TELEMETRY??"").toLowerCase();return n==="1"||n==="true"?!0:Object.keys(t).some(r=>r.startsWith("OTEL_"))}function nd(e){if(rr(process.env))return!0;let t=ue();return[...Hn(),b(t,".claude","settings.json"),b(t,".claude","remote-settings.json"),b(e,".claude","settings.json"),b(e,".claude","settings.local.json")].some(r=>{try{let o=le(r);return o?rr(o.env):!1}catch{return!1}})}function rd(e){try{let t=le(b(e,".claude","settings.json"));return t?rr(t.env):!1}catch{return!1}}function js(e){return Array.isArray(e)?e:[]}function Bt(e){let t=[],n=r=>!!r&&typeof r=="object"&&Hs(r.command);for(let r of js(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 $s(e,t){return[...Bt(e),...t]}function ar(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!Hs(t.command)):[]}function od(e,t){return[...ar(e),{command:t}]}function sd(e){return typeof e=="string"?[e]:e}function id(e){let t=(n="")=>({hooks:sd(e).map(r=>({type:"command",command:Ft(n,r)}))});return{SessionStart:[t("SessionStart")],UserPromptExpansion:[t()],UserPromptSubmit:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function ad(e){let t=typeof e=="string"?{command:e}:e,n=(r="")=>({hooks:[{type:"command",command:Ft(r,t.command),...t.commandWindows===void 0?{}:{commandWindows:Ft(r,t.commandWindows)},statusMessage:Bo}]});return{SessionStart:[n("SessionStart")],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var cd=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","beforeReadFile","beforeMCPExecution","subagentStart","subagentStop","stop"],ud=["afterShellExecution","afterFileEdit"];function ld(e,t=ud){let n={...e};for(let r of t){if(!(r in n))continue;let o=ar(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function dd(e,t,n={}){let r=b(e,".claude/settings.json"),o=ir(t,"claude"),s=le(r)??{};if(nd(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let p of Object.keys(u))u[p]=Bt(u[p]),js(u[p]).length===0&&delete u[p];Object.keys(u).length===0?delete s.hooks:s.hooks=u,Se(r,s)}return!1}let a=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=id(o),l={...a};for(let[u,p]of Object.entries(c))l[u]=$s(a[u],p);return s.hooks=l,Se(r,s),!0}function pd(e,t){let n=b(e,".cursor/hooks.json"),r=ir(t,"cursor"),o=le(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=ld({...s});for(let a of cd)i[a]=od(i[a],Ft(a,r));Se(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:i})}function fd(e,t){let n=b(e,".codex/hooks.json"),r=ir(t,"codex"),o=le(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},i=ad(r),a={...s};for(let[c,l]of Object.entries(i))a[c]=$s(s[c],l);Se(n,{...o,hooks:a})}function md(e){let t=b(e,".claude/settings.json"),n=le(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let i=r[s],a=Bt(i);JSON.stringify(i)!==JSON.stringify(a)&&(o=!0),a.length===0?delete r[s]:r[s]=a}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,Se(t,n),f(`Removed ev-ai hooks from ${t}`))}function gd(e){let t=b(e,".cursor/hooks.json"),n=le(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=ar(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks"&&a!=="version").length===0){jt(t,{force:!0}),f(`Removed ${t}`);return}Se(t,{...n,hooks:r}),f(`Removed ev-ai hooks from ${t}`)}}function _d(e){let t=b(e,".codex/hooks.json"),n=le(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let i of Object.keys(r)){let a=r[i],c=Bt(a);JSON.stringify(a)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[i]:(r[i]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(a=>a!=="hooks").length===0){jt(t,{force:!0}),f(`Removed ${t}`);return}Se(t,{...n,hooks:r}),f(`Removed ev-ai hooks from ${t}`)}}function cr(e=process.platform,t=process.arch,n={}){if(e==="win32")throw new Error("Windows install is not supported yet. Use macOS/Linux, or wait for phase-2 native commands.");(n.requireBinaryArch??!0)&&Is(e,t)}async function Bs(e={}){let t=Fl(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??vs();cr(process.platform,process.arch,{requireBinaryArch:s==="binary"});let i=e.cwd??process.cwd(),a=await ie(i),{command:c,hookPath:l,strategy:u}=Ql(a,ue(),s),{installationId:p,storePath:m}=await Ht(a,{overrideId:e.installationId}),{manifestPath:d,wrote:_}=Fs(a,e),S=[];return n?f("Skipped Claude hook \u2014 --no-claude"):dd(a,c,{force:e.force})?(S.push("Claude"),e.force&&rd(a)&&f("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):f("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?f("Skipped Cursor hook \u2014 --no-cursor"):(pd(a,c),S.push("Cursor")),o?f("Skipped Codex hook \u2014 --no-codex"):(fd(a,c),S.push("Codex")),f(`Installed hook (${u}) at ${l}`),f(`Installation identity ${p} at ${m}`),_&&d?f(`Shared manifest written to ${d}`):f("Using package default collector config (no shared manifest file needed)"),f(S.length>0?`Wired ${S.join(", ")} hooks in ${a} (commands include --runner)`:`No runner hooks wired in ${a} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),u==="npx"?f("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):u==="project_binary"?f("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):u==="dev_mjs"&&f("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&d&&e.collectorUrl&&f("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:a,hookPath:l,manifestPath:d,installationStorePath:m,strategy:u}}async function Ks(e=process.cwd()){cr(process.platform,process.arch,{requireBinaryArch:!0});let t=await ie(e),{projectPath:n,globalPath:r}=Yl(t);f(`Refreshed ${r}`),f(`Refreshed ${n}`),f("Hook configs and shared manifest left unchanged")}async function Gs(e={}){let t=Hl(e);e.collectorUrl=t,cr(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await ie(n),{manifestPath:o,wrote:s}=Fs(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?f(`Wrote ${o}`):t===void 0&&f("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),f("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function zs(e){for(let t of[()=>md(e),()=>gd(e),()=>_d(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: strip skipped a hook file: ${r}`)}}async function Vs(e=process.cwd()){let t=await ie(e);return zs(t),f("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),f("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function Ws(e=process.cwd()){let t=await ie(e);zs(t);for(let n of Pt){let r=b(t,n);if(he(r))try{jt(r,{force:!0}),f(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);f(`WARN: uninstall could not remove ${r}: ${s}`)}}}import{createHash as Qf}from"node:crypto";import{existsSync as em,mkdirSync as tm,readdirSync as nm,readFileSync as Qi,unlinkSync as ea,writeFileSync as rm}from"node:fs";import{homedir as ta}from"node:os";import{join as xr}from"node:path";import{existsSync as xd}from"node:fs";import{existsSync as hd}from"node:fs";import{homedir as Ys}from"node:os";import{join as Sd}from"node:path";function Xs(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Ed={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 Js(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function yd(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:Js(n.mcpJson,t.mcpJson),mcpToml:Js(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function Zs(e){return Object.fromEntries(Object.entries(Ed).map(([t,n])=>[t,yd(n,n[e])]))}var He=Zs("homeOnly"),ye=Zs("projectOnly");function Rd(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function Cd(e,t){return Rd(e).some(n=>hd(Sd(t,n)))}function qs(e,t){for(let n of e)if(Cd(n,t))return!0;return!1}function Ee(e){return[...new Set(e)]}function Re(e){let t=[],n=[],r=[],o=[],s=[],i=[],a=[];for(let c of e){t.push(...c.skillRoots);for(let l of c.dirs)l.kind==="SUBAGENT"?n.push(l.dir):l.kind==="COMMAND"?r.push(l.dir):o.push(l.dir);s.push(...c.memory.flat()),i.push(...c.settings),a.push(...c.mcpJson??[],...c.mcpToml??[])}return{skills:Ee(t),subagents:Ee(n),commands:Ee(r),rules:Ee(o),memory:Ee(s),settings:Ee(i),mcp:Ee(a)}}function Ad(e,t=Ys(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...Lt(o.managed,n,t));return Ee(r)}var Ce=Re(Object.values(He));function Qs(e=Ys(),t=process.platform){return Ad(Object.values(He),e,t)}import{existsSync as Id}from"node:fs";import{resolve as ur}from"node:path";function V(e){return ur(e).replaceAll("\\","/").replace(/\/$/,"")}function be(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function Kt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var kd=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function ot(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!kd.test(t)?null:t}function Fe(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=V(o);n.has(s)||(n.add(s),r.push(s))}return r}function Od(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function ee(e,t,n,r=Id){for(let o of e)for(let s of t){let i=V(ur(o,s)),a=ur(o,s,n).replaceAll("\\","/");if(Od(i,a)&&r(a))return a}return null}var ti=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,ni=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Pd=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,ei=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"]),bd=/^[a-z][a-z0-9-]{1,63}$/,Td=[".cursor/skills",".claude/skills",".agents/skills"],Nd=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],vd=be(Td,Re(Object.values(ye)).skills),wd=be(Nd,Re(Object.values(He)).skills),Md=new Set(["read","read_file","view"]),Ld=new Set(["bash","shell","zsh"]);function lr(e){let t=e.replace(/\\/g,"/");return ti.exec(t)?.[1]??null}function Ud(e){let t=e.replace(/\\/g,"/"),r=ni.exec(t)?.[1];return r?r.toLowerCase():null}function Dd(e){return lr(e)??Ud(e)}function Hd(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function Gt(e){return typeof e=="string"?Gt($(e,null)):!e||typeof e!="object"?null:Hd(e)}function ri(e){if(typeof e=="string")return ri($(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function dr(e){let t=ri(e.tool_input);if(t)return t;let n=xe(e.command);return n.length>0?n:null}function Fd(e){let t=e.replace(/\\/g,"/"),n=ti.exec(t);if(n?.[1])return n[1];let o=ni.exec(t)?.[1];return o?o.toLowerCase():null}function jd(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function pr(e){let t=Gt(e.tool_input)??xe(e.file_path);return t.length>0?t:null}function st(e,t,n){let r=jd(e).toLowerCase();if(Md.has(r)){let o=pr(e);return o?t(o):null}if(Ld.has(r)){let o=dr(e);return o?n(o):null}return null}function oi(e){return st(e,Dd,Fd)}function $d(e){let t=new Set,n=[];for(let r of e.matchAll(Pd)){let o=r[1]?.toLowerCase();!o||t.has(o)||Bd(o)||(t.add(o),n.push(o))}return n}function Bd(e){let t=e.split("/")[0];return ei.has(e)||t!==void 0&&ei.has(t)}function si(e){let t=e.skillId.toLowerCase();if(!bd.test(t))return null;let n=e.exists??xd,r=`${t}/SKILL.md`,o=ee(Fe(e.launchCwd,e.gitRoot),vd,r,n);return o!==null?o:e.home?ee([V(e.home)],wd,r,n):null}function Kd(e){return xe(e.prompt)}function ii(e){let t=h(e,"command_name");if(t){let r=h(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Kd(e);return n?$d(n):[]}var Er=Xe(Be(),1);import{existsSync as If}from"node:fs";var Ne={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function at(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Af(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return at(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return at(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?at(o[1]):at(t)}async function ct(e=process.cwd()){let t=await Y("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([Y("git",["remote","get-url","origin"],2e3,{cwd:e}),Y("git",["branch","--show-current"],2e3,{cwd:e}),Y("git",["rev-parse","HEAD"],2e3,{cwd:e}),Y("git",["status","--porcelain"],2e3,{cwd:e})]),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 bi(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ne[n];if(!a)return"";let c=ls(n,e.scope_path,i);if(s){let _=Ss(s,c);if(_)return _}let l=o??await ct(r),u=l?.remote?Af(l.remote):"";if(u||(u=at(process.env.GITHUB_REPOSITORY??"")),!u)return"";let p=e.scope_path??"",m=p?`${p}/`:"",d=`${u}:${m}${a}`;return s&&Es(s,c,d),d}var kf=[".cursor/rules",".claude/rules",".codex/rules"],Of=Re(Object.values(ye)).rules;function xf(e){return be(Kt(e?Ne[e]:void 0,kf),Of)}var Pf=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function Ti(e){let t=ot(e.relativePath);if(!t)return null;let n=e.exists??If,r=Fe(e.launchCwd,e.gitRoot),o=xf(e.runnerPlatform),s=ee(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=ee(r,["."],t,n);if(i!==null)return i}return e.home?ee([V(e.home)],o,t,n):null}function bf(e){let t=e.replace(/\\/g,"/"),r=Pf.exec(t)?.[1];return r?(0,Er.nativeKeyForRulePath)(r):null}function Ni(e){return st(e,Er.nativeKeyForRulePath,bf)}function vi(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function wi(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=ot(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var yr=Xe(Be(),1);import{existsSync as Tf}from"node:fs";var Nf=[".cursor/commands",".claude/commands",".codex/prompts"],vf=Re(Object.values(ye)).commands;function wf(e){return be(Kt(e?Ne[e]:void 0,Nf),vf)}var Mf=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function Mi(e){let t=ot(e.commandId);if(!t)return null;let n=e.exists??Tf,r=`${t}.md`,o=wf(e.runnerPlatform),s=ee(Fe(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?ee([V(e.home)],o,r,n):null}function Lf(e){let t=e.replace(/\\/g,"/"),r=Mf.exec(t)?.[1];return r?(0,yr.nativeKeyForCommandPath)(r):null}function Li(e){return st(e,yr.nativeKeyForCommandPath,Lf)}import{existsSync as Di}from"node:fs";import{homedir as Hi}from"node:os";import{join as ut,resolve as Rr,sep as Ui}from"node:path";function Cr(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Ar(e,t){let n=t.toLowerCase();return Cr(e).some(r=>r.toLowerCase()===n)}function Xt(e,t,n){if(!Di(e))return;let r=H(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function Uf(e,t,n){if(!Di(e))return;let r=H(e,{}),o=Rr(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Rr(a);(o===c||o.startsWith(c.endsWith(Ui)?c:c+Ui))&&(s===null||c.length>Rr(s).length)&&(s=a)}if(s===null)return;let i=r.projects?.[s]?.mcpServers??{};for(let[a,c]of Object.entries(i))n.set(a,{declared:{name:a,source:"claude_json_project",sourcePath:".claude.json",scope:"user"},config:c})}function Fi(e,t,n,r){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{declared:{name:s.name,source:"manifest"}});return n==="claude"?(Xt(ut(r,".claude.json"),{source:"claude_json_user"},o),Uf(ut(r,".claude.json"),t,o)):n==="cursor"&&Xt(ut(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),Xt(ut(t,".mcp.json"),{source:"mcp_json"},o),Xt(ut(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function Ir(e,t=process.cwd(),n="claude",r=Hi()){return[...Fi(e,t,n,r).values()].map(o=>o.declared)}function ji(e,t,n=process.cwd(),r="claude",o=Hi()){let s=Fi(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Ar(a,e))return c.config??null;return null}function kr(e){let t=Po(e);if(t.problem){f(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function $i(e,t){if(h(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Df(){return!!(A("CURSOR_VERSION")??A("CURSOR_PROJECT_DIR"))}function Or(e,t,n){return e!=="claude"&&e!=="codex"?!1:$i(t,n)?!0:Df()}function lt(e,t,n,r){if($i(e,t))return"cursor";if(bt(r))return r;let o=h(e,"conversation_id"),s=h(e,"turn_id"),i=h(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion"||a==="userpromptsubmit")&&(c="claude"),bt(n)&&(c=n),c}function Zt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Hf(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 Bi(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function Ki(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function Gi(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function zi(e,t,n){let r=h(e,"session_id")||h(e,"conversation_id"),o=h(e,"prompt.id")||h(e,"prompt_id")||h(e,"generation_id")||h(e,"turn_id"),s=h(e,"hook_event_name")||h(e,"event"),i=h(e,"source"),a=lt(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Ff=["session_start","session_end","tool_invoked","skill_invoked"];function jf(e){return Ff.includes(e)}function Vi(e,t){return e&&jf(e)?e:Hf(t.toLowerCase())}var $f={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Wi(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ji(e,t=""){let n=h(e,"tool_name")||h(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Wi(n)&&(n=`MCP:${n}`):n=$f[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?xe(o.skill)||xe(o.skill_name):"")||h(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=oi(a);let c=Ni(a),l=Li(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var Bf=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Yi(e){for(let t of["subagent_type","agent_type"]){let n=h(e,t);if(n&&Bf.test(n))return n}return null}function Xi(e){let t=ae(e,"duration_ms");if(typeof t=="number")return t;let n=ae(e,"duration");return typeof n=="number"?n:null}var Kf="error",Gf="interrupted",zf="permission_denied",Vf=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function dt(e){return Vf.test(e)?e:null}function Wf(e){for(let t of["failure_type","error_type"]){let n=dt(h(e,t));if(n)return n}return null}function Zi(e,t){return ae(e,"is_interrupt")===!0?Gf:t.toLowerCase()==="permissiondenied"?zf:Wf(e)??Kf}function Jf(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 Yf(e,t){let n=null;for(let r of t)!r||!Ar(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function Xf(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of Cr(s)){let a=`${i}__`;e.length>a.length&&e.slice(0,a.length).toLowerCase()===a.toLowerCase()&&i.length>r&&(n={mcpServer:s,mcpTool:e.slice(a.length)},r=i.length)}if(n!==null)return n;let o=/^(.+?)__(.+)$/.exec(e);return!o?.[1]||!o[2]?{mcpServer:null,mcpTool:null}:{mcpServer:Yf(o[1],t)??o[1],mcpTool:o[2]}}function Zf(e,t){if(/^mcp__/i.test(e))return Xf(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:Jf(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function qf(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function qi(e,t=[],n=""){let r=e?Zf(e,t):{mcpServer:null,mcpTool:null},o=dt(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Wi(e)&&(s=e),s&&(s=qf(s,o)),{mcpServer:o,mcpTool:s}}var na=3e4,om="claims",sm=!0,im=100,am=new Set(["sessionstart","sessionend","stopfailure"]),cm=["tool_name","tool","command","file_path","url"];function um(e=ta()){return xr(ce(e),om)}function ra(e){let t=e.split(`
|
|
25
25
|
`,1)[0]??"";return Number(t.trim())}function oa(e){return Qf("sha256").update(e).digest("hex").slice(0,32)}function lm(e){let t=[];for(let n of cm){let r=h(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":oa(t.join("\0"))}function dm(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=am.has(n);if(!a&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return oa(`${l}|${t}|${n}|${r}|${o}|${i}|${s}`)}function pm(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function fm(e,t){return xr(e,t)}function mm(e,t=Date.now()){let n;try{n=nm(e)}catch{return}let r=0;for(let o of n){if(r>=im)break;r+=1;let s=xr(e,o),i=Number.NaN;try{i=ra(Qi(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<na))try{ea(s)}catch{}}}function gm(e,t,n=Date.now()){let r=fm(t,e);try{if(em(r)){let o=Number.NaN;try{o=ra(Qi(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<na)return!1;try{ea(r)}catch{}}}catch{}try{tm(t,{recursive:!0}),rm(r,`${n}
|
|
26
|
-
`,{encoding:"utf8",flag:"wx"})}catch(o){if(pm(o))return!1;let s=o instanceof Error?o.message:String(o);return f(`WARN: event claim failed open: ${s}`),!0}return mm(t,n),!0}function _m(e,t,n){let r=h(e,"session_id")||h(e,"conversation_id"),o=h(e,"prompt.id")||h(e,"prompt_id")||h(e,"generation_id")||h(e,"turn_id"),s=h(e,"tool_use_id"),i=h(e,"subagent_id")||h(e,"agent_id"),a=lt(e,t,void 0,n),c=lm(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function sa(e,t,n,r=ta(),o=Date.now()){if(!sm)return!0;let s=dm(_m(e,t,n));if(!s)return!0;let i=gm(s,um(r),o);return!i&&A("EV_AI_HOOK_DEBUG")&&f(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{closeSync as hm,writeSync as Sm}from"node:fs";var Em=Buffer.from([1]),ia=Mo;function aa(e=process.env){let t=e[ia];if(delete e[ia],t===void 0)return;let n=Number.parseInt(t,10);if(!(!Number.isInteger(n)||n<3)){try{Sm(n,Em)}catch{}try{hm(n)}catch{}}}function Pr(e=process.env){let t=e[To];if(!t)return;let n=e[vo],r=e[wo];return{launcherVersion:t,hookSource:e[No]??"",fallbackReason:n??void 0,launcherScope:r??void 0}}function ca(e,t){return(e?bo(e):void 0)===t}import{realpathSync as
|
|
27
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: cloud cache write failed open: ${r}`)}}function bm(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?km:Im;return n-e.probed_at<r}async function Tm(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 Nm(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 vm(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 wm(e){let t=await Promise.allSettled([Tm(e),Nm(e),vm(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function br(e,t){if(e==="interactive")return null;let n=t?.home??ua(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Om(n),i=xm(s);if(bm(i,e,o))return i.result;let a=await wm(r);return Pm(s,{context:e,probed_at:o,result:a}),a}var Mm=["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"],Lm=["CURSOR_PROJECT_DIR"],Um=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Dm(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Um.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Tr(e=process.env){let t=Mm.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Dm(e[r]??"")}:{name:r,present:!1}),n=Lm.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as fg}from"node:os";import{homedir as la}from"node:os";import{join as Hm}from"node:path";function Fm(e=la()){return Hm(e,".claude.json")}function qt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function da(e=la()){let n=H(Fm(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=qt(n.emailAddress),o=qt(n.fullName)??qt(n.displayName),s=qt(n.accountUuid),i=r??s;return!i||z(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as ma}from"node:os";import{join as pa}from"node:path";var jm="https://api.openai.com/auth";function
|
|
26
|
+
`,{encoding:"utf8",flag:"wx"})}catch(o){if(pm(o))return!1;let s=o instanceof Error?o.message:String(o);return f(`WARN: event claim failed open: ${s}`),!0}return mm(t,n),!0}function _m(e,t,n){let r=h(e,"session_id")||h(e,"conversation_id"),o=h(e,"prompt.id")||h(e,"prompt_id")||h(e,"generation_id")||h(e,"turn_id"),s=h(e,"tool_use_id"),i=h(e,"subagent_id")||h(e,"agent_id"),a=lt(e,t,void 0,n),c=lm(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function sa(e,t,n,r=ta(),o=Date.now()){if(!sm)return!0;let s=dm(_m(e,t,n));if(!s)return!0;let i=gm(s,um(r),o);return!i&&A("EV_AI_HOOK_DEBUG")&&f(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{closeSync as hm,writeSync as Sm}from"node:fs";var Em=Buffer.from([1]),ia=Mo;function aa(e=process.env){let t=e[ia];if(delete e[ia],t===void 0)return;let n=Number.parseInt(t,10);if(!(!Number.isInteger(n)||n<3)){try{Sm(n,Em)}catch{}try{hm(n)}catch{}}}function Pr(e=process.env){let t=e[To];if(!t)return;let n=e[vo],r=e[wo];return{launcherVersion:t,hookSource:e[No]??"",fallbackReason:n??void 0,launcherScope:r??void 0}}function ca(e,t){return(e?bo(e):void 0)===t}import{realpathSync as nS}from"node:fs";import{homedir as Qc}from"node:os";var O=Xe(Be(),1);import{existsSync as ym,readFileSync as Rm}from"node:fs";import{homedir as ua}from"node:os";import{join as Cm}from"node:path";var Am="cloud-cache.json",Im=1440*60*1e3,km=900*1e3;function Om(e=ua()){return Cm(ce(e),Am)}function xm(e){if(!ym(e))return;let t=$(Rm(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 Pm(e,t){try{Q(e,`${JSON.stringify(t)}
|
|
27
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: cloud cache write failed open: ${r}`)}}function bm(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?km:Im;return n-e.probed_at<r}async function Tm(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 Nm(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 vm(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 wm(e){let t=await Promise.allSettled([Tm(e),Nm(e),vm(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function br(e,t){if(e==="interactive")return null;let n=t?.home??ua(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Om(n),i=xm(s);if(bm(i,e,o))return i.result;let a=await wm(r);return Pm(s,{context:e,probed_at:o,result:a}),a}var Mm=["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"],Lm=["CURSOR_PROJECT_DIR"],Um=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Dm(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Um.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Tr(e=process.env){let t=Mm.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Dm(e[r]??"")}:{name:r,present:!1}),n=Lm.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as fg}from"node:os";import{homedir as la}from"node:os";import{join as Hm}from"node:path";function Fm(e=la()){return Hm(e,".claude.json")}function qt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function da(e=la()){let n=H(Fm(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=qt(n.emailAddress),o=qt(n.fullName)??qt(n.displayName),s=qt(n.accountUuid),i=r??s;return!i||z(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as ma}from"node:os";import{join as pa}from"node:path";var jm="https://api.openai.com/auth";function Ke(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ga(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function $m(e){let t=e.split(".");if(t.length!==3||t.some(r=>r.length===0))return null;let n=t[1];if(!n)return null;try{let r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"));return ga(r)}catch{return null}}function fa(e,t,n){return Ke(e[n])??Ke(t?.[n])}function Bm(e=process.env,t=ma()){let n=Ke(e.CODEX_HOME)??pa(t,".codex");return pa(n,"auth.json")}function _a(e=process.env,t=ma()){let n=H(Bm(e,t),{}),r=Ke(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Ke(n.OPENAI_API_KEY))return null;let o=Ke(n.tokens?.id_token);if(!o)return null;let s=$m(o);if(!s)return null;let i=ga(s[jm]),a=fa(s,i,"name"),c=fa(s,i,"email");return!c||z(a,c)?null:{git_user_name:null,git_user_email:null,platform_login:c,identity_source:"codex_oauth"}}import{homedir as tn}from"node:os";import{join as fe}from"node:path";import{join as Km}from"node:path";var Gm="cursor-ide-identity.json",zm=et;function Sa(e){return Km(ce(e),Gm)}function ha(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ea(e){let t=H(e,{}),n=t.read_at_ms,r=t.db_path;if(!(typeof n!="number"||!Number.isFinite(n)||typeof r!="string"))return{read_at_ms:n,db_path:r,email:ha(t.email),auth_id:ha(t.auth_id)}}function ya(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<zm}function Ra(e,t){try{Q(e,`${JSON.stringify(t)}
|
|
28
28
|
`)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as Vm}from"node:child_process";import{existsSync as Wm}from"node:fs";import{createRequire as Jm}from"node:module";import{pathToFileURL as Ym}from"node:url";var Aa=Jm(import.meta.url),Qt=`
|
|
29
29
|
SELECT key, value
|
|
30
30
|
FROM ItemTable
|
|
@@ -35,17 +35,17 @@ ORDER BY key
|
|
|
35
35
|
`.trim(),Nr=new Map;function Ca(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:null}if(e instanceof Uint8Array){let t=Buffer.from(e).toString("utf8").trim();return t.length>0?t:null}return null}function Ia(e){return e.toLowerCase().includes("token")}function ka(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=Ca(r.key),s=Ca(r.value);o&&s&&!Ia(o)&&t.set(o,s)}return t}function Xm(e){let t=Ym(e);return t.search="mode=ro&immutable=1",t.href}function Zm(e){try{let t=Aa("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(Qt)??n.prepare(Qt);return ka(r.all?.())}finally{n.close?.()}}catch{return null}}function qm(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 Qm(e){try{return qm(()=>{let t=Aa("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return ka(n.prepare(Qt).all?.())}finally{n.close?.()}})}catch{return null}}function eg(e){let t=new Map;for(let n of e.split(`
|
|
36
36
|
`)){let r=n.trimEnd();if(!r)continue;let o=r.indexOf(" ");if(o<=0)continue;let s=r.slice(0,o).trim(),i=r.slice(o+1).trim();s&&i&&!Ia(s)&&t.set(s,i)}return t}function tg(e){try{let t=Vm("sqlite3",["-noheader","-batch","-separator"," ",e,Qt],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return eg(t)}catch{return null}}function Oa(e){let t=Nr.get(e);if(t)return t;if(!Wm(e)){let o=new Map;return Nr.set(e,o),o}let n=Xm(e),r=Zm(n)??tg(n)??Qm(n)??new Map;return Nr.set(e,r),r}var ng="cursorAuth/cachedEmail",rg="cursorAuth/stripeMembershipAuthId";function en(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function og(e=tn(),t=process.platform,n=process.env){let r=en(n.VSCODE_PORTABLE);if(r)return fe(r,"user-data");let o=en(n.VSCODE_APPDATA);if(o)return fe(o,"Cursor");switch(t){case"darwin":return fe(e,"Library","Application Support","Cursor");case"win32":return fe(en(n.APPDATA)??fe(e,"AppData","Roaming"),"Cursor");default:return fe(en(n.XDG_CONFIG_HOME)??fe(e,".config"),"Cursor")}}function sg(e=tn()){return fe(e,".cursor","cli-config.json")}function ig(e=tn(),t=process.platform,n=process.env){return fe(og(e,t,n),"User","globalStorage","state.vscdb")}function pt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ag(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):pt(e.userId)}function cg(e){return pt(e.email)??pt(e.authId)??ag(e)}function vr(e){let t=pt(e.email),n=pt(e.displayName),r=cg(e);return!r||z(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function ug(e){let n=H(sg(e),{}).authInfo;return!n||typeof n!="object"?null:vr(n)}function lg(e,t,n){let r=ig(e,process.platform,t),o=Sa(e),s=Ea(o);if(ya(s,r,n))return vr({email:s?.email,authId:s?.auth_id});let i=Oa(r),a=i.get(ng)??null,c=i.get(rg)??null;return Ra(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),vr({email:a,authId:c})}function xa(e=tn(),t=process.env,n=Date.now()){return ug(e)??lg(e,t,n)}import{createHash as dg}from"node:crypto";import{resolve as pg}from"node:path";function D(e){return dg("sha256").update(e).digest("hex").slice(0,16)}function wr(e){return D(pg(e))}function W(e,t){return`${e}\0${t}`}function Pa(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function ft(e){let n=[...e].sort((r,o)=>{let s=r.path.localeCompare(o.path);return s!==0?s:r.name.localeCompare(o.name)}).map(r=>`${r.path}|${r.name}|${r.content_hash}`).join(`
|
|
37
37
|
`);return D(n)}function mg(e,t,n="git_config",r=null){return D(`${e??""}|${t??""}|${r??""}|${n}`)}function gg(e){let t=null,n=null;for(let r of e.split(`
|
|
38
|
-
`)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function _g(e,t=L){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return gg(n)}function hg(e=process.env){let t=k(e.GIT_AUTHOR_NAME),n=k(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=k(e.GIT_COMMITTER_NAME),o=k(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=k(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function me(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function Sg(e=process.env){let t=k(e.EV_AI_HOOK_OPERATOR_EMAIL),n=k(e.EV_AI_HOOK_OPERATOR_LOGIN),r=me(k(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=k(e.GITHUB_ACTOR)??k(e.GITHUB_TRIGGERING_ACTOR)??k(e.GITHUB_USER),s=me(o,null,"github",o);if(s)return s;let i=k(e.GITLAB_USER_LOGIN),a=k(e.GITLAB_USER_EMAIL),c=me(k(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let l=k(e.BUILD_REQUESTEDFOREMAIL),u=me(k(e.BUILD_REQUESTEDFOR),l,"azure_devops",l??k(e.BUILD_REQUESTEDFORID));if(u)return u;let p=k(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=me(k(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(m)return m;let d=k(e.BUILD_USER_EMAIL)??k(e.CHANGE_AUTHOR_EMAIL),_=me(k(e.BUILD_USER)??k(e.CHANGE_AUTHOR),d,"jenkins",d??k(e.BUILD_USER_ID));if(_)return _;let S=k(e.CIRCLE_USERNAME),E=me(S,null,"circleci",S);if(E)return E;let y=k(e.CODEBUILD_INITIATOR),R=me(y,null,"codebuild",y);if(R)return R;let j=k(e.DRONE_COMMIT_AUTHOR_EMAIL),T=k(e.DRONE_COMMIT_AUTHOR),P=me(T??k(e.DRONE_COMMIT_AUTHOR_NAME),j,"drone",j??T);if(P)return P;if(ba(e.CLAUDE_CODE_REMOTE)||ba(e.CURSOR_AGENT)){let F=k(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:F&&!z(null,F)?F:null,identity_source:"cloud"}}return null}function Mr(e){return!!((e.git_user_name??e.git_user_email)&&!z(e.git_user_name,e.git_user_email))}function k(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ba(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Eg(e,t,n){return e==="claude"?da(t):e==="cursor"?xa(t,n):e==="codex"?_a(n,t):null}async function Lr(e,t=L,n=process.env,r={}){let o=await _g(e,t),s=hg(n),i=Mr(o)?o:s&&Mr(s)?s:null,a=Eg(r.runnerPlatform,r.home??fg(),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=Sg(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:Mr(o)?"git_config":"git_env"}:c||(o.git_user_name||o.git_user_email?{...o,identity_source:"git_config"}:s||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Ur(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??L,s=e.env??process.env,i=await Lr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=mg(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?qn(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&gs(d,a,Ut())}}}function Dr(e){return e?!qn(e)?.operator_identity_hash:!0}function Ta(e){return!0}import{existsSync as z_,readFileSync as V_}from"node:fs";import{homedir as kc}from"node:os";import{join as We,resolve as W_}from"node:path";import{basename as H_,join as Ve}from"node:path";import{dirname as $a,resolve as on}from"node:path";import{existsSync as yg}from"node:fs";import{homedir as wa}from"node:os";import{relative as Ma,resolve as ne,sep as Ie}from"node:path";var Rg=["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"],Cg=["prompt","tool_input","tool_response","last_assistant_message","command"],Ag=new Set;function Ig(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return Ag}}function La(e){return Ua(e)==="allowlist"}function Ua(e){return A("EV_AI_HOOK_CAPTURE_CONTENT")?.toLowerCase()==="off"||e.capture_hook_input==="allowlist"?"allowlist":e.capture_hook_input==="full"||e.debug===!0||A("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"?"full":"content"}function kg(e){let t={};for(let n of Rg){let r=ae(e,n);r!==void 0&&(t[n]=r)}return t}function nn(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=ne(e),r=ne(t),o=Ma(r,n);return!o||o==="."?".":o.startsWith(`..${Ie}`)||o===".."||ne(r,o)!==n?null:o.split(Ie).join("/")}function Da(e,t){let n=Ma(ne(t),ne(e)).split(Ie).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Ha(e){return typeof e!="string"||e.length===0?null:ne(e).split(Ie).join("/")}function Og(){let e=A("CURSOR_PROJECT_DIR");if(!e)return null;let t=ne(e);return yg(t)?t.split(Ie).join("/"):null}function Fr(e,t){return nn(e,t)!==null}function xg(e,t){let n=ne(t??wa(),".cursor").split(Ie).join("/");return Fr(e,n)}function Pg(e,t,n){return t!==null&&Fr(e,t)?!0:t!==null&&xg(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&Fr(e,n.gitRoot)?!0:t===null}function Fa(e,t){let n=Ha(e.cwd);if(n!==null)return n;let r=ne(process.cwd()).split(Ie).join("/"),o=Og();return Pg(r,o,t)?r:o??r}function Kr(e,t={}){return Fa(e,t)}function Br(e,t=wa()){let n=ne(t).split(Ie).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Na(e,t,n){let r=Ha(n.launchCwd)??Fa(t,n);e.cwd=Br(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?nn(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var ja="\u2026[truncated]\u2026",jr=Buffer.byteLength(ja,"utf8"),bg=8;function mt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function va(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function Tg(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(n.length-t).toString("utf8")}function Ng(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=jr)return va(e,t);let r=t-jr,o=Math.ceil(r/2),s=Math.floor(r/2);return`${va(e,o)}${ja}${Tg(e,s)}`}function $r(e,t,n){if(typeof e=="string"){n.push({path:t,value:e,bytes:Buffer.byteLength(e,"utf8")});return}if(Array.isArray(e)){e.forEach((r,o)=>{$r(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||$r(o,[...t,r],n)}function vg(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let i=t[s];if(i===void 0)return;r=(Array.isArray(r),r[i])}let o=t[t.length-1];if(!(o===void 0||r===null||typeof r!="object")){if(Array.isArray(r)){r[o]=n;return}r[o]=n}}var wg=256;function Mg(e,t,n){let r=n,o=Math.max(n,e[0]?.bytes??n);for(;r<o;){let s=Math.ceil((r+o)/2),i=0;for(let a of e)a.bytes>s&&(i+=a.bytes-s);i>=t?r=s:o=s-1}return r}function Lg(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=mt(e);if(s<=t)return;let i=[];$r(e,[],i),i.sort((u,p)=>p.bytes-u.bytes);let a=i.filter(u=>u.bytes>n);if(a.length===0)return;let c=Mg(a,s-t,n),l=Math.max(n,Math.min(c,r-1));if(l>=r)return;r=l;for(let u of a)u.bytes>r&&vg(e,u.path,Ng(u.value,r))}}function Ug(e,t){let n=Math.max(0,t-wg),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:mt(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(mt(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function Hr(e,t){let n=mt(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,Lg(r,t,jr+bg),mt(r)>t&&Ug(r,t),r}function Dg(e,t,n){let r=Ig(n.runnerEvent);for(let o of Cg){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function rn(e,t,n={}){let r=Ua(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,Na(s,e,n),Hr(s,Dn)}let o=kg(e);return Na(o,e,n),r==="content"?(Dg(o,e,n),Hr(o,Dn)):Hr(o,jo)}function Hg(e){return typeof e=="string"&&e.length>0}function Gr(e){let t=on(e.home),n=on(e.launchCwd),r=e.gitRoot?on(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Hg(e.remote)&&r!==null&&r!==t&&(i=r,o.add(r)),n!==t&&!o.has(n)&&(s.push({scope:"cwd",dir:n}),o.add(n)),i!==null&&s.push({scope:"repo",dir:i});let a=null,c=r!==null&&nn(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=$a(r);for(;;){let u=on(l);if(u===t)break;let p=$a(u);if(p===u)break;if(e.hasProjectSpec(u)){s.push({scope:"parent",dir:u}),a=Da(u,n);break}l=p}}return{anchors:s,parentRel:a}}import{existsSync as Ka,readdirSync as Fg,realpathSync as jg}from"node:fs";import{basename as $g,dirname as Kg,relative as Bg,resolve as Gg,sep as zg}from"node:path";var zr=400,sn=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??_e}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=Gg(t).split(zg).join("/");return Br(r,this.home)}let n=Bg(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${D(Kg(t))}/${$g(t)}`:n}claimFile(t){try{let n=jg(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(!Ka(t))return[];try{return Fg(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(Ka(t))return H(t,n)}push(t){return this.components.length>=this.maxEntries?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Vr,readFileSync as Vg,statSync as Wg}from"node:fs";import{basename as Ga,join as gt,relative as za}from"node:path";var Wr=100*1024,Jg=4;function Yg(e){return e.length<=Wr?e:`${e.slice(0,Wr-1)}\u2026`}function Xg(e){try{let t=Vg(e),n=t.toString("utf8");return{hash:D(t),length:t.length,text:Yg(n)}}catch{return null}}var Ba={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Zg(e){return e in Ba?Ba[e]:"UNSPECIFIED"}function an(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Xg(t.absolutePath);if(!n)return!1;let r=t.name??Ga(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.componentPath(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=Zg(t.kind);return s&&(o.trigger=s),e.push(o)}function qg(e,t,n){let r=za(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Ga(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function ve(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Jr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Jr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Jg))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let d=gt(r,u.name,c);if(Vr(d)){let _=za(n,gt(r,u.name)).replace(/\\/g,"/");an(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:_||u.name});continue}Jr(e,{walkRoot:n,currentDir:gt(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){Jr(e,{walkRoot:n,currentDir:gt(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let p=u.name.toLowerCase();if(!l.some(d=>p.endsWith(d)))continue;let m=gt(r,u.name);an(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:qg(n,m,!0)})}}function Va(e){for(let t of e)if(Vr(t))try{if(Wg(t).size>0)return t}catch{continue}return e.find(t=>Vr(t))}var cn=Xe(Ke(),1);var Qg="<omitted>",e_=["package_name","package_spec","package_version","package_version_source"],Wa=100,Ja=120,un=[{raw:"tools",attr:"tools"},{raw:"autoApprove",attr:"auto_approve"},{raw:"auto_approve",attr:"auto_approve"},{raw:"alwaysAllow",attr:"always_allow"},{raw:"always_allow",attr:"always_allow"},{raw:"enabledTools",attr:"enabled_tools"},{raw:"enabled_tools",attr:"enabled_tools"},{raw:"disabledTools",attr:"disabled_tools"},{raw:"disabled_tools",attr:"disabled_tools"}],Ya=new Set(un.map(e=>e.attr)),t_=["enabled","disabled"],n_=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],r_=new Set(["type","command","url","args","env","envVars","headers",...t_,...n_,...un.map(e=>e.raw)]),o_=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",...e_,...Ya,...[...Ya].map(e=>`${e}_truncated`)]);function Xa(e,t){for(let n of t)r_.has(n)||o_.has(n)||(e[n]=Qg)}var s_=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,i_=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,a_=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,c_=/^bearer(?:\s+|$)/i;function ln(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Za(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Yr(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=ln(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function we(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function u_(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,cn.launchContainsCredentials)({kind:"url",url:e})||(0,cn.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=ht([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,cn.launchContainsCredentials)({kind:"url",url:r}):!0)}function qa(e,t,n){u_(t,n)&&(e.launch_had_credentials=!0)}function l_(e){return a_.test(e)||c_.test(e)?"<redacted>":e.includes("://")?we(e):e}function Qa(e){if(/^https?:\/\//i.test(e))return we(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Qa(e.slice(t+1))}`:l_(e)}function d_(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return s_.test(t)||i_.test(t)}function ht(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(d_(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Qa(r))}return t}function p_(e){let t=Za(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ja?r.slice(0,Ja):r))].sort();if(n.length!==0)return n.length>Wa?{names:n.slice(0,Wa),truncated:!0}:{names:n,truncated:!1}}function f_(e){let t=ln(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function ec(e,t){let n=new Set;for(let{raw:r,attr:o}of un){if(n.has(o)||!(r in t))continue;let s=t[r];if(o==="auto_approve"&&typeof s=="boolean"){e.auto_approve=s,n.add(o);continue}let i=p_(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function tc(e,t){let n=ln(e),r={transport:t};if(!n)return r;Xa(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.serverUrl=="string"?n.serverUrl:void 0,a=o??s??i,c=Za(n.args);a&&(r.command_or_url=we(a));let l=ht(c);l.length>0&&(r.args=l),qa(r,a,c);let u=f_(n.env_http_headers),p=[...new Set([...Yr(n.env),...Yr(n.envVars),...Yr(n.env_vars),...u.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();p.length>0&&(r.env_var_names=p),u.headers.length>0&&(r.env_http_header_names=[...new Set(u.headers)].sort());for(let S of["headers","http_headers","env_http_headers"])if(n[S]!==void 0&&n[S]!==null){r.headers_present=!0;break}let m=typeof n.auth=="string"?n.auth:void 0;m&&(r.auth=m);let d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let _=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return _&&(r.default_tools_approval_mode=_),ec(r,n),r}function nc(e){let t=ln(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function qr(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return D(JSON.stringify({name:e,attributes:r,enabled:n}))}function Ge(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function _t(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*\\[([^\\]]*)\\]`,"m").exec(e);return n?.[1]?[...n[1].matchAll(/"([^"]*)"|'([^']*)'/g)].map(r=>r[1]??r[2]??"").filter(r=>r.length>0):[]}function Zr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Xr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=Ge(n[1]);return r.length>0?r:void 0}function m_(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],Ge(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
|
|
38
|
+
`)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function _g(e,t=L){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return gg(n)}function hg(e=process.env){let t=k(e.GIT_AUTHOR_NAME),n=k(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=k(e.GIT_COMMITTER_NAME),o=k(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=k(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function me(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function Sg(e=process.env){let t=k(e.EV_AI_HOOK_OPERATOR_EMAIL),n=k(e.EV_AI_HOOK_OPERATOR_LOGIN),r=me(k(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=k(e.GITHUB_ACTOR)??k(e.GITHUB_TRIGGERING_ACTOR)??k(e.GITHUB_USER),s=me(o,null,"github",o);if(s)return s;let i=k(e.GITLAB_USER_LOGIN),a=k(e.GITLAB_USER_EMAIL),c=me(k(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let l=k(e.BUILD_REQUESTEDFOREMAIL),u=me(k(e.BUILD_REQUESTEDFOR),l,"azure_devops",l??k(e.BUILD_REQUESTEDFORID));if(u)return u;let p=k(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=me(k(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(m)return m;let d=k(e.BUILD_USER_EMAIL)??k(e.CHANGE_AUTHOR_EMAIL),_=me(k(e.BUILD_USER)??k(e.CHANGE_AUTHOR),d,"jenkins",d??k(e.BUILD_USER_ID));if(_)return _;let S=k(e.CIRCLE_USERNAME),E=me(S,null,"circleci",S);if(E)return E;let y=k(e.CODEBUILD_INITIATOR),R=me(y,null,"codebuild",y);if(R)return R;let j=k(e.DRONE_COMMIT_AUTHOR_EMAIL),T=k(e.DRONE_COMMIT_AUTHOR),P=me(T??k(e.DRONE_COMMIT_AUTHOR_NAME),j,"drone",j??T);if(P)return P;if(ba(e.CLAUDE_CODE_REMOTE)||ba(e.CURSOR_AGENT)){let F=k(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:F&&!z(null,F)?F:null,identity_source:"cloud"}}return null}function Mr(e){return!!((e.git_user_name??e.git_user_email)&&!z(e.git_user_name,e.git_user_email))}function k(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function ba(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Eg(e,t,n){return e==="claude"?da(t):e==="cursor"?xa(t,n):e==="codex"?_a(n,t):null}async function Lr(e,t=L,n=process.env,r={}){let o=await _g(e,t),s=hg(n),i=Mr(o)?o:s&&Mr(s)?s:null,a=Eg(r.runnerPlatform,r.home??fg(),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=Sg(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:Mr(o)?"git_config":"git_env"}:c||(o.git_user_name||o.git_user_email?{...o,identity_source:"git_config"}:s||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Ur(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??L,s=e.env??process.env,i=await Lr(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=mg(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?qn(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&gs(d,a,Ut())}}}function Dr(e){return e?!qn(e)?.operator_identity_hash:!0}function Ta(e){return!0}import{existsSync as z_,readFileSync as V_}from"node:fs";import{homedir as kc}from"node:os";import{join as We,resolve as W_}from"node:path";import{basename as H_,join as Ve}from"node:path";import{dirname as $a,resolve as on}from"node:path";import{existsSync as yg}from"node:fs";import{homedir as wa}from"node:os";import{relative as Ma,resolve as ne,sep as Ie}from"node:path";var Rg=["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"],Cg=["prompt","tool_input","tool_response","last_assistant_message","command"],Ag=new Set;function Ig(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return Ag}}function La(e){return Ua(e)==="allowlist"}function Ua(e){return A("EV_AI_HOOK_CAPTURE_CONTENT")?.toLowerCase()==="off"||e.capture_hook_input==="allowlist"?"allowlist":e.capture_hook_input==="full"||e.debug===!0||A("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"?"full":"content"}function kg(e){let t={};for(let n of Rg){let r=ae(e,n);r!==void 0&&(t[n]=r)}return t}function nn(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=ne(e),r=ne(t),o=Ma(r,n);return!o||o==="."?".":o.startsWith(`..${Ie}`)||o===".."||ne(r,o)!==n?null:o.split(Ie).join("/")}function Da(e,t){let n=Ma(ne(t),ne(e)).split(Ie).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Ha(e){return typeof e!="string"||e.length===0?null:ne(e).split(Ie).join("/")}function Og(){let e=A("CURSOR_PROJECT_DIR");if(!e)return null;let t=ne(e);return yg(t)?t.split(Ie).join("/"):null}function Fr(e,t){return nn(e,t)!==null}function xg(e,t){let n=ne(t??wa(),".cursor").split(Ie).join("/");return Fr(e,n)}function Pg(e,t,n){return t!==null&&Fr(e,t)?!0:t!==null&&xg(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&Fr(e,n.gitRoot)?!0:t===null}function Fa(e,t){let n=Ha(e.cwd);if(n!==null)return n;let r=ne(process.cwd()).split(Ie).join("/"),o=Og();return Pg(r,o,t)?r:o??r}function Br(e,t={}){return Fa(e,t)}function Kr(e,t=wa()){let n=ne(t).split(Ie).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Na(e,t,n){let r=Ha(n.launchCwd)??Fa(t,n);e.cwd=Kr(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?nn(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var ja="\u2026[truncated]\u2026",jr=Buffer.byteLength(ja,"utf8"),bg=8;function mt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function va(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function Tg(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(n.length-t).toString("utf8")}function Ng(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=jr)return va(e,t);let r=t-jr,o=Math.ceil(r/2),s=Math.floor(r/2);return`${va(e,o)}${ja}${Tg(e,s)}`}function $r(e,t,n){if(typeof e=="string"){n.push({path:t,value:e,bytes:Buffer.byteLength(e,"utf8")});return}if(Array.isArray(e)){e.forEach((r,o)=>{$r(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||$r(o,[...t,r],n)}function vg(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let i=t[s];if(i===void 0)return;r=(Array.isArray(r),r[i])}let o=t[t.length-1];if(!(o===void 0||r===null||typeof r!="object")){if(Array.isArray(r)){r[o]=n;return}r[o]=n}}var wg=256;function Mg(e,t,n){let r=n,o=Math.max(n,e[0]?.bytes??n);for(;r<o;){let s=Math.ceil((r+o)/2),i=0;for(let a of e)a.bytes>s&&(i+=a.bytes-s);i>=t?r=s:o=s-1}return r}function Lg(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=mt(e);if(s<=t)return;let i=[];$r(e,[],i),i.sort((u,p)=>p.bytes-u.bytes);let a=i.filter(u=>u.bytes>n);if(a.length===0)return;let c=Mg(a,s-t,n),l=Math.max(n,Math.min(c,r-1));if(l>=r)return;r=l;for(let u of a)u.bytes>r&&vg(e,u.path,Ng(u.value,r))}}function Ug(e,t){let n=Math.max(0,t-wg),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:mt(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(mt(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function Hr(e,t){let n=mt(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,Lg(r,t,jr+bg),mt(r)>t&&Ug(r,t),r}function Dg(e,t,n){let r=Ig(n.runnerEvent);for(let o of Cg){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function rn(e,t,n={}){let r=Ua(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,Na(s,e,n),Hr(s,Dn)}let o=kg(e);return Na(o,e,n),r==="content"?(Dg(o,e,n),Hr(o,Dn)):Hr(o,jo)}function Hg(e){return typeof e=="string"&&e.length>0}function Gr(e){let t=on(e.home),n=on(e.launchCwd),r=e.gitRoot?on(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Hg(e.remote)&&r!==null&&r!==t&&(i=r,o.add(r)),n!==t&&!o.has(n)&&(s.push({scope:"cwd",dir:n}),o.add(n)),i!==null&&s.push({scope:"repo",dir:i});let a=null,c=r!==null&&nn(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=$a(r);for(;;){let u=on(l);if(u===t)break;let p=$a(u);if(p===u)break;if(e.hasProjectSpec(u)){s.push({scope:"parent",dir:u}),a=Da(u,n);break}l=p}}return{anchors:s,parentRel:a}}import{existsSync as Ba,readdirSync as Fg,realpathSync as jg}from"node:fs";import{basename as $g,dirname as Bg,relative as Kg,resolve as Gg,sep as zg}from"node:path";var zr=400,sn=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??_e}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=Gg(t).split(zg).join("/");return Kr(r,this.home)}let n=Kg(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${D(Bg(t))}/${$g(t)}`:n}claimFile(t){try{let n=jg(t);return this.seenRealpaths.has(n)?!1:(this.seenRealpaths.add(n),!0)}catch{return this.seenRealpaths.has(t)?!1:(this.seenRealpaths.add(t),!0)}}get atGlobalCap(){return this.truncated||this.components.length>=this.maxEntries}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!Ba(t))return[];try{return Fg(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(Ba(t))return H(t,n)}push(t){return this.components.length>=this.maxEntries?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Vr,readFileSync as Vg,statSync as Wg}from"node:fs";import{basename as Ga,join as gt,relative as za}from"node:path";var Wr=100*1024,Jg=4;function Yg(e){return e.length<=Wr?e:`${e.slice(0,Wr-1)}\u2026`}function Xg(e){try{let t=Vg(e),n=t.toString("utf8");return{hash:D(t),length:t.length,text:Yg(n)}}catch{return null}}var Ka={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function Zg(e){return e in Ka?Ka[e]:"UNSPECIFIED"}function an(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Xg(t.absolutePath);if(!n)return!1;let r=t.name??Ga(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.componentPath(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=Zg(t.kind);return s&&(o.trigger=s),e.push(o)}function qg(e,t,n){let r=za(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Ga(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function ve(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Jr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Jr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Jg))for(let u of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!u.isDirectory())continue;let d=gt(r,u.name,c);if(Vr(d)){let _=za(n,gt(r,u.name)).replace(/\\/g,"/");an(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:_||u.name});continue}Jr(e,{walkRoot:n,currentDir:gt(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){Jr(e,{walkRoot:n,currentDir:gt(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let p=u.name.toLowerCase();if(!l.some(d=>p.endsWith(d)))continue;let m=gt(r,u.name);an(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:qg(n,m,!0)})}}function Va(e){for(let t of e)if(Vr(t))try{if(Wg(t).size>0)return t}catch{continue}return e.find(t=>Vr(t))}var cn=Xe(Be(),1);var Qg="<omitted>",e_=["package_name","package_spec","package_version","package_version_source"],Wa=100,Ja=120,un=[{raw:"tools",attr:"tools"},{raw:"autoApprove",attr:"auto_approve"},{raw:"auto_approve",attr:"auto_approve"},{raw:"alwaysAllow",attr:"always_allow"},{raw:"always_allow",attr:"always_allow"},{raw:"enabledTools",attr:"enabled_tools"},{raw:"enabled_tools",attr:"enabled_tools"},{raw:"disabledTools",attr:"disabled_tools"},{raw:"disabled_tools",attr:"disabled_tools"}],Ya=new Set(un.map(e=>e.attr)),t_=["enabled","disabled"],n_=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],r_=new Set(["type","command","url","args","env","envVars","headers",...t_,...n_,...un.map(e=>e.raw)]),o_=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",...e_,...Ya,...[...Ya].map(e=>`${e}_truncated`)]);function Xa(e,t){for(let n of t)r_.has(n)||o_.has(n)||(e[n]=Qg)}var s_=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,i_=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,a_=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,c_=/^bearer(?:\s+|$)/i;function ln(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Za(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Yr(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=ln(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function we(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function u_(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,cn.launchContainsCredentials)({kind:"url",url:e})||(0,cn.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=ht([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,cn.launchContainsCredentials)({kind:"url",url:r}):!0)}function qa(e,t,n){u_(t,n)&&(e.launch_had_credentials=!0)}function l_(e){return a_.test(e)||c_.test(e)?"<redacted>":e.includes("://")?we(e):e}function Qa(e){if(/^https?:\/\//i.test(e))return we(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Qa(e.slice(t+1))}`:l_(e)}function d_(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return s_.test(t)||i_.test(t)}function ht(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(d_(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Qa(r))}return t}function p_(e){let t=Za(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Ja?r.slice(0,Ja):r))].sort();if(n.length!==0)return n.length>Wa?{names:n.slice(0,Wa),truncated:!0}:{names:n,truncated:!1}}function f_(e){let t=ln(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function ec(e,t){let n=new Set;for(let{raw:r,attr:o}of un){if(n.has(o)||!(r in t))continue;let s=t[r];if(o==="auto_approve"&&typeof s=="boolean"){e.auto_approve=s,n.add(o);continue}let i=p_(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function tc(e,t){let n=ln(e),r={transport:t};if(!n)return r;Xa(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.serverUrl=="string"?n.serverUrl:void 0,a=o??s??i,c=Za(n.args);a&&(r.command_or_url=we(a));let l=ht(c);l.length>0&&(r.args=l),qa(r,a,c);let u=f_(n.env_http_headers),p=[...new Set([...Yr(n.env),...Yr(n.envVars),...Yr(n.env_vars),...u.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();p.length>0&&(r.env_var_names=p),u.headers.length>0&&(r.env_http_header_names=[...new Set(u.headers)].sort());for(let S of["headers","http_headers","env_http_headers"])if(n[S]!==void 0&&n[S]!==null){r.headers_present=!0;break}let m=typeof n.auth=="string"?n.auth:void 0;m&&(r.auth=m);let d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let _=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return _&&(r.default_tools_approval_mode=_),ec(r,n),r}function nc(e){let t=ln(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function qr(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return D(JSON.stringify({name:e,attributes:r,enabled:n}))}function Ge(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function _t(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*\\[([^\\]]*)\\]`,"m").exec(e);return n?.[1]?[...n[1].matchAll(/"([^"]*)"|'([^']*)'/g)].map(r=>r[1]??r[2]??"").filter(r=>r.length>0):[]}function Zr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Xr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=Ge(n[1]);return r.length>0?r:void 0}function m_(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],Ge(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
|
|
39
39
|
${e}`);return s?.[1]&&r(s[1]),n}function rc(e){return Zr(e,"enabled")===!1?!1:Zr(e,"disabled")!==!0}function g_(e,t){let n={};for(let{raw:r,attr:o}of un){if(o==="auto_approve"){let i=Zr(t,r);if(i!==void 0){n[r]=i;continue}}let s=_t(t,r);s.length>0&&(n[r]=s)}ec(e,n)}var __=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,h_=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function S_(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
|
|
40
40
|
`)){let s=__.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(h_))o[1]&&t.add(o[1]);return[...t]}function oc(e,t){let n={transport:t};Xa(n,S_(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?Ge(r[1]??""):void 0,i=o?Ge(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=_t(e,"args");a&&(n.command_or_url=we(a));let l=ht(c);l.length>0&&(n.args=l),qa(n,a,c);let u=new Set;for(let y of e.split(`
|
|
41
41
|
`)){let R=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}let p=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(p?.[1])for(let y of p[1].split(",")){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}let m=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
|
|
42
42
|
${e}`);if(m?.[1])for(let y of m[1].split(`
|
|
43
|
-
`)){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}for(let y of _t(e,"env_vars"))u.add(y);let d=m_(e,"env_http_headers");for(let[,y]of d)y.length>0&&u.add(y);let _=Xr(e,"bearer_token_env_var");_&&(u.add(_),n.bearer_token_env_var=_),u.size>0&&(n.env_var_names=[...u].sort()),d.length>0&&(n.env_http_header_names=[...new Set(d.map(([y])=>y))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let S=Xr(e,"auth");S&&(n.auth=S);let E=Xr(e,"default_tools_approval_mode");return E&&(n.default_tools_approval_mode=E),g_(n,e),n}var E_=300,y_=256;function sc(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function dn(e){let t=[],n="",r=null;for(let o of e){if(r){o===r?r=null:n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}function ic(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function R_(e){return ic(e,E_)}function ac(e,t){let n=sc(e.trim(),t),r=dn(n);if(r.length===0)return"";let[o,...s]=r,i=we(o),a=ht(s);return R_([i,...a].join(" "))}function cc(e,t){if(typeof e!="string")return null;let n=sc(e.trim(),t),r=dn(n)[0];if(!r)return null;let o=we(r);return o.length===0?null:ic(o,y_)}function C_(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 A_(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 I_(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 A_(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",p=C_({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",d=D(u),_=m?`${s}:${m}:${p}:${d}`:`${s}:${p}:${d}`,S=`${s}|${m}|${p}|${u}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:D(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:d,...p!=="prompt"&&u.trim()?{command:ac(u,e.home)}:{}}})}}}function ze(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||I_(e,t,r.hooks,n)}import{existsSync as T_,readFileSync as N_}from"node:fs";var ke=Xe(
|
|
44
|
-
`);return k_("sha512").update(t).digest("hex").slice(0,16)}function x_(e){let t=process.platform==="win32"?St(A("LOCALAPPDATA")??e,"npm-cache"):St(e,".npm"),n=A("npm_config_cache")??A("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function uc(e){return typeof e=="string"&&e.length>0&&e.length<=ke.PACKAGE_FIELD_MAX?e:null}function P_(e,t,n){let r=O_(e);for(let o of x_(n)){let s=St(o,"_npx",r),i=H(St(s,"node_modules",...t.split("/"),"package.json"),{}),a=uc(i.version);if(a!==null)return a;let c=H(St(s,"package-lock.json"),{}),l=uc(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function b_(e){return e.length<=ke.PACKAGE_FIELD_MAX?e:`${e.slice(0,ke.PACKAGE_FIELD_MAX-1)}\u2026`}function Qr(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,ke.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,ke.packageNameFromSpec)(o);if(s===null)return null;let i=P_(r,s,n);return{package_name:s,package_spec:b_(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function lc(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=dn(e.trim());return n===void 0?null:Qr(n,r,t)}function pn(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=Array.isArray(n.args)?n.args.filter(o=>typeof o=="string"):[];return Qr(typeof n.command=="string"?n.command:null,r,t)}function dc(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:Qr(Ge(n[1]??""),_t(e,"args"),t)}function v_(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function pc(e,t,n){if(!e.claimFile(t))return;let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.componentPath(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=v_(a),l=tc(a,c);Object.assign(l,pn(a,e.home)??{});let u=nc(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:qr(i,l,u),origin:n,enabled:u,attributes:l})}}function fc(e,t,n){if(!T_(t)||!e.claimFile(t))return;let r;try{r=N_(t,"utf8")}catch{return}let o=e.componentPath(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),l=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),p="unknown";/^\s*url\s*=/m.test(u)?p="http":/^\s*command\s*=/m.test(u)&&(p="stdio");let m=oc(u,p);Object.assign(m,dc(u,e.home)??{});let d=rc(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:qr(a,m,d),origin:n,enabled:d,attributes:m})}}import{existsSync as w_,readdirSync as M_}from"node:fs";import{join as G}from"node:path";var mc=50;function eo(e,t,n,r){if(!w_(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(mc,()=>{ve(e,{dir:G(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),ve(e,{dir:G(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),ve(e,{dir:G(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});ze(e,G(t,"hooks","hooks.json"),n),ze(e,G(t,"hooks.json"),n);let i=e.components.length-o,a=s>=mc;return{componentCount:i,expandTruncated:a}}function to(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function gc(e){let t=G(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(G(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,E=0,y=!1;for(let R of l)if(typeof R.installPath=="string"&&R.installPath.length>0){let j=eo(e,R.installPath,S,p);E+=j.componentCount,y=y||j.expandTruncated}to(e,{pluginKey:a,rowPath:i,enabled:p,scope:_,version:d||void 0,marketplace:m||void 0,componentCount:E,expandTruncated:y,contentHash:D(`${a}|${d}|${_}|${p}|${E}`)})}}function L_(e){let t=e,n="";try{let r=M_(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=G(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=G(e,s),n=s)}}catch{}return{installPath:t,version:n}}var U_=/^\d+$/;function D_(e){let t=e.filter(n=>!U_.test(n.pluginId));return t.length>0?t:e}function _c(e){let t=[{base:G(e.home,".cursor/plugins/local"),scope:"local"},{base:G(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=G(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:p}=eo(e,c,l,!0);to(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:p,contentHash:D(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(G(n,s))){if(!a.isDirectory())continue;let c=G(n,s,a.name),{installPath:l,version:u}=L_(c);i.push({pluginId:a.name,installPath:l,version:u})}for(let a of D_(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:p}=eo(e,a.installPath,l,!0);to(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:p,contentHash:D(`${c}|${a.version}|${u}`)})}}}function F_(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)ve(e,{dir:Ve(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)ve(e,{dir:Ve(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=Va(i.map(c=>Ve(r,c)));a&&an(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:H_(a)})}for(let i of Xs(n))ze(e,Ve(r,i),o);for(let i of n.mcpJson??[])pc(e,Ve(r,i),o);for(let i of n.mcpToml??[])fc(e,Ve(r,i),o);if(s){if(n.managed)for(let i of Lt(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&ze(e,i,o);n.plugins==="claude"?gc(e):n.plugins==="cursor"&&_c(e)}}function hc(e,t){try{let n=new sn(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)F_(n,{layout:r,levelDir:t.levelDir,origin:t.origin,includeMachineWide:t.includeMachineWide});return{scopeRef:t.scopeRef,anchor:t.levelDir,components:n.components,truncated:n.truncated}}catch{return}}function no(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=hc(t,{layouts:Object.values(He),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:_e,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(ye),l=Gr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>qs(c,u)});i=l.parentRel;for(let u of l.anchors){let p=wr(u.dir);if(o!==void 0&&!o(u.scope,p))continue;let m=hc(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:zr,scopeRef:p});m&&(r[u.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function ro(e,t,n={}){let r=n.truncated===!0,o=ft(e),s=new Set(e.map(u=>W(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let u of e){let p=W(u.path,u.name);c[p]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let p=Pa(u);p&&l.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:l,unchanged:a.length===0&&l.length===0}}var Ec=2*1024*1024,j_=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function oo(e,t,n){let r=new Set(t.map(s=>W(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(W(s.path,s.name))||o.push(s));return o}function so(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function Sc(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function yc(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function io(e,t=Ec){let n=[],r=[];for(let u of e)j_.has(u.kind)?n.push(u):r.push(u);r.sort((u,p)=>(u.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let p=s.length>0?1:0,m=Sc(u)+p;if(i+m<=t){s.push(u),i+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let d=yc(u),_=Sc(d)+p;if(i+_<=t){s.push(d),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function ao(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:yc(n))}var $_=["user","cwd","repo","parent"];function co(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let T of $_){let P=t.scopes[T];if(!P)continue;let F=n(T,P.scopeRef),U=F.components,K=ro(P.components,U,{forceFull:U===void 0,truncated:P.truncated}),re=new Set(F.textHashes),w=oo(P.components,K.upserts,re),M=ao([...K.upserts,...w],re);s.push({scope:T,walk:P,delta:K,outgoing:M,outgoingKeys:new Set(M.map(C=>W(C.path,C.name))),deliveredTextHashes:re,cachedComponents:U})}let i=s.flatMap(T=>T.outgoing),a=io(i,o),c=new Set(a.components.map(T=>W(T.path,T.name))),l=[],u=[],p=[],m=[],d=[],_=[],S=[];for(let T of s){let{scope:P,walk:F,delta:U}=T;_.push(...F.components),l.push(P);let K=a.components.filter(C=>T.outgoingKeys.has(W(C.path,C.name))),re=[...T.outgoingKeys].some(C=>!c.has(C)),w=U.truncated||re;w?p.push(P):U.full&&u.push(P),m.push(...K),!U.full&&!w&&d.push(...U.removed);let M=U.full?{}:{...T.cachedComponents??{}};if(!w)for(let C of U.removed)delete M[W(C.path,C.name)];for(let C of K)M[W(C.path,C.name)]=C.content_hash;S.push({scope:P,scopeRef:F.scopeRef,components:M,textHashes:so(T.deliveredTextHashes,K.filter(C=>C.text!==void 0).map(C=>C.content_hash),F.components),collectedAtMs:r,included:K.length>0||U.removed.length>0&&!w||U.full})}let E={user_spec_hash:ft(_),user_spec_count:_.length,user_spec_truncated:p.length>0};l.length>0&&(E.user_spec_scopes=l,E.user_spec_full_scopes=u,E.user_spec_truncated_scopes=p,E.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(E.user_spec_full=!0),m.length>0&&(E.user_spec=m),d.length>0&&(E.user_spec_removed=d),a.textDeferredCount>0&&(E.user_spec_text_deferred=a.textDeferredCount);let y=t.scopes.cwd;y&&(E.user_spec_cwd_scope_ref=y.scopeRef);let R=t.scopes.repo;R&&(E.user_spec_repo_scope_ref=R.scopeRef);let j=t.scopes.parent;return j&&(E.user_spec_parent_scope_ref=j.scopeRef,t.parentRel&&(E.user_spec_parent_rel=t.parentRel)),{fields:E,scopes:S}}var yt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function fn(e){return e==="cwd"||e==="repo"||e==="parent"}function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uo(e){return!Et(e)||!Et(e.components)||!Object.values(e.components).every(t=>typeof t=="string")||!Array.isArray(e.text_hashes)||!e.text_hashes.every(t=>typeof t=="string")?!1:typeof e.collected_at_ms=="number"&&Number.isFinite(e.collected_at_ms)}function Rc(e){return K_(e)}function Cc(e){return B_(e)}function Ac(e){return G_(e)}function K_(e){if(!Et(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function B_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function lo(e,t){if(!Et(e))return;let n=e[t];return uo(n)?n:void 0}function G_(e){if(!Et(e))return{};let t={};for(let[n,r]of Object.entries(e))uo(r)&&(t[n]=r);return t}function po(e,t=20){let n=[];for(let[r,o]of Object.entries(e))uo(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 J_=200,Ic=200,Y_=["allow","deny","ask"],X_=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,mo="<path>",Z_=new RegExp(`${mo}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function q_(e){let t=e.replace(X_,mo).replace(Z_,mo);return t.length>Ic?`${t.slice(0,Ic)}...`:t}function gn(e){let t=H(e,{}),n=[];for(let r of Y_)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:q_(o),mode:r});return{model:t.model??"",permissionKeys:n}}function Q_(e){let{serverManaged:t,fileBased:n}=Fn(process.platform,e),r=gn(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=gn(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function eh(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 th=10,nh="self-config-cache.json",Oc=2;function _n(){return A("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function rh(){return A("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function oh(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=et}var sh={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function ih(e,t=L){let n=sh[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
|
|
43
|
+
`)){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&u.add(R[1])}for(let y of _t(e,"env_vars"))u.add(y);let d=m_(e,"env_http_headers");for(let[,y]of d)y.length>0&&u.add(y);let _=Xr(e,"bearer_token_env_var");_&&(u.add(_),n.bearer_token_env_var=_),u.size>0&&(n.env_var_names=[...u].sort()),d.length>0&&(n.env_http_header_names=[...new Set(d.map(([y])=>y))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let S=Xr(e,"auth");S&&(n.auth=S);let E=Xr(e,"default_tools_approval_mode");return E&&(n.default_tools_approval_mode=E),g_(n,e),n}var E_=300,y_=256;function sc(e,t){if(!t)return e;let n=[...new Set([t,t.replace(/\\/g,"/")])].filter(o=>o.length>1),r=e;for(let o of n)r=r.split(o).join("~");return r}function dn(e){let t=[],n="",r=null;for(let o of e){if(r){o===r?r=null:n+=o;continue}if(o==='"'||o==="'"){r=o;continue}if(/\s/.test(o)){n.length>0&&(t.push(n),n="");continue}n+=o}return n.length>0&&t.push(n),t}function ic(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function R_(e){return ic(e,E_)}function ac(e,t){let n=sc(e.trim(),t),r=dn(n);if(r.length===0)return"";let[o,...s]=r,i=we(o),a=ht(s);return R_([i,...a].join(" "))}function cc(e,t){if(typeof e!="string")return null;let n=sc(e.trim(),t),r=dn(n)[0];if(!r)return null;let o=we(r);return o.length===0?null:ic(o,y_)}function C_(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 A_(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 I_(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 A_(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",p=C_({type:l.type??c.type,command:l.command??c.command,bash:l.bash??c.bash,powershell:l.powershell??c.powershell,prompt:l.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",d=D(u),_=m?`${s}:${m}:${p}:${d}`:`${s}:${p}:${d}`,S=`${s}|${m}|${p}|${u}|attrs2`;e.push({kind:"HOOK",name:_,path:o,content_hash:D(S),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:d,...p!=="prompt"&&u.trim()?{command:ac(u,e.home)}:{}}})}}}function ze(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||I_(e,t,r.hooks,n)}import{existsSync as T_,readFileSync as N_}from"node:fs";var ke=Xe(Be(),1);import{createHash as k_}from"node:crypto";import{join as St}from"node:path";function O_(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
|
|
44
|
+
`);return k_("sha512").update(t).digest("hex").slice(0,16)}function x_(e){let t=process.platform==="win32"?St(A("LOCALAPPDATA")??e,"npm-cache"):St(e,".npm"),n=A("npm_config_cache")??A("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function uc(e){return typeof e=="string"&&e.length>0&&e.length<=ke.PACKAGE_FIELD_MAX?e:null}function P_(e,t,n){let r=O_(e);for(let o of x_(n)){let s=St(o,"_npx",r),i=H(St(s,"node_modules",...t.split("/"),"package.json"),{}),a=uc(i.version);if(a!==null)return a;let c=H(St(s,"package-lock.json"),{}),l=uc(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function b_(e){return e.length<=ke.PACKAGE_FIELD_MAX?e:`${e.slice(0,ke.PACKAGE_FIELD_MAX-1)}\u2026`}function Qr(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,ke.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,ke.packageNameFromSpec)(o);if(s===null)return null;let i=P_(r,s,n);return{package_name:s,package_spec:b_(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function lc(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=dn(e.trim());return n===void 0?null:Qr(n,r,t)}function pn(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=Array.isArray(n.args)?n.args.filter(o=>typeof o=="string"):[];return Qr(typeof n.command=="string"?n.command:null,r,t)}function dc(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:Qr(Ge(n[1]??""),_t(e,"args"),t)}function v_(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function pc(e,t,n){if(!e.claimFile(t))return;let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.componentPath(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=v_(a),l=tc(a,c);Object.assign(l,pn(a,e.home)??{});let u=nc(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:qr(i,l,u),origin:n,enabled:u,attributes:l})}}function fc(e,t,n){if(!T_(t)||!e.claimFile(t))return;let r;try{r=N_(t,"utf8")}catch{return}let o=e.componentPath(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),l=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),u=l===-1?c:c.slice(0,l),p="unknown";/^\s*url\s*=/m.test(u)?p="http":/^\s*command\s*=/m.test(u)&&(p="stdio");let m=oc(u,p);Object.assign(m,dc(u,e.home)??{});let d=rc(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:qr(a,m,d),origin:n,enabled:d,attributes:m})}}import{existsSync as w_,readdirSync as M_}from"node:fs";import{join as G}from"node:path";var mc=50;function eo(e,t,n,r){if(!w_(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(mc,()=>{ve(e,{dir:G(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),ve(e,{dir:G(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),ve(e,{dir:G(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});ze(e,G(t,"hooks","hooks.json"),n),ze(e,G(t,"hooks.json"),n);let i=e.components.length-o,a=s>=mc;return{componentCount:i,expandTruncated:a}}function to(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function gc(e){let t=G(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(G(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",S=`plugin:${a}`,E=0,y=!1;for(let R of l)if(typeof R.installPath=="string"&&R.installPath.length>0){let j=eo(e,R.installPath,S,p);E+=j.componentCount,y=y||j.expandTruncated}to(e,{pluginKey:a,rowPath:i,enabled:p,scope:_,version:d||void 0,marketplace:m||void 0,componentCount:E,expandTruncated:y,contentHash:D(`${a}|${d}|${_}|${p}|${E}`)})}}function L_(e){let t=e,n="";try{let r=M_(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=G(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=G(e,s),n=s)}}catch{}return{installPath:t,version:n}}var U_=/^\d+$/;function D_(e){let t=e.filter(n=>!U_.test(n.pluginId));return t.length>0?t:e}function _c(e){let t=[{base:G(e.home,".cursor/plugins/local"),scope:"local"},{base:G(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=G(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:p}=eo(e,c,l,!0);to(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:p,contentHash:D(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(G(n,s))){if(!a.isDirectory())continue;let c=G(n,s,a.name),{installPath:l,version:u}=L_(c);i.push({pluginId:a.name,installPath:l,version:u})}for(let a of D_(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:p}=eo(e,a.installPath,l,!0);to(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:p,contentHash:D(`${c}|${a.version}|${u}`)})}}}function F_(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)ve(e,{dir:Ve(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)ve(e,{dir:Ve(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=Va(i.map(c=>Ve(r,c)));a&&an(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:H_(a)})}for(let i of Xs(n))ze(e,Ve(r,i),o);for(let i of n.mcpJson??[])pc(e,Ve(r,i),o);for(let i of n.mcpToml??[])fc(e,Ve(r,i),o);if(s){if(n.managed)for(let i of Lt(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&ze(e,i,o);n.plugins==="claude"?gc(e):n.plugins==="cursor"&&_c(e)}}function hc(e,t){try{let n=new sn(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)F_(n,{layout:r,levelDir:t.levelDir,origin:t.origin,includeMachineWide:t.includeMachineWide});return{scopeRef:t.scopeRef,anchor:t.levelDir,components:n.components,truncated:n.truncated}}catch{return}}function no(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=hc(t,{layouts:Object.values(He),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:_e,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(ye),l=Gr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>qs(c,u)});i=l.parentRel;for(let u of l.anchors){let p=wr(u.dir);if(o!==void 0&&!o(u.scope,p))continue;let m=hc(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:zr,scopeRef:p});m&&(r[u.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function ro(e,t,n={}){let r=n.truncated===!0,o=ft(e),s=new Set(e.map(u=>W(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let u of e){let p=W(u.path,u.name);c[p]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let p=Pa(u);p&&l.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:l,unchanged:a.length===0&&l.length===0}}var Ec=2*1024*1024,j_=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function oo(e,t,n){let r=new Set(t.map(s=>W(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(W(s.path,s.name))||o.push(s));return o}function so(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function Sc(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function yc(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function io(e,t=Ec){let n=[],r=[];for(let u of e)j_.has(u.kind)?n.push(u):r.push(u);r.sort((u,p)=>(u.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,l=[];for(let u of o){let p=s.length>0?1:0,m=Sc(u)+p;if(i+m<=t){s.push(u),i+=m,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let d=yc(u),_=Sc(d)+p;if(i+_<=t){s.push(d),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function ao(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:yc(n))}var $_=["user","cwd","repo","parent"];function co(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let T of $_){let P=t.scopes[T];if(!P)continue;let F=n(T,P.scopeRef),U=F.components,B=ro(P.components,U,{forceFull:U===void 0,truncated:P.truncated}),re=new Set(F.textHashes),w=oo(P.components,B.upserts,re),M=ao([...B.upserts,...w],re);s.push({scope:T,walk:P,delta:B,outgoing:M,outgoingKeys:new Set(M.map(C=>W(C.path,C.name))),deliveredTextHashes:re,cachedComponents:U})}let i=s.flatMap(T=>T.outgoing),a=io(i,o),c=new Set(a.components.map(T=>W(T.path,T.name))),l=[],u=[],p=[],m=[],d=[],_=[],S=[];for(let T of s){let{scope:P,walk:F,delta:U}=T;_.push(...F.components),l.push(P);let B=a.components.filter(C=>T.outgoingKeys.has(W(C.path,C.name))),re=[...T.outgoingKeys].some(C=>!c.has(C)),w=U.truncated||re;w?p.push(P):U.full&&u.push(P),m.push(...B),!U.full&&!w&&d.push(...U.removed);let M=U.full?{}:{...T.cachedComponents??{}};if(!w)for(let C of U.removed)delete M[W(C.path,C.name)];for(let C of B)M[W(C.path,C.name)]=C.content_hash;S.push({scope:P,scopeRef:F.scopeRef,components:M,textHashes:so(T.deliveredTextHashes,B.filter(C=>C.text!==void 0).map(C=>C.content_hash),F.components),collectedAtMs:r,included:B.length>0||U.removed.length>0&&!w||U.full})}let E={user_spec_hash:ft(_),user_spec_count:_.length,user_spec_truncated:p.length>0};l.length>0&&(E.user_spec_scopes=l,E.user_spec_full_scopes=u,E.user_spec_truncated_scopes=p,E.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(E.user_spec_full=!0),m.length>0&&(E.user_spec=m),d.length>0&&(E.user_spec_removed=d),a.textDeferredCount>0&&(E.user_spec_text_deferred=a.textDeferredCount);let y=t.scopes.cwd;y&&(E.user_spec_cwd_scope_ref=y.scopeRef);let R=t.scopes.repo;R&&(E.user_spec_repo_scope_ref=R.scopeRef);let j=t.scopes.parent;return j&&(E.user_spec_parent_scope_ref=j.scopeRef,t.parentRel&&(E.user_spec_parent_rel=t.parentRel)),{fields:E,scopes:S}}var yt={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function fn(e){return e==="cwd"||e==="repo"||e==="parent"}function Et(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function uo(e){return!Et(e)||!Et(e.components)||!Object.values(e.components).every(t=>typeof t=="string")||!Array.isArray(e.text_hashes)||!e.text_hashes.every(t=>typeof t=="string")?!1:typeof e.collected_at_ms=="number"&&Number.isFinite(e.collected_at_ms)}function Rc(e){return B_(e)}function Cc(e){return K_(e)}function Ac(e){return G_(e)}function B_(e){if(!Et(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function K_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function lo(e,t){if(!Et(e))return;let n=e[t];return uo(n)?n:void 0}function G_(e){if(!Et(e))return{};let t={};for(let[n,r]of Object.entries(e))uo(r)&&(t[n]=r);return t}function po(e,t=20){let n=[];for(let[r,o]of Object.entries(e))uo(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 J_=200,Ic=200,Y_=["allow","deny","ask"],X_=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,mo="<path>",Z_=new RegExp(`${mo}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function q_(e){let t=e.replace(X_,mo).replace(Z_,mo);return t.length>Ic?`${t.slice(0,Ic)}...`:t}function gn(e){let t=H(e,{}),n=[];for(let r of Y_)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:q_(o),mode:r});return{model:t.model??"",permissionKeys:n}}function Q_(e){let{serverManaged:t,fileBased:n}=Fn(process.platform,e),r=gn(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=gn(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function eh(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 th=10,nh="self-config-cache.json",Oc=2;function _n(){return A("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function rh(){return A("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function oh(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=et}var sh={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function ih(e,t=L){let n=sh[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
|
|
45
45
|
`)[0]??"").trim();return a||r(o+1)};return r(0)}function ah(e=kc()){return We(e,".ev-ai","agent-hook",nh)}function ch(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
|
|
46
46
|
`);return D(n)}function mn(e,t,n=!1){let r=ch(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 fo(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>We(e,a)),...n]){let a=W_(i);if(s.has(a))continue;s.add(a);let c=Gn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function uh(e){return z_(e)?$(V_(e,"utf8"),{}):{}}function lh(e,t){try{Q(e,`${JSON.stringify(t)}
|
|
47
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: self-config cache write failed open: ${r}`)}}function dh(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(fn(t))return lo(e[yt[t]],n)?.collected_at_ms}function ph(e,t,n){if(t==="user")return{components:Rc(e.user_spec_components),textHashes:Cc(e.user_spec_text_hashes)};if(!fn(t))return{components:void 0,textHashes:[]};let r=lo(e[yt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function fh(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}if(r){o.user_spec_layout_version=Oc,r.home&&(o.user_spec_collected_at_ms=r.home.collectedAtMs,r.home.included&&(o.user_spec=r.hash,o.user_spec_components=r.home.components),o.user_spec_text_hashes=r.home.textHashes);for(let s of r.project){if(!fn(s.scope))continue;let i=yt[s.scope],a=Ac(o[i]),c=a[s.scopeRef];a[s.scopeRef]={components:s.included?s.components:c?.components??{},text_hashes:s.textHashes,collected_at_ms:s.collectedAtMs},o[i]=po(a)}}return o}async function xc(e,t=process.cwd(),n=kc(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await ih(e),a="",c=[];if(o){let w=Q_(n),M=gn(We(n,".claude/settings.json")),C=gn(We(t,".claude/settings.local.json"));a=w.model||C.model||M.model,c=eh([...w.permissionKeys,...M.permissionKeys,...C.permissionKeys]).slice(0,J_)}let l={present:!1,size:0},u=w=>{let M=[],C=!1;for(let oe of w){let kt=Zo(We(n,oe));if(M=M.concat(kt.entries),C=C||kt.truncated,M.length>=_e){M=M.slice(0,_e),C=!0;break}}return{entries:M,truncated:C}},p=ah(n),m=uh(p),d=m[e]??{},_=(d.send_count??0)+1,S=_>0&&_%th===0,E=w=>S?void 0:d[w],y=u(Ce.skills),R=u(Ce.subagents),j=u(Ce.commands),T=u(Ce.rules),P={skills:mn(y.entries,E("skills"),y.truncated),subagents:mn(R.entries,E("subagents"),R.truncated),commands:mn(j.entries,E("commands"),j.truncated),rules:mn(T.entries,E("rules"),T.truncated)},F={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:P.skills,subagents:P.subagents,commands:P.commands,rules:P.rules,memory:fo(n,Ce.memory),settings:fo(n,Ce.settings,Qs(n)),mcp:fo(n,Ce.mcp)},local_settings:o?Gn(We(t,".claude/settings.local.json")):l},U=null,
|
|
48
|
-
${n}`}function Wc(e,t=[],n=process.execPath,r=import.meta.url,o=Gc){if(vt(n))return{command:n,args:[e,...t]};let s
|
|
49
|
-
`);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function Cn(e,t=fetch){let n=await e(),r=
|
|
50
|
-
`,u=A("EV_AI_HOOK_DEBUG");u==="full"?f(`DEBUG envelope=${JSON.stringify(c)}`):u==="1"&&f(`DEBUG summary=${jh(c,Buffer.byteLength(l,"utf8"))}`);let p=process.argv.includes(Rn),m=A("EV_AI_HOOK_SYNC")==="1";return Zt(n.runnerEvent,n.runnerPlatform)||p||m?Gh(e,l,o):(await zh(e,l,o),!1)}import{createReadStream as Vh}from"node:fs";import{stat as Wh}from"node:fs/promises";import{basename as Jh,resolve as Yh}from"node:path";import{createInterface as Xh}from"node:readline";var Zh=1024*1024;function qh(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Jh(t).endsWith(".jsonl")}async function Xc(e){if(!e||!qh(e))return null;try{let t=Yh(e),n=await Wh(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Zh),o=[],s=Xh({input:Vh(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 In(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function It(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function Eo(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function eu(e){let t=Date.now();await uS(e);let{gitRoot:n}=e.manifest;await kn(e,n);let r=Eo(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:rn(e.hookInput,e.manifest.manifest,r),envelopeFields:In(e),launchCwd:Kr(e.hookInput,r),home:Qc()}}function Zc(e){try{return V(Qh(e))}catch{return null}}function tu(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function qc(e,t){let n=e.replaceAll("\\","/");if(!tu(n))return null;let r=V(e),o=V(t),s=Zc(e)??r,i=Zc(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function eS(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=qc(e,t)??(tu(r)?null:r),i=qc(e,n);return{repositorySourcePath:s,userSourcePath:i}}function An(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=eS(e,t,n),c=i??a,l=c===null?null:o(c),u=l!==null&&c!==null?tS({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 tS(e){try{let t=e.inRepository?oS(e.platformAgentId,e.sourcePath):(0,O.installationRootExternalKey)(e.installationId,(0,O.userConfigRootFromPath)(e.sourcePath));return t?(0,O.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function yo(e,t,n){return Ye("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Je,e.manifest.collectorUrl,t.buildStartedAtMs,It(e,t.home))}function nS(e){return Bi(e.runnerEvent,e.runnerPlatform)?[]:ii(e.hookInput)}function rS(e,t){return yo(e,t,{})}var nu=new Set([...Object.values(Ne),".github"]);function oS(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=>nu.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function sS(e,t,n,r,o,s,i){if(e===null||t===null||!(i!==null||/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||/^MCP:.+__.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let c=s.find(_=>_.name.toLowerCase()===t.toLowerCase()),l=c?.sourcePath??(c?.source==="claude_json_user"?".claude.json":c?.source==="cursor_mcp_user"?".cursor/mcp.json":c?.source==="codex_toml_user"||c===void 0&&o==="codex"?".codex/config.toml":void 0);if((c?.scope==="user"||c?.source==="claude_json_user"||c?.source==="cursor_mcp_user"||c?.source==="codex_toml_user"||c===void 0&&o==="codex")&&l)try{let _=(0,O.userConfigRootFromPath)(l);return(0,O.buildComponentReference)({installationRootExternalKey:(0,O.installationRootExternalKey)(r,_),installableKind:O.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),d=m.replaceAll("\\","/").split("/").at(-1);if(!(d===void 0||!nu.has(d)))try{return(0,O.buildComponentReference)({installationRootExternalKey:n,installableKind:O.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function iS(...e){for(let t of e)if(t)return t;return null}function J(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return f(`WARN: ${n} failed open: ${r}`),t}function aS(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 cS(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Me=new Set,At=null;async function uS(e){if(_n())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Me.has(t))return;if(!Dr(n)){Me.add(t);return}let r=nt({sessionId:e.sessionId,hostname:rt()});if(Ta(r)){if(At){await At;return}At=(async()=>{if(Me.has(t)||!Dr(n)){Me.add(t);return}if(!_s(n)){Me.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,p,m]=await Promise.allSettled([ct(i),Wn(),br(r),Jn(),Ur({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),d=J(c,null,"gitSnapshot"),_=J(l,"","detectVirt"),S=J(u,null,"probeCloud"),E=J(p,{},"hostEnv"),y=J(m,{commit:()=>{}},"resolveOperatorForSend");await kn(e,i,d);let R={identity:{host:rt(),context:r,virt:_||null,cloud:S,git:d},host_env:E,env_vars:Tr(),self_config:cS(a,y.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await Ye("session_start",R,In(e),Je,e.manifest.collectorUrl,s,It(e)),o&&(y.commit(),Me.add(t))}finally{hs(n)}})().finally(()=>{At=null}),await At}}async function kn(e,t,n){try{let r=n===void 0?await ct(t):n;e.platformAgentId=await bi(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);f(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function lS(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=nt({sessionId:e.sessionId,hostname:rt()}),o=String(e.runnerPlatform),s=Eo(e),i=Kr(e.hookInput,s),a=ct(n),c=_n()?Promise.resolve({commit:()=>{}}):Ur({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[l,u,p,m,d,_,S]=await Promise.allSettled([a,Wn(),br(r),Jn(),Ir(e.manifest.manifest,n,o),a.catch(()=>null).then(C=>xc(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:C?.remote??null})),c]),E=J(l,null,"gitSnapshot"),y=J(u,"","detectVirt"),R=J(p,null,"probeCloud"),j=J(m,{},"hostEnv"),T=J(d,[],"mcpDeclared"),P=J(_,aS(o),"selfConfig"),F=J(S,{commit:()=>{}},"resolveOperatorForSend"),U=P.config;await kn(e,n,E);let K=h(e.hookInput,"model");K&&(U.model=K);let re={identity:{host:rt(),context:r,virt:y||null,cloud:R,git:E},host_env:j,env_vars:Tr(),mcp:{declared:T},self_config:U,run_meta:{trigger:e.hookSource||"startup"},hook_input:rn(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},w={};try{w=await Kc(Qc())}catch{w={}}await Ye("session_start",re,{...In(e),...w},Je,e.manifest.collectorUrl,t,It(e))&&(P.commit(),F.commit(),Me.add(e.manifest.installationId))}async function dS(e){let t=Date.now(),{gitRoot:n}=e.manifest;await kn(e,n);let r=e.runnerEvent.toLowerCase(),o=iS(h(e.hookInput,"status"),h(e.hookInput,"stop_reason"),h(e.hookInput,"reason"),dt(h(e.hookInput,"error")),r==="stop"?ae(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=e.runnerPlatform==="claude"?await Xc(h(e.hookInput,"transcript_path")):null,i=rn(e.hookInput,e.manifest.manifest,Eo(e));s&&(i.model=s),r!=="stopfailure"&&!La(e.manifest.manifest)&&i.last_assistant_message===void 0&&(i.last_assistant_message=""),await Ye("session_end",{status:o,...s?{model:s}:{},hook_input:i},In(e),Je,e.manifest.collectorUrl,t,It(e))}function ru(e,t,n,r){let o=r??si({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=An(o,t.gitRoot,t.home,O.ComponentKind.SKILL,O.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&lr(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??Mi({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=An(i,t.gitRoot,t.home,O.ComponentKind.COMMAND,O.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function pS(e,t,n){let r=Gt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=ru(e,t,o,r);return yo(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 fS(e,t,n){return Promise.all(n.map(r=>{let o=Ti({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=An(o,t.gitRoot,t.home,O.ComponentKind.RULE,O.nativeKeyForRulePath,e),i=s.nativeKey??vi(r);return yo(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var mS=[{kind:O.ComponentKind.SKILL,nativeKeyFn:O.nativeKeyForSkillPath},{kind:O.ComponentKind.RULE,nativeKeyFn:O.nativeKeyForRulePath},{kind:O.ComponentKind.COMMAND,nativeKeyFn:O.nativeKeyForCommandPath}];function gS(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=pr(e.hookInput);if(r===null)return n.skillName===null?{}:ru(e,t,n.skillName,null);for(let o of mS){let s=An(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===O.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===O.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var _S=/mcp/i;function hS(e,t,n,r){let o=_S.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?lc(t,n):pn(r.declaredConfig,n);return s===null?{}:Object.fromEntries(Object.entries(s).filter(i=>typeof i[1]=="string").map(([i,a])=>[`mcp_${i}`,a]))}async function SS(e){let t=await eu(e),n=Ji(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=dr(e.hookInput),i=cc(s,t.home),a=Xi(e.hookInput),c=Gi(e.runnerEvent),l=c===!1?Zi(e.hookInput,e.runnerEvent):null,u=await Ir(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=dt(h(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:d}=qi(r,u.map(F=>F.name),p??""),_=sS(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),u,p),S=_===void 0?gS(e,t,n):{},E=m===null?null:ji(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),y=hS(e,s,t.home,{hasMcpIdentity:!!m||!!d,declaredConfig:E}),R=_??S.componentReference,j=S.ruleName??n.ruleName,T=S.commandName??n.commandName,P=Yi(e.hookInput);await Ye("tool_invoked",{tool_name:r,skill_name:o,...j?{rule_name:j}:{},...T?{command_name:T}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...m?{mcp_server:m}:{},...d?{mcp_tool:d}:{},...y,...R?{component_reference:R}:{},...P?{subagent_type:P}:{},hook_input:t.hookInput},t.envelopeFields,Je,e.manifest.collectorUrl,t.buildStartedAtMs,It(e,t.home))}async function ou(e){switch(e.internalEvent){case"session_start":await lS(e);return;case"session_end":await dS(e);return;case"skill_invoked":{let t=nS(e),n=wi(e.hookInput),r=Ki(e.runnerEvent);if(t.length===0&&n.length===0&&!r)return;let o=await eu(e);await Promise.all([r&&t.length===0&&n.length===0?rS(e,o):void 0,t.length===0?void 0:pS(e,o,t),n.length===0?void 0:fS(e,o,n)]);return}case"tool_invoked":await SS(e);return;default:return}}function su(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{createHash as ES}from"node:crypto";import{mkdirSync as yS,readdirSync as RS,readFileSync as CS,statSync as iu,unlinkSync as AS,writeFileSync as IS}from"node:fs";import{homedir as On}from"node:os";import{join as Ro}from"node:path";var kS="turns",au=1440*60*1e3,OS=100,xS=new Set(["stop","stopfailure","sessionend"]);function Co(e=On()){return Ro(ce(e),kS)}function PS(e){return ES("sha256").update(e).digest("hex").slice(0,32)}function cu(e,t){return Ro(e,PS(t))}function bS(e,t=Date.now()){let n;try{n=RS(e)}catch{return}let r=0;for(let o of n){if(r>=OS)return;r+=1;try{let s=Ro(e,o);t-iu(s).mtimeMs>au&&AS(s)}catch{}}}function TS(e,t,n=On()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=Co(n);yS(s,{recursive:!0}),IS(cu(s,r),o,"utf8")}catch{}}function NS(e,t=On()){let n=e.trim();if(!n)return"";try{let r=cu(Co(t),n);return Date.now()-iu(r).mtimeMs>au?"":CS(r,"utf8").trim()}catch{return""}}function uu(e,t,n,r=On()){let o=t.trim(),s=xS.has(n.trim().toLowerCase());return s&&bS(Co(r)),o?(TS(e,o,r),o):s?NS(e,r):""}async function lu(e,t,n,r){let o=t??await Kn(Un),s=$(o,{}),i=h(s,"session_id")||h(s,"conversation_id"),a=await Cs(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=zi(s,a.manifest.platform,n),l=Vi(e,c.runnerEvent);if(!l){f(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:uu(c.sessionId,c.turnId,c.runnerEvent),runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:a,platformAgentId:a.platformAgentId};if(su(l)){f(`WARN: unsupported internal event '${l}'`);return}await ou(u)}function vS(e,t){if(A("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ze(e),r=$(t,{}),o=n.event??(h(r,"hook_event_name")||h(r,"event")),s=lt(r,o,void 0,n.runner);return Zt(o,s)}async function du(e=process.argv.slice(2)){if(aa(),e[0]===Ct){try{await Cn(tt)}catch{}return 0}if(e[0]===Rn){try{let t=Ze(e.slice(1)),n=await tt(),r=$(n,{}),o=t.event??(h(r,"hook_event_name")||h(r,"event"));if(zn()||Or(t.runner,r,o))return 0;await lu(t.event,n,t.runner,kr(t))}catch(t){let n=t instanceof Error?t.message:String(t);f(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Kn(Un),n=Ze(e),r=kr(n),o=$(t,{}),s=n.event??(h(o,"hook_event_name")||h(o,"event"));if(zn()||Or(n.runner,o,s)||!sa(o,s,n.runner))return 0;vS(e,t)?await lu(n.event,t,n.runner,r):await Yc(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);f(`WARN: hook failed open: ${n}`)}finally{Xo()}return 0}function xn(){f("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),f(" configure [--url <\u2026/{orgToken}/hook>]"),f(" (manifest only \u2014 pair with marketplace plugins)"),f(" install --url <\u2026/{orgToken}/hook>"),f(" [--delivery npx|binary|local] [--force]"),f(" [--no-claude] [--no-cursor] [--no-codex]"),f(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),f(" (writes collector_url to shared manifest; hook commands use --runner only)"),f(" migrate-to-plugin"),f(" (strip ev-ai file hooks; keep collector manifest)"),f(" update (refresh binary pins from a local build; leaves hook configs alone)"),f(" uninstall"),f("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),f(" (--url/--token optional overrides; else collector_url from manifest)")}function pu(e){return e.includes("--help")||e.includes("-h")}async function DS(e=process.argv.slice(2)){let[t,...n]=e;if(t===Ct){try{await Cn(tt)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${se}
|
|
51
|
-
`),0):t==="configure"?pu(n)?(xn(),0):(await Gs(Ts(n)),0):t==="install"?pu(n)?(xn(),0):(await
|
|
47
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);f(`WARN: self-config cache write failed open: ${r}`)}}function dh(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(fn(t))return lo(e[yt[t]],n)?.collected_at_ms}function ph(e,t,n){if(t==="user")return{components:Rc(e.user_spec_components),textHashes:Cc(e.user_spec_text_hashes)};if(!fn(t))return{components:void 0,textHashes:[]};let r=lo(e[yt[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function fh(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}if(r){o.user_spec_layout_version=Oc,r.home&&(o.user_spec_collected_at_ms=r.home.collectedAtMs,r.home.included&&(o.user_spec=r.hash,o.user_spec_components=r.home.components),o.user_spec_text_hashes=r.home.textHashes);for(let s of r.project){if(!fn(s.scope))continue;let i=yt[s.scope],a=Ac(o[i]),c=a[s.scopeRef];a[s.scopeRef]={components:s.included?s.components:c?.components??{},text_hashes:s.textHashes,collected_at_ms:s.collectedAtMs},o[i]=po(a)}}return o}async function xc(e,t=process.cwd(),n=kc(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await ih(e),a="",c=[];if(o){let w=Q_(n),M=gn(We(n,".claude/settings.json")),C=gn(We(t,".claude/settings.local.json"));a=w.model||C.model||M.model,c=eh([...w.permissionKeys,...M.permissionKeys,...C.permissionKeys]).slice(0,J_)}let l={present:!1,size:0},u=w=>{let M=[],C=!1;for(let oe of w){let kt=Zo(We(n,oe));if(M=M.concat(kt.entries),C=C||kt.truncated,M.length>=_e){M=M.slice(0,_e),C=!0;break}}return{entries:M,truncated:C}},p=ah(n),m=uh(p),d=m[e]??{},_=(d.send_count??0)+1,S=_>0&&_%th===0,E=w=>S?void 0:d[w],y=u(Ce.skills),R=u(Ce.subagents),j=u(Ce.commands),T=u(Ce.rules),P={skills:mn(y.entries,E("skills"),y.truncated),subagents:mn(R.entries,E("subagents"),R.truncated),commands:mn(j.entries,E("commands"),j.truncated),rules:mn(T.entries,E("rules"),T.truncated)},F={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:P.skills,subagents:P.subagents,commands:P.commands,rules:P.rules,memory:fo(n,Ce.memory),settings:fo(n,Ce.settings,Qs(n)),mcp:fo(n,Ce.mcp)},local_settings:o?Gn(We(t,".claude/settings.local.json")):l},U=null,B=r.nowMs??Date.now();if(!_n()){let w=d.user_spec_layout_version!==Oc,M=no(e,n,{launchCwd:rh()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(C,oe)=>w||oh(dh(d,C,oe),B)});if(Object.keys(M.scopes).length>0){let C=co({collected:M,cacheFor:(oe,kt)=>w?{components:void 0,textHashes:[]}:ph(d,oe,kt),nowMs:B});Object.assign(F,C.fields),U={hash:C.fields.user_spec_hash,home:C.scopes.find(oe=>oe.scope==="user")??null,project:C.scopes.filter(oe=>oe.scope!=="user")}}}let re=fh(d,P,_,U);return{config:F,commit:()=>{m[e]=re,lh(p,m)}}}import{homedir as Fh}from"node:os";import{join as Mc}from"node:path";var kA=Buffer.from([1]);var OA=1024*1024,xA=4*1024*1024,PA=64*1024,bA=64*1024,TA=64*1024;var go=4096,NA=4*1024*1024;import{open as Pc,mkdir as mh,readFile as gh,readdir as _h,rename as hh,stat as Sh,rmdir as Eh,unlink as yh,utimes as Rh}from"node:fs/promises";var hn=new WeakMap;function Ch(e){if(e&&typeof e=="object"&&"code"in e)return e}function _o(e){return Ch(e)?.code==="ENOENT"}async function Tc(e,t){try{return await e.readdir(t)}catch(n){if(_o(n))return[];throw n}}function Nc(){return{async open(e,t){let n=await Pc(e,t),r={path:e};return hn.set(r,n),r},async write(e,t){let n=bc(e),r=typeof t=="string"?Buffer.from(t,"utf8"):t;await n.write(r)},async fsync(e){await bc(e).sync()},async close(e){let t=hn.get(e);hn.delete(e),t&&await t.close()},rename:hh,async readdir(e){return _h(e)},readFile:gh,async stat(e){let t=await Sh(e);return{mtimeMs:t.mtimeMs,size:t.size,isDirectory:()=>t.isDirectory()}},async mkdir(e,t){await mh(e,t)},unlink:yh,rmdir:Eh,utimes:Rh,async fsyncDir(e){if(process.platform==="win32")return;let t=await Pc(e,"r");try{await t.sync()}finally{await t.close()}}}}function bc(e){let t=hn.get(e);if(!t)throw new Error("closed");return t}function Sn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{join as En}from"node:path";function Ah(e){return En(e,".ev-ai","agent-hook","js","signed-v1")}function Ih(e){return En(Ah(e),"scopes")}function vc(e,t){return En(Ih(e),t)}function wc(e){return En(e,"attempts")}function ho(e){return String(e).padStart(10,"0")}var kh=/^(\d{10})$/,Oh=/^(\d{10})\.done$/,xh=/^[0-9a-f]{128}$/,Ph=64;async function Hc(e,t,n=!1){let r=wc(t),o=await Tc(e,r),s=new Map,i=new Map,a=Lc(o,kh),c=Lc(o,Oh),l=async m=>{let d=await Dc(e,Mc(r,bh(m)));return d&&s.set(m,{record:Nh(d.value),mtimeMs:d.mtimeMs}),d!==void 0},u=async m=>{let d=vh((await Dc(e,Mc(r,Th(m))))?.value);return d&&i.set(m,d),d!==void 0};if(!n)return await Promise.all([...a.map(l),...c.map(u)]),{claims:s,dones:i};await Promise.all([Uc(a,l),Uc(c,u)]);let p=Rt(s);return p<Rt(i)&&c.includes(p)&&await u(p),{claims:s,dones:i}}function Lc(e,t){return e.flatMap(n=>{let r=t.exec(n);return r?[Number(r[1])]:[]})}async function Uc(e,t){for(let n of[...e].sort((r,o)=>o-r))if(await t(n))return}function Rt(e){let t=0;for(let n of e.keys())n>t&&(t=n);return t}function Fc(e){if(e.record!=="empty"&&e.record.started_at){let t=Date.parse(e.record.started_at);if(Number.isFinite(t))return t}return e.mtimeMs}function bh(e){return ho(e)}function Th(e){return`${ho(e)}.done`}async function Dc(e,t){let n;try{n=await e.stat(t)}catch(o){if(_o(o))return;throw o}let r=n.mtimeMs;if(n.size===0||n.size>go)return{mtimeMs:r};try{let o=await e.readFile(t);return o.byteLength===0||o.byteLength>go?{mtimeMs:r}:{mtimeMs:r,value:JSON.parse(o.toString("utf8"))}}catch{return{mtimeMs:r}}}function Nh(e){if(!Sn(e))return"empty";let t={};return typeof e.started_at=="string"&&(t.started_at=e.started_at),(e.owner==="bootstrap"||e.owner==="refresh")&&(t.owner=e.owner),e.resync===!0&&(t.resync=!0),t}function vh(e){if(!Sn(e))return;let t=e;if(typeof t.finished_at!="string"||typeof t.outcome!="string"||typeof t.interval_s!="number"||!Number.isFinite(t.interval_s))return;let n=wh(t.selection);if(n)return{finished_at:t.finished_at,interval_s:t.interval_s,outcome:t.outcome,selection:n}}function wh(e){if(!Sn(e))return;let t=e;if(t.kind==="bundled")return t.why==="server"||t.why==="bootstrap_failed"?{kind:"bundled",why:t.why}:void 0;if(t.kind==="cached"&&typeof t.digest=="string"&&xh.test(t.digest)&&typeof t.version=="string"&&t.version.length>0&&typeof t.sha512=="string"&&Mh(t.sha512)===t.digest)return{kind:"cached",digest:t.digest,version:t.version,sha512:t.sha512}}function Mh(e){if(e.length===0||!/^[A-Za-z0-9+/]+=*$/.test(e))return;let t=Buffer.from(e,"base64");if(!(t.byteLength!==Ph||t.toString("base64")!==e))return t.toString("hex")}function Hh(e){return e==="bootstrap"?3e3:6e4}function $c(e,t){let n=Rt(e.claims);if(n===0)return;let r=Rt(e.dones),o=e.claims.get(n),s=e.dones.get(n);if(o&&!s){let a=Fc(o),c=o.record==="empty"?void 0:o.record.owner,l=Hh(c)+3e4;if(t-a>l)return{n,latest_claim:n,outcome:"incomplete",finished_at:null,selection_version:jc(e.dones.get(r)?.selection)}}if(r===0)return;let i=e.dones.get(r);if(i)return{n:r,latest_claim:n,outcome:i.outcome,finished_at:i.finished_at,selection_version:jc(i.selection)}}function jc(e){return e?.kind==="cached"&&typeof e.version=="string"?e.version:null}async function Bc(e=Fh(),t=process.env){let n=Pr(t),r=n?.launcherScope;if(!n||!r)return{};try{let o=await Hc(Nc(),vc(e,r)),s=$c(o,Date.now());return s?{launcher_scope:r,launcher_attempt:s}:{launcher_scope:r}}catch{return{launcher_scope:r}}}function Je(e,t,n){let r={installation_id:n.installationId};n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId);let o={schema_version:ge,event:e,timestamp:Ut(),session_id:n.sessionId||null,turn_id:n.turnId||null,installation_id:n.installationId,platform:n.runnerPlatform,platform_agent_id:n.platformAgentId||null,runner_event:n.runnerEvent||null,agent_hook_version:se,host_arch:process.arch,node_version:process.version,correlation:r,payload:t},s=Pr();return s&&(o.launcher_version=s.launcherVersion,o.hook_source=s.hookSource,o.hook_fallback_reason=s.fallbackReason??null,o.launcher_scope_match=ca(n.collectorUrl,s.launcherScope)),e==="session_start"&&(n.launcher_scope&&(o.launcher_scope=n.launcher_scope),n.launcher_attempt&&(o.launcher_attempt=n.launcher_attempt)),o}import{existsSync as Gc}from"node:fs";import{spawn as zc}from"node:child_process";import{fileURLToPath as $h}from"node:url";import{gzipSync as jh}from"node:zlib";function So(e){return A("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<$o?{body:e}:{body:jh(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function yn(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function Kc(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var Ct="__post",Rn="__work";async function Bh(e,t,n={}){if(A("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off")return e;let r=await Lr(n.gitRoot??process.cwd(),L,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 Kh(e,t){let n=e.payload,r=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],o=e.correlation&&typeof e.correlation=="object"?Object.keys(e.correlation):[];return JSON.stringify({event:e.event,schema_version:e.schema_version,agent_hook_version:e.agent_hook_version,host_arch:e.host_arch,node_version:e.node_version,build_ms:e.build_ms,body_bytes:t,correlation_keys:o,payload_keys:r})}function Vc(e){switch(e){case"session_start":return Do;case"session_end":return Ho;case"tool_invoked":case"skill_invoked":return Ln;default:return Ln}}function Gh(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
|
|
48
|
+
${n}`}function Wc(e,t=[],n=process.execPath,r=import.meta.url,o=Gc){if(vt(n))return{command:n,args:[e,...t]};let s=$h(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function zh(e=process.execPath,t=import.meta.url,n=Gc){return Wc(Ct,[],e,t,n)}function Vh(e){let t=e.indexOf(`
|
|
49
|
+
`);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function Cn(e,t=fetch){let n=await e(),r=Vh(n);if(!r)return;let{meta:o,body:s}=r,i=So(s),a=yn(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function Wh(e,t,n,r=fetch){let o=Vc(e),s=So(t),i=yn(s.contentEncoding),a=Kc(s.body);f(`POST event=${e} url=${Nt(n)} size=${a} encoding=${s.contentEncoding??"identity"} platform=${process.platform}`);let c=Date.now();try{let l=await r(n,{method:"POST",headers:i,body:s.body,signal:AbortSignal.timeout(o)});if(!l.ok&&s.contentEncoding==="gzip"&&(l.status===400||l.status===415)){try{await l.text()}catch{}f(`POST gzip rejected http=${l.status} \u2014 retrying uncompressed`),l=await r(n,{method:"POST",headers:yn(),body:t,signal:AbortSignal.timeout(o)})}let u=Date.now()-c;if(l.ok)return f(`POST outcome=ok elapsed_ms=${u} http=${l.status}`),!0;let p=(await l.text()).slice(0,200).replace(/[\n\r]/g,"");return f(`POST outcome=fail elapsed_ms=${u} http=${l.status} body=${p}`),!1}catch(l){let u=Date.now()-c,p=l instanceof Error?l.message:String(l);return f(`POST outcome=fail elapsed_ms=${u} http=000 body=${p}`),!1}}async function Jc(e,t,n,r,o){try{let s=r(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let i=!1;return await new Promise(a=>{let c=setTimeout(()=>{if(!i){f(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}a()},Fo),l=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return f(`WARN: ${o} spawn failed open: ${i}`),null}}async function Jh(e,t,n,r=zc,o=zh){let s=Vc(e),i=Gh(n,s,t),{command:a,args:c}=o();return Jc(a,c,i,r,"detached post")}async function Yc(e,t,n=zc,r=Wc){let{command:o,args:s}=r(Rn,t);return Jc(o,s,e,n,"detached work")}async function Ye(e,t,n,r,o,s,i){if(!o)return f("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!qe(o))return f(`WARN: collector URL blocked (https required): ${Nt(o)}`),!1;let a=await Bh(t,n.runnerPlatform,i),c=r(e,a,{...n,collectorUrl:o});s!==void 0&&(c.build_ms=Math.max(0,Date.now()-s));let l=`${JSON.stringify(c)}
|
|
50
|
+
`,u=A("EV_AI_HOOK_DEBUG");u==="full"?f(`DEBUG envelope=${JSON.stringify(c)}`):u==="1"&&f(`DEBUG summary=${Kh(c,Buffer.byteLength(l,"utf8"))}`);let p=process.argv.includes(Rn),m=A("EV_AI_HOOK_SYNC")==="1";return Zt(n.runnerEvent,n.runnerPlatform)||p||m?Wh(e,l,o):(await Jh(e,l,o),!1)}import{createReadStream as Yh}from"node:fs";import{stat as Xh}from"node:fs/promises";import{basename as Zh,resolve as qh}from"node:path";import{createInterface as Qh}from"node:readline";var eS=1024*1024;function tS(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&Zh(t).endsWith(".jsonl")}async function Xc(e){if(!e||!tS(e))return null;try{let t=qh(e),n=await Xh(t);if(!n.isFile())return null;let r=Math.max(0,n.size-eS),o=[],s=Qh({input:Yh(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 In(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function It(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function Eo(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function eu(e){let t=Date.now();await pS(e);let{gitRoot:n}=e.manifest;await kn(e,n);let r=Eo(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:rn(e.hookInput,e.manifest.manifest,r),envelopeFields:In(e),launchCwd:Br(e.hookInput,r),home:Qc()}}function Zc(e){try{return V(nS(e))}catch{return null}}function tu(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function qc(e,t){let n=e.replaceAll("\\","/");if(!tu(n))return null;let r=V(e),o=V(t),s=Zc(e)??r,i=Zc(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function rS(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=qc(e,t)??(tu(r)?null:r),i=qc(e,n);return{repositorySourcePath:s,userSourcePath:i}}function An(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=rS(e,t,n),c=i??a,l=c===null?null:o(c),u=l!==null&&c!==null?oS({installableKind:r,sourcePath:c,nativeKey:l,inRepository:i!==null,platformAgentId:s.platformAgentId,installationId:s.manifest.installationId}):void 0;return{sourcePath:c,nativeKey:l,componentReference:u}}function oS(e){try{let t=e.inRepository?aS(e.platformAgentId,e.sourcePath):(0,O.installationRootExternalKey)(e.installationId,(0,O.userConfigRootFromPath)(e.sourcePath));return t?(0,O.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function yo(e,t,n){return Ye("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Je,e.manifest.collectorUrl,t.buildStartedAtMs,It(e,t.home))}function sS(e){return Ki(e.runnerEvent,e.runnerPlatform)?[]:ii(e.hookInput)}function iS(e,t){return yo(e,t,{})}var nu=new Set([...Object.values(Ne),".github"]);function aS(e,t){let n=e.indexOf(":");if(n<=0)return null;let r=e.slice(0,n),o=t.replaceAll("\\","/").split("/").filter(Boolean),s=o.findIndex(i=>nu.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function cS(e,t,n,r,o,s,i){if(e===null||t===null||!(i!==null||/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||/^MCP:.+__.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let c=s.find(_=>_.name.toLowerCase()===t.toLowerCase()),l=c?.sourcePath??(c?.source==="claude_json_user"?".claude.json":c?.source==="cursor_mcp_user"?".cursor/mcp.json":c?.source==="codex_toml_user"||c===void 0&&o==="codex"?".codex/config.toml":void 0);if((c?.scope==="user"||c?.source==="claude_json_user"||c?.source==="cursor_mcp_user"||c?.source==="codex_toml_user"||c===void 0&&o==="codex")&&l)try{let _=(0,O.userConfigRootFromPath)(l);return(0,O.buildComponentReference)({installationRootExternalKey:(0,O.installationRootExternalKey)(r,_),installableKind:O.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),d=m.replaceAll("\\","/").split("/").at(-1);if(!(d===void 0||!nu.has(d)))try{return(0,O.buildComponentReference)({installationRootExternalKey:n,installableKind:O.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function uS(...e){for(let t of e)if(t)return t;return null}function J(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return f(`WARN: ${n} failed open: ${r}`),t}function lS(e){let t={present:!1,size:0},n={hash:"",count:0};return{config:{runner_platform:e,config_scope:"user",cli_version:null,claude_version:null,model:null,permission_keys:[],user_scope:{skills:n,subagents:n,commands:n,rules:n,memory:t,settings:t,mcp:t},local_settings:t},commit:()=>{}}}function dS(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Me=new Set,At=null;async function pS(e){if(_n())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Me.has(t))return;if(!Dr(n)){Me.add(t);return}let r=nt({sessionId:e.sessionId,hostname:rt()});if(Ta(r)){if(At){await At;return}At=(async()=>{if(Me.has(t)||!Dr(n)){Me.add(t);return}if(!_s(n)){Me.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,p,m]=await Promise.allSettled([ct(i),Wn(),br(r),Jn(),Ur({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),d=J(c,null,"gitSnapshot"),_=J(l,"","detectVirt"),S=J(u,null,"probeCloud"),E=J(p,{},"hostEnv"),y=J(m,{commit:()=>{}},"resolveOperatorForSend");await kn(e,i,d);let R={identity:{host:rt(),context:r,virt:_||null,cloud:S,git:d},host_env:E,env_vars:Tr(),self_config:dS(a,y.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await Ye("session_start",R,In(e),Je,e.manifest.collectorUrl,s,It(e)),o&&(y.commit(),Me.add(t))}finally{hs(n)}})().finally(()=>{At=null}),await At}}async function kn(e,t,n){try{let r=n===void 0?await ct(t):n;e.platformAgentId=await bi(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);f(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function fS(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=nt({sessionId:e.sessionId,hostname:rt()}),o=String(e.runnerPlatform),s=Eo(e),i=Br(e.hookInput,s),a=ct(n),c=_n()?Promise.resolve({commit:()=>{}}):Ur({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[l,u,p,m,d,_,S]=await Promise.allSettled([a,Wn(),br(r),Jn(),Ir(e.manifest.manifest,n,o),a.catch(()=>null).then(C=>xc(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:C?.remote??null})),c]),E=J(l,null,"gitSnapshot"),y=J(u,"","detectVirt"),R=J(p,null,"probeCloud"),j=J(m,{},"hostEnv"),T=J(d,[],"mcpDeclared"),P=J(_,lS(o),"selfConfig"),F=J(S,{commit:()=>{}},"resolveOperatorForSend"),U=P.config;await kn(e,n,E);let B=h(e.hookInput,"model");B&&(U.model=B);let re={identity:{host:rt(),context:r,virt:y||null,cloud:R,git:E},host_env:j,env_vars:Tr(),mcp:{declared:T},self_config:U,run_meta:{trigger:e.hookSource||"startup"},hook_input:rn(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},w={};try{w=await Bc(Qc())}catch{w={}}await Ye("session_start",re,{...In(e),...w},Je,e.manifest.collectorUrl,t,It(e))&&(P.commit(),F.commit(),Me.add(e.manifest.installationId))}async function mS(e){let t=Date.now(),{gitRoot:n}=e.manifest;await kn(e,n);let r=e.runnerEvent.toLowerCase(),o=uS(h(e.hookInput,"status"),h(e.hookInput,"stop_reason"),h(e.hookInput,"reason"),dt(h(e.hookInput,"error")),r==="stop"?ae(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=e.runnerPlatform==="claude"?await Xc(h(e.hookInput,"transcript_path")):null,i=rn(e.hookInput,e.manifest.manifest,Eo(e));s&&(i.model=s),r!=="stopfailure"&&!La(e.manifest.manifest)&&i.last_assistant_message===void 0&&(i.last_assistant_message=""),await Ye("session_end",{status:o,...s?{model:s}:{},hook_input:i},In(e),Je,e.manifest.collectorUrl,t,It(e))}function ru(e,t,n,r){let o=r??si({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=An(o,t.gitRoot,t.home,O.ComponentKind.SKILL,O.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&lr(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??Mi({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=An(i,t.gitRoot,t.home,O.ComponentKind.COMMAND,O.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function gS(e,t,n){let r=Gt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=ru(e,t,o,r);return yo(e,t,{tool_name:"Skill",skill_name:o,...s.commandName===void 0?{}:{command_name:s.commandName},...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}function _S(e,t,n){return Promise.all(n.map(r=>{let o=Ti({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=An(o,t.gitRoot,t.home,O.ComponentKind.RULE,O.nativeKeyForRulePath,e),i=s.nativeKey??vi(r);return yo(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var hS=[{kind:O.ComponentKind.SKILL,nativeKeyFn:O.nativeKeyForSkillPath},{kind:O.ComponentKind.RULE,nativeKeyFn:O.nativeKeyForRulePath},{kind:O.ComponentKind.COMMAND,nativeKeyFn:O.nativeKeyForCommandPath}];function SS(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=pr(e.hookInput);if(r===null)return n.skillName===null?{}:ru(e,t,n.skillName,null);for(let o of hS){let s=An(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===O.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===O.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var ES=/mcp/i;function yS(e,t,n,r){let o=ES.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?lc(t,n):pn(r.declaredConfig,n);return s===null?{}:Object.fromEntries(Object.entries(s).filter(i=>typeof i[1]=="string").map(([i,a])=>[`mcp_${i}`,a]))}async function RS(e){let t=await eu(e),n=Ji(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=dr(e.hookInput),i=cc(s,t.home),a=Xi(e.hookInput),c=Gi(e.runnerEvent),l=c===!1?Zi(e.hookInput,e.runnerEvent):null,u=await Ir(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=dt(h(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:d}=qi(r,u.map(F=>F.name),p??""),_=cS(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),u,p),S=_===void 0?SS(e,t,n):{},E=m===null?null:ji(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),y=yS(e,s,t.home,{hasMcpIdentity:!!m||!!d,declaredConfig:E}),R=_??S.componentReference,j=S.ruleName??n.ruleName,T=S.commandName??n.commandName,P=Yi(e.hookInput);await Ye("tool_invoked",{tool_name:r,skill_name:o,...j?{rule_name:j}:{},...T?{command_name:T}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...m?{mcp_server:m}:{},...d?{mcp_tool:d}:{},...y,...R?{component_reference:R}:{},...P?{subagent_type:P}:{},hook_input:t.hookInput},t.envelopeFields,Je,e.manifest.collectorUrl,t.buildStartedAtMs,It(e,t.home))}async function ou(e){switch(e.internalEvent){case"session_start":await fS(e);return;case"session_end":await mS(e);return;case"skill_invoked":{let t=sS(e),n=wi(e.hookInput),r=Bi(e.runnerEvent);if(t.length===0&&n.length===0&&!r)return;let o=await eu(e);await Promise.all([r&&t.length===0&&n.length===0?iS(e,o):void 0,t.length===0?void 0:gS(e,o,t),n.length===0?void 0:_S(e,o,n)]);return}case"tool_invoked":await RS(e);return;default:return}}function su(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{createHash as CS}from"node:crypto";import{mkdirSync as AS,readdirSync as IS,readFileSync as kS,statSync as iu,unlinkSync as OS,writeFileSync as xS}from"node:fs";import{homedir as On}from"node:os";import{join as Ro}from"node:path";var PS="turns",au=1440*60*1e3,bS=100,TS=new Set(["stop","stopfailure","sessionend"]);function Co(e=On()){return Ro(ce(e),PS)}function NS(e){return CS("sha256").update(e).digest("hex").slice(0,32)}function cu(e,t){return Ro(e,NS(t))}function vS(e,t=Date.now()){let n;try{n=IS(e)}catch{return}let r=0;for(let o of n){if(r>=bS)return;r+=1;try{let s=Ro(e,o);t-iu(s).mtimeMs>au&&OS(s)}catch{}}}function wS(e,t,n=On()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=Co(n);AS(s,{recursive:!0}),xS(cu(s,r),o,"utf8")}catch{}}function MS(e,t=On()){let n=e.trim();if(!n)return"";try{let r=cu(Co(t),n);return Date.now()-iu(r).mtimeMs>au?"":kS(r,"utf8").trim()}catch{return""}}function uu(e,t,n,r=On()){let o=t.trim(),s=TS.has(n.trim().toLowerCase());return s&&vS(Co(r)),o?(wS(e,o,r),o):s?MS(e,r):""}async function lu(e,t,n,r){let o=t??await Bn(Un),s=$(o,{}),i=h(s,"session_id")||h(s,"conversation_id"),a=await Cs(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=zi(s,a.manifest.platform,n),l=Vi(e,c.runnerEvent);if(!l){f(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:uu(c.sessionId,c.turnId,c.runnerEvent),runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:a,platformAgentId:a.platformAgentId};if(su(l)){f(`WARN: unsupported internal event '${l}'`);return}await ou(u)}function LS(e,t){if(A("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ze(e),r=$(t,{}),o=n.event??(h(r,"hook_event_name")||h(r,"event")),s=lt(r,o,void 0,n.runner);return Zt(o,s)}async function du(e=process.argv.slice(2)){if(aa(),e[0]===Ct){try{await Cn(tt)}catch{}return 0}if(e[0]===Rn){try{let t=Ze(e.slice(1)),n=await tt(),r=$(n,{}),o=t.event??(h(r,"hook_event_name")||h(r,"event"));if(zn()||Or(t.runner,r,o))return 0;await lu(t.event,n,t.runner,kr(t))}catch(t){let n=t instanceof Error?t.message:String(t);f(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Bn(Un),n=Ze(e),r=kr(n),o=$(t,{}),s=n.event??(h(o,"hook_event_name")||h(o,"event"));if(zn()||Or(n.runner,o,s)||!sa(o,s,n.runner))return 0;LS(e,t)?await lu(n.event,t,n.runner,r):await Yc(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);f(`WARN: hook failed open: ${n}`)}finally{Xo()}return 0}function xn(){f("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),f(" configure [--url <\u2026/{orgToken}/hook>]"),f(" (manifest only \u2014 pair with marketplace plugins)"),f(" install --url <\u2026/{orgToken}/hook>"),f(" [--delivery npx|binary|local] [--force]"),f(" [--no-claude] [--no-cursor] [--no-codex]"),f(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),f(" (writes collector_url to shared manifest; hook commands use --runner only)"),f(" migrate-to-plugin"),f(" (strip ev-ai file hooks; keep collector manifest)"),f(" update (refresh binary pins from a local build; leaves hook configs alone)"),f(" uninstall"),f("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),f(" (--url/--token optional overrides; else collector_url from manifest)")}function pu(e){return e.includes("--help")||e.includes("-h")}async function jS(e=process.argv.slice(2)){let[t,...n]=e;if(t===Ct){try{await Cn(tt)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${se}
|
|
51
|
+
`),0):t==="configure"?pu(n)?(xn(),0):(await Gs(Ts(n)),0):t==="install"?pu(n)?(xn(),0):(await Bs(Ns(n)),0):t==="migrate-to-plugin"?(await Vs(),0):t==="update"?(await Ks(),0):t==="uninstall"?(await Ws(),0):t==="help"||t==="--help"||t==="-h"?(xn(),0):t===void 0?(xn(),1):du(e)}function $S(e,t,n=US){if(!t)return!1;try{return e===FS(DS(t)).href?!0:n(HS(e))===n(t)}catch{return!1}}$S(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&jS().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);f(t),process.exit(1)});export{$S as isCliEntrypoint,jS as main};
|