@ev-ai/agent-hook 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,19 +1,28 @@
1
1
  #!/usr/bin/env node
2
+ import { createRequire as __createRequire } from 'node:module';
3
+ const require = __createRequire(import.meta.url);
2
4
 
3
- import{realpathSync as $s}from"node:fs";import{resolve as Bs}from"node:path";import{fileURLToPath as Ks,pathToFileURL as Gs}from"node:url";var Ln="https://hooks.evalon.ai";function Z(e,t=Ln){let n=t.replace(/\/+$/,""),o=e.trim();return`${n}/${o}/hook`}var D=".claude/evalon-runtime-report.json",Ye="node_modules/@evalon/agent-hook/dist/hook.mjs",P="evalon-agent-hook",Xe="https://cdn.evalon.ai/agent-hook",ye=`current/${P}`,Se=`.evalon/agent-hook/${P}`,qe=5e3,Ze=5e3,Ee=3e3;var ve=3e3,Qe=1500,et=4*1024,tt=32*1024,Un=4*1024,b="1.0.6",Q=`@evalon-ai/agent-hook@${b}`,nt="Evalon runtime report",ot=["claude","cursor","codex"];import{chmodSync as xt,cpSync as bt,existsSync as C,mkdirSync as Pe,readdirSync as go,readFileSync as ho,rmSync as ae,symlinkSync as _o,writeFileSync as ko}from"node:fs";import{homedir as A}from"node:os";import{basename as yo,dirname as Te,isAbsolute as So,join as f,relative as Rt,resolve as It,sep as Eo}from"node:path";import{fileURLToPath as vo}from"node:url";var jn=new Set(["localhost","127.0.0.1","[::1]","::1"]),rt=/^[A-Za-z0-9._~-]+$/;function st(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 ee(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?jn.has(t.hostname):!1}catch{return!1}}function $(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!ee(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Fn(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!rt.test(n))return`org token must match ${rt.source} (got: ${n})`;if(st(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(st(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function B(e){return new URL(e).toString()}function Fn(e){try{let n=new URL(e).pathname.split("/").filter(o=>o.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let o=n[n.length-2];return o.length>0?o:void 0}return}catch{return}}function we(e){try{let t=new URL(e),n=t.pathname.split("/").filter(o=>o.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 it(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?Z(t):""}import{createHash as Wn,randomBytes as Vn}from"node:crypto";import{existsSync as zn,mkdirSync as Yn,readFileSync as Xn,writeFileSync as qn}from"node:fs";import{homedir as oe}from"node:os";import{dirname as Zn,join as xe,resolve as Qn}from"node:path";import{randomBytes as Dn}from"node:crypto";import{existsSync as ut,mkdirSync as $n,readdirSync as Bn,renameSync as at,statSync as dt,unlinkSync as ct,writeFileSync as Kn}from"node:fs";import{basename as Gn,dirname as lt,join as ft,relative as Jn}from"node:path";function l(e){process.stderr.write(`[evalon-agent-hook] ${e}
4
- `)}function L(e,t){$n(lt(e),{recursive:!0});let n=ft(lt(e),`.${Gn(e)}.${process.pid}.${Dn(4).toString("hex")}.tmp`);try{Kn(n,t,"utf8");try{at(n,e)}catch(o){let r=o instanceof Error&&"code"in o?o.code:void 0;if(r==="EEXIST"||r==="EPERM"||r==="EACCES"){ct(e),at(n,e);return}throw o}}catch(o){try{ct(n)}catch{}throw o}}function pt(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function mt(){process.stdout.write('{"continue":true}')}function g(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function te(){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 Ie(e){return new Promise(t=>{let n="",o=!1,r=a=>{o||(o=!0,clearTimeout(s),t(a||"{}"))},s=setTimeout(()=>{r(n)},e);if(process.stdin.isTTY){r("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",a=>{n+=a}),process.stdin.on("end",()=>{r(n)}),process.stdin.on("error",()=>{r(n)}),process.stdin.resume()})}async function R(e,t,n=3e3,o={}){let{execFile:r}=await import("node:child_process"),{promisify:s}=await import("node:util"),a=s(r);try{let{stdout:i}=await a(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:o.cwd});return{ok:!0,stdout:i.trim()}}catch(i){let c=i,u=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:u,spawnFailed:u===void 0}}}async function h(e,t,n=3e3,o={}){let r=await R(e,t,n,o);return r.ok?r.stdout:""}async function w(e=process.cwd()){return await h("git",["rev-parse","--show-toplevel"],2e3,{cwd:e})||e}function _(e,t){try{return JSON.parse(e)}catch{return t}}function K(e){return typeof e=="string"?e:""}function N(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let o=t.split("."),r=e;for(let s of o){if(r===null||typeof r!="object"||Array.isArray(r))return;r=r[s]}if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return r}function d(e,t){let n=N(e,t);return typeof n=="string"?n:""}var ne=500;function G(e,t=2){if(!ut(e))return{entries:[],truncated:!1};let n=[],o=!1,r=(s,a)=>{if(a>t||o)return;let i;try{i=Bn(s,{withFileTypes:!0})}catch{return}for(let c of i){if(o)return;let u=ft(s,c.name);if(c.isDirectory()){r(u,a+1);continue}if(c.isFile()){try{n.push({name:Jn(e,u),size:dt(u).size})}catch{continue}if(n.length>=ne){o=!0;return}}}};return r(e,1),{entries:n,truncated:o}}function J(e){return ut(e)?{present:!0,size:dt(e).size}:{present:!1,size:0}}function _t(e,t){return`${e}:${t??""}`}function be(e=oe()){return xe(e,".evalon","agent-hook")}function eo(e=oe()){return xe(be(e),"installations")}function to(e,t=oe()){return xe(eo(t),`${e}.json`)}function gt(){return Vn(8).toString("hex")}async function no(e){let n=await h("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Qn(e);return Wn("sha256").update(n).digest("hex").slice(0,16)}function oo(e){if(!e||typeof e!="object"||Array.isArray(e))return;let t={};for(let[n,o]of Object.entries(e))typeof o=="string"&&o.length>0&&(t[n]=o);return Object.keys(t).length>0?t:void 0}function re(e){if(zn(e))try{let t=JSON.parse(Xn(e,"utf8"));if(typeof t.installation_id=="string"&&t.installation_id.length>0){let n=oo(t.platform_agent_ids);return{installation_id:t.installation_id,...n?{platform_agent_ids:n}:{}}}}catch{}}function kt(e,t){let o=re(e)?.platform_agent_ids?.[t];return typeof o=="string"&&o.length>0?o:void 0}function yt(e,t,n){if(!n)return;let o=re(e);if(!o||o.platform_agent_ids?.[t]===n)return;let r={installation_id:o.installation_id,platform_agent_ids:{...o.platform_agent_ids,[t]:n}};try{L(e,`${JSON.stringify(r,null,2)}
5
- `)}catch(s){let a=s instanceof Error?s.message:String(s);l(`WARN: platform_agent_id cache write failed open: ${a}`)}}function ro(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function so(e,t){Yn(Zn(e),{recursive:!0}),qn(e,`${JSON.stringify({installation_id:t},null,2)}
6
- `,{encoding:"utf8",flag:"wx"})}function ht(e,t){try{return so(e,t),{installation_id:t}}catch(n){if(!ro(n))throw n;return re(e)}}async function se(e,t={}){let n=t.home??oe(),o=await no(e),r=to(o,n),s=re(r);if(s)return{installationId:s.installation_id,storePath:r,repoKey:o};let a=t.overrideId??t.migrateFromManifestId??gt(),i=ht(r,a);if(i)return{installationId:i.installation_id,storePath:r,repoKey:o};let c=ht(r,gt());if(c)return{installationId:c.installation_id,storePath:r,repoKey:o};throw new Error(`Failed to create installation record at ${r}`)}import{existsSync as Re,readFileSync as io}from"node:fs";import{dirname as ao,join as St,relative as co}from"node:path";var ie=[D,".cursor/evalon-runtime-report.json",".codex/evalon-runtime-report.json"];async function lo(e=process.cwd(),t){let n=g("EVALON_HOOK_MANIFEST");if(n&&Re(n))return n;let o=t??await w(e);for(let r of ie){let s=St(o,r);if(Re(s))return s}for(let r of ie){let s=St(e,r);if(Re(s))return s}}async function uo(e,t){let n=t??await w(ao(e)),o=co(n,e),r=await R("git",["ls-files","--error-unmatch",o],2e3,{cwd:n});return r.ok?!0:r.code===1?!1:(l(`WARN: git ls-files failed for manifest ${e} (code=${String(r.code)}); treating as tracked`),!0)}function fo(e){let t=io(e,"utf8");return _(t,{})}function po(){return{schema_version:2,mcp_servers:[]}}async function Et(e=process.cwd()){let t=await w(e),n=await lo(e,t),o=n?fo(n):po(),r,s=n?await uo(n,t):!1;s&&o.installation_id?(l(`WARN: ignoring installation_id in git-tracked manifest ${n}; identity is per-machine under ~/.evalon/agent-hook/installations/`),delete o.installation_id):!s&&o.installation_id&&(r=o.installation_id,delete o.installation_id),o.capture_hook_input==="full"&&n&&s&&(l(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${n}; use EVALON_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete o.capture_hook_input);let{installationId:a,storePath:i}=await se(t,{migrateFromManifestId:r});return o.installation_id=a,{manifestPath:n??i,manifest:o,installationId:a,installationStorePath:i,collectorUrl:it(o),platformAgentId:o.platform_agent_id??"",gitRoot:t}}function vt(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var mo=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"];function Ce(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0}function wt(e=process.platform,t=process.arch){let n=Ce(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${mo.join(", ")}.`);return n}function Ae(e){return`compile-out/bin/${e}/evalon-agent-hook`}function wo(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.evalon.ai/{orgToken}/hook>`);let o=$(n);if(o)throw new Error(`collector URL rejected: ${o}`);return B(n)}function Io(e){let t=e.collectorUrl?.trim();if(!t)return;let n=$(t);if(n)throw new Error(`collector URL rejected: ${n}`);return B(t)}function xo(e){return wo(e,"install")}function Ct(e){let t={};for(let n=0;n<e.length;n++){let o=e[n];if(o==="--url"){let r=e[n+1];r&&!r.startsWith("--")&&(t.collectorUrl=r,n+=1);continue}if(o==="--collector-url")throw new Error("--collector-url was renamed to --url")}return t}function At(e){let t={};for(let n=0;n<e.length;n++){let o=e[n];if(o==="--url"){let r=e[n+1];r&&!r.startsWith("--")&&(t.collectorUrl=r,n+=1);continue}if(o==="--collector-url")throw new Error("--collector-url was renamed to --url");if(o==="--update")throw new Error("--update was removed; use the `update` command instead of `install --update`");if(o==="--delivery"){let r=e[n+1];(r==="npx"||r==="binary")&&(t.delivery=r,n+=1);continue}if(o==="--force"){t.force=!0;continue}if(o==="--no-claude"){t.skipClaude=!0;continue}if(o==="--no-cursor"){t.skipCursor=!0;continue}if(o==="--no-codex"){t.skipCodex=!0;continue}}return t}function Ot(e=process.execPath){return Pt(e)?"binary":"npx"}function bo(){return f(A(),".evalon","agent-hook")}function Ro(e=A()){return f(e,".evalon","agent-hook",ye)}function Co(){let e=Te(vo(import.meta.url)),t=f(e,"hook.mjs");return C(t)?t:f(e,"..","dist","hook.mjs")}function Pt(e=process.execPath){return yo(e)===P}function Tt(e,t){let n=Rt(It(e),It(t));return!n.startsWith("..")&&!So(n)}function ce(e){return e.split(Eo).join("/")}function Ao(e){return`node "$(git rev-parse --show-toplevel)/${ce(e)}"`}function Oo(e){return`"$(git rev-parse --show-toplevel)/${ce(e)}"`}function Po(e){return f(e,Se)}function Nt(e,t){let n=Po(e);Pe(Te(n),{recursive:!0}),bt(t,n,{force:!0});try{xt(n,493)}catch{}return n}function To(e){let t=f(bo(),"current");try{ae(t,{recursive:!0,force:!0})}catch{}_o(e,t,process.platform==="win32"?"junction":"dir")}function Ht(e,t=b,n=A()){let o=f(n,".evalon","agent-hook",t),r=f(o,P);Pe(o,{recursive:!0}),bt(e,r,{force:!0});try{xt(r,493)}catch{}return To(o),f(n,".evalon","agent-hook",ye)}function Mt(e){let t=Ce();if(!t)return;let n=[f(e,Ae(t)),f(e,"packages","agent-hook",Ae(t))];for(let o of n)if(C(o)&&Tt(e,o))return o}function No(e=A()){let t=Ro(e);return C(t)?t:void 0}function Ho(e,t=A()){let n=No(t);return n||(Pt()?Ht(process.execPath,b,t):Mt(e))}function Mo(e,t=A()){let n=Mt(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
7
- To install a released binary instead: curl -fsSL https://cdn.evalon.ai/agent-hook/install.sh | sh`);let o=Ht(n,b,t),r=Nt(e,n);return{sourcePath:n,projectPath:r,globalPath:o}}function Lo(e){let t=[f(e,"packages","agent-hook","dist","hook.mjs"),f(e,Ye)],n=Co();C(n)&&Tt(e,n)&&t.unshift(n);for(let o of t){if(!C(o))continue;let r=ce(Rt(e,o));return{command:Ao(r),hookPath:r,strategy:"dev_mjs"}}}function Uo(e=Q){return`npx -y ${e}`}function jo(e,t=A(),n=Ot()){if(n==="npx")return{command:Uo(),hookPath:Q,strategy:"npx"};let o=Ho(e,t);if(o){Nt(e,o);let s=ce(Se);return{command:Oo(s),hookPath:s,strategy:"project_binary"}}let r=Lo(e);if(r)return r;throw new Error(`evalon-agent-hook binary not found. Install from CDN:
8
- curl -fsSL ${Xe}/install.sh | sh
5
+ var Fo=Object.create;var fn=Object.defineProperty;var $o=Object.getOwnPropertyDescriptor;var Bo=Object.getOwnPropertyNames;var jo=Object.getPrototypeOf,Go=Object.prototype.hasOwnProperty;var pn=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var Ko=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Jo=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Bo(t))!Go.call(e,o)&&o!==n&&fn(e,o,{get:()=>t[o],enumerable:!(r=$o(t,o))||r.enumerable});return e};var Vo=(e,t,n)=>(n=e!=null?Fo(jo(e)):{},Jo(t||!e||!e.__esModule?fn(n,"default",{value:e,enumerable:!0}):n,e));var qr=Ko(K=>{"use strict";Object.defineProperty(K,"__esModule",{value:!0});K.ComponentKind=void 0;K.normalizeRepositoryRelativePath=Yr;K.nativeKeyForSkillPath=ba;K.serializeComponentIdentity=Xr;K.buildComponentReference=Pa;K.validateComponentReference=Na;var Oa=pn("node:crypto"),Aa=pn("node:path"),xa="cmp1_",Ta=/^cmp1_[A-Za-z0-9_-]{43}$/,va=["/skills/","/skills-cursor/"];K.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE"};function ze(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Yr(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=Aa.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return ze(n,"sourcePath")}function ba(e){let t=e.replaceAll("\\","/");for(let n of va){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function wa(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Xr(e){let t=[ze(e.installationRootExternalKey,"installationRootExternalKey"),ze(e.installableKind,"installableKind"),Yr(e.sourcePath),ze(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(wa).join("|")}`,"utf8")}function Pa(e){let t=(0,Oa.createHash)("sha256").update(Xr(e)).digest("base64url");return`${xa}${t}`}function Na(e){return Ta.test(e)}});import{realpathSync as Al}from"node:fs";import{resolve as xl}from"node:path";import{fileURLToPath as Tl,pathToFileURL as vl}from"node:url";var Wo="https://hooks.ev-ai.ai";function Ne(e,t=Wo){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var Ue=".claude/ev-ai-runtime-report.json",mn="node_modules/@ev-ai/agent-hook/dist/hook.mjs",z="ev-ai-agent-hook",gn="https://cdn.ev-ai.ai/agent-hook",at=`current/${z}`,ct=`.ev-ai/agent-hook/${z}`,_n=5e3,hn=5e3,lt=3e3;var ut=3e3,En=1500,Sn=4*1024,yn=32*1024,zo=4*1024,F="1.0.8",Le=`@ev-ai/agent-hook@${F}`,In="ev-ai runtime report",Rn=["claude","cursor","codex"];import{chmodSync as ar,cpSync as cr,existsSync as B,mkdirSync as xt,readdirSync as zs,readFileSync as Ys,rmSync as Be,symlinkSync as Xs,writeFileSync as qs}from"node:fs";import{homedir as j}from"node:os";import{basename as Zs,dirname as Tt,isAbsolute as Qs,join as y,relative as lr,resolve as sr,sep as ei}from"node:path";import{fileURLToPath as ti}from"node:url";var Yo=new Set(["localhost","127.0.0.1","[::1]","::1"]),kn=/^[A-Za-z0-9._~-]+$/;function Cn(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 Me(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Yo.has(t.hostname):!1}catch{return!1}}function pe(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Me(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Xo(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!kn.test(n))return`org token must match ${kn.source} (got: ${n})`;if(Cn(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(Cn(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function me(e){return new URL(e).toString()}function Xo(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function dt(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 On(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?Ne(t):""}import{createHash as Fn,randomBytes as Ss}from"node:crypto";import{existsSync as $n,mkdirSync as St,readFileSync as Bn,unlinkSync as jn,writeFileSync as Gn}from"node:fs";import{homedir as yt}from"node:os";import{dirname as De,join as It,resolve as ys}from"node:path";var qo=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),Zo=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function Q(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||Zo.has(n)||r.includes("[bot]")||qo.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 is,readFileSync as as}from"node:fs";import{hostname as Pn,userInfo as cs}from"node:os";import{randomBytes as Qo}from"node:crypto";import{existsSync as pt,mkdirSync as es,readdirSync as ts,readFileSync as ns,renameSync as An,statSync as vn,unlinkSync as xn,writeFileSync as rs}from"node:fs";import{basename as os,dirname as Tn,join as bn,relative as ss}from"node:path";function d(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
6
+ `)}function Y(e,t){es(Tn(e),{recursive:!0});let n=bn(Tn(e),`.${os(e)}.${process.pid}.${Qo(4).toString("hex")}.tmp`);try{rs(n,t,"utf8");try{An(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){xn(e),An(n,e);return}throw r}}catch(r){try{xn(n)}catch{}throw r}}function He(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function wn(){process.stdout.write('{"continue":true}')}function k(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function ge(){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 mt(e){return new Promise(t=>{let n="",r=!1,o=a=>{r||(r=!0,clearTimeout(s),t(a||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",a=>{n+=a}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function U(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),a=s(o);try{let{stdout:i}=await a(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:i.trim()}}catch(i){let c=i,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 C(e,t,n=3e3,r={}){let o=await U(e,t,n,r);return o.ok?o.stdout:""}async function gt(e=process.cwd()){let t=await U("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(k("EV_AI_HOOK_DEBUG")){let r=t.ok?"empty stdout":t.spawnFailed?"spawn failed":`exit ${String(t.code??"unknown")}`;d(`DEBUG: git rev-parse --show-toplevel failed (${r}) cwd=${e}`)}let n=k("CURSOR_PROJECT_DIR")??k("CLAUDE_PROJECT_DIR");if(n&&pt(n)){let r=await U("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 $(e=process.cwd()){return(await gt(e)).root}function w(e,t){try{return JSON.parse(e)}catch{return t}}var ft=new Map;function ae(e,t){let n=ft.get(e);if(n!==void 0)return n;try{let r=w(ns(e,"utf8"),t);return ft.set(e,r),r}catch{return ft.set(e,t),t}}function ee(e){return typeof e=="string"?e:""}function te(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 p(e,t){let n=te(e,t);return typeof n=="string"?n:""}var H=500;function _e(e,t=2){if(!pt(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,a)=>{if(a>t||r)return;let i;try{i=ts(s,{withFileTypes:!0})}catch{return}for(let c of i){if(r)return;let l=bn(s,c.name);if(c.isDirectory()){o(l,a+1);continue}if(c.isFile()){try{n.push({name:ss(e,l),size:vn(l).size})}catch{continue}if(n.length>=H){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function he(e){return pt(e)?{present:!0,size:vn(e).size}:{present:!1,size:0}}function Ee(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}var ls=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function us(e){return ls.some(t=>!!I(t,e))}function ds(e){if(I("KUBERNETES_SERVICE_HOST",e)||Ee(I("REMOTE_CONTAINERS",e))||Ee(I("DEVCONTAINER",e)))return!0;try{if(is("/.dockerenv")||as("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Nn(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!I(t,e))}function fs(e,t=process.platform){return Nn(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!I(n,e)):!1}function ps(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function ms(e){return e==="linux"}function I(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return k(e)}function gs(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!_s(I("CURSOR_VERSION",n))}function _s(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function _t(e){if(ps(e.sessionId))return!0;let t=e.hostname??Pn(),n=e.osUser??Un(e.env);return gs(t,n,e.env)}function hs(e){return Ee(I("CURSOR_AGENT",e.env))?!0:_t(e)}function Es(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(I("TERM",e)??I("TERM_PROGRAM",e))||(I("SSH_TTY",e)??I("SSH_CONNECTION",e))||(I("__CFBundleIdentifier",e)??I("XPC_SERVICE_NAME",e))||Nn(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!I(t,e))||I("SESSIONNAME",e))}function Se(e={}){let t=e.env;if(I("GITHUB_ACTIONS",t))return"github_actions";if(Ee(I("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!fs(t,n)&&hs(e)&&(Ee(I("CURSOR_AGENT",t))||ms(n)))return"cursor_cloud";if(I("CODESPACES",t)||I("CODESPACE_NAME",t))return"codespaces";if(I("GITLAB_CI",t))return"gitlab_ci";if(us(t))return"managed";let r=I("CI",t);return r&&r!=="false"&&r!=="0"?"managed":ds(t)?"container":Es(t)?"interactive":"unknown"}async function ht(){return await C("systemd-detect-virt",[],1e3)}function Un(e=process.env,t=cs){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 Et(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await C("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),a=s("/etc/os-release","utf8"),i=a.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=a.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=i??c??""}catch{t=await C("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await C("uname",["-r"],1e3))}else t=await C("ver",[],1e3);let n=Un(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await C("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function ye(){return Pn()}var Is="installation.json",Rs="cloud-bootstrap.lock",ks=6e4;function Kn(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function Ie(e=yt()){return It(e,".ev-ai","agent-hook")}function Cs(e=yt()){return It(Ie(e),Is)}function Jn(e){return It(De(e),Rs)}function Vn(){return Ss(8).toString("hex")}function ce(e){return Fn("sha256").update(e).digest("hex").slice(0,16)}function S(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Wn(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Os(e=process.env){let t=S(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Wn(t)){d(`WARN: ignoring EV_AI_HOOK_INSTALLATION_ID (expected 8\u201364 chars [A-Za-z0-9._-], got length ${t.length})`);return}return t}}function zn(e,t){return e&&Wn(e)?e:(e&&d(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Os(t))}function As(e){return/^[0-9a-f]{16}$/.test(e)}function xs(e=process.env){if(S(e.GITHUB_ACTIONS)){let t=S(e.GITHUB_REPOSITORY_ID)??S(e.GITHUB_REPOSITORY),n=S(e.GITHUB_ACTOR)??S(e.GITHUB_TRIGGERING_ACTOR)??S(e.GITHUB_USER);if(t&&n)return ce(`github_actions|${t}|${n}`)}if(S(e.CODESPACES)||S(e.CODESPACE_NAME)){let t=S(e.CODESPACE_NAME);if(t)return ce(`codespaces|${t}`);let n=S(e.GITHUB_REPOSITORY_ID)??S(e.GITHUB_REPOSITORY),r=S(e.GITHUB_USER)??S(e.GITHUB_ACTOR);if(n&&r)return ce(`codespaces|${n}|${r}`)}if(S(e.GITLAB_CI)){let t=S(e.CI_PROJECT_ID)??S(e.CI_PROJECT_PATH),n=S(e.GITLAB_USER_LOGIN)??S(e.GITLAB_USER_EMAIL)??S(e.GITLAB_USER_NAME);if(t&&n)return ce(`gitlab|${t}|${n}`)}return null}var Ts="cursoragent@cursor.com";function vs(e){let t=S(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===Ts?null:t}function bs(e,t){return S(e.CURSOR_PROJECT_DIR)??S(e.CLAUDE_PROJECT_DIR)??t}function ws(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Ps(e){let t=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?ws(t):e}async function Ns(e){let t=S(await C("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!Q(null,t))return t;let n=S(await C("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!Q(null,n)?n:null}function Us(e,t){let n=bs(e,t);return n?ce(`cursor_cloud|${n}|${vs(e)??""}`):null}async function Ls(e,t){let n=S(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Ps(n),o=await Ns(n);return ce(`claude_remote|${r}|${o??""}`)}function Ln(e,t){let n=zn(e,t);if(n)return n;let r=xs(t);return r||Vn()}async function Ms(e){let n=await C("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||ys(e);return Fn("sha256").update(n).digest("hex").slice(0,16)}function Hs(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 Ds(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Hs(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 ne(e){if($n(e))try{return Ds(Bn(e,"utf8"))}catch{}}function Rt(e){return ne(e)}function Yn(e,t,n){let r=ne(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Y(e,`${JSON.stringify(o,null,2)}
7
+ `)}catch(s){let a=s instanceof Error?s.message:String(s);d(`WARN: operator identity cache write failed open: ${a}`)}}function Xn(e,t=Date.now()){if(!e)return!0;if(ne(e)?.operator_identity_hash)return!1;let n=Jn(e);try{if($n(n)){let r=Number.NaN;try{r=Number(Bn(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<ks)return!1;try{jn(n)}catch{}}}catch{}try{return St(De(n),{recursive:!0}),Gn(n,`${t}
8
+ `,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(er(r))return!1;let o=r instanceof Error?r.message:String(r);return d(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function qn(e){if(e)try{jn(Jn(e))}catch{}}function Zn(e,t){let r=ne(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Qn(e,t,n){if(!n)return;let r=ne(e);if(!r||r.platform_agent_ids?.[t]===n)return;let o={installation_id:r.installation_id,platform_agent_ids:{...r.platform_agent_ids,[t]:n},...r.operator_identity_hash?{operator_identity_hash:r.operator_identity_hash}:{},...r.operator_identity_sent_at?{operator_identity_sent_at:r.operator_identity_sent_at}:{}};try{Y(e,`${JSON.stringify(o,null,2)}
9
+ `)}catch(s){let a=s instanceof Error?s.message:String(s);d(`WARN: platform_agent_id cache write failed open: ${a}`)}}function er(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Fs(e,t){St(De(e),{recursive:!0}),Gn(e,`${JSON.stringify(t,null,2)}
10
+ `,{encoding:"utf8",flag:"wx"})}function Mn(e,t){try{return Fs(e,t),t}catch(n){if(!er(n))throw n;return ne(e)}}function Hn(e,t){St(De(e),{recursive:!0}),Y(e,`${JSON.stringify(t,null,2)}
11
+ `)}function Dn(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Fe(e,t={}){let n=t.home??yt(),r=t.env??process.env,o=await Ms(e),s=Cs(n),a={sessionId:t.sessionId,hostname:S(r.HOSTNAME)??void 0,osUser:S(r.USER)??S(r.LOGNAME)??S(r.USERNAME)??void 0,env:r},i=Se(a),c=zn(t.overrideId,r),l=i==="cursor_cloud"&&_t(a)?Us(r,e):i==="claude_remote"?await Ls(r,e):null,u=ne(s);if(u){let E=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(E={...u,pinned:!0},Hn(s,E)),!!l&&l!==E.installation_id&&!c&&E.pinned!==!0&&As(E.installation_id)&&l){let A={installation_id:l,...E.platform_agent_ids?{platform_agent_ids:E.platform_agent_ids}:{}};return Hn(s,A),{installationId:l,storePath:s,repoKey:o}}return{installationId:E.installation_id,storePath:s,repoKey:o}}let f=c??l??Ln(void 0,r),g=Mn(s,Dn(f,c));if(g)return{installationId:g.installation_id,storePath:s,repoKey:o};let m=c??l??Ln(void 0,r),_=Mn(s,Dn(m===f?Vn():m,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as kt,readFileSync as $s}from"node:fs";import{dirname as Bs,join as tr,relative as js}from"node:path";var $e=[Ue,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];async function Gs(e=process.cwd(),t){let n=k("EV_AI_HOOK_MANIFEST");if(n&&kt(n))return n;let r=t??await $(e);for(let o of $e){let s=tr(r,o);if(kt(s))return s}for(let o of $e){let s=tr(e,o);if(kt(s))return s}}async function Ks(e,t){let n=t??await $(Bs(e)),r=js(n,e),o=await U("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(d(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function Js(e){let t=$s(e,"utf8");return w(t,{})}function Vs(){return{schema_version:2,mcp_servers:[]}}async function nr(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await gt(e),o=await Gs(e,n),s=o?Js(o):Vs();delete s.installation_id;let a=o?await Ks(o,n):!1;s.capture_hook_input==="full"&&o&&a&&(d(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${o}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete s.capture_hook_input);let{installationId:i,storePath:c,repoKey:l}=await Fe(n,{sessionId:t.sessionId});return{manifestPath:o??c,manifest:s,installationId:i,installationStorePath:c,repoKey:l,collectorUrl:On(s),platformAgentId:s.platform_agent_id??"",gitRoot:n,inGitRepo:r}}function rr(e){return{schema_version:2,...e?{collector_url:e}:{},mcp_servers:[]}}var Ws=["darwin-arm64","darwin-x64","linux-arm64","linux-x64"];function Ct(e=process.platform,t=process.arch){if(e==="darwin")return t==="arm64"?"darwin-arm64":t==="x64"?"darwin-x64":void 0;if(e==="linux")return t==="arm64"?"linux-arm64":t==="x64"?"linux-x64":void 0}function or(e=process.platform,t=process.arch){let n=Ct(e,t);if(!n)throw new Error(`Unsupported platform ${e}-${t}. Supported: ${Ws.join(", ")}.`);return n}function Ot(e){return`compile-out/bin/${e}/ev-ai-agent-hook`}function ni(e,t){let n=e.collectorUrl?.trim();if(!n)throw new Error(`${t} requires --url <https://hooks.ev-ai.ai/{orgToken}/hook>`);let r=pe(n);if(r)throw new Error(`collector URL rejected: ${r}`);return me(n)}function ri(e){let t=e.collectorUrl?.trim();if(!t)return;let n=pe(t);if(n)throw new Error(`collector URL rejected: ${n}`);return me(t)}function oi(e){return ni(e,"install")}function ur(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 dr(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 fr(e=process.execPath){return pr(e)?"binary":"npx"}function si(){return y(j(),".ev-ai","agent-hook")}function ii(e=j()){return y(e,".ev-ai","agent-hook",at)}function ai(){let e=Tt(ti(import.meta.url)),t=y(e,"hook.mjs");return B(t)?t:y(e,"..","dist","hook.mjs")}function pr(e=process.execPath){return Zs(e)===z}function mr(e,t){let n=lr(sr(e),sr(t));return!n.startsWith("..")&&!Qs(n)}function je(e){return e.split(ei).join("/")}function ci(e){return`node "$(git rev-parse --show-toplevel)/${je(e)}"`}function li(e){return`"$(git rev-parse --show-toplevel)/${je(e)}"`}function ui(e){return y(e,ct)}function gr(e,t){let n=ui(e);xt(Tt(n),{recursive:!0}),cr(t,n,{force:!0});try{ar(n,493)}catch{}return n}function di(e){let t=y(si(),"current");try{Be(t,{recursive:!0,force:!0})}catch{}Xs(e,t,process.platform==="win32"?"junction":"dir")}function _r(e,t=F,n=j()){let r=y(n,".ev-ai","agent-hook",t),o=y(r,z);xt(r,{recursive:!0}),cr(e,o,{force:!0});try{ar(o,493)}catch{}return di(r),y(n,".ev-ai","agent-hook",at)}function hr(e){let t=Ct();if(!t)return;let n=[y(e,Ot(t)),y(e,"packages","agent-hook",Ot(t))];for(let r of n)if(B(r)&&mr(e,r))return r}function fi(e=j()){let t=ii(e);return B(t)?t:void 0}function pi(e,t=j()){let n=fi(t);return n||(pr()?_r(process.execPath,F,t):hr(e))}function mi(e,t=j()){let n=hr(e);if(!n)throw new Error(`update requires a locally compiled binary \u2014 run this package\u2019s build:hook-binary script first.
12
+ To install a released binary instead: curl -fsSL https://cdn.ev-ai.ai/agent-hook/install.sh | sh`);let r=_r(n,F,t),o=gr(e,n);return{sourcePath:n,projectPath:o,globalPath:r}}function ir(e){let t=[y(e,"packages","agent-hook","dist","hook.mjs"),y(e,mn)],n=ai();B(n)&&mr(e,n)&&t.unshift(n);for(let r of t){if(!B(r))continue;let o=je(lr(e,r));return{command:ci(o),hookPath:o,strategy:"dev_mjs"}}}function gi(e=Le){return`npx -y ${e}`}function _i(e,t=j(),n=fr()){if(n==="npx")return{command:gi(),hookPath:Le,strategy:"npx"};if(n==="local"){let s=ir(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=pi(e,t);if(r){gr(e,r);let s=je(ct);return{command:li(s),hookPath:s,strategy:"project_binary"}}let o=ir(e);if(o)return o;throw new Error(`ev-ai-agent-hook binary not found. Install from CDN:
13
+ curl -fsSL ${gn}/install.sh | sh
9
14
  Or use npx delivery:
10
- npx ${Q} install`)}function Lt(e){return typeof e!="string"?!1:e.includes("@evalon-ai/agent-hook")||e.includes("@evalon/agent-hook")||e.includes("agent-hook/dist/hook")||e.includes(".evalon/agent-hook")||e.includes(P)||/(?:^|[\s/"'])evalon-agent-hook(?:$|[\s"'])/.test(e)}function Ne(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function T(e,t){Pe(Te(e),{recursive:!0}),ko(e,`${JSON.stringify(t,null,2)}
11
- `,"utf8")}function I(e){if(C(e))try{return JSON.parse(ho(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function Fo(e,t){let n=vt(t.collectorUrl),o={...e,schema_version:e?.schema_version??n.schema_version};return t.collectorUrl!==void 0?o.collector_url=t.collectorUrl:o.collector_url=e?.collector_url??n.collector_url,delete o.repo_ingest_token,delete o.installation_id,o.mcp_servers??=n.mcp_servers,o}function Do(e){return(e.schema_version??2)===2&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.repo_ingest_token===void 0}function Ut(e,t){let n=f(e,D),o=I(n),r=Fo(o,t);return t.collectorUrl!==void 0||C(n)||!Do(r)?(T(n,r),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function Oe(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(o=>o.startsWith("OTEL_"))}function $o(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return f(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function Bo(e=process.platform){let t=$o(e),n=[f(t,"managed-settings.json")],o=f(t,"managed-settings.d");try{if(!C(o))return n;let r=go(o).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>f(o,s));n.push(...r)}catch{}return n}function Ko(e){if(Oe(process.env))return!0;let t=A();return[...Bo(),f(t,".claude","settings.json"),f(t,".claude","remote-settings.json"),f(e,".claude","settings.json"),f(e,".claude","settings.local.json")].some(o=>{try{let r=I(o);return r?Oe(r.env):!1}catch{return!1}})}function Go(e){try{let t=I(f(e,".claude","settings.json"));return t?Oe(t.env):!1}catch{return!1}}function jt(e){return Array.isArray(e)?e:[]}function le(e){let t=[],n=o=>!!o&&typeof o=="object"&&Lt(o.command);for(let o of jt(e)){if(!o||typeof o!="object"){t.push(o);continue}let r=Array.isArray(o.hooks)?o.hooks:[],s=r.filter(a=>!n(a));if(!(s.length===0&&r.some(n))){if(s.length!==r.length){t.push({...o,hooks:s});continue}t.push(o)}}return t}function Ft(e,t){return[...le(e),...t]}function He(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!Lt(t.command)):[]}function Jo(e,t){return[...He(e),{command:t}]}function Wo(e){let t=()=>({hooks:[{type:"command",command:e}]});return{SessionStart:[t()],UserPromptExpansion:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function Vo(e){let t={type:"command",command:e,statusMessage:nt},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var zo=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","subagentStart","subagentStop","stop"],Yo=["beforeMCPExecution","beforeShellExecution","afterFileEdit"];function Xo(e){let t={...e};for(let n of Yo){if(!(n in t))continue;let o=He(t[n]);o.length===0?delete t[n]:t[n]=o}return t}function qo(e,t,n={}){let o=f(e,".claude/settings.json"),r=Ne(t,"claude"),s=I(o)??{};if(Ko(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let p={...s.hooks};for(let m of Object.keys(p))p[m]=le(p[m]),jt(p[m]).length===0&&delete p[m];Object.keys(p).length===0?delete s.hooks:s.hooks=p,T(o,s)}return!1}let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=Wo(r),u={...i};for(let[p,m]of Object.entries(c))u[p]=Ft(i[p],m);return s.hooks=u,T(o,s),!0}function Zo(e,t){let n=f(e,".cursor/hooks.json"),o=Ne(t,"cursor"),r=I(n)??{},s=r.hooks&&typeof r.hooks=="object"?r.hooks:{},a=Xo({...s});for(let i of zo)a[i]=Jo(a[i],o);T(n,{...r,version:typeof r.version=="number"?r.version:1,hooks:a})}function Qo(e,t){let n=f(e,".codex/hooks.json"),o=Ne(t,"codex"),r=I(n)??{},s=r.hooks&&typeof r.hooks=="object"?r.hooks:{},a=Vo(o),i={...s};for(let[c,u]of Object.entries(a))i[c]=Ft(s[c],u);T(n,{...r,hooks:i})}function er(e){let t=f(e,".claude/settings.json"),n=I(t);if(!n?.hooks||typeof n.hooks!="object")return;let o={...n.hooks},r=!1;for(let s of Object.keys(o)){let a=o[s],i=le(a);JSON.stringify(a)!==JSON.stringify(i)&&(r=!0),i.length===0?delete o[s]:o[s]=i}r&&(Object.keys(o).length===0?delete n.hooks:n.hooks=o,T(t,n),l(`Removed Evalon hooks from ${t}`))}function tr(e){let t=f(e,".cursor/hooks.json"),n=I(t);if(!n?.hooks||typeof n.hooks!="object")return;let o={...n.hooks},r=!1,s=0;for(let a of Object.keys(o)){let i=o[a],c=He(i);JSON.stringify(i)!==JSON.stringify(c)&&(r=!0),c.length===0?delete o[a]:(o[a]=c,s+=c.length)}if(r){if(s===0&&Object.keys(o).length===0&&Object.keys(n).filter(i=>i!=="hooks"&&i!=="version").length===0){ae(t,{force:!0}),l(`Removed ${t}`);return}T(t,{...n,hooks:o}),l(`Removed Evalon hooks from ${t}`)}}function nr(e){let t=f(e,".codex/hooks.json"),n=I(t);if(!n?.hooks||typeof n.hooks!="object")return;let o={...n.hooks},r=!1,s=0;for(let a of Object.keys(o)){let i=o[a],c=le(i);JSON.stringify(i)!==JSON.stringify(c)&&(r=!0),c.length===0?delete o[a]:(o[a]=c,s+=c.length)}if(r){if(s===0&&Object.keys(o).length===0&&Object.keys(n).filter(i=>i!=="hooks").length===0){ae(t,{force:!0}),l(`Removed ${t}`);return}T(t,{...n,hooks:o}),l(`Removed Evalon hooks from ${t}`)}}function Me(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)&&wt(e,t)}async function Dt(e={}){let t=xo(e);e.collectorUrl=t;let n=e.skipClaude===!0,o=e.skipCursor===!0,r=e.skipCodex===!0;if(n&&o&&r)throw new Error("at least one runner must be wired; refuse --no-claude --no-cursor --no-codex together");let s=e.delivery??Ot();Me(process.platform,process.arch,{requireBinaryArch:s==="binary"});let a=e.cwd??process.cwd(),i=await w(a),{command:c,hookPath:u,strategy:p}=jo(i,A(),s),m=I(f(i,D)),{installationId:E,storePath:k}=await se(i,{overrideId:e.installationId,migrateFromManifestId:m?.installation_id}),{manifestPath:O,wrote:v}=Ut(i,e),y=[];return n?l("Skipped Claude hook \u2014 --no-claude"):qo(i,c,{force:e.force})?(y.push("Claude"),e.force&&Go(i)&&l("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):l("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),o?l("Skipped Cursor hook \u2014 --no-cursor"):(Zo(i,c),y.push("Cursor")),r?l("Skipped Codex hook \u2014 --no-codex"):(Qo(i,c),y.push("Codex")),l(`Installed hook (${p}) at ${u}`),l(`Installation identity ${E} at ${k}`),v&&O?l(`Shared manifest written to ${O}`):l("Using package default collector config (no shared manifest file needed)"),l(y.length>0?`Wired ${y.join(", ")} hooks in ${i} (commands include --runner)`:`No runner hooks wired in ${i} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),p==="npx"?l("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)."):p==="project_binary"&&l("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .evalon/agent-hook/ (gitignored)."),v&&O&&e.collectorUrl&&l("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:i,hookPath:u,manifestPath:O,installationStorePath:k,strategy:p}}async function $t(e=process.cwd()){Me(process.platform,process.arch,{requireBinaryArch:!0});let t=await w(e),{projectPath:n,globalPath:o}=Mo(t);l(`Refreshed ${o}`),l(`Refreshed ${n}`),l("Hook configs and shared manifest left unchanged")}async function Bt(e={}){let t=Io(e);e.collectorUrl=t,Me(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),o=await w(n),{manifestPath:r,wrote:s}=Ut(o,e);if(t!==void 0&&(!r||!s))throw new Error("configure failed to write shared collector manifest");return s&&r?l(`Wrote ${r}`):t===void 0&&l("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),l("Manifest only \u2014 enable Evalon marketplace plugins (https://github.com/evalon-ai/marketplace). Do not also run file-wiring install for the same events."),{gitRoot:o,manifestPath:r}}function Kt(e){for(let t of[()=>er(e),()=>tr(e),()=>nr(e)])try{t()}catch(n){let o=n instanceof Error?n.message:String(n);l(`WARN: strip skipped a hook file: ${o}`)}}async function Gt(e=process.cwd()){let t=await w(e);return Kt(t),l("Stripped Evalon file-wired hooks; shared collector manifest left in place."),l("Next: enable Evalon marketplace plugins (https://github.com/evalon-ai/marketplace), then restart runners."),{gitRoot:t}}async function Jt(e=process.cwd()){let t=await w(e);Kt(t);for(let n of ie){let o=f(t,n);if(C(o))try{ae(o,{force:!0}),l(`Removed ${o}`)}catch(r){let s=r instanceof Error?r.message:String(r);l(`WARN: uninstall could not remove ${o}: ${s}`)}}}var or={claude:".claude",cursor:".cursor",codex:".codex"};function ue(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function rr(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 ue(n[1]);let o=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(o?.[1])return ue(o[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let r=t.match(/^[^/]+\/(.+)$/);return r?.[1]?ue(r[1]):ue(t)}async function Le(e=process.cwd()){let t=await R("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,o,r,s]=await Promise.all([R("git",["remote","get-url","origin"],2e3,{cwd:e}),R("git",["branch","--show-current"],2e3,{cwd:e}),R("git",["rev-parse","HEAD"],2e3,{cwd:e}),R("git",["status","--porcelain"],2e3,{cwd:e})]),a=n.ok?n.stdout:null;return{remote:a===null?null:a.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:o.ok?o.stdout:null,head:r.ok?r.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function Wt(e,t,n,o=process.cwd(),r,s){if(t)return t;let a=or[n];if(!a)return"";let i=_t(n,e.scope_path);if(s){let k=kt(s,i);if(k)return k}let c=r??await Le(o),u=c?.remote?rr(c.remote):"";if(u||(u=process.env.GITHUB_REPOSITORY??""),!u)return"";let p=e.scope_path??"",m=p?`${p}/`:"",E=`${u}:${m}${a}`;return s&&yt(s,i,E),E}import{existsSync as sr,readFileSync as ir}from"node:fs";import{hostname as ar,userInfo as cr}from"node:os";function Vt(){if(g("GITHUB_ACTIONS"))return"github_actions";let e=g("CI");if(e&&e!=="false"&&e!=="0")return"managed";try{if(sr("/.dockerenv")||ir("/proc/1/environ","utf8").includes("container="))return"container"}catch{}return process.stdin.isTTY||process.stdout.isTTY||g("TERM")?"interactive":"cron"}async function zt(){return await h("systemd-detect-virt",[],1e3)}async function Yt(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await h("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),a=s("/etc/os-release","utf8"),i=a.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=a.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=i??c??""}catch{t=await h("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await h("uname",["-r"],1e3))}else t=await h("ver",[],1e3);let n=process.env.USER??cr().username??"",o=(process.env.SHELL??"").split(/[/\\]/).pop()??"",r="";try{r=await h("tty",[],500),r.includes("not a tty")&&(r="")}catch{r=""}return{os:e,os_version:t||null,user:n||null,shell:o||null,tty:r||null}}function Xt(){return ar()}import{existsSync as lr,readFileSync as ur}from"node:fs";import{homedir as qt}from"node:os";import{join as dr}from"node:path";var fr="cloud-cache.json",pr=1440*60*1e3,mr=900*1e3;function gr(e=qt()){return dr(be(e),fr)}function hr(e){if(!lr(e))return;let t=_(ur(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 _r(e,t){try{L(e,`${JSON.stringify(t)}
12
- `)}catch(n){let o=n instanceof Error?n.message:String(n);l(`WARN: cloud cache write failed open: ${o}`)}}function kr(e,t,n){if(!e||e.context!==t)return!1;let o=e.result===null?mr:pr;return n-e.probed_at<o}async function yr(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 o={"X-aws-ec2-metadata-token":n},[r,s]=await Promise.all([fetch("http://169.254.169.254/latest/meta-data/placement/region",{headers:o,signal:AbortSignal.timeout(e)}).catch(()=>{}),fetch("http://169.254.169.254/latest/meta-data/instance-id",{headers:o,signal:AbortSignal.timeout(e)}).catch(()=>{})]);if(!r?.ok&&!s?.ok)return;let a=r?.ok?(await r.text()).trim():"",i=s?.ok?(await s.text()).trim():"";if(!(!a&&!i))return{provider:"aws",region:a,instance_id:i}}async function Sr(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(),o=typeof n.zone=="string"?n.zone.split("/").pop()??"":"",r=n.id===void 0?"":String(n.id);if(!(!o&&!r))return{provider:"gcp",region:o,instance_id:r}}async function Er(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(),o=n.compute?.location??"",r=n.compute?.vmId??"";if(!(!o&&!r))return{provider:"azure",region:o,instance_id:r}}async function vr(e){let t=await Promise.allSettled([yr(e),Sr(e),Er(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Zt(e,t){if(e==="interactive")return null;let n=t?.home??qt(),o=t?.timeoutMs??1e3,r=t?.nowMs??Date.now(),s=gr(n),a=hr(s);if(kr(a,e,r))return a.result;let i=await vr(o);return _r(s,{context:e,probed_at:r,result:i}),i}import{existsSync as wr,readFileSync as Ir}from"node:fs";import{homedir as xr}from"node:os";import{join as Ue}from"node:path";function je(e,t,n){if(!wr(e))return;let o=_(Ir(e,"utf8"),{});for(let r of Object.keys(o.mcpServers??{}))n.set(r,{name:r,source:t})}async function Qt(e,t=process.cwd(),n="claude",o=xr()){let r=new Map;for(let s of e.mcp_servers??[])s.name&&r.set(s.name,{name:s.name,source:"manifest"});return n==="claude"&&je(Ue(o,".claude.json"),"claude_json_user",r),je(Ue(t,".mcp.json"),"mcp_json",r),je(Ue(t,".cursor/mcp.json"),"cursor_mcp",r),[...r.values()]}var br=["CI","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","BUILDKITE","TF_BUILD","GITHUB_REPOSITORY","GITHUB_REF","GITHUB_SHA","GITHUB_RUN_ID","GITHUB_WORKFLOW","RUNNER_OS","RUNNER_ARCH","NODE_ENV","TERM_PROGRAM","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"],Rr=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Cr(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Rr.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function en(e=process.env){return br.map(t=>Object.prototype.hasOwnProperty.call(e,t)?{name:t,present:!0,value:Cr(e[t]??"")}:{name:t,present:!1})}import{createHash as Ar}from"node:crypto";import{existsSync as on,readFileSync as rn}from"node:fs";import{homedir as sn}from"node:os";import{join as S}from"node:path";var Or={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:".agents/skills",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},Pr=200,tn=200,Tr=["allow","deny","ask"],Nr=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Fe="<path>",Hr=new RegExp(`${Fe}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Mr(e){let t=e.replace(Nr,Fe).replace(Hr,Fe);return t.length>tn?`${t.slice(0,tn)}...`:t}function nn(e){if(!on(e))return{model:"",permissionKeys:[]};let t=_(rn(e,"utf8"),{}),n=[];for(let o of Tr)for(let r of t.permissions?.[o]??[])typeof r=="string"&&r.length>0&&n.push({key:Mr(r),mode:o});return{model:t.model??"",permissionKeys:n}}var Lr=10,Ur="self-config-cache.json",jr={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Fr(e,t=h){let n=jr[e];if(!n||n.length===0)return null;let o=async r=>{let s=n[r];if(s===void 0)return null;let i=((await t(s,["--version"],2e3)).split(`
13
- `)[0]??"").trim();return i||o(r+1)};return o(0)}function Dr(e=sn()){return S(e,".evalon","agent-hook",Ur)}function $r(e){let n=[...e].sort((o,r)=>o.name.localeCompare(r.name)).map(o=>`${o.name}:${o.size}`).join(`
14
- `);return Ar("sha256").update(n).digest("hex").slice(0,16)}function de(e,t,n=!1){let o=$r(e),r=e.length;return t===o?n?{hash:o,count:r,truncated:n}:{hash:o,count:r}:n?{hash:o,count:r,entries:e,truncated:n}:{hash:o,count:r,entries:e}}function Br(e){return on(e)?_(rn(e,"utf8"),{}):{}}function Kr(e,t){try{L(e,`${JSON.stringify(t)}
15
- `)}catch(n){let o=n instanceof Error?n.message:String(n);l(`WARN: self-config cache write failed open: ${o}`)}}function Gr(e,t,n){let o={...e,send_count:n};for(let r of Object.keys(t)){let s=t[r];s.entries!==void 0&&(o[r]=s.hash)}return o}async function an(e,t=process.cwd(),n=sn()){let o=e==="claude",r=await Fr(e),s="",a=[];if(o){let x=nn(S(n,".claude/settings.json")),X=nn(S(t,".claude/settings.local.json"));s=X.model||x.model,a=[...x.permissionKeys,...X.permissionKeys].slice(0,Pr)}let i=Or[e]??{},c={present:!1,size:0},u=x=>{let X=Array.isArray(x)?x:x?[x]:[],M=[],q=!1;for(let Mn of X){let ze=G(S(n,Mn));if(M=M.concat(ze.entries),q=q||ze.truncated,M.length>=ne){M=M.slice(0,ne),q=!0;break}}return{entries:M,truncated:q}},p=Dr(n),m=Br(p),E=m[e]??{},k=(E.send_count??0)+1,O=k>0&&k%Lr===0,v=x=>O?void 0:E[x],y=u(i.skills),j=i.subagents?G(S(n,i.subagents)):{entries:[],truncated:!1},We=i.commands?G(S(n,i.commands)):{entries:[],truncated:!1},Ve=i.rules?G(S(n,i.rules)):{entries:[],truncated:!1},F={skills:de(y.entries,v("skills"),y.truncated),subagents:de(j.entries,v("subagents"),j.truncated),commands:de(We.entries,v("commands"),We.truncated),rules:de(Ve.entries,v("rules"),Ve.truncated)};return m[e]=Gr(E,F,k),Kr(p,m),{runner_platform:e,config_scope:"user",cli_version:r,claude_version:o?r:null,model:o&&s||null,permission_keys:a,user_scope:{skills:F.skills,subagents:F.subagents,commands:F.commands,rules:F.rules,memory:i.memory?J(S(n,i.memory)):c,settings:i.settings?J(S(n,i.settings)):c,mcp:i.mcp?J(S(n,i.mcp)):c},local_settings:o?J(S(t,".claude/settings.local.json")):c}}function W(e,t,n){let o={installation_id:n.installationId};return n.platformAgentId&&(o.platform_agent_id=n.platformAgentId),n.sessionId&&(o.session_id=n.sessionId),n.turnId&&(o.turn_id=n.turnId),{schema_version:2,event:e,timestamp:pt(),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:b,host_arch:process.arch,node_version:process.version,correlation:o,payload:t}}import{existsSync as En}from"node:fs";import{spawn as vn}from"node:child_process";import{basename as ms}from"node:path";import{fileURLToPath as gs}from"node:url";var cn=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,ln=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Jr=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,Wr=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"]),Vr=new Set(["read","read_file","view"]),zr=new Set(["bash","shell","zsh"]);function Yr(e){let t=e.replace(/\\/g,"/");return cn.exec(t)?.[1]??null}function Xr(e){let t=e.replace(/\\/g,"/"),o=ln.exec(t)?.[1];return o?o.toLowerCase():null}function qr(e){return Yr(e)??Xr(e)}function Zr(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 un(e){if(typeof e=="string")try{let t=JSON.parse(e);return un(t)}catch{return null}return!e||typeof e!="object"?null:Zr(e)}function Qr(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function es(e){let t=e.replace(/\\/g,"/"),n=cn.exec(t);if(n?.[1])return n[1];let r=ln.exec(t)?.[1];return r?r.toLowerCase():null}function ts(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function dn(e){let t=ts(e).toLowerCase();if(Vr.has(t)){let n=un(e.tool_input);return n?qr(n):null}if(zr.has(t)){let n=Qr(e.tool_input);return n?es(n):null}return null}function ns(e){let t=new Set,n=[];for(let o of e.matchAll(Jr)){let r=o[1]?.toLowerCase();!r||t.has(r)||Wr.has(r)||(t.add(r),n.push(r))}return n}function os(e){return K(e.prompt)}function fn(e){let t=d(e,"command_name");if(t){let o=d(e,"expansion_type");if(o&&o!=="slash_command")return[];let r=t.replace(/^\//,"").toLowerCase();return r?[r]:[]}let n=os(e);return n?ns(n):[]}function De(e){return e!==void 0&&ot.includes(e)}function fe(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function pe(e){let t,n,o,r,s;for(let a=0;a<e.length;a++){let i=e[a];if(i!==void 0){if(i==="--runner"){let c=fe(e,a);t=c.value,a=c.next;continue}if(i.startsWith("--runner=")){t=i.slice(9);continue}if(i==="--url"){let c=fe(e,a);c.value&&(o=c.value),a=c.next;continue}if(i.startsWith("--url=")){o=i.slice(6);continue}if(i==="--token"){let c=fe(e,a);c.value&&(r=c.value),a=c.next;continue}if(i.startsWith("--token=")){r=i.slice(8);continue}if(i==="--base-url"){let c=fe(e,a);c.value&&(s=c.value),a=c.next;continue}if(i.startsWith("--base-url=")){s=i.slice(11);continue}!i.startsWith("-")&&n===void 0&&(n=i)}}return{runner:De(t)?t:void 0,event:n,collectorUrl:o,orgToken:r,baseUrl:s}}function $e(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let r=e.orgToken?.trim();r&&(n=Z(r,e.baseUrl?.trim()??void 0))}if(!n)return;let o=$(n);if(o){l(`WARN: ignoring --url/--token collector override: ${o}`);return}return B(n)}function rs(e,t){return d(e,"conversation_id")?!0:t!==""&&t===t.toLowerCase()}function Be(e,t,n,o){if(rs(e,t))return"cursor";if(De(o))return o;let r=d(e,"conversation_id"),s=d(e,"turn_id"),a=d(e,"session_id"),i=t.toLowerCase(),c="unknown";return r||t===i&&t!==""?c="cursor":s?c="codex":(a||i==="sessionstart"||i==="sessionend"||i==="stop"||i==="stopfailure"||i==="pretooluse"||i==="posttooluse"||i==="posttoolusefailure"||i==="permissiondenied"||i==="subagentstart"||i==="subagentstop"||i==="userpromptexpansion")&&(c="claude"),De(n)&&(c=n),c}function me(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function ss(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"afterfileedit":case"subagentstart":case"subagentstop":return"tool_invoked";case"beforesubmitprompt":case"userpromptexpansion":case"userpromptsubmit":return"skill_invoked";default:return""}}function pn(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function mn(e,t,n){let o=d(e,"session_id")||d(e,"conversation_id"),r=d(e,"prompt.id")||d(e,"prompt_id")||d(e,"generation_id")||d(e,"turn_id"),s=d(e,"hook_event_name")||d(e,"event"),a=d(e,"source"),i=Be(e,s,t,n);return{sessionId:o,turnId:r,runnerEvent:s,hookSource:a,runnerPlatform:i}}var is=["session_start","session_end","tool_invoked","skill_invoked"];function as(e){return is.includes(e)}function gn(e,t){return e&&as(e)?e:ss(t.toLowerCase())}function hn(e){let t=d(e,"tool_name")||d(e,"tool")||null,n=e.tool_input,r=(n&&typeof n=="object"?K(n.skill)||K(n.skill_name):"")||d(e,"skill_name")||null;return r??=dn(e),{toolName:t,skillName:r}}var cs=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function _n(e){for(let t of["subagent_type","agent_type"]){let n=d(e,t);if(n&&cs.test(n))return n}return null}function kn(e){let t=N(e,"duration_ms");if(typeof t=="number")return t;let n=N(e,"duration");return typeof n=="number"?n:null}var ls="error",us="interrupted",ds="permission_denied",fs=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Ke(e){return fs.test(e)?e:null}function ps(e){for(let t of["failure_type","error_type"]){let n=Ke(d(e,t));if(n)return n}return null}function yn(e,t){return N(e,"is_interrupt")===!0?us:t.toLowerCase()==="permissiondenied"?ds:ps(e)??ls}function Sn(e){if(!e)return{mcpServer:null,mcpTool:null};let t=/^mcp__(.+?)__(.+)$/i.exec(e);if(t?.[1]&&t[2])return{mcpServer:t[1],mcpTool:t[2]};if(/^MCP:/i.test(e)){let n=e.slice(4);if(!n)return{mcpServer:null,mcpTool:null};let o=n.indexOf(":");return o>0?{mcpServer:n.slice(0,o),mcpTool:n.slice(o+1)||null}:{mcpServer:null,mcpTool:n}}return{mcpServer:null,mcpTool:null}}var V="__post",Ge="__work";function hs(e,t){let n=e.payload,o=n&&typeof n=="object"&&!Array.isArray(n)?Object.keys(n):[],r=e.correlation&&typeof e.correlation=="object"?Object.keys(e.correlation):[];return JSON.stringify({event:e.event,schema_version:e.schema_version,agent_hook_version:e.agent_hook_version,host_arch:e.host_arch,node_version:e.node_version,body_bytes:t,correlation_keys:r,payload_keys:o})}function wn(e){switch(e){case"session_start":return qe;case"session_end":return Ze;case"tool_invoked":case"skill_invoked":return Ee;default:return Ee}}function _s(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
16
- ${n}`}function In(e,t=[],n=process.execPath,o=import.meta.url,r=En){if(ms(n)===P)return{command:n,args:[e,...t]};let s=gs(o);return r(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function ks(e=process.execPath,t=import.meta.url,n=En){return In(V,[],e,t,n)}function ys(e){let t=e.indexOf(`
17
- `);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 ge(e,t=fetch){let n=await e(),o=ys(n);if(!o)return;let{meta:r,body:s}=o,a={"Content-Type":"application/json"};try{await t(r.url,{method:"POST",headers:a,body:s,signal:AbortSignal.timeout(Number(r.timeoutMs))})}catch{}}async function Ss(e,t,n){let o=wn(e);l(`POST event=${e} url=${we(n)} size=${t.length} platform=${process.platform}`);let r={"Content-Type":"application/json"},s=Date.now();try{let a=await fetch(n,{method:"POST",headers:r,body:t,signal:AbortSignal.timeout(o)}),i=Date.now()-s;if(a.ok)return l(`POST outcome=ok elapsed_ms=${i} http=${a.status}`),!0;let c=(await a.text()).slice(0,200).replace(/[\n\r]/g,"");return l(`POST outcome=fail elapsed_ms=${i} http=${a.status} body=${c}`),!1}catch(a){let i=Date.now()-s,c=a instanceof Error?a.message:String(a);return l(`POST outcome=fail elapsed_ms=${i} http=000 body=${c}`),!1}}async function xn(e,t,n,o,r){try{let s=o(e,t,{detached:!0,stdio:["pipe","ignore","ignore"],windowsHide:!0});s.on("error",()=>{}),s.stdin.on("error",()=>{});let a=!1;return await new Promise(i=>{let c=setTimeout(()=>{if(!a){l(`WARN: ${r} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}i()},Qe),u=()=>{a=!0,clearTimeout(c),i()};s.stdin.end(n,()=>u()),s.stdin.once("error",()=>u())}),s.unref(),s}catch(s){let a=s instanceof Error?s.message:String(s);return l(`WARN: ${r} spawn failed open: ${a}`),null}}async function Es(e,t,n,o=vn,r=ks){let s=wn(e),a=_s(n,s,t),{command:i,args:c}=r();return xn(i,c,a,o,"detached post")}async function bn(e,t,n=vn,o=In){let{command:r,args:s}=o(Ge,t);return xn(r,s,e,n,"detached work")}async function z(e,t,n,o,r){if(!r){l("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest");return}if(!ee(r)){l(`WARN: collector URL blocked (https required): ${we(r)}`);return}let s=o(e,t,n),a=`${JSON.stringify(s)}
18
- `,i=g("EVALON_HOOK_DEBUG");if(i==="full"?l(`DEBUG envelope=${JSON.stringify(s)}`):i==="1"&&l(`DEBUG summary=${hs(s,Buffer.byteLength(a,"utf8"))}`),!me(n.runnerEvent,n.runnerPlatform)){await Es(e,a,r);return}await Ss(e,a,r)}import{relative as vs,resolve as Je,sep as Rn}from"node:path";var ws=["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","failure_type","is_interrupt"];function Is(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:g("EVALON_HOOK_CAPTURE_FULL_INPUT")==="1"}function xs(e){let t={};for(let n of ws){let o=N(e,n);o!==void 0&&(t[n]=o)}return t}function bs(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=Je(e),o=Je(t),r=vs(o,n);return!r||r==="."?".":r.startsWith(`..${Rn}`)||r===".."||Je(o,r)!==n?null:r.split(Rn).join("/")}function Cn(e,t){let n=JSON.stringify(e),o=Buffer.byteLength(n,"utf8");if(o<=t)return e;let r=Object.entries(e).filter(([a,i])=>!a.startsWith("_")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")).sort((a,i)=>Buffer.byteLength(JSON.stringify(a[1]),"utf8")-Buffer.byteLength(JSON.stringify(i[1]),"utf8")),s={_truncated:!0,_original_bytes:o};for(let[a,i]of r){let c={...s,[a]:i};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[a]=i}return s}function Y(e,t,n={}){let o=n.gitRoot!==void 0?bs(e.cwd,n.gitRoot):null;if(Is(t)){let s={...e};return delete s.cwd,delete s.transcript_path,o!==null&&(s.cwd_relative=o),Cn(s,tt)}let r=xs(e);return o!==null&&(r.cwd_relative=o),Cn(r,et)}import{createReadStream as Rs}from"node:fs";import{stat as Cs}from"node:fs/promises";import{basename as As,resolve as Os}from"node:path";import{createInterface as Ps}from"node:readline";var Ts=1024*1024;function Ns(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&As(t).endsWith(".jsonl")}async function An(e){if(!e||!Ns(e))return null;try{let t=Os(e),n=await Cs(t);if(!n.isFile())return null;let o=Math.max(0,n.size-Ts),r=[],s=Ps({input:Rs(t,{encoding:"utf8",start:o}),crlfDelay:1/0});for await(let a of s)a.length!==0&&r.push(a);o>0&&r.length>0&&r.shift();for(let a=r.length-1;a>=0;a--){let i=r[a];if(i)try{let c=JSON.parse(i);if(c.type!=="assistant")continue;let u=c.message;if(!u||typeof u!="object")continue;let p=u.model;if(typeof p=="string"&&p.length>0)return p}catch{continue}}return null}catch{return null}}function he(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function Hs(...e){for(let t of e)if(t)return t;return null}function U(e,t,n){if(e.status==="fulfilled")return e.value;let o=e.reason instanceof Error?e.reason.message:String(e.reason);return l(`WARN: ${n} failed open: ${o}`),t}function Ms(e){let t={present:!1,size:0},n={hash:"",count:0};return{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}}async function _e(e,t,n){try{e.platformAgentId=await Wt(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,n,e.manifest.installationStorePath)}catch(o){let r=o instanceof Error?o.message:String(o);l(`WARN: derivePlatformAgentId failed open: ${r}`)}}async function Ls(e){let{gitRoot:t}=e.manifest,n=Vt(),o=String(e.runnerPlatform),[r,s,a,i,c,u]=await Promise.allSettled([Le(t),zt(),Zt(n),Yt(),Qt(e.manifest.manifest,t,o),an(o,t)]),p=U(r,null,"gitSnapshot"),m=U(s,"","detectVirt"),E=U(a,null,"probeCloud"),k=U(i,{},"hostEnv"),O=U(c,[],"mcpDeclared"),v=U(u,Ms(o),"selfConfig");await _e(e,t,p);let y=d(e.hookInput,"model");y&&(v.model=y);let j={identity:{host:Xt(),context:n,virt:m||null,cloud:E,git:p},host_env:k,env_vars:en(),mcp:{declared:O},self_config:v,run_meta:{trigger:e.hookSource||"startup"},hook_input:Y(e.hookInput,e.manifest.manifest,{gitRoot:t})};await z("session_start",j,he(e),W,e.manifest.collectorUrl)}async function Us(e){let{gitRoot:t}=e.manifest;await _e(e,t);let n=Hs(d(e.hookInput,"status"),d(e.hookInput,"stop_reason"),d(e.hookInput,"reason"),Ke(d(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await An(d(e.hookInput,"transcript_path")):null,r=Y(e.hookInput,e.manifest.manifest,{gitRoot:t});o&&(r.model=o),await z("session_end",{status:n,...o?{model:o}:{},hook_input:r},he(e),W,e.manifest.collectorUrl)}async function js(e){let t=fn(e.hookInput);if(t.length===0)return;let{gitRoot:n}=e.manifest;await _e(e,n);let o=Y(e.hookInput,e.manifest.manifest,{gitRoot:n}),r=he(e);await Promise.all(t.map(s=>z("tool_invoked",{tool_name:"Skill",skill_name:s,success:null,duration_ms:null,hook_input:o},r,W,e.manifest.collectorUrl)))}async function Fs(e){let{gitRoot:t}=e.manifest;await _e(e,t);let{toolName:n,skillName:o}=hn(e.hookInput),r=kn(e.hookInput),s=pn(e.runnerEvent),a=s===!1?yn(e.hookInput,e.runnerEvent):null,{mcpServer:i,mcpTool:c}=Sn(n),u=_n(e.hookInput);await z("tool_invoked",{tool_name:n,skill_name:o,success:s,duration_ms:r,...a?{failure_reason:a}:{},...i?{mcp_server:i}:{},...c?{mcp_tool:c}:{},...u?{subagent_type:u}:{},hook_input:Y(e.hookInput,e.manifest.manifest,{gitRoot:t})},he(e),W,e.manifest.collectorUrl)}async function On(e){switch(e.internalEvent){case"session_start":await Ls(e);return;case"session_end":await Us(e);return;case"skill_invoked":await js(e);return;case"tool_invoked":await Fs(e);return;default:return}}function Pn(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function Tn(e,t,n,o){let r=t??await Ie(ve),s=_(r,{}),a=await Et();if(!a)return;o&&(a.collectorUrl=o);let i=mn(s,a.manifest.platform,n),c=gn(e,i.runnerEvent);if(!c){l(`WARN: unknown hook event '${i.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:i.sessionId,turnId:i.turnId,runnerEvent:i.runnerEvent,runnerPlatform:i.runnerPlatform,hookSource:i.hookSource,internalEvent:c,manifest:a,platformAgentId:a.platformAgentId};if(Pn(c)){l(`WARN: unsupported internal event '${c}'`);return}await On(u)}function Ds(e,t){if(g("EVALON_HOOK_SYNC")==="1")return!0;let n=pe(e),o=_(t,{}),r=n.event??(d(o,"hook_event_name")||d(o,"event")),s=Be(o,r,void 0,n.runner);return me(r,s)}async function Nn(e=process.argv.slice(2)){if(e[0]===V){try{await ge(te)}catch{}return 0}if(e[0]===Ge){try{let t=pe(e.slice(1));await Tn(t.event,void 0,t.runner,$e(t))}catch(t){let n=t instanceof Error?t.message:String(t);l(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Ie(ve),n=pe(e),o=$e(n);Ds(e,t)?await Tn(n.event,t,n.runner,o):await bn(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);l(`WARN: hook failed open: ${n}`)}finally{mt()}return 0}function ke(){l("Usage: evalon-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),l(" configure [--url <\u2026/{orgToken}/hook>]"),l(" (manifest only \u2014 pair with marketplace plugins)"),l(" install --url <\u2026/{orgToken}/hook>"),l(" [--delivery npx|binary] [--force]"),l(" [--no-claude] [--no-cursor] [--no-codex]"),l(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),l(" (writes collector_url to shared manifest; hook commands use --runner only)"),l(" migrate-to-plugin"),l(" (strip Evalon file hooks; keep collector manifest)"),l(" update (refresh binary pins from a local build; leaves hook configs alone)"),l(" uninstall"),l("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),l(" (--url/--token optional overrides; else collector_url from manifest)")}function Hn(e){return e.includes("--help")||e.includes("-h")}async function Js(e=process.argv.slice(2)){let[t,...n]=e;if(t===V){try{await ge(te)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${b}
19
- `),0):t==="configure"?Hn(n)?(ke(),0):(await Bt(Ct(n)),0):t==="install"?Hn(n)?(ke(),0):(await Dt(At(n)),0):t==="migrate-to-plugin"?(await Gt(),0):t==="update"?(await $t(),0):t==="uninstall"?(await Jt(),0):t==="help"||t==="--help"||t==="-h"?(ke(),0):t===void 0?(ke(),1):Nn(e)}function Ws(e,t,n=$s){if(!t)return!1;try{return e===Gs(Bs(t)).href?!0:n(Ks(e))===n(t)}catch{return!1}}Ws(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);l(t),process.exit(1)});export{Ws as isCliEntrypoint,Js as main};
15
+ npx ${Le} install`)}function Er(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(z)||/(?:^|[\s/"'])ev-ai-agent-hook(?:$|[\s"'])/.test(e)}function vt(e,t){return`${e.replace(/\s+--runner(?:=|\s+)\S+/g,"").trimEnd()} --runner ${t}`}function X(e,t){xt(Tt(e),{recursive:!0}),qs(e,`${JSON.stringify(t,null,2)}
16
+ `,"utf8")}function G(e){if(B(e))try{return JSON.parse(Ys(e,"utf8"))}catch(t){throw t instanceof SyntaxError?new Error(`Invalid JSON in ${e} \u2014 fix or remove the file`,{cause:t}):t}}function hi(e,t){let n=rr(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 Ei(e){return(e.schema_version??2)===2&&e.collector_url===void 0&&(e.mcp_servers?.length??0)===0&&e.platform_agent_id===void 0&&e.capture_hook_input===void 0&&e.repo_ingest_token===void 0}function Sr(e,t){let n=y(e,Ue),r=G(n),o=hi(r,t);return t.collectorUrl!==void 0||B(n)||!Ei(o)?(X(n,o),{manifestPath:n,wrote:!0}):{manifestPath:void 0,wrote:!1}}function At(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 Si(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return y(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function yi(e=process.platform){let t=Si(e),n=[y(t,"managed-settings.json")],r=y(t,"managed-settings.d");try{if(!B(r))return n;let o=zs(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>y(r,s));n.push(...o)}catch{}return n}function Ii(e){if(At(process.env))return!0;let t=j();return[...yi(),y(t,".claude","settings.json"),y(t,".claude","remote-settings.json"),y(e,".claude","settings.json"),y(e,".claude","settings.local.json")].some(r=>{try{let o=G(r);return o?At(o.env):!1}catch{return!1}})}function Ri(e){try{let t=G(y(e,".claude","settings.json"));return t?At(t.env):!1}catch{return!1}}function yr(e){return Array.isArray(e)?e:[]}function Ge(e){let t=[],n=r=>!!r&&typeof r=="object"&&Er(r.command);for(let r of yr(e)){if(!r||typeof r!="object"){t.push(r);continue}let o=Array.isArray(r.hooks)?r.hooks:[],s=o.filter(a=>!n(a));if(!(s.length===0&&o.some(n))){if(s.length!==o.length){t.push({...r,hooks:s});continue}t.push(r)}}return t}function Ir(e,t){return[...Ge(e),...t]}function bt(e){return Array.isArray(e)?e.filter(t=>!t||typeof t!="object"?!0:!Er(t.command)):[]}function ki(e,t){return[...bt(e),{command:t}]}function Ci(e){let t=()=>({hooks:[{type:"command",command:e}]});return{SessionStart:[t()],UserPromptExpansion:[t()],PreToolUse:[t()],PostToolUse:[t()],PostToolUseFailure:[t()],PermissionDenied:[t()],Stop:[t()],StopFailure:[t()],SessionEnd:[t()],SubagentStart:[t()],SubagentStop:[t()]}}function Oi(e){let t={type:"command",command:e,statusMessage:In},n=()=>({hooks:[t]});return{SessionStart:[n()],UserPromptSubmit:[n()],PreToolUse:[n()],PostToolUse:[n()],Stop:[n()]}}var Ai=["sessionStart","beforeSubmitPrompt","preToolUse","postToolUse","postToolUseFailure","beforeShellExecution","afterShellExecution","beforeReadFile","afterFileEdit","beforeMCPExecution","subagentStart","subagentStop","stop"],xi=[];function Ti(e,t=xi){let n={...e};for(let r of t){if(!(r in n))continue;let o=bt(n[r]);o.length===0?delete n[r]:n[r]=o}return n}function vi(e,t,n={}){let r=y(e,".claude/settings.json"),o=vt(t,"claude"),s=G(r)??{};if(Ii(e)&&!n.force){if(s.hooks&&typeof s.hooks=="object"){let u={...s.hooks};for(let f of Object.keys(u))u[f]=Ge(u[f]),yr(u[f]).length===0&&delete u[f];Object.keys(u).length===0?delete s.hooks:s.hooks=u,X(r,s)}return!1}let i=s.hooks&&typeof s.hooks=="object"?s.hooks:{},c=Ci(o),l={...i};for(let[u,f]of Object.entries(c))l[u]=Ir(i[u],f);return s.hooks=l,X(r,s),!0}function bi(e,t){let n=y(e,".cursor/hooks.json"),r=vt(t,"cursor"),o=G(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},a=Ti({...s});for(let i of Ai)a[i]=ki(a[i],r);X(n,{...o,version:typeof o.version=="number"?o.version:1,hooks:a})}function wi(e,t){let n=y(e,".codex/hooks.json"),r=vt(t,"codex"),o=G(n)??{},s=o.hooks&&typeof o.hooks=="object"?o.hooks:{},a=Oi(r),i={...s};for(let[c,l]of Object.entries(a))i[c]=Ir(s[c],l);X(n,{...o,hooks:i})}function Pi(e){let t=y(e,".claude/settings.json"),n=G(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1;for(let s of Object.keys(r)){let a=r[s],i=Ge(a);JSON.stringify(a)!==JSON.stringify(i)&&(o=!0),i.length===0?delete r[s]:r[s]=i}o&&(Object.keys(r).length===0?delete n.hooks:n.hooks=r,X(t,n),d(`Removed ev-ai hooks from ${t}`))}function Ni(e){let t=y(e,".cursor/hooks.json"),n=G(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let a of Object.keys(r)){let i=r[a],c=bt(i);JSON.stringify(i)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[a]:(r[a]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(i=>i!=="hooks"&&i!=="version").length===0){Be(t,{force:!0}),d(`Removed ${t}`);return}X(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function Ui(e){let t=y(e,".codex/hooks.json"),n=G(t);if(!n?.hooks||typeof n.hooks!="object")return;let r={...n.hooks},o=!1,s=0;for(let a of Object.keys(r)){let i=r[a],c=Ge(i);JSON.stringify(i)!==JSON.stringify(c)&&(o=!0),c.length===0?delete r[a]:(r[a]=c,s+=c.length)}if(o){if(s===0&&Object.keys(r).length===0&&Object.keys(n).filter(i=>i!=="hooks").length===0){Be(t,{force:!0}),d(`Removed ${t}`);return}X(t,{...n,hooks:r}),d(`Removed ev-ai hooks from ${t}`)}}function wt(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)&&or(e,t)}async function Rr(e={}){let t=oi(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??fr();wt(process.platform,process.arch,{requireBinaryArch:s==="binary"});let a=e.cwd??process.cwd(),i=await $(a),{command:c,hookPath:l,strategy:u}=_i(i,j(),s),{installationId:f,storePath:g}=await Fe(i,{overrideId:e.installationId}),{manifestPath:m,wrote:_}=Sr(i,e),E=[];return n?d("Skipped Claude hook \u2014 --no-claude"):vi(i,c,{force:e.force})?(E.push("Claude"),e.force&&Ri(i)&&d("Forced Claude hook despite project native OTEL \u2014 expect duplicate session/tool events")):d("Skipped Claude hook \u2014 native OTEL telemetry already enabled (avoids duplicate events); pass --force to wire anyway"),r?d("Skipped Cursor hook \u2014 --no-cursor"):(bi(i,c),E.push("Cursor")),o?d("Skipped Codex hook \u2014 --no-codex"):(wi(i,c),E.push("Codex")),d(`Installed hook (${u}) at ${l}`),d(`Installation identity ${f} at ${g}`),_&&m?d(`Shared manifest written to ${m}`):d("Using package default collector config (no shared manifest file needed)"),d(E.length>0?`Wired ${E.join(", ")} hooks in ${i} (commands include --runner)`:`No runner hooks wired in ${i} (Claude skipped by OTEL; Cursor/Codex excluded via flags)`),u==="npx"?d("Hook commands use npx and may be committed; teammates need Node on PATH only (no install step, no env vars when collector_url is in the shared manifest)."):u==="project_binary"?d("Hook commands are git-root-relative and may be committed; each collaborator runs install once to populate .ev-ai/agent-hook/ (gitignored)."):u==="dev_mjs"&&d("Hook commands use node + monorepo packages/agent-hook/dist/hook.mjs (local delivery; rebuild with yarn workspace @ev-ai/agent-hook build)."),_&&m&&e.collectorUrl&&d("Shared manifest includes collector_url \u2014 commit it with hook configs so teammates post without env vars."),{gitRoot:i,hookPath:l,manifestPath:m,installationStorePath:g,strategy:u}}async function kr(e=process.cwd()){wt(process.platform,process.arch,{requireBinaryArch:!0});let t=await $(e),{projectPath:n,globalPath:r}=mi(t);d(`Refreshed ${r}`),d(`Refreshed ${n}`),d("Hook configs and shared manifest left unchanged")}async function Cr(e={}){let t=ri(e);e.collectorUrl=t,wt(process.platform,process.arch,{requireBinaryArch:!1});let n=e.cwd??process.cwd(),r=await $(n),{manifestPath:o,wrote:s}=Sr(r,e);if(t!==void 0&&(!o||!s))throw new Error("configure failed to write shared collector manifest");return s&&o?d(`Wrote ${o}`):t===void 0&&d("No --url given and no shared manifest yet \u2014 pass --url <\u2026/{orgToken}/hook> to write collector destination."),d("Manifest only \u2014 enable ev-ai marketplace plugins. Do not also run file-wiring install for the same events."),{gitRoot:r,manifestPath:o}}function Or(e){for(let t of[()=>Pi(e),()=>Ni(e),()=>Ui(e)])try{t()}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: strip skipped a hook file: ${r}`)}}async function Ar(e=process.cwd()){let t=await $(e);return Or(t),d("Stripped ev-ai file-wired hooks; shared collector manifest left in place."),d("Next: enable ev-ai marketplace plugins, then restart runners."),{gitRoot:t}}async function xr(e=process.cwd()){let t=await $(e);Or(t);for(let n of $e){let r=y(t,n);if(B(r))try{Be(r,{force:!0}),d(`Removed ${r}`)}catch(o){let s=o instanceof Error?o.message:String(o);d(`WARN: uninstall could not remove ${r}: ${s}`)}}}import{createHash as ia}from"node:crypto";import{existsSync as aa,mkdirSync as ca,readdirSync as la,readFileSync as Br,unlinkSync as jr,writeFileSync as ua}from"node:fs";import{homedir as Gr}from"node:os";import{join as Ht}from"node:path";var Tr=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,vr=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,Li=/(?:^|\s)\/([a-z][a-z0-9-]{1,63})\b/gi,Mi=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"]),Hi=new Set(["read","read_file","view"]),Di=new Set(["bash","shell","zsh"]);function Fi(e){let t=e.replace(/\\/g,"/");return Tr.exec(t)?.[1]??null}function $i(e){let t=e.replace(/\\/g,"/"),r=vr.exec(t)?.[1];return r?r.toLowerCase():null}function Pt(e){return Fi(e)??$i(e)}function Bi(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 Ke(e){if(typeof e=="string")try{let t=JSON.parse(e);return Ke(t)}catch{return null}return!e||typeof e!="object"?null:Bi(e)}function ji(e){if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function Gi(e){let t=e.replace(/\\/g,"/"),n=Tr.exec(t);if(n?.[1])return n[1];let o=vr.exec(t)?.[1];return o?o.toLowerCase():null}function Ki(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function br(e){let t=Ki(e).toLowerCase();if(Hi.has(t)){let n=Ke(e.tool_input)??ee(e.file_path),r=n?Pt(n):null;if(r)return r}if(Di.has(t)){let n=ji(e.tool_input)??ee(e.command);return n?Gi(n):null}return null}function Ji(e){let t=new Set,n=[];for(let r of e.matchAll(Li)){let o=r[1]?.toLowerCase();!o||t.has(o)||Mi.has(o)||(t.add(o),n.push(o))}return n}function Vi(e){return ee(e.prompt)}function wr(e){let t=p(e,"command_name");if(t){let r=p(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Vi(e);return n?Ji(n):[]}function Nt(e){return e!==void 0&&Rn.includes(e)}function Je(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Ve(e){let t,n,r,o,s;for(let a=0;a<e.length;a++){let i=e[a];if(i!==void 0){if(i==="--runner"){let c=Je(e,a);t=c.value,a=c.next;continue}if(i.startsWith("--runner=")){t=i.slice(9);continue}if(i==="--url"){let c=Je(e,a);c.value&&(r=c.value),a=c.next;continue}if(i.startsWith("--url=")){r=i.slice(6);continue}if(i==="--token"){let c=Je(e,a);c.value&&(o=c.value),a=c.next;continue}if(i.startsWith("--token=")){o=i.slice(8);continue}if(i==="--base-url"){let c=Je(e,a);c.value&&(s=c.value),a=c.next;continue}if(i.startsWith("--base-url=")){s=i.slice(11);continue}!i.startsWith("-")&&n===void 0&&(n=i)}}return{runner:Nt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Ut(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=Ne(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=pe(n);if(r){d(`WARN: ignoring --url/--token collector override: ${r}`);return}return me(n)}function Pr(e,t){if(p(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function Wi(){return!!(k("CURSOR_VERSION")??k("CURSOR_PROJECT_DIR"))}function Lt(e,t,n){return e!=="claude"&&e!=="codex"?!1:Pr(t,n)?!0:Wi()}function Re(e,t,n,r){if(Pr(e,t))return"cursor";if(Nt(r))return r;let o=p(e,"conversation_id"),s=p(e,"turn_id"),a=p(e,"session_id"),i=t.toLowerCase(),c="unknown";return o||t===i&&t!==""?c="cursor":s?c="codex":(a||i==="sessionstart"||i==="sessionend"||i==="stop"||i==="stopfailure"||i==="pretooluse"||i==="posttooluse"||i==="posttoolusefailure"||i==="permissiondenied"||i==="subagentstart"||i==="subagentstop"||i==="userpromptexpansion")&&(c="claude"),Nt(n)&&(c=n),c}function We(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function zi(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 Nr(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Ur(e,t,n){let r=p(e,"session_id")||p(e,"conversation_id"),o=p(e,"prompt.id")||p(e,"prompt_id")||p(e,"generation_id")||p(e,"turn_id"),s=p(e,"hook_event_name")||p(e,"event"),a=p(e,"source"),i=Re(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:a,runnerPlatform:i}}var Yi=["session_start","session_end","tool_invoked","skill_invoked"];function Xi(e){return Yi.includes(e)}function Lr(e,t){return e&&Xi(e)?e:zi(t.toLowerCase())}var qi={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Zi(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Mr(e,t=""){let n=p(e,"tool_name")||p(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Zi(n)&&(n=`MCP:${n}`):n=qi[r]??null;let o=e.tool_input,a=(o&&typeof o=="object"?ee(o.skill)||ee(o.skill_name):"")||p(e,"skill_name")||null,i=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;return a??=br(i),{toolName:n,skillName:a}}var Qi=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Hr(e){for(let t of["subagent_type","agent_type"]){let n=p(e,t);if(n&&Qi.test(n))return n}return null}function Dr(e){let t=te(e,"duration_ms");if(typeof t=="number")return t;let n=te(e,"duration");return typeof n=="number"?n:null}var ea="error",ta="interrupted",na="permission_denied",ra=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Mt(e){return ra.test(e)?e:null}function oa(e){for(let t of["failure_type","error_type"]){let n=Mt(p(e,t));if(n)return n}return null}function Fr(e,t){return te(e,"is_interrupt")===!0?ta:t.toLowerCase()==="permissiondenied"?na:oa(e)??ea}function sa(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 $r(e,t=[]){if(!e)return{mcpServer:null,mcpTool:null};let n=/^mcp__(.+?)__(.+)$/i.exec(e);if(n?.[1]&&n[2])return{mcpServer:n[1],mcpTool:n[2]};if(/^MCP:/i.test(e)){let r=e.slice(4);if(!r)return{mcpServer:null,mcpTool:null};let o=r.indexOf(":");return o>0?{mcpServer:r.slice(0,o),mcpTool:r.slice(o+1)||null}:{mcpServer:sa(r,t),mcpTool:r}}return{mcpServer:null,mcpTool:null}}var Kr=3e4,da="claims",fa=!0,pa=100,ma=new Set(["sessionstart","sessionend","stopfailure"]),ga=["tool_name","tool","command","file_path","url"];function _a(e=Gr()){return Ht(Ie(e),da)}function Jr(e){let t=e.split(`
17
+ `,1)[0]??"";return Number(t.trim())}function Vr(e){return ia("sha256").update(e).digest("hex").slice(0,32)}function ha(e){let t=[];for(let n of ga){let r=p(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":Vr(t.join("\0"))}function Ea(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()??"",a=e.callFingerprint?.trim()??"",i=!!(o||r||s),c=ma.has(n);if(!i&&!c)return;let l=e.runnerPlatform.trim()||"unknown";return Vr(`${l}|${t}|${n}|${r}|${o}|${a}|${s}`)}function Sa(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function ya(e,t){return Ht(e,t)}function Ia(e,t=Date.now()){let n;try{n=la(e)}catch{return}let r=0;for(let o of n){if(r>=pa)break;r+=1;let s=Ht(e,o),a=Number.NaN;try{a=Jr(Br(s,"utf8"))}catch{continue}let i=t-a;if(!(!Number.isFinite(i)||i<0||i<Kr))try{jr(s)}catch{}}}function Ra(e,t,n=Date.now()){let r=ya(t,e);try{if(aa(r)){let o=Number.NaN;try{o=Jr(Br(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<Kr)return!1;try{jr(r)}catch{}}}catch{}try{ca(t,{recursive:!0}),ua(r,`${n}
18
+ `,{encoding:"utf8",flag:"wx"})}catch(o){if(Sa(o))return!1;let s=o instanceof Error?o.message:String(o);return d(`WARN: event claim failed open: ${s}`),!0}return Ia(t,n),!0}function ka(e,t,n){let r=p(e,"session_id")||p(e,"conversation_id"),o=p(e,"prompt.id")||p(e,"prompt_id")||p(e,"generation_id")||p(e,"turn_id"),s=p(e,"tool_use_id"),a=p(e,"subagent_id")||p(e,"agent_id"),i=Re(e,t,void 0,n),c=ha(e);return{runnerPlatform:i,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:a,callFingerprint:c}}function Wr(e,t,n,r=Gr(),o=Date.now()){if(!fa)return!0;let s=Ea(ka(e,t,n));if(!s)return!0;let a=Ra(s,_a(r),o);return!a&&k("EV_AI_HOOK_DEBUG")&&d(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),a}var Dt={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function ke(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Ca(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return ke(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return ke(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?ke(o[1]):ke(t)}async function Ce(e=process.cwd()){let t=await U("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([U("git",["remote","get-url","origin"],2e3,{cwd:e}),U("git",["branch","--show-current"],2e3,{cwd:e}),U("git",["rev-parse","HEAD"],2e3,{cwd:e}),U("git",["status","--porcelain"],2e3,{cwd:e})]),a=n.ok?n.stdout:null;return{remote:a===null?null:a.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 zr(e,t,n,r=process.cwd(),o,s,a){if(t)return t;let i=Dt[n];if(!i)return"";let c=Kn(n,e.scope_path,a);if(s){let _=Zn(s,c);if(_)return _}let l=o??await Ce(r),u=l?.remote?Ca(l.remote):"";if(u||(u=ke(process.env.GITHUB_REPOSITORY??"")),!u)return"";let f=e.scope_path??"",g=f?`${f}/`:"",m=`${u}:${g}${i}`;return s&&Qn(s,c,m),m}var q=Vo(qr(),1);import{existsSync as Ua,readFileSync as La}from"node:fs";import{homedir as Zr}from"node:os";import{join as Ma}from"node:path";var Ha="cloud-cache.json",Da=1440*60*1e3,Fa=900*1e3;function $a(e=Zr()){return Ma(Ie(e),Ha)}function Ba(e){if(!Ua(e))return;let t=w(La(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 ja(e,t){try{Y(e,`${JSON.stringify(t)}
19
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: cloud cache write failed open: ${r}`)}}function Ga(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?Fa:Da;return n-e.probed_at<r}async function Ka(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 a=o?.ok?(await o.text()).trim():"",i=s?.ok?(await s.text()).trim():"";if(!(!a&&!i))return{provider:"aws",region:a,instance_id:i}}async function Ja(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 Va(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 Wa(e){let t=await Promise.allSettled([Ka(e),Ja(e),Va(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function Ft(e,t){if(e==="interactive")return null;let n=t?.home??Zr(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=$a(n),a=Ba(s);if(Ga(a,e,o))return a.result;let i=await Wa(r);return ja(s,{context:e,probed_at:o,result:i}),i}import{existsSync as za}from"node:fs";import{homedir as Ya}from"node:os";import{join as $t}from"node:path";function Bt(e,t,n){if(!za(e))return;let r=ae(e,{});for(let o of Object.keys(r.mcpServers??{}))n.set(o,{name:o,source:t})}async function jt(e,t=process.cwd(),n="claude",r=Ya()){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{name:s.name,source:"manifest"});return n==="claude"&&Bt($t(r,".claude.json"),"claude_json_user",o),Bt($t(t,".mcp.json"),"mcp_json",o),Bt($t(t,".cursor/mcp.json"),"cursor_mcp",o),[...o.values()]}var Xa=["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"],qa=["CURSOR_PROJECT_DIR"],Za=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Qa(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Za.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Gt(e=process.env){let t=Xa.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Qa(e[r]??"")}:{name:r,present:!1}),n=qa.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{createHash as ec}from"node:crypto";function O(e){return ec("sha256").update(e).digest("hex").slice(0,16)}function J(e,t){return`${e}\0${t}`}function Qr(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function Kt(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(`
20
+ `);return O(n)}function tc(e,t,n="git_config",r=null){return O(`${e??""}|${t??""}|${r??""}|${n}`)}function nc(e){let t=null,n=null;for(let r of e.split(`
21
+ `)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let a=o.slice(0,s).toLowerCase(),i=o.slice(s+1).trim();i&&(a==="user.name"?t=i:a==="user.email"&&(n=i))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function rc(e,t=C){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return nc(n)}function oc(e=process.env){let t=h(e.GIT_AUTHOR_NAME),n=h(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=h(e.GIT_COMMITTER_NAME),o=h(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=h(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}async function sc(e,t=C){let n=await t("git",["log","-1","--format=%an%x00%ae"],2e3,{cwd:e});if(!n)return null;let r=n.indexOf("\0"),o=(r>=0?n.slice(0,r):n).trim(),s=(r>=0?n.slice(r+1):"").trim();return!o&&!s?null:{git_user_name:o||null,git_user_email:s||null,platform_login:null,identity_source:"git_log"}}function V(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 ic(e=process.env){let t=V(h(e.EV_AI_HOOK_OPERATOR_NAME),h(e.EV_AI_HOOK_OPERATOR_EMAIL),"configured",h(e.EV_AI_HOOK_OPERATOR_LOGIN));if(t)return t;let n=h(e.GITHUB_ACTOR)??h(e.GITHUB_TRIGGERING_ACTOR)??h(e.GITHUB_USER),r=V(n,null,"github",n);if(r)return r;let o=h(e.GITLAB_USER_LOGIN),s=V(h(e.GITLAB_USER_NAME)??o,h(e.GITLAB_USER_EMAIL),"gitlab",o);if(s)return s;let a=V(h(e.BUILD_REQUESTEDFOR),h(e.BUILD_REQUESTEDFOREMAIL),"azure_devops",h(e.BUILD_REQUESTEDFORID));if(a)return a;let i=h(e.BUILDKITE_BUILD_CREATOR_EMAIL),c=V(h(e.BUILDKITE_BUILD_CREATOR),i,"buildkite",i);if(c)return c;let l=V(h(e.BUILD_USER)??h(e.CHANGE_AUTHOR),h(e.BUILD_USER_EMAIL)??h(e.CHANGE_AUTHOR_EMAIL),"jenkins",h(e.BUILD_USER_ID));if(l)return l;let u=h(e.CIRCLE_USERNAME),f=V(u,null,"circleci",u);if(f)return f;let g=h(e.CODEBUILD_INITIATOR),m=V(g,null,"codebuild",g);if(m)return m;let _=V(h(e.DRONE_COMMIT_AUTHOR)??h(e.DRONE_COMMIT_AUTHOR_NAME),h(e.DRONE_COMMIT_AUTHOR_EMAIL),"drone",h(e.DRONE_COMMIT_AUTHOR));if(_)return _;if(eo(e.CLAUDE_CODE_REMOTE)||eo(e.CURSOR_AGENT)){let E=h(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:E&&!Q(null,E)?E:null,platform_login:null,identity_source:"cloud"}}return null}function Jt(e){return!!((e.git_user_name??e.git_user_email)&&!Q(e.git_user_name,e.git_user_email))}function h(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function eo(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}async function ac(e,t=C,n=process.env){let r=await rc(e,t);if(Jt(r))return{...r,identity_source:"git_config"};let o=oc(n);if(o&&Jt(o))return o;let s=ic(n);if(s&&(s.git_user_name||s.git_user_email||s.platform_login))return s;let a=await sc(e,t);return a&&Jt(a)?a:s||(r.git_user_name||r.git_user_email?{...r,identity_source:"git_config"}:o||a||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Ye(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??C,s=e.env??process.env,a=await ac(t,o,s),i=tc(a.git_user_name,a.git_user_email,a.identity_source,a.platform_login),l=(n?Rt(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==i||!l))return{commit:()=>{}};let m=n;return{operator:a,commit:()=>{m&&Yn(m,i,He())}}}function Vt(e){return e?!Rt(e)?.operator_identity_hash:!0}function to(e){return!0}import{existsSync as bc,readFileSync as wc}from"node:fs";import{homedir as Io}from"node:os";import{join as L}from"node:path";import{basename as Tc,join as le,resolve as mo}from"node:path";import{existsSync as no,readdirSync as cc}from"node:fs";import{basename as lc,dirname as uc,relative as dc}from"node:path";var Oe=class{constructor(t,n=""){this.home=t;this.pathPrefix=n}components=[];truncated=!1;pluginExpandRemaining;homeRel(t){let n=dc(this.home,t).replace(/\\/g,"/"),r=!n||n.startsWith("..")?`external/${O(uc(t))}/${lc(t)}`:n;return this.pathPrefix?`${this.pathPrefix}${r}`:r}get atGlobalCap(){return this.truncated||this.components.length>=H}get pluginBudgetSpent(){return this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0}readEntries(t){if(!no(t))return[];try{return cc(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(no(t))return ae(t,n)}push(t){return this.components.length>=H?(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 Wt,readFileSync as fc,statSync as pc}from"node:fs";import{basename as oo,join as Ae,relative as so}from"node:path";var zt=2e4,mc=4;function gc(e){return e.length<=zt?e:`${e.slice(0,zt-1)}\u2026`}function _c(e){try{let t=fc(e),n=t.toString("utf8");return{hash:O(t),length:t.length,text:gc(n)}}catch{return null}}var ro={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function hc(e){return e in ro?ro[e]:"UNSPECIFIED"}function Xe(e,t){let n=_c(t.absolutePath);if(!n)return!1;let r=t.name??oo(t.absolutePath).replace(/\.(md|mdc|toml)$/i,""),o={kind:t.kind,name:r,path:e.homeRel(t.absolutePath),text:n.text,content_hash:n.hash,content_length:n.length,origin:t.origin,enabled:t.enabled},s=hc(t.kind);return s&&(o.trigger=s),e.push(o)}function Ec(e,t,n){let r=so(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?oo(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function oe(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:a,extensions:i}=t;Yt(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:a,extensions:i})}function Yt(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:a,enabled:i,nested:c,extensions:l}=t;if(!(o>mc))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 m=Ae(r,u.name,c);if(Wt(m)){let _=so(n,Ae(r,u.name)).replace(/\\/g,"/");Xe(e,{absolutePath:m,kind:s,origin:a,enabled:i,name:_||u.name});continue}Yt(e,{walkRoot:n,currentDir:Ae(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(u.isDirectory()){Yt(e,{walkRoot:n,currentDir:Ae(r,u.name),depth:o+1,kind:s,origin:a,enabled:i,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let f=u.name.toLowerCase();if(!l.some(m=>f.endsWith(m)))continue;let g=Ae(r,u.name);Xe(e,{absolutePath:g,kind:s,origin:a,enabled:i,name:Ec(n,g,!0)})}}function io(e){for(let t of e)if(Wt(t))try{if(pc(t).size>0)return t}catch{continue}return e.find(t=>Wt(t))}function Sc(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 yc(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 Ic(e,t,n,r){let o=e.homeRel(t);for(let[s,a]of Object.entries(n))if(!(!Array.isArray(a)||e.truncated))for(let i of a){if(!i||typeof i!="object"||e.truncated)continue;let c=i;for(let l of yc(c)){if(e.truncated)return;let u=l.command??l.bash??l.prompt??l.powershell??c.powershell??"",f=Sc({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}),g=typeof c.matcher=="string"?c.matcher:"",m=O(u),_=g?`${s}:${g}:${f}:${m}`:`${s}:${f}:${m}`,E=`${s}|${g}|${f}|${u}`;e.push({kind:"HOOK",name:_,path:o,content_hash:O(E),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...g?{matcher:g}:{},action_kind:f,action_hash:m}})}}}function xe(e,t,n){let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||Ic(e,t,r.hooks,n)}var ao={claude:{skillRoots:[".claude/skills"],dirs:[{dir:".claude/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".claude/commands",kind:"COMMAND",extensions:[".md"]}],memory:[".claude/CLAUDE.md"],hooks:[".claude/settings.json"],mcpJson:[".claude.json"],plugins:"claude"},cursor:{skillRoots:[".cursor/skills",".cursor/skills-cursor"],dirs:[{dir:".cursor/agents",kind:"SUBAGENT",extensions:[".md"]},{dir:".cursor/commands",kind:"COMMAND",extensions:[".md"]},{dir:".cursor/rules",kind:"RULE",extensions:[".mdc",".md"]}],memory:[".cursor/AGENTS.md"],hooks:[".cursor/hooks.json"],mcpJson:[".cursor/mcp.json"],plugins:"cursor"},codex:{skillRoots:[".agents/skills",".codex/skills"],dirs:[{dir:".codex/agents",kind:"SUBAGENT",extensions:[".toml",".md"]},{dir:".codex/prompts",kind:"COMMAND",extensions:[".md"]}],memory:[".codex/AGENTS.override.md",".codex/AGENTS.md"],hooks:[".codex/hooks.json"],mcpToml:[".codex/config.toml"]}};import{existsSync as Rc,readFileSync as kc}from"node:fs";function Cc(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 co(e,t,n){let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.homeRel(t);for(let[a,i]of Object.entries(o)){if(e.truncated)return;let c=Cc(i);e.push({kind:"MCP_SERVER",name:a,path:s,content_hash:O(`${a}|${c}`),origin:n,enabled:!0,attributes:{transport:c}})}}function lo(e,t,n){if(!Rc(t))return;let r;try{r=kc(t,"utf8")}catch{return}let o=e.homeRel(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,a;for(;(a=s.exec(r))!==null;){if(e.truncated)return;let i=a[1]??a[2]??a[3];if(!i)continue;let c=r.slice(a.index+a[0].length),l=c.search(/^\[/m),u=l===-1?c:c.slice(0,l),f="unknown";/^\s*url\s*=/m.test(u)?f="http":/^\s*command\s*=/m.test(u)&&(f="stdio"),e.push({kind:"MCP_SERVER",name:i,path:o,content_hash:O(`${i}|${f}`),origin:n,enabled:!0,attributes:{transport:f}})}}import{existsSync as Oc,readdirSync as Ac}from"node:fs";import{join as x}from"node:path";var uo=50;function Xt(e,t,n,r){if(!Oc(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(uo,()=>{oe(e,{dir:x(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),oe(e,{dir:x(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),oe(e,{dir:x(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});xe(e,x(t,"hooks","hooks.json"),n),xe(e,x(t,"hooks.json"),n);let a=e.components.length-o,i=s>=uo;return{componentCount:a,expandTruncated:i}}function qt(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 fo(e){let t=x(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(x(e.home,".claude/settings.json"),{})?.enabledPlugins??{},a=e.homeRel(t);for(let[i,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},f=s[i]===!0,g=i.includes("@")?i.split("@").slice(1).join("@"):"",m=typeof u.version=="string"?u.version:"",_=typeof u.scope=="string"?u.scope:"user",E=`plugin:${i}`,T=0,A=!1;for(let P of l)if(typeof P.installPath=="string"&&P.installPath.length>0){let Z=Xt(e,P.installPath,E,f);T+=Z.componentCount,A=A||Z.expandTruncated}qt(e,{pluginKey:i,rowPath:a,enabled:f,scope:_,version:m||void 0,marketplace:g||void 0,componentCount:T,expandTruncated:A,contentHash:O(`${i}|${m}|${_}|${f}|${T}`)})}}function xc(e){let t=e,n="";try{let r=Ac(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=x(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=x(e,s),n=s)}}catch{}return{installPath:t,version:n}}function po(e){let t=[{base:x(e.home,".cursor/plugins/local"),scope:"local"},{base:x(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,i=x(n,o.name),c=`plugin:${a}`,{componentCount:l,expandTruncated:u}=Xt(e,i,c,!0);qt(e,{pluginKey:a,rowPath:e.homeRel(i),enabled:!0,scope:"local",componentCount:l,expandTruncated:u,contentHash:O(`${a}|local|${l}`)});continue}let s=o.name;for(let a of e.readEntries(x(n,s))){if(!a.isDirectory()||e.truncated)continue;let i=x(n,s,a.name),{installPath:c,version:l}=xc(i),u=`${a.name}@${s}`,f=`plugin:${u}`,{componentCount:g,expandTruncated:m}=Xt(e,c,f,!0);qt(e,{pluginKey:u,rowPath:e.homeRel(c),enabled:!0,scope:"cache",version:l||void 0,marketplace:s,componentCount:g,expandTruncated:m,contentHash:O(`${u}|${l}|${g}`)})}}}function go(e,t,n,r){let o=ao[t];if(!o)return;let s=e.home;for(let i of o.skillRoots)oe(e,{dir:le(s,i),kind:"SKILL",origin:n,enabled:!0,nested:"SKILL.md"});for(let i of o.dirs)oe(e,{dir:le(s,i.dir),kind:i.kind,origin:n,enabled:!0,extensions:i.extensions});let a=io(o.memory.map(i=>le(s,i)));a&&Xe(e,{absolutePath:a,kind:"MEMORY",origin:n,enabled:!0,name:Tc(a)});for(let i of o.hooks)xe(e,le(s,i),n);for(let i of o.mcpJson??[])co(e,le(s,i),n);for(let i of o.mcpToml??[])lo(e,le(s,i),n);r&&(o.plugins==="claude"?fo(e):o.plugins==="cursor"&&po(e))}function Zt(e,t,n){let r=new Oe(t);if(go(r,e,"user",!0),n===void 0||mo(n)===mo(t))return{components:r.components,truncated:r.truncated};let s=new Oe(n,"cwd/");go(s,e,"cwd",!1);let a=[...r.components,...s.components],i=r.truncated||s.truncated||a.length>H;return{components:a.slice(0,H),truncated:i}}function Qt(e,t,n={}){let r=n.truncated===!0,o=Kt(e),s=new Set(e.map(u=>J(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let i=[],c=t;for(let u of e){let f=J(u.path,u.name);c[f]!==u.content_hash&&i.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let f=Qr(u);f&&l.push(f)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:i,removed:l,unchanged:i.length===0&&l.length===0}}var ho=3e5,vc=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function en(e,t,n){let r=new Set(t.map(s=>J(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(J(s.path,s.name))||o.push(s));return o}function tn(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 _o(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Eo(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function nn(e,t=ho){let n=[],r=[];for(let u of e)vc.has(u.kind)?n.push(u):r.push(u);r.sort((u,f)=>(u.text?.length??0)-(f.text?.length??0));let o=[...n,...r],s=[],a=2,i=0,c=0,l=[];for(let u of o){let f=s.length>0?1:0,g=_o(u)+f;if(a+g<=t){s.push(u),a+=g,u.text!==void 0&&l.push(u.content_hash);continue}if(u.text!==void 0){let m=Eo(u),_=_o(m)+f;if(a+_<=t){s.push(m),a+=_,i+=1;continue}}c+=1}return{components:s,textDeferredCount:i,droppedCount:c,textHashesSent:l}}function rn(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Eo(n))}var Pc={claude:{skills:".claude/skills",subagents:".claude/agents",commands:".claude/commands",memory:".claude/CLAUDE.md",settings:".claude/settings.json"},cursor:{skills:[".cursor/skills",".cursor/skills-cursor"],subagents:".cursor/agents",commands:".cursor/commands",rules:".cursor/rules",mcp:".cursor/mcp.json"},codex:{skills:[".agents/skills",".codex/skills"],subagents:".codex/agents",commands:".codex/prompts",memory:".codex/AGENTS.md",settings:".codex/config.toml"}},Nc=200,So=200,Uc=["allow","deny","ask"],Lc=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,on="<path>",Mc=new RegExp(`${on}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Hc(e){let t=e.replace(Lc,on).replace(Mc,on);return t.length>So?`${t.slice(0,So)}...`:t}function yo(e){let t=ae(e,{}),n=[];for(let r of Uc)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Hc(o),mode:r});return{model:t.model??"",permissionKeys:n}}var Dc=10,Fc=840*60*1e3,$c="self-config-cache.json";function sn(){return k("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Bc(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=Fc}var jc={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Gc(e,t=C){let n=jc[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let i=((await t(s,["--version"],2e3)).split(`
22
+ `)[0]??"").trim();return i||r(o+1)};return r(0)}function Kc(e=Io()){return L(e,".ev-ai","agent-hook",$c)}function Jc(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
23
+ `);return O(n)}function qe(e,t,n=!1){let r=Jc(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 Vc(e){return bc(e)?w(wc(e,"utf8"),{}):{}}function Wc(e,t){try{Y(e,`${JSON.stringify(t)}
24
+ `)}catch(n){let r=n instanceof Error?n.message:String(n);d(`WARN: self-config cache write failed open: ${r}`)}}function zc(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let a=t[s];a.entries!==void 0&&(o[s]=a.hash)}return r&&(o.user_spec_collected_at_ms=r.collectedAtMs,r.included&&(o.user_spec=r.hash,o.user_spec_components=r.componentHashes),o.user_spec_text_hashes=r.textHashes),o}async function Ro(e,t=process.cwd(),n=Io(),r={}){let o=e==="claude",s=r.gitRoot??t,a=await Gc(e),i="",c=[];if(o){let N=yo(L(n,".claude/settings.json")),D=yo(L(t,".claude/settings.local.json"));i=D.model||N.model,c=[...N.permissionKeys,...D.permissionKeys].slice(0,Nc)}let l=Pc[e]??{},u={present:!1,size:0},f=N=>{let D=Array.isArray(N)?N:N?[N]:[],R=[],W=!1;for(let ot of D){let b=_e(L(n,ot));if(R=R.concat(b.entries),W=W||b.truncated,R.length>=H){R=R.slice(0,H),W=!0;break}}return{entries:R,truncated:W}},g=Kc(n),m=Vc(g),_=m[e]??{},E=(_.send_count??0)+1,T=E>0&&E%Dc===0,A=N=>T?void 0:_[N],P=f(l.skills),Z=l.subagents?_e(L(n,l.subagents)):{entries:[],truncated:!1},rt=l.commands?_e(L(n,l.commands)):{entries:[],truncated:!1},cn=l.rules?_e(L(n,l.rules)):{entries:[],truncated:!1},fe={skills:qe(P.entries,A("skills"),P.truncated),subagents:qe(Z.entries,A("subagents"),Z.truncated),commands:qe(rt.entries,A("commands"),rt.truncated),rules:qe(cn.entries,A("rules"),cn.truncated)},v={runner_platform:e,config_scope:"user",cli_version:a,claude_version:o?a:null,model:o&&i||null,permission_keys:c,user_scope:{skills:fe.skills,subagents:fe.subagents,commands:fe.commands,rules:fe.rules,memory:l.memory?he(L(n,l.memory)):u,settings:l.settings?he(L(n,l.settings)):u,mcp:l.mcp?he(L(n,l.mcp)):u},local_settings:o?he(L(t,".claude/settings.local.json")):u},ln=null,un=()=>{},dn=r.nowMs??Date.now();if(!sn()&&Bc(_.user_spec_collected_at_ms,dn)){let N=_.user_spec_collected_at_ms!==void 0,D=Zt(e,n),R=Qt(D.components,_.user_spec_components,{forceFull:!_.user_spec_components,truncated:D.truncated}),W=new Set(_.user_spec_text_hashes??[]),ot=en(D.components,R.upserts,W),b=nn(rn([...R.upserts,...ot],W));v.user_spec_hash=R.hash,v.user_spec_count=R.count,v.user_spec_truncated=R.truncated||b.droppedCount>0,(b.components.length>0||R.removed.length>0||R.full)&&(R.full&&(v.user_spec_full=!0),b.components.length>0&&(v.user_spec=b.components),R.removed.length>0&&!v.user_spec_truncated&&(v.user_spec_removed=R.removed),b.textDeferredCount>0&&(v.user_spec_text_deferred=b.textDeferredCount));let st=R.full?{}:{..._.user_spec_components??{}};if(!v.user_spec_truncated)for(let ie of R.removed)delete st[J(ie.path,ie.name)];for(let ie of b.components)st[J(ie.path,ie.name)]=ie.content_hash;ln={hash:R.hash,componentHashes:st,textHashes:tn(W,b.textHashesSent,D.components),included:b.components.length>0||R.removed.length>0&&!v.user_spec_truncated||R.full,collectedAtMs:dn};let it=await Ye({gitRoot:s,installationStorePath:r.installationStorePath,forceResend:N});it.operator&&(v.operator=it.operator),un=it.commit}let Do=zc(_,fe,E,ln);return{config:v,commit:()=>{m[e]=Do,Wc(g,m),un()}}}function ue(e,t,n){let r={installation_id:n.installationId};return n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId),{schema_version:2,event:e,timestamp:He(),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:F,host_arch:process.arch,node_version:process.version,correlation:r,payload:t}}import{existsSync as ko}from"node:fs";import{spawn as Co}from"node:child_process";import{basename as Yc}from"node:path";import{fileURLToPath as Xc}from"node:url";var Te="__post",Ze="__work";function qc(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 Oo(e){switch(e){case"session_start":return _n;case"session_end":return hn;case"tool_invoked":case"skill_invoked":return lt;default:return lt}}function Zc(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
25
+ ${n}`}function Ao(e,t=[],n=process.execPath,r=import.meta.url,o=ko){if(Yc(n)===z)return{command:n,args:[e,...t]};let s=Xc(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Qc(e=process.execPath,t=import.meta.url,n=ko){return Ao(Te,[],e,t,n)}function el(e){let t=e.indexOf(`
26
+ `);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 Qe(e,t=fetch){let n=await e(),r=el(n);if(!r)return;let{meta:o,body:s}=r,a={"Content-Type":"application/json"};try{await t(o.url,{method:"POST",headers:a,body:s,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function tl(e,t,n){let r=Oo(e);d(`POST event=${e} url=${dt(n)} size=${t.length} platform=${process.platform}`);let o={"Content-Type":"application/json"},s=Date.now();try{let a=await fetch(n,{method:"POST",headers:o,body:t,signal:AbortSignal.timeout(r)}),i=Date.now()-s;if(a.ok)return d(`POST outcome=ok elapsed_ms=${i} http=${a.status}`),!0;let c=(await a.text()).slice(0,200).replace(/[\n\r]/g,"");return d(`POST outcome=fail elapsed_ms=${i} http=${a.status} body=${c}`),!1}catch(a){let i=Date.now()-s,c=a instanceof Error?a.message:String(a);return d(`POST outcome=fail elapsed_ms=${i} http=000 body=${c}`),!1}}async function xo(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 a=!1;return await new Promise(i=>{let c=setTimeout(()=>{if(!a){d(`WARN: ${o} stdin handoff timed out \u2014 continuing fail-open`);try{s.stdin.destroy()}catch{}}i()},En),l=()=>{a=!0,clearTimeout(c),i()};s.stdin.end(n,()=>l()),s.stdin.once("error",()=>l())}),s.unref(),s}catch(s){let a=s instanceof Error?s.message:String(s);return d(`WARN: ${o} spawn failed open: ${a}`),null}}async function nl(e,t,n,r=Co,o=Qc){let s=Oo(e),a=Zc(n,s,t),{command:i,args:c}=o();return xo(i,c,a,r,"detached post")}async function To(e,t,n=Co,r=Ao){let{command:o,args:s}=r(Ze,t);return xo(o,s,e,n,"detached work")}async function de(e,t,n,r,o,s){if(!o)return d("WARN: collector URL missing \u2014 pass --url on the hook command or set collector_url in manifest"),!1;if(!Me(o))return d(`WARN: collector URL blocked (https required): ${dt(o)}`),!1;let a=r(e,t,n);s!==void 0&&(a.build_ms=Math.max(0,Date.now()-s));let i=`${JSON.stringify(a)}
27
+ `,c=k("EV_AI_HOOK_DEBUG");c==="full"?d(`DEBUG envelope=${JSON.stringify(a)}`):c==="1"&&d(`DEBUG summary=${qc(a,Buffer.byteLength(i,"utf8"))}`);let l=process.argv.includes(Ze),u=k("EV_AI_HOOK_SYNC")==="1";return We(n.runnerEvent,n.runnerPlatform)||l||u?tl(e,i,o):(await nl(e,i,o),!1)}import{relative as rl,resolve as et,sep as an}from"node:path";var ol=["session_id","conversation_id","turn_id","generation_id","prompt.id","prompt_id","hook_event_name","event","source","status","stop_reason","reason","tool_name","tool","tool_use_id","skill_name","command_name","expansion_type","command_source","permission_mode","model","model_id","agent_id","agent_type","subagent_id","subagent_type","subagent_model","is_parallel_worker","effort","effort.level","duration_ms","duration","sandbox","failure_type","is_interrupt"];function sl(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:k("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function il(e){let t={};for(let n of ol){let r=te(e,n);r!==void 0&&(t[n]=r)}return t}function al(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=et(e),r=et(t),o=rl(r,n);return!o||o==="."?".":o.startsWith(`..${an}`)||o===".."||et(r,o)!==n?null:o.split(an).join("/")}function cl(e){return typeof e!="string"||e.length===0?null:et(e).split(an).join("/")}function vo(e,t,n){let r=cl(t.cwd);r!==null&&(e.cwd=r);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?al(t.cwd,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function bo(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([a,i])=>!a.startsWith("_")&&(typeof i=="string"||typeof i=="number"||typeof i=="boolean")).sort((a,i)=>Buffer.byteLength(JSON.stringify(a[1]),"utf8")-Buffer.byteLength(JSON.stringify(i[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[a,i]of o){let c={...s,[a]:i};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[a]=i}return s}function ve(e,t,n={}){if(sl(t)){let o={...e};return delete o.cwd,delete o.transcript_path,vo(o,e,n),bo(o,yn)}let r=il(e);return vo(r,e,n),bo(r,Sn)}import{createReadStream as ll}from"node:fs";import{stat as ul}from"node:fs/promises";import{basename as dl,resolve as fl}from"node:path";import{createInterface as pl}from"node:readline";var ml=1024*1024;function gl(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&dl(t).endsWith(".jsonl")}async function wo(e){if(!e||!gl(e))return null;try{let t=fl(e),n=await ul(t);if(!n.isFile())return null;let r=Math.max(0,n.size-ml),o=[],s=pl({input:ll(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let a of s)a.length!==0&&o.push(a);r>0&&o.length>0&&o.shift();for(let a=o.length-1;a>=0;a--){let i=o[a];if(i)try{let c=JSON.parse(i);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 we(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function tt(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}var _l=new Set([...Object.values(Dt),".github"]);function hl(e,t,n){if(e===null||t===null||n===null||!(/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let o=n.indexOf(":");if(o<=0||o===n.length-1)return;let s=n.slice(o+1),a=s.replaceAll("\\","/").split("/").at(-1);if(!(a===void 0||!_l.has(a)))try{return(0,q.buildComponentReference)({installationRootExternalKey:n,installableKind:q.ComponentKind.INTERFACE,sourcePath:s,nativeKey:t})}catch{return}}function El(...e){for(let t of e)if(t)return t;return null}function M(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return d(`WARN: ${n} failed open: ${r}`),t}function Sl(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 yl(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var se=new Set,be=null;async function Po(e){if(sn())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(se.has(t))return;if(!Vt(n)){se.add(t);return}let r=Se({sessionId:e.sessionId,hostname:ye()});if(to(r)){if(be){await be;return}be=(async()=>{if(se.has(t)||!Vt(n)){se.add(t);return}if(!Xn(n)){se.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:a}=e.manifest,i=String(e.runnerPlatform),[c,l,u,f,g]=await Promise.allSettled([Ce(a),ht(),Ft(r),Et(),Ye({gitRoot:a,installationStorePath:n,forceResend:!1})]),m=M(c,null,"gitSnapshot"),_=M(l,"","detectVirt"),E=M(u,null,"probeCloud"),T=M(f,{},"hostEnv"),A=M(g,{commit:()=>{}},"resolveOperatorForSend");await Pe(e,a,m);let P={identity:{host:ye(),context:r,virt:_||null,cloud:E,git:m},host_env:T,env_vars:Gt(),self_config:yl(i,A.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await de("session_start",P,we(e),ue,e.manifest.collectorUrl,s),o&&(A.commit(),se.add(t))}finally{qn(n)}})().finally(()=>{be=null}),await be}}async function Pe(e,t,n){try{let r=n===void 0?await Ce(t):n;e.platformAgentId=await zr(e.manifest.manifest,e.platformAgentId,String(e.runnerPlatform),t,r,e.manifest.installationStorePath,e.manifest.repoKey)}catch(r){let o=r instanceof Error?r.message:String(r);d(`WARN: derivePlatformAgentId failed open: ${o}`)}}async function Il(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Se({sessionId:e.sessionId,hostname:ye()}),o=String(e.runnerPlatform),[s,a,i,c,l,u]=await Promise.allSettled([Ce(n),ht(),Ft(r),Et(),jt(e.manifest.manifest,n,o),Ro(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n})]),f=M(s,null,"gitSnapshot"),g=M(a,"","detectVirt"),m=M(i,null,"probeCloud"),_=M(c,{},"hostEnv"),E=M(l,[],"mcpDeclared"),T=M(u,Sl(o),"selfConfig"),A=T.config;await Pe(e,n,f);let P=p(e.hookInput,"model");P&&(A.model=P);let Z={identity:{host:ye(),context:r,virt:g||null,cloud:m,git:f},host_env:_,env_vars:Gt(),mcp:{declared:E},self_config:A,run_meta:{trigger:e.hookSource||"startup"},hook_input:ve(e.hookInput,e.manifest.manifest,tt(e))};await de("session_start",Z,we(e),ue,e.manifest.collectorUrl,t)&&(T.commit(),se.add(e.manifest.installationId))}async function Rl(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Pe(e,n);let r=El(p(e.hookInput,"status"),p(e.hookInput,"stop_reason"),p(e.hookInput,"reason"),Mt(p(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await wo(p(e.hookInput,"transcript_path")):null,s=ve(e.hookInput,e.manifest.manifest,tt(e));o&&(s.model=o),await de("session_end",{status:r,...o?{model:o}:{},hook_input:s},we(e),ue,e.manifest.collectorUrl,t)}async function kl(e){let t=Date.now(),n=wr(e.hookInput);if(n.length===0)return;await Po(e);let{gitRoot:r}=e.manifest;await Pe(e,r);let o=ve(e.hookInput,e.manifest.manifest,tt(e)),s=we(e),a=Ke(e.hookInput.tool_input),i=r.replaceAll("\\","/").replace(/\/$/,""),c=a?.replaceAll("\\","/"),l=c===void 0?null:c.startsWith(`${i}/`)?c.slice(i.length+1):c.startsWith("/")?null:c;await Promise.all(n.map(u=>{let f;if(l!==null&&Pt(l)?.toLowerCase()===u.toLowerCase()&&e.platformAgentId){let g=(0,q.nativeKeyForSkillPath)(l);if(g!==null)try{f=(0,q.buildComponentReference)({installationRootExternalKey:e.platformAgentId,installableKind:q.ComponentKind.SKILL,sourcePath:l,nativeKey:g})}catch{f=void 0}}return de("tool_invoked",{tool_name:"Skill",skill_name:u,...f===void 0?{}:{component_reference:f},success:null,duration_ms:null,hook_input:o},s,ue,e.manifest.collectorUrl,t)}))}async function Cl(e){let t=Date.now();await Po(e);let{gitRoot:n}=e.manifest;await Pe(e,n);let{toolName:r,skillName:o}=Mr(e.hookInput,e.runnerEvent),s=Dr(e.hookInput),a=Nr(e.runnerEvent),i=a===!1?Fr(e.hookInput,e.runnerEvent):null,c=await jt(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform)).catch(()=>[]),{mcpServer:l,mcpTool:u}=$r(r,c.map(m=>m.name)),f=hl(r,l,e.platformAgentId),g=Hr(e.hookInput);await de("tool_invoked",{tool_name:r,skill_name:o,success:a,duration_ms:s,...i?{failure_reason:i}:{},...l?{mcp_server:l}:{},...u?{mcp_tool:u}:{},...f?{component_reference:f}:{},...g?{subagent_type:g}:{},hook_input:ve(e.hookInput,e.manifest.manifest,tt(e))},we(e),ue,e.manifest.collectorUrl,t)}async function No(e){switch(e.internalEvent){case"session_start":await Il(e);return;case"session_end":await Rl(e);return;case"skill_invoked":await kl(e);return;case"tool_invoked":await Cl(e);return;default:return}}function Uo(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}async function Lo(e,t,n,r){let o=t??await mt(ut),s=w(o,{}),a=p(s,"session_id")||p(s,"conversation_id"),i=await nr(process.cwd(),{sessionId:a});if(!i)return;r&&(i.collectorUrl=r);let c=Ur(s,i.manifest.platform,n),l=Lr(e,c.runnerEvent);if(!l){d(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let u={hookInput:s,sessionId:c.sessionId,turnId:c.turnId,runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:l,manifest:i,platformAgentId:i.platformAgentId};if(Uo(l)){d(`WARN: unsupported internal event '${l}'`);return}await No(u)}function Ol(e,t){if(k("EV_AI_HOOK_SYNC")==="1")return!0;let n=Ve(e),r=w(t,{}),o=n.event??(p(r,"hook_event_name")||p(r,"event")),s=Re(r,o,void 0,n.runner);return We(o,s)}async function Mo(e=process.argv.slice(2)){if(e[0]===Te){try{await Qe(ge)}catch{}return 0}if(e[0]===Ze){try{let t=Ve(e.slice(1)),n=await ge(),r=w(n,{}),o=t.event??(p(r,"hook_event_name")||p(r,"event"));if(Lt(t.runner,r,o))return 0;await Lo(t.event,n,t.runner,Ut(t))}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await mt(ut),n=Ve(e),r=Ut(n),o=w(t,{}),s=n.event??(p(o,"hook_event_name")||p(o,"event"));if(Lt(n.runner,o,s)||!Wr(o,s,n.runner))return 0;Ol(e,t)?await Lo(n.event,t,n.runner,r):await To(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);d(`WARN: hook failed open: ${n}`)}finally{wn()}return 0}function nt(){d("Usage: ev-ai-agent-hook <configure|install|migrate-to-plugin|update|uninstall|--version>"),d(" configure [--url <\u2026/{orgToken}/hook>]"),d(" (manifest only \u2014 pair with marketplace plugins)"),d(" install --url <\u2026/{orgToken}/hook>"),d(" [--delivery npx|binary|local] [--force]"),d(" [--no-claude] [--no-cursor] [--no-codex]"),d(" (fallback: merge hooks into .claude / .cursor / .codex configs)"),d(" (writes collector_url to shared manifest; hook commands use --runner only)"),d(" migrate-to-plugin"),d(" (strip ev-ai file hooks; keep collector manifest)"),d(" update (refresh binary pins from a local build; leaves hook configs alone)"),d(" uninstall"),d("Hook mode: --runner <platform> [--url <\u2026/hook>|--token <orgToken>] [event]"),d(" (--url/--token optional overrides; else collector_url from manifest)")}function Ho(e){return e.includes("--help")||e.includes("-h")}async function bl(e=process.argv.slice(2)){let[t,...n]=e;if(t===Te){try{await Qe(ge)}catch{}return 0}return t==="--version"||t==="-V"?(process.stdout.write(`${F}
28
+ `),0):t==="configure"?Ho(n)?(nt(),0):(await Cr(ur(n)),0):t==="install"?Ho(n)?(nt(),0):(await Rr(dr(n)),0):t==="migrate-to-plugin"?(await Ar(),0):t==="update"?(await kr(),0):t==="uninstall"?(await xr(),0):t==="help"||t==="--help"||t==="-h"?(nt(),0):t===void 0?(nt(),1):Mo(e)}function wl(e,t,n=Al){if(!t)return!1;try{return e===vl(xl(t)).href?!0:n(Tl(e))===n(t)}catch{return!1}}wl(import.meta.url,process.argv[1])&&process.env.VITEST===void 0&&bl().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);d(t),process.exit(1)});export{wl as isCliEntrypoint,bl as main};