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