@ev-ai/agent-hook 1.1.6 → 1.2.0
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 +17 -13
- package/README.md +21 -6
- package/dist/cli.mjs +40 -32
- package/dist/hook.mjs +35 -27
- package/dist/launcher-update.mjs +5 -0
- package/dist/launcher.mjs +5 -0
- package/dist/managed-hooks-snippet.cjs +177 -0
- package/dist/managed-hooks-snippet.d.ts +3 -0
- package/dist/managed-hooks-snippet.mjs +149 -0
- package/dist/plugin-hooks.mjs +39 -26
- package/package.json +15 -2
package/dist/hook.mjs
CHANGED
|
@@ -1,37 +1,45 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from 'node:module';
|
|
2
2
|
const require = __createRequire(import.meta.url);
|
|
3
3
|
|
|
4
|
-
var ea=Object.create;var Sr=Object.defineProperty;var ta=Object.getOwnPropertyDescriptor;var na=Object.getOwnPropertyNames;var ra=Object.getPrototypeOf,oa=Object.prototype.hasOwnProperty;var $t=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});var rt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var sa=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of na(t))!oa.call(e,o)&&o!==n&&Sr(e,o,{get:()=>t[o],enumerable:!(r=ta(t,o))||r.enumerable});return e};var Ne=(e,t,n)=>(n=e!=null?ea(ra(e)):{},sa(t||!e||!e.__esModule?Sr(n,"default",{value:e,enumerable:!0}):n,e));var mn=rt(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.MCP_MISSING_LAUNCH_SERIALIZED=v.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;v.foldMcpName=Po;v.buildMcpFamilyCanonicalKey=Nc;v.launchContainsCredentials=Uc;v.serializeMcpLaunchIdentity=xo;v.hashMcpLaunchIdentity=je;v.projectMcpMissingLaunchIdentity=Fc;v.projectMcpLaunchIdentity=jc;v.maskMcpLaunchForDisplay=$c;v.normalizeMcpToolNames=Bc;var wc=$t("node:crypto");v.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";v.MCP_MISSING_LAUNCH_SERIALIZED=`${v.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function ee(e){return e.toLocaleLowerCase("en-US")}function Po(e){return ee(e)}function Nc(e){return`interface:${Po(e)}`}var Oo=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),Lc=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function ke(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Uc(e){return e.kind==="url"?Dc(e.url):e.kind==="command"?e.arguments.some(t=>Lc.test(t)):!1}function Dc(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(Oo.has(ee(n)))return!0;return!1}catch{let t=e.split("://",2),n=t.length===2?t[1]:e,r=n.indexOf("@"),o=n.indexOf("/");if(r>0&&(o===-1||r<o))return!0;let s=e.split("?",2)[1];return s===void 0?!1:s.split("&").some(i=>{let a=ee(i.split("=",1)[0]??"");return Oo.has(a)})}}function xo(e){if(e.kind==="url")return[v.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",ke(ee(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>ee(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[v.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",ke(ee(e.command)),String(t.length),...t.map(ke)].join("|")}return[v.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",ke(e.installationRootExternalKey),ke(e.sourcePath),ke(e.nativeKey)].join("|")}function je(e){return(0,wc.createHash)("sha256").update(e).digest("hex")}var Hc=je(v.MCP_MISSING_LAUNCH_SERIALIZED);function Fc(){return{kind:"unknown",arguments:[],serialized:v.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:Hc}}function jc(e){let t=xo(e);return e.kind==="url"?{kind:"url",url:ee(e.url),arguments:[],serialized:t,contentHash:je(t)}:e.kind==="command"?{kind:"command",command:ee(e.command),arguments:[...e.arguments].map(n=>ee(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:je(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:je(t)}}var Kc=/^(https?:\/\/)([^/?#]*@)/i;function $c(e){return e.replace(Kc,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function Bc(e){let t=new Set,n=[];for(let r of e)r.length===0||t.has(r)||(t.add(r),n.push(r));return n.sort((r,o)=>r<o?-1:r>o?1:0),n}});var _n=rt(ce=>{"use strict";Object.defineProperty(ce,"__esModule",{value:!0});ce.PACKAGE_FIELD_MAX=void 0;ce.npxExecBin=To;ce.packageNameFromSpec=gn;ce.npxPackageSpecs=qc;ce.PACKAGE_FIELD_MAX=128;var Gc=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,zc=new Set(["-p","--package"]),Wc=new Set(["-c","--call"]),Jc=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),Vc=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),Yc=/^--no-/;function Xc(e){return Vc.has(e)||Yc.test(e)}function To(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}function gn(e){if(e.length===0||e.length>ce.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return Gc.test(n)?n:null}function qc(e,t){let n=To(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(Wc.has(l))return[];if(zc.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||Xc(l))){if(Jc.has(l)){i+=1;continue}return[]}}return o.length>0?o.every(i=>gn(i)!==null)?o:[]:s===null||gn(s)===null?[]:[s]}});var Lo=rt(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.EMPTY_NPM_PUBLISHER=void 0;_e.isNpmRegistryPublisher=Qc;_e.classifyMcpProvenance=cu;var Mo=mn(),hn=_n();_e.EMPTY_NPM_PUBLISHER="npm:";var bo="npm:",Zc=/^[A-Za-z0-9._-]+$/;function Qc(e){return e.startsWith(bo)&&e!==_e.EMPTY_NPM_PUBLISHER&&Zc.test(e.slice(bo.length))}function vo(e){let t=e.split(".").map(Number);return t.length!==4||t.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:t[0]===0||t[0]===10||t[0]===127||t[0]===169&&t[1]===254||t[0]===172&&(t[1]??0)>=16&&(t[1]??0)<=31||t[0]===192&&t[1]===168}function eu(e){let t=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(e);if(t?.[1])return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(e);if(!n)return;let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return`${r>>8&255}.${r&255}.${o>>8&255}.${o&255}`}function Sn(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function tu(e){let t=Sn(e),n=eu(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||vo(t)||n!==void 0&&vo(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function nu(e){let t=Sn(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function ru(e){let t=Sn(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function wo(e){let t={kind:"url",url:e};if((0,Mo.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||tu(n.hostname))return{origin:"UNKNOWN"};let r=nu(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:ru(n)}}catch{return{origin:"UNKNOWN"}}}var No="mcp-remote";function ou(e,t){if(e===No)return t.find(n=>/^https?:\/\//i.test(n))}function su(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function iu(e,t,n){let r=ou(e,t);return r!==void 0?wo(r):e===No?{origin:"UNKNOWN"}:su(e,n)}function au(e){let t=e.replaceAll("\\","/");return t.startsWith("~/")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)?!1:t.startsWith("./")||t.startsWith("../")||t==="scripts"||t.startsWith("scripts/")}function cu(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,Mo.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return wo(t.url);let r=(0,hn.npxPackageSpecs)(t.command,t.arguments)[0];if(r!==void 0){let o=(0,hn.packageNameFromSpec)(r);if(o===null)return{origin:"UNKNOWN"};let s=iu(o,t.arguments,e.publisherName),i=typeof e.packageName=="string"?(0,hn.packageNameFromSpec)(e.packageName):null;return i!==null&&i===o&&s.packageName!==void 0?{...s,packageName:i,packageKey:i}:s}return au(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var Oe=rt(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.isNpmRegistryPublisher=g.EMPTY_NPM_PUBLISHER=g.classifyMcpProvenance=g.packageNameFromSpec=g.npxPackageSpecs=g.npxExecBin=g.PACKAGE_FIELD_MAX=g.serializeMcpLaunchIdentity=g.projectMcpMissingLaunchIdentity=g.projectMcpLaunchIdentity=g.normalizeMcpToolNames=g.MCP_MISSING_LAUNCH_SERIALIZED=g.MCP_LAUNCH_IDENTITY_ALGORITHM=g.maskMcpLaunchForDisplay=g.launchContainsCredentials=g.hashMcpLaunchIdentity=g.foldMcpName=g.buildMcpFamilyCanonicalKey=g.ComponentKind=void 0;g.userConfigRootFromPath=Su;g.installationRootExternalKey=Eu;g.normalizeRepositoryRelativePath=Uo;g.nativeKeyForSkillPath=yu;g.nativeKeyForRulePath=Ru;g.nativeKeyForCommandPath=Cu;g.serializeComponentIdentity=Ho;g.buildComponentReference=Au;g.validateComponentReference=ku;var uu=$t("node:crypto"),lu=$t("node:path"),du="cmp1_",pu=/^cmp1_[A-Za-z0-9_-]{43}$/,fu=["/skills/","/skills-cursor/"],mu=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,gu=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,_u=[".cursor",".claude",".codex"],hu={".claude.json":".claude",".agents":".codex"};g.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function Su(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>_u.includes(o));return n||(t.map(o=>hu[o]).find(o=>o!==void 0)??"unknown")}function Eu(e,t){return`runtime-install:${e}/${t}`}function ft(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Uo(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=lu.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return ft(n,"sourcePath")}function yu(e){let t=e.replaceAll("\\","/");for(let n of fu){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Do(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 Ru(e){return Do(e,mu,/\.(mdc|md|rules)$/i)}function Cu(e){return Do(e,gu,/\.(md|mdc|toml)$/i)}function Iu(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Ho(e){let t=[ft(e.installationRootExternalKey,"installationRootExternalKey"),ft(e.installableKind,"installableKind"),Uo(e.sourcePath),ft(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(Iu).join("|")}`,"utf8")}function Au(e){let t=(0,uu.createHash)("sha256").update(Ho(e)).digest("base64url");return`${du}${t}`}function ku(e){return pu.test(e)}var V=mn();Object.defineProperty(g,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return V.buildMcpFamilyCanonicalKey}});Object.defineProperty(g,"foldMcpName",{enumerable:!0,get:function(){return V.foldMcpName}});Object.defineProperty(g,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return V.hashMcpLaunchIdentity}});Object.defineProperty(g,"launchContainsCredentials",{enumerable:!0,get:function(){return V.launchContainsCredentials}});Object.defineProperty(g,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return V.maskMcpLaunchForDisplay}});Object.defineProperty(g,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return V.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(g,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return V.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(g,"normalizeMcpToolNames",{enumerable:!0,get:function(){return V.normalizeMcpToolNames}});Object.defineProperty(g,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return V.projectMcpLaunchIdentity}});Object.defineProperty(g,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return V.projectMcpMissingLaunchIdentity}});Object.defineProperty(g,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return V.serializeMcpLaunchIdentity}});var mt=_n();Object.defineProperty(g,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return mt.PACKAGE_FIELD_MAX}});Object.defineProperty(g,"npxExecBin",{enumerable:!0,get:function(){return mt.npxExecBin}});Object.defineProperty(g,"npxPackageSpecs",{enumerable:!0,get:function(){return mt.npxPackageSpecs}});Object.defineProperty(g,"packageNameFromSpec",{enumerable:!0,get:function(){return mt.packageNameFromSpec}});var En=Lo();Object.defineProperty(g,"classifyMcpProvenance",{enumerable:!0,get:function(){return En.classifyMcpProvenance}});Object.defineProperty(g,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return En.EMPTY_NPM_PUBLISHER}});Object.defineProperty(g,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return En.isNpmRegistryPublisher}})});import{existsSync as fa,readFileSync as ma}from"node:fs";import{hostname as Or,userInfo as ga}from"node:os";import{randomBytes as ia}from"node:crypto";import{existsSync as Gt,mkdirSync as aa,readdirSync as ca,readFileSync as ua,renameSync as Er,statSync as Cr,unlinkSync as yr,writeFileSync as la}from"node:fs";import{basename as da,dirname as Rr,join as Ir,relative as pa}from"node:path";function h(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
|
|
5
|
-
`)}function Y(e,t){aa(Rr(e),{recursive:!0});let n=Ir(Rr(e),`.${da(e)}.${process.pid}.${ia(4).toString("hex")}.tmp`);try{la(n,t,"utf8");try{Er(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){yr(e),Er(n,e);return}throw r}}catch(r){try{yr(n)}catch{}throw r}}function ot(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function Ar(){process.stdout.write('{"continue":true}')}function I(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function zt(){return new Promise(e=>{let t="";if(process.stdin.isTTY){e("");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",n=>{t+=n}),process.stdin.on("end",()=>{e(t)}),process.stdin.on("error",()=>{e(t)}),process.stdin.resume()})}async function Wt(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function J(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,l=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:l,spawnFailed:l===void 0}}}async function M(e,t,n=3e3,r={}){let o=await J(e,t,n,r);return o.ok?o.stdout:""}async function Jt(e=process.cwd()){let t=await J("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(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&&Gt(n)){let r=await J("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function Vt(e=process.cwd()){return(await Jt(e)).root}function F(e,t){try{return JSON.parse(e)}catch{return t}}var Bt=new Map;function L(e,t){let n=Bt.get(e);if(n!==void 0)return n;try{let r=F(ua(e,"utf8"),t);return Bt.set(e,r),r}catch{return Bt.set(e,t),t}}function de(e){return typeof e=="string"?e:""}function pe(e,t){let n=e[t];if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return n;if(!t.includes("."))return;let r=t.split("."),o=e;for(let s of r){if(o===null||typeof o!="object"||Array.isArray(o))return;o=o[s]}if(typeof o=="string"||typeof o=="number"||typeof o=="boolean")return o}function m(e,t){let n=pe(e,t);return typeof n=="string"?n:""}var re=500;function kr(e,t=2){if(!Gt(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=ca(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let l=Ir(s,c.name);if(c.isDirectory()){o(l,i+1);continue}if(c.isFile()){try{n.push({name:pa(e,l),size:Cr(l).size})}catch{continue}if(n.length>=re){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function Yt(e){return Gt(e)?{present:!0,size:Cr(e).size}:{present:!1,size:0}}function Re(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Xt(e=process.env){return Re(T("CURSOR_SANDBOX",e))}var _a=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function ha(e){return _a.some(t=>!!T(t,e))}function Sa(e){if(T("KUBERNETES_SERVICE_HOST",e)||Re(T("REMOTE_CONTAINERS",e))||Re(T("DEVCONTAINER",e)))return!0;try{if(fa("/.dockerenv")||ma("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function Pr(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!T(t,e))}function Ea(e,t=process.platform){return Pr(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!T(n,e)):!1}function ya(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Ra(e){return e==="linux"}function T(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return I(e)}function Ca(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Ia(T("CURSOR_VERSION",n))}function Ia(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function qt(e){if(ya(e.sessionId))return!0;let t=e.hostname??Or(),n=e.osUser??xr(e.env);return Ca(t,n,e.env)}function Aa(e){return Re(T("CURSOR_AGENT",e.env))?!0:qt(e)}function ka(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))||Pr(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!T(t,e))||T("SESSIONNAME",e))}function Le(e={}){let t=e.env;if(T("GITHUB_ACTIONS",t))return"github_actions";if(Re(T("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!Ea(t,n)&&Aa(e)&&(Re(T("CURSOR_AGENT",t))||Ra(n)))return"cursor_cloud";if(T("CODESPACES",t)||T("CODESPACE_NAME",t))return"codespaces";if(T("GITLAB_CI",t))return"gitlab_ci";if(ha(t))return"managed";let r=T("CI",t);return r&&r!=="false"&&r!=="0"?"managed":Sa(t)?"container":ka(t)?"interactive":"unknown"}async function Zt(){return await M("systemd-detect-virt",[],1e3)}function xr(e=process.env,t=ga){for(let n of["USER","LOGNAME","USERNAME"]){let r=e[n];if(typeof r=="string"){let o=r.trim();if(o.length>0)return o}}try{return t().username??""}catch{return""}}async function Qt(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await M("sw_vers",["-productVersion"],1e3);else if(process.platform==="linux"){try{let{readFileSync:s}=await import("node:fs"),i=s("/etc/os-release","utf8"),a=i.match(/^PRETTY_NAME="?([^"\n]+)"?/m)?.[1],c=i.match(/^VERSION_ID="?([^"\n]+)"?/m)?.[1];t=a??c??""}catch{t=await M("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await M("uname",["-r"],1e3))}else t=await M("ver",[],1e3);let n=xr(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await M("tty",[],500),o.includes("not a tty")&&(o="")}catch{o=""}return{os:e,os_version:t||null,user:n||null,shell:r||null,tty:o||null}}function Ue(){return Or()}var Oa="https://hooks.ev-ai.ai";function it(e,t=Oa){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}var Tr=".claude/ev-ai-runtime-report.json",br="config.json";var st="ev-ai-agent-hook";function Pa(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function vr(e){let t=Pa(e);return t===st||t===`${st}.exe`}var im=`current/${st}`,am=`.ev-ai/agent-hook/${st}`,Mr=5e3,wr=5e3,en=3e3;var tn=3e3,Nr=1500,Lr=4*1024,Ur=32*1024,xa=4*1024,Dr=32*1024,De=840*60*1e3,nn="1.1.6",cm=`@ev-ai/agent-hook@${nn}`;var Hr=["claude","cursor","codex"];import{createHash as nl}from"node:crypto";import{existsSync as rl,mkdirSync as ol,readdirSync as sl,readFileSync as as,unlinkSync as cs,writeFileSync as il}from"node:fs";import{homedir as us}from"node:os";import{join as Tn}from"node:path";import{createHash as Br,randomBytes as va}from"node:crypto";import{existsSync as Gr,mkdirSync as rn,readFileSync as zr,unlinkSync as Wr,writeFileSync as Jr}from"node:fs";import{homedir as on}from"node:os";import{dirname as at,join as sn,resolve as Ma}from"node:path";var Ta=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),ba=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function B(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||ba.has(n)||r.includes("[bot]")||Ta.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 wa="installation.json",Na="cloud-bootstrap.lock",La=6e4;function Vr(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function fe(e=on()){return sn(e,".ev-ai","agent-hook")}function Ua(e=on()){return sn(fe(e),wa)}function Yr(e){return sn(at(e),Na)}function Xr(){return va(8).toString("hex")}function Ce(e){return Br("sha256").update(e).digest("hex").slice(0,16)}function A(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function qr(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function Da(e=process.env){let t=A(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!qr(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 Zr(e,t){return e&&qr(e)?e:(e&&h(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),Da(t))}function Ha(e){return/^[0-9a-f]{16}$/.test(e)}function Fa(e=process.env){if(A(e.GITHUB_ACTIONS)){let t=A(e.GITHUB_REPOSITORY_ID)??A(e.GITHUB_REPOSITORY),n=A(e.GITHUB_ACTOR)??A(e.GITHUB_TRIGGERING_ACTOR)??A(e.GITHUB_USER);if(t&&n)return Ce(`github_actions|${t}|${n}`)}if(A(e.CODESPACES)||A(e.CODESPACE_NAME)){let t=A(e.CODESPACE_NAME);if(t)return Ce(`codespaces|${t}`);let n=A(e.GITHUB_REPOSITORY_ID)??A(e.GITHUB_REPOSITORY),r=A(e.GITHUB_USER)??A(e.GITHUB_ACTOR);if(n&&r)return Ce(`codespaces|${n}|${r}`)}if(A(e.GITLAB_CI)){let t=A(e.CI_PROJECT_ID)??A(e.CI_PROJECT_PATH),n=A(e.GITLAB_USER_LOGIN)??A(e.GITLAB_USER_EMAIL)??A(e.GITLAB_USER_NAME);if(t&&n)return Ce(`gitlab|${t}|${n}`)}return null}var ja="cursoragent@cursor.com";function Ka(e){let t=A(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===ja?null:t}function $a(e,t){return A(e.CURSOR_PROJECT_DIR)??A(e.CLAUDE_PROJECT_DIR)??t}function Ba(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function Ga(e){let t=await M("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?Ba(t):e}async function za(e){let t=A(await M("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!B(null,t))return t;let n=A(await M("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!B(null,n)?n:null}function Wa(e,t){let n=$a(e,t);return n?Ce(`cursor_cloud|${n}|${Ka(e)??""}`):null}async function Ja(e,t){let n=A(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await Ga(n),o=await za(n);return Ce(`claude_remote|${r}|${o??""}`)}function Fr(e,t){let n=Zr(e,t);if(n)return n;let r=Fa(t);return r||Xr()}async function Va(e){let n=await M("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Ma(e);return Br("sha256").update(n).digest("hex").slice(0,16)}function Ya(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 Xa(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=Ya(t.platform_agent_ids);return{installation_id:t.installation_id,...t.pinned===!0?{pinned:!0}:{},...n?{platform_agent_ids:n}:{},...typeof t.operator_identity_hash=="string"?{operator_identity_hash:t.operator_identity_hash}:{},...typeof t.operator_identity_sent_at=="string"?{operator_identity_sent_at:t.operator_identity_sent_at}:{}}}catch{return}}function me(e){if(Gr(e))try{return Xa(zr(e,"utf8"))}catch{}}function an(e){return me(e)}function Qr(e,t,n){let r=me(e);if(!r||r.operator_identity_hash===t&&r.operator_identity_sent_at===n)return;let o={...r,operator_identity_hash:t,operator_identity_sent_at:n};try{Y(e,`${JSON.stringify(o,null,2)}
|
|
6
|
-
`)
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
`)}function $r(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function so(e,t={}){let n=t.home??on(),r=t.env??process.env,o=await Va(e),s=Ua(n),i={sessionId:t.sessionId,hostname:A(r.HOSTNAME)??void 0,osUser:A(r.USER)??A(r.LOGNAME)??A(r.USERNAME)??void 0,env:r},a=Le(i),c=Zr(t.overrideId,r),l=a==="cursor_cloud"&&qt(i)?Wa(r,e):a==="claude_remote"?await Ja(r,e):null,u=me(s);if(u){let E=u;if(c&&c===u.installation_id&&u.pinned!==!0&&(E={...u,pinned:!0},Kr(s,E)),!!l&&l!==E.installation_id&&!c&&E.pinned!==!0&&Ha(E.installation_id)&&l){let y={installation_id:l,...E.platform_agent_ids?{platform_agent_ids:E.platform_agent_ids}:{}};return Kr(s,y),{installationId:l,storePath:s,repoKey:o}}return{installationId:E.installation_id,storePath:s,repoKey:o}}let d=c??l??Fr(void 0,r),p=jr(s,$r(d,c));if(p)return{installationId:p.installation_id,storePath:s,repoKey:o};let f=c??l??Fr(void 0,r),_=jr(s,$r(f===d?Xr():f,c));if(_)return{installationId:_.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}var Za=new Set(["localhost","127.0.0.1","[::1]","::1"]),io=/^[A-Za-z0-9._~-]+$/;function ao(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function ct(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Za.has(t.hostname):!1}catch{return!1}}function co(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!ct(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=Qa(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!io.test(n))return`org token must match ${io.source} (got: ${n})`;if(ao(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(ao(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function uo(e){return new URL(e).toString()}function Qa(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r.length>0?r:void 0}return}catch{return}}function cn(e){try{let t=new URL(e),n=t.pathname.split("/").filter(r=>r.length>0);return n.length>=2&&n[n.length-1]==="hook"&&(n[n.length-2]="***",t.pathname=`/${n.join("/")}`),t.toString()}catch{return"<invalid-url>"}}function lo(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token?.trim();return t?it(t):""}import{existsSync as _c}from"node:fs";import{existsSync as ic}from"node:fs";import{homedir as mo}from"node:os";import{join as ac}from"node:path";import{existsSync as ec,readdirSync as po}from"node:fs";import{homedir as ut}from"node:os";import{join as K}from"node:path";function tc(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return K(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function nc(e=process.platform){let t=tc(e),n=[K(t,"managed-settings.json")],r=K(t,"managed-settings.d");try{if(!ec(r))return n;let o=po(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>K(r,s));n.push(...o)}catch{}return n}function un(e=process.platform,t=ut()){return{serverManaged:K(t,".claude","remote-settings.json"),fileBased:nc(e)}}function rc(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/Cursor";case"win32":return K(process.env.ProgramData??"C:\\ProgramData","Cursor");default:return"/etc/cursor"}}function oc(e=process.platform,t=ut()){let n=[K(rc(e),"hooks.json")],r=K(t,".cursor","managed");try{for(let o of po(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push(K(r,o.name,"hooks.json"))}catch{}return n}function sc(e=process.platform,t=ut()){let n=e==="win32"?K(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[K(n,"requirements.toml")];return e!=="win32"&&r.push(K(n,"managed_config.toml")),r.push(K(t,".codex","managed_config.toml"),K(n,"config.toml")),r}function lt(e,t=process.platform,n=ut()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=un(t,n);return[r,...o]}case"cursor":return oc(t,n);default:return sc(t,n)}}function go(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var cc={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 fo(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function uc(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:fo(n.mcpJson,t.mcpJson),mcpToml:fo(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function _o(e){return Object.fromEntries(Object.entries(cc).map(([t,n])=>[t,uc(n,n[e])]))}var Ie=_o("homeOnly"),se=_o("projectOnly");function lc(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function dc(e,t){return lc(e).some(n=>ic(ac(t,n)))}function ho(e,t){for(let n of e)if(dc(n,t))return!0;return!1}function oe(e){return[...new Set(e)]}function ie(e){let t=[],n=[],r=[],o=[],s=[],i=[],a=[];for(let c of e){t.push(...c.skillRoots);for(let l of c.dirs)l.kind==="SUBAGENT"?n.push(l.dir):l.kind==="COMMAND"?r.push(l.dir):o.push(l.dir);s.push(...c.memory.flat()),i.push(...c.settings),a.push(...c.mcpJson??[],...c.mcpToml??[])}return{skills:oe(t),subagents:oe(n),commands:oe(r),rules:oe(o),memory:oe(s),settings:oe(i),mcp:oe(a)}}function pc(e,t=mo(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...lt(o.managed,n,t));return oe(r)}var ae=ie(Object.values(Ie));function So(e=mo(),t=process.platform){return pc(Object.values(Ie),e,t)}import{existsSync as fc}from"node:fs";import{resolve as ln}from"node:path";function G(e){return ln(e).replaceAll("\\","/").replace(/\/$/,"")}function ge(e,t){let n=new Set(t),r=[];for(let o of e)n.delete(o)&&r.push(o);for(let o of[...n].sort())r.push(o);return r}function dt(e,t){if(!e)return t;let n=`${e}/`,r=[],o=[];for(let s of t)s===e||s.startsWith(n)?r.push(s):o.push(s);return r.length===0?t:[...r,...o]}var mc=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function He(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!mc.test(t)?null:t}function Ae(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=G(o);n.has(s)||(n.add(s),r.push(s))}return r}function gc(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function X(e,t,n,r=fc){for(let o of e)for(let s of t){let i=G(ln(o,s)),a=ln(o,s,n).replaceAll("\\","/");if(gc(i,a)&&r(a))return a}return null}var yo=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,Ro=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,hc=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,Eo=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"]),Sc=/^[a-z][a-z0-9-]{1,63}$/,Ec=[".cursor/skills",".claude/skills",".agents/skills"],yc=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],Rc=ge(Ec,ie(Object.values(se)).skills),Cc=ge(yc,ie(Object.values(Ie)).skills),Ic=new Set(["read","read_file","view"]),Ac=new Set(["bash","shell","zsh"]);function dn(e){let t=e.replace(/\\/g,"/");return yo.exec(t)?.[1]??null}function kc(e){let t=e.replace(/\\/g,"/"),r=Ro.exec(t)?.[1];return r?r.toLowerCase():null}function Oc(e){return dn(e)??kc(e)}function Pc(e){for(let t of["path","file_path","target_file"]){let n=e[t];if(typeof n=="string"&&n.length>0)return n}return null}function pt(e){return typeof e=="string"?pt(F(e,null)):!e||typeof e!="object"?null:Pc(e)}function Co(e){if(typeof e=="string")return Co(F(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function pn(e){let t=Co(e.tool_input);if(t)return t;let n=de(e.command);return n.length>0?n:null}function xc(e){let t=e.replace(/\\/g,"/"),n=yo.exec(t);if(n?.[1])return n[1];let o=Ro.exec(t)?.[1];return o?o.toLowerCase():null}function Tc(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function fn(e){let t=pt(e.tool_input)??de(e.file_path);return t.length>0?t:null}function Fe(e,t,n){let r=Tc(e).toLowerCase();if(Ic.has(r)){let o=fn(e);return o?t(o):null}if(Ac.has(r)){let o=pn(e);return o?n(o):null}return null}function Io(e){return Fe(e,Oc,xc)}function bc(e){let t=new Set,n=[];for(let r of e.matchAll(hc)){let o=r[1]?.toLowerCase();!o||t.has(o)||vc(o)||(t.add(o),n.push(o))}return n}function vc(e){let t=e.split("/")[0];return Eo.has(e)||t!==void 0&&Eo.has(t)}function Ao(e){let t=e.skillId.toLowerCase();if(!Sc.test(t))return null;let n=e.exists??_c,r=`${t}/SKILL.md`,o=X(Ae(e.launchCwd,e.gitRoot),Rc,r,n);return o!==null?o:e.home?X([G(e.home)],Cc,r,n):null}function Mc(e){return de(e.prompt)}function ko(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=Mc(e);return n?bc(n):[]}var yn=Ne(Oe(),1);import{existsSync as Pu}from"node:fs";var he={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Ke(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function Ou(e){if(!e)return"";let t=e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1");t=t.replace(/\.git$/i,"");let n=t.match(/^git@[^:]+:(.+)$/);if(n?.[1])return Ke(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Ke(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Ke(o[1]):Ke(t)}async function $e(e=process.cwd()){let t=await J("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([J("git",["remote","get-url","origin"],2e3,{cwd:e}),J("git",["branch","--show-current"],2e3,{cwd:e}),J("git",["rev-parse","HEAD"],2e3,{cwd:e}),J("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function Fo(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=he[n];if(!a)return"";let c=Vr(n,e.scope_path,i);if(s){let _=no(s,c);if(_)return _}let l=o??await $e(r),u=l?.remote?Ou(l.remote):"";if(u||(u=Ke(process.env.GITHUB_REPOSITORY??"")),!u)return"";let d=e.scope_path??"",p=d?`${d}/`:"",f=`${u}:${p}${a}`;return s&&ro(s,c,f),f}var xu=[".cursor/rules",".claude/rules",".codex/rules"],Tu=ie(Object.values(se)).rules;function bu(e){return ge(dt(e?he[e]:void 0,xu),Tu)}var vu=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function jo(e){let t=He(e.relativePath);if(!t)return null;let n=e.exists??Pu,r=Ae(e.launchCwd,e.gitRoot),o=bu(e.runnerPlatform),s=X(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=X(r,["."],t,n);if(i!==null)return i}return e.home?X([G(e.home)],o,t,n):null}function Mu(e){let t=e.replace(/\\/g,"/"),r=vu.exec(t)?.[1];return r?(0,yn.nativeKeyForRulePath)(r):null}function Ko(e){return Fe(e,yn.nativeKeyForRulePath,Mu)}function $o(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function Bo(e){let t=e.attachments;if(!Array.isArray(t))return[];let n=new Set,r=[];for(let o of t){if(!o||typeof o!="object"||Array.isArray(o))continue;let s=o;if(s.type!=="rule")continue;let i=typeof s.file_path=="string"?s.file_path:"",a=He(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var Rn=Ne(Oe(),1);import{existsSync as wu}from"node:fs";var Nu=[".cursor/commands",".claude/commands",".codex/prompts"],Lu=ie(Object.values(se)).commands;function Uu(e){return ge(dt(e?he[e]:void 0,Nu),Lu)}var Du=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function Go(e){let t=He(e.commandId);if(!t)return null;let n=e.exists??wu,r=`${t}.md`,o=Uu(e.runnerPlatform),s=X(Ae(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?X([G(e.home)],o,r,n):null}function Hu(e){let t=e.replace(/\\/g,"/"),r=Du.exec(t)?.[1];return r?(0,Rn.nativeKeyForCommandPath)(r):null}function zo(e){return Fe(e,Rn.nativeKeyForCommandPath,Hu)}import{existsSync as Jo}from"node:fs";import{homedir as Vo}from"node:os";import{join as Be,resolve as Cn,sep as Wo}from"node:path";function In(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function An(e,t){let n=t.toLowerCase();return In(e).some(r=>r.toLowerCase()===n)}function gt(e,t,n){if(!Jo(e))return;let r=L(e,{});for(let[o,s]of Object.entries(r.mcpServers??{}))n.set(o,{declared:{name:o,...t},config:s})}function Fu(e,t,n){if(!Jo(e))return;let r=L(e,{}),o=Cn(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Cn(a);(o===c||o.startsWith(c.endsWith(Wo)?c:c+Wo))&&(s===null||c.length>Cn(s).length)&&(s=a)}if(s===null)return;let i=r.projects?.[s]?.mcpServers??{};for(let[a,c]of Object.entries(i))n.set(a,{declared:{name:a,source:"claude_json_project",sourcePath:".claude.json",scope:"user"},config:c})}function Yo(e,t,n,r){let o=new Map;for(let s of e.mcp_servers??[])s.name&&o.set(s.name,{declared:{name:s.name,source:"manifest"}});return n==="claude"?(gt(Be(r,".claude.json"),{source:"claude_json_user"},o),Fu(Be(r,".claude.json"),t,o)):n==="cursor"&>(Be(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),gt(Be(t,".mcp.json"),{source:"mcp_json"},o),gt(Be(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function kn(e,t=process.cwd(),n="claude",r=Vo()){return[...Yo(e,t,n,r).values()].map(o=>o.declared)}function Xo(e,t,n=process.cwd(),r="claude",o=Vo()){let s=Yo(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(An(a,e))return c.config??null;return null}function On(e){return e!==void 0&&Hr.includes(e)}function _t(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function ht(e){let t,n,r,o,s;for(let i=0;i<e.length;i++){let a=e[i];if(a!==void 0){if(a==="--runner"){let c=_t(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=_t(e,i);c.value&&(r=c.value),i=c.next;continue}if(a.startsWith("--url=")){r=a.slice(6);continue}if(a==="--token"){let c=_t(e,i);c.value&&(o=c.value),i=c.next;continue}if(a.startsWith("--token=")){o=a.slice(8);continue}if(a==="--base-url"){let c=_t(e,i);c.value&&(s=c.value),i=c.next;continue}if(a.startsWith("--base-url=")){s=a.slice(11);continue}!a.startsWith("-")&&n===void 0&&(n=a)}}return{runner:On(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function Pn(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=it(o,e.baseUrl?.trim()??void 0))}if(!n)return;let r=co(n);if(r){h(`WARN: ignoring --url/--token collector override: ${r}`);return}return uo(n)}function qo(e,t){if(m(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function ju(){return!!(I("CURSOR_VERSION")??I("CURSOR_PROJECT_DIR"))}function xn(e,t,n){return e!=="claude"&&e!=="codex"?!1:qo(t,n)?!0:ju()}function Ge(e,t,n,r){if(qo(e,t))return"cursor";if(On(r))return r;let o=m(e,"conversation_id"),s=m(e,"turn_id"),i=m(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion")&&(c="claude"),On(n)&&(c=n),c}function St(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Ku(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 Zo(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function Qo(e,t,n){let r=m(e,"session_id")||m(e,"conversation_id"),o=m(e,"prompt.id")||m(e,"prompt_id")||m(e,"generation_id")||m(e,"turn_id"),s=m(e,"hook_event_name")||m(e,"event"),i=m(e,"source"),a=Ge(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var $u=["session_start","session_end","tool_invoked","skill_invoked"];function Bu(e){return $u.includes(e)}function es(e,t){return e&&Bu(e)?e:Ku(t.toLowerCase())}var Gu={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function ts(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function ns(e,t=""){let n=m(e,"tool_name")||m(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!ts(n)&&(n=`MCP:${n}`):n=Gu[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?de(o.skill)||de(o.skill_name):"")||m(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=Io(a);let c=Ko(a),l=zo(a);return{toolName:n,skillName:i,ruleName:c,commandName:l}}var zu=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function rs(e){for(let t of["subagent_type","agent_type"]){let n=m(e,t);if(n&&zu.test(n))return n}return null}function os(e){let t=pe(e,"duration_ms");if(typeof t=="number")return t;let n=pe(e,"duration");return typeof n=="number"?n:null}var Wu="error",Ju="interrupted",Vu="permission_denied",Yu=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function ze(e){return Yu.test(e)?e:null}function Xu(e){for(let t of["failure_type","error_type"]){let n=ze(m(e,t));if(n)return n}return null}function ss(e,t){return pe(e,"is_interrupt")===!0?Ju:t.toLowerCase()==="permissiondenied"?Vu:Xu(e)??Wu}function qu(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 Zu(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 Qu(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of In(s)){let a=`${i}__`;e.length>a.length&&e.slice(0,a.length).toLowerCase()===a.toLowerCase()&&i.length>r&&(n={mcpServer:s,mcpTool:e.slice(a.length)},r=i.length)}if(n!==null)return n;let o=/^(.+?)__(.+)$/.exec(e);return!o?.[1]||!o[2]?{mcpServer:null,mcpTool:null}:{mcpServer:Zu(o[1],t)??o[1],mcpTool:o[2]}}function el(e,t){if(/^mcp__/i.test(e))return Qu(e.slice(5),t);if(/^MCP:/i.test(e)){let n=e.slice(4);if(!n)return{mcpServer:null,mcpTool:null};let r=n.indexOf(":");if(r>0)return{mcpServer:n.slice(0,r),mcpTool:n.slice(r+1)||null};let o=n.indexOf("__");return o>0?{mcpServer:n.slice(0,o),mcpTool:n.slice(o+2)||null}:{mcpServer:qu(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function tl(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function is(e,t=[],n=""){let r=e?el(e,t):{mcpServer:null,mcpTool:null},o=ze(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!ts(e)&&(s=e),s&&(s=tl(s,o)),{mcpServer:o,mcpTool:s}}var ls=3e4,al="claims",cl=!0,ul=100,ll=new Set(["sessionstart","sessionend","stopfailure"]),dl=["tool_name","tool","command","file_path","url"];function pl(e=us()){return Tn(fe(e),al)}function ds(e){let t=e.split(`
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: cloud cache write failed open: ${r}`)}}function Tl(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?kl:Al;return n-e.probed_at<r}async function bl(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 vl(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 Ml(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 wl(e){let t=await Promise.allSettled([bl(e),vl(e),Ml(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function bn(e,t){if(e==="interactive")return null;let n=t?.home??ms(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Ol(n),i=Pl(s);if(Tl(i,e,o))return i.result;let a=await wl(r);return xl(s,{context:e,probed_at:o,result:a}),a}var Nl=["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"],Ll=["CURSOR_PROJECT_DIR"],Ul=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function Dl(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Ul.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function vn(e=process.env){let t=Nl.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:Dl(e[r]??"")}:{name:r,present:!1}),n=Ll.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as fd}from"node:os";import{homedir as gs}from"node:os";import{join as Hl}from"node:path";function Fl(e=gs()){return Hl(e,".claude.json")}function Et(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function _s(e=gs()){let n=L(Fl(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=Et(n.emailAddress),o=Et(n.fullName)??Et(n.displayName),s=Et(n.accountUuid),i=r??s;return!i||B(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as Es}from"node:os";import{join as hs}from"node:path";var jl="https://api.openai.com/auth";function Pe(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ys(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Kl(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 ys(r)}catch{return null}}function Ss(e,t,n){return Pe(e[n])??Pe(t?.[n])}function $l(e=process.env,t=Es()){let n=Pe(e.CODEX_HOME)??hs(t,".codex");return hs(n,"auth.json")}function Rs(e=process.env,t=Es()){let n=L($l(e,t),{}),r=Pe(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&Pe(n.OPENAI_API_KEY))return null;let o=Pe(n.tokens?.id_token);if(!o)return null;let s=Kl(o);if(!s)return null;let i=ys(s[jl]),a=Ss(s,i,"name"),c=Ss(s,i,"email");return!c||B(a,c)?null:{git_user_name:null,git_user_email:null,platform_login:c,identity_source:"codex_oauth"}}import{homedir as Ct}from"node:os";import{join as te}from"node:path";import{join as Bl}from"node:path";var Gl="cursor-ide-identity.json",zl=De;function Is(e){return Bl(fe(e),Gl)}function Cs(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function As(e){let t=L(e,{}),n=t.read_at_ms,r=t.db_path;if(!(typeof n!="number"||!Number.isFinite(n)||typeof r!="string"))return{read_at_ms:n,db_path:r,email:Cs(t.email),auth_id:Cs(t.auth_id)}}function ks(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<zl}function Os(e,t){try{Y(e,`${JSON.stringify(t)}
|
|
14
|
-
`)}catch(
|
|
4
|
+
var gc=Object.create;var Yr=Object.defineProperty;var _c=Object.getOwnPropertyDescriptor;var hc=Object.getOwnPropertyNames;var Ec=Object.getPrototypeOf,Sc=Object.prototype.hasOwnProperty;var sn=(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 he=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var yc=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of hc(t))!Sc.call(e,o)&&o!==n&&Yr(e,o,{get:()=>t[o],enumerable:!(r=_c(t,o))||r.enumerable});return e};var je=(e,t,n)=>(n=e!=null?gc(Ec(e)):{},yc(t||!e||!e.__esModule?Yr(n,"default",{value:e,enumerable:!0}):n,e));var Ot=he(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.MCP_MISSING_LAUNCH_SERIALIZED=N.MCP_LAUNCH_IDENTITY_ALGORITHM=void 0;N.foldMcpName=cs;N.buildMcpFamilyCanonicalKey=Zu;N.launchContainsCredentials=Qu;N.serializeMcpLaunchIdentity=us;N.hashMcpLaunchIdentity=Ye;N.projectMcpMissingLaunchIdentity=nl;N.projectMcpLaunchIdentity=rl;N.maskMcpLaunchForDisplay=sl;N.normalizeMcpToolNames=il;var Xu=sn("node:crypto");N.MCP_LAUNCH_IDENTITY_ALGORITHM="mcp-launch-v1";N.MCP_MISSING_LAUNCH_SERIALIZED=`${N.MCP_LAUNCH_IDENTITY_ALGORITHM}|missing`;function se(e){return e.toLocaleLowerCase("en-US")}function cs(e){return se(e)}function Zu(e){return`interface:${cs(e)}`}var as=new Set(["access_token","api_key","apikey","auth","authorization","key","password","secret","token"]),qu=/^(?:--?(?:token|api[-_]?key|password|secret|authorization)(?:=|\s+)|(?:sk-|ghp_|xox[baprs]-|Bearer\s+))/i;function be(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Qu(e){return e.kind==="url"?el(e.url):e.kind==="command"?e.arguments.some(t=>qu.test(t)):!1}function el(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(as.has(se(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=se(i.split("=",1)[0]??"");return as.has(a)})}}function us(e){if(e.kind==="url")return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"url",be(se(e.url))].join("|");if(e.kind==="command"){let t=[...e.arguments].map(n=>se(n)).sort((n,r)=>n<r?-1:n>r?1:0);return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"command",be(se(e.command)),String(t.length),...t.map(be)].join("|")}return[N.MCP_LAUNCH_IDENTITY_ALGORITHM,"unknown",be(e.installationRootExternalKey),be(e.sourcePath),be(e.nativeKey)].join("|")}function Ye(e){return(0,Xu.createHash)("sha256").update(e).digest("hex")}var tl=Ye(N.MCP_MISSING_LAUNCH_SERIALIZED);function nl(){return{kind:"unknown",arguments:[],serialized:N.MCP_MISSING_LAUNCH_SERIALIZED,contentHash:tl}}function rl(e){let t=us(e);return e.kind==="url"?{kind:"url",url:se(e.url),arguments:[],serialized:t,contentHash:Ye(t)}:e.kind==="command"?{kind:"command",command:se(e.command),arguments:[...e.arguments].map(n=>se(n)).sort((n,r)=>n<r?-1:n>r?1:0),serialized:t,contentHash:Ye(t)}:{kind:"unknown",arguments:[],serialized:t,contentHash:Ye(t)}}var ol=/^(https?:\/\/)([^/?#]*@)/i;function sl(e){return e.replace(ol,"$1***@").replace(/([?&](?:access_token|api_key|apikey|auth|authorization|key|password|secret|token)=)([^&]*)/gi,"$1***")}function il(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 Tt=he(Q=>{"use strict";Object.defineProperty(Q,"__esModule",{value:!0});Q.PACKAGE_FIELD_MAX=void 0;Q.npxExecBin=ls;Q.packageNameFromSpec=Pt;Q.pinnedPackageVersionFromSpec=ds;Q.pinnedPackageVersionFromNpx=gl;Q.npxPackageSpecs=ps;Q.PACKAGE_FIELD_MAX=128;var al=/^(?:@[A-Za-z0-9~-][A-Za-z0-9._~-]*\/)?[A-Za-z0-9~-][A-Za-z0-9._~-]*$/,cl=new Set(["-p","--package"]),ul=new Set(["-c","--call"]),ll=new Set(["--registry","--userconfig","--globalconfig","--prefix","--cache","--node-options","--workspace","-w","--loglevel"]),dl=new Set(["-y","--yes","-n","--no","-q","-s","--quiet","--silent","--offline","--prefer-offline","--prefer-online","--ignore-existing","--ignore-scripts","--legacy-peer-deps","--foreground-scripts"]),pl=/^--no-/;function fl(e){return dl.has(e)||pl.test(e)}function ls(e){let n=(e.replace(/\\/g,"/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="npx"?"npx":n==="npm"?"npm":null}var ml=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/;function Pt(e){if(e.length===0||e.length>Q.PACKAGE_FIELD_MAX)return null;let t=e.lastIndexOf("@"),n=t>0?e.slice(0,t):e;return al.test(n)?n:null}function ds(e){let t=Pt(e);if(t===null||!e.startsWith(`${t}@`))return;let n=e.slice(t.length+1);return ml.test(n)?n:void 0}function gl(e,t){for(let n of ps(e,t)){let r=ds(n);if(r!==void 0)return r}}function ps(e,t){let n=ls(e);if(n===null)return[];let r=[...t];if(n==="npm"){let i=r[0]?.toLowerCase();if(i!=="exec"&&i!=="x")return[];r=r.slice(1)}let o=[],s=null;for(let i=0;i<r.length;i+=1){let a=r[i]??"";if(a==="--"){s=r[i+1]??null;break}if(!a.startsWith("-")){s=a;break}let c=a.indexOf("="),u=c===-1?a:a.slice(0,c);if(ul.has(u))return[];if(cl.has(u)){let l=c===-1?r[i+1]:a.slice(c+1);l!==void 0&&l.length>0&&o.push(l),c===-1&&(i+=1);continue}if(!(c!==-1||fl(u))){if(ll.has(u)){i+=1;continue}return[]}}return o.length>0?o.every(i=>Pt(i)!==null)?o:[]:s===null||Pt(s)===null?[]:[s]}});var fs=he(Re=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.McpPackageEcosystem=void 0;Re.resolveMcpPackageIdentity=kl;var _l=Ot(),Un=Tt();Re.McpPackageEcosystem={NPM:"npm",PYPI:"pypi"};var hl=/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/,El=/^[A-Za-z0-9](?:[A-Za-z0-9._-]*[A-Za-z0-9])?$/,Sl=/^(?:\d+!)?\d+(?:\.\d+)*(?:(?:a|b|rc)\d+)?(?:\.post\d+)?(?:\.dev\d+)?(?:\+[0-9A-Za-z]+(?:[.][0-9A-Za-z]+)*)?$/;function yl(e){let n=(e.replaceAll("\\","/").split("/").pop()??"").replace(/\.(cmd|exe|bat|ps1)$/i,"").toLowerCase();return n==="uvx"||n==="uv"||n==="pipx"?n:null}var Rl=new Set(["--from","--spec"]),Cl=new Set(["--python","-p","--with","--with-editable","--with-requirements","--index","--index-url","--default-index","--extra-index-url","--find-links","-f","--constraint","-c","--override","--refresh-package","--cache-dir","--directory","--project","--config-file","--color","--exclude-newer","--pip-args","--verbose-pip"]),Il=new Set(["-q","--quiet","-v","--verbose","-n","--native-tls","--offline","--isolated","--preview","--refresh","--reinstall","--upgrade","-U","--force","--system","--system-site-packages","--path","--managed-python","--progress"]),Al=/^--no-/;function Ol(e,t){let n=yl(e);if(n===null)return null;let r=[...t];if(n==="uv"){if(r[0]?.toLowerCase()!=="tool"||r[1]?.toLowerCase()!=="run")return null;r=r.slice(2)}else if(n==="pipx"){if(r[0]?.toLowerCase()!=="run")return null;r=r.slice(1)}let o=null,s=null;for(let i=0;i<r.length;i+=1){let a=r[i]??"";if(a==="--"){s=r[i+1]??null;break}if(!a.startsWith("-")){s=a;break}let c=a.indexOf("="),u=c===-1?a:a.slice(0,c);if(Rl.has(u)){let l=c===-1?r[i+1]:a.slice(c+1);l!==void 0&&l.length>0&&(o=l),c===-1&&(i+=1);continue}if(!(c!==-1||Il.has(u)||Al.test(u))){if(Cl.has(u)){i+=1;continue}return null}}return o??s}function Pl(e){if(e.length===0||e.length>Un.PACKAGE_FIELD_MAX)return null;let t=e.includes("==")?"==":e.includes("@")?"@":null;if(t===null)return null;let n=e.indexOf(t),r=e.slice(0,n),o=e.slice(n+t.length);return!El.test(r)||!Sl.test(o)?null:{ecosystem:Re.McpPackageEcosystem.PYPI,packageName:r,version:o}}function Tl(e){let t=(0,Un.packageNameFromSpec)(e);if(t===null||!e.startsWith(`${t}@`))return null;let n=e.slice(t.length+1);return hl.test(n)?{ecosystem:Re.McpPackageEcosystem.NPM,packageName:t,version:n}:null}function kl(e){if(e?.kind!=="command"||(0,_l.launchContainsCredentials)(e))return;for(let n of(0,Un.npxPackageSpecs)(e.command,e.arguments)){let r=Tl(n);if(r!==null)return r}let t=Ol(e.command,e.arguments);if(t!==null)return Pl(t)??void 0}});var Ss=he(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.EMPTY_NPM_PUBLISHER=void 0;ie.isNpmRegistryPublisher=bl;ie.displayPublisherName=Nl;ie.classifyMcpProvenance=jl;var _s=Ot(),Dn=Tt();ie.EMPTY_NPM_PUBLISHER="npm:";var ms="npm:",xl=/^[A-Za-z0-9._-]+$/;function bl(e){return e.startsWith(ms)&&e!==ie.EMPTY_NPM_PUBLISHER&&xl.test(e.slice(ms.length))}function Nl(e){if(!(e==null||e===""||e===ie.EMPTY_NPM_PUBLISHER))return e}function gs(e){let t=e.split(".").map(Number);return t.length!==4||t.some(n=>!Number.isInteger(n)||n<0||n>255)?!1:t[0]===0||t[0]===10||t[0]===127||t[0]===169&&t[1]===254||t[0]===172&&(t[1]??0)>=16&&(t[1]??0)<=31||t[0]===192&&t[1]===168}function Ml(e){let t=/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i.exec(e);if(t?.[1])return t[1];let n=/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i.exec(e);if(!n)return;let r=Number.parseInt(n[1],16),o=Number.parseInt(n[2],16);return`${r>>8&255}.${r&255}.${o>>8&255}.${o&255}`}function Fn(e){return e.toLowerCase().replace(/^\[|\]$/g,"").replace(/\.$/,"")}function vl(e){let t=Fn(e),n=Ml(t);return t==="localhost"||t.endsWith(".localhost")||t==="::1"||t.endsWith(".local")||!t.includes(".")&&!t.includes(":")||gs(t)||n!==void 0&&gs(n)||/^(?:fc|fd)[0-9a-f]{2}:/i.test(t)||/^fe[89ab][0-9a-f]:/i.test(t)}function wl(e){let t=Fn(e);return t.includes(":")||/^[0-9.]+$/.test(t)||t.split(".").filter(Boolean).length<2?null:t}function Ll(e){let t=Fn(e.hostname),n=t.includes(":")?`[${t}]`:t,r=e.port?`:${e.port}`:"";return`${e.protocol}//${n}${r}`}function hs(e){let t={kind:"url",url:e};if((0,_s.launchContainsCredentials)(t))return{origin:"UNKNOWN"};try{let n=new URL(e);if(!["http:","https:"].includes(n.protocol)||vl(n.hostname))return{origin:"UNKNOWN"};let r=wl(n.hostname);return{origin:"THIRD_PARTY",...r===null?{}:{publisherName:r},packageSourceUrl:Ll(n)}}catch{return{origin:"UNKNOWN"}}}var Es="mcp-remote";function Ul(e,t){if(e===Es)return t.find(n=>/^https?:\/\//i.test(n))}function Dl(e,t){return{origin:"THIRD_PARTY",...t?{publisherName:t}:{},packageName:e,packageKey:e}}function Fl(e,t,n){let r=Ul(e,t);return r!==void 0?hs(r):e===Es?{origin:"UNKNOWN"}:Dl(e,n)}function Hl(e){let t=e.replaceAll("\\","/");return t.startsWith("~/")||t.startsWith("/")||/^[A-Za-z]:\//.test(t)?!1:t.startsWith("./")||t.startsWith("../")||t==="scripts"||t.startsWith("scripts/")}function jl(e){let t=e.launch;if(t===void 0||t.kind==="unknown")return{origin:"UNKNOWN"};if((0,_s.launchContainsCredentials)(t))return{origin:"UNKNOWN"};if(t.kind==="url")return hs(t.url);let r=(0,Dn.npxPackageSpecs)(t.command,t.arguments)[0];if(r!==void 0){let o=(0,Dn.packageNameFromSpec)(r);if(o===null)return{origin:"UNKNOWN"};let s=Fl(o,t.arguments,e.publisherName),i=typeof e.packageName=="string"?(0,Dn.packageNameFromSpec)(e.packageName):null;return i!==null&&i===o&&s.packageName!==void 0?{...s,packageName:i,packageKey:i}:s}return Hl(t.command)?{origin:"INTERNAL"}:{origin:"UNKNOWN"}}});var ys=he(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.parseFrontmatterField=J.parseFrontmatterDescription=J.usableCatalogText=void 0;var Kl=/^(?:>|\|)[-+]?$/,$l=/^(?:>|\|)[-+]?(?:\s+(.*))?$/,Bl=e=>{let t=e?.trim()??"";if(!(t.length===0||Kl.test(t)))return t};J.usableCatalogText=Bl;var Gl=e=>(0,J.parseFrontmatterField)(e,"description");J.parseFrontmatterDescription=Gl;var zl=(e,t)=>{let n=/^---\s*\n([\s\S]*?)\n---/.exec(e);if(n)return Wl(n[1],t)};J.parseFrontmatterField=zl;var Vl=e=>e.replace(/^["']|["']$/g,"");function Wl(e,t){let n=e.split(`
|
|
5
|
+
`),r=`${t}:`,o=n.findIndex(d=>d===r||d.startsWith(`${r} `)||d.startsWith(`${r} `));if(o<0)return;let s=(n[o]??"").slice(r.length).trim(),i=$l.exec(s);if(!i){let d=Vl(s).trim();return(0,J.usableCatalogText)(d)}let a=[];for(let d=o+1;d<n.length;d+=1){let g=n[d]??"";if(g.trim()===""){a.push("");continue}if(g.length===g.trimStart().length)break;a.push(g)}let c=a.reduce((d,g)=>g.trim()===""?d:Math.min(d,g.length-g.trimStart().length),Number.POSITIVE_INFINITY),u=[],l=i[1]?.trim();l&&u.push(l);for(let d of a)u.push(d.trim()===""?"":d.slice(c));for(;u.length>0&&u[u.length-1]==="";)u.pop();let m=s.startsWith(">")?u.join(`
|
|
6
|
+
`).split(/\n{2,}/).map(d=>d.split(`
|
|
7
|
+
`).map(g=>g.trim()).filter(Boolean).join(" ")).filter(d=>d.length>0).join(`
|
|
8
|
+
|
|
9
|
+
`):u.join(`
|
|
10
|
+
`).trimEnd();return(0,J.usableCatalogText)(m)}});var As=he(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=T.COMPONENT_INSPECTION_TEXT_MAX_BYTES=T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=void 0;T.fitSnapshotInspectionTextBudget=Yl;T.capComponentTextBytes=Cs;T.prepareComponentInspectionText=Jl;T.redactComponentSource=jn;T.componentSourceContainsRedactableSecret=ld;T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER="[REDACTED]";T.COMPONENT_INSPECTION_TEXT_MAX_BYTES=256*1024;T.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=3*1024*1024;function Yl(e){let t=0;return e.map(n=>{let r=n,o=r.skill?.inspectionText;if(o===void 0)return n;let s=Buffer.byteLength(o,"utf8");return t+s<=T.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES?(t+=s,n):{...n,skill:{...r.skill,inspectionText:void 0}}})}function Cs(e,t){if(e==null||e.length===0)return;let n=Buffer.from(e,"utf8");if(n.byteLength<=t)return e;let r=new TextDecoder("utf-8",{fatal:!0});for(let o=t;o>0;o-=1)try{return r.decode(n.subarray(0,o))}catch{}}function Jl(e){if(!(e==null||e.length===0))return Cs(jn(e),T.COMPONENT_INSPECTION_TEXT_MAX_BYTES)}var Xl="(?:[A-Za-z0-9_.-]*(?:passwd|password|secret|token|credential|credentials|apikey|api[_-]?key|access[_-]?key|secret[_-]?key|private[_-]?key|auth|authorization|session[_-]?id)[A-Za-z0-9_.-]*)",Zl=new RegExp(`(\\b${Xl})(\\s*[:=]\\s*)(?:(")([^"\\n]*)(")|(')([^'\\n]*)(')|([^\\s"'][^"'\\n]*))`,"gi"),ql=[/^(?:none|null|nil|n\/a|empty|unset|not (?:required|needed|set)|no (?:password|token|auth))(?=$|[\s.,;:()—–-])/i,/^\$\{?[A-Za-z_][A-Za-z0-9_]*\}?$/,/^\$\(.*\)$/,/^\$\{\{.*\}\}$/,/^%[A-Za-z_][A-Za-z0-9_]*%$/,/^(?:process\.env|os\.environ|import\.meta\.env)\.[A-Za-z_][A-Za-z0-9_]*[,;]?$/,/^<[^<>]*>$/,/^(?:\*{3,}|\.{3,}|…|x{3,})$/i,/^your[-_ ]/i,/^(?:see|from|via|stored in|use|ask|obtain|get|fetch|run|read|provided by|generated by)\b/i];function Hn(e){let t=e.trim().replace(/^`+|`+$/g,"").trim();return ql.some(n=>n.test(t))}function Ql(e){if(e.startsWith("$(")){let n=0;for(let r=1;r<e.length;r+=1)if(e[r]==="("&&(n+=1),e[r]===")"&&(n-=1,n===0))return e.slice(0,r+1);return e}return/^(?:\$\{\{[^}]*\}\}|<[^<>]*>)/.exec(e)?.[0]??/^\S+/.exec(e)?.[0]??""}var ed=[/\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}/g,/\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,/\bgithub_pat_[A-Za-z0-9_]{20,}/g,/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g,/\bAIza[0-9A-Za-z_-]{35}\b/g,/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g],td=/\b[A-Za-z0-9_+/-]{32,}={0,2}\b/g,nd=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;function rd(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function od(e){return e.replace(td,t=>{if(nd.test(t))return t;let n=/[A-Za-z]/.test(t),r=/\d/.test(t);return n&&r&&rd(t)>=3.5?T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:t})}var sd=/\b(Bearer\s+)[A-Za-z0-9._~+/=-]{8,}/gi,id=/\b([a-z][a-z0-9+.-]*:\/\/)([^\s/@:]+):([^\s/@]*)@/gi,ad=/([?&](?:access_token|api_key|apikey|auth|authorization|client_secret|key|password|secret|token)=)[^&\s"'<>]+/gi,cd=/-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/,Rs=/-----END [A-Z0-9 ]*PRIVATE KEY-----/;function Is(e){return e.replace(Zl,(t,n,r,o,s,i,a,c,u,l)=>{let p=`${n}${r}`;if(o!==void 0||a!==void 0){let d=o??a??"",g=i??u??"",E=s??c??"";return E===""||E.includes(T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Hn(E)?t:`${p}${d}${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${g}`}let m=l??"";if(r==="="){let d=Ql(m).replace(/`+$/,""),g=Is(m.slice(d.length));return d===""||d.includes(T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Hn(d)?`${p}${d}${g}`:`${p}${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}${g}`}return m.includes(T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER)||Hn(m)?t:`${p}${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`})}function ud(e){let t=e.replace(id,(n,r)=>`${r}${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}:${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}@`);t=t.replace(ad,(n,r)=>`${r}${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`),t=t.replace(sd,(n,r)=>`${r}${T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}`);for(let n of ed)t=t.replace(n,T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER);return Is(od(t))}function jn(e){if(e.length===0)return e;let t=e.split(`
|
|
11
|
+
`),n=!1;return t.map(o=>n?Rs.test(o)?(n=!1,o):o.trim().length===0?o:T.COMPONENT_SOURCE_REDACTION_PLACEHOLDER:cd.test(o)&&!Rs.test(o)?(n=!0,o):ud(o)).join(`
|
|
12
|
+
`)}function ld(e){return jn(e)!==e}});var Me=he(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.redactComponentSource=f.prepareComponentInspectionText=f.fitSnapshotInspectionTextBudget=f.componentSourceContainsRedactableSecret=f.capComponentTextBytes=f.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES=f.COMPONENT_SOURCE_REDACTION_PLACEHOLDER=f.COMPONENT_INSPECTION_TEXT_MAX_BYTES=f.usableCatalogText=f.parseFrontmatterField=f.parseFrontmatterDescription=f.isNpmRegistryPublisher=f.EMPTY_NPM_PUBLISHER=f.displayPublisherName=f.classifyMcpProvenance=f.resolveMcpPackageIdentity=f.McpPackageEcosystem=f.pinnedPackageVersionFromSpec=f.pinnedPackageVersionFromNpx=f.packageNameFromSpec=f.npxPackageSpecs=f.npxExecBin=f.PACKAGE_FIELD_MAX=f.serializeMcpLaunchIdentity=f.projectMcpMissingLaunchIdentity=f.projectMcpLaunchIdentity=f.normalizeMcpToolNames=f.MCP_MISSING_LAUNCH_SERIALIZED=f.MCP_LAUNCH_IDENTITY_ALGORITHM=f.maskMcpLaunchForDisplay=f.launchContainsCredentials=f.hashMcpLaunchIdentity=f.foldMcpName=f.buildMcpFamilyCanonicalKey=f.ComponentKind=void 0;f.userConfigRootFromPath=yd;f.installationRootExternalKey=Rd;f.normalizeRepositoryRelativePath=Os;f.nativeKeyForSkillPath=Cd;f.nativeKeyForRulePath=Id;f.nativeKeyForCommandPath=Ad;f.serializeComponentIdentity=Ts;f.buildComponentReference=Pd;f.validateComponentReference=Td;var dd=sn("node:crypto"),pd=sn("node:path"),fd="cmp1_",md=/^cmp1_[A-Za-z0-9_-]{43}$/,gd=["/skills/","/skills-cursor/"],_d=/(?:^|\/)\.(?:cursor|claude|codex)\/rules\/(.+)$/i,hd=/(?:^|\/)\.(?:cursor|claude|codex)\/(?:commands|prompts)\/(.+)$/i,Ed=[".cursor",".claude",".codex"],Sd={".claude.json":".claude",".agents":".codex"};f.ComponentKind={SKILL:"SKILL",INTERFACE:"INTERFACE",RULE:"RULE",COMMAND:"COMMAND"};function yd(e){let t=e.replaceAll("\\","/").split("/").filter(Boolean),n=t.find(o=>Ed.includes(o));return n||(t.map(o=>Sd[o]).find(o=>o!==void 0)??"unknown")}function Rd(e,t){return`runtime-install:${e}/${t}`}function kt(e,t){if(e.length===0)throw new Error(`${t} is required`);return e}function Os(e){let t=e.replaceAll("\\","/");if(t.startsWith("/")||/^[A-Za-z]:\//.test(t))throw new Error("sourcePath must be repository-relative");let n=pd.posix.normalize(t).replace(/^\.\//,"");if(n==="."||n===".."||n.startsWith("../"))throw new Error("sourcePath must be repository-relative");return kt(n,"sourcePath")}function Cd(e){let t=e.replaceAll("\\","/");for(let n of gd){let r=t.split(n)[1]?.split("/")[0];if(r&&r.length>0)return r}return null}function Ps(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 Id(e){return Ps(e,_d,/\.(mdc|md|rules)$/i)}function Ad(e){return Ps(e,hd,/\.(md|mdc|toml)$/i)}function Od(e){return`${Buffer.byteLength(e,"utf8")}:${e}`}function Ts(e){let t=[kt(e.installationRootExternalKey,"installationRootExternalKey"),kt(e.installableKind,"installableKind"),Os(e.sourcePath),kt(e.nativeKey,"nativeKey")];return Buffer.from(`1|${t.map(Od).join("|")}`,"utf8")}function Pd(e){let t=(0,dd.createHash)("sha256").update(Ts(e)).digest("base64url");return`${fd}${t}`}function Td(e){return md.test(e)}var X=Ot();Object.defineProperty(f,"buildMcpFamilyCanonicalKey",{enumerable:!0,get:function(){return X.buildMcpFamilyCanonicalKey}});Object.defineProperty(f,"foldMcpName",{enumerable:!0,get:function(){return X.foldMcpName}});Object.defineProperty(f,"hashMcpLaunchIdentity",{enumerable:!0,get:function(){return X.hashMcpLaunchIdentity}});Object.defineProperty(f,"launchContainsCredentials",{enumerable:!0,get:function(){return X.launchContainsCredentials}});Object.defineProperty(f,"maskMcpLaunchForDisplay",{enumerable:!0,get:function(){return X.maskMcpLaunchForDisplay}});Object.defineProperty(f,"MCP_LAUNCH_IDENTITY_ALGORITHM",{enumerable:!0,get:function(){return X.MCP_LAUNCH_IDENTITY_ALGORITHM}});Object.defineProperty(f,"MCP_MISSING_LAUNCH_SERIALIZED",{enumerable:!0,get:function(){return X.MCP_MISSING_LAUNCH_SERIALIZED}});Object.defineProperty(f,"normalizeMcpToolNames",{enumerable:!0,get:function(){return X.normalizeMcpToolNames}});Object.defineProperty(f,"projectMcpLaunchIdentity",{enumerable:!0,get:function(){return X.projectMcpLaunchIdentity}});Object.defineProperty(f,"projectMcpMissingLaunchIdentity",{enumerable:!0,get:function(){return X.projectMcpMissingLaunchIdentity}});Object.defineProperty(f,"serializeMcpLaunchIdentity",{enumerable:!0,get:function(){return X.serializeMcpLaunchIdentity}});var Ne=Tt();Object.defineProperty(f,"PACKAGE_FIELD_MAX",{enumerable:!0,get:function(){return Ne.PACKAGE_FIELD_MAX}});Object.defineProperty(f,"npxExecBin",{enumerable:!0,get:function(){return Ne.npxExecBin}});Object.defineProperty(f,"npxPackageSpecs",{enumerable:!0,get:function(){return Ne.npxPackageSpecs}});Object.defineProperty(f,"packageNameFromSpec",{enumerable:!0,get:function(){return Ne.packageNameFromSpec}});Object.defineProperty(f,"pinnedPackageVersionFromNpx",{enumerable:!0,get:function(){return Ne.pinnedPackageVersionFromNpx}});Object.defineProperty(f,"pinnedPackageVersionFromSpec",{enumerable:!0,get:function(){return Ne.pinnedPackageVersionFromSpec}});var ks=fs();Object.defineProperty(f,"McpPackageEcosystem",{enumerable:!0,get:function(){return ks.McpPackageEcosystem}});Object.defineProperty(f,"resolveMcpPackageIdentity",{enumerable:!0,get:function(){return ks.resolveMcpPackageIdentity}});var xt=Ss();Object.defineProperty(f,"classifyMcpProvenance",{enumerable:!0,get:function(){return xt.classifyMcpProvenance}});Object.defineProperty(f,"displayPublisherName",{enumerable:!0,get:function(){return xt.displayPublisherName}});Object.defineProperty(f,"EMPTY_NPM_PUBLISHER",{enumerable:!0,get:function(){return xt.EMPTY_NPM_PUBLISHER}});Object.defineProperty(f,"isNpmRegistryPublisher",{enumerable:!0,get:function(){return xt.isNpmRegistryPublisher}});var Kn=ys();Object.defineProperty(f,"parseFrontmatterDescription",{enumerable:!0,get:function(){return Kn.parseFrontmatterDescription}});Object.defineProperty(f,"parseFrontmatterField",{enumerable:!0,get:function(){return Kn.parseFrontmatterField}});Object.defineProperty(f,"usableCatalogText",{enumerable:!0,get:function(){return Kn.usableCatalogText}});var me=As();Object.defineProperty(f,"COMPONENT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return me.COMPONENT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(f,"COMPONENT_SOURCE_REDACTION_PLACEHOLDER",{enumerable:!0,get:function(){return me.COMPONENT_SOURCE_REDACTION_PLACEHOLDER}});Object.defineProperty(f,"SNAPSHOT_INSPECTION_TEXT_MAX_BYTES",{enumerable:!0,get:function(){return me.SNAPSHOT_INSPECTION_TEXT_MAX_BYTES}});Object.defineProperty(f,"capComponentTextBytes",{enumerable:!0,get:function(){return me.capComponentTextBytes}});Object.defineProperty(f,"componentSourceContainsRedactableSecret",{enumerable:!0,get:function(){return me.componentSourceContainsRedactableSecret}});Object.defineProperty(f,"fitSnapshotInspectionTextBudget",{enumerable:!0,get:function(){return me.fitSnapshotInspectionTextBudget}});Object.defineProperty(f,"prepareComponentInspectionText",{enumerable:!0,get:function(){return me.prepareComponentInspectionText}});Object.defineProperty(f,"redactComponentSource",{enumerable:!0,get:function(){return me.redactComponentSource}})});import{existsSync as kc,readFileSync as xc}from"node:fs";import{hostname as no,userInfo as bc}from"node:os";import{randomBytes as Rc}from"node:crypto";import{existsSync as cn,mkdirSync as Cc,readdirSync as Ic,readFileSync as Ac,renameSync as Jr,statSync as qr,unlinkSync as Xr,writeFileSync as Oc}from"node:fs";import{basename as Pc,dirname as Zr,join as Qr,relative as Tc}from"node:path";function h(e){process.stderr.write(`[ev-ai-agent-hook] ${e}
|
|
13
|
+
`)}function Z(e,t){Cc(Zr(e),{recursive:!0});let n=Qr(Zr(e),`.${Pc(e)}.${process.pid}.${Rc(4).toString("hex")}.tmp`);try{Oc(n,t,"utf8");try{Jr(n,e)}catch(r){let o=r instanceof Error&&"code"in r?r.code:void 0;if(o==="EEXIST"||o==="EPERM"||o==="EACCES"){Xr(e),Jr(n,e);return}throw r}}catch(r){try{Xr(n)}catch{}throw r}}function ft(){return new Date().toISOString().replace(/\.\d{3}Z$/,"Z")}function eo(){process.stdout.write('{"continue":true}')}function I(e){let t=process.env[e];return t===void 0||t===""?void 0:t}async function un(){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 ln(e){return new Promise(t=>{let n="",r=!1,o=i=>{r||(r=!0,clearTimeout(s),t(i||"{}"))},s=setTimeout(()=>{o(n)},e);if(process.stdin.isTTY){o("{}");return}process.stdin.setEncoding("utf8"),process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>{o(n)}),process.stdin.on("error",()=>{o(n)}),process.stdin.resume()})}async function Y(e,t,n=3e3,r={}){let{execFile:o}=await import("node:child_process"),{promisify:s}=await import("node:util"),i=s(o);try{let{stdout:a}=await i(e,t,{timeout:n,windowsHide:!0,maxBuffer:1048576,cwd:r.cwd});return{ok:!0,stdout:a.trim()}}catch(a){let c=a,u=typeof c.code=="number"?c.code:typeof c.status=="number"?c.status:void 0;return{ok:!1,code:u,spawnFailed:u===void 0}}}async function w(e,t,n=3e3,r={}){let o=await Y(e,t,n,r);return o.ok?o.stdout:""}async function dn(e=process.cwd()){let t=await Y("git",["rev-parse","--show-toplevel"],2e3,{cwd:e});if(t.ok&&t.stdout)return{root:t.stdout,inGitRepo:!0};if(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&&cn(n)){let r=await Y("git",["rev-parse","--show-toplevel"],2e3,{cwd:n});return r.ok&&r.stdout?{root:r.stdout,inGitRepo:!0}:{root:n,inGitRepo:!1}}return{root:e,inGitRepo:!1}}async function pn(e=process.cwd()){return(await dn(e)).root}function j(e,t){try{return JSON.parse(e)}catch{return t}}var an=new Map;function D(e,t){let n=an.get(e);if(n!==void 0)return n;try{let r=j(Ac(e,"utf8"),t);return an.set(e,r),r}catch{return an.set(e,t),t}}function Ee(e){return typeof e=="string"?e:""}function re(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 _(e,t){let n=re(e,t);return typeof n=="string"?n:""}var ue=500;function to(e,t=2){if(!cn(e))return{entries:[],truncated:!1};let n=[],r=!1,o=(s,i)=>{if(i>t||r)return;let a;try{a=Ic(s,{withFileTypes:!0})}catch{return}for(let c of a){if(r)return;let u=Qr(s,c.name);if(c.isDirectory()){o(u,i+1);continue}if(c.isFile()){try{n.push({name:Tc(e,u),size:qr(u).size})}catch{continue}if(n.length>=ue){r=!0;return}}}};return o(e,1),{entries:n,truncated:r}}function fn(e){return cn(e)?{present:!0,size:qr(e).size}:{present:!1,size:0}}function Pe(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function mn(e=process.env){return Pe(b("CURSOR_SANDBOX",e))}var Nc=["CIRCLECI","BUILDKITE","TF_BUILD","JENKINS_URL","JENKINS_HOME","CODEBUILD_BUILD_ID","DRONE","DRONE_BUILD_NUMBER","TEAMCITY_VERSION","TRAVIS","APPVEYOR","BITBUCKET_BUILD_NUMBER"];function Mc(e){return Nc.some(t=>!!b(t,e))}function vc(e){if(b("KUBERNETES_SERVICE_HOST",e)||Pe(b("REMOTE_CONTAINERS",e))||Pe(b("DEVCONTAINER",e)))return!0;try{if(kc("/.dockerenv")||xc("/proc/1/environ","utf8").includes("container="))return!0}catch{}return!1}function ro(e){return["VSCODE_PID","VSCODE_IPC_HOOK","CURSOR_EXTENSION_HOST_ROLE","CURSOR_WORKSPACE_LABEL"].some(t=>!!b(t,e))}function wc(e,t=process.platform){return ro(e)?t==="darwin"||t==="win32"?!0:["__CFBundleIdentifier","DISPLAY","WAYLAND_DISPLAY","SESSIONNAME"].some(n=>!!b(n,e)):!1}function Lc(e){return e===void 0?!1:e.trim().toLowerCase().startsWith("bc-")}function Uc(e){return e==="linux"}function b(e,t){if(t){let n=t[e];return n===void 0||n===""?void 0:n}return I(e)}function Dc(e,t,n){return e.trim().toLowerCase()==="cursor"&&t.trim().toLowerCase()==="ubuntu"&&!!Fc(b("CURSOR_VERSION",n))}function Fc(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function gn(e){if(Lc(e.sessionId))return!0;let t=e.hostname??no(),n=e.osUser??oo(e.env);return Dc(t,n,e.env)}function Hc(e){return Pe(b("CURSOR_AGENT",e.env))?!0:gn(e)}function jc(e){return!!(process.stdin.isTTY||process.stdout.isTTY||(b("TERM",e)??b("TERM_PROGRAM",e))||(b("SSH_TTY",e)??b("SSH_CONNECTION",e))||(b("__CFBundleIdentifier",e)??b("XPC_SERVICE_NAME",e))||ro(e)||["DISPLAY","WAYLAND_DISPLAY","XDG_SESSION_TYPE","DBUS_SESSION_BUS_ADDRESS"].some(t=>!!b(t,e))||b("SESSIONNAME",e))}function Ke(e={}){let t=e.env;if(b("GITHUB_ACTIONS",t))return"github_actions";if(Pe(b("CLAUDE_CODE_REMOTE",t)))return"claude_remote";let n=e.platform??process.platform;if(!wc(t,n)&&Hc(e)&&(Pe(b("CURSOR_AGENT",t))||Uc(n)))return"cursor_cloud";if(b("CODESPACES",t)||b("CODESPACE_NAME",t))return"codespaces";if(b("GITLAB_CI",t))return"gitlab_ci";if(Mc(t))return"managed";let r=b("CI",t);return r&&r!=="false"&&r!=="0"?"managed":vc(t)?"container":jc(t)?"interactive":"unknown"}async function _n(){return await w("systemd-detect-virt",[],1e3)}function oo(e=process.env,t=bc){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 hn(){let e=process.platform==="darwin"?"Darwin":process.platform==="win32"?"Windows_NT":"Linux",t="";if(process.platform==="darwin")t=await w("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 w("lsb_release",["-sd"],1e3).then(s=>s.replace(/^"|"$/g,""))}t||(t=await w("uname",["-r"],1e3))}else t=await w("ver",[],1e3);let n=oo(),r=(process.env.SHELL??"").split(/[/\\]/).pop()??"",o="";try{o=await w("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 $e(){return no()}import{createHash as Kc}from"node:crypto";import{homedir as $c}from"node:os";import{dirname as ih,join as Bc,parse as ah,resolve as ch}from"node:path";var io="https://hooks.ev-ai.ai",ao=".claude/ev-ai-runtime-report.json",co="config.json",uh=1024*1024,Gc=new Set(["localhost","127.0.0.1","[::1]","::1"]),zc=["claude","cursor","codex"],uo=[ao,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"],En=/^[A-Za-z0-9._~-]+$/;function gt(e){return e!==void 0&&zc.includes(e)}function mt(e,t){let n=e[t+1];return n&&!n.startsWith("--")?{value:n,next:t+1}:{next:t}}function Be(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=mt(e,i);t=c.value,i=c.next;continue}if(a.startsWith("--runner=")){t=a.slice(9);continue}if(a==="--url"){let c=mt(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=mt(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=mt(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:gt(t)?t:void 0,event:n,collectorUrl:r,orgToken:o,baseUrl:s}}function _t(e,t=io){let n=t.replace(/\/+$/,""),r=e.trim();return`${n}/${r}/hook`}function Sn(e=$c()){return Bc(e,".ev-ai",co)}function lo(e,t){return{...e,...t}}function so(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<=32||n===127||n===39)return!0}return!1}function Ge(e){try{let t=new URL(e);return t.protocol==="https:"?!0:t.protocol==="http:"?Gc.has(t.hostname):!1}catch{return!1}}function yn(e){try{let n=new URL(e).pathname.split("/").filter(r=>r.length>0);if(n.length>=2&&n[n.length-1]==="hook"){let r=n[n.length-2];return r&&r.length>0?r:void 0}return}catch{return}}function Rn(e){let t;try{t=new URL(e)}catch{return`invalid URL (got: ${e})`}if(!Ge(e))return`must be https (or http on localhost / 127.0.0.1 / ::1) (got: ${e})`;let n=yn(e);if(!n)return`must end with /{orgToken}/hook (got: ${e})`;if(!En.test(n))return`org token must match ${En.source} (got: ${n})`;if(so(e))return`must not contain whitespace, control characters, or single quotes (got: ${e})`;if(so(t.pathname))return`pathname must not contain whitespace, control characters, or single quotes (got: ${e})`}function po(e){return new URL(e).toString()}function Cn(e){if(e.collector_url)return e.collector_url;let t=e.repo_ingest_token,n=typeof t=="string"?t.trim():void 0;return n?_t(n):""}function ht(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 fo(e){let t=e.collectorUrl?.trim(),n;if(t)n=t;else{let o=e.orgToken?.trim();o&&(n=_t(o,e.baseUrl?.trim()??void 0))}if(!n)return{};let r=Rn(n);return r?{problem:r}:{url:po(n)}}function mo(e){if(Rn(e))return;let t;try{t=new URL(e)}catch{return}let n=yn(e);if(!n)return;let o=t.pathname.split("/").filter(a=>a.length>0).slice(0,-2),s=o.length>0?`/${o.join("/")}`:"",i=`${t.origin}${s}/${n}`;return Kc("sha256").update(i).digest("hex").slice(0,32)}var St=2;var go="EV_AI_LAUNCHER_VERSION";var _o="EV_AI_HOOK_SOURCE",ho="EV_AI_HOOK_FALLBACK_REASON",Eo="EV_AI_LAUNCHER_SCOPE",So="EV_AI_LAUNCHER_READY_FD";var Et="ev-ai-agent-hook";function Vc(e){let t=e.split(/[/\\]/).pop();return t&&t.length>0?t:e}function yo(e){let t=Vc(e);return t===Et||t===`${Et}.exe`}var dh=`current/${Et}`,ph=`.ev-ai/agent-hook/${Et}`,Ro=5e3,Co=5e3,In=3e3;var An=3e3,Io=1500,Ao=4*1024,On=256*1024,Wc=4*1024,Oo=32*1024,ze=840*60*1e3,Pn="1.2.0",fh=`@ev-ai/agent-hook@${Pn}`;import{createHash as op}from"node:crypto";import{existsSync as sp,mkdirSync as ip,readdirSync as ap,readFileSync as Qs,unlinkSync as ei,writeFileSync as cp}from"node:fs";import{homedir as ti}from"node:os";import{join as Xn}from"node:path";import{createHash as bo,randomBytes as Xc}from"node:crypto";import{existsSync as No,mkdirSync as Tn,readFileSync as Mo,unlinkSync as vo,writeFileSync as wo}from"node:fs";import{homedir as kn}from"node:os";import{dirname as yt,join as xn,resolve as Zc}from"node:path";var Yc=new Set(["action@github.com","noreply@github.com","noreply@anthropic.com","cursoragent@cursor.com"]),Jc=new Set(["github-actions","github actions","dependabot","renovate","cursoragent","cursor agent"]);function G(e,t){let n=(e??"").trim().toLowerCase(),r=(t??"").trim().toLowerCase();if(!n&&!r)return!1;if(n.includes("[bot]")||Jc.has(n)||r.includes("[bot]")||Yc.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 qc="installation.json",Qc="cloud-bootstrap.lock",eu=6e4;function Lo(e,t,n){let r=`${e}:${t??""}`;return n?`${n}:${r}`:r}function oe(e=kn()){return xn(e,".ev-ai","agent-hook")}function tu(e=kn()){return xn(oe(e),qc)}function Uo(e){return xn(yt(e),Qc)}function Do(){return Xc(8).toString("hex")}function Te(e){return bo("sha256").update(e).digest("hex").slice(0,16)}function A(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Fo(e){return/^[A-Za-z0-9._-]{8,64}$/.test(e)}function nu(e=process.env){let t=A(e.EV_AI_HOOK_INSTALLATION_ID);if(t){if(!Fo(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 Ho(e,t){return e&&Fo(e)?e:(e&&h(`WARN: ignoring installation id override (expected 8\u201364 chars [A-Za-z0-9._-], got length ${e.length})`),nu(t))}function ru(e){return/^[0-9a-f]{16}$/.test(e)}function ou(e=process.env){if(A(e.GITHUB_ACTIONS)){let t=A(e.GITHUB_REPOSITORY_ID)??A(e.GITHUB_REPOSITORY),n=A(e.GITHUB_ACTOR)??A(e.GITHUB_TRIGGERING_ACTOR)??A(e.GITHUB_USER);if(t&&n)return Te(`github_actions|${t}|${n}`)}if(A(e.CODESPACES)||A(e.CODESPACE_NAME)){let t=A(e.CODESPACE_NAME);if(t)return Te(`codespaces|${t}`);let n=A(e.GITHUB_REPOSITORY_ID)??A(e.GITHUB_REPOSITORY),r=A(e.GITHUB_USER)??A(e.GITHUB_ACTOR);if(n&&r)return Te(`codespaces|${n}|${r}`)}if(A(e.GITLAB_CI)){let t=A(e.CI_PROJECT_ID)??A(e.CI_PROJECT_PATH),n=A(e.GITLAB_USER_LOGIN)??A(e.GITLAB_USER_EMAIL)??A(e.GITLAB_USER_NAME);if(t&&n)return Te(`gitlab|${t}|${n}`)}return null}var su="cursoragent@cursor.com";function iu(e){let t=A(e.CURSOR_USER_EMAIL);return!t||t.toLowerCase()===su?null:t}function au(e,t){return A(e.CURSOR_PROJECT_DIR)??A(e.CLAUDE_PROJECT_DIR)??t}function cu(e){return e.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1").replace(/\.git$/i,"").toLowerCase()}async function uu(e){let t=await w("git",["config","--get","remote.origin.url"],2e3,{cwd:e});return t?cu(t):e}async function lu(e){let t=A(await w("git",["config","--local","--get","user.email"],2e3,{cwd:e})||void 0);if(t&&!G(null,t))return t;let n=A(await w("git",["log","-1","--format=%ae"],2e3,{cwd:e})||void 0);return n&&!G(null,n)?n:null}function du(e,t){let n=au(e,t);return n?Te(`cursor_cloud|${n}|${iu(e)??""}`):null}async function pu(e,t){let n=A(e.CLAUDE_PROJECT_DIR)??t;if(!n)return null;let r=await uu(n),o=await lu(n);return Te(`claude_remote|${r}|${o??""}`)}function Po(e,t){let n=Ho(e,t);if(n)return n;let r=ou(t);return r||Do()}async function fu(e){let n=await w("git",["config","--get","remote.origin.url"],2e3,{cwd:e})||Zc(e);return bo("sha256").update(n).digest("hex").slice(0,16)}function mu(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 gu(e){try{let t=JSON.parse(e);if(typeof t.installation_id!="string"||t.installation_id.length===0)return;let n=mu(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 Se(e){if(No(e))try{return gu(Mo(e,"utf8"))}catch{}}function bn(e){return Se(e)}function jo(e,t,n){let r=Se(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{Z(e,`${JSON.stringify(o,null,2)}
|
|
14
|
+
`)}catch(s){let i=s instanceof Error?s.message:String(s);h(`WARN: operator identity cache write failed open: ${i}`)}}function Ko(e,t=Date.now()){if(!e)return!0;if(Se(e)?.operator_identity_hash)return!1;let n=Uo(e);try{if(No(n)){let r=Number.NaN;try{r=Number(Mo(n,"utf8").trim())}catch{}let o=t-r;if(Number.isFinite(o)&&o>=0&&o<eu)return!1;try{vo(n)}catch{}}}catch{}try{return Tn(yt(n),{recursive:!0}),wo(n,`${t}
|
|
15
|
+
`,{encoding:"utf8",flag:"wx"}),!0}catch(r){if(zo(r))return!1;let o=r instanceof Error?r.message:String(r);return h(`WARN: cloud bootstrap claim failed open: ${o}`),!0}}function $o(e){if(e)try{vo(Uo(e))}catch{}}function Bo(e,t){let r=Se(e)?.platform_agent_ids?.[t];return typeof r=="string"&&r.length>0?r:void 0}function Go(e,t,n){if(!n)return;let r=Se(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{Z(e,`${JSON.stringify(o,null,2)}
|
|
16
|
+
`)}catch(s){let i=s instanceof Error?s.message:String(s);h(`WARN: platform_agent_id cache write failed open: ${i}`)}}function zo(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function _u(e,t){Tn(yt(e),{recursive:!0}),wo(e,`${JSON.stringify(t,null,2)}
|
|
17
|
+
`,{encoding:"utf8",flag:"wx"})}function To(e,t){try{return _u(e,t),t}catch(n){if(!zo(n))throw n;return Se(e)}}function ko(e,t){Tn(yt(e),{recursive:!0}),Z(e,`${JSON.stringify(t,null,2)}
|
|
18
|
+
`)}function xo(e,t){return{installation_id:e,...t&&t===e?{pinned:!0}:{}}}async function Vo(e,t={}){let n=t.home??kn(),r=t.env??process.env,o=await fu(e),s=tu(n),i={sessionId:t.sessionId,hostname:A(r.HOSTNAME)??void 0,osUser:A(r.USER)??A(r.LOGNAME)??A(r.USERNAME)??void 0,env:r},a=Ke(i),c=Ho(t.overrideId,r),u=a==="cursor_cloud"&&gn(i)?du(r,e):a==="claude_remote"?await pu(r,e):null,l=Se(s);if(l){let E=l;if(c&&c===l.installation_id&&l.pinned!==!0&&(E={...l,pinned:!0},ko(s,E)),!!u&&u!==E.installation_id&&!c&&E.pinned!==!0&&ru(E.installation_id)&&u){let y={installation_id:u,...E.platform_agent_ids?{platform_agent_ids:E.platform_agent_ids}:{}};return ko(s,y),{installationId:u,storePath:s,repoKey:o}}return{installationId:E.installation_id,storePath:s,repoKey:o}}let p=c??u??Po(void 0,r),m=To(s,xo(p,c));if(m)return{installationId:m.installation_id,storePath:s,repoKey:o};let d=c??u??Po(void 0,r),g=To(s,xo(d===p?Do():d,c));if(g)return{installationId:g.installation_id,storePath:s,repoKey:o};throw new Error(`Failed to create installation record at ${s}`)}import{existsSync as vu}from"node:fs";import{existsSync as Iu}from"node:fs";import{homedir as Jo}from"node:os";import{join as Au}from"node:path";import{existsSync as hu,readdirSync as Wo}from"node:fs";import{homedir as Rt}from"node:os";import{join as $}from"node:path";function Eu(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/ClaudeCode";case"win32":return $(process.env.ProgramFiles??"C:\\Program Files","ClaudeCode");default:return"/etc/claude-code"}}function Su(e=process.platform){let t=Eu(e),n=[$(t,"managed-settings.json")],r=$(t,"managed-settings.d");try{if(!hu(r))return n;let o=Wo(r).filter(s=>s.endsWith(".json")&&!s.startsWith(".")).sort().map(s=>$(r,s));n.push(...o)}catch{}return n}function Nn(e=process.platform,t=Rt()){return{serverManaged:$(t,".claude","remote-settings.json"),fileBased:Su(e)}}function yu(e=process.platform){switch(e){case"darwin":return"/Library/Application Support/Cursor";case"win32":return $(process.env.ProgramData??"C:\\ProgramData","Cursor");default:return"/etc/cursor"}}function Ru(e=process.platform,t=Rt()){let n=[$(yu(e),"hooks.json")],r=$(t,".cursor","managed");try{for(let o of Wo(r,{withFileTypes:!0}))!o.isDirectory()||o.name.startsWith(".")||n.push($(r,o.name,"hooks.json"))}catch{}return n}function Cu(e=process.platform,t=Rt()){let n=e==="win32"?$(process.env.ProgramData??"C:\\ProgramData","OpenAI","Codex"):"/etc/codex",r=[$(n,"requirements.toml")];return e!=="win32"&&r.push($(n,"managed_config.toml")),r.push($(t,".codex","managed_config.toml"),$(n,"config.toml")),r}function Ct(e,t=process.platform,n=Rt()){switch(e){case"claude":{let{serverManaged:r,fileBased:o}=Nn(t,n);return[r,...o]}case"cursor":return Ru(t,n);default:return Cu(t,n)}}function Xo(e){return e.settings.filter(t=>t.toLowerCase().endsWith(".json"))}var Ou={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 Yo(e,t){if(!(!e&&!t))return[...e??[],...t??[]]}function Pu(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:Yo(n.mcpJson,t.mcpJson),mcpToml:Yo(n.mcpToml,t.mcpToml),plugins:t.plugins??n.plugins,managed:t.managed??n.managed}}function Zo(e){return Object.fromEntries(Object.entries(Ou).map(([t,n])=>[t,Pu(n,n[e])]))}var ke=Zo("homeOnly"),de=Zo("projectOnly");function Tu(e){return[...e.skillRoots,...e.dirs.map(t=>t.dir),...e.memory.flat(),...e.settings,...e.mcpJson??[],...e.mcpToml??[]]}function ku(e,t){return Tu(e).some(n=>Iu(Au(t,n)))}function qo(e,t){for(let n of e)if(ku(n,t))return!0;return!1}function le(e){return[...new Set(e)]}function pe(e){let t=[],n=[],r=[],o=[],s=[],i=[],a=[];for(let c of e){t.push(...c.skillRoots);for(let u of c.dirs)u.kind==="SUBAGENT"?n.push(u.dir):u.kind==="COMMAND"?r.push(u.dir):o.push(u.dir);s.push(...c.memory.flat()),i.push(...c.settings),a.push(...c.mcpJson??[],...c.mcpToml??[])}return{skills:le(t),subagents:le(n),commands:le(r),rules:le(o),memory:le(s),settings:le(i),mcp:le(a)}}function xu(e,t=Jo(),n=process.platform){let r=[];for(let o of e)o.managed&&r.push(...Ct(o.managed,n,t));return le(r)}var fe=pe(Object.values(ke));function Qo(e=Jo(),t=process.platform){return xu(Object.values(ke),e,t)}import{existsSync as bu}from"node:fs";import{resolve as Mn}from"node:path";function z(e){return Mn(e).replaceAll("\\","/").replace(/\/$/,"")}function ye(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 It(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 Nu=/^(?!\.)[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/;function Ve(e){let t=e.replaceAll("\\","/").replace(/^\.\//,"");return!t||t.startsWith("/")||/^[A-Za-z]:\//.test(t)||t.split("/").includes("..")||!Nu.test(t)?null:t}function xe(e,t){let n=new Set,r=[];for(let o of[e,t]){if(!o)continue;let s=z(o);n.has(s)||(n.add(s),r.push(s))}return r}function Mu(e,t){let n=`${e}/`;return t===e||t.startsWith(n)}function q(e,t,n,r=bu){for(let o of e)for(let s of t){let i=z(Mn(o,s)),a=Mn(o,s,n).replaceAll("\\","/");if(Mu(i,a)&&r(a))return a}return null}var ts=/(?:^|\/|[\s"'=(])(?:\.cursor\/|\.claude\/|\.agents\/)skills(?:-cursor)?\/([^/]+)\/SKILL\.md/i,ns=/(?:^|\/|[\s"'=(])\.codex\/commands\/([^/]+)\.md\b/i,wu=/(?:^|\s)\/([a-z][a-z0-9-]{1,63}(?:\/[a-z][a-z0-9-]{1,63}){0,5})\b/gi,es=new Set(["applications","app","bin","boot","data","dev","etc","home","lib","media","mnt","node_modules","opt","pkg","private","proc","projects","repos","run","sbin","src","srv","sys","tmp","usr","users","var","volumes","workspace","workspaces"]),Lu=/^[a-z][a-z0-9-]{1,63}$/,Uu=[".cursor/skills",".claude/skills",".agents/skills"],Du=[".cursor/skills",".cursor/skills-cursor",".claude/skills",".agents/skills"],Fu=ye(Uu,pe(Object.values(de)).skills),Hu=ye(Du,pe(Object.values(ke)).skills),ju=new Set(["read","read_file","view"]),Ku=new Set(["bash","shell","zsh"]);function vn(e){let t=e.replace(/\\/g,"/");return ts.exec(t)?.[1]??null}function $u(e){let t=e.replace(/\\/g,"/"),r=ns.exec(t)?.[1];return r?r.toLowerCase():null}function Bu(e){return vn(e)??$u(e)}function Gu(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 At(e){return typeof e=="string"?At(j(e,null)):!e||typeof e!="object"?null:Gu(e)}function rs(e){if(typeof e=="string")return rs(j(e,null));if(!e||typeof e!="object")return null;let t=e.command;return typeof t=="string"&&t.length>0?t:null}function wn(e){let t=rs(e.tool_input);if(t)return t;let n=Ee(e.command);return n.length>0?n:null}function zu(e){let t=e.replace(/\\/g,"/"),n=ts.exec(t);if(n?.[1])return n[1];let o=ns.exec(t)?.[1];return o?o.toLowerCase():null}function Vu(e){return typeof e.tool_name=="string"?e.tool_name:typeof e.tool=="string"?e.tool:""}function Ln(e){let t=At(e.tool_input)??Ee(e.file_path);return t.length>0?t:null}function We(e,t,n){let r=Vu(e).toLowerCase();if(ju.has(r)){let o=Ln(e);return o?t(o):null}if(Ku.has(r)){let o=wn(e);return o?n(o):null}return null}function os(e){return We(e,Bu,zu)}function Wu(e){let t=new Set,n=[];for(let r of e.matchAll(wu)){let o=r[1]?.toLowerCase();!o||t.has(o)||Yu(o)||(t.add(o),n.push(o))}return n}function Yu(e){let t=e.split("/")[0];return es.has(e)||t!==void 0&&es.has(t)}function ss(e){let t=e.skillId.toLowerCase();if(!Lu.test(t))return null;let n=e.exists??vu,r=`${t}/SKILL.md`,o=q(xe(e.launchCwd,e.gitRoot),Fu,r,n);return o!==null?o:e.home?q([z(e.home)],Hu,r,n):null}function Ju(e){return Ee(e.prompt)}function is(e){let t=_(e,"command_name");if(t){let r=_(e,"expansion_type");if(r&&r!=="slash_command")return[];let o=t.replace(/^\//,"").toLowerCase();return o?[o]:[]}let n=Ju(e);return n?Wu(n):[]}var $n=je(Me(),1);import{existsSync as xd}from"node:fs";var Ce={claude:".claude",cursor:".cursor",codex:".codex",opencode:".opencode"};function Je(e){let n=e.replace(/^\/+|\/+$/g,"").toLowerCase().split("/").filter(Boolean);return n.length<2?"":n.join("/")}function kd(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 Je(n[1]);let r=t.match(/^ssh:\/\/[^/]+\/(.+)$/i);if(r?.[1])return Je(r[1]);t=t.replace(/^https:\/\//i,""),t=t.replace(/^http:\/\//i,""),t=t.replace(/^ssh:\/\//i,"");let o=t.match(/^[^/]+\/(.+)$/);return o?.[1]?Je(o[1]):Je(t)}async function Xe(e=process.cwd()){let t=await Y("git",["rev-parse","--is-inside-work-tree"],2e3,{cwd:e});if(!t.ok||t.stdout!=="true")return null;let[n,r,o,s]=await Promise.all([Y("git",["remote","get-url","origin"],2e3,{cwd:e}),Y("git",["branch","--show-current"],2e3,{cwd:e}),Y("git",["rev-parse","HEAD"],2e3,{cwd:e}),Y("git",["status","--porcelain"],2e3,{cwd:e})]),i=n.ok?n.stdout:null;return{remote:i===null?null:i.replace(/^([a-z]+:\/\/)[^/@]+@/i,"$1"),branch:r.ok?r.stdout:null,head:o.ok?o.stdout:null,dirty:s.ok?s.stdout.length>0:null}}async function xs(e,t,n,r=process.cwd(),o,s,i){if(t)return t;let a=Ce[n];if(!a)return"";let c=Lo(n,e.scope_path,i);if(s){let g=Bo(s,c);if(g)return g}let u=o??await Xe(r),l=u?.remote?kd(u.remote):"";if(l||(l=Je(process.env.GITHUB_REPOSITORY??"")),!l)return"";let p=e.scope_path??"",m=p?`${p}/`:"",d=`${l}:${m}${a}`;return s&&Go(s,c,d),d}var bd=[".cursor/rules",".claude/rules",".codex/rules"],Nd=pe(Object.values(de)).rules;function Md(e){return ye(It(e?Ce[e]:void 0,bd),Nd)}var vd=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/rules\/[^'"\s]+?\.(?:mdc|md|rules))\b/i;function bs(e){let t=Ve(e.relativePath);if(!t)return null;let n=e.exists??xd,r=xe(e.launchCwd,e.gitRoot),o=Md(e.runnerPlatform),s=q(r,o,t,n);if(s!==null)return s;if(!t.includes("/")){let i=q(r,["."],t,n);if(i!==null)return i}return e.home?q([z(e.home)],o,t,n):null}function wd(e){let t=e.replace(/\\/g,"/"),r=vd.exec(t)?.[1];return r?(0,$n.nativeKeyForRulePath)(r):null}function Ns(e){return We(e,$n.nativeKeyForRulePath,wd)}function Ms(e){return e.replace(/\.(mdc|md|rules)$/i,"")}function vs(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=Ve(i);!a||n.has(a)||(n.add(a),r.push(a))}return r}var Bn=je(Me(),1);import{existsSync as Ld}from"node:fs";var Ud=[".cursor/commands",".claude/commands",".codex/prompts"],Dd=pe(Object.values(de)).commands;function Fd(e){return ye(It(e?Ce[e]:void 0,Ud),Dd)}var Hd=/(?:^|\/|[\s"'=(])((?:\.cursor|\.claude|\.codex)\/(?:commands|prompts)\/[^'"\s]+?\.(?:md|mdc))\b/i;function ws(e){let t=Ve(e.commandId);if(!t)return null;let n=e.exists??Ld,r=`${t}.md`,o=Fd(e.runnerPlatform),s=q(xe(e.launchCwd,e.gitRoot),o,r,n);return s!==null?s:e.home?q([z(e.home)],o,r,n):null}function jd(e){let t=e.replace(/\\/g,"/"),r=Hd.exec(t)?.[1];return r?(0,Bn.nativeKeyForCommandPath)(r):null}function Ls(e){return We(e,Bn.nativeKeyForCommandPath,jd)}import{existsSync as Ds}from"node:fs";import{homedir as Fs}from"node:os";import{join as Ze,resolve as Gn,sep as Us}from"node:path";function zn(e){return[...new Set([e,e.replaceAll(/[^A-Za-z0-9_-]/g,"_"),e.replaceAll(/[^A-Za-z0-9_-]+/g,"_")])]}function Vn(e,t){let n=t.toLowerCase();return zn(e).some(r=>r.toLowerCase()===n)}function bt(e,t,n){if(!Ds(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 Kd(e,t,n){if(!Ds(e))return;let r=D(e,{}),o=Gn(t),s=null;for(let a of Object.keys(r.projects??{})){let c=Gn(a);(o===c||o.startsWith(c.endsWith(Us)?c:c+Us))&&(s===null||c.length>Gn(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 Hs(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"?(bt(Ze(r,".claude.json"),{source:"claude_json_user"},o),Kd(Ze(r,".claude.json"),t,o)):n==="cursor"&&bt(Ze(r,".cursor/mcp.json"),{source:"cursor_mcp_user"},o),bt(Ze(t,".mcp.json"),{source:"mcp_json"},o),bt(Ze(t,".cursor/mcp.json"),{source:"cursor_mcp"},o),o}async function Wn(e,t=process.cwd(),n="claude",r=Fs()){return[...Hs(e,t,n,r).values()].map(o=>o.declared)}function js(e,t,n=process.cwd(),r="claude",o=Fs()){let s=Hs(t,n,r,o),i=s.get(e);if(i!==void 0)return i.config??null;for(let[a,c]of s)if(Vn(a,e))return c.config??null;return null}function Yn(e){let t=fo(e);if(t.problem){h(`WARN: ignoring --url/--token collector override: ${t.problem}`);return}return t.url}function Ks(e,t){if(_(e,"conversation_id"))return!0;if(t==="")return!1;let n=t[0];return n?.toLowerCase()===n}function $d(){return!!(I("CURSOR_VERSION")??I("CURSOR_PROJECT_DIR"))}function Jn(e,t,n){return e!=="claude"&&e!=="codex"?!1:Ks(t,n)?!0:$d()}function qe(e,t,n,r){if(Ks(e,t))return"cursor";if(gt(r))return r;let o=_(e,"conversation_id"),s=_(e,"turn_id"),i=_(e,"session_id"),a=t.toLowerCase(),c="unknown";return o||t===a&&t!==""?c="cursor":s?c="codex":(i||a==="sessionstart"||a==="sessionend"||a==="stop"||a==="stopfailure"||a==="pretooluse"||a==="posttooluse"||a==="posttoolusefailure"||a==="permissiondenied"||a==="subagentstart"||a==="subagentstop"||a==="userpromptexpansion"||a==="userpromptsubmit")&&(c="claude"),gt(n)&&(c=n),c}function Nt(e,t){let n=e.toLowerCase();return n==="sessionend"||n==="stopfailure"||n==="subagentstop"?!0:n==="stop"&&t==="codex"}function Bd(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 $s(e){let t=e.toLowerCase();return t==="userpromptsubmit"||t==="beforesubmitprompt"}function Bs(e,t){return e.toLowerCase()==="userpromptsubmit"&&t==="claude"}function Gs(e){let t=e.toLowerCase();return t==="posttooluse"?!0:t==="posttoolusefailure"||t==="permissiondenied"?!1:null}function zs(e,t,n){let r=_(e,"session_id")||_(e,"conversation_id"),o=_(e,"prompt.id")||_(e,"prompt_id")||_(e,"generation_id")||_(e,"turn_id"),s=_(e,"hook_event_name")||_(e,"event"),i=_(e,"source"),a=qe(e,s,t,n);return{sessionId:r,turnId:o,runnerEvent:s,hookSource:i,runnerPlatform:a}}var Gd=["session_start","session_end","tool_invoked","skill_invoked"];function zd(e){return Gd.includes(e)}function Vs(e,t){return e&&zd(e)?e:Bd(t.toLowerCase())}var Vd={beforeshellexecution:"Shell",aftershellexecution:"Shell",beforereadfile:"Read",afterfileedit:"Write"};function Ws(e){return/^mcp__/i.test(e)||/^MCP:/i.test(e)}function Ys(e,t=""){let n=_(e,"tool_name")||_(e,"tool")||null,r=t.toLowerCase();n?r==="beforemcpexecution"&&!Ws(n)&&(n=`MCP:${n}`):n=Vd[r]??null;let o=e.tool_input,i=(o&&typeof o=="object"?Ee(o.skill)||Ee(o.skill_name):"")||_(e,"skill_name")||null,a=n&&e.tool_name!==n&&e.tool!==n?{...e,tool_name:n}:e;i??=os(a);let c=Ns(a),u=Ls(a);return{toolName:n,skillName:i,ruleName:c,commandName:u}}var Wd=/^[A-Za-z][A-Za-z0-9_.:-]{0,63}$/;function Js(e){for(let t of["subagent_type","agent_type"]){let n=_(e,t);if(n&&Wd.test(n))return n}return null}function Xs(e){let t=re(e,"duration_ms");if(typeof t=="number")return t;let n=re(e,"duration");return typeof n=="number"?n:null}var Yd="error",Jd="interrupted",Xd="permission_denied",Zd=/^[A-Za-z][A-Za-z0-9_.-]{0,63}$/;function Qe(e){return Zd.test(e)?e:null}function qd(e){for(let t of["failure_type","error_type"]){let n=Qe(_(e,t));if(n)return n}return null}function Zs(e,t){return re(e,"is_interrupt")===!0?Jd:t.toLowerCase()==="permissiondenied"?Xd:qd(e)??Yd}function Qd(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 ep(e,t){let n=null;for(let r of t)!r||!Vn(r,e)||(n===null||r.length>n.length)&&(n=r);return n}function tp(e,t){let n=null,r=0;for(let s of t)if(s)for(let i of zn(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:ep(o[1],t)??o[1],mcpTool:o[2]}}function np(e,t){if(/^mcp__/i.test(e))return tp(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:Qd(n,t),mcpTool:n}}return{mcpServer:null,mcpTool:null}}function rp(e,t){let n=`${t}__`;return e.length>n.length&&e.toLowerCase().startsWith(n.toLowerCase())?e.slice(n.length):e}function qs(e,t=[],n=""){let r=e?np(e,t):{mcpServer:null,mcpTool:null},o=Qe(n.trim());if(!o)return r;let s=r.mcpTool;return!s&&e&&!Ws(e)&&(s=e),s&&(s=rp(s,o)),{mcpServer:o,mcpTool:s}}var ni=3e4,up="claims",lp=!0,dp=100,pp=new Set(["sessionstart","sessionend","stopfailure"]),fp=["tool_name","tool","command","file_path","url"];function mp(e=ti()){return Xn(oe(e),up)}function ri(e){let t=e.split(`
|
|
19
|
+
`,1)[0]??"";return Number(t.trim())}function oi(e){return op("sha256").update(e).digest("hex").slice(0,32)}function gp(e){let t=[];for(let n of fp){let r=_(e,n).trim();r&&t.push(`${n}=${r}`)}return t.length===0?"":oi(t.join("\0"))}function _p(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=pp.has(n);if(!a&&!c)return;let u=e.runnerPlatform.trim()||"unknown";return oi(`${u}|${t}|${n}|${r}|${o}|${i}|${s}`)}function hp(e){return e instanceof Error&&"code"in e&&e.code==="EEXIST"}function Ep(e,t){return Xn(e,t)}function Sp(e,t=Date.now()){let n;try{n=ap(e)}catch{return}let r=0;for(let o of n){if(r>=dp)break;r+=1;let s=Xn(e,o),i=Number.NaN;try{i=ri(Qs(s,"utf8"))}catch{continue}let a=t-i;if(!(!Number.isFinite(a)||a<0||a<ni))try{ei(s)}catch{}}}function yp(e,t,n=Date.now()){let r=Ep(t,e);try{if(sp(r)){let o=Number.NaN;try{o=ri(Qs(r,"utf8"))}catch{}let s=n-o;if(Number.isFinite(s)&&s>=0&&s<ni)return!1;try{ei(r)}catch{}}}catch{}try{ip(t,{recursive:!0}),cp(r,`${n}
|
|
20
|
+
`,{encoding:"utf8",flag:"wx"})}catch(o){if(hp(o))return!1;let s=o instanceof Error?o.message:String(o);return h(`WARN: event claim failed open: ${s}`),!0}return Sp(t,n),!0}function Rp(e,t,n){let r=_(e,"session_id")||_(e,"conversation_id"),o=_(e,"prompt.id")||_(e,"prompt_id")||_(e,"generation_id")||_(e,"turn_id"),s=_(e,"tool_use_id"),i=_(e,"subagent_id")||_(e,"agent_id"),a=qe(e,t,void 0,n),c=gp(e);return{runnerPlatform:a,sessionId:r,runnerEvent:t,turnId:o,toolUseId:s,subagentId:i,callFingerprint:c}}function si(e,t,n,r=ti(),o=Date.now()){if(!lp)return!0;let s=_p(Rp(e,t,n));if(!s)return!0;let i=yp(s,mp(r),o);return!i&&I("EV_AI_HOOK_DEBUG")&&h(`DEBUG: duplicate hook event suppressed (claim ${s.slice(0,8)}\u2026)`),i}import{closeSync as Cp,writeSync as Ip}from"node:fs";var Ap=Buffer.from([1]),ii=So;function ai(e=process.env){let t=e[ii];if(delete e[ii],t===void 0)return;let n=Number.parseInt(t,10);if(!(!Number.isInteger(n)||n<3)){try{Ip(n,Ap)}catch{}try{Cp(n)}catch{}}}function Zn(e=process.env){let t=e[go];if(!t)return;let n=e[ho],r=e[Eo];return{launcherVersion:t,hookSource:e[_o]??"",fallbackReason:n??void 0,launcherScope:r??void 0}}function ci(e,t){return(e?mo(e):void 0)===t}import{realpathSync as s_}from"node:fs";import{homedir as ec}from"node:os";var P=je(Me(),1);import{existsSync as Op,readFileSync as Pp}from"node:fs";import{homedir as ui}from"node:os";import{join as Tp}from"node:path";var kp="cloud-cache.json",xp=1440*60*1e3,bp=900*1e3;function Np(e=ui()){return Tp(oe(e),kp)}function Mp(e){if(!Op(e))return;let t=j(Pp(e,"utf8"),{});if(!(typeof t.context!="string"||typeof t.probed_at!="number"||t.result!==null&&t.result!==void 0&&typeof t.result!="object"))return{context:t.context,probed_at:t.probed_at,result:t.result??null}}function vp(e,t){try{Z(e,`${JSON.stringify(t)}
|
|
21
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: cloud cache write failed open: ${r}`)}}function wp(e,t,n){if(!e||e.context!==t)return!1;let r=e.result===null?bp:xp;return n-e.probed_at<r}async function Lp(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 Up(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 Dp(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 Fp(e){let t=await Promise.allSettled([Lp(e),Up(e),Dp(e)]);for(let n of t)if(n.status==="fulfilled"&&n.value)return n.value;return null}async function qn(e,t){if(e==="interactive")return null;let n=t?.home??ui(),r=t?.timeoutMs??1e3,o=t?.nowMs??Date.now(),s=Np(n),i=Mp(s);if(wp(i,e,o))return i.result;let a=await Fp(r);return vp(s,{context:e,probed_at:o,result:a}),a}var Hp=["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"],jp=["CURSOR_PROJECT_DIR"],Kp=new Set(["key","api-key","api_key","apikey","token","sig","signature","access_token","password","pwd","secret","client_secret"]);function $p(e){try{let t=new URL(e);(t.username||t.password)&&(t.username="",t.password="");for(let[n]of t.searchParams)Kp.has(n.toLowerCase())&&t.searchParams.set(n,"[redacted]");return t.toString()}catch{return e}}function Qn(e=process.env){let t=Hp.map(r=>Object.prototype.hasOwnProperty.call(e,r)?{name:r,present:!0,value:$p(e[r]??"")}:{name:r,present:!1}),n=jp.map(r=>({name:r,present:Object.prototype.hasOwnProperty.call(e,r)&&!!e[r]}));return[...t,...n]}import{homedir as Sf}from"node:os";import{homedir as li}from"node:os";import{join as Bp}from"node:path";function Gp(e=li()){return Bp(e,".claude.json")}function Mt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function di(e=li()){let n=D(Gp(e),{}).oauthAccount;if(!n||typeof n!="object")return null;let r=Mt(n.emailAddress),o=Mt(n.fullName)??Mt(n.displayName),s=Mt(n.accountUuid),i=r??s;return!i||G(o,r)?null:{git_user_name:null,git_user_email:null,platform_login:i,identity_source:"claude_oauth"}}import{homedir as mi}from"node:os";import{join as pi}from"node:path";var zp="https://api.openai.com/auth";function ve(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function gi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Vp(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 gi(r)}catch{return null}}function fi(e,t,n){return ve(e[n])??ve(t?.[n])}function Wp(e=process.env,t=mi()){let n=ve(e.CODEX_HOME)??pi(t,".codex");return pi(n,"auth.json")}function _i(e=process.env,t=mi()){let n=D(Wp(e,t),{}),r=ve(n.auth_mode);if(r!==null&&r!=="chatgpt"||r===null&&ve(n.OPENAI_API_KEY))return null;let o=ve(n.tokens?.id_token);if(!o)return null;let s=Vp(o);if(!s)return null;let i=gi(s[zp]),a=fi(s,i,"name"),c=fi(s,i,"email");return!c||G(a,c)?null:{git_user_name:null,git_user_email:null,platform_login:c,identity_source:"codex_oauth"}}import{homedir as Lt}from"node:os";import{join as ae}from"node:path";import{join as Yp}from"node:path";var Jp="cursor-ide-identity.json",Xp=ze;function Ei(e){return Yp(oe(e),Jp)}function hi(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Si(e){let t=D(e,{}),n=t.read_at_ms,r=t.db_path;if(!(typeof n!="number"||!Number.isFinite(n)||typeof r!="string"))return{read_at_ms:n,db_path:r,email:hi(t.email),auth_id:hi(t.auth_id)}}function yi(e,t,n){if(e?.db_path!==t)return!1;let r=n-e.read_at_ms;return r>=0&&r<Xp}function Ri(e,t){try{Z(e,`${JSON.stringify(t)}
|
|
22
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: cursor IDE identity cache write failed open: ${r}`)}}import{execFileSync as Zp}from"node:child_process";import{existsSync as qp}from"node:fs";import{createRequire as Qp}from"node:module";import{pathToFileURL as ef}from"node:url";var Ii=Qp(import.meta.url),vt=`
|
|
15
23
|
SELECT key, value
|
|
16
24
|
FROM ItemTable
|
|
17
25
|
WHERE key LIKE 'cursorAuth/%'
|
|
18
26
|
AND key NOT LIKE '%Token%'
|
|
19
27
|
AND key NOT LIKE '%token%'
|
|
20
28
|
ORDER BY key
|
|
21
|
-
`.trim(),
|
|
22
|
-
`)){let r=n.trimEnd();if(!r)continue;let o=r.indexOf(" ");if(o<=0)continue;let s=r.slice(0,o).trim(),i=r.slice(o+1).trim();s&&i&&!
|
|
23
|
-
`);return
|
|
24
|
-
`)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function _d(e,t=M){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return gd(n)}function hd(e=process.env){let t=k(e.GIT_AUTHOR_NAME),n=k(e.GIT_AUTHOR_EMAIL);if(t||n)return{git_user_name:t,git_user_email:n,platform_login:null,identity_source:"git_env"};let r=k(e.GIT_COMMITTER_NAME),o=k(e.GIT_COMMITTER_EMAIL);if(r||o)return{git_user_name:r,git_user_email:o,platform_login:null,identity_source:"git_env"};let s=k(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function ne(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function Sd(e=process.env){let t=k(e.EV_AI_HOOK_OPERATOR_EMAIL),n=k(e.EV_AI_HOOK_OPERATOR_LOGIN),r=ne(k(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=k(e.GITHUB_ACTOR)??k(e.GITHUB_TRIGGERING_ACTOR)??k(e.GITHUB_USER),s=ne(o,null,"github",o);if(s)return s;let i=k(e.GITLAB_USER_LOGIN),a=k(e.GITLAB_USER_EMAIL),c=ne(k(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let l=k(e.BUILD_REQUESTEDFOREMAIL),u=ne(k(e.BUILD_REQUESTEDFOR),l,"azure_devops",l??k(e.BUILD_REQUESTEDFORID));if(u)return u;let d=k(e.BUILDKITE_BUILD_CREATOR_EMAIL),p=ne(k(e.BUILDKITE_BUILD_CREATOR),d,"buildkite",d);if(p)return p;let f=k(e.BUILD_USER_EMAIL)??k(e.CHANGE_AUTHOR_EMAIL),_=ne(k(e.BUILD_USER)??k(e.CHANGE_AUTHOR),f,"jenkins",f??k(e.BUILD_USER_ID));if(_)return _;let E=k(e.CIRCLE_USERNAME),S=ne(E,null,"circleci",E);if(S)return S;let y=k(e.CODEBUILD_INITIATOR),R=ne(y,null,"codebuild",y);if(R)return R;let H=k(e.DRONE_COMMIT_AUTHOR_EMAIL),x=k(e.DRONE_COMMIT_AUTHOR),P=ne(x??k(e.DRONE_COMMIT_AUTHOR_NAME),H,"drone",H??x);if(P)return P;if(Ns(e.CLAUDE_CODE_REMOTE)||Ns(e.CURSOR_AGENT)){let U=k(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:U&&!B(null,U)?U:null,identity_source:"cloud"}}return null}function Ln(e){return!!((e.git_user_name??e.git_user_email)&&!B(e.git_user_name,e.git_user_email))}function k(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function Ns(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Ed(e,t,n){return e==="claude"?_s(t):e==="cursor"?Ms(t,n):e==="codex"?Rs(n,t):null}async function Un(e,t=M,n=process.env,r={}){let o=await _d(e,t),s=hd(n),i=Ln(o)?o:s&&Ln(s)?s:null,a=Ed(r.runnerPlatform,r.home??fd(),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=Sd(n);return c?.platform_login?{git_user_name:i?.git_user_name??null,git_user_email:i?.git_user_email??null,platform_login:c.platform_login,identity_source:c.identity_source}:i?{...i,platform_login:null,identity_source:Ln(o)?"git_config":"git_env"}:c||(o.git_user_name||o.git_user_email?{...o,identity_source:"git_config"}:s||{git_user_name:null,git_user_email:null,platform_login:null,identity_source:"git_config"})}async function Dn(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??M,s=e.env??process.env,i=await Un(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=md(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),l=(n?an(n):void 0)?.operator_identity_hash;if(!(r||l!==void 0&&l!==a||!l))return{commit:()=>{}};let f=n;return{operator:i,commit:()=>{f&&Qr(f,a,ot())}}}function Hn(e){return e?!an(e)?.operator_identity_hash:!0}function Ls(e){return!0}import{existsSync as Np,readFileSync as Lp}from"node:fs";import{homedir as Pi}from"node:os";import{join as ve,resolve as Up}from"node:path";import{basename as Pp,join as be}from"node:path";import{dirname as Bs,resolve as kt}from"node:path";import{existsSync as yd}from"node:fs";import{homedir as Hs}from"node:os";import{relative as Fs,resolve as q,sep as ue}from"node:path";var Rd=["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 Cd(e){return e.capture_hook_input==="full"?!0:e.capture_hook_input==="allowlist"?!1:e.debug===!0?!0:I("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"}function Id(e){let t={};for(let n of Rd){let r=pe(e,n);r!==void 0&&(t[n]=r)}return t}function It(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=q(e),r=q(t),o=Fs(r,n);return!o||o==="."?".":o.startsWith(`..${ue}`)||o===".."||q(r,o)!==n?null:o.split(ue).join("/")}function js(e,t){let n=Fs(q(t),q(e)).split(ue).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Ks(e){return typeof e!="string"||e.length===0?null:q(e).split(ue).join("/")}function Ad(){let e=I("CURSOR_PROJECT_DIR");if(!e)return null;let t=q(e);return yd(t)?t.split(ue).join("/"):null}function Fn(e,t){return It(e,t)!==null}function kd(e,t){let n=q(t??Hs(),".cursor").split(ue).join("/");return Fn(e,n)}function Od(e,t,n){return t!==null&&Fn(e,t)?!0:t!==null&&kd(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&Fn(e,n.gitRoot)?!0:t===null}function $s(e,t){let n=Ks(e.cwd);if(n!==null)return n;let r=q(process.cwd()).split(ue).join("/"),o=Ad();return Od(r,o,t)?r:o??r}function jn(e,t={}){return $s(e,t)}function Kn(e,t=Hs()){let n=q(t).split(ue).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Us(e,t,n){let r=Ks(n.launchCwd)??$s(t,n);e.cwd=Kn(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?It(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}function Ds(e,t){let n=JSON.stringify(e),r=Buffer.byteLength(n,"utf8");if(r<=t)return e;let o=Object.entries(e).filter(([i,a])=>!i.startsWith("_")&&(typeof a=="string"||typeof a=="number"||typeof a=="boolean")).sort((i,a)=>Buffer.byteLength(JSON.stringify(i[1]),"utf8")-Buffer.byteLength(JSON.stringify(a[1]),"utf8")),s={_truncated:!0,_original_bytes:r};for(let[i,a]of o){let c={...s,[i]:a};if(Buffer.byteLength(JSON.stringify(c),"utf8")>t)break;s[i]=a}return s}function At(e,t,n={}){if(Cd(t)){let o={...e};return delete o.cwd,delete o.transcript_path,Us(o,e,n),Ds(o,Ur)}let r=Id(e);return Us(r,e,n),Ds(r,Lr)}function Pd(e){return typeof e=="string"&&e.length>0}function $n(e){let t=kt(e.home),n=kt(e.launchCwd),r=e.gitRoot?kt(e.gitRoot):null,o=new Set,s=[],i=null;e.inGitRepo&&Pd(e.remote)&&r!==null&&r!==t&&(i=r,o.add(r)),n!==t&&!o.has(n)&&(s.push({scope:"cwd",dir:n}),o.add(n)),i!==null&&s.push({scope:"repo",dir:i});let a=null,c=r!==null&&It(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let l=Bs(r);for(;;){let u=kt(l);if(u===t)break;let d=Bs(u);if(d===u)break;if(e.hasProjectSpec(u)){s.push({scope:"parent",dir:u}),a=js(u,n);break}l=d}}return{anchors:s,parentRel:a}}import{existsSync as Gs,readdirSync as xd,realpathSync as Td}from"node:fs";import{basename as bd,dirname as vd,relative as Md,resolve as wd,sep as Nd}from"node:path";var Bn=400,Ot=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??re}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=wd(t).split(Nd).join("/");return Kn(r,this.home)}let n=Md(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${N(vd(t))}/${bd(t)}`:n}claimFile(t){try{let n=Td(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(!Gs(t))return[];try{return xd(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if(Gs(t))return L(t,n)}push(t){return this.components.length>=this.maxEntries?(this.truncated=!0,!1):this.pluginExpandRemaining!==void 0&&this.pluginExpandRemaining<=0?!1:(this.pluginExpandRemaining!==void 0&&(this.pluginExpandRemaining-=1),this.components.push(t),!0)}withPluginExpandCap(t,n){let r=this.pluginExpandRemaining;this.pluginExpandRemaining=t;try{let o=n(),s=t-(this.pluginExpandRemaining??0);return{result:o,expanded:s}}finally{this.pluginExpandRemaining=r}}};import{existsSync as Gn,readFileSync as Ld,statSync as Ud}from"node:fs";import{basename as Ws,join as Ve,relative as Js}from"node:path";var zn=100*1024,Dd=4;function Hd(e){return e.length<=zn?e:`${e.slice(0,zn-1)}\u2026`}function Fd(e){try{let t=Ld(e),n=t.toString("utf8");return{hash:N(t),length:t.length,text:Hd(n)}}catch{return null}}var zs={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function jd(e){return e in zs?zs[e]:"UNSPECIFIED"}function Pt(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=Fd(t.absolutePath);if(!n)return!1;let r=t.name??Ws(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=jd(t.kind);return s&&(o.trigger=s),e.push(o)}function Kd(e,t,n){let r=Js(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Ws(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Se(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;Wn(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function Wn(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:l}=t;if(!(o>Dd))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=Ve(r,u.name,c);if(Gn(f)){let _=Js(n,Ve(r,u.name)).replace(/\\/g,"/");Pt(e,{absolutePath:f,kind:s,origin:i,enabled:a,name:_||u.name});continue}Wn(e,{walkRoot:n,currentDir:Ve(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(u.isDirectory()){Wn(e,{walkRoot:n,currentDir:Ve(r,u.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:l});continue}if(!u.isFile()||!l)continue;let d=u.name.toLowerCase();if(!l.some(f=>d.endsWith(f)))continue;let p=Ve(r,u.name);Pt(e,{absolutePath:p,kind:s,origin:i,enabled:a,name:Kd(n,p,!0)})}}function Vs(e){for(let t of e)if(Gn(t))try{if(Ud(t).size>0)return t}catch{continue}return e.find(t=>Gn(t))}var xt=Ne(Oe(),1);var $d="<omitted>",Bd=["package_name","package_spec","package_version","package_version_source"],Ys=100,Xs=120,Tt=[{raw:"tools",attr:"tools"},{raw:"autoApprove",attr:"auto_approve"},{raw:"auto_approve",attr:"auto_approve"},{raw:"alwaysAllow",attr:"always_allow"},{raw:"always_allow",attr:"always_allow"},{raw:"enabledTools",attr:"enabled_tools"},{raw:"enabled_tools",attr:"enabled_tools"},{raw:"disabledTools",attr:"disabled_tools"},{raw:"disabled_tools",attr:"disabled_tools"}],qs=new Set(Tt.map(e=>e.attr)),Gd=["enabled","disabled"],zd=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],Wd=new Set(["type","command","url","args","env","envVars","headers",...Gd,...zd,...Tt.map(e=>e.raw)]),Jd=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",...Bd,...qs,...[...qs].map(e=>`${e}_truncated`)]);function Zs(e,t){for(let n of t)Wd.has(n)||Jd.has(n)||(e[n]=$d)}var Vd=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,Yd=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,Xd=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,qd=/^bearer(?:\s+|$)/i;function bt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Qs(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Jn(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=bt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Ee(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function Zd(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,xt.launchContainsCredentials)({kind:"url",url:e})||(0,xt.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=Xe([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,xt.launchContainsCredentials)({kind:"url",url:r}):!0)}function ei(e,t,n){Zd(t,n)&&(e.launch_had_credentials=!0)}function Qd(e){return Xd.test(e)||qd.test(e)?"<redacted>":e.includes("://")?Ee(e):e}function ti(e){if(/^https?:\/\//i.test(e))return Ee(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${ti(e.slice(t+1))}`:Qd(e)}function ep(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return Vd.test(t)||Yd.test(t)}function Xe(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(ep(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(ti(r))}return t}function tp(e){let t=Qs(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Xs?r.slice(0,Xs):r))].sort();if(n.length!==0)return n.length>Ys?{names:n.slice(0,Ys),truncated:!0}:{names:n,truncated:!1}}function np(e){let t=bt(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function ni(e,t){let n=new Set;for(let{raw:r,attr:o}of Tt){if(n.has(o)||!(r in t))continue;let s=t[r];if(o==="auto_approve"&&typeof s=="boolean"){e.auto_approve=s,n.add(o);continue}let i=tp(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function ri(e,t){let n=bt(e),r={transport:t};if(!n)return r;Zs(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.serverUrl=="string"?n.serverUrl:void 0,a=o??s??i,c=Qs(n.args);a&&(r.command_or_url=Ee(a));let l=Xe(c);l.length>0&&(r.args=l),ei(r,a,c);let u=np(n.env_http_headers),d=[...new Set([...Jn(n.env),...Jn(n.envVars),...Jn(n.env_vars),...u.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();d.length>0&&(r.env_var_names=d),u.headers.length>0&&(r.env_http_header_names=[...new Set(u.headers)].sort());for(let E of["headers","http_headers","env_http_headers"])if(n[E]!==void 0&&n[E]!==null){r.headers_present=!0;break}let p=typeof n.auth=="string"?n.auth:void 0;p&&(r.auth=p);let f=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;f&&(r.bearer_token_env_var=f);let _=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return _&&(r.default_tools_approval_mode=_),ni(r,n),r}function oi(e){let t=bt(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function Xn(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return N(JSON.stringify({name:e,attributes:r,enabled:n}))}function xe(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function Ye(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*\\[([^\\]]*)\\]`,"m").exec(e);return n?.[1]?[...n[1].matchAll(/"([^"]*)"|'([^']*)'/g)].map(r=>r[1]??r[2]??"").filter(r=>r.length>0):[]}function Yn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Vn(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=xe(n[1]);return r.length>0?r:void 0}function rp(e,t){let n=[],r=i=>{for(let a of i.split(/[,\n]/)){let c=/^\s*"?([A-Za-z_][A-Za-z0-9_-]*)"?\s*=\s*(.+?)\s*$/.exec(a);c?.[1]&&n.push([c[1],xe(c[2]??"")])}},o=new RegExp(`^\\s*${t}\\s*=\\s*\\{([^}]*)\\}`,"m").exec(e);o?.[1]&&r(o[1]);let s=new RegExp(`(?:^|\\n)\\[[^\\]]*\\.${t}\\]\\s*\\n([\\s\\S]*?)(?=\\n\\[|$)`).exec(`
|
|
25
|
-
${e}`);return s?.[1]&&r(s[1]),n}function
|
|
26
|
-
`)){let s=
|
|
27
|
-
`)){let R=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&
|
|
28
|
-
${e}`);if(
|
|
29
|
-
`)){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&
|
|
30
|
-
`);return mp("sha512").update(t).digest("hex").slice(0,16)}function _p(e){let t=process.platform==="win32"?qe(I("LOCALAPPDATA")??e,"npm-cache"):qe(e,".npm"),n=I("npm_config_cache")??I("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function di(e){return typeof e=="string"&&e.length>0&&e.length<=le.PACKAGE_FIELD_MAX?e:null}function hp(e,t,n){let r=gp(e);for(let o of _p(n)){let s=qe(o,"_npx",r),i=L(qe(s,"node_modules",...t.split("/"),"package.json"),{}),a=di(i.version);if(a!==null)return a;let c=L(qe(s,"package-lock.json"),{}),l=di(c.packages?.[`node_modules/${t}`]?.version);if(l!==null)return l}return null}function Sp(e){return e.length<=le.PACKAGE_FIELD_MAX?e:`${e.slice(0,le.PACKAGE_FIELD_MAX-1)}\u2026`}function qn(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,le.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,le.packageNameFromSpec)(o);if(s===null)return null;let i=hp(r,s,n);return{package_name:s,package_spec:Sp(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function pi(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=vt(e.trim());return n===void 0?null:qn(n,r,t)}function Mt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=Array.isArray(n.args)?n.args.filter(o=>typeof o=="string"):[];return qn(typeof n.command=="string"?n.command:null,r,t)}function fi(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:qn(xe(n[1]??""),Ye(e,"args"),t)}function Rp(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 mi(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=Rp(a),l=ri(a,c);Object.assign(l,Mt(a,e.home)??{});let u=oi(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:Xn(i,l,u),origin:n,enabled:u,attributes:l})}}function gi(e,t,n){if(!Ep(t)||!e.claimFile(t))return;let r;try{r=yp(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=ii(u,d);Object.assign(p,fi(u,e.home)??{});let f=si(u);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:Xn(a,p,f),origin:n,enabled:f,attributes:p})}}import{existsSync as Cp,readdirSync as Ip}from"node:fs";import{join as $}from"node:path";var _i=50;function Zn(e,t,n,r){if(!Cp(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(_i,()=>{Se(e,{dir:$(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Se(e,{dir:$(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Se(e,{dir:$(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});Te(e,$(t,"hooks","hooks.json"),n),Te(e,$(t,"hooks.json"),n);let i=e.components.length-o,a=s>=_i;return{componentCount:i,expandTruncated:a}}function Qn(e,t){e.push({kind:"PLUGIN",name:t.pluginKey,path:t.rowPath,content_hash:t.contentHash,origin:"user",enabled:t.enabled,attributes:{...t.marketplace?{marketplace:t.marketplace}:{},...t.version?{version:t.version}:{},scope:t.scope,component_count:t.componentCount,...t.expandTruncated?{expand_truncated:!0}:{}}})}function hi(e){let t=$(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson($(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let l=Array.isArray(c)?c:[c],u=l[0]??{},d=s[a]===!0,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}`,S=0,y=!1;for(let R of l)if(typeof R.installPath=="string"&&R.installPath.length>0){let H=Zn(e,R.installPath,E,d);S+=H.componentCount,y=y||H.expandTruncated}Qn(e,{pluginKey:a,rowPath:i,enabled:d,scope:_,version:f||void 0,marketplace:p||void 0,componentCount:S,expandTruncated:y,contentHash:N(`${a}|${f}|${_}|${d}|${S}`)})}}function Ap(e){let t=e,n="";try{let r=Ip(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=$(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=$(e,s),n=s)}}catch{}return{installPath:t,version:n}}var kp=/^\d+$/;function Op(e){let t=e.filter(n=>!kp.test(n.pluginId));return t.length>0?t:e}function Si(e){let t=[{base:$(e.home,".cursor/plugins/local"),scope:"local"},{base:$(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=$(n,o.name),l=`plugin:${a}`,{componentCount:u,expandTruncated:d}=Zn(e,c,l,!0);Qn(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:u,expandTruncated:d,contentHash:N(`${a}|local|${u}`)});continue}let s=o.name,i=[];for(let a of e.readEntries($(n,s))){if(!a.isDirectory())continue;let c=$(n,s,a.name),{installPath:l,version:u}=Ap(c);i.push({pluginId:a.name,installPath:l,version:u})}for(let a of Op(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,l=`plugin:${c}`,{componentCount:u,expandTruncated:d}=Zn(e,a.installPath,l,!0);Qn(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:u,expandTruncated:d,contentHash:N(`${c}|${a.version}|${u}`)})}}}function xp(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Se(e,{dir:be(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Se(e,{dir:be(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=Vs(i.map(c=>be(r,c)));a&&Pt(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:Pp(a)})}for(let i of go(n))Te(e,be(r,i),o);for(let i of n.mcpJson??[])mi(e,be(r,i),o);for(let i of n.mcpToml??[])gi(e,be(r,i),o);if(s){if(n.managed)for(let i of lt(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&Te(e,i,o);n.plugins==="claude"?hi(e):n.plugins==="cursor"&&Si(e)}}function Ei(e,t){try{let n=new Ot(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)xp(n,{layout:r,levelDir:t.levelDir,origin:t.origin,includeMachineWide:t.includeMachineWide});return{scopeRef:t.scopeRef,anchor:t.levelDir,components:n.components,truncated:n.truncated}}catch{return}}function er(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=Ei(t,{layouts:Object.values(Ie),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:re,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(se),l=$n({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:u=>ho(c,u)});i=l.parentRel;for(let u of l.anchors){let d=Nn(u.dir);if(o!==void 0&&!o(u.scope,d))continue;let p=Ei(t,{layouts:c,levelDir:u.dir,origin:u.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:Bn,scopeRef:d});p&&(r[u.scope]=p)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function tr(e,t,n={}){let r=n.truncated===!0,o=Je(e),s=new Set(e.map(u=>z(u.path,u.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let u of e){let d=z(u.path,u.name);c[d]!==u.content_hash&&a.push(u)}let l=[];if(!r){for(let u of Object.keys(c))if(!s.has(u)){let d=ws(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 Ri=2*1024*1024,Tp=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function nr(e,t,n){let r=new Set(t.map(s=>z(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(z(s.path,s.name))||o.push(s));return o}function rr(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function yi(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Ci(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function or(e,t=Ri){let n=[],r=[];for(let u of e)Tp.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=yi(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=Ci(u),_=yi(f)+d;if(i+_<=t){s.push(f),i+=_,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:l}}function sr(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:Ci(n))}var bp=["user","cwd","repo","parent"];function ir(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let x of bp){let P=t.scopes[x];if(!P)continue;let U=n(x,P.scopeRef),w=U.components,j=tr(P.components,w,{forceFull:w===void 0,truncated:P.truncated}),Z=new Set(U.textHashes),D=nr(P.components,j.upserts,Z),b=sr([...j.upserts,...D],Z);s.push({scope:x,walk:P,delta:j,outgoing:b,outgoingKeys:new Set(b.map(C=>z(C.path,C.name))),deliveredTextHashes:Z,cachedComponents:w})}let i=s.flatMap(x=>x.outgoing),a=or(i,o),c=new Set(a.components.map(x=>z(x.path,x.name))),l=[],u=[],d=[],p=[],f=[],_=[],E=[];for(let x of s){let{scope:P,walk:U,delta:w}=x;_.push(...U.components),l.push(P);let j=a.components.filter(C=>x.outgoingKeys.has(z(C.path,C.name))),Z=[...x.outgoingKeys].some(C=>!c.has(C)),D=w.truncated||Z;D?d.push(P):w.full&&u.push(P),p.push(...j),!w.full&&!D&&f.push(...w.removed);let b=w.full?{}:{...x.cachedComponents??{}};if(!D)for(let C of w.removed)delete b[z(C.path,C.name)];for(let C of j)b[z(C.path,C.name)]=C.content_hash;E.push({scope:P,scopeRef:U.scopeRef,components:b,textHashes:rr(x.deliveredTextHashes,j.filter(C=>C.text!==void 0).map(C=>C.content_hash),U.components),collectedAtMs:r,included:j.length>0||w.removed.length>0&&!D||w.full})}let S={user_spec_hash:Je(_),user_spec_count:_.length,user_spec_truncated:d.length>0};l.length>0&&(S.user_spec_scopes=l,S.user_spec_full_scopes=u,S.user_spec_truncated_scopes=d,S.user_spec_cwd_in_git_repo=t.cwdInGitRepo),u.length>0&&u.length===l.length&&(S.user_spec_full=!0),p.length>0&&(S.user_spec=p),f.length>0&&(S.user_spec_removed=f),a.textDeferredCount>0&&(S.user_spec_text_deferred=a.textDeferredCount);let y=t.scopes.cwd;y&&(S.user_spec_cwd_scope_ref=y.scopeRef);let R=t.scopes.repo;R&&(S.user_spec_repo_scope_ref=R.scopeRef);let H=t.scopes.parent;return H&&(S.user_spec_parent_scope_ref=H.scopeRef,t.parentRel&&(S.user_spec_parent_rel=t.parentRel)),{fields:S,scopes:E}}var Qe={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function wt(e){return e==="cwd"||e==="repo"||e==="parent"}function Ze(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ar(e){return!Ze(e)||!Ze(e.components)||!Object.values(e.components).every(t=>typeof t=="string")||!Array.isArray(e.text_hashes)||!e.text_hashes.every(t=>typeof t=="string")?!1:typeof e.collected_at_ms=="number"&&Number.isFinite(e.collected_at_ms)}function Ii(e){return vp(e)}function Ai(e){return Mp(e)}function ki(e){return wp(e)}function vp(e){if(!Ze(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function Mp(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function cr(e,t){if(!Ze(e))return;let n=e[t];return ar(n)?n:void 0}function wp(e){if(!Ze(e))return{};let t={};for(let[n,r]of Object.entries(e))ar(r)&&(t[n]=r);return t}function ur(e,t=20){let n=[];for(let[r,o]of Object.entries(e))ar(o)&&n.push([r,o]);return n.sort((r,o)=>o[1].collected_at_ms-r[1].collected_at_ms),Object.fromEntries(n.slice(0,t))}var Dp=200,Oi=200,Hp=["allow","deny","ask"],Fp=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,dr="<path>",jp=new RegExp(`${dr}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function Kp(e){let t=e.replace(Fp,dr).replace(jp,dr);return t.length>Oi?`${t.slice(0,Oi)}...`:t}function Lt(e){let t=L(e,{}),n=[];for(let r of Hp)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:Kp(o),mode:r});return{model:t.model??"",permissionKeys:n}}function $p(e){let{serverManaged:t,fileBased:n}=un(process.platform,e),r=Lt(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=Lt(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function Bp(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 Gp=10,zp="self-config-cache.json",xi=2;function Ut(){return I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function Wp(){return I("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function Jp(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=De}var Vp={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function Yp(e,t=M){let n=Vp[e];if(!n||n.length===0)return null;let r=async o=>{let s=n[o];if(s===void 0)return null;let a=((await t(s,["--version"],2e3)).split(`
|
|
31
|
-
`)[0]??"").trim();return a||r(o+1)};return r(0)}function
|
|
32
|
-
`);return
|
|
33
|
-
`)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: self-config cache write failed open: ${r}`)}}function
|
|
34
|
-
${n}`}function
|
|
35
|
-
`);if(t<0)return null;let n;try{n=JSON.parse(e.slice(0,t))}catch{return null}return{meta:n,body:e.slice(t+1)}}async function
|
|
36
|
-
`,u=I("EV_AI_HOOK_DEBUG");u==="full"?h(`DEBUG envelope=${JSON.stringify(c)}`):u==="1"&&h(`DEBUG summary=${af(c,Buffer.byteLength(l,"utf8"))}`);let d=process.argv.includes(Ht),p=I("EV_AI_HOOK_SYNC")==="1";return St(n.runnerEvent,n.runnerPlatform)||d||p?df(e,l,o):(await pf(e,l,o),!1)}import{createReadStream as ff}from"node:fs";import{stat as mf}from"node:fs/promises";import{basename as gf,resolve as _f}from"node:path";import{createInterface as hf}from"node:readline";var Sf=1024*1024;function Ef(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&gf(t).endsWith(".jsonl")}async function Hi(e){if(!e||!Ef(e))return null;try{let t=_f(e),n=await mf(t);if(!n.isFile())return null;let r=Math.max(0,n.size-Sf),o=[],s=hf({input:ff(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let i of s)i.length!==0&&o.push(i);r>0&&o.length>0&&o.shift();for(let i=o.length-1;i>=0;i--){let a=o[i];if(a)try{let c=JSON.parse(a);if(c.type!=="assistant")continue;let l=c.message;if(!l||typeof l!="object")continue;let u=l.model;if(typeof u=="string"&&u.length>0)return u}catch{continue}}return null}catch{return null}}function jt(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function tt(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function gr(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo}}async function Ki(e){let t=Date.now();await Tf(e);let{gitRoot:n}=e.manifest;await Kt(e,n);let r=gr(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:At(e.hookInput,e.manifest.manifest,r),envelopeFields:jt(e),launchCwd:jn(e.hookInput,r),home:Rf()}}function Fi(e){try{return G(yf(e))}catch{return null}}function $i(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function ji(e,t){let n=e.replaceAll("\\","/");if(!$i(n))return null;let r=G(e),o=G(t),s=Fi(e)??r,i=Fi(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function Cf(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=ji(e,t)??($i(r)?null:r),i=ji(e,n);return{repositorySourcePath:s,userSourcePath:i}}function Ft(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=Cf(e,t,n),c=i??a,l=c===null?null:o(c),u=l!==null&&c!==null?If({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 If(e){try{let t=e.inRepository?Af(e.platformAgentId,e.sourcePath):(0,O.installationRootExternalKey)(e.installationId,(0,O.userConfigRootFromPath)(e.sourcePath));return t?(0,O.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function Bi(e,t,n){return we("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Me,e.manifest.collectorUrl,t.buildStartedAtMs,tt(e,t.home))}var Gi=new Set([...Object.values(he),".github"]);function Af(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=>Gi.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function kf(e,t,n,r,o,s,i){if(e===null||t===null||!(i!==null||/^mcp__.+?__.+$/i.test(e)||/^MCP:[^:]+:.+$/i.test(e)||/^MCP:.+__.+$/i.test(e)||e.toLowerCase()===`mcp:${t.toLowerCase()}`))return;let c=s.find(_=>_.name.toLowerCase()===t.toLowerCase()),l=c?.sourcePath??(c?.source==="claude_json_user"?".claude.json":c?.source==="cursor_mcp_user"?".cursor/mcp.json":c?.source==="codex_toml_user"||c===void 0&&o==="codex"?".codex/config.toml":void 0);if((c?.scope==="user"||c?.source==="claude_json_user"||c?.source==="cursor_mcp_user"||c?.source==="codex_toml_user"||c===void 0&&o==="codex")&&l)try{let _=(0,O.userConfigRootFromPath)(l);return(0,O.buildComponentReference)({installationRootExternalKey:(0,O.installationRootExternalKey)(r,_),installableKind:O.ComponentKind.INTERFACE,sourcePath:l,nativeKey:c?.name??t})}catch{return}if(n===null)return;let 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||!Gi.has(f)))try{return(0,O.buildComponentReference)({installationRootExternalKey:n,installableKind:O.ComponentKind.INTERFACE,sourcePath:p,nativeKey:t})}catch{return}}function Of(...e){for(let t of e)if(t)return t;return null}function W(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return h(`WARN: ${n} failed open: ${r}`),t}function Pf(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 xf(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var ye=new Set,et=null;async function Tf(e){if(Ut())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(ye.has(t))return;if(!Hn(n)){ye.add(t);return}let r=Le({sessionId:e.sessionId,hostname:Ue()});if(Ls(r)){if(et){await et;return}et=(async()=>{if(ye.has(t)||!Hn(n)){ye.add(t);return}if(!eo(n)){ye.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,l,u,d,p]=await Promise.allSettled([$e(i),Zt(),bn(r),Qt(),Dn({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),f=W(c,null,"gitSnapshot"),_=W(l,"","detectVirt"),E=W(u,null,"probeCloud"),S=W(d,{},"hostEnv"),y=W(p,{commit:()=>{}},"resolveOperatorForSend");await Kt(e,i,f);let R={identity:{host:Ue(),context:r,virt:_||null,cloud:E,git:f},host_env:S,env_vars:vn(),self_config:xf(a,y.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await we("session_start",R,jt(e),Me,e.manifest.collectorUrl,s,tt(e)),o&&(y.commit(),ye.add(t))}finally{to(n)}})().finally(()=>{et=null}),await et}}async function Kt(e,t,n){try{let r=n===void 0?await $e(t):n;e.platformAgentId=await 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 bf(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Le({sessionId:e.sessionId,hostname:Ue()}),o=String(e.runnerPlatform),s=gr(e),i=jn(e.hookInput,s),a=$e(n),c=Ut()?Promise.resolve({commit:()=>{}}):Dn({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[l,u,d,p,f,_,E]=await Promise.allSettled([a,Zt(),bn(r),Qt(),kn(e.manifest.manifest,n,o),a.catch(()=>null).then(b=>Ti(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:b?.remote??null})),c]),S=W(l,null,"gitSnapshot"),y=W(u,"","detectVirt"),R=W(d,null,"probeCloud"),H=W(p,{},"hostEnv"),x=W(f,[],"mcpDeclared"),P=W(_,Pf(o),"selfConfig"),U=W(E,{commit:()=>{}},"resolveOperatorForSend"),w=P.config;await Kt(e,n,S);let j=m(e.hookInput,"model");j&&(w.model=j);let Z={identity:{host:Ue(),context:r,virt:y||null,cloud:R,git:S},host_env:H,env_vars:vn(),mcp:{declared:x},self_config:w,run_meta:{trigger:e.hookSource||"startup"},hook_input:At(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})};await we("session_start",Z,jt(e),Me,e.manifest.collectorUrl,t,tt(e))&&(P.commit(),U.commit(),ye.add(e.manifest.installationId))}async function vf(e){let t=Date.now(),{gitRoot:n}=e.manifest;await Kt(e,n);let r=Of(m(e.hookInput,"status"),m(e.hookInput,"stop_reason"),m(e.hookInput,"reason"),ze(m(e.hookInput,"error"))),o=e.runnerPlatform==="claude"?await Hi(m(e.hookInput,"transcript_path")):null,s=At(e.hookInput,e.manifest.manifest,gr(e));o&&(s.model=o),await we("session_end",{status:r,...o?{model:o}:{},hook_input:s},jt(e),Me,e.manifest.collectorUrl,t,tt(e))}function zi(e,t,n,r){let o=r??Ao({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=Ft(o,t.gitRoot,t.home,O.ComponentKind.SKILL,O.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&dn(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??Go({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=Ft(i,t.gitRoot,t.home,O.ComponentKind.COMMAND,O.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function Mf(e,t,n){let r=pt(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=zi(e,t,o,r);return Bi(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 wf(e,t,n){return Promise.all(n.map(r=>{let o=jo({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=Ft(o,t.gitRoot,t.home,O.ComponentKind.RULE,O.nativeKeyForRulePath,e),i=s.nativeKey??$o(r);return Bi(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var Nf=[{kind:O.ComponentKind.SKILL,nativeKeyFn:O.nativeKeyForSkillPath},{kind:O.ComponentKind.RULE,nativeKeyFn:O.nativeKeyForRulePath},{kind:O.ComponentKind.COMMAND,nativeKeyFn:O.nativeKeyForCommandPath}];function Lf(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=fn(e.hookInput);if(r===null)return n.skillName===null?{}:zi(e,t,n.skillName,null);for(let o of Nf){let s=Ft(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===O.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===O.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var Uf=/mcp/i;function Df(e,t,n,r){let o=Uf.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?pi(t,n):Mt(r.declaredConfig,n);return s===null?{}:Object.fromEntries(Object.entries(s).filter(i=>typeof i[1]=="string").map(([i,a])=>[`mcp_${i}`,a]))}async function Hf(e){let t=await Ki(e),n=ns(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=pn(e.hookInput),i=li(s,t.home),a=os(e.hookInput),c=Zo(e.runnerEvent),l=c===!1?ss(e.hookInput,e.runnerEvent):null,u=await kn(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),d=ze(m(e.hookInput,"mcp_server_name")),{mcpServer:p,mcpTool:f}=is(r,u.map(U=>U.name),d??""),_=kf(r,p,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),u,d),E=_===void 0?Lf(e,t,n):{},S=p===null?null:Xo(p,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),y=Df(e,s,t.home,{hasMcpIdentity:!!p||!!f,declaredConfig:S}),R=_??E.componentReference,H=E.ruleName??n.ruleName,x=E.commandName??n.commandName,P=rs(e.hookInput);await we("tool_invoked",{tool_name:r,skill_name:o,...H?{rule_name:H}:{},...x?{command_name:x}:{},success:c,duration_ms:a,...i?{executable:i}:{},...l?{failure_reason:l}:{},...p?{mcp_server:p}:{},...f?{mcp_tool:f}:{},...y,...R?{component_reference:R}:{},...P?{subagent_type:P}:{},hook_input:t.hookInput},t.envelopeFields,Me,e.manifest.collectorUrl,t.buildStartedAtMs,tt(e,t.home))}async function Wi(e){switch(e.internalEvent){case"session_start":await bf(e);return;case"session_end":await vf(e);return;case"skill_invoked":{let t=ko(e.hookInput),n=Bo(e.hookInput);if(t.length===0&&n.length===0)return;let r=await Ki(e);await Promise.all([t.length===0?void 0:Mf(e,r,t),n.length===0?void 0:wf(e,r,n)]);return}case"tool_invoked":await Hf(e);return;default:return}}function Ji(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{existsSync as hr,readFileSync as Ff}from"node:fs";import{homedir as jf}from"node:os";import{dirname as Kf,isAbsolute as $f,join as Xi,relative as Bf}from"node:path";var Gf=[Tr,".cursor/ev-ai-runtime-report.json",".codex/ev-ai-runtime-report.json"];function Vi(e=jf()){return Xi(e,".ev-ai",br)}function Yi(e){for(let t of Gf){let n=Xi(e,t);if(hr(n))return n}}async function zf(e=process.cwd(),t){let n=t??await Vt(e);return Yi(n)??Yi(e)}async function Wf(e,t){let n=t??await Vt(Kf(e)),r=Bf(n,e);if(r.startsWith("..")||$f(r))return!1;let o=await J("git",["ls-files","--error-unmatch",r],2e3,{cwd:n});return o.ok?!0:o.code===1?!1:(h(`WARN: git ls-files failed for manifest ${e} (code=${String(o.code)}); treating as tracked`),!0)}function _r(e){let t=Ff(e,"utf8");return F(t,{})}function Jf(){return{schema_version:2,mcp_servers:[]}}function Vf(e,t){return{...e,...t}}function Yf(e,t,n,r){!t||!n||(e.capture_hook_input==="full"&&r.has("capture_hook_input")&&(h(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${t}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete e.capture_hook_input),e.debug===!0&&r.has("debug")&&(h(`WARN: ignoring debug=true in git-tracked manifest ${t}; set debug on ~/.ev-ai/config.json`),delete e.debug))}async function qi(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await Jt(e),o=I("EV_AI_HOOK_MANIFEST"),s=o&&hr(o)?o:void 0,i=s?void 0:hr(Vi())?Vi():void 0,a=s?void 0:await zf(e,n),c=i?_r(i):void 0,l=a?_r(a):void 0,u,d,p,f=new Set;if(s){u=_r(s),d=s,p=s;for(let R of Object.keys(u))f.add(R)}else if(c&&l){u=Vf(l,c),d=i,p=a;for(let R of Object.keys(l))R in c||f.add(R)}else if(c)u=c,d=i;else if(l){u=l,d=a,p=a;for(let R of Object.keys(l))f.add(R)}else u=Jf();delete u.installation_id;let _=p?await Wf(p,n):!1;Yf(u,p,_,f);let{installationId:E,storePath:S,repoKey:y}=await so(n,{sessionId:t.sessionId});return{manifestPath:d??S,manifest:u,installationId:E,installationStorePath:S,repoKey:y,collectorUrl:lo(u),platformAgentId:u.platform_agent_id??"",gitRoot:n,inGitRepo:r}}async function Zi(e,t,n,r){let o=t??await Wt(tn),s=F(o,{}),i=m(s,"session_id")||m(s,"conversation_id"),a=await qi(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=Qo(s,a.manifest.platform,n),l=es(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(Ji(l)){h(`WARN: unsupported internal event '${l}'`);return}await Wi(u)}function Xf(e,t){if(I("EV_AI_HOOK_SYNC")==="1")return!0;let n=ht(e),r=F(t,{}),o=n.event??(m(r,"hook_event_name")||m(r,"event")),s=Ge(r,o,void 0,n.runner);return St(o,s)}async function Qi(e=process.argv.slice(2)){if(e[0]===mr){try{await Li(zt)}catch{}return 0}if(e[0]===Ht){try{let t=ht(e.slice(1)),n=await zt(),r=F(n,{}),o=t.event??(m(r,"hook_event_name")||m(r,"event"));if(Xt()||xn(t.runner,r,o))return 0;await Zi(t.event,n,t.runner,Pn(t))}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: detached work failed open: ${n}`)}return 0}try{let t=await Wt(tn),n=ht(e),r=Pn(n),o=F(t,{}),s=n.event??(m(o,"hook_event_name")||m(o,"event"));if(Xt()||xn(n.runner,o,s)||!fs(o,s,n.runner))return 0;Xf(e,t)?await Zi(n.event,t,n.runner,r):await Di(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: hook failed open: ${n}`)}finally{Ar()}return 0}Qi().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
|
|
29
|
+
`.trim(),er=new Map;function Ci(e){if(typeof e=="string"){let t=e.trim();return t.length>0?t:null}if(e instanceof Uint8Array){let t=Buffer.from(e).toString("utf8").trim();return t.length>0?t:null}return null}function Ai(e){return e.toLowerCase().includes("token")}function Oi(e){let t=new Map;if(!Array.isArray(e))return t;for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=Ci(r.key),s=Ci(r.value);o&&s&&!Ai(o)&&t.set(o,s)}return t}function tf(e){let t=ef(e);return t.search="mode=ro&immutable=1",t.href}function nf(e){try{let t=Ii("bun:sqlite");if(typeof t.Database!="function")return null;let n=new t.Database(e,{readonly:!0,create:!1});try{let r=n.query?.(vt)??n.prepare(vt);return Oi(r.all?.())}finally{n.close?.()}}catch{return null}}function rf(e){let t=process.emitWarning.bind(process);process.emitWarning=((n,...r)=>{(typeof n=="string"?n:n instanceof Error?n.message:"").includes("SQLite is an experimental feature")||t(n,...r)});try{return e()}finally{process.emitWarning=t}}function of(e){try{return rf(()=>{let t=Ii("node:sqlite");if(typeof t.DatabaseSync!="function")return null;let n=new t.DatabaseSync(e,{readOnly:!0});try{return Oi(n.prepare(vt).all?.())}finally{n.close?.()}})}catch{return null}}function sf(e){let t=new Map;for(let n of e.split(`
|
|
30
|
+
`)){let r=n.trimEnd();if(!r)continue;let o=r.indexOf(" ");if(o<=0)continue;let s=r.slice(0,o).trim(),i=r.slice(o+1).trim();s&&i&&!Ai(s)&&t.set(s,i)}return t}function af(e){try{let t=Zp("sqlite3",["-noheader","-batch","-separator"," ",e,vt],{encoding:"utf8",timeout:2e3,maxBuffer:65536,windowsHide:!0,stdio:["ignore","pipe","ignore"]});return sf(t)}catch{return null}}function Pi(e){let t=er.get(e);if(t)return t;if(!qp(e)){let o=new Map;return er.set(e,o),o}let n=tf(e),r=nf(n)??af(n)??of(n)??new Map;return er.set(e,r),r}var cf="cursorAuth/cachedEmail",uf="cursorAuth/stripeMembershipAuthId";function wt(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function lf(e=Lt(),t=process.platform,n=process.env){let r=wt(n.VSCODE_PORTABLE);if(r)return ae(r,"user-data");let o=wt(n.VSCODE_APPDATA);if(o)return ae(o,"Cursor");switch(t){case"darwin":return ae(e,"Library","Application Support","Cursor");case"win32":return ae(wt(n.APPDATA)??ae(e,"AppData","Roaming"),"Cursor");default:return ae(wt(n.XDG_CONFIG_HOME)??ae(e,".config"),"Cursor")}}function df(e=Lt()){return ae(e,".cursor","cli-config.json")}function pf(e=Lt(),t=process.platform,n=process.env){return ae(lf(e,t,n),"User","globalStorage","state.vscdb")}function et(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function ff(e){return typeof e.userId=="number"&&Number.isFinite(e.userId)?String(e.userId):et(e.userId)}function mf(e){return et(e.email)??et(e.authId)??ff(e)}function tr(e){let t=et(e.email),n=et(e.displayName),r=mf(e);return!r||G(n,t)?null:{git_user_name:null,git_user_email:null,platform_login:r,identity_source:"cursor_oauth"}}function gf(e){let n=D(df(e),{}).authInfo;return!n||typeof n!="object"?null:tr(n)}function _f(e,t,n){let r=pf(e,process.platform,t),o=Ei(e),s=Si(o);if(yi(s,r,n))return tr({email:s?.email,authId:s?.auth_id});let i=Pi(r),a=i.get(cf)??null,c=i.get(uf)??null;return Ri(o,{read_at_ms:n,db_path:r,email:a,auth_id:c}),tr({email:a,authId:c})}function Ti(e=Lt(),t=process.env,n=Date.now()){return gf(e)??_f(e,t,n)}import{createHash as hf}from"node:crypto";import{resolve as Ef}from"node:path";function U(e){return hf("sha256").update(e).digest("hex").slice(0,16)}function nr(e){return U(Ef(e))}function V(e,t){return`${e}\0${t}`}function ki(e){let t=e.indexOf("\0");return t<=0?null:{path:e.slice(0,t),name:e.slice(t+1)}}function tt(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(`
|
|
31
|
+
`);return U(n)}function yf(e,t,n="git_config",r=null){return U(`${e??""}|${t??""}|${r??""}|${n}`)}function Rf(e){let t=null,n=null;for(let r of e.split(`
|
|
32
|
+
`)){let o=r.trim();if(!o)continue;let s=o.indexOf(" ");if(s<=0)continue;let i=o.slice(0,s).toLowerCase(),a=o.slice(s+1).trim();a&&(i==="user.name"?t=a:i==="user.email"&&(n=a))}return{git_user_name:t,git_user_email:n,platform_login:null}}async function Cf(e,t=w){let n=await t("git",["config","--get-regexp","^user\\.(name|email)$"],2e3,{cwd:e});return Rf(n)}function If(e=process.env){let t=O(e.GIT_AUTHOR_NAME),n=O(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=O(e.GIT_COMMITTER_NAME),o=O(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=O(e.EMAIL);return s?{git_user_name:null,git_user_email:s,platform_login:null,identity_source:"git_env"}:null}function ce(e,t,n,r=null){return!e&&!t&&!r?null:{git_user_name:e,git_user_email:t,platform_login:r,identity_source:n}}function Af(e=process.env){let t=O(e.EV_AI_HOOK_OPERATOR_EMAIL),n=O(e.EV_AI_HOOK_OPERATOR_LOGIN),r=ce(O(e.EV_AI_HOOK_OPERATOR_NAME),t,"configured",t??n);if(r)return r;let o=O(e.GITHUB_ACTOR)??O(e.GITHUB_TRIGGERING_ACTOR)??O(e.GITHUB_USER),s=ce(o,null,"github",o);if(s)return s;let i=O(e.GITLAB_USER_LOGIN),a=O(e.GITLAB_USER_EMAIL),c=ce(O(e.GITLAB_USER_NAME)??i,a,"gitlab",a??i);if(c)return c;let u=O(e.BUILD_REQUESTEDFOREMAIL),l=ce(O(e.BUILD_REQUESTEDFOR),u,"azure_devops",u??O(e.BUILD_REQUESTEDFORID));if(l)return l;let p=O(e.BUILDKITE_BUILD_CREATOR_EMAIL),m=ce(O(e.BUILDKITE_BUILD_CREATOR),p,"buildkite",p);if(m)return m;let d=O(e.BUILD_USER_EMAIL)??O(e.CHANGE_AUTHOR_EMAIL),g=ce(O(e.BUILD_USER)??O(e.CHANGE_AUTHOR),d,"jenkins",d??O(e.BUILD_USER_ID));if(g)return g;let E=O(e.CIRCLE_USERNAME),S=ce(E,null,"circleci",E);if(S)return S;let y=O(e.CODEBUILD_INITIATOR),R=ce(y,null,"codebuild",y);if(R)return R;let H=O(e.DRONE_COMMIT_AUTHOR_EMAIL),x=O(e.DRONE_COMMIT_AUTHOR),k=ce(x??O(e.DRONE_COMMIT_AUTHOR_NAME),H,"drone",H??x);if(k)return k;if(xi(e.CLAUDE_CODE_REMOTE)||xi(e.CURSOR_AGENT)){let F=O(e.CURSOR_USER_EMAIL);return{git_user_name:null,git_user_email:null,platform_login:F&&!G(null,F)?F:null,identity_source:"cloud"}}return null}function rr(e){return!!((e.git_user_name??e.git_user_email)&&!G(e.git_user_name,e.git_user_email))}function O(e){if(e===void 0)return null;let t=e.trim();return t.length>0?t:null}function xi(e){if(e===void 0||e==="")return!1;let t=e.trim().toLowerCase();return t!=="0"&&t!=="false"&&t!=="no"}function Of(e,t,n){return e==="claude"?di(t):e==="cursor"?Ti(t,n):e==="codex"?_i(n,t):null}async function or(e,t=w,n=process.env,r={}){let o=await Cf(e,t),s=If(n),i=rr(o)?o:s&&rr(s)?s:null,a=Of(r.runnerPlatform,r.home??Sf(),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=Af(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:rr(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 sr(e){let{gitRoot:t,installationStorePath:n,forceResend:r}=e,o=e.exec??w,s=e.env??process.env,i=await or(t,o,s,{runnerPlatform:e.runnerPlatform,home:e.home}),a=yf(i.git_user_name,i.git_user_email,i.identity_source,i.platform_login),u=(n?bn(n):void 0)?.operator_identity_hash;if(!(r||u!==void 0&&u!==a||!u))return{commit:()=>{}};let d=n;return{operator:i,commit:()=>{d&&jo(d,a,ft())}}}function ir(e){return e?!bn(e)?.operator_identity_hash:!0}function bi(e){return!0}import{existsSync as Zm,readFileSync as qm}from"node:fs";import{homedir as Oa}from"node:os";import{join as De,resolve as Qm}from"node:path";import{basename as Gm,join as Ue}from"node:path";import{dirname as Ki,resolve as Ft}from"node:path";import{existsSync as Pf}from"node:fs";import{homedir as vi}from"node:os";import{relative as wi,resolve as ee,sep as ge}from"node:path";var Tf=["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"],kf=["prompt","tool_input","tool_response","last_assistant_message","command"],xf=new Set;function bf(e){switch(e?.toLowerCase()){case"beforemcpexecution":return new Set(["command"]);case"stopfailure":return new Set(["last_assistant_message"]);default:return xf}}function Li(e){return Ui(e)==="allowlist"}function Ui(e){return I("EV_AI_HOOK_CAPTURE_CONTENT")?.toLowerCase()==="off"||e.capture_hook_input==="allowlist"?"allowlist":e.capture_hook_input==="full"||e.debug===!0||I("EV_AI_HOOK_CAPTURE_FULL_INPUT")==="1"?"full":"content"}function Nf(e){let t={};for(let n of Tf){let r=re(e,n);r!==void 0&&(t[n]=r)}return t}function Ut(e,t){if(typeof e!="string"||e.length===0||!t)return null;let n=ee(e),r=ee(t),o=wi(r,n);return!o||o==="."?".":o.startsWith(`..${ge}`)||o===".."||ee(r,o)!==n?null:o.split(ge).join("/")}function Di(e,t){let n=wi(ee(t),ee(e)).split(ge).join("/");return!n||n==="."?null:n===".."||n.startsWith("../")&&n.split("/").every(r=>r==="..")?n:null}function Fi(e){return typeof e!="string"||e.length===0?null:ee(e).split(ge).join("/")}function Mf(){let e=I("CURSOR_PROJECT_DIR");if(!e)return null;let t=ee(e);return Pf(t)?t.split(ge).join("/"):null}function cr(e,t){return Ut(e,t)!==null}function vf(e,t){let n=ee(t??vi(),".cursor").split(ge).join("/");return cr(e,n)}function wf(e,t,n){return t!==null&&cr(e,t)?!0:t!==null&&vf(e,n.home)?!1:n.inGitRepo===!0&&n.gitRoot!==void 0&&cr(e,n.gitRoot)?!0:t===null}function Hi(e,t){let n=Fi(e.cwd);if(n!==null)return n;let r=ee(process.cwd()).split(ge).join("/"),o=Mf();return wf(r,o,t)?r:o??r}function dr(e,t={}){return Hi(e,t)}function pr(e,t=vi()){let n=ee(t).split(ge).join("/").replace(/\/$/,"");return n.length<=1?e:e===n?"~":e.startsWith(`${n}/`)?`~${e.slice(n.length)}`:e}function Ni(e,t,n){let r=Fi(n.launchCwd)??Hi(t,n);e.cwd=pr(r,n.home);let o=n.inGitRepo===!0&&n.gitRoot!==void 0?Ut(r,n.gitRoot):null;o!==null&&(e.cwd_relative=o)}var ji="\u2026[truncated]\u2026",ur=Buffer.byteLength(ji,"utf8"),Lf=8;function nt(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function Mi(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(0,t).toString("utf8")}function Uf(e,t){if(t<=0)return"";let n=Buffer.from(e,"utf8");return n.length<=t?e:n.subarray(n.length-t).toString("utf8")}function Df(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;if(t<=ur)return Mi(e,t);let r=t-ur,o=Math.ceil(r/2),s=Math.floor(r/2);return`${Mi(e,o)}${ji}${Uf(e,s)}`}function lr(e,t,n){if(typeof e=="string"){n.push({path:t,value:e,bytes:Buffer.byteLength(e,"utf8")});return}if(Array.isArray(e)){e.forEach((r,o)=>{lr(r,[...t,o],n)});return}if(e!==null&&typeof e=="object")for(let[r,o]of Object.entries(e))t.length===0&&r.startsWith("_")||lr(o,[...t,r],n)}function Ff(e,t,n){let r=e;for(let s=0;s<t.length-1;s++){let i=t[s];if(i===void 0)return;r=(Array.isArray(r),r[i])}let o=t[t.length-1];if(!(o===void 0||r===null||typeof r!="object")){if(Array.isArray(r)){r[o]=n;return}r[o]=n}}var Hf=256;function jf(e,t,n){let r=n,o=Math.max(n,e[0]?.bytes??n);for(;r<o;){let s=Math.ceil((r+o)/2),i=0;for(let a of e)a.bytes>s&&(i+=a.bytes-s);i>=t?r=s:o=s-1}return r}function Kf(e,t,n){let r=Number.POSITIVE_INFINITY;for(let o=0;o<6;o++){let s=nt(e);if(s<=t)return;let i=[];lr(e,[],i),i.sort((l,p)=>p.bytes-l.bytes);let a=i.filter(l=>l.bytes>n);if(a.length===0)return;let c=jf(a,s-t,n),u=Math.max(n,Math.min(c,r-1));if(u>=r)return;r=u;for(let l of a)l.bytes>r&&Ff(e,l.path,Df(l.value,r))}}function $f(e,t){let n=Math.max(0,t-Hf),r=Object.keys(e).filter(s=>!s.startsWith("_")).map(s=>({key:s,bytes:nt(e[s])})).sort((s,i)=>i.bytes-s.bytes),o=[];for(let{key:s}of r){if(nt(e)<=n)break;delete e[s],o.push(s)}o.length>0&&(e._dropped_keys=o.slice(0,10))}function ar(e,t){let n=nt(e);if(n<=t)return e;let r=structuredClone(e);return r._truncated=!0,r._original_bytes=n,Kf(r,t,ur+Lf),nt(r)>t&&$f(r,t),r}function Bf(e,t,n){let r=bf(n.runnerEvent);for(let o of kf){if(r.has(o))continue;let s=t[o];s!==void 0&&(e[o]=s)}}function Dt(e,t,n={}){let r=Ui(t);if(r==="full"){let s={...e};return delete s.cwd,delete s.transcript_path,Ni(s,e,n),ar(s,On)}let o=Nf(e);return Ni(o,e,n),r==="content"?(Bf(o,e,n),ar(o,On)):ar(o,Ao)}function Gf(e){return typeof e=="string"&&e.length>0}function fr(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&&Gf(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&&Ut(n,r)!==null;if(e.inGitRepo&&r!==null&&r!==t&&c){let u=Ki(r);for(;;){let l=Ft(u);if(l===t)break;let p=Ki(l);if(p===l)break;if(e.hasProjectSpec(l)){s.push({scope:"parent",dir:l}),a=Di(l,n);break}u=p}}return{anchors:s,parentRel:a}}import{existsSync as $i,readdirSync as zf,realpathSync as Vf}from"node:fs";import{basename as Wf,dirname as Yf,relative as Jf,resolve as Xf,sep as Zf}from"node:path";var mr=400,Ht=class{constructor(t,n={}){this.home=t;this.pathMode=n.pathMode??"home-relative",this.maxEntries=n.maxEntries??ue}components=[];truncated=!1;pathMode;maxEntries;pluginExpandRemaining;seenRealpaths=new Set;componentPath(t){if(this.pathMode==="tilde"){let r=Xf(t).split(Zf).join("/");return pr(r,this.home)}let n=Jf(this.home,t).replace(/\\/g,"/");return!n||n.startsWith("..")?`external/${U(Yf(t))}/${Wf(t)}`:n}claimFile(t){try{let n=Vf(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(!$i(t))return[];try{return zf(t,{withFileTypes:!0})}catch{return[]}}readJson(t,n){if($i(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 gr,readFileSync as qf,statSync as Qf}from"node:fs";import{basename as Gi,join as rt,relative as zi}from"node:path";var _r=100*1024,em=4;function tm(e){return e.length<=_r?e:`${e.slice(0,_r-1)}\u2026`}function nm(e){try{let t=qf(e),n=t.toString("utf8");return{hash:U(t),length:t.length,text:tm(n)}}catch{return null}}var Bi={HOOK:"EVENT",COMMAND:"EXPLICIT_INVOCATION",MEMORY:void 0,MCP_SERVER:void 0,PLUGIN:void 0,SKILL:"UNSPECIFIED",RULE:"UNSPECIFIED",SUBAGENT:"UNSPECIFIED"};function rm(e){return e in Bi?Bi[e]:"UNSPECIFIED"}function jt(e,t){if(!e.claimFile(t.absolutePath))return!1;let n=nm(t.absolutePath);if(!n)return!1;let r=t.name??Gi(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=rm(t.kind);return s&&(o.trigger=s),e.push(o)}function om(e,t,n){let r=zi(e,t).replace(/\\/g,"/");return!r||r.startsWith("..")?Gi(t).replace(/\.(md|mdc|toml)$/i,""):n?r.replace(/\.(md|mdc|toml)$/i,""):r}function Ie(e,t){let{dir:n,kind:r,origin:o,enabled:s,nested:i,extensions:a}=t;hr(e,{walkRoot:n,currentDir:n,depth:0,kind:r,origin:o,enabled:s,nested:i,extensions:a})}function hr(e,t){let{walkRoot:n,currentDir:r,depth:o,kind:s,origin:i,enabled:a,nested:c,extensions:u}=t;if(!(o>em))for(let l of e.readEntries(r)){if(e.atGlobalCap){e.truncated=!0;return}if(e.pluginBudgetSpent)return;if(c){if(!l.isDirectory())continue;let d=rt(r,l.name,c);if(gr(d)){let g=zi(n,rt(r,l.name)).replace(/\\/g,"/");jt(e,{absolutePath:d,kind:s,origin:i,enabled:a,name:g||l.name});continue}hr(e,{walkRoot:n,currentDir:rt(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(l.isDirectory()){hr(e,{walkRoot:n,currentDir:rt(r,l.name),depth:o+1,kind:s,origin:i,enabled:a,nested:c,extensions:u});continue}if(!l.isFile()||!u)continue;let p=l.name.toLowerCase();if(!u.some(d=>p.endsWith(d)))continue;let m=rt(r,l.name);jt(e,{absolutePath:m,kind:s,origin:i,enabled:a,name:om(n,m,!0)})}}function Vi(e){for(let t of e)if(gr(t))try{if(Qf(t).size>0)return t}catch{continue}return e.find(t=>gr(t))}var Kt=je(Me(),1);var sm="<omitted>",im=["package_name","package_spec","package_version","package_version_source"],Wi=100,Yi=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"}],Ji=new Set($t.map(e=>e.attr)),am=["enabled","disabled"],cm=["serverUrl","auth","bearer_token_env_var","default_tools_approval_mode","defaultToolsApprovalMode","env_vars","env_http_headers","http_headers"],um=new Set(["type","command","url","args","env","envVars","headers",...am,...cm,...$t.map(e=>e.raw)]),lm=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",...im,...Ji,...[...Ji].map(e=>`${e}_truncated`)]);function Xi(e,t){for(let n of t)um.has(n)||lm.has(n)||(e[n]=sm)}var dm=/^(authorization|auth|api[-_]?key|access[-_]?token|refresh[-_]?token|secret|password|passwd|token|bearer|client[-_]?secret|client[-_]?id|private[-_]?key|signing[-_]?key)$/i,pm=/(?:^|[-_])(secret|password|passwd|token|api[-_]?key|private[-_]?key|signing[-_]?key|client[-_]?secret|client[-_]?id)(?:[-_]|$)/i,fm=/^(sk-|ghp_|gho_|github_pat_|xox[baprs]-|AKIA|ASIA|AIza|ya29\.)/,mm=/^bearer(?:\s+|$)/i;function Bt(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function Zi(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"&&t.length>0):[]}function Er(e){if(Array.isArray(e)){let n=[];for(let r of e){if(typeof r!="string"||r.length===0)continue;let o=r.split("=",1)[0]?.trim();o&&n.push(o)}return n}let t=Bt(e);return t?Object.keys(t).filter(n=>n.length>0):[]}function Ae(e){try{let t=new URL(e);return`${t.origin}${t.pathname}`}catch{return e}}function gm(e,t){if(e!==void 0&&/^https?:\/\//i.test(e)&&(0,Kt.launchContainsCredentials)({kind:"url",url:e})||(0,Kt.launchContainsCredentials)({kind:"command",command:e??"",arguments:t}))return!0;let n=st([...t]);return t.some((r,o)=>n[o]===r?!1:/^https?:\/\//i.test(r)?(0,Kt.launchContainsCredentials)({kind:"url",url:r}):!0)}function qi(e,t,n){gm(t,n)&&(e.launch_had_credentials=!0)}function _m(e){return fm.test(e)||mm.test(e)?"<redacted>":e.includes("://")?Ae(e):e}function Qi(e){if(/^https?:\/\//i.test(e))return Ae(e);let t=e.indexOf("=");return t>0?`${e.slice(0,t+1)}${Qi(e.slice(t+1))}`:_m(e)}function hm(e){let t=e.replace(/^-+/,"").split("=",1)[0]??"";return dm.test(t)||pm.test(t)}function st(e){let t=[],n=!1;for(let r of e){if(n){t.push("<redacted>"),n=!1;continue}if(hm(r)){t.push("<redacted>"),n=!r.includes("=");continue}t.push(Qi(r))}return t}function Em(e){let t=Zi(e);if(t.length===0)return;let n=[...new Set(t.map(r=>r.length>Yi?r.slice(0,Yi):r))].sort();if(n.length!==0)return n.length>Wi?{names:n.slice(0,Wi),truncated:!0}:{names:n,truncated:!1}}function Sm(e){let t=Bt(e);if(!t)return{headers:[],envVars:[]};let n=[],r=[];for(let[o,s]of Object.entries(t))o.length>0&&n.push(o),typeof s=="string"&&s.length>0&&r.push(s);return{headers:n,envVars:r}}function ea(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=Em(s);i&&(e[o]=i.names,i.truncated&&(e[`${o}_truncated`]=!0),n.add(o))}}function ta(e,t){let n=Bt(e),r={transport:t};if(!n)return r;Xi(r,Object.keys(n));let o=typeof n.command=="string"?n.command:void 0,s=typeof n.url=="string"?n.url:void 0,i=typeof n.serverUrl=="string"?n.serverUrl:void 0,a=o??s??i,c=Zi(n.args);a&&(r.command_or_url=Ae(a));let u=st(c);u.length>0&&(r.args=u),qi(r,a,c);let l=Sm(n.env_http_headers),p=[...new Set([...Er(n.env),...Er(n.envVars),...Er(n.env_vars),...l.envVars,...typeof n.bearer_token_env_var=="string"&&n.bearer_token_env_var.length>0?[n.bearer_token_env_var]:[]])].sort();p.length>0&&(r.env_var_names=p),l.headers.length>0&&(r.env_http_header_names=[...new Set(l.headers)].sort());for(let E of["headers","http_headers","env_http_headers"])if(n[E]!==void 0&&n[E]!==null){r.headers_present=!0;break}let m=typeof n.auth=="string"?n.auth:void 0;m&&(r.auth=m);let d=typeof n.bearer_token_env_var=="string"?n.bearer_token_env_var:void 0;d&&(r.bearer_token_env_var=d);let g=typeof n.default_tools_approval_mode=="string"?n.default_tools_approval_mode:typeof n.defaultToolsApprovalMode=="string"?n.defaultToolsApprovalMode:void 0;return g&&(r.default_tools_approval_mode=g),ea(r,n),r}function na(e){let t=Bt(e);return t?t.enabled===!1?!1:t.disabled!==!0:!0}function Rr(e,t,n=!0){let r=Object.keys(t).sort().map(o=>[o,t[o]??null]);return U(JSON.stringify({name:e,attributes:r,enabled:n}))}function we(e){let t=e.trim();return t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'")?t.slice(1,-1):t}function ot(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 yr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(true|false)\\s*$`,"m").exec(e);if(n?.[1])return n[1]==="true"}function Sr(e,t){let n=new RegExp(`^\\s*${t}\\s*=\\s*(.+)$`,"m").exec(e);if(!n?.[1])return;let r=we(n[1]);return r.length>0?r:void 0}function ym(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],we(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(`
|
|
33
|
+
${e}`);return s?.[1]&&r(s[1]),n}function ra(e){return yr(e,"enabled")===!1?!1:yr(e,"disabled")!==!0}function Rm(e,t){let n={};for(let{raw:r,attr:o}of $t){if(o==="auto_approve"){let i=yr(t,r);if(i!==void 0){n[r]=i;continue}}let s=ot(t,r);s.length>0&&(n[r]=s)}ea(e,n)}var Cm=/^\s*([A-Za-z_][A-Za-z0-9_-]*)\s*[.=]/,Im=/^\[[^\]]*\.([A-Za-z_][A-Za-z0-9_-]*)\]\s*$/gm;function Am(e){let t=new Set,n=e.search(/^\[/m),r=n===-1?e:e.slice(0,n);for(let o of r.split(`
|
|
34
|
+
`)){let s=Cm.exec(o);s?.[1]&&t.add(s[1])}for(let o of e.matchAll(Im))o[1]&&t.add(o[1]);return[...t]}function oa(e,t){let n={transport:t};Xi(n,Am(e));let r=/^\s*command\s*=\s*(.+)$/m.exec(e),o=/^\s*url\s*=\s*(.+)$/m.exec(e),s=r?we(r[1]??""):void 0,i=o?we(o[1]??""):void 0,a=s!==void 0&&s.length>0?s:i,c=ot(e,"args");a&&(n.command_or_url=Ae(a));let u=st(c);u.length>0&&(n.args=u),qi(n,a,c);let l=new Set;for(let y of e.split(`
|
|
35
|
+
`)){let R=/^\s*env\.([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&l.add(R[1])}let p=/^\s*env\s*=\s*\{([^}]*)\}/m.exec(e);if(p?.[1])for(let y of p[1].split(",")){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&l.add(R[1])}let m=/(?:^|\n)\[[^\]]*env\]\s*\n([\s\S]*?)(?=\n\[|$)/.exec(`
|
|
36
|
+
${e}`);if(m?.[1])for(let y of m[1].split(`
|
|
37
|
+
`)){let R=/^\s*([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(y);R?.[1]&&l.add(R[1])}for(let y of ot(e,"env_vars"))l.add(y);let d=ym(e,"env_http_headers");for(let[,y]of d)y.length>0&&l.add(y);let g=Sr(e,"bearer_token_env_var");g&&(l.add(g),n.bearer_token_env_var=g),l.size>0&&(n.env_var_names=[...l].sort()),d.length>0&&(n.env_http_header_names=[...new Set(d.map(([y])=>y))].sort()),(/^\s*(?:http_|env_http_)?headers\s*=/m.test(e)||/(?:^|\n)\[[^\]]*headers\]\s*(?:\n|$)/.test(e))&&(n.headers_present=!0);let E=Sr(e,"auth");E&&(n.auth=E);let S=Sr(e,"default_tools_approval_mode");return S&&(n.default_tools_approval_mode=S),Rm(n,e),n}var Om=300,Pm=256;function sa(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 Gt(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 ia(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function Tm(e){return ia(e,Om)}function aa(e,t){let n=sa(e.trim(),t),r=Gt(n);if(r.length===0)return"";let[o,...s]=r,i=Ae(o),a=st(s);return Tm([i,...a].join(" "))}function ca(e,t){if(typeof e!="string")return null;let n=sa(e.trim(),t),r=Gt(n)[0];if(!r)return null;let o=Ae(r);return o.length===0?null:ia(o,Pm)}function km(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 xm(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 bm(e,t,n,r){let o=e.componentPath(t);for(let[s,i]of Object.entries(n))if(!(!Array.isArray(i)||e.truncated))for(let a of i){if(!a||typeof a!="object"||e.truncated)continue;let c=a;for(let u of xm(c)){if(e.truncated)return;let l=u.command??u.bash??u.prompt??u.powershell??c.powershell??"",p=km({type:u.type??c.type,command:u.command??c.command,bash:u.bash??c.bash,powershell:u.powershell??c.powershell,prompt:u.prompt??c.prompt}),m=typeof c.matcher=="string"?c.matcher:"",d=U(l),g=m?`${s}:${m}:${p}:${d}`:`${s}:${p}:${d}`,E=`${s}|${m}|${p}|${l}|attrs2`;e.push({kind:"HOOK",name:g,path:o,content_hash:U(E),origin:r,enabled:!0,trigger:"EVENT",attributes:{event:s,...m?{matcher:m}:{},action_kind:p,action_hash:d,...p!=="prompt"&&l.trim()?{command:aa(l,e.home)}:{}}})}}}function Le(e,t,n){if(!e.claimFile(t))return;let r=e.readJson(t,{});!r?.hooks||typeof r.hooks!="object"||bm(e,t,r.hooks,n)}import{existsSync as Um,readFileSync as Dm}from"node:fs";var _e=je(Me(),1);import{createHash as Nm}from"node:crypto";import{join as it}from"node:path";function Mm(e){let t=[...e].sort((n,r)=>n.localeCompare(r,"en")).join(`
|
|
38
|
+
`);return Nm("sha512").update(t).digest("hex").slice(0,16)}function vm(e){let t=process.platform==="win32"?it(I("LOCALAPPDATA")??e,"npm-cache"):it(e,".npm"),n=I("npm_config_cache")??I("NPM_CONFIG_CACHE");return n===void 0||n===t?[t]:[n,t]}function ua(e){return typeof e=="string"&&e.length>0&&e.length<=_e.PACKAGE_FIELD_MAX?e:null}function wm(e,t,n){let r=Mm(e);for(let o of vm(n)){let s=it(o,"_npx",r),i=D(it(s,"node_modules",...t.split("/"),"package.json"),{}),a=ua(i.version);if(a!==null)return a;let c=D(it(s,"package-lock.json"),{}),u=ua(c.packages?.[`node_modules/${t}`]?.version);if(u!==null)return u}return null}function Lm(e){return e.length<=_e.PACKAGE_FIELD_MAX?e:`${e.slice(0,_e.PACKAGE_FIELD_MAX-1)}\u2026`}function Cr(e,t,n){if(typeof e!="string"||e.length===0)return null;let r=(0,_e.npxPackageSpecs)(e,t??[]),o=r[0];if(o===void 0)return null;let s=(0,_e.packageNameFromSpec)(o);if(s===null)return null;let i=wm(r,s,n);return{package_name:s,package_spec:Lm(o),...i===null?{}:{package_version:i,package_version_source:"npx_cache"}}}function la(e,t){if(typeof e!="string"||e.length===0)return null;let[n,...r]=Gt(e.trim());return n===void 0?null:Cr(n,r,t)}function zt(e,t){if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=Array.isArray(n.args)?n.args.filter(o=>typeof o=="string"):[];return Cr(typeof n.command=="string"?n.command:null,r,t)}function da(e,t){let n=/^\s*command\s*=\s*(.+)$/m.exec(e);return n===null?null:Cr(we(n[1]??""),ot(e,"args"),t)}function Fm(e){if(!e||typeof e!="object"||Array.isArray(e))return"unknown";let t=e;return typeof t.type=="string"&&t.type.length>0?t.type:typeof t.url=="string"?"http":typeof t.command=="string"?"stdio":"unknown"}function pa(e,t,n){if(!e.claimFile(t))return;let o=e.readJson(t,{})?.mcpServers;if(!o||typeof o!="object")return;let s=e.componentPath(t);for(let[i,a]of Object.entries(o)){if(e.truncated)return;let c=Fm(a),u=ta(a,c);Object.assign(u,zt(a,e.home)??{});let l=na(a);e.push({kind:"MCP_SERVER",name:i,path:s,content_hash:Rr(i,u,l),origin:n,enabled:l,attributes:u})}}function fa(e,t,n){if(!Um(t)||!e.claimFile(t))return;let r;try{r=Dm(t,"utf8")}catch{return}let o=e.componentPath(t),s=/^\[mcp_servers(?:\.(\w+)|\."([^"]+)"|\.'([^']+)')\]\s*$/gm,i;for(;(i=s.exec(r))!==null;){if(e.truncated)return;let a=i[1]??i[2]??i[3];if(!a)continue;let c=r.slice(i.index+i[0].length),u=c.search(/^\[mcp_servers(?:\.(?:\w+|"[^"]+"|'[^']+'))\]\s*$/m),l=u===-1?c:c.slice(0,u),p="unknown";/^\s*url\s*=/m.test(l)?p="http":/^\s*command\s*=/m.test(l)&&(p="stdio");let m=oa(l,p);Object.assign(m,da(l,e.home)??{});let d=ra(l);e.push({kind:"MCP_SERVER",name:a,path:o,content_hash:Rr(a,m,d),origin:n,enabled:d,attributes:m})}}import{existsSync as Hm,readdirSync as jm}from"node:fs";import{join as B}from"node:path";var ma=50;function Ir(e,t,n,r){if(!Hm(t))return{componentCount:0,expandTruncated:!1};let o=e.components.length,{expanded:s}=e.withPluginExpandCap(ma,()=>{Ie(e,{dir:B(t,"skills"),kind:"SKILL",origin:n,enabled:r,nested:"SKILL.md"}),Ie(e,{dir:B(t,"commands"),kind:"COMMAND",origin:n,enabled:r,extensions:[".md"]}),Ie(e,{dir:B(t,"agents"),kind:"SUBAGENT",origin:n,enabled:r,extensions:[".md"]})});Le(e,B(t,"hooks","hooks.json"),n),Le(e,B(t,"hooks.json"),n);let i=e.components.length-o,a=s>=ma;return{componentCount:i,expandTruncated:a}}function Ar(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 ga(e){let t=B(e.home,".claude/plugins/installed_plugins.json"),n=e.readJson(t,{});if(!n)return;let r=n.plugins??{},s=e.readJson(B(e.home,".claude/settings.json"),{})?.enabledPlugins??{},i=e.componentPath(t);for(let[a,c]of Object.entries(r)){if(e.truncated)return;let u=Array.isArray(c)?c:[c],l=u[0]??{},p=s[a]===!0,m=a.includes("@")?a.split("@").slice(1).join("@"):"",d=typeof l.version=="string"?l.version:"",g=typeof l.scope=="string"?l.scope:"user",E=`plugin:${a}`,S=0,y=!1;for(let R of u)if(typeof R.installPath=="string"&&R.installPath.length>0){let H=Ir(e,R.installPath,E,p);S+=H.componentCount,y=y||H.expandTruncated}Ar(e,{pluginKey:a,rowPath:i,enabled:p,scope:g,version:d||void 0,marketplace:m||void 0,componentCount:S,expandTruncated:y,contentHash:U(`${a}|${d}|${g}|${p}|${S}`)})}}function Km(e){let t=e,n="";try{let r=jm(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).map(o=>o.name);if(r.length===1&&r[0])t=B(e,r[0]),n=r[0];else if(r.length>1){let o=[...r].sort(),s=o[o.length-1];s&&(t=B(e,s),n=s)}}catch{}return{installPath:t,version:n}}var $m=/^\d+$/;function Bm(e){let t=e.filter(n=>!$m.test(n.pluginId));return t.length>0?t:e}function _a(e){let t=[{base:B(e.home,".cursor/plugins/local"),scope:"local"},{base:B(e.home,".cursor/plugins/cache"),scope:"cache"}];for(let{base:n,scope:r}of t)if(!e.truncated)for(let o of e.readEntries(n)){if(!o.isDirectory()||e.truncated)continue;if(r==="local"){let a=o.name,c=B(n,o.name),u=`plugin:${a}`,{componentCount:l,expandTruncated:p}=Ir(e,c,u,!0);Ar(e,{pluginKey:a,rowPath:e.componentPath(c),enabled:!0,scope:"local",componentCount:l,expandTruncated:p,contentHash:U(`${a}|local|${l}`)});continue}let s=o.name,i=[];for(let a of e.readEntries(B(n,s))){if(!a.isDirectory())continue;let c=B(n,s,a.name),{installPath:u,version:l}=Km(c);i.push({pluginId:a.name,installPath:u,version:l})}for(let a of Bm(i)){if(e.truncated)break;let c=`${a.pluginId}@${s}`,u=`plugin:${c}`,{componentCount:l,expandTruncated:p}=Ir(e,a.installPath,u,!0);Ar(e,{pluginKey:c,rowPath:e.componentPath(a.installPath),enabled:!0,scope:"cache",version:a.version||void 0,marketplace:s,componentCount:l,expandTruncated:p,contentHash:U(`${c}|${a.version}|${l}`)})}}}function zm(e,t){let{layout:n,levelDir:r,origin:o,includeMachineWide:s}=t;for(let i of n.skillRoots)Ie(e,{dir:Ue(r,i),kind:"SKILL",origin:o,enabled:!0,nested:"SKILL.md"});for(let i of n.dirs)Ie(e,{dir:Ue(r,i.dir),kind:i.kind,origin:o,enabled:!0,extensions:i.extensions});for(let i of n.memory){let a=Vi(i.map(c=>Ue(r,c)));a&&jt(e,{absolutePath:a,kind:"MEMORY",origin:o,enabled:!0,name:Gm(a)})}for(let i of Xo(n))Le(e,Ue(r,i),o);for(let i of n.mcpJson??[])pa(e,Ue(r,i),o);for(let i of n.mcpToml??[])fa(e,Ue(r,i),o);if(s){if(n.managed)for(let i of Ct(n.managed,process.platform,e.home))i.toLowerCase().endsWith(".json")&&Le(e,i,o);n.plugins==="claude"?ga(e):n.plugins==="cursor"&&_a(e)}}function ha(e,t){try{let n=new Ht(e,{pathMode:t.pathMode,maxEntries:t.maxEntries});for(let r of t.layouts)zm(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 Or(e,t,n={}){let r={},o=n.shouldWalk;if(o===void 0||o("user","")){let c=ha(t,{layouts:Object.values(ke),levelDir:t,origin:"user",includeMachineWide:!0,pathMode:"home-relative",maxEntries:ue,scopeRef:""});c&&(r.user=c)}let s=n.inGitRepo===!0,i=null,a=n.launchCwd;if(a!==void 0){let c=Object.values(de),u=fr({launchCwd:a,gitRoot:n.gitRoot,inGitRepo:s,remote:n.remote,home:t,hasProjectSpec:l=>qo(c,l)});i=u.parentRel;for(let l of u.anchors){let p=nr(l.dir);if(o!==void 0&&!o(l.scope,p))continue;let m=ha(t,{layouts:c,levelDir:l.dir,origin:l.scope,includeMachineWide:!1,pathMode:"tilde",maxEntries:mr,scopeRef:p});m&&(r[l.scope]=m)}r.parent||(i=null)}return{scopes:r,parentRel:i,cwdInGitRepo:s}}function Pr(e,t,n={}){let r=n.truncated===!0,o=tt(e),s=new Set(e.map(l=>V(l.path,l.name)));if(n.forceFull===!0||t===void 0)return{hash:o,count:e.length,truncated:r,full:!0,upserts:e,removed:[],unchanged:!1};let a=[],c=t;for(let l of e){let p=V(l.path,l.name);c[p]!==l.content_hash&&a.push(l)}let u=[];if(!r){for(let l of Object.keys(c))if(!s.has(l)){let p=ki(l);p&&u.push(p)}}return{hash:o,count:e.length,truncated:r,full:!1,upserts:a,removed:u,unchanged:a.length===0&&u.length===0}}var Sa=2*1024*1024,Vm=new Set(["HOOK","MCP_SERVER","PLUGIN"]);function Tr(e,t,n){let r=new Set(t.map(s=>V(s.path,s.name))),o=[];for(let s of e)s.text!==void 0&&(n.has(s.content_hash)||r.has(V(s.path,s.name))||o.push(s));return o}function kr(e,t,n){let r=new Set(e);for(let s of t)r.add(s);let o=new Set(n.map(s=>s.content_hash));return[...r].filter(s=>o.has(s))}function Ea(e){return Buffer.byteLength(JSON.stringify(e),"utf8")}function ya(e){if(e.text===void 0)return e;let{text:t,...n}=e;return n}function xr(e,t=Sa){let n=[],r=[];for(let l of e)Vm.has(l.kind)?n.push(l):r.push(l);r.sort((l,p)=>(l.text?.length??0)-(p.text?.length??0));let o=[...n,...r],s=[],i=2,a=0,c=0,u=[];for(let l of o){let p=s.length>0?1:0,m=Ea(l)+p;if(i+m<=t){s.push(l),i+=m,l.text!==void 0&&u.push(l.content_hash);continue}if(l.text!==void 0){let d=ya(l),g=Ea(d)+p;if(i+g<=t){s.push(d),i+=g,a+=1;continue}}c+=1}return{components:s,textDeferredCount:a,droppedCount:c,textHashesSent:u}}function br(e,t){return t.size===0?e:e.map(n=>n.text===void 0||!t.has(n.content_hash)?n:ya(n))}var Wm=["user","cwd","repo","parent"];function Nr(e){let{collected:t,cacheFor:n,nowMs:r,maxBytes:o}=e,s=[];for(let x of Wm){let k=t.scopes[x];if(!k)continue;let F=n(x,k.scopeRef),L=F.components,K=Pr(k.components,L,{forceFull:L===void 0,truncated:k.truncated}),te=new Set(F.textHashes),M=Tr(k.components,K.upserts,te),v=br([...K.upserts,...M],te);s.push({scope:x,walk:k,delta:K,outgoing:v,outgoingKeys:new Set(v.map(C=>V(C.path,C.name))),deliveredTextHashes:te,cachedComponents:L})}let i=s.flatMap(x=>x.outgoing),a=xr(i,o),c=new Set(a.components.map(x=>V(x.path,x.name))),u=[],l=[],p=[],m=[],d=[],g=[],E=[];for(let x of s){let{scope:k,walk:F,delta:L}=x;g.push(...F.components),u.push(k);let K=a.components.filter(C=>x.outgoingKeys.has(V(C.path,C.name))),te=[...x.outgoingKeys].some(C=>!c.has(C)),M=L.truncated||te;M?p.push(k):L.full&&l.push(k),m.push(...K),!L.full&&!M&&d.push(...L.removed);let v=L.full?{}:{...x.cachedComponents??{}};if(!M)for(let C of L.removed)delete v[V(C.path,C.name)];for(let C of K)v[V(C.path,C.name)]=C.content_hash;E.push({scope:k,scopeRef:F.scopeRef,components:v,textHashes:kr(x.deliveredTextHashes,K.filter(C=>C.text!==void 0).map(C=>C.content_hash),F.components),collectedAtMs:r,included:K.length>0||L.removed.length>0&&!M||L.full})}let S={user_spec_hash:tt(g),user_spec_count:g.length,user_spec_truncated:p.length>0};u.length>0&&(S.user_spec_scopes=u,S.user_spec_full_scopes=l,S.user_spec_truncated_scopes=p,S.user_spec_cwd_in_git_repo=t.cwdInGitRepo),l.length>0&&l.length===u.length&&(S.user_spec_full=!0),m.length>0&&(S.user_spec=m),d.length>0&&(S.user_spec_removed=d),a.textDeferredCount>0&&(S.user_spec_text_deferred=a.textDeferredCount);let y=t.scopes.cwd;y&&(S.user_spec_cwd_scope_ref=y.scopeRef);let R=t.scopes.repo;R&&(S.user_spec_repo_scope_ref=R.scopeRef);let H=t.scopes.parent;return H&&(S.user_spec_parent_scope_ref=H.scopeRef,t.parentRel&&(S.user_spec_parent_rel=t.parentRel)),{fields:S,scopes:E}}var ct={cwd:"cwd_spec",repo:"repo_spec",parent:"parent_spec"};function Vt(e){return e==="cwd"||e==="repo"||e==="parent"}function at(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mr(e){return!at(e)||!at(e.components)||!Object.values(e.components).every(t=>typeof t=="string")||!Array.isArray(e.text_hashes)||!e.text_hashes.every(t=>typeof t=="string")?!1:typeof e.collected_at_ms=="number"&&Number.isFinite(e.collected_at_ms)}function Ra(e){return Ym(e)}function Ca(e){return Jm(e)}function Ia(e){return Xm(e)}function Ym(e){if(!at(e))return;let t={};for(let[n,r]of Object.entries(e))typeof r=="string"&&(t[n]=r);return t}function Jm(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function vr(e,t){if(!at(e))return;let n=e[t];return Mr(n)?n:void 0}function Xm(e){if(!at(e))return{};let t={};for(let[n,r]of Object.entries(e))Mr(r)&&(t[n]=r);return t}function wr(e,t=20){let n=[];for(let[r,o]of Object.entries(e))Mr(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 eg=200,Aa=200,tg=["allow","deny","ask"],ng=/(?<=^|[\s(,=:])(?:~|[A-Za-z]:)?[\\/][^\s,)]+/g,Ur="<path>",rg=new RegExp(`${Ur}(?:\\s+[A-Za-z.][^\\s,)]*[\\\\/][^\\s,)]*)+`,"g");function og(e){let t=e.replace(ng,Ur).replace(rg,Ur);return t.length>Aa?`${t.slice(0,Aa)}...`:t}function Yt(e){let t=D(e,{}),n=[];for(let r of tg)for(let o of t.permissions?.[r]??[])typeof o=="string"&&o.length>0&&n.push({key:og(o),mode:r});return{model:t.model??"",permissionKeys:n}}function sg(e){let{serverManaged:t,fileBased:n}=Nn(process.platform,e),r=Yt(t);if(r.model||r.permissionKeys.length>0)return r;let o="",s=[];for(let i of n){let a=Yt(i);a.model&&(o=a.model),s.push(...a.permissionKeys)}return{model:o,permissionKeys:s}}function ig(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 ag=10,cg="self-config-cache.json",Pa=2;function Jt(){return I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off"}function ug(){return I("EV_AI_HOOK_CWD_SPEC")?.toLowerCase()==="off"}function lg(e,t=Date.now()){return e===void 0||!Number.isFinite(e)?!0:t-e>=ze}var dg={claude:["claude"],cursor:["agent","cursor-agent"],codex:["codex"]};async function pg(e,t=w){let n=dg[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(`
|
|
39
|
+
`)[0]??"").trim();return a||r(o+1)};return r(0)}function fg(e=Oa()){return De(e,".ev-ai","agent-hook",cg)}function mg(e){let n=[...e].sort((r,o)=>r.name.localeCompare(o.name)).map(r=>`${r.name}:${r.size}`).join(`
|
|
40
|
+
`);return U(n)}function Wt(e,t,n=!1){let r=mg(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 Lr(e,t,n=[]){let r=0,o=!1,s=new Set;for(let i of[...t.map(a=>De(e,a)),...n]){let a=Qm(i);if(s.has(a))continue;s.add(a);let c=fn(i);c.present&&(o=!0,r+=c.size)}return o?{present:!0,size:r}:{present:!1,size:0}}function gg(e){return Zm(e)?j(qm(e,"utf8"),{}):{}}function _g(e,t){try{Z(e,`${JSON.stringify(t)}
|
|
41
|
+
`)}catch(n){let r=n instanceof Error?n.message:String(n);h(`WARN: self-config cache write failed open: ${r}`)}}function hg(e,t,n){if(t==="user")return e.user_spec_collected_at_ms;if(Vt(t))return vr(e[ct[t]],n)?.collected_at_ms}function Eg(e,t,n){if(t==="user")return{components:Ra(e.user_spec_components),textHashes:Ca(e.user_spec_text_hashes)};if(!Vt(t))return{components:void 0,textHashes:[]};let r=vr(e[ct[t]],n);return r?{components:r.components,textHashes:r.text_hashes}:{components:void 0,textHashes:[]}}function Sg(e,t,n,r){let o={...e,send_count:n};for(let s of Object.keys(t)){let i=t[s];i.entries!==void 0&&(o[s]=i.hash)}if(r){o.user_spec_layout_version=Pa,r.home&&(o.user_spec_collected_at_ms=r.home.collectedAtMs,r.home.included&&(o.user_spec=r.hash,o.user_spec_components=r.home.components),o.user_spec_text_hashes=r.home.textHashes);for(let s of r.project){if(!Vt(s.scope))continue;let i=ct[s.scope],a=Ia(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]=wr(a)}}return o}async function Ta(e,t=process.cwd(),n=Oa(),r={}){let o=e==="claude",s=r.gitRoot??t,i=await pg(e),a="",c=[];if(o){let M=sg(n),v=Yt(De(n,".claude/settings.json")),C=Yt(De(t,".claude/settings.local.json"));a=M.model||C.model||v.model,c=ig([...M.permissionKeys,...v.permissionKeys,...C.permissionKeys]).slice(0,eg)}let u={present:!1,size:0},l=M=>{let v=[],C=!1;for(let ne of M){let pt=to(De(n,ne));if(v=v.concat(pt.entries),C=C||pt.truncated,v.length>=ue){v=v.slice(0,ue),C=!0;break}}return{entries:v,truncated:C}},p=fg(n),m=gg(p),d=m[e]??{},g=(d.send_count??0)+1,E=g>0&&g%ag===0,S=M=>E?void 0:d[M],y=l(fe.skills),R=l(fe.subagents),H=l(fe.commands),x=l(fe.rules),k={skills:Wt(y.entries,S("skills"),y.truncated),subagents:Wt(R.entries,S("subagents"),R.truncated),commands:Wt(H.entries,S("commands"),H.truncated),rules:Wt(x.entries,S("rules"),x.truncated)},F={runner_platform:e,config_scope:"user",cli_version:i,claude_version:o?i:null,model:o&&a||null,permission_keys:c,user_scope:{skills:k.skills,subagents:k.subagents,commands:k.commands,rules:k.rules,memory:Lr(n,fe.memory),settings:Lr(n,fe.settings,Qo(n)),mcp:Lr(n,fe.mcp)},local_settings:o?fn(De(t,".claude/settings.local.json")):u},L=null,K=r.nowMs??Date.now();if(!Jt()){let M=d.user_spec_layout_version!==Pa,v=Or(e,n,{launchCwd:ug()?void 0:r.launchCwd,gitRoot:s,inGitRepo:r.inGitRepo,remote:r.remote,shouldWalk:(C,ne)=>M||lg(hg(d,C,ne),K)});if(Object.keys(v.scopes).length>0){let C=Nr({collected:v,cacheFor:(ne,pt)=>M?{components:void 0,textHashes:[]}:Eg(d,ne,pt),nowMs:K});Object.assign(F,C.fields),L={hash:C.fields.user_spec_hash,home:C.scopes.find(ne=>ne.scope==="user")??null,project:C.scopes.filter(ne=>ne.scope!=="user")}}}let te=Sg(d,k,g,L);return{config:F,commit:()=>{m[e]=te,_g(p,m)}}}import{homedir as $g}from"node:os";import{join as wa}from"node:path";var aR=Buffer.from([1]);var cR=1024*1024,uR=4*1024*1024,lR=64*1024,dR=64*1024,pR=64*1024;var Dr=4096,fR=4*1024*1024;import{open as ka,mkdir as yg,readFile as Rg,readdir as Cg,rename as Ig,stat as Ag,unlink as Og,utimes as Pg}from"node:fs/promises";var Xt=new WeakMap;function Tg(e){if(e&&typeof e=="object"&&"code"in e)return e}function Fr(e){return Tg(e)?.code==="ENOENT"}async function ba(e,t){try{return await e.readdir(t)}catch(n){if(Fr(n))return[];throw n}}function Na(){return{async open(e,t){let n=await ka(e,t),r={path:e};return Xt.set(r,n),r},async write(e,t){let n=xa(e),r=typeof t=="string"?Buffer.from(t,"utf8"):t;await n.write(r)},async fsync(e){await xa(e).sync()},async close(e){let t=Xt.get(e);Xt.delete(e),t&&await t.close()},rename:Ig,async readdir(e){return Cg(e)},readFile:Rg,async stat(e){let t=await Ag(e);return{mtimeMs:t.mtimeMs,size:t.size,isDirectory:()=>t.isDirectory()}},async mkdir(e,t){await yg(e,t)},unlink:Og,utimes:Pg,async fsyncDir(e){if(process.platform==="win32")return;let t=await ka(e,"r");try{await t.sync()}finally{await t.close()}}}}function xa(e){let t=Xt.get(e);if(!t)throw new Error("closed");return t}function Zt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}import{join as qt}from"node:path";function kg(e){return qt(e,".ev-ai","agent-hook","js")}function xg(e){return qt(kg(e),"scopes")}function Ma(e,t){return qt(xg(e),t)}function va(e){return qt(e,"attempts")}function Hr(e){return String(e).padStart(10,"0")}var bg=/^(\d{10})$/,Ng=/^(\d{10})\.done$/,Mg=/^[0-9a-f]{64}$/i;async function Fa(e,t,n=!1){let r=va(t),o=await ba(e,r),s=new Map,i=new Map,a=La(o,bg),c=La(o,Ng),u=async m=>{let d=await Da(e,wa(r,vg(m)));return d&&s.set(m,{record:Lg(d.value),mtimeMs:d.mtimeMs}),d!==void 0},l=async m=>{let d=Ug((await Da(e,wa(r,wg(m))))?.value);return d&&i.set(m,d),d!==void 0};if(!n)return await Promise.all([...a.map(u),...c.map(l)]),{claims:s,dones:i};await Promise.all([Ua(a,u),Ua(c,l)]);let p=ut(s);return p<ut(i)&&c.includes(p)&&await l(p),{claims:s,dones:i}}function La(e,t){return e.flatMap(n=>{let r=t.exec(n);return r?[Number(r[1])]:[]})}async function Ua(e,t){for(let n of[...e].sort((r,o)=>o-r))if(await t(n))return}function ut(e){let t=0;for(let n of e.keys())n>t&&(t=n);return t}function Ha(e){if(e.record!=="empty"&&e.record.started_at){let t=Date.parse(e.record.started_at);if(Number.isFinite(t))return t}return e.mtimeMs}function vg(e){return Hr(e)}function wg(e){return`${Hr(e)}.done`}async function Da(e,t){let n;try{n=await e.stat(t)}catch(o){if(Fr(o))return;throw o}let r=n.mtimeMs;if(n.size===0||n.size>Dr)return{mtimeMs:r};try{let o=await e.readFile(t);return o.byteLength===0||o.byteLength>Dr?{mtimeMs:r}:{mtimeMs:r,value:JSON.parse(o.toString("utf8"))}}catch{return{mtimeMs:r}}}function Lg(e){if(!Zt(e))return"empty";let t={};return typeof e.started_at=="string"&&(t.started_at=e.started_at),(e.owner==="bootstrap"||e.owner==="refresh")&&(t.owner=e.owner),e.resync===!0&&(t.resync=!0),t}function Ug(e){if(!Zt(e))return;let t=e;if(typeof t.finished_at!="string"||typeof t.outcome!="string"||typeof t.interval_s!="number"||!Number.isFinite(t.interval_s))return;let n=Dg(t.selection);if(n)return{finished_at:t.finished_at,interval_s:t.interval_s,outcome:t.outcome,selection:n}}function Dg(e){if(!Zt(e))return;let t=e;if(t.kind==="bundled")return t.why==="server"||t.why==="bootstrap_failed"?{kind:"bundled",why:t.why}:void 0;if(t.kind==="cached"&&typeof t.digest=="string"&&Mg.test(t.digest)&&typeof t.version=="string"&&t.version.length>0&&typeof t.integrity=="string"&&t.integrity.startsWith("sha512-"))return{kind:"cached",digest:t.digest.toLowerCase(),version:t.version,integrity:t.integrity}}function Kg(e){return e==="bootstrap"?3e3:6e4}function Ka(e,t){let n=ut(e.claims);if(n===0)return;let r=ut(e.dones),o=e.claims.get(n),s=e.dones.get(n);if(o&&!s){let a=Ha(o),c=o.record==="empty"?void 0:o.record.owner,u=Kg(c)+3e4;if(t-a>u)return{n,latest_claim:n,outcome:"incomplete",finished_at:null,selection_version:ja(e.dones.get(r)?.selection)}}if(r===0)return;let i=e.dones.get(r);if(i)return{n:r,latest_claim:n,outcome:i.outcome,finished_at:i.finished_at,selection_version:ja(i.selection)}}function ja(e){return e?.kind==="cached"&&typeof e.version=="string"?e.version:null}async function $a(e=$g(),t=process.env){let n=Zn(t),r=n?.launcherScope;if(!n||!r)return{};try{let o=await Fa(Na(),Ma(e,r)),s=Ka(o,Date.now());return s?{launcher_scope:r,launcher_attempt:s}:{launcher_scope:r}}catch{return{launcher_scope:r}}}function Fe(e,t,n){let r={installation_id:n.installationId};n.platformAgentId&&(r.platform_agent_id=n.platformAgentId),n.sessionId&&(r.session_id=n.sessionId),n.turnId&&(r.turn_id=n.turnId);let o={schema_version:St,event:e,timestamp:ft(),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:Pn,host_arch:process.arch,node_version:process.version,correlation:r,payload:t},s=Zn();return s&&(o.launcher_version=s.launcherVersion,o.hook_source=s.hookSource,o.hook_fallback_reason=s.fallbackReason??null,o.launcher_scope_match=ci(n.collectorUrl,s.launcherScope)),e==="session_start"&&(n.launcher_scope&&(o.launcher_scope=n.launcher_scope),n.launcher_attempt&&(o.launcher_attempt=n.launcher_attempt)),o}import{existsSync as Ga}from"node:fs";import{spawn as za}from"node:child_process";import{fileURLToPath as Gg}from"node:url";import{gzipSync as Bg}from"node:zlib";function jr(e){return I("EV_AI_HOOK_COMPRESS")==="off"?{body:e}:Buffer.byteLength(e,"utf8")<Oo?{body:e}:{body:Bg(Buffer.from(e,"utf8")),contentEncoding:"gzip"}}function Qt(e){let t={"Content-Type":"application/json"};return e!==void 0&&(t["Content-Encoding"]=e),t}function Ba(e){return typeof e=="string"?Buffer.byteLength(e,"utf8"):e.length}var Kr="__post",en="__work";async function zg(e,t,n={}){if(I("EV_AI_HOOK_USER_SPEC")?.toLowerCase()==="off")return e;let r=await or(n.gitRoot??process.cwd(),w,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 Vg(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 Va(e){switch(e){case"session_start":return Ro;case"session_end":return Co;case"tool_invoked":case"skill_invoked":return In;default:return In}}function Wg(e,t,n){return`${JSON.stringify({url:e,timeoutMs:t})}
|
|
42
|
+
${n}`}function Wa(e,t=[],n=process.execPath,r=import.meta.url,o=Ga){if(yo(n))return{command:n,args:[e,...t]};let s=Gg(r);return o(s)?{command:n,args:[s,e,...t]}:{command:n,args:[e,...t]}}function Yg(e=process.execPath,t=import.meta.url,n=Ga){return Wa(Kr,[],e,t,n)}function Jg(e){let t=e.indexOf(`
|
|
43
|
+
`);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 Ya(e,t=fetch){let n=await e(),r=Jg(n);if(!r)return;let{meta:o,body:s}=r,i=jr(s),a=Qt(i.contentEncoding);try{await t(o.url,{method:"POST",headers:a,body:i.body,signal:AbortSignal.timeout(Number(o.timeoutMs))})}catch{}}async function Xg(e,t,n,r=fetch){let o=Va(e),s=jr(t),i=Qt(s.contentEncoding),a=Ba(s.body);h(`POST event=${e} url=${ht(n)} size=${a} encoding=${s.contentEncoding??"identity"} platform=${process.platform}`);let c=Date.now();try{let u=await r(n,{method:"POST",headers:i,body:s.body,signal:AbortSignal.timeout(o)});if(!u.ok&&s.contentEncoding==="gzip"&&(u.status===400||u.status===415)){try{await u.text()}catch{}h(`POST gzip rejected http=${u.status} \u2014 retrying uncompressed`),u=await r(n,{method:"POST",headers:Qt(),body:t,signal:AbortSignal.timeout(o)})}let l=Date.now()-c;if(u.ok)return h(`POST outcome=ok elapsed_ms=${l} http=${u.status}`),!0;let p=(await u.text()).slice(0,200).replace(/[\n\r]/g,"");return h(`POST outcome=fail elapsed_ms=${l} http=${u.status} body=${p}`),!1}catch(u){let l=Date.now()-c,p=u instanceof Error?u.message:String(u);return h(`POST outcome=fail elapsed_ms=${l} http=000 body=${p}`),!1}}async function Ja(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()},Io),u=()=>{i=!0,clearTimeout(c),a()};s.stdin.end(n,()=>u()),s.stdin.once("error",()=>u())}),s.unref(),s}catch(s){let i=s instanceof Error?s.message:String(s);return h(`WARN: ${o} spawn failed open: ${i}`),null}}async function Zg(e,t,n,r=za,o=Yg){let s=Va(e),i=Wg(n,s,t),{command:a,args:c}=o();return Ja(a,c,i,r,"detached post")}async function Xa(e,t,n=za,r=Wa){let{command:o,args:s}=r(en,t);return Ja(o,s,e,n,"detached work")}async function He(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(!Ge(o))return h(`WARN: collector URL blocked (https required): ${ht(o)}`),!1;let a=await zg(t,n.runnerPlatform,i),c=r(e,a,{...n,collectorUrl:o});s!==void 0&&(c.build_ms=Math.max(0,Date.now()-s));let u=`${JSON.stringify(c)}
|
|
44
|
+
`,l=I("EV_AI_HOOK_DEBUG");l==="full"?h(`DEBUG envelope=${JSON.stringify(c)}`):l==="1"&&h(`DEBUG summary=${Vg(c,Buffer.byteLength(u,"utf8"))}`);let p=process.argv.includes(en),m=I("EV_AI_HOOK_SYNC")==="1";return Nt(n.runnerEvent,n.runnerPlatform)||p||m?Xg(e,u,o):(await Zg(e,u,o),!1)}import{createReadStream as qg}from"node:fs";import{stat as Qg}from"node:fs/promises";import{basename as e_,resolve as t_}from"node:path";import{createInterface as n_}from"node:readline";var r_=1024*1024;function o_(e){let t=e.replace(/\\/g,"/");return t.includes("/.claude/projects/")&&e_(t).endsWith(".jsonl")}async function Za(e){if(!e||!o_(e))return null;try{let t=t_(e),n=await Qg(t);if(!n.isFile())return null;let r=Math.max(0,n.size-r_),o=[],s=n_({input:qg(t,{encoding:"utf8",start:r}),crlfDelay:1/0});for await(let i of s)i.length!==0&&o.push(i);r>0&&o.length>0&&o.shift();for(let i=o.length-1;i>=0;i--){let a=o[i];if(a)try{let c=JSON.parse(a);if(c.type!=="assistant")continue;let u=c.message;if(!u||typeof u!="object")continue;let l=u.model;if(typeof l=="string"&&l.length>0)return l}catch{continue}}return null}catch{return null}}function nn(e){return{sessionId:e.sessionId,turnId:e.turnId,installationId:e.manifest.installationId,runnerPlatform:e.runnerPlatform,platformAgentId:e.platformAgentId,runnerEvent:e.runnerEvent}}function dt(e,t){return{gitRoot:e.manifest.gitRoot,...t?{home:t}:{}}}function $r(e){return{gitRoot:e.manifest.gitRoot,inGitRepo:e.manifest.inGitRepo,runnerEvent:e.runnerEvent}}async function tc(e){let t=Date.now();await g_(e);let{gitRoot:n}=e.manifest;await rn(e,n);let r=$r(e);return{buildStartedAtMs:t,gitRoot:n,hookInput:Dt(e.hookInput,e.manifest.manifest,r),envelopeFields:nn(e),launchCwd:dr(e.hookInput,r),home:ec()}}function qa(e){try{return z(s_(e))}catch{return null}}function nc(e){return e.startsWith("/")||/^[A-Za-z]:\//.test(e)}function Qa(e,t){let n=e.replaceAll("\\","/");if(!nc(n))return null;let r=z(e),o=z(t),s=qa(e)??r,i=qa(t)??o;return s.startsWith(`${i}/`)?s.slice(i.length+1):r.startsWith(`${o}/`)?r.slice(o.length+1):null}function i_(e,t,n){if(!e)return{repositorySourcePath:null,userSourcePath:null};let r=e.replaceAll("\\","/"),s=Qa(e,t)??(nc(r)?null:r),i=Qa(e,n);return{repositorySourcePath:s,userSourcePath:i}}function tn(e,t,n,r,o,s){let{repositorySourcePath:i,userSourcePath:a}=i_(e,t,n),c=i??a,u=c===null?null:o(c),l=u!==null&&c!==null?a_({installableKind:r,sourcePath:c,nativeKey:u,inRepository:i!==null,platformAgentId:s.platformAgentId,installationId:s.manifest.installationId}):void 0;return{sourcePath:c,nativeKey:u,componentReference:l}}function a_(e){try{let t=e.inRepository?l_(e.platformAgentId,e.sourcePath):(0,P.installationRootExternalKey)(e.installationId,(0,P.userConfigRootFromPath)(e.sourcePath));return t?(0,P.buildComponentReference)({installationRootExternalKey:t,installableKind:e.installableKind,sourcePath:e.sourcePath,nativeKey:e.nativeKey}):void 0}catch{return}}function Br(e,t,n){return He("tool_invoked",{...n,success:null,duration_ms:null,hook_input:t.hookInput},t.envelopeFields,Fe,e.manifest.collectorUrl,t.buildStartedAtMs,dt(e,t.home))}function c_(e){return Bs(e.runnerEvent,e.runnerPlatform)?[]:is(e.hookInput)}function u_(e,t){return Br(e,t,{})}var rc=new Set([...Object.values(Ce),".github"]);function l_(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=>rc.has(i));return s<0?null:`${r}:${o.slice(0,s+1).join("/")}`}function d_(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(g=>g.name.toLowerCase()===t.toLowerCase()),u=c?.sourcePath??(c?.source==="claude_json_user"?".claude.json":c?.source==="cursor_mcp_user"?".cursor/mcp.json":c?.source==="codex_toml_user"||c===void 0&&o==="codex"?".codex/config.toml":void 0);if((c?.scope==="user"||c?.source==="claude_json_user"||c?.source==="cursor_mcp_user"||c?.source==="codex_toml_user"||c===void 0&&o==="codex")&&u)try{let g=(0,P.userConfigRootFromPath)(u);return(0,P.buildComponentReference)({installationRootExternalKey:(0,P.installationRootExternalKey)(r,g),installableKind:P.ComponentKind.INTERFACE,sourcePath:u,nativeKey:c?.name??t})}catch{return}if(n===null)return;let p=n.indexOf(":");if(p<=0||p===n.length-1)return;let m=n.slice(p+1),d=m.replaceAll("\\","/").split("/").at(-1);if(!(d===void 0||!rc.has(d)))try{return(0,P.buildComponentReference)({installationRootExternalKey:n,installableKind:P.ComponentKind.INTERFACE,sourcePath:m,nativeKey:t})}catch{return}}function p_(...e){for(let t of e)if(t)return t;return null}function W(e,t,n){if(e.status==="fulfilled")return e.value;let r=e.reason instanceof Error?e.reason.message:String(e.reason);return h(`WARN: ${n} failed open: ${r}`),t}function f_(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 m_(e,t){return{runner_platform:e,config_scope:"user",...t?{operator:t}:{}}}var Oe=new Set,lt=null;async function g_(e){if(Jt())return;let t=e.manifest.installationId,n=e.manifest.installationStorePath;if(Oe.has(t))return;if(!ir(n)){Oe.add(t);return}let r=Ke({sessionId:e.sessionId,hostname:$e()});if(bi(r)){if(lt){await lt;return}lt=(async()=>{if(Oe.has(t)||!ir(n)){Oe.add(t);return}if(!Ko(n)){Oe.add(t);return}let o=!1;try{let s=Date.now(),{gitRoot:i}=e.manifest,a=String(e.runnerPlatform),[c,u,l,p,m]=await Promise.allSettled([Xe(i),_n(),qn(r),hn(),sr({gitRoot:i,installationStorePath:n,forceResend:!1,runnerPlatform:a})]),d=W(c,null,"gitSnapshot"),g=W(u,"","detectVirt"),E=W(l,null,"probeCloud"),S=W(p,{},"hostEnv"),y=W(m,{commit:()=>{}},"resolveOperatorForSend");await rn(e,i,d);let R={identity:{host:$e(),context:r,virt:g||null,cloud:E,git:d},host_env:S,env_vars:Qn(),self_config:m_(a,y.operator),run_meta:{trigger:"cloud_identity_bootstrap"}};o=!!await He("session_start",R,nn(e),Fe,e.manifest.collectorUrl,s,dt(e)),o&&(y.commit(),Oe.add(t))}finally{$o(n)}})().finally(()=>{lt=null}),await lt}}async function rn(e,t,n){try{let r=n===void 0?await Xe(t):n;e.platformAgentId=await xs(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 __(e){let t=Date.now(),{gitRoot:n}=e.manifest,r=Ke({sessionId:e.sessionId,hostname:$e()}),o=String(e.runnerPlatform),s=$r(e),i=dr(e.hookInput,s),a=Xe(n),c=Jt()?Promise.resolve({commit:()=>{}}):sr({gitRoot:n,installationStorePath:e.manifest.installationStorePath,forceResend:!1,runnerPlatform:o}),[u,l,p,m,d,g,E]=await Promise.allSettled([a,_n(),qn(r),hn(),Wn(e.manifest.manifest,n,o),a.catch(()=>null).then(C=>Ta(o,n,void 0,{installationStorePath:e.manifest.installationStorePath,gitRoot:n,launchCwd:i,inGitRepo:e.manifest.inGitRepo,remote:C?.remote??null})),c]),S=W(u,null,"gitSnapshot"),y=W(l,"","detectVirt"),R=W(p,null,"probeCloud"),H=W(m,{},"hostEnv"),x=W(d,[],"mcpDeclared"),k=W(g,f_(o),"selfConfig"),F=W(E,{commit:()=>{}},"resolveOperatorForSend"),L=k.config;await rn(e,n,S);let K=_(e.hookInput,"model");K&&(L.model=K);let te={identity:{host:$e(),context:r,virt:y||null,cloud:R,git:S},host_env:H,env_vars:Qn(),mcp:{declared:x},self_config:L,run_meta:{trigger:e.hookSource||"startup"},hook_input:Dt(e.hookInput,e.manifest.manifest,{...s,launchCwd:i})},M={};try{M=await $a(ec())}catch{M={}}await He("session_start",te,{...nn(e),...M},Fe,e.manifest.collectorUrl,t,dt(e))&&(k.commit(),F.commit(),Oe.add(e.manifest.installationId))}async function h_(e){let t=Date.now(),{gitRoot:n}=e.manifest;await rn(e,n);let r=e.runnerEvent.toLowerCase(),o=p_(_(e.hookInput,"status"),_(e.hookInput,"stop_reason"),_(e.hookInput,"reason"),Qe(_(e.hookInput,"error")),r==="stop"?re(e.hookInput,"is_interrupt")===!0?"interrupted":"completed":""),s=e.runnerPlatform==="claude"?await Za(_(e.hookInput,"transcript_path")):null,i=Dt(e.hookInput,e.manifest.manifest,$r(e));s&&(i.model=s),r!=="stopfailure"&&!Li(e.manifest.manifest)&&i.last_assistant_message===void 0&&(i.last_assistant_message=""),await He("session_end",{status:o,...s?{model:s}:{},hook_input:i},nn(e),Fe,e.manifest.collectorUrl,t,dt(e))}function oc(e,t,n,r){let o=r??ss({skillId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home}),s=tn(o,t.gitRoot,t.home,P.ComponentKind.SKILL,P.nativeKeyForSkillPath,e);if(s.sourcePath!==null&&vn(s.sourcePath)?.toLowerCase()===n.toLowerCase())return s.componentReference===void 0?{}:{componentReference:s.componentReference};let i=r??ws({commandId:n,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),a=tn(i,t.gitRoot,t.home,P.ComponentKind.COMMAND,P.nativeKeyForCommandPath,e);return a.nativeKey?.toLowerCase()!==n.toLowerCase()?{}:{commandName:a.nativeKey,...a.componentReference===void 0?{}:{componentReference:a.componentReference}}}function E_(e,t,n){let r=At(e.hookInput.tool_input);return Promise.all(n.map(o=>{let s=oc(e,t,o,r);return Br(e,t,{tool_name:"Skill",skill_name:o,...s.commandName===void 0?{}:{command_name:s.commandName},...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}function S_(e,t,n){return Promise.all(n.map(r=>{let o=bs({relativePath:r,launchCwd:t.launchCwd,gitRoot:t.gitRoot,home:t.home,runnerPlatform:e.runnerPlatform}),s=tn(o,t.gitRoot,t.home,P.ComponentKind.RULE,P.nativeKeyForRulePath,e),i=s.nativeKey??Ms(r);return Br(e,t,{tool_name:"Rule",rule_name:i,...s.componentReference===void 0?{}:{component_reference:s.componentReference}})}))}var y_=[{kind:P.ComponentKind.SKILL,nativeKeyFn:P.nativeKeyForSkillPath},{kind:P.ComponentKind.RULE,nativeKeyFn:P.nativeKeyForRulePath},{kind:P.ComponentKind.COMMAND,nativeKeyFn:P.nativeKeyForCommandPath}];function R_(e,t,n){if(n.skillName===null&&n.ruleName===null&&n.commandName===null)return{};let r=Ln(e.hookInput);if(r===null)return n.skillName===null?{}:oc(e,t,n.skillName,null);for(let o of y_){let s=tn(r,t.gitRoot,t.home,o.kind,o.nativeKeyFn,e);if(s.nativeKey!==null)return{...s.componentReference===void 0?{}:{componentReference:s.componentReference},...o.kind===P.ComponentKind.RULE?{ruleName:s.nativeKey}:{},...o.kind===P.ComponentKind.COMMAND?{commandName:s.nativeKey}:{}}}return{}}var C_=/mcp/i;function I_(e,t,n,r){let o=C_.test(e.runnerEvent);if(!r.hasMcpIdentity&&!o)return{};let s=o?la(t,n):zt(r.declaredConfig,n);return s===null?{}:Object.fromEntries(Object.entries(s).filter(i=>typeof i[1]=="string").map(([i,a])=>[`mcp_${i}`,a]))}async function A_(e){let t=await tc(e),n=Ys(e.hookInput,e.runnerEvent),{toolName:r,skillName:o}=n,s=wn(e.hookInput),i=ca(s,t.home),a=Xs(e.hookInput),c=Gs(e.runnerEvent),u=c===!1?Zs(e.hookInput,e.runnerEvent):null,l=await Wn(e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home).catch(()=>[]),p=Qe(_(e.hookInput,"mcp_server_name")),{mcpServer:m,mcpTool:d}=qs(r,l.map(F=>F.name),p??""),g=d_(r,m,e.platformAgentId,e.manifest.installationId,String(e.runnerPlatform),l,p),E=g===void 0?R_(e,t,n):{},S=m===null?null:js(m,e.manifest.manifest,e.manifest.gitRoot,String(e.runnerPlatform),t.home),y=I_(e,s,t.home,{hasMcpIdentity:!!m||!!d,declaredConfig:S}),R=g??E.componentReference,H=E.ruleName??n.ruleName,x=E.commandName??n.commandName,k=Js(e.hookInput);await He("tool_invoked",{tool_name:r,skill_name:o,...H?{rule_name:H}:{},...x?{command_name:x}:{},success:c,duration_ms:a,...i?{executable:i}:{},...u?{failure_reason:u}:{},...m?{mcp_server:m}:{},...d?{mcp_tool:d}:{},...y,...R?{component_reference:R}:{},...k?{subagent_type:k}:{},hook_input:t.hookInput},t.envelopeFields,Fe,e.manifest.collectorUrl,t.buildStartedAtMs,dt(e,t.home))}async function sc(e){switch(e.internalEvent){case"session_start":await __(e);return;case"session_end":await h_(e);return;case"skill_invoked":{let t=c_(e),n=vs(e.hookInput),r=$s(e.runnerEvent);if(t.length===0&&n.length===0&&!r)return;let o=await tc(e);await Promise.all([r&&t.length===0&&n.length===0?u_(e,o):void 0,t.length===0?void 0:E_(e,o,t),n.length===0?void 0:S_(e,o,n)]);return}case"tool_invoked":await A_(e);return;default:return}}function ic(e){return e!=="session_start"&&e!=="session_end"&&e!=="tool_invoked"&&e!=="skill_invoked"&&e!==""}import{existsSync as zr,readFileSync as O_}from"node:fs";import{dirname as P_,isAbsolute as T_,join as k_,relative as x_}from"node:path";function ac(e){for(let t of uo){let n=k_(e,t);if(zr(n))return n}}async function b_(e=process.cwd(),t){let n=t??await pn(e);return ac(n)??ac(e)}async function N_(e,t){let n=t??await pn(P_(e)),r=x_(n,e);if(r.startsWith("..")||T_(r))return!1;let o=await Y("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 Gr(e){let t=O_(e,"utf8");return j(t,{})}function M_(){return{schema_version:St,mcp_servers:[]}}function v_(e,t,n,r){!t||!n||(e.capture_hook_input==="full"&&r.has("capture_hook_input")&&(h(`WARN: ignoring capture_hook_input=full in git-tracked manifest ${t}; use EV_AI_HOOK_CAPTURE_FULL_INPUT=1 or an untracked operator manifest`),delete e.capture_hook_input),e.debug===!0&&r.has("debug")&&(h(`WARN: ignoring debug=true in git-tracked manifest ${t}; set debug on ~/.ev-ai/config.json`),delete e.debug))}async function cc(e=process.cwd(),t={}){let{root:n,inGitRepo:r}=await dn(e),o=I("EV_AI_HOOK_MANIFEST"),s=o&&zr(o)?o:void 0,i=s?void 0:zr(Sn())?Sn():void 0,a=s?void 0:await b_(e,n),c=i?Gr(i):void 0,u=a?Gr(a):void 0,l,p,m,d=new Set;if(s){l=Gr(s),p=s,m=s;for(let R of Object.keys(l))d.add(R)}else if(c&&u){l=lo(u,c),p=i,m=a;for(let R of Object.keys(u))R in c||d.add(R)}else if(c)l=c,p=i;else if(u){l=u,p=a,m=a;for(let R of Object.keys(u))d.add(R)}else l=M_();delete l.installation_id;let g=m?await N_(m,n):!1;v_(l,m,g,d);let{installationId:E,storePath:S,repoKey:y}=await Vo(n,{sessionId:t.sessionId});return{manifestPath:p??S,manifest:l,installationId:E,installationStorePath:S,repoKey:y,collectorUrl:Cn(l),platformAgentId:l.platform_agent_id??"",gitRoot:n,inGitRepo:r}}import{createHash as w_}from"node:crypto";import{mkdirSync as L_,readdirSync as U_,readFileSync as D_,statSync as uc,unlinkSync as F_,writeFileSync as H_}from"node:fs";import{homedir as on}from"node:os";import{join as Vr}from"node:path";var j_="turns",lc=1440*60*1e3,K_=100,$_=new Set(["stop","stopfailure","sessionend"]);function Wr(e=on()){return Vr(oe(e),j_)}function B_(e){return w_("sha256").update(e).digest("hex").slice(0,32)}function dc(e,t){return Vr(e,B_(t))}function G_(e,t=Date.now()){let n;try{n=U_(e)}catch{return}let r=0;for(let o of n){if(r>=K_)return;r+=1;try{let s=Vr(e,o);t-uc(s).mtimeMs>lc&&F_(s)}catch{}}}function z_(e,t,n=on()){let r=e.trim(),o=t.trim();if(!(!r||!o))try{let s=Wr(n);L_(s,{recursive:!0}),H_(dc(s,r),o,"utf8")}catch{}}function V_(e,t=on()){let n=e.trim();if(!n)return"";try{let r=dc(Wr(t),n);return Date.now()-uc(r).mtimeMs>lc?"":D_(r,"utf8").trim()}catch{return""}}function pc(e,t,n,r=on()){let o=t.trim(),s=$_.has(n.trim().toLowerCase());return s&&G_(Wr(r)),o?(z_(e,o,r),o):s?V_(e,r):""}async function fc(e,t,n,r){let o=t??await ln(An),s=j(o,{}),i=_(s,"session_id")||_(s,"conversation_id"),a=await cc(process.cwd(),{sessionId:i});if(!a)return;r&&(a.collectorUrl=r);let c=zs(s,a.manifest.platform,n),u=Vs(e,c.runnerEvent);if(!u){h(`WARN: unknown hook event '${c.runnerEvent}'; skipping telemetry`);return}let l={hookInput:s,sessionId:c.sessionId,turnId:pc(c.sessionId,c.turnId,c.runnerEvent),runnerEvent:c.runnerEvent,runnerPlatform:c.runnerPlatform,hookSource:c.hookSource,internalEvent:u,manifest:a,platformAgentId:a.platformAgentId};if(ic(u)){h(`WARN: unsupported internal event '${u}'`);return}await sc(l)}function W_(e,t){if(I("EV_AI_HOOK_SYNC")==="1")return!0;let n=Be(e),r=j(t,{}),o=n.event??(_(r,"hook_event_name")||_(r,"event")),s=qe(r,o,void 0,n.runner);return Nt(o,s)}async function mc(e=process.argv.slice(2)){if(ai(),e[0]===Kr){try{await Ya(un)}catch{}return 0}if(e[0]===en){try{let t=Be(e.slice(1)),n=await un(),r=j(n,{}),o=t.event??(_(r,"hook_event_name")||_(r,"event"));if(mn()||Jn(t.runner,r,o))return 0;await fc(t.event,n,t.runner,Yn(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 ln(An),n=Be(e),r=Yn(n),o=j(t,{}),s=n.event??(_(o,"hook_event_name")||_(o,"event"));if(mn()||Jn(n.runner,o,s)||!si(o,s,n.runner))return 0;W_(e,t)?await fc(n.event,t,n.runner,r):await Xa(t,e)}catch(t){let n=t instanceof Error?t.message:String(t);h(`WARN: hook failed open: ${n}`)}finally{eo()}return 0}mc().then(e=>{process.exit(e)}).catch(e=>{let t=e instanceof Error?e.message:String(e);process.stderr.write(`[ev-ai-agent-hook] ${t}
|
|
37
45
|
`),process.exit(1)});
|