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