@agenttrail/cli 0.2.12 → 0.2.26

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.
@@ -1,13 +1,15 @@
1
- var qo=Object.defineProperty;var Jo=(t,e)=>{for(var n in e)qo(t,n,{get:e[n],enumerable:!0})};import{renameSync as pu}from"fs";import{homedir as fu}from"os";import{mkdirSync as fs,readFileSync as gs,unlinkSync as Vu}from"fs";import{dirname as ms,join as zt}from"path";import{randomBytes as ns}from"crypto";import{chmodSync as rs,lstatSync as os,mkdirSync as Mu,readFileSync as Nu,readlinkSync as ss,realpathSync as is,renameSync as as,statSync as ds,unlinkSync as cs,writeFileSync as us}from"fs";import{dirname as ls,join as Uu,resolve as ps}from"path";var pt="agenttrail.agent.vendor",Lt="agenttrail.tool.vendor_name";var Ye="agenttrail.usage.reported",Bt="agenttrail.time.approximate",$t="agenttrail.span.synthetic",Vt="agenttrail.subagent.conversation_id";var Kt="agenttrail.turn.closed_by";var Qt="agenttrail.mcp.server_unknown",Gt="agenttrail.pep.blocked";var Wt="7f050af4-796e-5b05-94c2-dba78bcdc7c2";var Ht="7d12feb9-faf4-5d1a-b711-9362724c66b3";function Ne(t,e,n={}){let r=t,o=!0;try{r=is(t)}catch{o=!1;let a=!0;for(let d=0;d<8;d++){let c;try{c=os(r).isSymbolicLink()}catch{a=!1;break}if(!c){a=!1;break}r=ps(ls(r),ss(r))}if(a){let d=new Error(`atomicWriteFileSync: too many symbolic links: ${t}`);throw d.code="ELOOP",d}}let s=n.mode;if(s===void 0&&o)try{s=ds(r).mode&4095}catch{}let i=`${r}.tmp-${process.pid}-${ns(6).toString("hex")}`;try{us(i,e,s!==void 0?{mode:s,encoding:"utf8"}:"utf8"),s!==void 0&&rs(i,s),as(i,r)}catch(a){try{cs(i)}catch{}throw a}}var ys=448;function Ze(t,e="claude"){switch(e){case"claude":return zt(t,".agenttrail","credentials.json");case"cursor":return zt(t,".agenttrail","cursor","credentials.json");case"codex":return zt(t,".agenttrail","codex","credentials.json")}return hs(e)}function hs(t){throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(t)}.`)}function Yt(t,e={},n="claude"){let r=e.readFile??(o=>gs(o,"utf8"));try{let o=JSON.parse(r(Ze(t,n)));return _s(o)?o:null}catch{return null}}function Zt(t,e,n={},r="claude"){let o=Ze(t,r),s=n.writeFile??((a,d,c)=>Ne(a,d,c!==void 0?{mode:c}:{}));return(n.mkdir??((a,d)=>fs(a,{recursive:!0,mode:d})))(ms(o),ys),s(o,`${JSON.stringify(e,null,2)}
2
- `,384),o}function _s(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.refresh_token=="string"&&typeof e.ingest_token=="string"&&typeof e.ingest_token_expires_at=="string"&&typeof e.org_id=="string"&&typeof e.host=="string"&&typeof e.endpoint=="string"&&(e.api_endpoint===void 0||typeof e.api_endpoint=="string")}function Nn(t){throw new Error(`AgentTrail has no path for the agent ${JSON.stringify(t)}.`)}var Ss=(t,e)=>fetch(t,e);function Rs(t,e){return`${t.replace(/\/$/,"")}${e}`}async function Ts(t,e,n){let r=await t(e,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(n)}),o=null;try{o=await r.json()}catch{o=null}return{status:r.status,ok:r.ok,data:o}}async function qt(t,e,n=Ss,r={}){let{ok:o,status:s,data:i}=await Ts(n,Rs(t,"/auth/device/refresh"),{...r,refresh_token:e});if(!o||!xs(i)){let a=bs(i)?i.error:`HTTP ${s}`;throw new Error(`device/refresh failed: ${a}`)}return i}function xs(t){if(typeof t!="object"||t===null)return!1;let e=t;return typeof e.ingest_token=="string"&&typeof e.refresh_token=="string"&&typeof e.expires_in=="number"&&typeof e.org_id=="string"}function bs(t){return typeof t!="object"||t===null?!1:typeof t.error=="string"}import{closeSync as Es,openSync as vs,readFileSync as Yu,rmSync as As,statSync as Cs,writeSync as Is}from"fs";var ks=3e4,Os=(t,e)=>{let n=vs(t,"wx");try{Is(n,e)}finally{Es(n)}},ws=t=>{try{As(t,{force:!0})}catch{}},Ds=t=>{try{let e=Cs(t);return Date.now()-e.mtimeMs}catch{return null}};async function Jt(t,e){let n=t.io??{},r=n.acquire??Os,o=n.release??ws,s=n.age??Ds,i=n.now??(()=>Date.now()),a=n.sleep??(y=>new Promise(v=>setTimeout(v,y))),d=t.staleMs??ks,c=t.timeoutMs??1e4,u=t.retryMs??50,f=i()+c;for(;;)try{r(t.lockPath,`${process.pid} ${new Date(i()).toISOString()}
3
- `);break}catch{let y=s(t.lockPath);if(y!==null&&y>d){o(t.lockPath);continue}if(i()>=f)throw new Error(`could not acquire refresh lock (${t.lockPath}); another refresh is in progress.`);await a(u)}try{return await e()}finally{o(t.lockPath)}}var al=1440*60*1e3;function Pn(t,e={}){try{return t.device?.fields(t.agent,e)??{}}catch{return{}}}function Un(t,e,n,r=!1){try{t.device?.record(t.agent,e,n.device_name!==void 0?{typed:r}:void 0)}catch{}}function Ms(t){switch(t){case"claude":return!1;case"cursor":case"codex":return!0}return Nn(t)}function Xt(t,e,n=t){return{refresh_token:e.refresh_token,ingest_token:e.ingest_token,ingest_token_expires_at:new Date((t.now?.()??Date.now())+e.expires_in*1e3).toISOString(),org_id:e.org_id,host:t.host,endpoint:n.ingestEndpoint,...e.org_tier?{org_tier:e.org_tier}:{},...Ms(t.agent)?{api_endpoint:n.apiEndpoint}:{}}}function ft(t){return Yt(t.homeDir,t.credentialsIO,"cursor")}import{mkdirSync as Ln,readFileSync as ei}from"fs";import{dirname as ti,join as Bn}from"path";var Ns=["MacBook Pro","MacBook Air","Mac mini","iMac","Mac Studio","Mac Pro","Mac","Windows","Linux"];function gt(t){return typeof t=="string"&&Ns.includes(t)}import{execFileSync as Ps}from"child_process";var Us=(t,e,n)=>Ps(t,[...e],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"],env:{PATH:"/usr/sbin:/usr/bin:/bin"}}),js=5e3,Fs=1e3,Ls={"Mac13,1":"Mac Studio","Mac13,2":"Mac Studio","Mac14,2":"MacBook Air","Mac14,3":"Mac mini","Mac14,5":"MacBook Pro","Mac14,6":"MacBook Pro","Mac14,7":"MacBook Pro","Mac14,8":"Mac Pro","Mac14,9":"MacBook Pro","Mac14,10":"MacBook Pro","Mac14,12":"Mac mini","Mac14,13":"Mac Studio","Mac14,14":"Mac Studio","Mac14,15":"MacBook Air","Mac15,3":"MacBook Pro","Mac15,4":"iMac","Mac15,5":"iMac","Mac15,6":"MacBook Pro","Mac15,7":"MacBook Pro","Mac15,8":"MacBook Pro","Mac15,9":"MacBook Pro","Mac15,10":"MacBook Pro","Mac15,11":"MacBook Pro","Mac15,12":"MacBook Air","Mac15,13":"MacBook Air","Mac15,14":"Mac Studio","Mac16,1":"MacBook Pro","Mac16,2":"iMac","Mac16,3":"iMac","Mac16,5":"MacBook Pro","Mac16,6":"MacBook Pro","Mac16,7":"MacBook Pro","Mac16,8":"MacBook Pro","Mac16,9":"Mac Studio","Mac16,10":"Mac mini","Mac16,11":"Mac mini","Mac16,12":"MacBook Air","Mac16,13":"MacBook Air"},Bs=[["MacBookPro","MacBook Pro"],["MacBookAir","MacBook Air"],["Macmini","Mac mini"],["MacPro","Mac Pro"],["iMac","iMac"]];function $s(t){let e=t.trim(),n=Ls[e];if(n)return n;for(let[r,o]of Bs)if(e.startsWith(r)&&/^\d/.test(e.slice(r.length)))return o;return"Mac"}function Vs(t){if(typeof t!="string")return"Mac";let e=t.trim();return gt(e)&&e!=="Windows"&&e!=="Linux"?e:"Mac"}var Ks=["SPHardwareDataType","-json","-detailLevel","mini"];function Qs(t){try{let n=JSON.parse(t)?.SPHardwareDataType,r=Array.isArray(n)?n[0]:void 0;return typeof r!="object"||r===null?void 0:{machine_name:r.machine_name}}catch{return}}function Gs(t){try{let e=Qs(t("/usr/sbin/system_profiler",Ks,js));if(e===void 0)return;let n=Vs(e.machine_name);return n==="Mac"?void 0:n}catch{return}}function Ws(t){try{let e=$s(t("/usr/sbin/sysctl",["-n","hw.model"],Fs));return e==="Mac"?void 0:e}catch{return}}function jn(t={}){let e=t.platform??process.platform,n=t.exec??Us;switch(e){case"darwin":return(t.thorough?Gs(n):void 0)??Ws(n)??"Mac";case"win32":return"Windows";case"linux":return"Linux";default:return}}import{randomUUID as Hs}from"crypto";import{readFileSync as zs}from"fs";import{join as Ys}from"path";var Zs=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function qs(t){return Ys(t,".agenttrail","machine-id")}function Js(t,e){try{return(t.readFile??(n=>zs(n,"utf8")))(e)}catch{return}}function Xs(t,e,n){(t.writeFile??((o,s,i)=>Ne(o,s,i!==void 0?{mode:i}:{})))(e,n,384)}function Fn(t,e={}){let n=qs(t),r=Js(e,n)?.trim();if(r&&Zs.test(r))return r;let o=Hs();return Xs(e,n,`${o}
4
- `),o}function $n(t){return Bn(t,".agenttrail","device.json")}var Vn=["claude","cursor","codex"];function qe(t,e={}){let n=e.readFile??(r=>ei(r,"utf8"));try{let r=JSON.parse(n($n(t)));if(typeof r!="object"||r===null||Array.isArray(r))return{};let o=r,s=typeof o.device_name=="string"&&o.device_name!==""?o.device_name:null,i=Array.isArray(o.named)?Vn.filter(a=>o.named.includes(a)):[];return{...gt(o.device_model)?{device_model:o.device_model}:{},...s!==null?{device_name:s}:{},...s!==null&&o.name_chosen===!0?{name_chosen:!0}:{},...i.length>0?{named:i}:{}}}catch{return{}}}function en(t,e,n={}){let r=$n(t);try{(n.mkdir??((o,s)=>Ln(o,{recursive:!0,mode:s})))(ti(r),448),(n.writeFile??((o,s,i)=>Ne(o,s,i!==void 0?{mode:i}:{})))(r,`${JSON.stringify(e,null,2)}
5
- `,384)}catch{}}function ni(t,e,n,r){if(e.device_model&&!r)return e.device_model;let o=jn({thorough:r,exec:n.exec,platform:n.platform})??e.device_model;return o!==void 0&&o!==e.device_model&&en(t,{...e,device_model:o},n),o}function Kn(t,e={}){return{fields(n,r={}){let o={};try{(e.mkdir??((s,i)=>Ln(s,{recursive:!0,mode:i})))(Bn(t,".agenttrail"),448),o.machine_id=Fn(t,e)}catch{}try{let s=qe(t,e);if(!r.exchange&&s.named?.includes(n))return o;if(s.name_chosen&&s.device_name)return o.device_name=s.device_name,o;let i=ni(t,s,e,r.thorough===!0);i!==void 0&&(o.device_model=i)}catch{}return o},record(n,r,o){try{let s=qe(t,e),i=r.device_name_rejected===!0,a=typeof r.device_name=="string"?r.device_name:null,d;if(a!==null){let c=new Set([...s.named??[],n]),u=a===s.device_name&&s.name_chosen===!0,f=o!==void 0&&!i||u;d={...s.device_model?{device_model:s.device_model}:{},device_name:a,...f?{name_chosen:!0}:{},named:Vn.filter(y=>c.has(y))}}else{let c=s;if(o!==void 0&&i&&!o.typed){let{name_chosen:u,...f}=c;c=f}r.device_name===null&&c.named?.includes(n)&&(c={...c,named:c.named.filter(u=>u!==n)}),c!==s&&(d=c)}d!==void 0&&en(t,d,e)}catch{}},name(){return qe(t,e).device_name},confirmedName(n){let r=qe(t,e);return r.named?.includes(n)?r.device_name:void 0},forget(n){try{let r=qe(t,e);if(!r.named?.includes(n))return;en(t,{...r,named:r.named.filter(o=>o!==n)},e)}catch{}}}}import{createHash as Va}from"crypto";var ri=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,oi=/[A-Z][a-z]{3,}|[a-z]{4,}|[A-Z]{4,}/g,si=new Set("api app auth backend billing blue build canary checkout cluster controller default deploy deployment dev east frontend gateway green ingest ingress internal job main migration north prod production release replica rollout service south staging stage test web west worker".split(" "));function ii(t){let e=new Map;for(let r of t)e.set(r,(e.get(r)??0)+1);let n=0;for(let r of e.values()){let o=r/t.length;n-=o*Math.log2(o)}return n}function ai(t){let e=0;for(let n of t.match(oi)??[])e+=n.length;return e/t.replace(/[-_]/g,"").length>=.7}function di(t){let e=t.split(/[-_]/);return e.length<5||e.some(n=>n.length>12)?!1:e.filter(n=>si.has(n.toLowerCase())).length>=3}function Qn(t){return t.length<32||ri.test(t)||/^sha(?:1|224|256|384|512)-/i.test(t)||ai(t)||di(t)||/\d{8,}/.test(t)||t.split(/[-_]/).some(e=>e.length>=32&&/^[0-9a-fA-F]+$/.test(e))||/^[0-9a-fA-F]+$/.test(t)||!/[A-Za-z]/.test(t)||!/[0-9]/.test(t)?!1:ii(t)>=4}var ci=/^(?:mysql\w*|mariadb[\w-]*)$/i,tn=/(?:^|[\s'"`(;|&/])(?:mysql\w*|mariadb[\w-]*)(?=$|[\s'"`);|&\\])/i,ui=/[\s,:}\]]/;function li(t){let e=t[3],n=e==="\\"&&t[4]==='"'?t[5]:e==='"'||e==="'"?t[4]:void 0;return n!==void 0&&ui.test(n)}function pi(t){return t.length===5?t.endsWith("''")||t.endsWith('""'):t.length===7&&t.endsWith('\\"\\"')}var Gn=new RegExp(tn.source,"gi"),fi=/^[A-Za-z_]\w*=/,gi="\uE000",mi=new Set(["then","do","else","elif","!","{","RUN","CMD","ENTRYPOINT"]),yi=/^(?:[\w.-]+:|-|\*|\d+[.)]|[$%>#]|[\w.-]+@[\w.-]+:\S*[#$%>])$/,hi=new Map([["sudo",new Set(["-u","-g","-p","-C","-D","-r","-t","-U","--user","--group","--prompt","--chdir","--role","--type"])],["doas",new Set(["-u","-C"])],["env",new Set(["-u","-C","-S","--unset","--chdir","--split-string"])],["nice",new Set(["-n","--adjustment"])],["ionice",new Set(["-c","-n","-p","--class","--classdata"])],["stdbuf",new Set(["-i","-o","-e"])],["timeout",new Set(["-s","-k","--signal","--kill-after"])],["xargs",new Set(["-n","-I","-L","-P","-d","-s","-E","-a","--max-args","--replace","--max-procs","--delimiter","--arg-file"])],["nohup",new Set],["time",new Set(["-f","-o","--format","--output"])],["exec",new Set(["-a"])],["command",new Set],["watch",new Set(["-n","-d","--interval"])],["strace",new Set(["-o","-e","-p","-s"])],["chroot",new Set(["--userspec","--groups"])],["gosu",new Set],["su-exec",new Set],["eval",new Set],["npx",new Set(["-p","--package"])],["dotenv",new Set(["-e","-v","-p"])]]),_i=new Set(["timeout","chroot","gosu","su-exec"]),Wn=new Set(["-u","-w","-e","--user","--workdir","--env","--env-file","--detach-keys"]),Si=new Set([...Wn,"-a","-c","-h","-l","-m","-p","-v","--add-host","--annotation","--arch","--attach","--blkio-weight","--blkio-weight-device","--cap-add","--cap-drop","--cgroup-parent","--cgroupns","--cidfile","--cpu-period","--cpu-quota","--cpu-rt-period","--cpu-rt-runtime","--cpu-shares","--cpus","--cpuset-cpus","--cpuset-mems","--device","--device-cgroup-rule","--device-read-bps","--device-read-iops","--device-write-bps","--device-write-iops","--dns","--dns-option","--dns-search","--domainname","--entrypoint","--expose","--gpus","--gidmap","--group-add","--health-cmd","--health-interval","--health-retries","--health-start-interval","--health-start-period","--health-timeout","--hostname","--ip","--ip6","--ipc","--isolation","--kernel-memory","--label","--label-file","--link","--link-local-ip","--log-driver","--log-opt","--mac-address","--memory","--memory-reservation","--memory-swap","--memory-swappiness","--mount","--name","--net","--network","--network-alias","--oom-score-adj","--os","--pid","--pids-limit","--platform","--pod","--publish","--pull","--restart","--runtime","--secret","--security-opt","--shm-size","--stop-signal","--stop-timeout","--storage-opt","--sysctl","--tmpfs","--uidmap","--ulimit","--userns","--uts","--volume","--volume-driver","--volumes-from"]),Ri=new Set(["-H","-c","-l","-n","-a","--host","--context","--config","--log-level","--tlscacert","--tlscert","--tlskey","--connection","--url","--identity","--root","--runroot","--storage-driver","--namespace","--address","--snapshotter"]),Ti=new Set(["-f","-p","--file","--project-name","--project-directory","--env-file","--profile","--ansi","--progress","--parallel"]),xi=new Set(["-u","-w","-e","-l","-v","-p","--user","--workdir","--env","--index","--label","--volume","--publish","--name","--entrypoint"]),bi=new Set(["-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w","-B"]),Hn=new Set([";","|","&","(",")","`",`
6
- `,"\r","{","}"]);function zn(t){let e=t.replace(/['"\\]/g,""),n=e.lastIndexOf("/");return(n===-1?e:e.slice(n+1)).toLowerCase()}function Ei(t,e){if(e.has(t))return!0;if(t.startsWith("--"))return!1;for(let n=1;n<t.length;n++)if(e.has(`-${t[n]}`))return n===t.length-1;return!1}function Pe(t,e,n){let r=e;for(;r<t.length;){let o=t[r];if(o==="--")return r+1;if(!o.startsWith("-")||o==="-")return r;r+=Ei(o,n)?2:1}return r}function vi(t,e,n){for(let r=e;r<n;r++){let o=t[r],s=o==="--entrypoint"?t[r+1]:o.startsWith("--entrypoint=")?o.slice(13):void 0;if(s!==void 0)return s.replace(/['"]/g,"")===""?null:s}return null}function Ai(t){let e=0,n=!0;for(let r=0;r<=t.length&&e<t.length;r++){let o=t[e];if(n&&yi.test(o)){e++;continue}if(n=!1,fi.test(o)||mi.has(o)||o.includes(gi)){e++;continue}let s=zn(o),i=hi.get(s);if(i){e=Pe(t,e+1,i),_i.has(s)&&e++;continue}let a=s==="docker"||s==="podman"||s==="nerdctl",d=a?Pe(t,e+1,Ri):e+1;if(a&&t[d]==="container"&&d++,s==="docker-compose"||a&&t[d]==="compose"){let c=Pe(t,s==="docker-compose"?e+1:d+1,Ti);if(t[c]!=="exec"&&t[c]!=="run")return o;e=Pe(t,c+1,xi)+1;continue}if(a&&(t[d]==="exec"||t[d]==="run")){let c=t[d]==="run",u=Pe(t,d+1,c?Si:Wn),f=c?vi(t,d+1,u):null;if(f!==null)return f;e=u+1;continue}if(s==="kubectl"||s==="oc"){let c=t.indexOf("--",e),u=c===-1?[]:t.slice(e,c);if(!u.includes("exec")&&!u.includes("run")&&!u.includes("debug"))return null;e=c+1;continue}if(s==="ssh"){e=Pe(t,e+1,bi)+1;continue}return o}return null}function Yn(t){let e=Ai(t);return e!==null&&ci.test(zn(e))}function Ci(t,e,n,r){for(let o=n;o+e.length<=r;o++)if(Zn(t,o)||t.startsWith(e,o)&&(e==='\\"'||t[o-1]!=="\\"))return o;return-1}function Zn(t,e){let n=t[e];return n===`
7
- `||n==="\r"?!0:n==="\\"&&(t[e+1]==="n"||t[e+1]==="r")}function Ii(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t===46||t===45}function ki(t,e,n){let r=t[e]==="\\",o=e+(r?2:1),s=o;for(;s<o+65&&s<n&&Ii(t.charCodeAt(s));)s++;if(s===o||s-o>64)return 0;if(r){if(t[s]!=="\\"||t[s+1]!=='"')return 0;s+=2}else{if(t[s]!=='"')return 0;s++}for(;s<n&&(t[s]===" "||t[s]===" ");)s++;return s<n&&t[s]===":"?s+1-e:0}function Oi(t,e,n){let r=Math.max(e,n-8),o=n-1;for(;o>=r&&(t[o]===" "||t[o]===" ");)o--;if(o<r)return!1;let s=t[o];if(s===":"||s===","||s==="["||s==="{")return!0;if(s!=="c")return!1;let i=o-1;for(;i>=r&&/[A-Za-z]/.test(t[i]);)i--;return i>=r&&t[i]==="-"&&(i===r||t[i-1]===" "||t[i-1]===" ")}function wi(t,e,n){let r=Math.max(n,e-64),o=e;for(;o>r&&t[o-1]!==" "&&t[o-1]!==" ";)o--;return o}var ie=null;function Di(t,e){let n=Math.max(0,e-512),r,o,s,i,a,d;for(ie&&ie.text===t&&ie.i<=e&&ie.i>=n?{i:r,at:o,found:s,blank:i,inside:a,word:d}=ie:(r=n,o=n,s=n===0,i=!0,a=null,d=!1),ie=null;r<e;){let c=t[r],u=t[r+1];if(c==="\\"){if(u==="n"||u==="r"){o=r+2,s=!0,i=!0,a=null,r+=2;continue}if(u==="\\"){r+=t[r+2]==="\\"&&t[r+3]==="n"?4:2,i=!1;continue}if(u===`
8
- `||u==="\r"){r+=2;continue}if(u==="u"&&t.startsWith("0026",r+2)){o=r+6,s=!0,i=!0,r+=6;continue}}let f=c==="\\"&&u==='"'?'\\"':c==='"'||c==="'"?c:null;if(f){let y=ki(t,r,e);if(y>0){r+=y,o=r,s=!0,i=!0,a=null;continue}let v=t[r+f.length];if(f===a&&d&&(v===" "||v===" ")){r+=f.length,i=!1,a=null;continue}if(f===a||!i&&(v===","||v==="]"||v==="}")){r+=f.length,o=r,s=!0,i=!0,a=null;continue}if(i||Oi(t,o,r)){r+=f.length,o=r,s=!0,i=!0,a=f,d=!0;continue}let I=Ci(t,f,r+f.length,e);if(I===-1)return ie={text:t,i:r,at:o,found:s,blank:i,inside:a,word:d},{start:wi(t,r,o),unsure:!0,inside:a};if(Zn(t,I)){r+=f.length,i=!1;continue}r=I+f.length,i=!1;continue}Hn.has(c)?(o=r+1,s=!0,i=!0,d=!1,(c===`
9
- `||c==="\r")&&(a=null)):c!==" "&&c!==" "?i=!1:d=!1,r++}return ie={text:t,i:r,at:o,found:s,blank:i,inside:a,word:d},s&&o>=n?{start:o,unsure:!1,inside:a}:{start:Math.max(n,e-210),unsure:!0,outside:!0,inside:null}}var Q=null;function Mi(t,e,n){for((!Q||Q.text!==t||Q.end>n)&&(Q={text:t,last:-1,next:-1,end:n}),Q.end=n;Q.next<n;){Q.next!==-1&&(Q.last=Q.next),Gn.lastIndex=Q.next===-1?0:Q.next+1;let r=Gn.exec(t);Q.next=r?r.index:Number.POSITIVE_INFINITY}return Q.last>=e}function Ni(t,e){let n=e-1,r=t[n];if(r!==")"&&r!=="`")return!1;let o=-1;for(let d=n-1;d>=Math.max(0,n-64);d--)if(r===")"?t[d]==="("&&t[d-1]==="$":t[d]==="`"){o=d;break}if(o===-1)return!1;let s=r===")"?o-2:o-1,i=s-8;for(;s>=0&&s>i&&(t[s]===" "||t[s]===" ");)s--;let a=t[s];return s>=0&&!Hn.has(a)&&a!=='"'&&a!=="'"?!1:tn.test(t.slice(o+1,n))}function Pi(t,e,n){let r=-1;if(n[0]==="[")r=e;else for(let s=e-1;s>=Math.max(0,e-512);s--){let i=t[s];if(i==="["){r=s;break}if(i==="]"||i===`
10
- `)break}if(r===-1)return!1;let o=t.slice(r+1,e).split(",").map(s=>s.trim().replace(/["\\]/g,""));return Yn(o)}function qn(t,e,n){if(t[0]==="["||t[0]===",")return Pi(n,e,t);if(pi(t))return!1;let r=Di(n,e);if(r.inside!==null&&t.startsWith(r.inside,3)||r.unsure&&li(t))return!1;if(r.outside)return Mi(n,r.start,e);let o=n.slice(r.start,e);if(r.unsure)return tn.test(o);let s=o.trim().split(/\s+/);return Yn(s)||Ni(n,r.start)}function N(t,e){return e?`[REDACTED:${t}:${e}]`:`[REDACTED:${t}]`}var rn=String.raw`(?<=\\[nrtfb])|(?<=\\u[0-9A-Fa-f]{4})|(?<=\x1b\[[0-9;:?]{0,32}[@-~])|(?<=\\(?:u001[bB]|x1[bB]|033)\[[0-9;:?]{0,32}[@-~])|(?<=\x1b\([0-9A-Za-z])|(?<=\\(?:u001[bB]|x1[bB]|033)\([0-9A-Za-z])`,er=`(?:\\b|${rn})`,on=`(?:(?<![A-Za-z0-9_-])|${rn})`,tr=String.raw`(?<!\[REDACTED:)`,Je=String.raw`(?!["']?\[REDACTED:[a-z0-9:-]+\]["']?(?:[\s,;}\])]|$))`;function G(t,e){return new RegExp(`${er}${t}`,e)}var Ui=G(String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,"g"),ji=new RegExp(`((?:aws[_-]?)?secret[_-]?access[_-]?key)(["']?\\s*[=:]\\s*["']?)((?![0-9a-f]{40}(?![A-Za-z0-9/+=]))[A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])`,"gi"),Fi=G(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),Li=G(String.raw`(?:(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,255}\b|github_pat_[A-Za-z0-9_]{22,255}\b)`,"g"),Bi=G(String.raw`xox[baprs]-[A-Za-z0-9-]{10,255}\b`,"g"),$i=G(String.raw`Bearer\s+([A-Za-z0-9._~+/-]{8,})=*`,"gi"),Vi=G(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),Ki=G(String.raw`eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b`,"g"),Qi=/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]{0,8192}?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,Gi=G(String.raw`(https?|ftp|wss?):\/\/[^\s/@:]+:[^\s]*@(?=[^\s/:@])`,"gi"),Wi=(()=>{let e="([A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API[_-]?KEY|APIKEY|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|CLIENT[_-]?SECRET|AUTH[_-]?TOKEN|CREDENTIALS?)[A-Z0-9_]*)",n=`(?:(")([^"\uE000]{4,})"|(')([^'\uE000]{4,})'|([^\\s"',;\uE000]{4,}))`;return new RegExp(`${er}${tr}${e}(["']?\\s*[=:]\\s*)${Je}${n}`,"gi")})(),$="\uE000",Hi=new RegExp(`${on}${tr}([A-Z0-9]+(?:_[A-Z0-9]+)*_KEY(?==|["']\\s*:)|(?![Ii]dempotency-)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*-[Kk][Ee][Yy](?=["']?\\s*:))(["']?\\s*[=:]\\s*)${Je}(?!["']?[~.]{0,2}/)(?:(")([^"${$}]{4,})"|(')([^'${$}]{4,})'|([^\\s"',;${$}]{4,}))`,"g"),zi=new RegExp(`${on}((?:Proxy-)?Authorization["']?\\s*[=:]\\s*["']?)((?:Basic|Token|Digest|Negotiate|ApiKey|Api-Key)\\s+)?(?!Bearer\\s)${Je}([^\\s"',;${$}]{8,})`,"gi"),Jn="(?:[Mm][Yy][Ss][Qq][Ll]|[Mm][Aa][Rr][Ii][Aa][Dd][Bb])",nn=`[^\\s"'\`;|&)\\\\${$}]`,nr='(?:\\\\\\\\|\\\\(?!["\\\\]))',rr=`${nn}*(?:${nr}${nn}*)*`,Yi=`(?=${nn}|${nr})${rr}`,Zi=`(?:'[^'\\n${$}]*'|\\$'(?:[^'\\\\\\n${$}]|\\\\[^\\n${$}]){0,1024}'|\\\\"[^"\\\\\\n${$}]*\\\\"|"[^"\\n${$}]*")`,qi=new RegExp(`(\\s-p)(?<=${Jn}(?:\\\\\\n|[^\\n]){0,200}\\s-p)${Je}(?:${Zi}${rr}|${Yi})|([[,]\\s{0,8}\\\\?"-p)(?<=${Jn}[^\\n]{0,200}"-p)${Je}[^"\\\\\\n${$}]+(?=\\\\?")`,"g"),Ji=new RegExp([`${on}([A-Za-z0-9_]*(?:ACCOUNT[_-]?ID|CF_ACCOUNT|CLOUDFLARE_ACCOUNT|AWS_ACCOUNT|GOOGLE_CLOUD_PROJECT|GCLOUD_PROJECT|GCP_PROJECT|CORE_PROJECT))(["']?\\s*[=:]\\s*)(["']?)([^\\s"',;<[${$}][^\\s"',;${$}]*)\\3`,`(--(?:account-id|account|owner-id|account-number))(=|\\s+)(["']?)(\\d{12}|[0-9a-f]{32})\\7(?![A-Za-z0-9])`,"(?<=\\barn:aws[a-z-]*:[a-z0-9-]*:[a-z0-9-]*:)\\d{12}(?![A-Za-z0-9])",`(?<=\\b(?:gcloud|gsutil|bq|firebase)\\b[^\\n;|&${$}]{0,200}?)(--project(?:_id|-id)?)(=|\\s+)(["']?)([a-z][a-z0-9-]{4,28}[a-z0-9])\\11(?![A-Za-z0-9-])`].join("|"),"gi"),Xi=new RegExp(`(?:(?<![A-Za-z0-9_+/.%-])|${rn})(?<!==)(?<!sha(?:1|224|256|384|512)[-:])(?<!base64,)[A-Za-z0-9_-]{${32},}(?![A-Za-z0-9_+/=.%-])`,"g"),ea=new RegExp(`[A-Za-z0-9_-]{${32}}`);function mt(t,e,n,r){let o=n??"";return`${t}${e}${o}${r}${o}`}var ta=G(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`,"g"),na=G(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`,"g"),ra=G(String.raw`(?:\d{13,19}\b|\d{3,6}([ -])\d{3,6}(?:\1\d{3,6}){1,3}\b)`,"g"),oa=G(String.raw`(?:\+?\d{1,3}[ .-]?)?(?:\(\d{2,4}\)[ .-]?)?\d{2,4}[ .-]\d{2,4}[ .-]\d{2,4}\b`,"g"),or=[{id:"aws-access-key-id",kind:"secret",category:"aws",severity:"high",tier:"permissive",regex:Ui,placeholder:()=>N("secret:aws")},{id:"pem-private-key",kind:"secret",category:"private-key",severity:"high",tier:"permissive",regex:Qi,placeholder:()=>N("secret:private-key")},{id:"jwt",kind:"secret",category:"jwt",severity:"high",tier:"permissive",regex:Ki,placeholder:()=>N("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Li,placeholder:()=>N("secret:github")},{id:"slack-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Bi,placeholder:()=>N("secret:slack")},{id:"openai-key",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Fi,placeholder:()=>N("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:Vi,placeholder:()=>N("secret:connection-string")},{id:"basic-auth-url",kind:"secret",category:"basic-auth",severity:"high",tier:"permissive",regex:Gi,placeholder:t=>`${t[1].toLowerCase()}://${N("secret:basic-auth")}@`},{id:"bearer-token",kind:"secret",category:"token",severity:"medium",tier:"permissive",regex:$i,placeholder:()=>`Bearer ${N("secret:bearer")}`},{id:"aws-secret-access-key",kind:"secret",category:"aws",severity:"medium",tier:"standard",regex:ji,placeholder:t=>`${t[1]}${t[2]}${N("secret:aws-secret")}`},{id:"env-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:Wi,placeholder:t=>{let e=t[3]??t[5]??"";return`${t[1]}${t[2]}${e}${N("secret:env")}${e}`}},{id:"key-name-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:Hi,prefilter:/_KEY|-key/i,placeholder:t=>mt(t[1]??"",t[2]??"",t[3]??t[5],N("secret:env"))},{id:"authorization-header",kind:"secret",category:"token",severity:"medium",tier:"standard",regex:zi,prefilter:/authorization/i,placeholder:t=>`${t[1]??""}${t[2]??""}${N("secret:auth")}`},{id:"mysql-password-flag",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:qi,prefilter:/mysql|mariadb/i,accept:qn,placeholder:t=>`${t[1]??t[2]??""}${N("secret:password")}`},{id:"cloud-account-id",kind:"pii",category:"cloud-account",severity:"low",tier:"standard",regex:Ji,prefilter:/account|project|owner-id|arn:aws/i,placeholder:t=>{let e=N("pii:account");return t[1]!==void 0?mt(t[1],t[2]??"",t[3],e):t[5]!==void 0?mt(t[5],t[6]??"",t[7],e):t[9]!==void 0?mt(t[9],t[10]??"",t[11],e):e}},{id:"generic-secret",kind:"secret",category:"generic",severity:"low",tier:"standard",regex:Xi,prefilter:ea,accept:Qn,placeholder:()=>N("secret:generic")},{id:"email",kind:"pii",category:"email",severity:"low",tier:"standard",regex:ta,placeholder:()=>N("pii:email")},{id:"ssn",kind:"pii",category:"ssn",severity:"high",tier:"standard",regex:na,placeholder:()=>N("pii:ssn")},{id:"credit-card",kind:"pii",category:"credit-card",severity:"high",tier:"standard",regex:ra,placeholder:()=>N("pii:credit-card")},{id:"phone",kind:"pii",category:"phone",severity:"low",tier:"strict",regex:oa,placeholder:()=>N("pii:phone")}],sr=new Set(["credit-card"]);function ir(t){let e=t.replace(/\D/g,"");if(e.length<13||e.length>19)return!1;let n=0,r=!1;for(let o=e.length-1;o>=0;o--){let s=e.charCodeAt(o)-48;r&&(s*=2,s>9&&(s-=9)),n+=s,r=!r}return n%10===0}var sa={permissive:new Set(["permissive"]),standard:new Set(["permissive","standard"]),strict:new Set(["permissive","standard","strict"])},Ue="\uE000",ia=new RegExp(`${Ue}(\\d+)${Ue}`,"g");function ar(t){return`${Ue}${t}${Ue}`}function aa(t,e=!1){if(t==="off")return[];let n=sa[t];return or.filter(r=>r.id==="phone"?n.has("strict")||e:n.has(r.tier))}function da(t){if(!t||t.length===0)return[];let e=[];for(let n of t)try{e.push(new RegExp(n,"g"))}catch{}return e}function ca(t,e,n,r){if(e.prefilter&&!e.prefilter.test(t))return t;let o=sr.has(e.id);return t.replace(e.regex,(...s)=>{let i=s[0];if(o&&!ir(i)||e.accept&&!e.accept(i,s[s.length-2],s[s.length-1]))return i;let a=s.slice(0,s.length-2);n[e.id]=(n[e.id]??0)+1;let d=r.length;return r.push(e.placeholder(a)),ar(d)})}function sn(t){return t.mode==="off"?null:{patterns:aa(t.mode,t.enablePhone),denylist:da(t.denylistPatterns)}}function dr(t,e){if(t.length===0)return{text:t,redactions:{},total:0};let{patterns:n,denylist:r}=e;return n.length===0&&r.length===0?{text:t,redactions:{},total:0}:ua(t,n,r)}function ua(t,e,n){let r={},o=[],s=t.includes(Ue)?t.split(Ue).join(""):t;for(let a of e)s=ca(s,a,r,o);for(let a=0;a<n.length;a++)s=s.replace(n[a],()=>{r.custom=(r.custom??0)+1;let d=o.length;return o.push("[REDACTED:custom]"),ar(d)});if(o.length===0)return{text:t,redactions:{},total:0};s=s.replace(ia,(a,d)=>o[Number(d)]);let i=0;for(let a in r)i+=r[a];return{text:s,redactions:r,total:i}}var cr="pubsub:sse:org:",la=`${cr}*`;var yt={mode:"standard"};function ur(t){return Object.entries(t).map(([e,n])=>({key:e,value:{stringValue:n}}))}function ht(t){return{resourceSpans:(Array.isArray(t)?t:[t]).map(n=>({resource:{attributes:ur(n.resource.attributes)},scopeSpans:[{scope:{name:n.scope.name,version:n.scope.version},spans:n.spans.map(r=>{let o={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,name:r.name,kind:r.kind,startTimeUnixNano:r.startTimeUnixNano,endTimeUnixNano:r.endTimeUnixNano,attributes:ur(r.attributes)};return r.error&&(o.status={code:2}),o})}]}))}}var pa=t=>new Promise(e=>setTimeout(e,t));function fa(t){let e=t.get("retry-after");if(!e)return null;let n=Number(e);return Number.isFinite(n)&&n>=0?n*1e3:null}async function pr(t,e,n={}){if(e.dryRun)return{status:"skipped",attempts:0};let r=n.fetch??globalThis.fetch,o=n.sleep??pa,s=e.maxRetries??5,i=e.baseBackoffMs??500,a=`${e.endpoint.replace(/\/$/,"")}/v1/traces`,d=JSON.stringify(t),c=0,u="",f;for(;c<=s;){c++;let y;try{y=await r(a,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${e.token}`},body:d})}catch(I){if(u=I.message,f=void 0,c>s)break;await o(lr(i,c,null));continue}if(f=y.status,y.ok)return{status:"ok",httpStatus:y.status,attempts:c};if(!(y.status===429||y.status>=500&&y.status<=599)||c>s){u=`HTTP ${y.status}: ${(await y.text().catch(()=>"")).slice(0,200)}`;break}await o(lr(i,c,fa(y.headers)))}return{status:"failed",httpStatus:f,attempts:c,error:u}}function lr(t,e,n){if(n!==null)return n;let r=t*2**(e-1),o=Math.floor(Math.random()*t);return Math.min(r+o,3e4)}function fr(t,e,n){if(e.length===0)return{records:t,filledToolUseId:0};let r=d=>{if(!n.fillableEvent(d.event))return!1;let c=d.tool;return c!==void 0&&c.correlationId===null},o=(d,c)=>{let u=c.tool;if(u===void 0)return!1;let f=n.decisionTurnOf(d),y=n.turnOf(c);return d.toolUseId!==null&&d.toolUseId!==""&&f.conversationId===y.conversationId&&f.generationId===y.generationId&&d.vendorTool===u.vendorTool&&d.argsHash===u.argsHash&&d.decidedAtMs<=c.capturedAtMs},s=new Set,i=0,a=t.map(d=>{if(!r(d))return d;let c;if(e.forEach((f,y)=>{s.has(y)||!o(f,d)||(c===void 0||f.decidedAtMs>c.decision.decidedAtMs)&&(c={index:y,decision:f})}),c===void 0)return d;s.add(c.index),i+=1;let u=d.tool;return{...d,tool:{...u,correlationId:c.decision.toolUseId}}});return{records:ga(a,e,n),filledToolUseId:i}}function ga(t,e,n){let r=e.filter(o=>o.blocked&&o.toolUseId!==null&&o.toolUseId!=="");return r.length===0?t:t.map(o=>{let s=o.tool;if(s===void 0||s.failed!==!0||!n.fillableEvent(o.event)||s.correlationId===null)return o;let i=n.turnOf(o);return r.some(d=>{let c=n.decisionTurnOf(d);return d.toolUseId===s.correlationId&&c.conversationId===i.conversationId&&c.generationId===i.generationId&&d.decidedAtMs<=o.capturedAtMs})?{...o,tool:{...s,pepBlocked:!0}}:o})}import{appendFileSync as qp}from"fs";import{chmodSync as ma,existsSync as ya,mkdirSync as gr,readdirSync as ha,readFileSync as _a,renameSync as Sa,rmSync as mr,writeFileSync as Ra}from"fs";import{basename as Ta,dirname as hr,join as xa}from"path";var _r=448,ae=384,yr=0;function Sr(t,e=process.pid){return yr+=1,xa(hr(t),`.${Ta(t)}.${e}.${yr}.tmp`)}var P={readFile(t){return _a(t)},writeFileAtomic(t,e,n){gr(hr(t),{recursive:!0,mode:_r});let r=Sr(t);try{Ra(r,e,{mode:n}),ma(r,n),Sa(r,t)}catch(o){throw mr(r,{force:!0}),o}},mkdirp(t,e){gr(t,{recursive:!0,mode:e})},remove(t){mr(t,{recursive:!0,force:!0})},exists(t){return ya(t)},readdir(t){return ha(t).sort()}};var an=".dropped",ba="c";function Rr(t){return t===ba?"queue-full":`mark-${t}`}import{createHash as tf}from"crypto";import{join as U}from"path";function B(t,e){let n=U(t,".agenttrail",e),r=U(n,"runtime");return{root:n,credentials:U(n,"credentials.json"),install:U(n,"install.json"),projects:U(n,"projects.json"),runtime:r,captureHook:U(r,"capture-hook.mjs"),flush:U(r,"flush.mjs"),queueKey:U(n,"queue.key"),enforcement:U(n,"enforcement.json"),pepSnapshot:U(n,"pep-snapshot.json"),queue:U(n,"queue"),turns:U(n,"turns"),senderLock:U(n,"sender.lock"),senderState:U(n,"sender-state.json"),backfillState:U(n,"backfill-state.json")}}function Xe(t,e,n){return U(B(t,e).queue,n)}function _t(t,e,n){return U(B(t,e).turns,`${n}.json`)}import{randomBytes as Ea}from"crypto";import{closeSync as va,openSync as Aa,readFileSync as Ca,rmSync as Ia,statSync as ka,utimesSync as Oa,writeSync as wa}from"fs";var Tr=5e3,dn=2e4,et={acquire(t,e){let n=Aa(t,"wx",384);try{wa(n,e)}finally{va(n)}},release(t){try{Ia(t,{force:!0})}catch{}},age(t){try{return Date.now()-ka(t).mtimeMs}catch{return null}},read(t){try{return Ca(t,"utf8")}catch{return null}},touch(t){try{let e=new Date;Oa(t,e,e)}catch{}},now:()=>Date.now()};function xr(t,e=et){let n=e.age(t);return n!==null&&n<=dn&&n>=-dn}function Da(t,e){return`${t} ${new Date(e).toISOString()} ${Ea(8).toString("hex")}
11
- `}function St(t,e=et,n=process.pid){let r=Da(n,e.now()),o=()=>{try{return e.acquire(t,r),!0}catch{return!1}};if(!o()&&(xr(t,e)||(e.release(t),!o())))return;let s=e.now();return{token:r,owned:()=>e.read(t)===r,heartbeat(){let i=e.now();return i-s<Tr?!0:(s=i,e.read(t)!==r?!1:(e.touch(t),!0))},release(){e.read(t)===r&&e.release(t)}}}var tt=Object.freeze({v:1,dropped:Object.freeze({}),unknownKinds:Object.freeze({}),pepDecisions:Object.freeze({seen:0,filledToolUseId:0,orphaned:0}),projects:Object.freeze({})});function nt(){return{dropped:{},unknownKinds:{},pepDecisions:{seen:0,filledToolUseId:0,orphaned:0},projects:{}}}function ln(t){return t.lastUploadAtMs===void 0&&t.lastError===void 0&&Object.keys(t.dropped).length===0&&Object.keys(t.unknownKinds).length===0&&t.pepDecisions.seen===0&&t.pepDecisions.filledToolUseId===0&&t.pepDecisions.orphaned===0&&Object.keys(t.projects).length===0}function Fe(t,e){t[e]=(t[e]??0)+1}function rt(t,e){let n=t.projects[e];if(n!==void 0)return n;let r={dropped:{}};return t.projects[e]=r,r}function ge(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function cn(t){if(!ge(t))return{};let e={};for(let[n,r]of Object.entries(t))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(e[n]=r);return e}function br(t){if(!ge(t))return;let{version:e,seenAtMs:n}=t;if(!(typeof e!="string"||e==="")&&!(typeof n!="number"||!Number.isFinite(n)))return{version:e,seenAtMs:n}}function je(t){return typeof t=="number"&&Number.isFinite(t)?t:void 0}function Tt(t,e){return e!==void 0?{[t]:e}:{}}function Rt(t,e){return t===void 0?void 0:t[e]}function Ar(t,e){if(t===void 0)return tt;let n;try{n=JSON.parse(t)}catch{return tt}if(!ge(n)||n.v!==1)return tt;let r=ge(n.pepDecisions)?n.pepDecisions:{},o={};if(ge(n.projects))for(let[c,u]of Object.entries(n.projects)){if(!ge(u))continue;let f=br(u[e]),y=je(u.lastUploadAtMs);o[c]={...Tt(e,f),...y!==void 0?{lastUploadAtMs:y}:{},dropped:cn(u.dropped)}}let s=ge(n.lastError)?n.lastError:void 0,i=je(s?.atMs),a=br(n[e]),d=je(n.lastUploadAtMs);return{v:1,...d!==void 0?{lastUploadAtMs:d}:{},...i!==void 0&&typeof s?.message=="string"?{lastError:{atMs:i,message:s.message}}:{},dropped:cn(n.dropped),unknownKinds:cn(n.unknownKinds),pepDecisions:{seen:je(r.seen)??0,filledToolUseId:je(r.filledToolUseId)??0,orphaned:je(r.orphaned)??0},...Tt(e,a),projects:o}}function Cr(t){return`${JSON.stringify(t)}
12
- `}function pn(t,e,n,r=P){try{return Ar(r.readFile(B(t,e).senderState).toString("utf8"),n)}catch{return tt}}function fn(t,e,n,r=P){r.writeFileAtomic(B(t,e).senderState,Cr(n),ae)}function un(t,e){let n={...t};for(let[r,o]of Object.entries(e))n[r]=(n[r]??0)+o;return n}function Er(t,e){return e===void 0?t:t===void 0||e.seenAtMs>=t.seenAtMs?e:t}function vr(t,e){return e===void 0?t:t===void 0?e:Math.max(t,e)}function gn(t,e,n){let r={...t.projects};for(let[a,d]of Object.entries(e.projects)){let c=r[a]??{},u=Er(Rt(c,n),Rt(d,n)),f=vr(c.lastUploadAtMs,d.lastUploadAtMs);r[a]={...Tt(n,u),...f!==void 0?{lastUploadAtMs:f}:{},dropped:un(c.dropped??{},d.dropped)}}let o=Object.values(e.projects).reduce((a,d)=>Er(a,Rt(d,n)),Rt(t,n)),s=vr(t.lastUploadAtMs,e.lastUploadAtMs),i=e.lastError??t.lastError;return{v:1,...s!==void 0?{lastUploadAtMs:s}:{},...i!==void 0?{lastError:i}:{},dropped:un(t.dropped,e.dropped),unknownKinds:un(t.unknownKinds,e.unknownKinds),pepDecisions:{seen:t.pepDecisions.seen+e.pepDecisions.seen,filledToolUseId:t.pepDecisions.filledToolUseId+e.pepDecisions.filledToolUseId,orphaned:t.pepDecisions.orphaned+e.pepDecisions.orphaned},...Tt(n,o),projects:r}}var Ma=600*1e3,xt=600*1e3,Or=1440*60*1e3,Na={idleSweepMs:Ma,orphanWindowMs:xt,retentionMs:Or};function de(t,e){return`${t}\0${e??""}`}function Pa(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function Ua(t){let e;try{e=JSON.parse(t)}catch{return}if(!(!Pa(e)||e.v!==1)&&!(typeof e.traceId!="string"||typeof e.projectKey!="string")&&typeof e.conversationId=="string"&&!(typeof e.lastRecordAtMs!="number"||!Number.isFinite(e.lastRecordAtMs))&&!(!Array.isArray(e.files)||!e.files.every(n=>typeof n=="string")))return e}function ja(t){return`${JSON.stringify(t)}
13
- `}function wr(t,e,n=P){let r=B(t,e).turns,o;try{o=n.readdir(r)}catch{return{states:[],unreadable:[]}}let s=[],i=[];for(let a of o){if(!a.endsWith(".json"))continue;let d=`${r}/${a}`,c;try{c=Ua(n.readFile(d).toString("utf8"))}catch{c=void 0}c===void 0?i.push(d):s.push(c)}return{states:s,unreadable:i}}function ot(t,e,n,r=P){r.writeFileAtomic(_t(t,e,n.traceId),ja(n),ae)}function mn(t,e,n,r=P){r.remove(_t(t,e,n))}function Fa(t){let e=/^(\d+)-(\d+)-(\d+)\.json$/.exec(t);if(e!==null)return{atMs:Number(e[1]),pid:Number(e[2]),seq:Number(e[3])}}function La(t){return[...t].sort((e,n)=>e.atMs-n.atMs||e.pid-n.pid||e.seq-n.seq||e.name.localeCompare(n.name))}function Dr(t,e,n=P,r,o=""){let s;try{s=n.readdir(t)}catch{return{files:[],other:[]}}let i=[],a=[];for(let d of s){let c=Fa(d);if(c===void 0){a.push(d);continue}let u=o===""?d:`${o}/${d}`,f=r?.get(u);if(f!==void 0){i.push(f);continue}let y;try{y=e(n.readFile(`${t}/${d}`).toString("utf8"))}catch{y=void 0}let v={name:d,...c,entry:y};r?.set(u,v),i.push(v)}return{files:La(i),other:a}}function Ba(t,e,n,r,o){return{v:1,traceId:e,projectKey:t,conversationId:n,generationId:r,files:[],starts:{},sent:{},lastRecordAtMs:o}}function me(t){return t.records.reduce((e,n)=>Math.max(e,n.capturedAtMs),t.loaded.lastRecordAtMs)}function Mr(t,e){return t.records.find(n=>{if(!e.closesTurn(n))return!1;let r=e.turnOf(n);return r.conversationId!==null&&de(r.conversationId,r.generationId)===t.key})}function Ir(t,e,n){let r=Mr(t,n);if(r!==void 0&&r.capturedAtMs<e)return!1;let o=t.loaded.closed;return o!==void 0&&o.atMs<e&&r===void 0?me(t)>o.atMs:!0}function Nr(t){let e=t.rules,n={...Na,...t.limits},r=[],o=new Map,s=new Set,i=[],a=[],d=[],c=new Map(t.files.map(g=>[g.name,g]));for(let g of t.states){if(g.projectKey!==t.projectKey)continue;let x={key:de(g.conversationId,g.generationId),loaded:g,records:[],decisions:[],files:[]};r.push(x),o.set(x.key,x)}let u=(g,x)=>{s.add(x.name),g.files.push(x.name);let A=x.entry;A!==void 0&&(A.kind==="capture"?g.records.push(A):A.kind==="pep-decision"&&g.decisions.push(A))};for(let g of r)for(let x of g.loaded.files){let A=c.get(x);A!==void 0&&u(g,A)}for(let g of r)for(let x of g.records)kr(d,g,x,e);let f=(g,x)=>r.filter(A=>A.loaded.conversationId===g&&Ir(A,x,e)).sort((A,k)=>me(A)-me(k)).at(-1),y=g=>d.filter(x=>x.startAtMs<=g&&(x.stopAtMs===void 0||g<=x.stopAtMs)).sort((x,A)=>x.startAtMs-A.startAtMs).at(-1),v=(g,x)=>{let A=r.filter(k=>Ir(k,g.atMs,e)&&Math.abs(g.atMs-me(k))<=n.orphanWindowMs).sort((k,D)=>me(k)-me(D)).at(-1);if(A!==void 0){u(A,g);return}t.nowMs-g.atMs>=n.orphanWindowMs?a.push({file:g,reason:x}):i.push(g)};for(let g of t.files){if(s.has(g.name))continue;let x=g.entry;if(x===void 0){a.push({file:g,reason:"unreadable"});continue}if(x.kind==="unknown"){t.nowMs-g.atMs>=n.orphanWindowMs?a.push({file:g,reason:"unknown-kind"}):i.push(g);continue}if(x.kind==="pep-decision"){let O=e.decisionTurnOf(x),w=O.conversationId===null?void 0:o.get(de(O.conversationId,O.generationId));w!==void 0?u(w,g):t.nowMs-g.atMs>=n.orphanWindowMs?a.push({file:g,reason:"decision-orphan"}):i.push(g);continue}let A=x,k=e.subagentOf(A);if(k!==void 0){let O=k.parentConversationId,w=O===null?void 0:f(O,A.capturedAtMs);if(w===void 0){v(g,"orphan");continue}u(w,g),kr(d,w,A,e);continue}let D=e.turnOf(A);if(D.conversationId!==null){let O=o.get(de(D.conversationId,D.generationId));if(O!==void 0){u(O,g);continue}if(e.opensTurn(A)){let l=t.traceIdFor({conversationId:D.conversationId,generationId:D.generationId}),S={key:de(D.conversationId,D.generationId),loaded:Ba(t.projectKey,l,D.conversationId,D.generationId,A.capturedAtMs),records:[],decisions:[],files:[]};r.push(S),o.set(S.key,S),u(S,g);continue}let w=y(A.capturedAtMs);if(w!==void 0){u(w.builder,g);continue}}v(g,"orphan")}return{turns:r.filter(g=>g.files.length>0||g.loaded.files.length>0).map(g=>$a(g,t.nowMs,n,e)),pending:i,dropped:a,expired:[]}}function kr(t,e,n,r){let o=r.subagentOf(n);if(o===void 0)return;if(o.edge==="start"){t.push({builder:e,subagentId:o.subagentId,startAtMs:n.capturedAtMs});return}let s=t.find(i=>i.builder===e&&i.subagentId===o.subagentId);s!==void 0&&(s.stopAtMs=n.capturedAtMs)}function $a(t,e,n,r){let o=[...t.records].sort((c,u)=>c.capturedAtMs-u.capturedAtMs),s=me(t),i=Mr(t,r),a;i!==void 0?a={atMs:i.capturedAtMs,by:"stop"}:e-s>=n.idleSweepMs?a={atMs:s,by:"idle-sweep"}:t.loaded.closed!==void 0&&s<=t.loaded.closed.atMs&&(a=t.loaded.closed);let d={...t.loaded,files:[...t.files].sort(),lastRecordAtMs:s,...a!==void 0?{closed:a}:{}};return a===void 0&&"closed"in d&&delete d.closed,{state:d,records:o,decisions:t.decisions,files:d.files}}function Pr(t,e,n=Or){return t.filter(r=>r.files.length===0&&r.closed!==void 0&&e-r.lastRecordAtMs>=n)}var Fr=35e5,Ka=new Set([400,413,422]),yn={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function hn(t){return Va("sha256").update(JSON.stringify([t.spanId,t.parentSpanId,t.name,t.kind,t.startTimeUnixNano,t.endTimeUnixNano,t.error,Object.entries(t.attributes).sort()]),"utf8").digest("hex").slice(0,16)}function Lr(t,e){let n=e.closed;return n===void 0?{...t,endMs:null}:n.by==="stop"?{...t,endMs:t.endMs??n.atMs,closedBy:"stop"}:{...t,endMs:t.endMs??n.atMs,closedBy:n.by,status:t.status??"unknown"}}function Br(t,e,n){let r={},o=[];for(let s of t){if(n.has(s.spanId))continue;let i=e.starts[s.spanId],a=i===void 0||i===s.startTimeUnixNano?s:{...s,startTimeUnixNano:i,endTimeUnixNano:BigInt(s.endTimeUnixNano)<BigInt(i)?i:s.endTimeUnixNano},d=e.sent[a.spanId];d!==hn(a)&&d?.startsWith("dropped:")!==!0&&(o.push(a),r[a.spanId]=a.startTimeUnixNano)}return{spans:o,starts:r}}function $r(t,e,n=Fr){let r=[],o=[];for(let s of e){let i=[...o,s];if(Buffer.byteLength(JSON.stringify(ht({...t,spans:i})),"utf8")>n&&o.length>0){r.push(o),o=[s];continue}o=i}return o.length>0&&r.push(o),r}function bt(t,e,n){Fe(t.totals.dropped,n),Fe(t.report,n),e!==void 0&&Fe(rt(t.totals,e).dropped,n)}async function Qa(t,e,n){let r=async()=>(e.posts+=1,pr(n,{endpoint:e.credentials.endpoint,token:e.credentials.ingest_token,maxRetries:2},{fetch:t.fetch,sleep:t.sleep})),o=await r();if(o.status==="failed"&&o.httpStatus===401){let s=await t.refresh(e.credentials.ingest_token);if(s===null)return{ok:!1,status:401,error:"not signed in"};e.credentials=s,o=await r()}return o.status==="ok"?{ok:!0,status:o.httpStatus}:{ok:!1,...o.httpStatus!==void 0?{status:o.httpStatus}:{},...o.error!==void 0?{error:o.error}:{}}}function Ga(t,e,n,r){if(n.length===e.length)return!1;let o=new Set(n),s=de(r.conversationId,r.generationId);return e.some(i=>{if(o.has(i)||!t.closesTurn(i))return!1;let a=t.turnOf(i);return a.conversationId!==null&&de(a.conversationId,a.generationId)===s})}function Wa(t){let{closed:e,...n}=t;return n}async function Ha(t,e,n){let{adapter:r,deps:o,mem:s}=t,i=o.now(),a=fr(n.records,n.decisions,r),d=r.holdBack(a.records,i),c=d.length!==a.records.length,u=n.state,f=Ga(r,a.records,d,u)?Wa(u):u,y=f.closed===void 0;if(d.length===0)return u.closed===void 0||c?{state:u,sent:0,drained:!1,open:y}:Ur(t,u,n,a.filledToolUseId);let v=Lr(o.builder.assemble(d,void 0,n.decisions),f);if(f.closed!==void 0&&r.usageOf!==void 0){let O=r.usageOf({conversationId:u.conversationId,generationId:u.generationId},{home:o.home,env:o.env??process.env,io:o.io});O!==null&&(v={...v,usage:O})}let I=o.builder.build(v,{orgId:e.credentials.org_id,project:{projectId:e.project.projectId,projectLabel:e.project.projectLabel,...e.project.developerId!==void 0?{developerId:e.project.developerId}:{}},captureContent:e.project.captureContent,mode:"live",scopeVersion:o.scopeVersion,resolvedScrubbers:s.scrubbers}),g=new Set;y&&(g.add(o.builder.spanId(u.traceId,"root")),g.add(o.builder.spanId(u.traceId,"model")));let{spans:x,starts:A}=Br(I.spans,u,g),k=0;for(let O of $r(I,x)){let w=await Qa(o,e,ht({...I,spans:O}));if(w.ok){let l={...u.sent},S={...u.starts};for(let se of O)l[se.spanId]=hn(se),S[se.spanId]=A[se.spanId]??se.startTimeUnixNano;u={...u,sent:l,starts:S},k+=O.length;let M=o.now();s.totals.lastUploadAtMs=M,rt(s.totals,e.project.projectKey).lastUploadAtMs=M,ot(o.home,r.stateDir,u,o.io);continue}if(w.status!==void 0&&Ka.has(w.status)){let l={...u.sent};for(let S of O)l[S.spanId]=`dropped:${w.status}`,bt(s,e.project.projectKey,`rejected-${w.status}`);u={...u,sent:l},ot(o.home,r.stateDir,u,o.io);continue}return{state:u,sent:k,drained:!1,open:y,fatal:w.status===401?"auth":"network",...w.error!==void 0?{error:w.error}:{}}}return u.closed!==void 0&&!c&&I.spans.every(O=>u.sent[O.spanId]!==void 0)?{...Ur(t,u,n,a.filledToolUseId),sent:k}:{state:u,sent:k,drained:!1,open:y}}function Ur(t,e,n,r){let{adapter:o,deps:s,mem:i}=t,a={...e,files:[]};ot(s.home,o.stateDir,a,s.io);let d=Xe(s.home,o.stateDir,e.projectKey);for(let c of n.files)s.io.remove(`${d}/${c}`);return i.totals.pepDecisions.seen+=n.decisions.length,i.totals.pepDecisions.filledToolUseId+=r,{state:a,sent:0,drained:!0,open:!1}}function za(t,e,n){let{adapter:r,mem:o}=t,s;for(let d of n){let c=d.entry;if(c?.kind!=="capture")continue;let u=r.versionOf(c);u!==void 0&&(s===void 0||u.seenAtMs>s.seenAtMs)&&(s=u)}if(s===void 0)return;let i=rt(o.totals,e),a=i[r.versionKey];(a===void 0||s.seenAtMs>=a.seenAtMs)&&(i[r.versionKey]=s)}function Ya(t,e,n){let{deps:r,mem:o}=t,s=`${n}/${an}`,i=`${s}.${r.pid}.${r.now()}`;if(r.claimFile(s,i)){try{for(let a of r.io.readFile(i).toString("utf8"))bt(o,e,Rr(a))}catch{}r.io.remove(i)}}function Za(t,e){let n=/^\.(\d+)-\d+-\d+\.json\./.exec(t);if(!(n===null||!t.endsWith(".tmp")))return e-Number(n[1])}function jr(t){let{adapter:e,deps:n,mem:r}=t;if(!ln(r.totals))try{if(!n.io.exists(B(n.home,e.stateDir).projects)){r.totals=nt();return}fn(n.home,e.stateDir,gn(pn(n.home,e.stateDir,e.versionKey,n.io),r.totals,e.versionKey),n.io),r.totals=nt()}catch{}}function Vr(t,e,n){try{return n.readdir(B(t,e).queue)}catch{return[]}}async function qa(t,e){let{adapter:n,deps:r,mem:o}=t,s=r.now(),i=r.credentials();if(i===null)return Ja(s,{fatal:"credentials"});let a=n.readRegistry(r.home,r.io),d=0,c=0,u=0,f=0,y=!1,v,I;for(let g of Vr(r.home,n.stateDir,r.io)){let x=Xe(r.home,n.stateDir,g),{files:A,other:k}=Dr(x,l=>n.parseQueueEntry(l),r.io,o.cache,x);k.includes(an)&&Ya(t,g,x);for(let l of k){let S=Za(l,s);S!==void 0&&S>=xt&&r.io.remove(`${x}/${l}`)}if(A.length===0)continue;for(let l of A)u=Math.max(u,l.atMs);za(t,g,A);let D=Nr({projectKey:g,files:A,states:[...o.states.values()],nowMs:s,traceIdFor:l=>r.builder.traceId(l),...e.closeOpenTurns===!0?{limits:{idleSweepMs:0}}:{},rules:n});for(let{file:l,reason:S}of D.dropped){bt(o,g,S);let M=l.entry;M?.kind==="unknown"&&Fe(o.totals.unknownKinds,M.rawKind),S==="decision-orphan"&&(o.totals.pepDecisions.orphaned+=1,o.totals.pepDecisions.seen+=1),r.io.remove(`${x}/${l.name}`),o.cache.delete(`${x}/${l.name}`)}d+=D.pending.length;let O=a.kind==="ok"?a.registry.projects[g]:void 0;if(O===void 0){if(d+=D.turns.reduce((l,S)=>l+S.files.length,0),a.kind==="ok"){for(let l of D.turns)if(!(s-l.state.lastRecordAtMs<xt)){for(let S of l.files)bt(o,g,"unregistered"),r.io.remove(`${x}/${S}`),o.cache.delete(`${x}/${S}`);o.states.delete(l.state.traceId),mn(r.home,n.stateDir,l.state.traceId,r.io)}}continue}let w={project:O,credentials:i,posts:o.posts};for(let l of D.turns){let S;try{S=await Ha(t,w,l)}catch(M){S={state:l.state,sent:0,drained:!1,open:l.state.closed===void 0,fatal:"network",error:M instanceof Error?M.message:String(M)},Xa(t,l.state)}if(o.states.set(S.state.traceId,S.state),f+=S.sent,S.drained)for(let M of l.files)o.cache.delete(`${x}/${M}`);else d+=l.files.length,S.open&&(c+=1);if(S.fatal!==void 0){y=!0,I=S.error??I,o.totals.lastError={atMs:r.now(),message:S.error??(S.fatal==="auth"?"not signed in":"upload failed")},S.fatal==="auth"&&(v="auth");break}}if(o.posts=w.posts,i=w.credentials,v!==void 0)break}return{entries:d,openTurns:c,newestRecordMs:u,sent:f,failed:y,...v!==void 0?{fatal:v}:{},...I!==void 0?{error:I}:{}}}function Ja(t,e={}){return{entries:0,openTurns:0,newestRecordMs:t,sent:0,failed:!1,...e}}function Xa(t,e){try{ot(t.deps.home,t.adapter.stateDir,e,t.deps.io)}catch{}}function ed(t,e,n){for(let r of Vr(t,e,n))try{if(n.readdir(Xe(t,e,r)).some(s=>s.endsWith(".json")&&!s.startsWith(".")))return!0}catch{}return!1}function td(t,e,n,r){return t.failed?r:t.openTurns===0?e.pollIdleMs:n-t.newestRecordMs<=e.flowWindowMs?e.pollFlowingMs:e.pollOpenMs}async function Kr(t,e,n={}){let r=B(e.home,t.stateDir),o=St(r.senderLock,e.lockIO,e.pid);if(o===void 0)return{outcome:"locked",cycles:0,posts:0,spansSent:0,dropped:{}};let s=wr(e.home,t.stateDir,e.io);for(let g of s.unreadable)e.io.remove(g);let i={states:new Map(s.states.map(g=>[g.traceId,g])),cache:new Map,totals:nt(),report:{},scrubbers:sn(yt),posts:0},a={adapter:t,deps:e,mem:i},d=e.now(),c="done",u=0,f=0,y,v,I=e.limits.backoffMs;try{for(;;){if(!o.heartbeat()){c="lost-lock";break}let g=await qa(a,n);u+=1,f+=g.sent,y=g.error??y,jr(a);for(let x of Pr([...i.states.values()],e.now()))mn(e.home,t.stateDir,x.traceId,e.io),i.states.delete(x.traceId);if(g.fatal==="credentials"){c="no-credentials";break}if(g.failed){if(v??=e.now(),g.fatal==="auth"||e.now()-v>=e.limits.giveUpMs){c="send-failed";break}}else v=void 0,I=e.limits.backoffMs;if(n.maxRunMs!==void 0&&e.now()-d>=n.maxRunMs){c="time-limit";break}if(g.entries===0&&!g.failed){if(o.release(),o=void 0,!ed(e.home,t.stateDir,e.io)||(o=St(r.senderLock,e.lockIO,e.pid),o===void 0))break;continue}await e.sleep(td(g,e.limits,e.now(),I)),g.failed&&(I=Math.min(I*2,e.limits.pollIdleMs*12))}}finally{jr(a),o?.release()}return{outcome:c,cycles:u,posts:i.posts,spansSent:f,dropped:i.report,...y!==void 0?{lastError:y}:{}}}function Qr(t,e,n){try{let r=JSON.parse(n.readFile(B(t,e).install).toString("utf8"));return typeof r.cliVersion=="string"?r.cliVersion:void 0}catch{return}}var nd="cursor",Et="cursor",ye="cursor",Gr={agent:nd,vendor:Et,stateDir:ye};import{createHash as Of}from"crypto";var _n="MCP:";var st="user_prompt",id="gen_ai.completion",Z="full_command",Le="file_path",he="gen_ai.tool.call.result",it=new Set([st,id,Z,Le,he]);var vt="secret-manager-output",At=`[REDACTED:secret:${vt}]`,ad=[/^op\s+read(\s|$)/,/^op\s+item\s+get(\s|$)/,/^aws\s+secretsmanager\s+get-secret-value(\s|$)/,/^gcloud\s+secrets\s+versions\s+access(\s|$)/,/^vault\s+read(\s|$)/,/^vault\s+kv\s+get(\s|$)/,/^az\s+keyvault\s+secret\s+show(\s|$)/],dd=/&&|\|\||;|\|/,cd=/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;function ud(t){let e=t.trimStart().replace(cd,"");return ad.some(n=>n.test(e))}function ld(t){if(t.length===0)return!1;for(let e of t.split(dd))if(ud(e))return!0;return!1}var pd=new Set;function zr(t,e){let n=t[e.commandKey];if(typeof n!="string"||!ld(n))return pd;let r=new Set;for(let o of Object.keys(t)){let s=t[o];if(!(typeof s!="string"||s.length===0)){if(e.resultKeys?.has(o)){r.add(o);continue}e.resultKeyPrefixes?.some(i=>o.startsWith(i))&&r.add(o)}}return r}var fd={commandKey:Z,resultKeys:new Set([he])};function Yr(t,e,n={}){let r={},o={},s=0;if(e===null){for(let[a,d]of Object.entries(t))r[a]=d;return{attributes:r,redactedCount:0,byType:{}}}let i=zr(n.correlationCommand===void 0?t:{...t,[Z]:n.correlationCommand},fd);for(let[a,d]of Object.entries(t)){if(typeof d!="string"||d.length===0){r[a]=d;continue}if(i.has(a)){r[a]=At,o[vt]=(o[vt]??0)+1,s+=1;continue}if(!it.has(a)){r[a]=d;continue}let c=dr(d,e);if(r[a]=c.text,c.total>0){s+=c.total;for(let u in c.redactions)o[u]=(o[u]??0)+c.redactions[u]}}return{attributes:r,redactedCount:s,byType:o}}var Ct=8192;var qr=16*1024,Zr=Ct+qr;function Sn(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function gd(t){return t.length>Ct?t.slice(0,Ct):t}function md(t,e){let n=0,r=Math.min(t.length,e.length);for(;n<r&&t.charCodeAt(t.length-1-n)===e.charCodeAt(e.length-1-n);)n+=1;return n}function Jr(t,e){let n={},r=new Map;for(let[a,d]of Object.entries(t))if(it.has(a)&&d.length>Zr){let c=d.slice(0,Zr);n[a]=c,r.set(a,c)}else n[a]=d;let o=t[Z],s=Yr(n,e,o===void 0?{}:{correlationCommand:o}),i={};for(let[a,d]of Object.entries(s.attributes)){if(!it.has(a)){i[a]=d;continue}let c=r.get(a),u=d;if(c!==void 0&&u!==At){let f=Math.min(qr,md(c,u));u=u.slice(0,u.length-f)}i[a]=gd(u)}return{attributes:i,redactedCount:s.redactedCount,byType:s.byType}}function yd(t,e){if(typeof t.event!="string"||!e.has(t.event)||typeof t.capturedAtMs!="number"||!Number.isFinite(t.capturedAtMs))return!1;let n=t.tool;return n===void 0?!0:Sn(n)&&typeof n.vendorTool=="string"&&typeof n.argsHash=="string"&&Sn(n.call)&&typeof n.call.tool=="string"}function hd(t){return typeof t.decidedAtMs=="number"&&Number.isFinite(t.decidedAtMs)&&typeof t.decisionMs=="number"&&typeof t.hookEvent=="string"&&typeof t.vendorTool=="string"&&typeof t.argsHash=="string"&&typeof t.verdict=="string"&&typeof t.blocked=="boolean"}function Xr(t,e){let n;try{n=JSON.parse(t)}catch{return}if(!Sn(n))return;let r=n,o=()=>({kind:"unknown",rawKind:typeof r.kind=="string"?r.kind:String(r.kind),rawV:r.v});return r.v!==1?o():r.kind==="capture"&&yd(r,e)||r.kind==="pep-decision"&&hd(r)?r:o()}import{createHmac as tg,randomBytes as ng}from"crypto";var eo=Object.freeze(["beforeSubmitPrompt","postToolUse","postToolUseFailure","afterMCPExecution","afterAgentResponse","afterFileEdit","subagentStart","subagentStop","stop"]);var Sd=new Set(eo);function to(t){return Xr(t,Sd)}function It(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function no(t){return typeof t=="string"&&t!==""}function Rd(t,e){if(!It(e))return{key:t};let n=no(e.root)?e.root:void 0,r=Array.isArray(e.subfolders)?e.subfolders.map(o=>It(o)&&no(o.path)?o.path:void 0).filter(o=>o!==void 0):[];return{key:t,...n!==void 0?{root:n}:{},...r.length>0?{subfolders:r}:{}}}function Td(t,e){let n;try{n=JSON.parse(t)}catch{return}if(!It(n)||n.v!==1||!It(n.projects))return;let r={},o=[];for(let[s,i]of Object.entries(n.projects))e(s,i)?r[s]=i:o.push(Rd(s,i));return{registry:{v:1,projects:r},skipped:o}}var xd=Object.freeze({v:1,projects:Object.freeze({})});function ro(t,e,n=P){let r;try{if(!n.exists(t))return{kind:"missing"};r=n.readFile(t).toString("utf8")}catch{return{kind:"unreadable"}}let o=Td(r,e);return o===void 0?{kind:"unreadable"}:{kind:"ok",registry:o.registry,skipped:o.skipped}}import{join as Wg}from"path";function oo(t){return B(t,ye)}function so(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function ee(t){return typeof t=="string"&&t!==""}function io(t){return t==="project"||t==="user"}var bd=new Set(["flag","agenttrail-json","derived"]);function Ed(t){return so(t)&&ee(t.path)&&ee(t.transcriptFolder)&&io(t.install)&&ee(t.registeredAt)}function vd(t,e){return so(e)?e.projectKey===t&&ee(e.root)&&ee(e.transcriptFolder)&&ee(e.orgId)&&ee(e.projectSlug)&&ee(e.projectId)&&bd.has(e.projectSource)&&typeof e.projectLabel=="string"&&(e.developerId===void 0||typeof e.developerId=="string")&&typeof e.captureContent=="boolean"&&io(e.install)&&ee(e.registeredAt)&&(e.subfolders===void 0||Array.isArray(e.subfolders)&&e.subfolders.every(Ed)):!1}function ao(t,e=P){return ro(oo(t).projects,vd,e)}var co="cursorVersion";import{createHash as Gc}from"crypto";var uo=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Ad(t){return typeof t=="string"&&uo.test(t)}var lo=Ad;var j=[];for(let t=0;t<256;++t)j.push((t+256).toString(16).slice(1));function po(t,e=0){return j[t[e+0]]+j[t[e+1]]+j[t[e+2]]+j[t[e+3]]+"-"+j[t[e+4]]+j[t[e+5]]+"-"+j[t[e+6]]+j[t[e+7]]+"-"+j[t[e+8]]+j[t[e+9]]+"-"+j[t[e+10]]+j[t[e+11]]+j[t[e+12]]+j[t[e+13]]+j[t[e+14]]+j[t[e+15]]}function Cd(t){if(!lo(t))throw TypeError("Invalid UUID");let e,n=new Uint8Array(16);return n[0]=(e=parseInt(t.slice(0,8),16))>>>24,n[1]=e>>>16&255,n[2]=e>>>8&255,n[3]=e&255,n[4]=(e=parseInt(t.slice(9,13),16))>>>8,n[5]=e&255,n[6]=(e=parseInt(t.slice(14,18),16))>>>8,n[7]=e&255,n[8]=(e=parseInt(t.slice(19,23),16))>>>8,n[9]=e&255,n[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,n[11]=e/4294967296&255,n[12]=e>>>24&255,n[13]=e>>>16&255,n[14]=e>>>8&255,n[15]=e&255,n}var fo=Cd;function Id(t){t=unescape(encodeURIComponent(t));let e=[];for(let n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}var kd="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Od="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Rn(t,e,n){function r(o,s,i,a){var d;if(typeof o=="string"&&(o=Id(o)),typeof s=="string"&&(s=fo(s)),((d=s)===null||d===void 0?void 0:d.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=n(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){a=a||0;for(let u=0;u<16;++u)i[a+u]=c[u];return i}return po(c)}try{r.name=t}catch{}return r.DNS=kd,r.URL=Od,r}import wd from"crypto";function Dd(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),wd.createHash("sha1").update(t).digest()}var go=Dd;var Md=Rn("v5",80,go),kt=Md;var fe={};Jo(fe,{BRAND:()=>sc,DIRTY:()=>_e,EMPTY_PATH:()=>jd,INVALID:()=>R,NEVER:()=>Kc,OK:()=>L,ParseStatus:()=>F,Schema:()=>E,ZodAny:()=>le,ZodArray:()=>oe,ZodBigInt:()=>Re,ZodBoolean:()=>Te,ZodBranded:()=>dt,ZodCatch:()=>De,ZodDate:()=>xe,ZodDefault:()=>we,ZodDiscriminatedUnion:()=>Dt,ZodEffects:()=>z,ZodEnum:()=>ke,ZodError:()=>V,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>Nt,ZodIntersection:()=>Ae,ZodIssueCode:()=>p,ZodLazy:()=>Ce,ZodLiteral:()=>Ie,ZodMap:()=>Ge,ZodNaN:()=>He,ZodNativeEnum:()=>Oe,ZodNever:()=>Y,ZodNull:()=>Ee,ZodNullable:()=>X,ZodNumber:()=>Se,ZodObject:()=>K,ZodOptional:()=>W,ZodParsedType:()=>h,ZodPipeline:()=>ct,ZodPromise:()=>pe,ZodReadonly:()=>Me,ZodRecord:()=>Mt,ZodSchema:()=>E,ZodSet:()=>We,ZodString:()=>ue,ZodSymbol:()=>Ke,ZodTransformer:()=>z,ZodTuple:()=>J,ZodType:()=>E,ZodUndefined:()=>be,ZodUnion:()=>ve,ZodUnknown:()=>re,ZodVoid:()=>Qe,addIssueToContext:()=>m,any:()=>gc,array:()=>_c,bigint:()=>cc,boolean:()=>vo,coerce:()=>Vc,custom:()=>xo,date:()=>uc,datetimeRegex:()=>Ro,defaultErrorMap:()=>te,discriminatedUnion:()=>xc,effect:()=>Nc,enum:()=>wc,function:()=>Ic,getErrorMap:()=>Be,getParsedType:()=>q,instanceof:()=>ac,intersection:()=>bc,isAborted:()=>Ot,isAsync:()=>$e,isDirty:()=>wt,isValid:()=>ce,late:()=>ic,lazy:()=>kc,literal:()=>Oc,makeIssue:()=>at,map:()=>Ac,nan:()=>dc,nativeEnum:()=>Dc,never:()=>yc,null:()=>fc,nullable:()=>Uc,number:()=>Eo,object:()=>Sc,objectUtil:()=>Tn,oboolean:()=>$c,onumber:()=>Bc,optional:()=>Pc,ostring:()=>Lc,pipeline:()=>Fc,preprocess:()=>jc,promise:()=>Mc,quotelessJson:()=>Nd,record:()=>vc,set:()=>Cc,setErrorMap:()=>Ud,strictObject:()=>Rc,string:()=>bo,symbol:()=>lc,transformer:()=>Nc,tuple:()=>Ec,undefined:()=>pc,union:()=>Tc,unknown:()=>mc,util:()=>C,void:()=>hc});var C;(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function n(o){throw new Error}t.assertNever=n,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(C||(C={}));var Tn;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Tn||(Tn={}));var h=C.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),q=t=>{switch(typeof t){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(t)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(t)?h.array:t===null?h.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?h.promise:typeof Map<"u"&&t instanceof Map?h.map:typeof Set<"u"&&t instanceof Set?h.set:typeof Date<"u"&&t instanceof Date?h.date:h.object;default:return h.unknown}};var p=C.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Nd=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),V=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){let n=e||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,d=0;for(;d<i.path.length;){let c=i.path[d];d===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],d++}}};return o(this),r}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,C.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(e(o))}else r.push(e(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};V.create=t=>new V(t);var Pd=(t,e)=>{let n;switch(t.code){case p.invalid_type:t.received===h.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case p.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,C.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:n=`Unrecognized key(s) in object: ${C.joinValues(t.keys,", ")}`;break;case p.invalid_union:n="Invalid input";break;case p.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${C.joinValues(t.options)}`;break;case p.invalid_enum_value:n=`Invalid enum value. Expected ${C.joinValues(t.options)}, received '${t.received}'`;break;case p.invalid_arguments:n="Invalid function arguments";break;case p.invalid_return_type:n="Invalid function return type";break;case p.invalid_date:n="Invalid date";break;case p.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:C.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case p.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case p.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case p.custom:n="Invalid input";break;case p.invalid_intersection_types:n="Intersection results could not be merged";break;case p.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case p.not_finite:n="Number must be finite";break;default:n=e.defaultError,C.assertNever(t)}return{message:n}},te=Pd;var mo=te;function Ud(t){mo=t}function Be(){return mo}var at=t=>{let{data:e,path:n,errorMaps:r,issueData:o}=t,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",d=r.filter(c=>!!c).slice().reverse();for(let c of d)a=c(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},jd=[];function m(t,e){let n=Be(),r=at({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===te?void 0:te].filter(o=>!!o)});t.common.issues.push(r)}var F=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){let r=[];for(let o of n){if(o.status==="aborted")return R;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return t.mergeObjectSync(e,r)}static mergeObjectSync(e,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return R;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:e.value,value:r}}},R=Object.freeze({status:"aborted"}),_e=t=>({status:"dirty",value:t}),L=t=>({status:"valid",value:t}),Ot=t=>t.status==="aborted",wt=t=>t.status==="dirty",ce=t=>t.status==="valid",$e=t=>typeof Promise<"u"&&t instanceof Promise;var _;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(_||(_={}));var H=class{constructor(e,n,r,o){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},yo=(t,e)=>{if(ce(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new V(t.common.issues);return this._error=n,this._error}}};function b(t){if(!t)return{};let{errorMap:e,invalid_type_error:n,required_error:r,description:o}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:d}=t;return i.code==="invalid_enum_value"?{message:d??a.defaultError}:typeof a.data>"u"?{message:d??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:d??n??a.defaultError}},description:o}}var E=class{get description(){return this._def.description}_getType(e){return q(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:q(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new F,ctx:{common:e.parent.common,data:e.data,parsedType:q(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let n=this._parse(e);if($e(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){let n=this._parse(e);return Promise.resolve(n)}parse(e,n){let r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:q(e)},o=this._parseSync({data:e,path:r.path,parent:r});return yo(r,o)}"~validate"(e){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:q(e)};if(!this["~standard"].async)try{let r=this._parseSync({data:e,path:[],parent:n});return ce(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(r=>ce(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(e,n){let r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:q(e)},o=this._parse({data:e,path:r.path,parent:r}),s=await($e(o)?o:Promise.resolve(o));return yo(r,s)}refine(e,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:p.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,n){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(e){return new z({schema:this,typeName:T.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return W.create(this,this._def)}nullable(){return X.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return oe.create(this)}promise(){return pe.create(this,this._def)}or(e){return ve.create([this,e],this._def)}and(e){return Ae.create(this,e,this._def)}transform(e){return new z({...b(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let n=typeof e=="function"?e:()=>e;return new we({...b(this._def),innerType:this,defaultValue:n,typeName:T.ZodDefault})}brand(){return new dt({typeName:T.ZodBranded,type:this,...b(this._def)})}catch(e){let n=typeof e=="function"?e:()=>e;return new De({...b(this._def),innerType:this,catchValue:n,typeName:T.ZodCatch})}describe(e){let n=this.constructor;return new n({...this._def,description:e})}pipe(e){return ct.create(this,e)}readonly(){return Me.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Fd=/^c[^\s-]{8,}$/i,Ld=/^[0-9a-z]+$/,Bd=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$d=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Vd=/^[a-z0-9_-]{21}$/i,Kd=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Qd=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Gd=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Wd="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xn,Hd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,zd=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Yd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Zd=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,qd=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Jd=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,_o="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Xd=new RegExp(`^${_o}$`);function So(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function ec(t){return new RegExp(`^${So(t)}$`)}function Ro(t){let e=`${_o}T${So(t)}`,n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function tc(t,e){return!!((e==="v4"||!e)&&Hd.test(t)||(e==="v6"||!e)&&Yd.test(t))}function nc(t,e){if(!Kd.test(t))return!1;try{let[n]=t.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function rc(t,e){return!!((e==="v4"||!e)&&zd.test(t)||(e==="v6"||!e)&&Zd.test(t))}var ue=class t extends E{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==h.string){let s=this._getOrReturnCtx(e);return m(s,{code:p.invalid_type,expected:h.string,received:s.parsedType}),R}let r=new F,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),m(o,{code:p.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),m(o,{code:p.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?m(o,{code:p.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&m(o,{code:p.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Gd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"email",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")xn||(xn=new RegExp(Wd,"u")),xn.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"emoji",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")$d.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"uuid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Vd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"nanoid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Fd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"cuid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Ld.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"cuid2",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Bd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"ulid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),m(o,{validation:"url",code:p.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"regex",code:p.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),m(o,{code:p.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),m(o,{code:p.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),m(o,{code:p.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Ro(s).test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{code:p.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?Xd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{code:p.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?ec(s).test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{code:p.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Qd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"duration",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?tc(e.data,s.version)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"ip",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?nc(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"jwt",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?rc(e.data,s.version)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"cidr",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?qd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"base64",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?Jd.test(e.data)||(o=this._getOrReturnCtx(e,o),m(o,{validation:"base64url",code:p.invalid_string,message:s.message}),r.dirty()):C.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(o=>e.test(o),{validation:n,code:p.invalid_string,..._.errToObj(r)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",..._.errToObj(e)})}url(e){return this._addCheck({kind:"url",..._.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",..._.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",..._.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",..._.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",..._.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",..._.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",..._.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",..._.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",..._.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",..._.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",..._.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",..._.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,..._.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,..._.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",..._.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,..._.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n?.position,..._.errToObj(n?.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,..._.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,..._.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,..._.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,..._.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,..._.errToObj(n)})}nonempty(e){return this.min(1,_.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};ue.create=t=>new ue({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...b(t)});function oc(t,e){let n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}var Se=class t extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==h.number){let s=this._getOrReturnCtx(e);return m(s,{code:p.invalid_type,expected:h.number,received:s.parsedType}),R}let r,o=new F;for(let s of this._def.checks)s.kind==="int"?C.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),m(r,{code:p.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?oc(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),m(r,{code:p.not_finite,message:s.message}),o.dirty()):C.assertNever(s);return{status:o.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,_.toString(n))}gt(e,n){return this.setLimit("min",e,!1,_.toString(n))}lte(e,n){return this.setLimit("max",e,!0,_.toString(n))}lt(e,n){return this.setLimit("max",e,!1,_.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:_.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:_.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:_.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.toString(e)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&C.isInteger(e.value))}get isFinite(){let e=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};Se.create=t=>new Se({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...b(t)});var Re=class t extends E{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==h.bigint)return this._getInvalidInput(e);let r,o=new F;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),m(r,{code:p.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):C.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:h.bigint,received:n.parsedType}),R}gte(e,n){return this.setLimit("min",e,!0,_.toString(n))}gt(e,n){return this.setLimit("min",e,!1,_.toString(n))}lte(e,n){return this.setLimit("max",e,!0,_.toString(n))}lt(e,n){return this.setLimit("max",e,!1,_.toString(n))}setLimit(e,n,r,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:_.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:_.toString(n)})}get minValue(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Re.create=t=>new Re({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...b(t)});var Te=class extends E{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==h.boolean){let r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:h.boolean,received:r.parsedType}),R}return L(e.data)}};Te.create=t=>new Te({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...b(t)});var xe=class t extends E{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==h.date){let s=this._getOrReturnCtx(e);return m(s,{code:p.invalid_type,expected:h.date,received:s.parsedType}),R}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return m(s,{code:p.invalid_date}),R}let r=new F,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),m(o,{code:p.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),m(o,{code:p.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):C.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:_.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:_.toString(n)})}get minDate(){let e=null;for(let n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}};xe.create=t=>new xe({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...b(t)});var Ke=class extends E{_parse(e){if(this._getType(e)!==h.symbol){let r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:h.symbol,received:r.parsedType}),R}return L(e.data)}};Ke.create=t=>new Ke({typeName:T.ZodSymbol,...b(t)});var be=class extends E{_parse(e){if(this._getType(e)!==h.undefined){let r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:h.undefined,received:r.parsedType}),R}return L(e.data)}};be.create=t=>new be({typeName:T.ZodUndefined,...b(t)});var Ee=class extends E{_parse(e){if(this._getType(e)!==h.null){let r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:h.null,received:r.parsedType}),R}return L(e.data)}};Ee.create=t=>new Ee({typeName:T.ZodNull,...b(t)});var le=class extends E{constructor(){super(...arguments),this._any=!0}_parse(e){return L(e.data)}};le.create=t=>new le({typeName:T.ZodAny,...b(t)});var re=class extends E{constructor(){super(...arguments),this._unknown=!0}_parse(e){return L(e.data)}};re.create=t=>new re({typeName:T.ZodUnknown,...b(t)});var Y=class extends E{_parse(e){let n=this._getOrReturnCtx(e);return m(n,{code:p.invalid_type,expected:h.never,received:n.parsedType}),R}};Y.create=t=>new Y({typeName:T.ZodNever,...b(t)});var Qe=class extends E{_parse(e){if(this._getType(e)!==h.undefined){let r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:h.void,received:r.parsedType}),R}return L(e.data)}};Qe.create=t=>new Qe({typeName:T.ZodVoid,...b(t)});var oe=class t extends E{_parse(e){let{ctx:n,status:r}=this._processInputParams(e),o=this._def;if(n.parsedType!==h.array)return m(n,{code:p.invalid_type,expected:h.array,received:n.parsedType}),R;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(m(n,{code:i?p.too_big:p.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(m(n,{code:p.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(m(n,{code:p.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new H(n,i,n.path,a)))).then(i=>F.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new H(n,i,n.path,a)));return F.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new t({...this._def,minLength:{value:e,message:_.toString(n)}})}max(e,n){return new t({...this._def,maxLength:{value:e,message:_.toString(n)}})}length(e,n){return new t({...this._def,exactLength:{value:e,message:_.toString(n)}})}nonempty(e){return this.min(1,e)}};oe.create=(t,e)=>new oe({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...b(e)});function Ve(t){if(t instanceof K){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=W.create(Ve(r))}return new K({...t._def,shape:()=>e})}else return t instanceof oe?new oe({...t._def,type:Ve(t.element)}):t instanceof W?W.create(Ve(t.unwrap())):t instanceof X?X.create(Ve(t.unwrap())):t instanceof J?J.create(t.items.map(e=>Ve(e))):t}var K=class t extends E{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),n=C.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==h.object){let c=this._getOrReturnCtx(e);return m(c,{code:p.invalid_type,expected:h.object,received:c.parsedType}),R}let{status:r,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Y&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let d=[];for(let c of i){let u=s[c],f=o.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new H(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof Y){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)d.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(m(o,{code:p.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let f=o.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new H(o,f,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of d){let f=await u.key,y=await u.value;c.push({key:f,value:y,alwaysSet:u.alwaysSet})}return c}).then(c=>F.mergeObjectSync(r,c)):F.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(e){return _.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:_.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:T.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let n={};for(let r of C.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}omit(e){let n={};for(let r of C.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new t({...this._def,shape:()=>n})}deepPartial(){return Ve(this)}partial(e){let n={};for(let r of C.objectKeys(this.shape)){let o=this.shape[r];e&&!e[r]?n[r]=o:n[r]=o.optional()}return new t({...this._def,shape:()=>n})}required(e){let n={};for(let r of C.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof W;)s=s._def.innerType;n[r]=s}return new t({...this._def,shape:()=>n})}keyof(){return To(C.objectKeys(this.shape))}};K.create=(t,e)=>new K({shape:()=>t,unknownKeys:"strip",catchall:Y.create(),typeName:T.ZodObject,...b(e)});K.strictCreate=(t,e)=>new K({shape:()=>t,unknownKeys:"strict",catchall:Y.create(),typeName:T.ZodObject,...b(e)});K.lazycreate=(t,e)=>new K({shape:t,unknownKeys:"strip",catchall:Y.create(),typeName:T.ZodObject,...b(e)});var ve=class extends E{_parse(e){let{ctx:n}=this._processInputParams(e),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new V(a.ctx.common.issues));return m(n,{code:p.invalid_union,unionErrors:i}),R}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let d of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=d._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(d=>new V(d));return m(n,{code:p.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};ve.create=(t,e)=>new ve({options:t,typeName:T.ZodUnion,...b(e)});var ne=t=>t instanceof Ce?ne(t.schema):t instanceof z?ne(t.innerType()):t instanceof Ie?[t.value]:t instanceof ke?t.options:t instanceof Oe?C.objectValues(t.enum):t instanceof we?ne(t._def.innerType):t instanceof be?[void 0]:t instanceof Ee?[null]:t instanceof W?[void 0,...ne(t.unwrap())]:t instanceof X?[null,...ne(t.unwrap())]:t instanceof dt||t instanceof Me?ne(t.unwrap()):t instanceof De?ne(t._def.innerType):[],Dt=class t extends E{_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==h.object)return m(n,{code:p.invalid_type,expected:h.object,received:n.parsedType}),R;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(m(n,{code:p.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),R)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,n,r){let o=new Map;for(let s of n){let i=ne(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:T.ZodDiscriminatedUnion,discriminator:e,options:n,optionsMap:o,...b(r)})}};function bn(t,e){let n=q(t),r=q(e);if(t===e)return{valid:!0,data:t};if(n===h.object&&r===h.object){let o=C.objectKeys(e),s=C.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let d=bn(t[a],e[a]);if(!d.valid)return{valid:!1};i[a]=d.data}return{valid:!0,data:i}}else if(n===h.array&&r===h.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],d=bn(i,a);if(!d.valid)return{valid:!1};o.push(d.data)}return{valid:!0,data:o}}else return n===h.date&&r===h.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var Ae=class extends E{_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=(s,i)=>{if(Ot(s)||Ot(i))return R;let a=bn(s.value,i.value);return a.valid?((wt(s)||wt(i))&&n.dirty(),{status:n.value,value:a.data}):(m(r,{code:p.invalid_intersection_types}),R)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ae.create=(t,e,n)=>new Ae({left:t,right:e,typeName:T.ZodIntersection,...b(n)});var J=class t extends E{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.array)return m(r,{code:p.invalid_type,expected:h.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return m(r,{code:p.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),R;!this._def.rest&&r.data.length>this._def.items.length&&(m(r,{code:p.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let d=this._def.items[a]||this._def.rest;return d?d._parse(new H(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>F.mergeArray(n,i)):F.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};J.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new J({items:t,typeName:T.ZodTuple,rest:null,...b(e)})};var Mt=class t extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.object)return m(r,{code:p.invalid_type,expected:h.object,received:r.parsedType}),R;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new H(r,a,r.path,a)),value:i._parse(new H(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?F.mergeObjectAsync(n,o):F.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof E?new t({keyType:e,valueType:n,typeName:T.ZodRecord,...b(r)}):new t({keyType:ue.create(),valueType:e,typeName:T.ZodRecord,...b(n)})}},Ge=class extends E{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.map)return m(r,{code:p.invalid_type,expected:h.map,received:r.parsedType}),R;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,d],c)=>({key:o._parse(new H(r,a,r.path,[c,"key"])),value:s._parse(new H(r,d,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let d of i){let c=await d.key,u=await d.value;if(c.status==="aborted"||u.status==="aborted")return R;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let d of i){let c=d.key,u=d.value;if(c.status==="aborted"||u.status==="aborted")return R;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Ge.create=(t,e,n)=>new Ge({valueType:e,keyType:t,typeName:T.ZodMap,...b(n)});var We=class t extends E{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==h.set)return m(r,{code:p.invalid_type,expected:h.set,received:r.parsedType}),R;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(m(r,{code:p.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(m(r,{code:p.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(d){let c=new Set;for(let u of d){if(u.status==="aborted")return R;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((d,c)=>s._parse(new H(r,d,r.path,c)));return r.common.async?Promise.all(a).then(d=>i(d)):i(a)}min(e,n){return new t({...this._def,minSize:{value:e,message:_.toString(n)}})}max(e,n){return new t({...this._def,maxSize:{value:e,message:_.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}};We.create=(t,e)=>new We({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...b(e)});var Nt=class t extends E{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==h.function)return m(n,{code:p.invalid_type,expected:h.function,received:n.parsedType}),R;function r(a,d){return at({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Be(),te].filter(c=>!!c),issueData:{code:p.invalid_arguments,argumentsError:d}})}function o(a,d){return at({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Be(),te].filter(c=>!!c),issueData:{code:p.invalid_return_type,returnTypeError:d}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof pe){let a=this;return L(async function(...d){let c=new V([]),u=await a._def.args.parseAsync(d,s).catch(v=>{throw c.addIssue(r(d,v)),c}),f=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(f,s).catch(v=>{throw c.addIssue(o(f,v)),c})})}else{let a=this;return L(function(...d){let c=a._def.args.safeParse(d,s);if(!c.success)throw new V([r(d,c.error)]);let u=Reflect.apply(i,this,c.data),f=a._def.returns.safeParse(u,s);if(!f.success)throw new V([o(u,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:J.create(e).rest(re.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,n,r){return new t({args:e||J.create([]).rest(re.create()),returns:n||re.create(),typeName:T.ZodFunction,...b(r)})}},Ce=class extends E{get schema(){return this._def.getter()}_parse(e){let{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};Ce.create=(t,e)=>new Ce({getter:t,typeName:T.ZodLazy,...b(e)});var Ie=class extends E{_parse(e){if(e.data!==this._def.value){let n=this._getOrReturnCtx(e);return m(n,{received:n.data,code:p.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:e.data}}get value(){return this._def.value}};Ie.create=(t,e)=>new Ie({value:t,typeName:T.ZodLiteral,...b(e)});function To(t,e){return new ke({values:t,typeName:T.ZodEnum,...b(e)})}var ke=class t extends E{_parse(e){if(typeof e.data!="string"){let n=this._getOrReturnCtx(e),r=this._def.values;return m(n,{expected:C.joinValues(r),received:n.parsedType,code:p.invalid_type}),R}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let n=this._getOrReturnCtx(e),r=this._def.values;return m(n,{received:n.data,code:p.invalid_enum_value,options:r}),R}return L(e.data)}get options(){return this._def.values}get enum(){let e={};for(let n of this._def.values)e[n]=n;return e}get Values(){let e={};for(let n of this._def.values)e[n]=n;return e}get Enum(){let e={};for(let n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return t.create(e,{...this._def,...n})}exclude(e,n=this._def){return t.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};ke.create=To;var Oe=class extends E{_parse(e){let n=C.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==h.string&&r.parsedType!==h.number){let o=C.objectValues(n);return m(r,{expected:C.joinValues(o),received:r.parsedType,code:p.invalid_type}),R}if(this._cache||(this._cache=new Set(C.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=C.objectValues(n);return m(r,{received:r.data,code:p.invalid_enum_value,options:o}),R}return L(e.data)}get enum(){return this._def.values}};Oe.create=(t,e)=>new Oe({values:t,typeName:T.ZodNativeEnum,...b(e)});var pe=class extends E{unwrap(){return this._def.type}_parse(e){let{ctx:n}=this._processInputParams(e);if(n.parsedType!==h.promise&&n.common.async===!1)return m(n,{code:p.invalid_type,expected:h.promise,received:n.parsedType}),R;let r=n.parsedType===h.promise?n.data:Promise.resolve(n.data);return L(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};pe.create=(t,e)=>new pe({type:t,typeName:T.ZodPromise,...b(e)});var z=class extends E{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:n,ctx:r}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{m(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return R;let d=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return d.status==="aborted"?R:d.status==="dirty"?_e(d.value):n.value==="dirty"?_e(d.value):d});{if(n.value==="aborted")return R;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?R:a.status==="dirty"?_e(a.value):n.value==="dirty"?_e(a.value):a}}if(o.type==="refinement"){let i=a=>{let d=o.refinement(a,s);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?R:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?R:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ce(i))return R;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>ce(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):R);C.assertNever(o)}};z.create=(t,e,n)=>new z({schema:t,typeName:T.ZodEffects,effect:e,...b(n)});z.createWithPreprocess=(t,e,n)=>new z({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...b(n)});var W=class extends E{_parse(e){return this._getType(e)===h.undefined?L(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};W.create=(t,e)=>new W({innerType:t,typeName:T.ZodOptional,...b(e)});var X=class extends E{_parse(e){return this._getType(e)===h.null?L(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};X.create=(t,e)=>new X({innerType:t,typeName:T.ZodNullable,...b(e)});var we=class extends E{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return n.parsedType===h.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};we.create=(t,e)=>new we({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var De=class extends E{_parse(e){let{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return $e(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new V(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};De.create=(t,e)=>new De({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var He=class extends E{_parse(e){if(this._getType(e)!==h.nan){let r=this._getOrReturnCtx(e);return m(r,{code:p.invalid_type,expected:h.nan,received:r.parsedType}),R}return{status:"valid",value:e.data}}};He.create=t=>new He({typeName:T.ZodNaN,...b(t)});var sc=Symbol("zod_brand"),dt=class extends E{_parse(e){let{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ct=class t extends E{_parse(e){let{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?R:s.status==="dirty"?(n.dirty(),_e(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?R:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,n){return new t({in:e,out:n,typeName:T.ZodPipeline})}},Me=class extends E{_parse(e){let n=this._def.innerType._parse(e),r=o=>(ce(o)&&(o.value=Object.freeze(o.value)),o);return $e(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Me.create=(t,e)=>new Me({innerType:t,typeName:T.ZodReadonly,...b(e)});function ho(t,e){let n=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof n=="string"?{message:n}:n}function xo(t,e={},n){return t?le.create().superRefine((r,o)=>{let s=t(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=ho(e,r),d=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:d})}});if(!s){let i=ho(e,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):le.create()}var ic={object:K.lazycreate},T;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(T||(T={}));var ac=(t,e={message:`Input not instance of ${t.name}`})=>xo(n=>n instanceof t,e),bo=ue.create,Eo=Se.create,dc=He.create,cc=Re.create,vo=Te.create,uc=xe.create,lc=Ke.create,pc=be.create,fc=Ee.create,gc=le.create,mc=re.create,yc=Y.create,hc=Qe.create,_c=oe.create,Sc=K.create,Rc=K.strictCreate,Tc=ve.create,xc=Dt.create,bc=Ae.create,Ec=J.create,vc=Mt.create,Ac=Ge.create,Cc=We.create,Ic=Nt.create,kc=Ce.create,Oc=Ie.create,wc=ke.create,Dc=Oe.create,Mc=pe.create,Nc=z.create,Pc=W.create,Uc=X.create,jc=z.createWithPreprocess,Fc=ct.create,Lc=()=>bo().optional(),Bc=()=>Eo().optional(),$c=()=>vo().optional(),Vc={string:(t=>ue.create({...t,coerce:!0})),number:(t=>Se.create({...t,coerce:!0})),boolean:(t=>Te.create({...t,coerce:!0})),bigint:(t=>Re.create({...t,coerce:!0})),date:(t=>xe.create({...t,coerce:!0}))};var Kc=R;var ut="agenttrail.ingest.mode",lt="agenttrail.ingest.batch_id",Pt="backfill";var Ut=fe.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"must be a UUID"),Qc=fe.string().min(1).refine(t=>t.startsWith("dlv_"),{message:"AgentTrail API key must start with 'dlv_'"}),gy=fe.object({orgId:Ut,projectSlug:fe.string().min(1),projectId:Ut.optional(),agentId:Ut.optional(),developerId:Ut.optional(),apiKey:Qc.optional(),captureContent:fe.boolean().optional()}).strict();function Io(t,e){return kt(`${t}:${e}`,Wt)}var ko="agenttrail.org.id",Oo="agenttrail.project.id",wo="agenttrail.agent.id",Do="agenttrail.developer.id",Mo="agenttrail.project",No="gen_ai.conversation.id",Po="session.id",Uo="gen_ai.request.model",jo="llm_request.context",Fo="tool_name",Lo="gen_ai.tool.name",Bo="gen_ai.tool.call.id",En="gen_ai.usage.input_tokens",vn="gen_ai.usage.output_tokens",An="gen_ai.usage.cache_read.input_tokens",Cn="gen_ai.usage.cache_creation.input_tokens",Wc="interaction",Ao=1,Hc=3,zc=Object.freeze({[ko]:"metadata",[Oo]:"metadata",[wo]:"metadata",[pt]:"metadata",[Do]:"metadata",[Mo]:"metadata",[Ye]:"metadata",[ut]:"metadata",[lt]:"metadata",[Bt]:"metadata",[No]:"metadata",[Po]:"metadata",[Kt]:"metadata",[Uo]:"metadata",[jo]:"metadata",[$t]:"metadata",[En]:"metadata",[vn]:"metadata",[An]:"metadata",[Cn]:"metadata",[Fo]:"metadata",[Lo]:"metadata",[Lt]:"metadata",[Bo]:"metadata",[Qt]:"metadata",[Gt]:"metadata",[Vt]:"metadata",[st]:"content",[Z]:"content",[Le]:"content",[he]:"content"});function jt(t,e,n){let r=n==="import"?`import:${e.conversationId}:${e.importKey??e.importOrdinal??0}`:`live:${e.conversationId}:${e.generationId??""}`;return kt(r,t).replace(/-/g,"")}function ze(t,e){let n=typeof e=="string"?e:`tool:${e.tool}`;return Gc("sha256").update(`${t}:${n}`).digest("hex").slice(0,16)}function In(t){return t.correlationId??`ordinal:${t.ordinal}`}function kn(t,e){return ze(t,{tool:In(e)})}function Co(t){if(!Number.isFinite(t)||t<=0)return"0";let e=Math.floor(t),n=Math.round((t-e)*1e6);return(BigInt(e)*1000000n+BigInt(n)).toString()}function Yc(t,e,n){let r={...e};if(t.call.tool!==""&&(r[Fo]=t.call.tool,r[Lo]=t.call.tool),t.vendorTool!==""&&(r[Lt]=t.vendorTool),t.correlationId!==null&&(r[Bo]=t.correlationId),t.mcpServerUnknown===!0&&(r[Qt]="true"),t.pepBlocked===!0&&t.failed&&(r[Gt]="true"),t.subagentConversationId!==void 0&&(r[Vt]=t.subagentConversationId),n){let{full_command:o,file_path:s}=t.call.args;o!==void 0&&(r[Z]=o),s!==void 0&&(r[Le]=s),t.output!==void 0&&(r[he]=t.output)}return r}function Zc(t,e,n){let r=n.mode==="import",o=jt(t.traceNamespace,e,n.mode),s=ze(o,"root"),i=e.endMs,a=n.include,d=!r&&e.usage!==null&&e.model!==null,c={};e.conversationId!==""&&(c[No]=e.conversationId,c[Po]=e.conversationId);let u=r?{[Bt]:"true",[ut]:Pt,...n.batchId?{[lt]:n.batchId}:{}}:{},f=[];if(i!==null&&(a?.root??!0)){let y=e.closedBy??(r?"import":void 0);f.push({spanId:s,parentSpanId:"",name:t.rootSpanName,kind:Ao,startMs:e.startMs,endMs:i,attributes:{...c,...y!==void 0?{[Kt]:y}:{},...n.captureContent&&e.prompt?{[st]:e.prompt}:{},...d?{}:{[Ye]:"false"},...u},error:e.status==="error"})}!r&&i!==null&&e.model!==null&&(a?.model??!0)&&f.push({spanId:ze(o,"model"),parentSpanId:s,name:`chat ${e.model.name}`,kind:Hc,startMs:e.startMs,endMs:e.model.endMs,attributes:{...c,[Uo]:e.model.name,[jo]:Wc,[$t]:"true",...d&&e.usage!==null?t.usageAttributes(e.usage):{[Ye]:"false"}},error:!1});for(let y of e.tools){let v=y.endMs??i;v!==null&&(a?.toolKeys!==void 0&&!a.toolKeys.has(In(y))||f.push({spanId:kn(o,y),parentSpanId:y.parentTaskKey===void 0?s:ze(o,{tool:y.parentTaskKey}),name:y.call.tool===""?"execute_tool":`execute_tool ${y.call.tool}`,kind:Ao,startMs:y.startMs,endMs:v,attributes:{...Yc(y,c,n.captureContent),...u},error:y.failed}))}return f}function $o(t,e,n,r){let o=n.mode==="import",s=jt(t.traceNamespace,e,n.mode),i=n.resolvedScrubbers??null,a=0,d={},c=Zc(t,e,n).map(f=>{let y=Jr(f.attributes,i);a+=y.redactedCount;for(let[I,g]of Object.entries(y.byType))d[I]=(d[I]??0)+g;let v=y.attributes;return{traceId:s,spanId:f.spanId,parentSpanId:f.parentSpanId,name:f.name,kind:f.kind,startTimeUnixNano:Co(f.startMs),endTimeUnixNano:Co(Math.max(f.endMs,f.startMs)),attributes:v,error:f.error}});return{resource:{attributes:{[ko]:n.orgId,[Oo]:n.project.projectId,[wo]:r,[pt]:t.vendor,...n.project.developerId?{[Do]:n.project.developerId}:{},...n.project.projectLabel?{[Mo]:n.project.projectLabel}:{},[Ye]:o?"false":"true",...o?{[ut]:Pt}:{},...o&&n.batchId?{[lt]:n.batchId}:{}}},scope:{name:t.scopeName,version:n.scopeVersion},spans:c,redactions:{total:a,byType:d}}}function qc(t){return Io(t,Et)}var Jc="agenttrail-cursor";function wn(t,e){return jt(Ko.traceNamespace,{conversationId:t.conversationId,generationId:t.generationId,...t.importOrdinal!==void 0?{importOrdinal:t.importOrdinal}:{}},e)}function Xc(t){if(!("importKey"in t))return t;let{importKey:e,...n}=t;return n}function Dn(t,e){return ze(t,e)}function eu(t,e){return kn(t,e)}var On=new Set(["subagentStart","subagentStop"]),tu=new Set(["postToolUse","postToolUseFailure","afterFileEdit"]),nu=Object.freeze({conversationId:"",generationId:null,startMs:0,endMs:null,model:null,usage:null,tools:Object.freeze([])});function ru(t){if(t===null||typeof t!="object")return!1;let e=t;return e.kind==="capture"&&typeof e.capturedAtMs=="number"&&Number.isFinite(e.capturedAtMs)}function Mn(t){let e=t.tool?.durationMs;return e!==void 0&&Number.isFinite(e)&&e>=0?t.capturedAtMs-e:t.capturedAtMs}function ou(t,e){for(let n=t.length-1;n>=0;n-=1){let r=t[n];if(e(r))return r}}function su(t){let e=t.find(n=>n.event==="beforeSubmitPrompt"&&n.conversationId!==null);if(e?.conversationId)return e.conversationId;for(let n of t){if(!On.has(n.event))continue;let r=n.subagent?.parentConversationId??n.conversationId;if(r)return r}for(let n of["stop","afterAgentResponse"]){let r=ou(t,o=>o.event===n&&o.conversationId!==null);if(r?.conversationId)return r.conversationId}return t.find(n=>n.conversationId!==null)?.conversationId??""}function iu(t){switch(t){case"completed":return"success";case"aborted":return"aborted";case"error":return"error";default:return"unknown"}}function au(t,e,n){let r=t.tool;if(r?.mcpServerUnknown!==!0)return;let o=e.filter(a=>!n.has(a)&&a.tool?.vendorTool===r.vendorTool&&a.conversationId===t.conversationId&&a.generationId===t.generationId&&a.capturedAtMs<=t.capturedAtMs),s=o.filter(a=>r.durationMs!==void 0&&a.tool?.durationMs===r.durationMs),i;for(let a of s.length>0?s:o)(i===void 0||a.capturedAtMs>=i.capturedAtMs)&&(i=a);return i!==void 0&&n.add(i),i}function du(t,e,n,r){let o=t.tool,s=n?.tool,i=s===void 0?o.call:{tool:s.call.tool,args:s.call.args.full_command!==void 0?s.call.args:o.call.args},a=t.content?.output??t.content?.error;return{ordinal:e,vendorTool:o.vendorTool,call:i,correlationId:o.correlationId,startMs:Mn(t),endMs:t.capturedAtMs,failed:o.failed===!0,...a!==void 0?{output:a}:{},...s===void 0&&o.mcpServerUnknown===!0?{mcpServerUnknown:!0}:{},...o.pepBlocked===!0?{pepBlocked:!0}:{},isTask:!1,...r(t.conversationId)?{}:{foreignConversationId:t.conversationId},placedAtMs:t.capturedAtMs}}function cu(t,e,n){let{post:r,start:o,stop:s}=t,i=o??s,a=o?.capturedAtMs??(r!==void 0?Mn(r):s?.capturedAtMs??0),d=i?.subagent?.parentConversationId??i?.conversationId??null,c=r?.content?.output??r?.content?.error;return{ordinal:e,vendorTool:r?.tool?.vendorTool??"Task",call:r?.tool?.call??{tool:"Task",args:{}},correlationId:t.key,startMs:a,endMs:s?.capturedAtMs??r?.capturedAtMs??null,failed:r?.tool?.failed===!0||s?.status==="error",...c!==void 0?{output:c}:{},isTask:!0,...n(d)?{}:{foreignConversationId:d},placedAtMs:a}}function uu(t,e){let n;for(let r of e)r.ordinal>=t.ordinal||r.correlationId===null||r.startMs>t.placedAtMs||r.endMs!==null&&t.placedAtMs>r.endMs||(n===void 0||r.startMs>=n.startMs)&&(n=r);return n}function Vo(t,e){let n=t.map((l,S)=>({record:l,index:S})).filter(({record:l})=>ru(l)).sort((l,S)=>l.record.capturedAtMs-S.record.capturedAtMs||l.index-S.index).map(({record:l})=>l);if(n.length===0)return nu;let r=su(n),o=l=>l===null||l===r,s=n.find(l=>o(l.conversationId)&&!On.has(l.event)&&l.generationId!==null)?.generationId??null,i=wn({conversationId:r,generationId:s},"live"),a=l=>{let S=e?.get(l);return typeof S=="number"&&Number.isFinite(S)?S:void 0},d=[],c=new Map,u=l=>{let S=l===null?void 0:c.get(l);if(S!==void 0)return S;let M={key:l};return d.push(M),l!==null&&c.set(l,M),M};for(let l of n)if(tu.has(l.event)&&l.tool!==void 0){let S=u(l.tool.correlationId);S.post??=l}else if(On.has(l.event)){let S=l.subagent?.subagentId??null;if(S===null)continue;let M=u(S);l.event==="subagentStart"?M.start??=l:M.stop=l}let f=n.filter(l=>l.event==="afterMCPExecution"&&l.tool!==void 0),y=new Set,v=d.map((l,S)=>{let M=l.start!==void 0||l.stop!==void 0?cu(l,S,o):du(l.post,S,au(l.post,f,y),o),se=a(eu(i,M));return se===void 0?M:{...M,startMs:se}}),I=v.filter(l=>l.isTask),g=v.map(l=>{let S=l.foreignConversationId===void 0?void 0:uu(l,I);return{vendorTool:l.vendorTool,call:l.call,correlationId:l.correlationId,ordinal:l.ordinal,startMs:l.startMs,endMs:l.endMs,failed:l.failed,...l.output!==void 0?{output:l.output}:{},...l.mcpServerUnknown===!0?{mcpServerUnknown:!0}:{},...l.pepBlocked===!0?{pepBlocked:!0}:{},...l.foreignConversationId!==void 0?{subagentConversationId:l.foreignConversationId}:{},...S?.correlationId?{parentTaskKey:S.correlationId}:{}}}),x,A,k,D=Number.POSITIVE_INFINITY;for(let l of n)D=Math.min(D,Mn(l)),o(l.conversationId)&&(l.event==="beforeSubmitPrompt"?x??=l.content?.prompt:l.event==="afterAgentResponse"?A=l:l.event==="stop"&&(k=l));let O=A?.model??k?.model??null,w=A?.capturedAtMs??k?.capturedAtMs;return{conversationId:r,generationId:s,startMs:a(Dn(i,"root"))??D,endMs:k?.capturedAtMs??null,...k!==void 0?{closedBy:"stop",status:iu(k.status)}:{},...x!==void 0?{prompt:x}:{},model:O!==null&&w!==void 0?{name:O,endMs:w}:null,usage:k?.usage??null,tools:g}}function Ft(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):0}function lu(t){let e=Ft(t.cacheReadTokens),n=Ft(t.cacheWriteTokens);return{[En]:String(Math.max(0,Ft(t.inputTokens)-e-n)),[vn]:String(Ft(t.outputTokens)),[An]:String(e),[Cn]:String(n)}}var Ko={vendor:Et,scopeName:Jc,traceNamespace:Ht,rootSpanName:"invoke_agent Cursor",usageAttributes:lu};function Qo(t,e){return $o(Ko,Xc(t),e,qc(e.orgId))}function Go(t){return{conversationId:t.conversationId,generationId:t.generationId}}function Wo(t){return{conversationId:t.conversationId,generationId:t.generationId}}function Ho(t){return t.event==="beforeSubmitPrompt"}function zo(t){return t.event==="stop"}function Yo(t){if(!(t.event!=="subagentStart"&&t.event!=="subagentStop"))return{edge:t.event==="subagentStart"?"start":"stop",subagentId:t.subagent?.subagentId??null,parentConversationId:t.subagent?.parentConversationId??t.conversationId}}function Zo(t){return t==="postToolUse"||t==="postToolUseFailure"}var gu=2e3,mu={traceId:t=>wn(t,"live"),spanId:(t,e)=>Dn(t,e),assemble:t=>Vo(t),build:(t,e)=>Qo(t,e)};function yu(t,e,n=gu){let r=new Set(t.filter(o=>o.event==="afterMCPExecution").map(o=>`${o.generationId??""}\0${o.tool?.vendorTool??""}`));return t.filter(o=>{if(o.event!=="postToolUse")return!0;let s=o.tool;return s?.mcpServerUnknown!==!0||!s.vendorTool.startsWith(_n)||r.has(`${o.generationId??""}\0${s.vendorTool}`)?!0:e-o.capturedAtMs>=n})}function hu(t){if(t.cursorVersion!==null)return{version:t.cursorVersion,seenAtMs:t.capturedAtMs}}var _u={...Gr,versionKey:co,versionOf:hu,readRegistry:(t,e)=>ao(t,e),parseQueueEntry:t=>to(t),turnOf:Go,decisionTurnOf:Wo,opensTurn:Ho,closesTurn:zo,subagentOf:Yo,fillableEvent:Zo,holdBack:(t,e)=>yu(t,e)};function Su(t,e={}){return Kr(_u,t,e)}async function Ru(t,e,n){let r=ft({homeDir:t});return r===null?null:r.ingest_token!==e?r:Jt({lockPath:`${Ze(t,"cursor")}.lock`},async()=>{let o=ft({homeDir:t});if(o===null)return null;if(o.ingest_token!==e)return o;let s=o.api_endpoint;if(s===void 0)return null;try{let i={agent:"cursor",apiEndpoint:s,ingestEndpoint:o.endpoint,homeDir:t,host:o.host,device:Kn(t),log:()=>{}},a=Pn(i),d=await qt(s,o.refresh_token,n,a),c=Xt(i,d,{apiEndpoint:s,ingestEndpoint:o.endpoint});return Zt(t,c,{},"cursor"),Un(i,d,a),c}catch{return null}})}function Tu(t={}){let e=t.home??fu(),n=t.io??P;return{home:e,io:n,lockIO:et,now:()=>Date.now(),sleep:r=>new Promise(o=>setTimeout(o,r)),fetch:globalThis.fetch,builder:mu,pid:process.pid,limits:yn,credentials:()=>ft({homeDir:e}),refresh:r=>Ru(e,r),claimFile:(r,o)=>{try{return pu(r,o),!0}catch{return!1}},scopeVersion:Qr(e,ye,n)??"0.0.0",...t}}async function xu(t={}){try{await Su(Tu(t.deps??{}),t)}catch{}return 0}function bu(){return/flush\.(mjs|cjs|js)$/.test(process.argv[1]??"")}bu()&&xu().then(t=>{process.exitCode=t});export{yn as DEFAULT_SENDER_LIMITS,Fr as MAX_BODY_BYTES,gu as MCP_JOIN_WAIT_MS,_u as cursorSenderAdapter,hu as cursorVersionOf,yu as holdUnjoinedMcp,mu as liveTurnBuilder,Tu as realSenderDeps,Ru as refreshCursorToken,xu as runCursorSender,Su as runSender,Br as selectSpans,Lr as snapshotForState,hn as spanFingerprint,$r as splitSpanBatches};
1
+ var mi=Object.defineProperty;var gi=(e,t)=>{for(var n in t)mi(e,n,{get:t[n],enumerable:!0})};import{renameSync as Ap}from"fs";import{homedir as wp}from"os";import{mkdirSync as Oi,readFileSync as Ai,unlinkSync as af}from"fs";import{dirname as wi,join as un}from"path";import{randomBytes as _i}from"crypto";import{chmodSync as Si,lstatSync as Ri,mkdirSync as Jp,readFileSync as Zp,readlinkSync as Ei,realpathSync as xi,renameSync as bi,statSync as Ti,unlinkSync as Ci,writeFileSync as ki}from"fs";import{dirname as vi,join as ef,resolve as Ii}from"path";var cr=["claude-code","cursor","codex","replit-agent","devin","aider","windsurf","github-copilot"];function Rt(e){return typeof e=="string"&&cr.includes(e)}var Et="agenttrail.agent.vendor",en="agenttrail.tool.vendor_name";var Xe="agenttrail.usage.reported",tn="agenttrail.time.approximate",nn="agenttrail.span.synthetic",rn="agenttrail.subagent.conversation_id";var on="agenttrail.turn.closed_by";var sn="agenttrail.mcp.server_unknown",an="agenttrail.pep.blocked";var dn="7f050af4-796e-5b05-94c2-dba78bcdc7c2";var cn="7d12feb9-faf4-5d1a-b711-9362724c66b3";function de(e,t,n={}){let r=e,o=!0;try{r=xi(e)}catch{o=!1;let a=!0;for(let d=0;d<8;d++){let c;try{c=Ri(r).isSymbolicLink()}catch{a=!1;break}if(!c){a=!1;break}r=Ii(vi(r),Ei(r))}if(a){let d=new Error(`atomicWriteFileSync: too many symbolic links: ${e}`);throw d.code="ELOOP",d}}let s=n.mode;if(s===void 0&&o)try{s=Ti(r).mode&4095}catch{}let i=`${r}.tmp-${process.pid}-${_i(6).toString("hex")}`;try{ki(i,t,s!==void 0?{mode:s,encoding:"utf8"}:"utf8"),s!==void 0&&Si(i,s),bi(i,r)}catch(a){try{Ci(i)}catch{}throw a}}var Di=448;function he(e,t="claude"){switch(t){case"claude":return un(e,".agenttrail","credentials.json");case"cursor":return un(e,".agenttrail","cursor","credentials.json");case"codex":return un(e,".agenttrail","codex","credentials.json")}return Mi(t)}function Mi(e){throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(e)}.`)}function ln(e,t={},n="claude"){let r=t.readFile??(o=>Ai(o,"utf8"));try{let o=JSON.parse(r(he(e,n)));return Pi(o)?o:null}catch{return null}}function pn(e,t,n={},r="claude"){let o=he(e,r),s=n.writeFile??((a,d,c)=>de(a,d,c!==void 0?{mode:c}:{}));return(n.mkdir??((a,d)=>Oi(a,{recursive:!0,mode:d})))(wi(o),Di),s(o,`${JSON.stringify(t,null,2)}
2
+ `,384),o}function Pi(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.refresh_token=="string"&&typeof t.ingest_token=="string"&&typeof t.ingest_token_expires_at=="string"&&typeof t.org_id=="string"&&typeof t.host=="string"&&typeof t.endpoint=="string"&&(t.api_endpoint===void 0||typeof t.api_endpoint=="string")}import{closeSync as Ni,constants as fn,fchmodSync as Ui,fstatSync as Fi,openSync as ji}from"fs";import{dirname as Li,join as ur,relative as Bi,sep as $i}from"path";function Vi(e,t=process.getuid?.()){if(t===void 0)return;let n;try{n=ji(e,fn.O_RDONLY|fn.O_DIRECTORY|fn.O_NOFOLLOW);let r=Fi(n);if(!r.isDirectory()||r.uid!==t)return;let o=r.mode&4095;if((o&63)===0)return;Ui(n,o&-64)}catch{}finally{if(n!==void 0)try{Ni(n)}catch{}}}function Ki(e,t){let n=ur(e,".agenttrail"),r=Bi(n,Li(he(e,t))),o=[n];for(let s of r===""?[]:r.split($i))o.push(ur(o[o.length-1],s));return o}function mn(e,t,n=Vi){for(let r of Ki(e,t))n(r)}function lr(e){throw new Error(`AgentTrail has no path for the agent ${JSON.stringify(e)}.`)}var Hi=(e,t)=>fetch(e,t);function Qi(e,t){return`${e.replace(/\/$/,"")}${t}`}async function Gi(e,t,n){let r=await e(t,{method:"POST",headers:{"content-type":"application/json",accept:"application/json"},body:JSON.stringify(n)}),o=null;try{o=await r.json()}catch{o=null}return{status:r.status,ok:r.ok,data:o}}async function gn(e,t,n=Hi,r={}){let{ok:o,status:s,data:i}=await Gi(n,Qi(e,"/auth/device/refresh"),{...r,refresh_token:t});if(!o||!Wi(i)){let a=zi(i)?i.error:`HTTP ${s}`;throw new Error(`device/refresh failed: ${a}`)}return i}function Wi(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.ingest_token=="string"&&typeof t.refresh_token=="string"&&typeof t.expires_in=="number"&&typeof t.org_id=="string"}function zi(e){return typeof e!="object"||e===null?!1:typeof e.error=="string"}import{closeSync as Yi,openSync as qi,readFileSync as _f,rmSync as Ji,statSync as Zi,writeSync as Xi}from"fs";var ea=3e4,ta=(e,t)=>{let n=qi(e,"wx");try{Xi(n,t)}finally{Yi(n)}},na=e=>{try{Ji(e,{force:!0})}catch{}},ra=e=>{try{let t=Zi(e);return Date.now()-t.mtimeMs}catch{return null}};async function yn(e,t){let n=e.io??{},r=n.acquire??ta,o=n.release??na,s=n.age??ra,i=n.now??(()=>Date.now()),a=n.sleep??(g=>new Promise(R=>setTimeout(R,g))),d=e.staleMs??ea,c=e.timeoutMs??1e4,u=e.retryMs??50,l=i()+c;for(;;)try{r(e.lockPath,`${process.pid} ${new Date(i()).toISOString()}
3
+ `);break}catch{let g=s(e.lockPath);if(g!==null&&g>d){o(e.lockPath);continue}if(i()>=l)throw new Error(`could not acquire refresh lock (${e.lockPath}); another refresh is in progress.`);await a(u)}try{return await t()}finally{o(e.lockPath)}}var Af=1440*60*1e3;function pr(e,t={}){try{return e.device?.fields(e.agent,t)??{}}catch{return{}}}function fr(e,t,n,r=!1){try{e.device?.record(e.agent,t,n.device_name!==void 0?{typed:r}:void 0)}catch{}}function oa(e){switch(e){case"claude":case"cursor":case"codex":return!0}return lr(e)}function hn(e,t,n=e){return{refresh_token:t.refresh_token,ingest_token:t.ingest_token,ingest_token_expires_at:new Date((e.now?.()??Date.now())+t.expires_in*1e3).toISOString(),org_id:t.org_id,host:e.host,endpoint:n.ingestEndpoint,...t.org_tier?{org_tier:t.org_tier}:{},...oa(e.agent)?{api_endpoint:n.apiEndpoint}:{}}}function je(e){return ln(e.homeDir,e.credentialsIO,"cursor")}import{mkdirSync as Er,readFileSync as Ea}from"fs";import{dirname as xa,join as xr}from"path";var sa=["MacBook Pro","MacBook Air","Mac mini","iMac","Mac Studio","Mac Pro","Mac","Windows","Linux"];function xt(e){return typeof e=="string"&&sa.includes(e)}import{execFileSync as ia}from"child_process";var aa=(e,t,n)=>ia(e,[...t],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"],env:{PATH:"/usr/sbin:/usr/bin:/bin"}}),da=5e3,ca=1e3,ua={"Mac13,1":"Mac Studio","Mac13,2":"Mac Studio","Mac14,2":"MacBook Air","Mac14,3":"Mac mini","Mac14,5":"MacBook Pro","Mac14,6":"MacBook Pro","Mac14,7":"MacBook Pro","Mac14,8":"Mac Pro","Mac14,9":"MacBook Pro","Mac14,10":"MacBook Pro","Mac14,12":"Mac mini","Mac14,13":"Mac Studio","Mac14,14":"Mac Studio","Mac14,15":"MacBook Air","Mac15,3":"MacBook Pro","Mac15,4":"iMac","Mac15,5":"iMac","Mac15,6":"MacBook Pro","Mac15,7":"MacBook Pro","Mac15,8":"MacBook Pro","Mac15,9":"MacBook Pro","Mac15,10":"MacBook Pro","Mac15,11":"MacBook Pro","Mac15,12":"MacBook Air","Mac15,13":"MacBook Air","Mac15,14":"Mac Studio","Mac16,1":"MacBook Pro","Mac16,2":"iMac","Mac16,3":"iMac","Mac16,5":"MacBook Pro","Mac16,6":"MacBook Pro","Mac16,7":"MacBook Pro","Mac16,8":"MacBook Pro","Mac16,9":"Mac Studio","Mac16,10":"Mac mini","Mac16,11":"Mac mini","Mac16,12":"MacBook Air","Mac16,13":"MacBook Air"},la=[["MacBookPro","MacBook Pro"],["MacBookAir","MacBook Air"],["Macmini","Mac mini"],["MacPro","Mac Pro"],["iMac","iMac"]];function pa(e){let t=e.trim(),n=ua[t];if(n)return n;for(let[r,o]of la)if(t.startsWith(r)&&/^\d/.test(t.slice(r.length)))return o;return"Mac"}function fa(e){if(typeof e!="string")return"Mac";let t=e.trim();return xt(t)&&t!=="Windows"&&t!=="Linux"?t:"Mac"}var ma=["SPHardwareDataType","-json","-detailLevel","mini"];function ga(e){try{let n=JSON.parse(e)?.SPHardwareDataType,r=Array.isArray(n)?n[0]:void 0;return typeof r!="object"||r===null?void 0:{machine_name:r.machine_name}}catch{return}}function ya(e){try{let t=ga(e("/usr/sbin/system_profiler",ma,da));if(t===void 0)return;let n=fa(t.machine_name);return n==="Mac"?void 0:n}catch{return}}function ha(e){try{let t=pa(e("/usr/sbin/sysctl",["-n","hw.model"],ca));return t==="Mac"?void 0:t}catch{return}}function mr(e={}){let t=e.platform??process.platform,n=e.exec??aa;switch(t){case"darwin":return(e.thorough?ya(n):void 0)??ha(n)??"Mac";case"win32":return"Windows";case"linux":return"Linux";default:return}}import{randomUUID as gr}from"crypto";import{readFileSync as _a}from"fs";import{join as yr}from"path";var hr=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Sa(e){return yr(e,".agenttrail","machine-id")}function Ra(e){return yr(e,".agenttrail","installs.json")}function _r(e,t){try{return(e.readFile??(n=>_a(n,"utf8")))(t)}catch{return}}function Sr(e,t,n){(e.writeFile??((o,s,i)=>de(o,s,i!==void 0?{mode:i}:{})))(t,n,384)}function bt(e,t={}){let n=Sa(e),r=_r(t,n)?.trim();if(r&&hr.test(r))return r;let o=gr();return Sr(t,n,`${o}
4
+ `),o}function Rr(e,t,n={}){let r=Ra(e),o={},s=_r(n,r);if(s)try{let d=JSON.parse(s);typeof d=="object"&&d!==null&&!Array.isArray(d)&&(o=d)}catch{o={}}let i=o[t];if(typeof i=="string"&&hr.test(i))return i;let a=gr();return o[t]=a,Sr(n,r,`${JSON.stringify(o,null,2)}
5
+ `),a}function br(e){return xr(e,".agenttrail","device.json")}var Tr=["claude","cursor","codex"];function et(e,t={}){let n=t.readFile??(r=>Ea(r,"utf8"));try{let r=JSON.parse(n(br(e)));if(typeof r!="object"||r===null||Array.isArray(r))return{};let o=r,s=typeof o.device_name=="string"&&o.device_name!==""?o.device_name:null,i=Array.isArray(o.named)?Tr.filter(a=>o.named.includes(a)):[];return{...xt(o.device_model)?{device_model:o.device_model}:{},...s!==null?{device_name:s}:{},...s!==null&&o.name_chosen===!0?{name_chosen:!0}:{},...i.length>0?{named:i}:{}}}catch{return{}}}function _n(e,t,n={}){let r=br(e);try{(n.mkdir??((o,s)=>Er(o,{recursive:!0,mode:s})))(xa(r),448),(n.writeFile??((o,s,i)=>de(o,s,i!==void 0?{mode:i}:{})))(r,`${JSON.stringify(t,null,2)}
6
+ `,384)}catch{}}function ba(e,t,n,r){if(t.device_model&&!r)return t.device_model;let o=mr({thorough:r,exec:n.exec,platform:n.platform})??t.device_model;return o!==void 0&&o!==t.device_model&&_n(e,{...t,device_model:o},n),o}function Cr(e,t={}){return{fields(n,r={}){let o={};try{(t.mkdir??((s,i)=>Er(s,{recursive:!0,mode:i})))(xr(e,".agenttrail"),448),o.machine_id=bt(e,t)}catch{}try{let s=et(e,t);if(!r.exchange&&s.named?.includes(n))return o;if(s.name_chosen&&s.device_name)return o.device_name=s.device_name,o;let i=ba(e,s,t,r.thorough===!0);i!==void 0&&(o.device_model=i)}catch{}return o},record(n,r,o){try{let s=et(e,t),i=r.device_name_rejected===!0,a=typeof r.device_name=="string"?r.device_name:null,d;if(a!==null){let c=new Set([...s.named??[],n]),u=a===s.device_name&&s.name_chosen===!0,l=o!==void 0&&!i||u;d={...s.device_model?{device_model:s.device_model}:{},device_name:a,...l?{name_chosen:!0}:{},named:Tr.filter(g=>c.has(g))}}else{let c=s;if(o!==void 0&&i&&!o.typed){let{name_chosen:u,...l}=c;c=l}r.device_name===null&&c.named?.includes(n)&&(c={...c,named:c.named.filter(u=>u!==n)}),c!==s&&(d=c)}d!==void 0&&_n(e,d,t)}catch{}},name(){return et(e,t).device_name},confirmedName(n){let r=et(e,t);return r.named?.includes(n)?r.device_name:void 0},forget(n){try{let r=et(e,t);if(!r.named?.includes(n))return;_n(e,{...r,named:r.named.filter(o=>o!==n)},t)}catch{}}}}import{createHash as cc}from"crypto";var Ta=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ca=/[A-Z][a-z]{3,}|[a-z]{4,}|[A-Z]{4,}/g,ka=new Set("api app auth backend billing blue build canary checkout cluster controller default deploy deployment dev east frontend gateway green ingest ingress internal job main migration north prod production release replica rollout service south staging stage test web west worker".split(" "));function va(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 Ia(e){let t=0;for(let n of e.match(Ca)??[])t+=n.length;return t/e.replace(/[-_]/g,"").length>=.7}function Oa(e){let t=e.split(/[-_]/);return t.length<5||t.some(n=>n.length>12)?!1:t.filter(n=>ka.has(n.toLowerCase())).length>=3}function kr(e){return e.length<32||Ta.test(e)||/^sha(?:1|224|256|384|512)-/i.test(e)||Ia(e)||Oa(e)||/\d{8,}/.test(e)||e.split(/[-_]/).some(t=>t.length>=32&&/^[0-9a-fA-F]+$/.test(t))||/^[0-9a-fA-F]+$/.test(e)||!/[A-Za-z]/.test(e)||!/[0-9]/.test(e)?!1:va(e)>=4}var Aa=/^(?:mysql\w*|mariadb[\w-]*)$/i,Sn=/(?:^|[\s'"`(;|&/])(?:mysql\w*|mariadb[\w-]*)(?=$|[\s'"`);|&\\])/i,wa=/[\s,:}\]]/;function Da(e){let t=e[3],n=t==="\\"&&e[4]==='"'?e[5]:t==='"'||t==="'"?e[4]:void 0;return n!==void 0&&wa.test(n)}function Ma(e){return e.length===5?e.endsWith("''")||e.endsWith('""'):e.length===7&&e.endsWith('\\"\\"')}var vr=new RegExp(Sn.source,"gi"),Pa=/^[A-Za-z_]\w*=/,Na="\uE000",Ua=new Set(["then","do","else","elif","!","{","RUN","CMD","ENTRYPOINT"]),Fa=/^(?:[\w.-]+:|-|\*|\d+[.)]|[$%>#]|[\w.-]+@[\w.-]+:\S*[#$%>])$/,ja=new Map([["sudo",new Set(["-u","-g","-p","-C","-D","-r","-t","-U","--user","--group","--prompt","--chdir","--role","--type"])],["doas",new Set(["-u","-C"])],["env",new Set(["-u","-C","-S","--unset","--chdir","--split-string"])],["nice",new Set(["-n","--adjustment"])],["ionice",new Set(["-c","-n","-p","--class","--classdata"])],["stdbuf",new Set(["-i","-o","-e"])],["timeout",new Set(["-s","-k","--signal","--kill-after"])],["xargs",new Set(["-n","-I","-L","-P","-d","-s","-E","-a","--max-args","--replace","--max-procs","--delimiter","--arg-file"])],["nohup",new Set],["time",new Set(["-f","-o","--format","--output"])],["exec",new Set(["-a"])],["command",new Set],["watch",new Set(["-n","-d","--interval"])],["strace",new Set(["-o","-e","-p","-s"])],["chroot",new Set(["--userspec","--groups"])],["gosu",new Set],["su-exec",new Set],["eval",new Set],["npx",new Set(["-p","--package"])],["dotenv",new Set(["-e","-v","-p"])]]),La=new Set(["timeout","chroot","gosu","su-exec"]),Ir=new Set(["-u","-w","-e","--user","--workdir","--env","--env-file","--detach-keys"]),Ba=new Set([...Ir,"-a","-c","-h","-l","-m","-p","-v","--add-host","--annotation","--arch","--attach","--blkio-weight","--blkio-weight-device","--cap-add","--cap-drop","--cgroup-parent","--cgroupns","--cidfile","--cpu-period","--cpu-quota","--cpu-rt-period","--cpu-rt-runtime","--cpu-shares","--cpus","--cpuset-cpus","--cpuset-mems","--device","--device-cgroup-rule","--device-read-bps","--device-read-iops","--device-write-bps","--device-write-iops","--dns","--dns-option","--dns-search","--domainname","--entrypoint","--expose","--gpus","--gidmap","--group-add","--health-cmd","--health-interval","--health-retries","--health-start-interval","--health-start-period","--health-timeout","--hostname","--ip","--ip6","--ipc","--isolation","--kernel-memory","--label","--label-file","--link","--link-local-ip","--log-driver","--log-opt","--mac-address","--memory","--memory-reservation","--memory-swap","--memory-swappiness","--mount","--name","--net","--network","--network-alias","--oom-score-adj","--os","--pid","--pids-limit","--platform","--pod","--publish","--pull","--restart","--runtime","--secret","--security-opt","--shm-size","--stop-signal","--stop-timeout","--storage-opt","--sysctl","--tmpfs","--uidmap","--ulimit","--userns","--uts","--volume","--volume-driver","--volumes-from"]),$a=new Set(["-H","-c","-l","-n","-a","--host","--context","--config","--log-level","--tlscacert","--tlscert","--tlskey","--connection","--url","--identity","--root","--runroot","--storage-driver","--namespace","--address","--snapshotter"]),Va=new Set(["-f","-p","--file","--project-name","--project-directory","--env-file","--profile","--ansi","--progress","--parallel"]),Ka=new Set(["-u","-w","-e","-l","-v","-p","--user","--workdir","--env","--index","--label","--volume","--publish","--name","--entrypoint"]),Ha=new Set(["-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w","-B"]),Or=new Set([";","|","&","(",")","`",`
7
+ `,"\r","{","}"]);function Ar(e){let t=e.replace(/['"\\]/g,""),n=t.lastIndexOf("/");return(n===-1?t:t.slice(n+1)).toLowerCase()}function Qa(e,t){if(t.has(e))return!0;if(e.startsWith("--"))return!1;for(let n=1;n<e.length;n++)if(t.has(`-${e[n]}`))return n===e.length-1;return!1}function Le(e,t,n){let r=t;for(;r<e.length;){let o=e[r];if(o==="--")return r+1;if(!o.startsWith("-")||o==="-")return r;r+=Qa(o,n)?2:1}return r}function Ga(e,t,n){for(let r=t;r<n;r++){let o=e[r],s=o==="--entrypoint"?e[r+1]:o.startsWith("--entrypoint=")?o.slice(13):void 0;if(s!==void 0)return s.replace(/['"]/g,"")===""?null:s}return null}function Wa(e){let t=0,n=!0;for(let r=0;r<=e.length&&t<e.length;r++){let o=e[t];if(n&&Fa.test(o)){t++;continue}if(n=!1,Pa.test(o)||Ua.has(o)||o.includes(Na)){t++;continue}let s=Ar(o),i=ja.get(s);if(i){t=Le(e,t+1,i),La.has(s)&&t++;continue}let a=s==="docker"||s==="podman"||s==="nerdctl",d=a?Le(e,t+1,$a):t+1;if(a&&e[d]==="container"&&d++,s==="docker-compose"||a&&e[d]==="compose"){let c=Le(e,s==="docker-compose"?t+1:d+1,Va);if(e[c]!=="exec"&&e[c]!=="run")return o;t=Le(e,c+1,Ka)+1;continue}if(a&&(e[d]==="exec"||e[d]==="run")){let c=e[d]==="run",u=Le(e,d+1,c?Ba:Ir),l=c?Ga(e,d+1,u):null;if(l!==null)return l;t=u+1;continue}if(s==="kubectl"||s==="oc"){let c=e.indexOf("--",t),u=c===-1?[]:e.slice(t,c);if(!u.includes("exec")&&!u.includes("run")&&!u.includes("debug"))return null;t=c+1;continue}if(s==="ssh"){t=Le(e,t+1,Ha)+1;continue}return o}return null}function wr(e){let t=Wa(e);return t!==null&&Aa.test(Ar(t))}function za(e,t,n,r){for(let o=n;o+t.length<=r;o++)if(Dr(e,o)||e.startsWith(t,o)&&(t==='\\"'||e[o-1]!=="\\"))return o;return-1}function Dr(e,t){let n=e[t];return n===`
8
+ `||n==="\r"?!0:n==="\\"&&(e[t+1]==="n"||e[t+1]==="r")}function Ya(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===46||e===45}function qa(e,t,n){let r=e[t]==="\\",o=t+(r?2:1),s=o;for(;s<o+65&&s<n&&Ya(e.charCodeAt(s));)s++;if(s===o||s-o>64)return 0;if(r){if(e[s]!=="\\"||e[s+1]!=='"')return 0;s+=2}else{if(e[s]!=='"')return 0;s++}for(;s<n&&(e[s]===" "||e[s]===" ");)s++;return s<n&&e[s]===":"?s+1-t:0}function Ja(e,t,n){let r=Math.max(t,n-8),o=n-1;for(;o>=r&&(e[o]===" "||e[o]===" ");)o--;if(o<r)return!1;let s=e[o];if(s===":"||s===","||s==="["||s==="{")return!0;if(s!=="c")return!1;let i=o-1;for(;i>=r&&/[A-Za-z]/.test(e[i]);)i--;return i>=r&&e[i]==="-"&&(i===r||e[i-1]===" "||e[i-1]===" ")}function Za(e,t,n){let r=Math.max(n,t-64),o=t;for(;o>r&&e[o-1]!==" "&&e[o-1]!==" ";)o--;return o}var ce=null;function Xa(e,t){let n=Math.max(0,t-512),r,o,s,i,a,d;for(ce&&ce.text===e&&ce.i<=t&&ce.i>=n?{i:r,at:o,found:s,blank:i,inside:a,word:d}=ce:(r=n,o=n,s=n===0,i=!0,a=null,d=!1),ce=null;r<t;){let c=e[r],u=e[r+1];if(c==="\\"){if(u==="n"||u==="r"){o=r+2,s=!0,i=!0,a=null,r+=2;continue}if(u==="\\"){r+=e[r+2]==="\\"&&e[r+3]==="n"?4:2,i=!1;continue}if(u===`
9
+ `||u==="\r"){r+=2;continue}if(u==="u"&&e.startsWith("0026",r+2)){o=r+6,s=!0,i=!0,r+=6;continue}}let l=c==="\\"&&u==='"'?'\\"':c==='"'||c==="'"?c:null;if(l){let g=qa(e,r,t);if(g>0){r+=g,o=r,s=!0,i=!0,a=null;continue}let R=e[r+l.length];if(l===a&&d&&(R===" "||R===" ")){r+=l.length,i=!1,a=null;continue}if(l===a||!i&&(R===","||R==="]"||R==="}")){r+=l.length,o=r,s=!0,i=!0,a=null;continue}if(i||Ja(e,o,r)){r+=l.length,o=r,s=!0,i=!0,a=l,d=!0;continue}let T=za(e,l,r+l.length,t);if(T===-1)return ce={text:e,i:r,at:o,found:s,blank:i,inside:a,word:d},{start:Za(e,r,o),unsure:!0,inside:a};if(Dr(e,T)){r+=l.length,i=!1;continue}r=T+l.length,i=!1;continue}Or.has(c)?(o=r+1,s=!0,i=!0,d=!1,(c===`
10
+ `||c==="\r")&&(a=null)):c!==" "&&c!==" "?i=!1:d=!1,r++}return ce={text:e,i:r,at:o,found:s,blank:i,inside:a,word:d},s&&o>=n?{start:o,unsure:!1,inside:a}:{start:Math.max(n,t-210),unsure:!0,outside:!0,inside:null}}var H=null;function ed(e,t,n){for((!H||H.text!==e||H.end>n)&&(H={text:e,last:-1,next:-1,end:n}),H.end=n;H.next<n;){H.next!==-1&&(H.last=H.next),vr.lastIndex=H.next===-1?0:H.next+1;let r=vr.exec(e);H.next=r?r.index:Number.POSITIVE_INFINITY}return H.last>=t}function td(e,t){let n=t-1,r=e[n];if(r!==")"&&r!=="`")return!1;let o=-1;for(let d=n-1;d>=Math.max(0,n-64);d--)if(r===")"?e[d]==="("&&e[d-1]==="$":e[d]==="`"){o=d;break}if(o===-1)return!1;let s=r===")"?o-2:o-1,i=s-8;for(;s>=0&&s>i&&(e[s]===" "||e[s]===" ");)s--;let a=e[s];return s>=0&&!Or.has(a)&&a!=='"'&&a!=="'"?!1:Sn.test(e.slice(o+1,n))}function nd(e,t,n){let r=-1;if(n[0]==="[")r=t;else for(let s=t-1;s>=Math.max(0,t-512);s--){let i=e[s];if(i==="["){r=s;break}if(i==="]"||i===`
11
+ `)break}if(r===-1)return!1;let o=e.slice(r+1,t).split(",").map(s=>s.trim().replace(/["\\]/g,""));return wr(o)}function Mr(e,t,n){if(e[0]==="["||e[0]===",")return nd(n,t,e);if(Ma(e))return!1;let r=Xa(n,t);if(r.inside!==null&&e.startsWith(r.inside,3)||r.unsure&&Da(e))return!1;if(r.outside)return ed(n,r.start,t);let o=n.slice(r.start,t);if(r.unsure)return Sn.test(o);let s=o.trim().split(/\s+/);return wr(s)||td(n,r.start)}function N(e,t){return t?`[REDACTED:${e}:${t}]`:`[REDACTED:${e}]`}var En=String.raw`(?<=\\[nrtfb])|(?<=\\u[0-9A-Fa-f]{4})|(?<=\x1b\[[0-9;:?]{0,32}[@-~])|(?<=\\(?:u001[bB]|x1[bB]|033)\[[0-9;:?]{0,32}[@-~])|(?<=\x1b\([0-9A-Za-z])|(?<=\\(?:u001[bB]|x1[bB]|033)\([0-9A-Za-z])`,Ur=`(?:\\b|${En})`,xn=`(?:(?<![A-Za-z0-9_-])|${En})`,Fr=String.raw`(?<!\[REDACTED:)`,tt=String.raw`(?!["']?\[REDACTED:[a-z0-9:-]+\]["']?(?:[\s,;}\])]|$))`;function G(e,t){return new RegExp(`${Ur}${e}`,t)}var rd=G(String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,"g"),od=new RegExp(`((?:aws[_-]?)?secret[_-]?access[_-]?key)(["']?\\s*[=:]\\s*["']?)((?![0-9a-f]{40}(?![A-Za-z0-9/+=]))[A-Za-z0-9/+]{40})(?![A-Za-z0-9/+=])`,"gi"),sd=G(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),id=G(String.raw`(?:(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,255}\b|github_pat_[A-Za-z0-9_]{22,255}\b)`,"g"),ad=G(String.raw`xox[baprs]-[A-Za-z0-9-]{10,255}\b`,"g"),dd=G(String.raw`Bearer\s+([A-Za-z0-9._~+/-]{8,})=*`,"gi"),cd=G(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),ud=G(String.raw`eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b`,"g"),ld=/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]{0,8192}?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,pd=G(String.raw`(https?|ftp|wss?):\/\/[^\s/@:]+:[^\s]*@(?=[^\s/:@])`,"gi"),fd=(()=>{let t="([A-Z0-9_]*(?:PASSWORD|PASSWD|SECRET|TOKEN|API[_-]?KEY|APIKEY|ACCESS[_-]?KEY|PRIVATE[_-]?KEY|CLIENT[_-]?SECRET|AUTH[_-]?TOKEN|CREDENTIALS?)[A-Z0-9_]*)",n=`(?:(")([^"\uE000]{4,})"|(')([^'\uE000]{4,})'|([^\\s"',;\uE000]{4,}))`;return new RegExp(`${Ur}${Fr}${t}(["']?\\s*[=:]\\s*)${tt}${n}`,"gi")})(),$="\uE000",md=new RegExp(`${xn}${Fr}([A-Z0-9]+(?:_[A-Z0-9]+)*_KEY(?==|["']\\s*:)|(?![Ii]dempotency-)[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*-[Kk][Ee][Yy](?=["']?\\s*:))(["']?\\s*[=:]\\s*)${tt}(?!["']?[~.]{0,2}/)(?:(")([^"${$}]{4,})"|(')([^'${$}]{4,})'|([^\\s"',;${$}]{4,}))`,"g"),gd=new RegExp(`${xn}((?:Proxy-)?Authorization["']?\\s*[=:]\\s*["']?)((?:Basic|Token|Digest|Negotiate|ApiKey|Api-Key)\\s+)?(?!Bearer\\s)${tt}([^\\s"',;${$}]{8,})`,"gi"),Pr="(?:[Mm][Yy][Ss][Qq][Ll]|[Mm][Aa][Rr][Ii][Aa][Dd][Bb])",Rn=`[^\\s"'\`;|&)\\\\${$}]`,jr='(?:\\\\\\\\|\\\\(?!["\\\\]))',Lr=`${Rn}*(?:${jr}${Rn}*)*`,yd=`(?=${Rn}|${jr})${Lr}`,hd=`(?:'[^'\\n${$}]*'|\\$'(?:[^'\\\\\\n${$}]|\\\\[^\\n${$}]){0,1024}'|\\\\"[^"\\\\\\n${$}]*\\\\"|"[^"\\n${$}]*")`,_d=new RegExp(`(\\s-p)(?<=${Pr}(?:\\\\\\n|[^\\n]){0,200}\\s-p)${tt}(?:${hd}${Lr}|${yd})|([[,]\\s{0,8}\\\\?"-p)(?<=${Pr}[^\\n]{0,200}"-p)${tt}[^"\\\\\\n${$}]+(?=\\\\?")`,"g"),Sd=new RegExp([`${xn}([A-Za-z0-9_]*(?:ACCOUNT[_-]?ID|CF_ACCOUNT|CLOUDFLARE_ACCOUNT|AWS_ACCOUNT|GOOGLE_CLOUD_PROJECT|GCLOUD_PROJECT|GCP_PROJECT|CORE_PROJECT))(["']?\\s*[=:]\\s*)(["']?)([^\\s"',;<[${$}][^\\s"',;${$}]*)\\3`,`(--(?:account-id|account|owner-id|account-number))(=|\\s+)(["']?)(\\d{12}|[0-9a-f]{32})\\7(?![A-Za-z0-9])`,"(?<=\\barn:aws[a-z-]*:[a-z0-9-]*:[a-z0-9-]*:)\\d{12}(?![A-Za-z0-9])",`(?<=\\b(?:gcloud|gsutil|bq|firebase)\\b[^\\n;|&${$}]{0,200}?)(--project(?:_id|-id)?)(=|\\s+)(["']?)([a-z][a-z0-9-]{4,28}[a-z0-9])\\11(?![A-Za-z0-9-])`].join("|"),"gi"),Rd=new RegExp(`(?:(?<![A-Za-z0-9_+/.%-])|${En})(?<!==)(?<!sha(?:1|224|256|384|512)[-:])(?<!base64,)[A-Za-z0-9_-]{${32},}(?![A-Za-z0-9_+/=.%-])`,"g"),Ed=new RegExp(`[A-Za-z0-9_-]{${32}}`);function Tt(e,t,n,r){let o=n??"";return`${e}${t}${o}${r}${o}`}var xd=G(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`,"g"),bd=G(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`,"g"),Td=G(String.raw`(?:\d{13,19}\b|\d{3,6}([ -])\d{3,6}(?:\1\d{3,6}){1,3}\b)`,"g"),Cd=G(String.raw`(?:\+?\d{1,3}[ .-]?)?(?:\(\d{2,4}\)[ .-]?)?\d{2,4}[ .-]\d{2,4}[ .-]\d{2,4}\b`,"g"),Br=[{id:"aws-access-key-id",kind:"secret",category:"aws",severity:"high",tier:"permissive",regex:rd,placeholder:()=>N("secret:aws")},{id:"pem-private-key",kind:"secret",category:"private-key",severity:"high",tier:"permissive",regex:ld,placeholder:()=>N("secret:private-key")},{id:"jwt",kind:"secret",category:"jwt",severity:"high",tier:"permissive",regex:ud,placeholder:()=>N("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:id,placeholder:()=>N("secret:github")},{id:"slack-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:ad,placeholder:()=>N("secret:slack")},{id:"openai-key",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:sd,placeholder:()=>N("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:cd,placeholder:()=>N("secret:connection-string")},{id:"basic-auth-url",kind:"secret",category:"basic-auth",severity:"high",tier:"permissive",regex:pd,placeholder:e=>`${e[1].toLowerCase()}://${N("secret:basic-auth")}@`},{id:"bearer-token",kind:"secret",category:"token",severity:"medium",tier:"permissive",regex:dd,placeholder:()=>`Bearer ${N("secret:bearer")}`},{id:"aws-secret-access-key",kind:"secret",category:"aws",severity:"medium",tier:"standard",regex:od,placeholder:e=>`${e[1]}${e[2]}${N("secret:aws-secret")}`},{id:"env-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:fd,placeholder:e=>{let t=e[3]??e[5]??"";return`${e[1]}${e[2]}${t}${N("secret:env")}${t}`}},{id:"key-name-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:md,prefilter:/_KEY|-key/i,placeholder:e=>Tt(e[1]??"",e[2]??"",e[3]??e[5],N("secret:env"))},{id:"authorization-header",kind:"secret",category:"token",severity:"medium",tier:"standard",regex:gd,prefilter:/authorization/i,placeholder:e=>`${e[1]??""}${e[2]??""}${N("secret:auth")}`},{id:"mysql-password-flag",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:_d,prefilter:/mysql|mariadb/i,accept:Mr,placeholder:e=>`${e[1]??e[2]??""}${N("secret:password")}`},{id:"cloud-account-id",kind:"pii",category:"cloud-account",severity:"low",tier:"standard",regex:Sd,prefilter:/account|project|owner-id|arn:aws/i,placeholder:e=>{let t=N("pii:account");return e[1]!==void 0?Tt(e[1],e[2]??"",e[3],t):e[5]!==void 0?Tt(e[5],e[6]??"",e[7],t):e[9]!==void 0?Tt(e[9],e[10]??"",e[11],t):t}},{id:"generic-secret",kind:"secret",category:"generic",severity:"low",tier:"standard",regex:Rd,prefilter:Ed,accept:kr,placeholder:()=>N("secret:generic")},{id:"email",kind:"pii",category:"email",severity:"low",tier:"standard",regex:xd,placeholder:()=>N("pii:email")},{id:"ssn",kind:"pii",category:"ssn",severity:"high",tier:"standard",regex:bd,placeholder:()=>N("pii:ssn")},{id:"credit-card",kind:"pii",category:"credit-card",severity:"high",tier:"standard",regex:Td,placeholder:()=>N("pii:credit-card")},{id:"phone",kind:"pii",category:"phone",severity:"low",tier:"strict",regex:Cd,placeholder:()=>N("pii:phone")}],$r=new Set(["credit-card"]);function Vr(e){let t=e.replace(/\D/g,"");if(t.length<13||t.length>19)return!1;let n=0,r=!1;for(let o=t.length-1;o>=0;o--){let s=t.charCodeAt(o)-48;r&&(s*=2,s>9&&(s-=9)),n+=s,r=!r}return n%10===0}var kd={permissive:new Set(["permissive"]),standard:new Set(["permissive","standard"]),strict:new Set(["permissive","standard","strict"])},Be="\uE000",vd=new RegExp(`${Be}(\\d+)${Be}`,"g");function Kr(e){return`${Be}${e}${Be}`}function Id(e,t=!1){if(e==="off")return[];let n=kd[e];return Br.filter(r=>r.id==="phone"?n.has("strict")||t:n.has(r.tier))}function Od(e){if(!e||e.length===0)return[];let t=[];for(let n of e)try{t.push(new RegExp(n,"g"))}catch{}return t}function Ad(e,t,n,r){if(t.prefilter&&!t.prefilter.test(e))return e;let o=$r.has(t.id);return e.replace(t.regex,(...s)=>{let i=s[0];if(o&&!Vr(i)||t.accept&&!t.accept(i,s[s.length-2],s[s.length-1]))return i;let a=s.slice(0,s.length-2);n[t.id]=(n[t.id]??0)+1;let d=r.length;return r.push(t.placeholder(a)),Kr(d)})}function bn(e){return e.mode==="off"?null:{patterns:Id(e.mode,e.enablePhone),denylist:Od(e.denylistPatterns)}}function Hr(e,t){if(e.length===0)return{text:e,redactions:{},total:0};let{patterns:n,denylist:r}=t;return n.length===0&&r.length===0?{text:e,redactions:{},total:0}:wd(e,n,r)}function wd(e,t,n){let r={},o=[],s=e.includes(Be)?e.split(Be).join(""):e;for(let a of t)s=Ad(s,a,r,o);for(let a=0;a<n.length;a++)s=s.replace(n[a],()=>{r.custom=(r.custom??0)+1;let d=o.length;return o.push("[REDACTED:custom]"),Kr(d)});if(o.length===0)return{text:e,redactions:{},total:0};s=s.replace(vd,(a,d)=>o[Number(d)]);let i=0;for(let a in r)i+=r[a];return{text:s,redactions:r,total:i}}var Tn=["snapshot","none"],Cn=["allow","deny","require_approval"];var kn=["proceed","deny","ask"],vn=["pdp_refused","no_snapshot","credential_rejected","config_blank","misconfigured","hold_unavailable","watchdog"],In=["no_snapshot","hold_unavailable"],On=["timeout","unreachable","config_unavailable","evaluator_crash","rejected_request","waf_403","parse_error"];var nt={maxOutcomes:500,maxDropDays:31,maxDropCount:1e5,maxAgeDays:30,maxFutureMinutes:5,clientDropRetentionDays:29};var Qr="pubsub:sse:org:",Dd=`${Qr}*`;var Ct={mode:"standard"};function Gr(e){return Object.entries(e).map(([t,n])=>({key:t,value:{stringValue:n}}))}function kt(e){return{resourceSpans:(Array.isArray(e)?e:[e]).map(n=>({resource:{attributes:Gr(n.resource.attributes)},scopeSpans:[{scope:{name:n.scope.name,version:n.scope.version},spans:n.spans.map(r=>{let o={traceId:r.traceId,spanId:r.spanId,parentSpanId:r.parentSpanId,name:r.name,kind:r.kind,startTimeUnixNano:r.startTimeUnixNano,endTimeUnixNano:r.endTimeUnixNano,attributes:Gr(r.attributes)};return r.error&&(o.status={code:2}),o})}]}))}}var Md=e=>new Promise(t=>setTimeout(t,e));function Pd(e){let t=e.get("retry-after");if(!t)return null;let n=Number(t);return Number.isFinite(n)&&n>=0?n*1e3:null}async function zr(e,t,n={}){if(t.dryRun)return{status:"skipped",attempts:0};let r=n.fetch??globalThis.fetch,o=n.sleep??Md,s=t.maxRetries??5,i=t.baseBackoffMs??500,a=`${t.endpoint.replace(/\/$/,"")}/v1/traces`,d=JSON.stringify(e),c=0,u="",l;for(;c<=s;){c++;let g;try{g=await r(a,{method:"POST",headers:{"content-type":"application/json",authorization:`Bearer ${t.token}`},body:d})}catch(T){if(u=T.message,l=void 0,c>s)break;await o(Wr(i,c,null));continue}if(l=g.status,g.ok)return{status:"ok",httpStatus:g.status,attempts:c};if(!(g.status===429||g.status>=500&&g.status<=599)||c>s){u=`HTTP ${g.status}: ${(await g.text().catch(()=>"")).slice(0,200)}`;break}await o(Wr(i,c,Pd(g.headers)))}return{status:"failed",httpStatus:l,attempts:c,error:u}}function Wr(e,t,n){if(n!==null)return n;let r=e*2**(t-1),o=Math.floor(Math.random()*e);return Math.min(r+o,3e4)}function Yr(e,t,n){if(t.length===0)return{records:e,filledToolUseId:0};let r=d=>{if(!n.fillableEvent(d.event))return!1;let c=d.tool;return c!==void 0&&c.correlationId===null},o=(d,c)=>{let u=c.tool;if(u===void 0)return!1;let l=n.decisionTurnOf(d),g=n.turnOf(c);return d.toolUseId!==null&&d.toolUseId!==""&&l.conversationId===g.conversationId&&l.generationId===g.generationId&&d.vendorTool===u.vendorTool&&d.argsHash===u.argsHash&&d.decidedAtMs<=c.capturedAtMs},s=new Set,i=0,a=e.map(d=>{if(!r(d))return d;let c;if(t.forEach((l,g)=>{s.has(g)||!o(l,d)||(c===void 0||l.decidedAtMs>c.decision.decidedAtMs)&&(c={index:g,decision:l})}),c===void 0)return d;s.add(c.index),i+=1;let u=d.tool;return{...d,tool:{...u,correlationId:c.decision.toolUseId}}});return{records:Nd(a,t,n),filledToolUseId:i}}function Nd(e,t,n){let r=t.filter(o=>o.blocked&&o.toolUseId!==null&&o.toolUseId!=="");return r.length===0?e:e.map(o=>{let s=o.tool;if(s===void 0||s.failed!==!0||!n.fillableEvent(o.event)||s.correlationId===null)return o;let i=n.turnOf(o);return r.some(d=>{let c=n.decisionTurnOf(d);return d.toolUseId===s.correlationId&&c.conversationId===i.conversationId&&c.generationId===i.generationId&&d.decidedAtMs<=o.capturedAtMs})?{...o,tool:{...s,pepBlocked:!0}}:o})}import{appendFileSync as Bg}from"fs";import{chmodSync as Ud,existsSync as Fd,mkdirSync as qr,readdirSync as jd,readFileSync as Ld,renameSync as Bd,rmSync as Jr,writeFileSync as $d}from"fs";import{basename as Vd,dirname as Xr,join as Kd}from"path";var rt=448,Q=384,Zr=0;function eo(e,t=process.pid){return Zr+=1,Kd(Xr(e),`.${Vd(e)}.${t}.${Zr}.tmp`)}var O={readFile(e){return Ld(e)},writeFileAtomic(e,t,n){qr(Xr(e),{recursive:!0,mode:rt});let r=eo(e);try{$d(r,t,{mode:n}),Ud(r,n),Bd(r,e)}catch(o){throw Jr(r,{force:!0}),o}},mkdirp(e,t){qr(e,{recursive:!0,mode:t})},remove(e){Jr(e,{recursive:!0,force:!0})},exists(e){return Fd(e)},readdir(e){return jd(e).sort()}};var An=".dropped",Hd="c";function to(e){return e===Hd?"queue-full":`mark-${e}`}import{createHash as Hg}from"crypto";import{join as F}from"path";function U(e,t){let n=F(e,".agenttrail",t),r=F(n,"runtime");return{root:n,credentials:F(n,"credentials.json"),install:F(n,"install.json"),projects:F(n,"projects.json"),runtime:r,captureHook:F(r,"capture-hook.mjs"),flush:F(r,"flush.mjs"),queueKey:F(n,"queue.key"),enforcement:F(n,"enforcement.json"),pepSnapshot:F(n,"pep-snapshot.json"),queue:F(n,"queue"),turns:F(n,"turns"),senderLock:F(n,"sender.lock"),senderState:F(n,"sender-state.json"),backfillState:F(n,"backfill-state.json")}}function ot(e,t,n){return F(U(e,t).queue,n)}function vt(e,t,n){return F(U(e,t).turns,`${n}.json`)}import{randomBytes as Qd}from"crypto";import{closeSync as Gd,openSync as Wd,readFileSync as zd,rmSync as Yd,statSync as qd,utimesSync as Jd,writeSync as Zd}from"fs";var no=5e3,wn=2e4,st={acquire(e,t){let n=Wd(e,"wx",384);try{Zd(n,t)}finally{Gd(n)}},release(e){try{Yd(e,{force:!0})}catch{}},age(e){try{return Date.now()-qd(e).mtimeMs}catch{return null}},read(e){try{return zd(e,"utf8")}catch{return null}},touch(e){try{let t=new Date;Jd(e,t,t)}catch{}},now:()=>Date.now()};function ro(e,t=st){let n=t.age(e);return n!==null&&n<=wn&&n>=-wn}function Xd(e,t){return`${e} ${new Date(t).toISOString()} ${Qd(8).toString("hex")}
12
+ `}function It(e,t=st,n=process.pid){let r=Xd(n,t.now()),o=()=>{try{return t.acquire(e,r),!0}catch{return!1}};if(!o()&&(ro(e,t)||(t.release(e),!o())))return;let s=t.now();return{token:r,owned:()=>t.read(e)===r,heartbeat(){let i=t.now();return i-s<no?!0:(s=i,t.read(e)!==r?!1:(t.touch(e),!0))},release(){t.read(e)===r&&t.release(e)}}}var it=Object.freeze({v:1,dropped:Object.freeze({}),unknownKinds:Object.freeze({}),pepDecisions:Object.freeze({seen:0,filledToolUseId:0,orphaned:0}),projects:Object.freeze({})});function at(){return{dropped:{},unknownKinds:{},pepDecisions:{seen:0,filledToolUseId:0,orphaned:0},projects:{}}}function Pn(e){return e.lastUploadAtMs===void 0&&e.lastError===void 0&&Object.keys(e.dropped).length===0&&Object.keys(e.unknownKinds).length===0&&e.pepDecisions.seen===0&&e.pepDecisions.filledToolUseId===0&&e.pepDecisions.orphaned===0&&Object.keys(e.projects).length===0}function Se(e,t){e[t]=(e[t]??0)+1}function dt(e,t){let n=e.projects[t];if(n!==void 0)return n;let r={dropped:{}};return e.projects[t]=r,r}function _e(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Dn(e){if(!_e(e))return{};let t={};for(let[n,r]of Object.entries(e))typeof r=="number"&&Number.isFinite(r)&&r>=0&&(t[n]=r);return t}function oo(e){if(!_e(e))return;let{version:t,seenAtMs:n}=e;if(!(typeof t!="string"||t==="")&&!(typeof n!="number"||!Number.isFinite(n)))return{version:t,seenAtMs:n}}function $e(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function At(e,t){return t!==void 0?{[e]:t}:{}}function Ot(e,t){return e===void 0?void 0:e[t]}function ao(e,t){if(e===void 0)return it;let n;try{n=JSON.parse(e)}catch{return it}if(!_e(n)||n.v!==1)return it;let r=_e(n.pepDecisions)?n.pepDecisions:{},o={};if(_e(n.projects))for(let[c,u]of Object.entries(n.projects)){if(!_e(u))continue;let l=oo(u[t]),g=$e(u.lastUploadAtMs);o[c]={...At(t,l),...g!==void 0?{lastUploadAtMs:g}:{},dropped:Dn(u.dropped)}}let s=_e(n.lastError)?n.lastError:void 0,i=$e(s?.atMs),a=oo(n[t]),d=$e(n.lastUploadAtMs);return{v:1,...d!==void 0?{lastUploadAtMs:d}:{},...i!==void 0&&typeof s?.message=="string"?{lastError:{atMs:i,message:s.message}}:{},dropped:Dn(n.dropped),unknownKinds:Dn(n.unknownKinds),pepDecisions:{seen:$e(r.seen)??0,filledToolUseId:$e(r.filledToolUseId)??0,orphaned:$e(r.orphaned)??0},...At(t,a),projects:o}}function co(e){return`${JSON.stringify(e)}
13
+ `}function Nn(e,t,n,r=O){try{return ao(r.readFile(U(e,t).senderState).toString("utf8"),n)}catch{return it}}function Un(e,t,n,r=O){r.writeFileAtomic(U(e,t).senderState,co(n),Q)}function Mn(e,t){let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function so(e,t){return t===void 0?e:e===void 0||t.seenAtMs>=e.seenAtMs?t:e}function io(e,t){return t===void 0?e:e===void 0?t:Math.max(e,t)}function Fn(e,t,n){let r={...e.projects};for(let[a,d]of Object.entries(t.projects)){let c=r[a]??{},u=so(Ot(c,n),Ot(d,n)),l=io(c.lastUploadAtMs,d.lastUploadAtMs);r[a]={...At(n,u),...l!==void 0?{lastUploadAtMs:l}:{},dropped:Mn(c.dropped??{},d.dropped)}}let o=Object.values(t.projects).reduce((a,d)=>so(a,Ot(d,n)),Ot(e,n)),s=io(e.lastUploadAtMs,t.lastUploadAtMs),i=t.lastError??e.lastError;return{v:1,...s!==void 0?{lastUploadAtMs:s}:{},...i!==void 0?{lastError:i}:{},dropped:Mn(e.dropped,t.dropped),unknownKinds:Mn(e.unknownKinds,t.unknownKinds),pepDecisions:{seen:e.pepDecisions.seen+t.pepDecisions.seen,filledToolUseId:e.pepDecisions.filledToolUseId+t.pepDecisions.filledToolUseId,orphaned:e.pepDecisions.orphaned+t.pepDecisions.orphaned},...At(n,o),projects:r}}var ec=600*1e3,wt=600*1e3,po=1440*60*1e3,tc={idleSweepMs:ec,orphanWindowMs:wt,retentionMs:po};function ue(e,t){return`${e}\0${t??""}`}function nc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rc(e){let t;try{t=JSON.parse(e)}catch{return}if(!(!nc(t)||t.v!==1)&&!(typeof t.traceId!="string"||typeof t.projectKey!="string")&&typeof t.conversationId=="string"&&!(typeof t.lastRecordAtMs!="number"||!Number.isFinite(t.lastRecordAtMs))&&!(!Array.isArray(t.files)||!t.files.every(n=>typeof n=="string")))return t}function oc(e){return`${JSON.stringify(e)}
14
+ `}function fo(e,t,n=O){let r=U(e,t).turns,o;try{o=n.readdir(r)}catch{return{states:[],unreadable:[]}}let s=[],i=[];for(let a of o){if(!a.endsWith(".json"))continue;let d=`${r}/${a}`,c;try{c=rc(n.readFile(d).toString("utf8"))}catch{c=void 0}c===void 0?i.push(d):s.push(c)}return{states:s,unreadable:i}}function ct(e,t,n,r=O){r.writeFileAtomic(vt(e,t,n.traceId),oc(n),Q)}function jn(e,t,n,r=O){r.remove(vt(e,t,n))}function sc(e){let t=/^(\d+)-(\d+)-(\d+)\.json$/.exec(e);if(t!==null)return{atMs:Number(t[1]),pid:Number(t[2]),seq:Number(t[3])}}function ic(e){return[...e].sort((t,n)=>t.atMs-n.atMs||t.pid-n.pid||t.seq-n.seq||t.name.localeCompare(n.name))}function mo(e,t,n=O,r,o=""){let s;try{s=n.readdir(e)}catch{return{files:[],other:[]}}let i=[],a=[];for(let d of s){let c=sc(d);if(c===void 0){a.push(d);continue}let u=o===""?d:`${o}/${d}`,l=r?.get(u);if(l!==void 0){i.push(l);continue}let g;try{g=t(n.readFile(`${e}/${d}`).toString("utf8"))}catch{g=void 0}let R={name:d,...c,entry:g};r?.set(u,R),i.push(R)}return{files:ic(i),other:a}}function ac(e,t,n,r,o){return{v:1,traceId:t,projectKey:e,conversationId:n,generationId:r,files:[],starts:{},sent:{},lastRecordAtMs:o}}function Re(e){return e.records.reduce((t,n)=>Math.max(t,n.capturedAtMs),e.loaded.lastRecordAtMs)}function go(e,t){return e.records.find(n=>{if(!t.closesTurn(n))return!1;let r=t.turnOf(n);return r.conversationId!==null&&ue(r.conversationId,r.generationId)===e.key})}function uo(e,t,n){let r=go(e,n);if(r!==void 0&&r.capturedAtMs<t)return!1;let o=e.loaded.closed;return o!==void 0&&o.atMs<t&&r===void 0?Re(e)>o.atMs:!0}function yo(e){let t=e.rules,n={...tc,...e.limits},r=[],o=new Map,s=new Set,i=[],a=[],d=[],c=new Map(e.files.map(m=>[m.name,m]));for(let m of e.states){if(m.projectKey!==e.projectKey)continue;let E={key:ue(m.conversationId,m.generationId),loaded:m,records:[],decisions:[],files:[]};r.push(E),o.set(E.key,E)}let u=(m,E)=>{s.add(E.name),m.files.push(E.name);let k=E.entry;k!==void 0&&(k.kind==="capture"?m.records.push(k):k.kind==="pep-decision"&&m.decisions.push(k))};for(let m of r)for(let E of m.loaded.files){let k=c.get(E);k!==void 0&&u(m,k)}for(let m of r)for(let E of m.records)lo(d,m,E,t);let l=(m,E)=>r.filter(k=>k.loaded.conversationId===m&&uo(k,E,t)).sort((k,D)=>Re(k)-Re(D)).at(-1),g=m=>d.filter(E=>E.startAtMs<=m&&(E.stopAtMs===void 0||m<=E.stopAtMs)).sort((E,k)=>E.startAtMs-k.startAtMs).at(-1),R=(m,E)=>{let k=r.filter(D=>uo(D,m.atMs,t)&&Math.abs(m.atMs-Re(D))<=n.orphanWindowMs).sort((D,A)=>Re(D)-Re(A)).at(-1);if(k!==void 0){u(k,m);return}e.nowMs-m.atMs>=n.orphanWindowMs?a.push({file:m,reason:E}):i.push(m)};for(let m of e.files){if(s.has(m.name))continue;let E=m.entry;if(E===void 0){a.push({file:m,reason:"unreadable"});continue}if(E.kind==="unknown"){e.nowMs-m.atMs>=n.orphanWindowMs?a.push({file:m,reason:"unknown-kind"}):i.push(m);continue}if(E.kind==="pep-decision"){let w=t.decisionTurnOf(E),M=w.conversationId===null?void 0:o.get(ue(w.conversationId,w.generationId));M!==void 0?u(M,m):e.nowMs-m.atMs>=n.orphanWindowMs?a.push({file:m,reason:"decision-orphan"}):i.push(m);continue}let k=E,D=t.subagentOf(k);if(D!==void 0){let w=D.parentConversationId,M=w===null?void 0:l(w,k.capturedAtMs);if(M===void 0){R(m,"orphan");continue}u(M,m),lo(d,M,k,t);continue}let A=t.turnOf(k);if(A.conversationId!==null){let w=o.get(ue(A.conversationId,A.generationId));if(w!==void 0){u(w,m);continue}if(t.opensTurn(k)){let p=e.traceIdFor({conversationId:A.conversationId,generationId:A.generationId}),S={key:ue(A.conversationId,A.generationId),loaded:ac(e.projectKey,p,A.conversationId,A.generationId,k.capturedAtMs),records:[],decisions:[],files:[]};r.push(S),o.set(S.key,S),u(S,m);continue}let M=g(k.capturedAtMs);if(M!==void 0){u(M.builder,m);continue}}R(m,"orphan")}return{turns:r.filter(m=>m.files.length>0||m.loaded.files.length>0).map(m=>dc(m,e.nowMs,n,t)),pending:i,dropped:a,expired:[]}}function lo(e,t,n,r){let o=r.subagentOf(n);if(o===void 0)return;if(o.edge==="start"){e.push({builder:t,subagentId:o.subagentId,startAtMs:n.capturedAtMs});return}let s=e.find(i=>i.builder===t&&i.subagentId===o.subagentId);s!==void 0&&(s.stopAtMs=n.capturedAtMs)}function dc(e,t,n,r){let o=[...e.records].sort((c,u)=>c.capturedAtMs-u.capturedAtMs),s=Re(e),i=go(e,r),a;i!==void 0?a={atMs:i.capturedAtMs,by:"stop"}:t-s>=n.idleSweepMs?a={atMs:s,by:"idle-sweep"}:e.loaded.closed!==void 0&&s<=e.loaded.closed.atMs&&(a=e.loaded.closed);let d={...e.loaded,files:[...e.files].sort(),lastRecordAtMs:s,...a!==void 0?{closed:a}:{}};return a===void 0&&"closed"in d&&delete d.closed,{state:d,records:o,decisions:e.decisions,files:d.files}}function ho(e,t,n=po){return e.filter(r=>r.files.length===0&&r.closed!==void 0&&t-r.lastRecordAtMs>=n)}var Ro=35e5,uc=new Set([400,413,422]),Ln={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function Bn(e){return cc("sha256").update(JSON.stringify([e.spanId,e.parentSpanId,e.name,e.kind,e.startTimeUnixNano,e.endTimeUnixNano,e.error,Object.entries(e.attributes).sort()]),"utf8").digest("hex").slice(0,16)}function Eo(e,t){let n=t.closed;return n===void 0?{...e,endMs:null}:n.by==="stop"?{...e,endMs:e.endMs??n.atMs,closedBy:"stop"}:{...e,endMs:e.endMs??n.atMs,closedBy:n.by,status:e.status??"unknown"}}function xo(e,t,n){let r={},o=[];for(let s of e){if(n.has(s.spanId))continue;let i=t.starts[s.spanId],a=i===void 0||i===s.startTimeUnixNano?s:{...s,startTimeUnixNano:i,endTimeUnixNano:BigInt(s.endTimeUnixNano)<BigInt(i)?i:s.endTimeUnixNano},d=t.sent[a.spanId];d!==Bn(a)&&d?.startsWith("dropped:")!==!0&&(o.push(a),r[a.spanId]=a.startTimeUnixNano)}return{spans:o,starts:r}}function bo(e,t,n=Ro){let r=[],o=[];for(let s of t){let i=[...o,s];if(Buffer.byteLength(JSON.stringify(kt({...e,spans:i})),"utf8")>n&&o.length>0){r.push(o),o=[s];continue}o=i}return o.length>0&&r.push(o),r}function Dt(e,t,n){Se(e.totals.dropped,n),Se(e.report,n),t!==void 0&&Se(dt(e.totals,t).dropped,n)}async function lc(e,t,n){let r=async()=>(t.posts+=1,zr(n,{endpoint:t.credentials.endpoint,token:t.credentials.ingest_token,maxRetries:2},{fetch:e.fetch,sleep:e.sleep})),o=await r();if(o.status==="failed"&&o.httpStatus===401){let s=await e.refresh(t.credentials.ingest_token);if(s===null)return{ok:!1,status:401,error:"not signed in"};t.credentials=s,o=await r()}return o.status==="ok"?{ok:!0,status:o.httpStatus}:{ok:!1,...o.httpStatus!==void 0?{status:o.httpStatus}:{},...o.error!==void 0?{error:o.error}:{}}}function pc(e,t,n,r){if(n.length===t.length)return!1;let o=new Set(n),s=ue(r.conversationId,r.generationId);return t.some(i=>{if(o.has(i)||!e.closesTurn(i))return!1;let a=e.turnOf(i);return a.conversationId!==null&&ue(a.conversationId,a.generationId)===s})}function fc(e){let{closed:t,...n}=e;return n}async function mc(e,t,n){let{adapter:r,deps:o,mem:s}=e,i=o.now(),a=Yr(n.records,n.decisions,r),d=r.holdBack(a.records,i),c=d.length!==a.records.length,u=n.state,l=pc(r,a.records,d,u)?fc(u):u,g=l.closed===void 0;if(d.length===0)return u.closed===void 0||c?{state:u,sent:0,drained:!1,open:g}:_o(e,t.project.orgId,u,n,a.filledToolUseId);let R=Eo(o.builder.assemble(d,void 0,n.decisions),l);if(l.closed!==void 0&&r.usageOf!==void 0){let w=r.usageOf({conversationId:u.conversationId,generationId:u.generationId},{home:o.home,env:o.env??process.env,io:o.io});w!==null&&(R={...R,usage:w})}let T=o.builder.build(R,{orgId:t.credentials.org_id,project:{projectId:t.project.projectId,projectLabel:t.project.projectLabel,...t.project.developerId!==void 0?{developerId:t.project.developerId}:{}},captureContent:t.project.captureContent,mode:"live",scopeVersion:o.scopeVersion,resolvedScrubbers:s.scrubbers}),m=new Set;g&&(m.add(o.builder.spanId(u.traceId,"root")),m.add(o.builder.spanId(u.traceId,"model")));let{spans:E,starts:k}=xo(T.spans,u,m),D=0;for(let w of bo(T,E)){let M=await lc(o,t,kt({...T,spans:w}));if(M.ok){let p={...u.sent},S={...u.starts};for(let ae of w)p[ae.spanId]=Bn(ae),S[ae.spanId]=k[ae.spanId]??ae.startTimeUnixNano;u={...u,sent:p,starts:S},D+=w.length;let P=o.now();s.totals.lastUploadAtMs=P,dt(s.totals,t.project.projectKey).lastUploadAtMs=P,ct(o.home,r.stateDir,u,o.io);continue}if(M.status!==void 0&&uc.has(M.status)){let p={...u.sent};for(let S of w)p[S.spanId]=`dropped:${M.status}`,Dt(s,t.project.projectKey,`rejected-${M.status}`);u={...u,sent:p},ct(o.home,r.stateDir,u,o.io);continue}return{state:u,sent:D,drained:!1,open:g,fatal:M.status===401?"auth":"network",...M.error!==void 0?{error:M.error}:{}}}return u.closed!==void 0&&!c&&T.spans.every(w=>u.sent[w.spanId]!==void 0)?{...await _o(e,t.project.orgId,u,n,a.filledToolUseId),sent:D}:{state:u,sent:D,drained:!1,open:g}}async function _o(e,t,n,r,o){let{adapter:s,deps:i,mem:a}=e;await To(e,n.projectKey,t,r.decisions);let d={...n,files:[]};ct(i.home,s.stateDir,d,i.io);let c=ot(i.home,s.stateDir,n.projectKey);for(let u of r.files)i.io.remove(`${c}/${u}`);return a.totals.pepDecisions.seen+=r.decisions.length,a.totals.pepDecisions.filledToolUseId+=o,{state:d,sent:0,drained:!0,open:!1}}async function To(e,t,n,r){let o=e.deps.retainDecisions;if(!(o===void 0||r.length===0))try{let{queueFull:s}=await o({projectKey:t,orgId:n,decisions:r}),i=Math.min(r.length,Number.isSafeInteger(s)?s:0);for(let a=0;a<i;a++)Se(e.mem.report,"outcome-queue-full")}catch{}}function gc(e,t,n){let{adapter:r,mem:o}=e,s;for(let d of n){let c=d.entry;if(c?.kind!=="capture")continue;let u=r.versionOf(c);u!==void 0&&(s===void 0||u.seenAtMs>s.seenAtMs)&&(s=u)}if(s===void 0)return;let i=dt(o.totals,t),a=i[r.versionKey];(a===void 0||s.seenAtMs>=a.seenAtMs)&&(i[r.versionKey]=s)}function yc(e,t,n){let{deps:r,mem:o}=e,s=`${n}/${An}`,i=`${s}.${r.pid}.${r.now()}`;if(r.claimFile(s,i)){try{for(let a of r.io.readFile(i).toString("utf8"))Dt(o,t,to(a))}catch{}r.io.remove(i)}}function hc(e,t){let n=/^\.(\d+)-\d+-\d+\.json\./.exec(e);if(!(n===null||!e.endsWith(".tmp")))return t-Number(n[1])}function So(e){let{adapter:t,deps:n,mem:r}=e;if(!Pn(r.totals))try{if(!n.io.exists(U(n.home,t.stateDir).projects)){r.totals=at();return}Un(n.home,t.stateDir,Fn(Nn(n.home,t.stateDir,t.versionKey,n.io),r.totals,t.versionKey),n.io),r.totals=at()}catch{}}function Co(e,t,n){try{return n.readdir(U(e,t).queue)}catch{return[]}}async function _c(e,t){let{adapter:n,deps:r,mem:o}=e,s=r.now(),i=r.credentials();if(i===null)return Sc(s,{fatal:"credentials"});let a=n.readRegistry(r.home,r.io),d=0,c=0,u=0,l=0,g=!1,R,T;for(let m of Co(r.home,n.stateDir,r.io)){let E=ot(r.home,n.stateDir,m),{files:k,other:D}=mo(E,p=>n.parseQueueEntry(p),r.io,o.cache,E);D.includes(An)&&yc(e,m,E);for(let p of D){let S=hc(p,s);S!==void 0&&S>=wt&&r.io.remove(`${E}/${p}`)}if(k.length===0)continue;for(let p of k)u=Math.max(u,p.atMs);gc(e,m,k);let A=yo({projectKey:m,files:k,states:[...o.states.values()],nowMs:s,traceIdFor:p=>r.builder.traceId(p),...t.closeOpenTurns===!0?{limits:{idleSweepMs:0}}:{},rules:n}),w=a.kind==="ok"?a.registry.projects[m]:void 0;for(let{file:p,reason:S}of A.dropped){Dt(o,m,S);let P=p.entry;P?.kind==="unknown"&&Se(o.totals.unknownKinds,P.rawKind),S==="decision-orphan"&&(o.totals.pepDecisions.orphaned+=1,o.totals.pepDecisions.seen+=1,w!==void 0&&P?.kind==="pep-decision"&&await To(e,m,w.orgId,[P])),r.io.remove(`${E}/${p.name}`),o.cache.delete(`${E}/${p.name}`)}if(d+=A.pending.length,w===void 0){if(d+=A.turns.reduce((p,S)=>p+S.files.length,0),a.kind==="ok"){for(let p of A.turns)if(!(s-p.state.lastRecordAtMs<wt)){for(let S of p.files)Dt(o,m,"unregistered"),r.io.remove(`${E}/${S}`),o.cache.delete(`${E}/${S}`);o.states.delete(p.state.traceId),jn(r.home,n.stateDir,p.state.traceId,r.io)}}continue}let M={project:w,credentials:i,posts:o.posts};for(let p of A.turns){let S;try{S=await mc(e,M,p)}catch(P){S={state:p.state,sent:0,drained:!1,open:p.state.closed===void 0,fatal:"network",error:P instanceof Error?P.message:String(P)},Rc(e,p.state)}if(o.states.set(S.state.traceId,S.state),l+=S.sent,S.drained)for(let P of p.files)o.cache.delete(`${E}/${P}`);else d+=p.files.length,S.open&&(c+=1);if(S.fatal!==void 0){g=!0,T=S.error??T,o.totals.lastError={atMs:r.now(),message:S.error??(S.fatal==="auth"?"not signed in":"upload failed")},S.fatal==="auth"&&(R="auth");break}}if(o.posts=M.posts,i=M.credentials,R!==void 0)break}return{entries:d,openTurns:c,newestRecordMs:u,sent:l,failed:g,...R!==void 0?{fatal:R}:{},...T!==void 0?{error:T}:{}}}function Sc(e,t={}){return{entries:0,openTurns:0,newestRecordMs:e,sent:0,failed:!1,...t}}function Rc(e,t){try{ct(e.deps.home,e.adapter.stateDir,t,e.deps.io)}catch{}}function Ec(e,t,n){for(let r of Co(e,t,n))try{if(n.readdir(ot(e,t,r)).some(s=>s.endsWith(".json")&&!s.startsWith(".")))return!0}catch{}return!1}function xc(e,t,n,r){return e.failed?r:e.openTurns===0?t.pollIdleMs:n-e.newestRecordMs<=t.flowWindowMs?t.pollFlowingMs:t.pollOpenMs}async function ko(e,t,n={}){let r=U(t.home,e.stateDir),o=It(r.senderLock,t.lockIO,t.pid);if(o===void 0)return{outcome:"locked",cycles:0,posts:0,spansSent:0,dropped:{}};let s=fo(t.home,e.stateDir,t.io);for(let m of s.unreadable)t.io.remove(m);let i={states:new Map(s.states.map(m=>[m.traceId,m])),cache:new Map,totals:at(),report:{},scrubbers:bn(Ct),posts:0},a={adapter:e,deps:t,mem:i},d=t.now(),c="done",u=0,l=0,g,R,T=t.limits.backoffMs;try{for(;;){if(!o.heartbeat()){c="lost-lock";break}let m=await _c(a,n);u+=1,l+=m.sent,g=m.error??g,So(a);for(let E of ho([...i.states.values()],t.now()))jn(t.home,e.stateDir,E.traceId,t.io),i.states.delete(E.traceId);if(m.fatal==="credentials"){c="no-credentials";break}if(m.failed){if(R??=t.now(),m.fatal==="auth"||t.now()-R>=t.limits.giveUpMs){c="send-failed";break}}else R=void 0,T=t.limits.backoffMs;if(n.maxRunMs!==void 0&&t.now()-d>=n.maxRunMs){c="time-limit";break}if(m.entries===0&&!m.failed){if(o.release(),o=void 0,!Ec(t.home,e.stateDir,t.io)||(o=It(r.senderLock,t.lockIO,t.pid),o===void 0))break;continue}await t.sleep(xc(m,t.limits,t.now(),T)),m.failed&&(T=Math.min(T*2,t.limits.pollIdleMs*12))}}finally{So(a),o?.release()}return{outcome:c,cycles:u,posts:i.posts,spansSent:l,dropped:i.report,...g!==void 0?{lastError:g}:{}}}function vo(e,t,n){try{let r=JSON.parse(n.readFile(U(e,t).install).toString("utf8"));return typeof r.cliVersion=="string"?r.cliVersion:void 0}catch{return}}import{createHash as jc}from"crypto";import{join as hy}from"path";var Io="cursor",Mt="cursor",J="cursor",Oo={agent:Io,vendor:Mt,stateDir:J};function le(e){return U(e,J)}import{constants as lt,promises as ut}from"fs";import{dirname as bc,isAbsolute as wo,join as Nt}from"path";var Tc=2e3,Cc=1e3,Cy=nt.maxOutcomes;var kc=10*6e4,vc=864e5,Do=nt.maxAgeDays*vc,Ic=nt.maxFutureMinutes*6e4,Oc=255,Ac=128,wc=448,Dc=384,Mc=lt.O_NOFOLLOW??0,ky=lt.O_NONBLOCK??0,Pc=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,$n="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",Nc=new RegExp(`^(\\d{15})-(${$n})-(${$n})\\.json$`),Uc=new RegExp(`^\\.tmp-(\\d{15})-(${$n})$`),Mo={mkdir:(e,t)=>ut.mkdir(e,t),readdir:e=>ut.readdir(e),open:(e,t,n)=>ut.open(e,t,n),rename:(e,t)=>ut.rename(e,t),unlink:e=>ut.unlink(e)};function Po(e){return Nt(bc(e),"pending-outcomes")}function Ao(e){if(typeof e!="string")return;let t=e.toLowerCase();return Pc.test(t)?t:void 0}function Pt(e,t=Oc){return typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Ve(e,t){return e.includes(t)?t:void 0}function Vn(e,t=new Date){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e,r=Ao(n.id),o=Ao(n.org_id),s=Rt(n.vendor)?n.vendor:void 0,i=Pt(n.session_id),a=Pt(n.correlation_id),d=Pt(n.tool_name),c=Ve(Tn,n.decided_via),u=Ve(kn,n.answer);if(r===void 0||o===void 0||s===void 0||i===void 0||a===void 0||d===void 0||c===void 0||u===void 0)return;let l=typeof n.decided_at=="string"?Date.parse(n.decided_at):Number.NaN;if(!Number.isFinite(l))return;let g=t.getTime();if(l<g-Do||l>g+Ic)return;let R;if(n.snapshot_age_seconds!==void 0){let A=n.snapshot_age_seconds;if(typeof A!="number"||!Number.isSafeInteger(A)||A<0)return;R=A}let T;if(n.fail_mode!==void 0&&(T=Ve(["open","closed"],n.fail_mode),T===void 0))return;let m=n.fallback_cause===void 0?void 0:Ve(On,n.fallback_cause);if(n.fallback_cause!==void 0&&m===void 0)return;let E={id:r,org_id:o,vendor:s,session_id:i,correlation_id:a,tool_name:d,answer:u,...R!==void 0?{snapshot_age_seconds:R}:{},...T!==void 0?{fail_mode:T}:{},decided_at:new Date(l).toISOString()};if(c==="snapshot"){let A=Ve(Cn,n.verdict),w=Pt(n.snapshot_version,Ac);return A===void 0||w===void 0||m===void 0||n.cause!==void 0?void 0:{...E,decided_via:c,verdict:A,fallback_cause:m,snapshot_version:w}}let k=Ve(vn,n.cause);if(!(k===void 0||n.verdict!==void 0||n.snapshot_version!==void 0||In.includes(k)!==(m!==void 0)))return{...E,decided_via:c,cause:k,...m!==void 0?{fallback_cause:m}:{}}}function Fc(e){return`${String(Date.parse(e.decided_at)).padStart(15,"0")}-${e.org_id}-${e.id}.json`}function No(e){let t=Nc.exec(e);if(t!==null)return{decidedMs:Number(t[1]),orgId:t[2],id:t[3]}}async function Uo(e,t){try{return await e.readdir(t)}catch{return}}async function Fo(e,t){try{return await e.unlink(t),!0}catch{return!1}}async function jo(e,t,n={}){let r=n.fs??Mo,o=n.now??new Date;if(!wo(e))return"failed";let s=Vn(t,o);if(s===void 0)return"invalid";let i;try{await r.mkdir(e,{recursive:!0,mode:wc});let a=await Uo(r,e);if(a===void 0)return"failed";let d=0,c=0;for(let R of a){let T=No(R);T!==void 0&&(d++,T.orgId===s.org_id&&c++)}if(d>=Tc||c>=Cc)return"queue_full";let u=String(o.getTime()).padStart(15,"0"),l=Nt(e,`.tmp-${u}-${s.id}`),g=await r.open(l,lt.O_WRONLY|lt.O_CREAT|lt.O_EXCL|Mc,Dc);i=l;try{await g.writeFile(JSON.stringify(s),"utf8")}finally{await g.close()}return await r.rename(l,Nt(e,Fc(s))),"queued"}catch{return i!==void 0&&await Fo(r,i),"failed"}}async function Lo(e,t={}){let n=t.fs??Mo,r=(t.now??new Date).getTime();if(!wo(e))return 0;let o=await Uo(n,e);if(o===void 0)return 0;let s=0;for(let i of o){let a=No(i),d;if(a!==void 0)d=a.decidedMs<r-Do;else{let c=Uc.exec(i);d=c===null||Number(c[1])<r-kc}d&&await Fo(n,Nt(e,i))&&s++}return s}var Lc=new Set(["preToolUse","beforeMCPExecution"]);function Bc(e){if(!Lc.has(e.hookEvent))return{kind:"skip",reason:"checkpoint"};if(e.verdict==="observed")return{kind:"skip",reason:"observed"};if(e.handoff!==void 0)return{kind:"skip",reason:"handoff"};if(e.hold?.outcome==="no-correlation")return{kind:"skip",reason:"no-correlation"};switch(e.via){case"cached-rules":return{kind:"snapshot"};case"no-cache":return{kind:"none",cause:"no_snapshot"};case"unauthorized":return{kind:"none",cause:"credential_rejected"};case"forbidden":return{kind:"none",cause:"pdp_refused"};case"misconfigured":return{kind:"none",cause:"misconfigured"};case"pdp":return e.hold?.outcome==="unreachable"?{kind:"none",cause:"hold_unavailable"}:{kind:"skip",reason:"online"};default:return{kind:"skip",reason:"unknown-via"}}}function $c(e,t){let n=jc("sha256").update(JSON.stringify(["at944-cursor-outcome-v1",e,t.decidedAtMs,t.hookEvent,t.conversationId,t.generationId,t.toolUseId,t.argsHash]),"utf8").digest("hex"),r=(Number.parseInt(n.slice(16,17),16)&3|8).toString(16);return`${n.slice(0,8)}-${n.slice(8,12)}-8${n.slice(13,16)}-${r}${n.slice(17,20)}-${n.slice(20,32)}`}function Vc(e,t){let n=Bc(e);if(n.kind==="skip")return{skip:n.reason};let r={id:$c(t.projectKey,e),org_id:t.orgId,vendor:"cursor",session_id:e.conversationId,correlation_id:e.toolUseId,tool_name:e.vendorTool,answer:e.blocked===!0?"deny":"proceed",decided_at:Number.isFinite(e.decidedAtMs)?new Date(e.decidedAtMs).toISOString():void 0},o=n.kind==="snapshot"?{...r,decided_via:"snapshot",verdict:e.verdict,snapshot_version:e.snapshotVersion,snapshot_age_seconds:e.snapshotAgeSeconds,fail_mode:e.failMode,fallback_cause:e.fallbackCause}:{...r,decided_via:"none",cause:n.cause,...n.cause==="no_snapshot"||n.cause==="hold_unavailable"?{fallback_cause:e.fallbackCause}:{}},s=Vn(o,t.now??new Date);return s===void 0?{skip:"invalid"}:{item:s}}function Kc(e){return Po(le(e).pepSnapshot)}async function Hc(e){let t=0,n=0,r=0,o=0,s=e.now??new Date;for(let i of e.decisions){let a;try{a=Vc(i,{orgId:e.orgId,projectKey:e.projectKey,now:s})}catch{a={skip:"invalid"}}if("skip"in a){r++;continue}let d=await jo(e.dir,a.item,{now:s,...e.fs===void 0?{}:{fs:e.fs}});d==="queued"?t++:d==="queue_full"?n++:d==="invalid"?r++:o++}return{queued:t,queueFull:n,skipped:r,failed:o}}function Bo(e,t={}){let n=Kc(e),r=!1;return async o=>{let s=t.now?.()??new Date,i=t.fs===void 0?{}:{fs:t.fs};return r||(r=!0,await Lo(n,{now:s,...i})),Hc({dir:n,...o,now:s,...i})}}import{createHash as Ny}from"crypto";var Kn="MCP:";var pt="user_prompt",zc="gen_ai.completion",Z="full_command",Ke="file_path",Ee="gen_ai.tool.call.result",ft=new Set([pt,zc,Z,Ke,Ee]);var Ut="secret-manager-output",Ft=`[REDACTED:secret:${Ut}]`,Yc=[/^op\s+read(\s|$)/,/^op\s+item\s+get(\s|$)/,/^aws\s+secretsmanager\s+get-secret-value(\s|$)/,/^gcloud\s+secrets\s+versions\s+access(\s|$)/,/^vault\s+read(\s|$)/,/^vault\s+kv\s+get(\s|$)/,/^az\s+keyvault\s+secret\s+show(\s|$)/],qc=/&&|\|\||;|\|/,Jc=/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;function Zc(e){let t=e.trimStart().replace(Jc,"");return Yc.some(n=>n.test(t))}function Xc(e){if(e.length===0)return!1;for(let t of e.split(qc))if(Zc(t))return!0;return!1}var eu=new Set;function Ko(e,t){let n=e[t.commandKey];if(typeof n!="string"||!Xc(n))return eu;let r=new Set;for(let o of Object.keys(e)){let s=e[o];if(!(typeof s!="string"||s.length===0)){if(t.resultKeys?.has(o)){r.add(o);continue}t.resultKeyPrefixes?.some(i=>o.startsWith(i))&&r.add(o)}}return r}var tu={commandKey:Z,resultKeys:new Set([Ee])};function Ho(e,t,n={}){let r={},o={},s=0;if(t===null){for(let[a,d]of Object.entries(e))r[a]=d;return{attributes:r,redactedCount:0,byType:{}}}let i=Ko(n.correlationCommand===void 0?e:{...e,[Z]:n.correlationCommand},tu);for(let[a,d]of Object.entries(e)){if(typeof d!="string"||d.length===0){r[a]=d;continue}if(i.has(a)){r[a]=Ft,o[Ut]=(o[Ut]??0)+1,s+=1;continue}if(!ft.has(a)){r[a]=d;continue}let c=Hr(d,t);if(r[a]=c.text,c.total>0){s+=c.total;for(let u in c.redactions)o[u]=(o[u]??0)+c.redactions[u]}}return{attributes:r,redactedCount:s,byType:o}}var jt=8192;var Go=16*1024,Qo=jt+Go;function Hn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nu(e){return e.length>jt?e.slice(0,jt):e}function ru(e,t){let n=0,r=Math.min(e.length,t.length);for(;n<r&&e.charCodeAt(e.length-1-n)===t.charCodeAt(t.length-1-n);)n+=1;return n}function Wo(e,t){let n={},r=new Map;for(let[a,d]of Object.entries(e))if(ft.has(a)&&d.length>Qo){let c=d.slice(0,Qo);n[a]=c,r.set(a,c)}else n[a]=d;let o=e[Z],s=Ho(n,t,o===void 0?{}:{correlationCommand:o}),i={};for(let[a,d]of Object.entries(s.attributes)){if(!ft.has(a)){i[a]=d;continue}let c=r.get(a),u=d;if(c!==void 0&&u!==Ft){let l=Math.min(Go,ru(c,u));u=u.slice(0,u.length-l)}i[a]=nu(u)}return{attributes:i,redactedCount:s.redactedCount,byType:s.byType}}function ou(e,t){if(typeof e.event!="string"||!t.has(e.event)||typeof e.capturedAtMs!="number"||!Number.isFinite(e.capturedAtMs))return!1;let n=e.tool;return n===void 0?!0:Hn(n)&&typeof n.vendorTool=="string"&&typeof n.argsHash=="string"&&Hn(n.call)&&typeof n.call.tool=="string"}function su(e){return typeof e.decidedAtMs=="number"&&Number.isFinite(e.decidedAtMs)&&typeof e.decisionMs=="number"&&typeof e.hookEvent=="string"&&typeof e.vendorTool=="string"&&typeof e.argsHash=="string"&&typeof e.verdict=="string"&&typeof e.blocked=="boolean"}function zo(e,t){let n;try{n=JSON.parse(e)}catch{return}if(!Hn(n))return;let r=n,o=()=>({kind:"unknown",rawKind:typeof r.kind=="string"?r.kind:String(r.kind),rawV:r.v});return r.v!==1?o():r.kind==="capture"&&ou(r,t)||r.kind==="pep-decision"&&su(r)?r:o()}import{createHmac as ih,randomBytes as ah}from"crypto";var Yo=Object.freeze(["beforeSubmitPrompt","postToolUse","postToolUseFailure","afterMCPExecution","afterAgentResponse","afterFileEdit","subagentStart","subagentStop","stop"]);var au=new Set(Yo);function qo(e){return zo(e,au)}function Lt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Jo(e){return typeof e=="string"&&e!==""}function du(e,t){if(!Lt(t))return{key:e};let n=Jo(t.root)?t.root:void 0,r=Array.isArray(t.subfolders)?t.subfolders.map(o=>Lt(o)&&Jo(o.path)?o.path:void 0).filter(o=>o!==void 0):[];return{key:e,...n!==void 0?{root:n}:{},...r.length>0?{subfolders:r}:{}}}function cu(e,t){let n;try{n=JSON.parse(e)}catch{return}if(!Lt(n)||n.v!==1||!Lt(n.projects))return;let r={},o=[];for(let[s,i]of Object.entries(n.projects))t(s,i)?r[s]=i:o.push(du(s,i));return{registry:{v:1,projects:r},skipped:o}}var uu=Object.freeze({v:1,projects:Object.freeze({})});function Zo(e,t,n=O){let r;try{if(!n.exists(e))return{kind:"missing"};r=n.readFile(e).toString("utf8")}catch{return{kind:"unreadable"}}let o=cu(r,t);return o===void 0?{kind:"unreadable"}:{kind:"ok",registry:o.registry,skipped:o.skipped}}function Xo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ne(e){return typeof e=="string"&&e!==""}function es(e){return e==="project"||e==="user"}var lu=new Set(["flag","agenttrail-json","derived"]);function pu(e){return Xo(e)&&ne(e.path)&&ne(e.transcriptFolder)&&es(e.install)&&ne(e.registeredAt)}function fu(e,t){return Xo(t)?t.projectKey===e&&ne(t.root)&&ne(t.transcriptFolder)&&ne(t.orgId)&&ne(t.projectSlug)&&ne(t.projectId)&&lu.has(t.projectSource)&&typeof t.projectLabel=="string"&&(t.developerId===void 0||typeof t.developerId=="string")&&typeof t.captureContent=="boolean"&&es(t.install)&&ne(t.registeredAt)&&(t.subfolders===void 0||Array.isArray(t.subfolders)&&t.subfolders.every(pu)):!1}function Bt(e,t=O){return Zo(le(e).projects,fu,t)}import{join as Ts}from"path";function mu(e){let t=e.replace(/\/+$/,"");return`${/\/api\/v\d+$/.test(t)?t:`${t}/api/v1`}/machines/enforcement`}function Qn(e){let t=(e.now??(()=>new Date))().toISOString(),n={machine_id:e.machineId,install_id:e.installId,enforced:e.enforced,reported_at:t};return!e.enforced&&e.reason!==void 0&&(n.reason=e.reason),e.installScope!==void 0&&(n.install_scope=e.installScope),e.installScope==="project"&&e.projectId!==void 0&&(n.project_id=e.projectId),e.contentCapture!==void 0&&(n.content_capture=e.contentCapture),n}async function ts(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),2e3);try{return(await t(mu(e.apiBase),{method:"PUT",headers:{Authorization:`Bearer ${e.token}`,"content-type":"application/json"},body:JSON.stringify(Qn(e)),signal:n.signal})).ok}catch{return!1}finally{clearTimeout(r)}}import{join as U_}from"path";import{execFileSync as g_}from"child_process";import{accessSync as h_,constants as __}from"fs";var $t=class extends Error{constructor(t){super(t),this.name="HookCommandError"}};var yu="{}",as="CURSOR_PROJECT_DIR",mt=class extends $t{constructor(t){super(t),this.name="CursorGateError"}};var ns='m() { case "$1" in ',rs=`) return 0 ;; esac; return 1; }; if m "$${as}"; then exec `,os=`; fi; p=$(cd -P -- "$${as}" 2>/dev/null && pwd -P); if [ -n "$p" ] && m "$p"; then exec `,ss=`; fi; printf "${yu}"`,is="/bin/sh -c ";function ds(e,t){let n=t,r="",o=!1;for(;;){let s=e[n];if(s===void 0||s==="|"||s===")")break;if(o)throw new mt("a gate pattern ends at its star");if(s==="'"){let i=e.indexOf("'",n+1);if(i===-1)throw new mt("an unterminated quoted run");r+=e.slice(n+1,i),n=i+1}else if(e.startsWith(`"'"`,n))r+="'",n+=3;else if(e.startsWith("\\\\",n))r+="\\",n+=2;else if(s==="*")o=!0,n+=1;else throw new mt("a character this generator never writes")}return{value:r,end:n,star:o}}function hu(e){try{let t=ds(e,0);return t.end===e.length&&!t.star?t.value:void 0}catch{return}}function cs(e){if(!e.startsWith(is))return;let t=hu(e.slice(is.length));if(t===void 0||!t.startsWith(ns))return;let n=[],r=ns.length;try{for(;;){let d=ds(t,r);if(d.star||n.push(d.value),r=d.end,t[r]==="|"){r+=1;continue}break}}catch{return}if(n.length===0||!t.startsWith(rs,r))return;let o=t.slice(r+rs.length),s=o.indexOf(os);if(s===-1||!o.endsWith(ss))return;let i=o.slice(0,s),a=o.slice(s+os.length,o.length-ss.length);return i===a?{folders:n,helper:i}:void 0}import{readFileSync as C_}from"fs";var Gn="pep-hook.mjs",_u={preToolUse:600,beforeMCPExecution:600,beforeShellExecution:30},$_=Object.keys(_u);function us(e){return typeof e=="string"&&e.includes(Gn)&&/(?:^|\s)--agent cursor(?=\s|$)/.test(e)}function Vt(e){switch(e){case"unauthorized":return"AgentTrail could not verify this device (401), so enforcement is off and capture is on. Run `login --agent cursor` again, then setup.";case"forbidden":return"AgentTrail refused the enforcement check (403), so enforcement is off and capture is on.";case"unreachable":return"AgentTrail could not be reached, so enforcement is off and capture is on. Run setup again when you are online."}}function ls(e,t=O){let n;try{let o=le(e).enforcement;if(!t.exists(o))return;n=JSON.parse(t.readFile(o).toString("utf8"))}catch{return}if(n===null||typeof n!="object"||Array.isArray(n))return;let r=n;if(r.v===1&&!(typeof r.enabled!="boolean"||typeof r.apiBase!="string"||typeof r.orgId!="string"||typeof r.agentId!="string"||typeof r.timeoutMs!="number"||typeof r.userScopeHandoff!="boolean"))return r}import{createHash as z_}from"crypto";import{existsSync as Su,mkdirSync as Ru,readdirSync as Eu,readFileSync as xu,rmdirSync as bu,statSync as Tu,unlinkSync as Cu}from"fs";import{dirname as ku,join as J_}from"path";function Wn(e){return e?.code==="ENOENT"}var Kt={readText(e){try{return xu(e,"utf8")}catch(t){if(Wn(t))return;throw t}},fileMode(e){try{return Tu(e).mode&511}catch(t){if(Wn(t))return;throw t}},writeText(e,t,n){Ru(ku(e),{recursive:!0,mode:rt}),de(e,t,{mode:n})},deleteFile(e){try{Cu(e)}catch(t){if(!Wn(t))throw t}},dirExists(e){return Su(e)},removeDirIfEmpty(e){try{Eu(e).length===0&&bu(e)}catch{}}};function zn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vu(e){if(e===void 0){let o={};return{ok:!0,doc:{version:1,hooks:o},hooks:o}}let t;try{t=JSON.parse(e)}catch{return{ok:!1,reason:"is not valid JSON"}}if(!zn(t))return{ok:!1,reason:"is not a JSON object"};if(t.version!==void 0&&t.version!==1)return{ok:!1,reason:`has version ${JSON.stringify(t.version)}, not 1`};if(t.hooks!==void 0&&!zn(t.hooks))return{ok:!1,reason:'has a "hooks" value that is not an object'};let n=t.hooks??{};for(let[o,s]of Object.entries(n))if(!Array.isArray(s))return{ok:!1,reason:`has a "${o}" hook list that is not an array`};let r="version"in t?{...t}:{version:1,...t};return r.hooks=n,{ok:!0,doc:r,hooks:n}}function Iu(e){return zn(e)&&typeof e.command=="string"?e.command:void 0}function ps(e,t){let n=vu(e);if(!n.ok)return[];let r=[];for(let[o,s]of Object.entries(n.hooks))for(let i of s){let a=Iu(i);a!==void 0&&t(a)&&r.push({event:o,entry:i})}return r}import{createHash as Ou}from"crypto";import{join as Au}from"path";var wu=360*60*1e3,Du=900*1e3;function fs(e){return Au(le(e).root,"machine-report.json")}function ms(e){return Ou("sha256").update(JSON.stringify(e)).digest("hex").slice(0,32)}function gs(e,t=O){try{let n=fs(e);if(!t.exists(n))return;let r=JSON.parse(t.readFile(n).toString("utf8"));return r?.v!==1||typeof r.attemptedAtMs!="number"||typeof r.hash!="string"||typeof r.accepted!="boolean"?void 0:r}catch{return}}function ys(e,t,n=O){try{n.writeFileAtomic(fs(e),`${JSON.stringify(t)}
15
+ `,Q)}catch{}}function hs(e,t,n){return e===void 0||e.hash!==t||e.attemptedAtMs>n?!0:e.accepted?n-(e.acceptedAtMs??e.attemptedAtMs)>=wu:n-e.attemptedAtMs>=Du}import{createHash as Mu}from"crypto";import{dirname as RS,join as Pu}from"path";import{fileURLToPath as xS}from"url";function Nu(e){return Mu("sha256").update(e).digest("hex")}function _s(e,t,n=O){let r=U(e,t).install;try{if(!n.exists(r))return;let o=JSON.parse(n.readFile(r).toString("utf8"));if(o===null||typeof o!="object")return;let s=o;return s.v===1&&typeof s.nodePath=="string"?s:void 0}catch{return}}function Ss(e,t,n,r=O){let o=U(e,t),s=_s(e,t,r);if(s===void 0)return["no install record (run setup again)"];let i=[];r.exists(s.nodePath)||i.push(`the Node the hooks run, ${s.nodePath}, is no longer there`);for(let a of n){let d=Pu(o.runtime,a),c;try{c=r.exists(d)?Nu(r.readFile(d)):void 0}catch{c=void 0}c===void 0?i.push(`${d} is missing`):s.files[a]!==void 0&&c!==s.files[a]&&i.push(`${d} is not the file setup copied`)}return i}var Uu=["capture-hook.mjs","flush.mjs","pep-hook.mjs"];function Rs(e,t=O,n=Uu){return Ss(e,J,n,t)}function Fu(e){return Ts(e,".cursor","hooks.json")}function ju(e,t,n=Kt){let r=t.install==="project"?Ts(t.path,".cursor","hooks.json"):Fu(e),o;try{o=n.readText(r)}catch{return}let s=ps(o,us);return t.install==="project"?s.length>0:s.some(i=>(cs(i.entry.command)?.folders??[]).includes(t.path))}function Lu(e){return e===void 0?"disabled":e===Vt("unauthorized")||e===Vt("forbidden")?"credential-rejected":e===Vt("unreachable")?"unreachable":"disabled"}function Bu(e){return[{path:e.root,install:e.install},...(e.subfolders??[]).map(t=>({path:t.path,install:t.install}))]}function Es(e,t,n,r,o){let s=Bu(t).map(i=>ju(e,i,o));return s.some(i=>i===!0)&&(n===void 0||!n.enabled)?{enforced:!1,reason:"install-failed"}:n===void 0||!n.enabled?{enforced:!1,reason:n===void 0?"disabled":Lu(n.probeNote)}:t.enforce!==!0?{enforced:!1,reason:"disabled"}:Rs(e,r,[Gn]).length>0?{enforced:!1,reason:"install-failed"}:s.some(i=>i!==!0)?{enforced:!1,reason:"install-failed"}:{enforced:!0}}function xs(e,t,n){return`cursor:${e==="global"?n:t}`}function bs(e){if(e.length!==0){if(e.every(t=>t.captureContent))return"on";if(e.every(t=>!t.captureContent))return"off"}}function $u(e){let t=e.io??O,n=e.hooksIO??Kt,r=Bt(e.home,t);if(r.kind!=="ok")return[];let o=Object.values(r.registry.projects);if(o.length===0)return[];let s=ls(e.home,t),i=(e.machineId??(()=>bt(e.home)))(),a=e.installId??(u=>Rr(e.home,u)),d=[];for(let u of o.filter(l=>l.install==="project")){let l=Es(e.home,u,s,t,n),g=bs([u]);d.push({params:{machineId:i,installId:a(xs("project",u.root,e.home)),enforced:l.enforced,...l.reason!==void 0?{reason:l.reason}:{},installScope:"project",projectId:u.projectId,...g!==void 0?{contentCapture:g}:{}}})}let c=o.filter(u=>u.install==="user");if(c.length>0){let l=c.map(R=>Es(e.home,R,s,t,n)).find(R=>!R.enforced),g=bs(c);d.push({params:{machineId:i,installId:a(xs("global","",e.home)),enforced:l===void 0,...l?.reason!==void 0?{reason:l.reason}:{},installScope:"global",...g!==void 0?{contentCapture:g}:{}}})}return d}var Vu=2e3;async function Cs(e){let t;try{let n=new Promise(r=>{t=setTimeout(()=>r(!1),Vu)});return await Promise.race([Ku(e),n])}catch{return!1}finally{t!==void 0&&clearTimeout(t)}}async function Ku(e){let t=e.io??O,n=je({homeDir:e.home});if(n===null||n.api_endpoint===void 0)return!1;let r=$u(e);if(r.length===0)return!1;let o=ms(r.map(T=>Qn({...T.params,apiBase:"",token:"",now:()=>new Date(0)}))),s=gs(e.home,t),i=e.now();if(e.force!==!0&&!hs(s,o,i))return!1;let a=n.api_endpoint,d=n.ingest_token,c=!1,u=async(T,m)=>{let E=await e.fetch(T,m);return E.status===401&&(c=!0),E},l=T=>Promise.all(r.map(m=>ts({...m.params,apiBase:a,token:T},u))),g=await l(d);if(c&&!g.every(Boolean)){let T=await e.refresh(d);T!==null&&T.ingest_token!==d&&(d=T.ingest_token,g=await l(d))}let R=g.every(Boolean);return ys(e.home,{v:1,attemptedAtMs:i,...R?{acceptedAtMs:i}:{},hash:o,accepted:R},t),R}var ks="cursorVersion";import{createHash as cp}from"crypto";var vs=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function Hu(e){return typeof e=="string"&&vs.test(e)}var Is=Hu;var j=[];for(let e=0;e<256;++e)j.push((e+256).toString(16).slice(1));function Os(e,t=0){return j[e[t+0]]+j[e[t+1]]+j[e[t+2]]+j[e[t+3]]+"-"+j[e[t+4]]+j[e[t+5]]+"-"+j[e[t+6]]+j[e[t+7]]+"-"+j[e[t+8]]+j[e[t+9]]+"-"+j[e[t+10]]+j[e[t+11]]+j[e[t+12]]+j[e[t+13]]+j[e[t+14]]+j[e[t+15]]}function Qu(e){if(!Is(e))throw TypeError("Invalid UUID");let t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}var As=Qu;function Gu(e){e=unescape(encodeURIComponent(e));let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var Wu="6ba7b810-9dad-11d1-80b4-00c04fd430c8",zu="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Yn(e,t,n){function r(o,s,i,a){var d;if(typeof o=="string"&&(o=Gu(o)),typeof s=="string"&&(s=As(s)),((d=s)===null||d===void 0?void 0:d.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(s),c.set(o,s.length),c=n(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,i){a=a||0;for(let u=0;u<16;++u)i[a+u]=c[u];return i}return Os(c)}try{r.name=e}catch{}return r.DNS=Wu,r.URL=zu,r}import Yu from"crypto";function qu(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),Yu.createHash("sha1").update(e).digest()}var ws=qu;var Ju=Yn("v5",80,ws),Ht=Ju;var ye={};gi(ye,{BRAND:()=>bl,DIRTY:()=>xe,EMPTY_PATH:()=>tl,INVALID:()=>x,NEVER:()=>ap,OK:()=>B,ParseStatus:()=>L,Schema:()=>v,ZodAny:()=>me,ZodArray:()=>ie,ZodBigInt:()=>Te,ZodBoolean:()=>Ce,ZodBranded:()=>yt,ZodCatch:()=>Ue,ZodDate:()=>ke,ZodDefault:()=>Ne,ZodDiscriminatedUnion:()=>Wt,ZodEffects:()=>Y,ZodEnum:()=>Me,ZodError:()=>V,ZodFirstPartyTypeKind:()=>b,ZodFunction:()=>Yt,ZodIntersection:()=>Ae,ZodIssueCode:()=>f,ZodLazy:()=>we,ZodLiteral:()=>De,ZodMap:()=>Ye,ZodNaN:()=>Je,ZodNativeEnum:()=>Pe,ZodNever:()=>q,ZodNull:()=>Ie,ZodNullable:()=>te,ZodNumber:()=>be,ZodObject:()=>K,ZodOptional:()=>W,ZodParsedType:()=>h,ZodPipeline:()=>ht,ZodPromise:()=>ge,ZodReadonly:()=>Fe,ZodRecord:()=>zt,ZodSchema:()=>v,ZodSet:()=>qe,ZodString:()=>fe,ZodSymbol:()=>We,ZodTransformer:()=>Y,ZodTuple:()=>ee,ZodType:()=>v,ZodUndefined:()=>ve,ZodUnion:()=>Oe,ZodUnknown:()=>se,ZodVoid:()=>ze,addIssueToContext:()=>y,any:()=>Dl,array:()=>Ul,bigint:()=>vl,boolean:()=>Vs,coerce:()=>ip,custom:()=>Ls,date:()=>Il,datetimeRegex:()=>Fs,defaultErrorMap:()=>re,discriminatedUnion:()=>Bl,effect:()=>Zl,enum:()=>Yl,function:()=>Gl,getErrorMap:()=>He,getParsedType:()=>X,instanceof:()=>Cl,intersection:()=>$l,isAborted:()=>Qt,isAsync:()=>Qe,isDirty:()=>Gt,isValid:()=>pe,late:()=>Tl,lazy:()=>Wl,literal:()=>zl,makeIssue:()=>gt,map:()=>Hl,nan:()=>kl,nativeEnum:()=>ql,never:()=>Pl,null:()=>wl,nullable:()=>ep,number:()=>$s,object:()=>Fl,objectUtil:()=>qn,oboolean:()=>sp,onumber:()=>op,optional:()=>Xl,ostring:()=>rp,pipeline:()=>np,preprocess:()=>tp,promise:()=>Jl,quotelessJson:()=>Zu,record:()=>Kl,set:()=>Ql,setErrorMap:()=>el,strictObject:()=>jl,string:()=>Bs,symbol:()=>Ol,transformer:()=>Zl,tuple:()=>Vl,undefined:()=>Al,union:()=>Ll,unknown:()=>Ml,util:()=>I,void:()=>Nl});var I;(function(e){e.assertEqual=o=>{};function t(o){}e.assertIs=t;function n(o){throw new Error}e.assertNever=n,e.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},e.getValidEnumValues=o=>{let s=e.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return e.objectValues(i)},e.objectValues=o=>e.objectKeys(o).map(function(s){return o[s]}),e.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},e.find=(o,s)=>{for(let i of o)if(s(i))return i},e.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function r(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}e.joinValues=r,e.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(I||(I={}));var qn;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(qn||(qn={}));var h=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),X=e=>{switch(typeof e){case"undefined":return h.undefined;case"string":return h.string;case"number":return Number.isNaN(e)?h.nan:h.number;case"boolean":return h.boolean;case"function":return h.function;case"bigint":return h.bigint;case"symbol":return h.symbol;case"object":return Array.isArray(e)?h.array:e===null?h.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?h.promise:typeof Map<"u"&&e instanceof Map?h.map:typeof Set<"u"&&e instanceof Set?h.set:typeof Date<"u"&&e instanceof Date?h.date:h.object;default:return h.unknown}};var f=I.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Zu=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),V=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(s){return s.message},r={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)r._errors.push(n(i));else{let a=r,d=0;for(;d<i.path.length;){let c=i.path[d];d===i.path.length-1?(a[c]=a[c]||{_errors:[]},a[c]._errors.push(n(i))):a[c]=a[c]||{_errors:[]},a=a[c],d++}}};return o(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,I.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];n[s]=n[s]||[],n[s].push(t(o))}else r.push(t(o));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};V.create=e=>new V(e);var Xu=(e,t)=>{let n;switch(e.code){case f.invalid_type:e.received===h.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case f.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,I.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:n=`Unrecognized key(s) in object: ${I.joinValues(e.keys,", ")}`;break;case f.invalid_union:n="Invalid input";break;case f.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${I.joinValues(e.options)}`;break;case f.invalid_enum_value:n=`Invalid enum value. Expected ${I.joinValues(e.options)}, received '${e.received}'`;break;case f.invalid_arguments:n="Invalid function arguments";break;case f.invalid_return_type:n="Invalid function return type";break;case f.invalid_date:n="Invalid date";break;case f.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:I.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case f.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case f.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case f.custom:n="Invalid input";break;case f.invalid_intersection_types:n="Intersection results could not be merged";break;case f.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case f.not_finite:n="Number must be finite";break;default:n=t.defaultError,I.assertNever(e)}return{message:n}},re=Xu;var Ds=re;function el(e){Ds=e}function He(){return Ds}var gt=e=>{let{data:t,path:n,errorMaps:r,issueData:o}=e,s=[...n,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",d=r.filter(c=>!!c).slice().reverse();for(let c of d)a=c(i,{data:t,defaultError:a}).message;return{...o,path:s,message:a}},tl=[];function y(e,t){let n=He(),r=gt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===re?void 0:re].filter(o=>!!o)});e.common.issues.push(r)}var L=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let o of n){if(o.status==="aborted")return x;o.status==="dirty"&&t.dirty(),r.push(o.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let o of n){let s=await o.key,i=await o.value;r.push({key:s,value:i})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let o of n){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return x;s.status==="dirty"&&t.dirty(),i.status==="dirty"&&t.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(r[s.value]=i.value)}return{status:t.value,value:r}}},x=Object.freeze({status:"aborted"}),xe=e=>({status:"dirty",value:e}),B=e=>({status:"valid",value:e}),Qt=e=>e.status==="aborted",Gt=e=>e.status==="dirty",pe=e=>e.status==="valid",Qe=e=>typeof Promise<"u"&&e instanceof Promise;var _;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(_||(_={}));var z=class{constructor(t,n,r,o){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Ms=(e,t)=>{if(pe(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new V(e.common.issues);return this._error=n,this._error}}};function C(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:o}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:o}:{errorMap:(i,a)=>{let{message:d}=e;return i.code==="invalid_enum_value"?{message:d??a.defaultError}:typeof a.data>"u"?{message:d??r??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:d??n??a.defaultError}},description:o}}var v=class{get description(){return this._def.description}_getType(t){return X(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:X(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new L,ctx:{common:t.parent.common,data:t.data,parsedType:X(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Qe(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:X(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Ms(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:X(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return pe(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>pe(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:X(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Qe(o)?o:Promise.resolve(o));return Ms(r,s)}refine(t,n){let r=o=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(o):n;return this._refinement((o,s)=>{let i=t(o),a=()=>s.addIssue({code:f.custom,...r(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(d=>d?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(t,n){return this._refinement((r,o)=>t(r)?!0:(o.addIssue(typeof n=="function"?n(r,o):n),!1))}_refinement(t){return new Y({schema:this,typeName:b.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return W.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ie.create(this)}promise(){return ge.create(this,this._def)}or(t){return Oe.create([this,t],this._def)}and(t){return Ae.create(this,t,this._def)}transform(t){return new Y({...C(this._def),schema:this,typeName:b.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Ne({...C(this._def),innerType:this,defaultValue:n,typeName:b.ZodDefault})}brand(){return new yt({typeName:b.ZodBranded,type:this,...C(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ue({...C(this._def),innerType:this,catchValue:n,typeName:b.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ht.create(this,t)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},nl=/^c[^\s-]{8,}$/i,rl=/^[0-9a-z]+$/,ol=/^[0-9A-HJKMNP-TV-Z]{26}$/i,sl=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,il=/^[a-z0-9_-]{21}$/i,al=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,dl=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,cl=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ul="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Jn,ll=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pl=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,fl=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,ml=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gl=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,yl=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ns="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",hl=new RegExp(`^${Ns}$`);function Us(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function _l(e){return new RegExp(`^${Us(e)}$`)}function Fs(e){let t=`${Ns}T${Us(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function Sl(e,t){return!!((t==="v4"||!t)&&ll.test(e)||(t==="v6"||!t)&&fl.test(e))}function Rl(e,t){if(!al.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||t&&o.alg!==t)}catch{return!1}}function El(e,t){return!!((t==="v4"||!t)&&pl.test(e)||(t==="v6"||!t)&&ml.test(e))}var fe=class e extends v{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==h.string){let s=this._getOrReturnCtx(t);return y(s,{code:f.invalid_type,expected:h.string,received:s.parsedType}),x}let r=new L,o;for(let s of this._def.checks)if(s.kind==="min")t.data.length<s.value&&(o=this._getOrReturnCtx(t,o),y(o,{code:f.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")t.data.length>s.value&&(o=this._getOrReturnCtx(t,o),y(o,{code:f.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){let i=t.data.length>s.value,a=t.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(t,o),i?y(o,{code:f.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&y(o,{code:f.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")cl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"email",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Jn||(Jn=new RegExp(ul,"u")),Jn.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"emoji",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")sl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"uuid",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")il.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"nanoid",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")nl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"cuid",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")rl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"cuid2",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")ol.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"ulid",code:f.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(t.data)}catch{o=this._getOrReturnCtx(t,o),y(o,{validation:"url",code:f.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"regex",code:f.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?t.data=t.data.trim():s.kind==="includes"?t.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(t,o),y(o,{code:f.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?t.data=t.data.toLowerCase():s.kind==="toUpperCase"?t.data=t.data.toUpperCase():s.kind==="startsWith"?t.data.startsWith(s.value)||(o=this._getOrReturnCtx(t,o),y(o,{code:f.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?t.data.endsWith(s.value)||(o=this._getOrReturnCtx(t,o),y(o,{code:f.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Fs(s).test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{code:f.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?hl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{code:f.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?_l(s).test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{code:f.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?dl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"duration",code:f.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?Sl(t.data,s.version)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"ip",code:f.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?Rl(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"jwt",code:f.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?El(t.data,s.version)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"cidr",code:f.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?gl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"base64",code:f.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?yl.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"base64url",code:f.invalid_string,message:s.message}),r.dirty()):I.assertNever(s);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(o=>t.test(o),{validation:n,code:f.invalid_string,..._.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",..._.errToObj(t)})}url(t){return this._addCheck({kind:"url",..._.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",..._.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",..._.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",..._.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",..._.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",..._.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",..._.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",..._.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",..._.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",..._.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",..._.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",..._.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,..._.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,..._.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",..._.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,..._.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,..._.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,..._.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,..._.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,..._.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,..._.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,..._.errToObj(n)})}nonempty(t){return this.min(1,_.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};fe.create=e=>new fe({checks:[],typeName:b.ZodString,coerce:e?.coerce??!1,...C(e)});function xl(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,o=n>r?n:r,s=Number.parseInt(e.toFixed(o).replace(".","")),i=Number.parseInt(t.toFixed(o).replace(".",""));return s%i/10**o}var be=class e extends v{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==h.number){let s=this._getOrReturnCtx(t);return y(s,{code:f.invalid_type,expected:h.number,received:s.parsedType}),x}let r,o=new L;for(let s of this._def.checks)s.kind==="int"?I.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?xl(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_finite,message:s.message}),o.dirty()):I.assertNever(s);return{status:o.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,_.toString(n))}gt(t,n){return this.setLimit("min",t,!1,_.toString(n))}lte(t,n){return this.setLimit("max",t,!0,_.toString(n))}lt(t,n){return this.setLimit("max",t,!1,_.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:_.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:_.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:_.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:_.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:_.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:_.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:_.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:_.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:_.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:_.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&I.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};be.create=e=>new be({checks:[],typeName:b.ZodNumber,coerce:e?.coerce||!1,...C(e)});var Te=class e extends v{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==h.bigint)return this._getInvalidInput(t);let r,o=new L;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?t.data<s.value:t.data<=s.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?t.data>s.value:t.data>=s.value)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?t.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),y(r,{code:f.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):I.assertNever(s);return{status:o.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:h.bigint,received:n.parsedType}),x}gte(t,n){return this.setLimit("min",t,!0,_.toString(n))}gt(t,n){return this.setLimit("min",t,!1,_.toString(n))}lte(t,n){return this.setLimit("max",t,!0,_.toString(n))}lt(t,n){return this.setLimit("max",t,!1,_.toString(n))}setLimit(t,n,r,o){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:_.toString(o)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:_.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:_.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:_.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:_.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:_.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};Te.create=e=>new Te({checks:[],typeName:b.ZodBigInt,coerce:e?.coerce??!1,...C(e)});var Ce=class extends v{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==h.boolean){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:h.boolean,received:r.parsedType}),x}return B(t.data)}};Ce.create=e=>new Ce({typeName:b.ZodBoolean,coerce:e?.coerce||!1,...C(e)});var ke=class e extends v{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==h.date){let s=this._getOrReturnCtx(t);return y(s,{code:f.invalid_type,expected:h.date,received:s.parsedType}),x}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return y(s,{code:f.invalid_date}),x}let r=new L,o;for(let s of this._def.checks)s.kind==="min"?t.data.getTime()<s.value&&(o=this._getOrReturnCtx(t,o),y(o,{code:f.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?t.data.getTime()>s.value&&(o=this._getOrReturnCtx(t,o),y(o,{code:f.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):I.assertNever(s);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:_.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:_.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};ke.create=e=>new ke({checks:[],coerce:e?.coerce||!1,typeName:b.ZodDate,...C(e)});var We=class extends v{_parse(t){if(this._getType(t)!==h.symbol){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:h.symbol,received:r.parsedType}),x}return B(t.data)}};We.create=e=>new We({typeName:b.ZodSymbol,...C(e)});var ve=class extends v{_parse(t){if(this._getType(t)!==h.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:h.undefined,received:r.parsedType}),x}return B(t.data)}};ve.create=e=>new ve({typeName:b.ZodUndefined,...C(e)});var Ie=class extends v{_parse(t){if(this._getType(t)!==h.null){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:h.null,received:r.parsedType}),x}return B(t.data)}};Ie.create=e=>new Ie({typeName:b.ZodNull,...C(e)});var me=class extends v{constructor(){super(...arguments),this._any=!0}_parse(t){return B(t.data)}};me.create=e=>new me({typeName:b.ZodAny,...C(e)});var se=class extends v{constructor(){super(...arguments),this._unknown=!0}_parse(t){return B(t.data)}};se.create=e=>new se({typeName:b.ZodUnknown,...C(e)});var q=class extends v{_parse(t){let n=this._getOrReturnCtx(t);return y(n,{code:f.invalid_type,expected:h.never,received:n.parsedType}),x}};q.create=e=>new q({typeName:b.ZodNever,...C(e)});var ze=class extends v{_parse(t){if(this._getType(t)!==h.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:h.void,received:r.parsedType}),x}return B(t.data)}};ze.create=e=>new ze({typeName:b.ZodVoid,...C(e)});var ie=class e extends v{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==h.array)return y(n,{code:f.invalid_type,expected:h.array,received:n.parsedType}),x;if(o.exactLength!==null){let i=n.data.length>o.exactLength.value,a=n.data.length<o.exactLength.value;(i||a)&&(y(n,{code:i?f.too_big:f.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&n.data.length<o.minLength.value&&(y(n,{code:f.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&n.data.length>o.maxLength.value&&(y(n,{code:f.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((i,a)=>o.type._parseAsync(new z(n,i,n.path,a)))).then(i=>L.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new z(n,i,n.path,a)));return L.mergeArray(r,s)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:_.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:_.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:_.toString(n)}})}nonempty(t){return this.min(1,t)}};ie.create=(e,t)=>new ie({type:e,minLength:null,maxLength:null,exactLength:null,typeName:b.ZodArray,...C(t)});function Ge(e){if(e instanceof K){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=W.create(Ge(r))}return new K({...e._def,shape:()=>t})}else return e instanceof ie?new ie({...e._def,type:Ge(e.element)}):e instanceof W?W.create(Ge(e.unwrap())):e instanceof te?te.create(Ge(e.unwrap())):e instanceof ee?ee.create(e.items.map(t=>Ge(t))):e}var K=class e extends v{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=I.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==h.object){let c=this._getOrReturnCtx(t);return y(c,{code:f.invalid_type,expected:h.object,received:c.parsedType}),x}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof q&&this._def.unknownKeys==="strip"))for(let c in o.data)i.includes(c)||a.push(c);let d=[];for(let c of i){let u=s[c],l=o.data[c];d.push({key:{status:"valid",value:c},value:u._parse(new z(o,l,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof q){let c=this._def.unknownKeys;if(c==="passthrough")for(let u of a)d.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(c==="strict")a.length>0&&(y(o,{code:f.unrecognized_keys,keys:a}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let c=this._def.catchall;for(let u of a){let l=o.data[u];d.push({key:{status:"valid",value:u},value:c._parse(new z(o,l,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let c=[];for(let u of d){let l=await u.key,g=await u.value;c.push({key:l,value:g,alwaysSet:u.alwaysSet})}return c}).then(c=>L.mergeObjectSync(r,c)):L.mergeObjectSync(r,d)}get shape(){return this._def.shape()}strict(t){return _.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let o=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:_.errToObj(t).message??o}:{message:o}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:b.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of I.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of I.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ge(this)}partial(t){let n={};for(let r of I.objectKeys(this.shape)){let o=this.shape[r];t&&!t[r]?n[r]=o:n[r]=o.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of I.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof W;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return js(I.objectKeys(this.shape))}};K.create=(e,t)=>new K({shape:()=>e,unknownKeys:"strip",catchall:q.create(),typeName:b.ZodObject,...C(t)});K.strictCreate=(e,t)=>new K({shape:()=>e,unknownKeys:"strict",catchall:q.create(),typeName:b.ZodObject,...C(t)});K.lazycreate=(e,t)=>new K({shape:e,unknownKeys:"strip",catchall:q.create(),typeName:b.ZodObject,...C(t)});var Oe=class extends v{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return n.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new V(a.ctx.common.issues));return y(n,{code:f.invalid_union,unionErrors:i}),x}if(n.common.async)return Promise.all(r.map(async s=>{let i={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let d of r){let c={...n,common:{...n.common,issues:[]},parent:null},u=d._parseSync({data:n.data,path:n.path,parent:c});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(d=>new V(d));return y(n,{code:f.invalid_union,unionErrors:a}),x}}get options(){return this._def.options}};Oe.create=(e,t)=>new Oe({options:e,typeName:b.ZodUnion,...C(t)});var oe=e=>e instanceof we?oe(e.schema):e instanceof Y?oe(e.innerType()):e instanceof De?[e.value]:e instanceof Me?e.options:e instanceof Pe?I.objectValues(e.enum):e instanceof Ne?oe(e._def.innerType):e instanceof ve?[void 0]:e instanceof Ie?[null]:e instanceof W?[void 0,...oe(e.unwrap())]:e instanceof te?[null,...oe(e.unwrap())]:e instanceof yt||e instanceof Fe?oe(e.unwrap()):e instanceof Ue?oe(e._def.innerType):[],Wt=class e extends v{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==h.object)return y(n,{code:f.invalid_type,expected:h.object,received:n.parsedType}),x;let r=this.discriminator,o=n.data[r],s=this.optionsMap.get(o);return s?n.common.async?s._parseAsync({data:n.data,path:n.path,parent:n}):s._parseSync({data:n.data,path:n.path,parent:n}):(y(n,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),x)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let o=new Map;for(let s of n){let i=oe(s.shape[t]);if(!i.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);o.set(a,s)}}return new e({typeName:b.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...C(r)})}};function Zn(e,t){let n=X(e),r=X(t);if(e===t)return{valid:!0,data:e};if(n===h.object&&r===h.object){let o=I.objectKeys(t),s=I.objectKeys(e).filter(a=>o.indexOf(a)!==-1),i={...e,...t};for(let a of s){let d=Zn(e[a],t[a]);if(!d.valid)return{valid:!1};i[a]=d.data}return{valid:!0,data:i}}else if(n===h.array&&r===h.array){if(e.length!==t.length)return{valid:!1};let o=[];for(let s=0;s<e.length;s++){let i=e[s],a=t[s],d=Zn(i,a);if(!d.valid)return{valid:!1};o.push(d.data)}return{valid:!0,data:o}}else return n===h.date&&r===h.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Ae=class extends v{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(Qt(s)||Qt(i))return x;let a=Zn(s.value,i.value);return a.valid?((Gt(s)||Gt(i))&&n.dirty(),{status:n.value,value:a.data}):(y(r,{code:f.invalid_intersection_types}),x)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Ae.create=(e,t,n)=>new Ae({left:e,right:t,typeName:b.ZodIntersection,...C(n)});var ee=class e extends v{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==h.array)return y(r,{code:f.invalid_type,expected:h.array,received:r.parsedType}),x;if(r.data.length<this._def.items.length)return y(r,{code:f.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),x;!this._def.rest&&r.data.length>this._def.items.length&&(y(r,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let s=[...r.data].map((i,a)=>{let d=this._def.items[a]||this._def.rest;return d?d._parse(new z(r,i,r.path,a)):null}).filter(i=>!!i);return r.common.async?Promise.all(s).then(i=>L.mergeArray(n,i)):L.mergeArray(n,s)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};ee.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:e,typeName:b.ZodTuple,rest:null,...C(t)})};var zt=class e extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==h.object)return y(r,{code:f.invalid_type,expected:h.object,received:r.parsedType}),x;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in r.data)o.push({key:s._parse(new z(r,a,r.path,a)),value:i._parse(new z(r,r.data[a],r.path,a)),alwaysSet:a in r.data});return r.common.async?L.mergeObjectAsync(n,o):L.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof v?new e({keyType:t,valueType:n,typeName:b.ZodRecord,...C(r)}):new e({keyType:fe.create(),valueType:t,typeName:b.ZodRecord,...C(n)})}},Ye=class extends v{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==h.map)return y(r,{code:f.invalid_type,expected:h.map,received:r.parsedType}),x;let o=this._def.keyType,s=this._def.valueType,i=[...r.data.entries()].map(([a,d],c)=>({key:o._parse(new z(r,a,r.path,[c,"key"])),value:s._parse(new z(r,d,r.path,[c,"value"]))}));if(r.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let d of i){let c=await d.key,u=await d.value;if(c.status==="aborted"||u.status==="aborted")return x;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}})}else{let a=new Map;for(let d of i){let c=d.key,u=d.value;if(c.status==="aborted"||u.status==="aborted")return x;(c.status==="dirty"||u.status==="dirty")&&n.dirty(),a.set(c.value,u.value)}return{status:n.value,value:a}}}};Ye.create=(e,t,n)=>new Ye({valueType:t,keyType:e,typeName:b.ZodMap,...C(n)});var qe=class e extends v{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==h.set)return y(r,{code:f.invalid_type,expected:h.set,received:r.parsedType}),x;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(y(r,{code:f.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),n.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(y(r,{code:f.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),n.dirty());let s=this._def.valueType;function i(d){let c=new Set;for(let u of d){if(u.status==="aborted")return x;u.status==="dirty"&&n.dirty(),c.add(u.value)}return{status:n.value,value:c}}let a=[...r.data.values()].map((d,c)=>s._parse(new z(r,d,r.path,c)));return r.common.async?Promise.all(a).then(d=>i(d)):i(a)}min(t,n){return new e({...this._def,minSize:{value:t,message:_.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:_.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};qe.create=(e,t)=>new qe({valueType:e,minSize:null,maxSize:null,typeName:b.ZodSet,...C(t)});var Yt=class e extends v{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==h.function)return y(n,{code:f.invalid_type,expected:h.function,received:n.parsedType}),x;function r(a,d){return gt({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,He(),re].filter(c=>!!c),issueData:{code:f.invalid_arguments,argumentsError:d}})}function o(a,d){return gt({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,He(),re].filter(c=>!!c),issueData:{code:f.invalid_return_type,returnTypeError:d}})}let s={errorMap:n.common.contextualErrorMap},i=n.data;if(this._def.returns instanceof ge){let a=this;return B(async function(...d){let c=new V([]),u=await a._def.args.parseAsync(d,s).catch(R=>{throw c.addIssue(r(d,R)),c}),l=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(l,s).catch(R=>{throw c.addIssue(o(l,R)),c})})}else{let a=this;return B(function(...d){let c=a._def.args.safeParse(d,s);if(!c.success)throw new V([r(d,c.error)]);let u=Reflect.apply(i,this,c.data),l=a._def.returns.safeParse(u,s);if(!l.success)throw new V([o(u,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:ee.create(t).rest(se.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||ee.create([]).rest(se.create()),returns:n||se.create(),typeName:b.ZodFunction,...C(r)})}},we=class extends v{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};we.create=(e,t)=>new we({getter:e,typeName:b.ZodLazy,...C(t)});var De=class extends v{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:f.invalid_literal,expected:this._def.value}),x}return{status:"valid",value:t.data}}get value(){return this._def.value}};De.create=(e,t)=>new De({value:e,typeName:b.ZodLiteral,...C(t)});function js(e,t){return new Me({values:e,typeName:b.ZodEnum,...C(t)})}var Me=class e extends v{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return y(n,{expected:I.joinValues(r),received:n.parsedType,code:f.invalid_type}),x}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return y(n,{received:n.data,code:f.invalid_enum_value,options:r}),x}return B(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};Me.create=js;var Pe=class extends v{_parse(t){let n=I.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==h.string&&r.parsedType!==h.number){let o=I.objectValues(n);return y(r,{expected:I.joinValues(o),received:r.parsedType,code:f.invalid_type}),x}if(this._cache||(this._cache=new Set(I.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let o=I.objectValues(n);return y(r,{received:r.data,code:f.invalid_enum_value,options:o}),x}return B(t.data)}get enum(){return this._def.values}};Pe.create=(e,t)=>new Pe({values:e,typeName:b.ZodNativeEnum,...C(t)});var ge=class extends v{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==h.promise&&n.common.async===!1)return y(n,{code:f.invalid_type,expected:h.promise,received:n.parsedType}),x;let r=n.parsedType===h.promise?n.data:Promise.resolve(n.data);return B(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};ge.create=(e,t)=>new ge({type:e,typeName:b.ZodPromise,...C(t)});var Y=class extends v{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===b.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=this._def.effect||null,s={addIssue:i=>{y(r,i),i.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(r.data,s);if(r.common.async)return Promise.resolve(i).then(async a=>{if(n.value==="aborted")return x;let d=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return d.status==="aborted"?x:d.status==="dirty"?xe(d.value):n.value==="dirty"?xe(d.value):d});{if(n.value==="aborted")return x;let a=this._def.schema._parseSync({data:i,path:r.path,parent:r});return a.status==="aborted"?x:a.status==="dirty"?xe(a.value):n.value==="dirty"?xe(a.value):a}}if(o.type==="refinement"){let i=a=>{let d=o.refinement(a,s);if(r.common.async)return Promise.resolve(d);if(d instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?x:(a.status==="dirty"&&n.dirty(),i(a.value),{status:n.value,value:a.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>a.status==="aborted"?x:(a.status==="dirty"&&n.dirty(),i(a.value).then(()=>({status:n.value,value:a.value}))))}if(o.type==="transform")if(r.common.async===!1){let i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!pe(i))return x;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:a}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>pe(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:n.value,value:a})):x);I.assertNever(o)}};Y.create=(e,t,n)=>new Y({schema:e,typeName:b.ZodEffects,effect:t,...C(n)});Y.createWithPreprocess=(e,t,n)=>new Y({schema:t,effect:{type:"preprocess",transform:e},typeName:b.ZodEffects,...C(n)});var W=class extends v{_parse(t){return this._getType(t)===h.undefined?B(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};W.create=(e,t)=>new W({innerType:e,typeName:b.ZodOptional,...C(t)});var te=class extends v{_parse(t){return this._getType(t)===h.null?B(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};te.create=(e,t)=>new te({innerType:e,typeName:b.ZodNullable,...C(t)});var Ne=class extends v{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===h.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Ne.create=(e,t)=>new Ne({innerType:e,typeName:b.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...C(t)});var Ue=class extends v{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Qe(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new V(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Ue.create=(e,t)=>new Ue({innerType:e,typeName:b.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...C(t)});var Je=class extends v{_parse(t){if(this._getType(t)!==h.nan){let r=this._getOrReturnCtx(t);return y(r,{code:f.invalid_type,expected:h.nan,received:r.parsedType}),x}return{status:"valid",value:t.data}}};Je.create=e=>new Je({typeName:b.ZodNaN,...C(e)});var bl=Symbol("zod_brand"),yt=class extends v{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},ht=class e extends v{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?x:s.status==="dirty"?(n.dirty(),xe(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?x:o.status==="dirty"?(n.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:b.ZodPipeline})}},Fe=class extends v{_parse(t){let n=this._def.innerType._parse(t),r=o=>(pe(o)&&(o.value=Object.freeze(o.value)),o);return Qe(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Fe.create=(e,t)=>new Fe({innerType:e,typeName:b.ZodReadonly,...C(t)});function Ps(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Ls(e,t={},n){return e?me.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Ps(t,r),d=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:d})}});if(!s){let i=Ps(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):me.create()}var Tl={object:K.lazycreate},b;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})(b||(b={}));var Cl=(e,t={message:`Input not instance of ${e.name}`})=>Ls(n=>n instanceof e,t),Bs=fe.create,$s=be.create,kl=Je.create,vl=Te.create,Vs=Ce.create,Il=ke.create,Ol=We.create,Al=ve.create,wl=Ie.create,Dl=me.create,Ml=se.create,Pl=q.create,Nl=ze.create,Ul=ie.create,Fl=K.create,jl=K.strictCreate,Ll=Oe.create,Bl=Wt.create,$l=Ae.create,Vl=ee.create,Kl=zt.create,Hl=Ye.create,Ql=qe.create,Gl=Yt.create,Wl=we.create,zl=De.create,Yl=Me.create,ql=Pe.create,Jl=ge.create,Zl=Y.create,Xl=W.create,ep=te.create,tp=Y.createWithPreprocess,np=ht.create,rp=()=>Bs().optional(),op=()=>$s().optional(),sp=()=>Vs().optional(),ip={string:(e=>fe.create({...e,coerce:!0})),number:(e=>be.create({...e,coerce:!0})),boolean:(e=>Ce.create({...e,coerce:!0})),bigint:(e=>Te.create({...e,coerce:!0})),date:(e=>ke.create({...e,coerce:!0}))};var ap=x;var _t="agenttrail.ingest.mode",St="agenttrail.ingest.batch_id",qt="backfill";var Jt=ye.string().regex(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,"must be a UUID"),dp=ye.string().min(1).refine(e=>e.startsWith("dlv_"),{message:"AgentTrail API key must start with 'dlv_'"}),qR=ye.object({orgId:Jt,projectSlug:ye.string().min(1),projectId:Jt.optional(),agentId:Jt.optional(),developerId:Jt.optional(),apiKey:dp.optional(),captureContent:ye.boolean().optional()}).strict();function Qs(e,t){return Ht(`${e}:${t}`,dn)}var Gs="agenttrail.org.id",Ws="agenttrail.project.id",zs="agenttrail.agent.id",Ys="agenttrail.developer.id",qs="agenttrail.project",Js="gen_ai.conversation.id",Zs="session.id",Xs="gen_ai.request.model",ei="llm_request.context",ti="tool_name",ni="gen_ai.tool.name",ri="gen_ai.tool.call.id",Xn="gen_ai.usage.input_tokens",er="gen_ai.usage.output_tokens",tr="gen_ai.usage.cache_read.input_tokens",nr="gen_ai.usage.cache_creation.input_tokens",up="interaction",Ks=1,lp=3,pp=Object.freeze({[Gs]:"metadata",[Ws]:"metadata",[zs]:"metadata",[Et]:"metadata",[Ys]:"metadata",[qs]:"metadata",[Xe]:"metadata",[_t]:"metadata",[St]:"metadata",[tn]:"metadata",[Js]:"metadata",[Zs]:"metadata",[on]:"metadata",[Xs]:"metadata",[ei]:"metadata",[nn]:"metadata",[Xn]:"metadata",[er]:"metadata",[tr]:"metadata",[nr]:"metadata",[ti]:"metadata",[ni]:"metadata",[en]:"metadata",[ri]:"metadata",[sn]:"metadata",[an]:"metadata",[rn]:"metadata",[pt]:"content",[Z]:"content",[Ke]:"content",[Ee]:"content"});function Zt(e,t,n){let r=n==="import"?`import:${t.conversationId}:${t.importKey??t.importOrdinal??0}`:`live:${t.conversationId}:${t.generationId??""}`;return Ht(r,e).replace(/-/g,"")}function Ze(e,t){let n=typeof t=="string"?t:`tool:${t.tool}`;return cp("sha256").update(`${e}:${n}`).digest("hex").slice(0,16)}function rr(e){return e.correlationId??`ordinal:${e.ordinal}`}function or(e,t){return Ze(e,{tool:rr(t)})}function Hs(e){if(!Number.isFinite(e)||e<=0)return"0";let t=Math.floor(e),n=Math.round((e-t)*1e6);return(BigInt(t)*1000000n+BigInt(n)).toString()}function fp(e,t,n){let r={...t};if(e.call.tool!==""&&(r[ti]=e.call.tool,r[ni]=e.call.tool),e.vendorTool!==""&&(r[en]=e.vendorTool),e.correlationId!==null&&(r[ri]=e.correlationId),e.mcpServerUnknown===!0&&(r[sn]="true"),e.pepBlocked===!0&&e.failed&&(r[an]="true"),e.subagentConversationId!==void 0&&(r[rn]=e.subagentConversationId),n){let{full_command:o,file_path:s}=e.call.args;o!==void 0&&(r[Z]=o),s!==void 0&&(r[Ke]=s),e.output!==void 0&&(r[Ee]=e.output)}return r}function mp(e,t,n){let r=n.mode==="import",o=Zt(e.traceNamespace,t,n.mode),s=Ze(o,"root"),i=t.endMs,a=n.include,d=!r&&t.usage!==null&&t.model!==null,c={};t.conversationId!==""&&(c[Js]=t.conversationId,c[Zs]=t.conversationId);let u=r?{[tn]:"true",[_t]:qt,...n.batchId?{[St]:n.batchId}:{}}:{},l=[];if(i!==null&&(a?.root??!0)){let g=t.closedBy??(r?"import":void 0);l.push({spanId:s,parentSpanId:"",name:e.rootSpanName,kind:Ks,startMs:t.startMs,endMs:i,attributes:{...c,...g!==void 0?{[on]:g}:{},...n.captureContent&&t.prompt?{[pt]:t.prompt}:{},...d?{}:{[Xe]:"false"},...u},error:t.status==="error"})}!r&&i!==null&&t.model!==null&&(a?.model??!0)&&l.push({spanId:Ze(o,"model"),parentSpanId:s,name:`chat ${t.model.name}`,kind:lp,startMs:t.startMs,endMs:t.model.endMs,attributes:{...c,[Xs]:t.model.name,[ei]:up,[nn]:"true",...d&&t.usage!==null?e.usageAttributes(t.usage):{[Xe]:"false"}},error:!1});for(let g of t.tools){let R=g.endMs??i;R!==null&&(a?.toolKeys!==void 0&&!a.toolKeys.has(rr(g))||l.push({spanId:or(o,g),parentSpanId:g.parentTaskKey===void 0?s:Ze(o,{tool:g.parentTaskKey}),name:g.call.tool===""?"execute_tool":`execute_tool ${g.call.tool}`,kind:Ks,startMs:g.startMs,endMs:R,attributes:{...fp(g,c,n.captureContent),...u},error:g.failed}))}return l}function oi(e,t,n,r){let o=n.mode==="import",s=Zt(e.traceNamespace,t,n.mode),i=n.resolvedScrubbers??null,a=0,d={},c=mp(e,t,n).map(l=>{let g=Wo(l.attributes,i);a+=g.redactedCount;for(let[T,m]of Object.entries(g.byType))d[T]=(d[T]??0)+m;let R=g.attributes;return{traceId:s,spanId:l.spanId,parentSpanId:l.parentSpanId,name:l.name,kind:l.kind,startTimeUnixNano:Hs(l.startMs),endTimeUnixNano:Hs(Math.max(l.endMs,l.startMs)),attributes:R,error:l.error}});return{resource:{attributes:{[Gs]:n.orgId,[Ws]:n.project.projectId,[zs]:r,[Et]:e.vendor,...n.project.developerId?{[Ys]:n.project.developerId}:{},...n.project.projectLabel?{[qs]:n.project.projectLabel}:{},[Xe]:o?"false":"true",...o?{[_t]:qt}:{},...o&&n.batchId?{[St]:n.batchId}:{}}},scope:{name:e.scopeName,version:n.scopeVersion},spans:c,redactions:{total:a,byType:d}}}function gp(e){return Qs(e,Mt)}var yp="agenttrail-cursor";function ir(e,t){return Zt(ii.traceNamespace,{conversationId:e.conversationId,generationId:e.generationId,...e.importOrdinal!==void 0?{importOrdinal:e.importOrdinal}:{}},t)}function hp(e){if(!("importKey"in e))return e;let{importKey:t,...n}=e;return n}function ar(e,t){return Ze(e,t)}function _p(e,t){return or(e,t)}var sr=new Set(["subagentStart","subagentStop"]),Sp=new Set(["postToolUse","postToolUseFailure","afterFileEdit"]),Rp=Object.freeze({conversationId:"",generationId:null,startMs:0,endMs:null,model:null,usage:null,tools:Object.freeze([])});function Ep(e){if(e===null||typeof e!="object")return!1;let t=e;return t.kind==="capture"&&typeof t.capturedAtMs=="number"&&Number.isFinite(t.capturedAtMs)}function dr(e){let t=e.tool?.durationMs;return t!==void 0&&Number.isFinite(t)&&t>=0?e.capturedAtMs-t:e.capturedAtMs}function xp(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}function bp(e){let t=e.find(n=>n.event==="beforeSubmitPrompt"&&n.conversationId!==null);if(t?.conversationId)return t.conversationId;for(let n of e){if(!sr.has(n.event))continue;let r=n.subagent?.parentConversationId??n.conversationId;if(r)return r}for(let n of["stop","afterAgentResponse"]){let r=xp(e,o=>o.event===n&&o.conversationId!==null);if(r?.conversationId)return r.conversationId}return e.find(n=>n.conversationId!==null)?.conversationId??""}function Tp(e){switch(e){case"completed":return"success";case"aborted":return"aborted";case"error":return"error";default:return"unknown"}}function Cp(e,t,n){let r=e.tool;if(r?.mcpServerUnknown!==!0)return;let o=t.filter(a=>!n.has(a)&&a.tool?.vendorTool===r.vendorTool&&a.conversationId===e.conversationId&&a.generationId===e.generationId&&a.capturedAtMs<=e.capturedAtMs),s=o.filter(a=>r.durationMs!==void 0&&a.tool?.durationMs===r.durationMs),i;for(let a of s.length>0?s:o)(i===void 0||a.capturedAtMs>=i.capturedAtMs)&&(i=a);return i!==void 0&&n.add(i),i}function kp(e,t,n,r){let o=e.tool,s=n?.tool,i=s===void 0?o.call:{tool:s.call.tool,args:s.call.args.full_command!==void 0?s.call.args:o.call.args},a=e.content?.output??e.content?.error;return{ordinal:t,vendorTool:o.vendorTool,call:i,correlationId:o.correlationId,startMs:dr(e),endMs:e.capturedAtMs,failed:o.failed===!0,...a!==void 0?{output:a}:{},...s===void 0&&o.mcpServerUnknown===!0?{mcpServerUnknown:!0}:{},...o.pepBlocked===!0?{pepBlocked:!0}:{},isTask:!1,...r(e.conversationId)?{}:{foreignConversationId:e.conversationId},placedAtMs:e.capturedAtMs}}function vp(e,t,n){let{post:r,start:o,stop:s}=e,i=o??s,a=o?.capturedAtMs??(r!==void 0?dr(r):s?.capturedAtMs??0),d=i?.subagent?.parentConversationId??i?.conversationId??null,c=r?.content?.output??r?.content?.error;return{ordinal:t,vendorTool:r?.tool?.vendorTool??"Task",call:r?.tool?.call??{tool:"Task",args:{}},correlationId:e.key,startMs:a,endMs:s?.capturedAtMs??r?.capturedAtMs??null,failed:r?.tool?.failed===!0||s?.status==="error",...c!==void 0?{output:c}:{},isTask:!0,...n(d)?{}:{foreignConversationId:d},placedAtMs:a}}function Ip(e,t){let n;for(let r of t)r.ordinal>=e.ordinal||r.correlationId===null||r.startMs>e.placedAtMs||r.endMs!==null&&e.placedAtMs>r.endMs||(n===void 0||r.startMs>=n.startMs)&&(n=r);return n}function si(e,t){let n=e.map((p,S)=>({record:p,index:S})).filter(({record:p})=>Ep(p)).sort((p,S)=>p.record.capturedAtMs-S.record.capturedAtMs||p.index-S.index).map(({record:p})=>p);if(n.length===0)return Rp;let r=bp(n),o=p=>p===null||p===r,s=n.find(p=>o(p.conversationId)&&!sr.has(p.event)&&p.generationId!==null)?.generationId??null,i=ir({conversationId:r,generationId:s},"live"),a=p=>{let S=t?.get(p);return typeof S=="number"&&Number.isFinite(S)?S:void 0},d=[],c=new Map,u=p=>{let S=p===null?void 0:c.get(p);if(S!==void 0)return S;let P={key:p};return d.push(P),p!==null&&c.set(p,P),P};for(let p of n)if(Sp.has(p.event)&&p.tool!==void 0){let S=u(p.tool.correlationId);S.post??=p}else if(sr.has(p.event)){let S=p.subagent?.subagentId??null;if(S===null)continue;let P=u(S);p.event==="subagentStart"?P.start??=p:P.stop=p}let l=n.filter(p=>p.event==="afterMCPExecution"&&p.tool!==void 0),g=new Set,R=d.map((p,S)=>{let P=p.start!==void 0||p.stop!==void 0?vp(p,S,o):kp(p.post,S,Cp(p.post,l,g),o),ae=a(_p(i,P));return ae===void 0?P:{...P,startMs:ae}}),T=R.filter(p=>p.isTask),m=R.map(p=>{let S=p.foreignConversationId===void 0?void 0:Ip(p,T);return{vendorTool:p.vendorTool,call:p.call,correlationId:p.correlationId,ordinal:p.ordinal,startMs:p.startMs,endMs:p.endMs,failed:p.failed,...p.output!==void 0?{output:p.output}:{},...p.mcpServerUnknown===!0?{mcpServerUnknown:!0}:{},...p.pepBlocked===!0?{pepBlocked:!0}:{},...p.foreignConversationId!==void 0?{subagentConversationId:p.foreignConversationId}:{},...S?.correlationId?{parentTaskKey:S.correlationId}:{}}}),E,k,D,A=Number.POSITIVE_INFINITY;for(let p of n)A=Math.min(A,dr(p)),o(p.conversationId)&&(p.event==="beforeSubmitPrompt"?E??=p.content?.prompt:p.event==="afterAgentResponse"?k=p:p.event==="stop"&&(D=p));let w=k?.model??D?.model??null,M=k?.capturedAtMs??D?.capturedAtMs;return{conversationId:r,generationId:s,startMs:a(ar(i,"root"))??A,endMs:D?.capturedAtMs??null,...D!==void 0?{closedBy:"stop",status:Tp(D.status)}:{},...E!==void 0?{prompt:E}:{},model:w!==null&&M!==void 0?{name:w,endMs:M}:null,usage:D?.usage??null,tools:m}}function Xt(e){return e!==void 0&&Number.isFinite(e)&&e>0?Math.floor(e):0}function Op(e){let t=Xt(e.cacheReadTokens),n=Xt(e.cacheWriteTokens);return{[Xn]:String(Math.max(0,Xt(e.inputTokens)-t-n)),[er]:String(Xt(e.outputTokens)),[tr]:String(t),[nr]:String(n)}}var ii={vendor:Mt,scopeName:yp,traceNamespace:cn,rootSpanName:"invoke_agent Cursor",usageAttributes:Op};function ai(e,t){return oi(ii,hp(e),t,gp(t.orgId))}function di(e){return{conversationId:e.conversationId,generationId:e.generationId}}function ci(e){return{conversationId:e.conversationId,generationId:e.generationId}}function ui(e){return e.event==="beforeSubmitPrompt"}function li(e){return e.event==="stop"}function pi(e){if(!(e.event!=="subagentStart"&&e.event!=="subagentStop"))return{edge:e.event==="subagentStart"?"start":"stop",subagentId:e.subagent?.subagentId??null,parentConversationId:e.subagent?.parentConversationId??e.conversationId}}function fi(e){return e==="postToolUse"||e==="postToolUseFailure"}var Dp=2e3,Mp={traceId:e=>ir(e,"live"),spanId:(e,t)=>ar(e,t),assemble:e=>si(e),build:(e,t)=>ai(e,t)};function Pp(e,t,n=Dp){let r=new Set(e.filter(o=>o.event==="afterMCPExecution").map(o=>`${o.generationId??""}\0${o.tool?.vendorTool??""}`));return e.filter(o=>{if(o.event!=="postToolUse")return!0;let s=o.tool;return s?.mcpServerUnknown!==!0||!s.vendorTool.startsWith(Kn)||r.has(`${o.generationId??""}\0${s.vendorTool}`)?!0:t-o.capturedAtMs>=n})}function Np(e){if(e.cursorVersion!==null)return{version:e.cursorVersion,seenAtMs:e.capturedAtMs}}var Up={...Oo,versionKey:ks,versionOf:Np,readRegistry:(e,t)=>Bt(e,t),parseQueueEntry:e=>qo(e),turnOf:di,decisionTurnOf:ci,opensTurn:ui,closesTurn:li,subagentOf:pi,fillableEvent:fi,holdBack:(e,t)=>Pp(e,t)};function Fp(e,t={}){return ko(Up,e,t)}async function jp(e,t,n){let r=je({homeDir:e});return r===null?null:r.ingest_token!==t?r:yn({lockPath:`${he(e,"cursor")}.lock`},async()=>{let o=je({homeDir:e});if(o===null)return null;if(o.ingest_token!==t)return o;let s=o.api_endpoint;if(s===void 0)return null;try{let i={agent:"cursor",apiEndpoint:s,ingestEndpoint:o.endpoint,homeDir:e,host:o.host,device:Cr(e),log:()=>{}},a=pr(i),d=await gn(s,o.refresh_token,n,a),c=hn(i,d,{apiEndpoint:s,ingestEndpoint:o.endpoint});return pn(e,c,{},"cursor"),mn(e,"cursor"),fr(i,d,a),c}catch{return null}})}function Lp(e={}){let t=e.home??wp(),n=e.io??O;return{home:t,io:n,lockIO:st,now:()=>Date.now(),sleep:r=>new Promise(o=>setTimeout(o,r)),fetch:globalThis.fetch,builder:Mp,pid:process.pid,limits:Ln,credentials:()=>je({homeDir:t}),refresh:r=>jp(t,r),claimFile:(r,o)=>{try{return Ap(r,o),!0}catch{return!1}},scopeVersion:vo(t,J,n)??"0.0.0",retainDecisions:Bo(t),...e}}async function Bp(e={}){try{let t=Lp(e.deps??{});e.closeOpenTurns!==!0&&await Cs({home:t.home,io:t.io,fetch:t.fetch,now:t.now,refresh:t.refresh}),await Fp(t,e)}catch{}return 0}function $p(){return/flush\.(mjs|cjs|js)$/.test(process.argv[1]??"")}$p()&&Bp().then(e=>{process.exitCode=e});export{Ln as DEFAULT_SENDER_LIMITS,Ro as MAX_BODY_BYTES,Dp as MCP_JOIN_WAIT_MS,Up as cursorSenderAdapter,Np as cursorVersionOf,Pp as holdUnjoinedMcp,Mp as liveTurnBuilder,Lp as realSenderDeps,jp as refreshCursorToken,Bp as runCursorSender,Fp as runSender,xo as selectSpans,Eo as snapshotForState,Bn as spanFingerprint,bo as splitSpanBatches};