@agenttrail/cli 0.2.12 → 0.2.24

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,13 @@
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 As=Object.defineProperty;var ks=(e,t)=>{for(var n in t)As(e,n,{get:t[n],enumerable:!0})};import{renameSync as Sl}from"fs";import{homedir as Rl}from"os";import{mkdirSync as Ks,readFileSync as Qs,unlinkSync as zl}from"fs";import{dirname as Gs,join as nn}from"path";import{randomBytes as ws}from"crypto";import{chmodSync as Ms,lstatSync as Ns,mkdirSync as Bl,readFileSync as $l,readlinkSync as Ps,realpathSync as Us,renameSync as js,statSync as Ls,unlinkSync as Fs,writeFileSync as Bs}from"fs";import{dirname as $s,join as Kl,resolve as Vs}from"path";var Jn=["claude-code","cursor","codex","replit-agent","devin","aider","windsurf","github-copilot"];function yt(e){return typeof e=="string"&&Jn.includes(e)}var ht="agenttrail.agent.vendor",Wt="agenttrail.tool.vendor_name";var Ze="agenttrail.usage.reported",Yt="agenttrail.time.approximate",zt="agenttrail.span.synthetic",qt="agenttrail.subagent.conversation_id";var Zt="agenttrail.turn.closed_by";var Jt="agenttrail.mcp.server_unknown",Xt="agenttrail.pep.blocked";var en="7f050af4-796e-5b05-94c2-dba78bcdc7c2";var tn="7d12feb9-faf4-5d1a-b711-9362724c66b3";function Ue(e,t,n={}){let r=e,o=!0;try{r=Us(e)}catch{o=!1;let a=!0;for(let d=0;d<8;d++){let c;try{c=Ns(r).isSymbolicLink()}catch{a=!1;break}if(!c){a=!1;break}r=Vs($s(r),Ps(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=Ls(r).mode&4095}catch{}let i=`${r}.tmp-${process.pid}-${ws(6).toString("hex")}`;try{Bs(i,t,s!==void 0?{mode:s,encoding:"utf8"}:"utf8"),s!==void 0&&Ms(i,s),js(i,r)}catch(a){try{Fs(i)}catch{}throw a}}var Hs=448;function me(e,t="claude"){switch(t){case"claude":return nn(e,".agenttrail","credentials.json");case"cursor":return nn(e,".agenttrail","cursor","credentials.json");case"codex":return nn(e,".agenttrail","codex","credentials.json")}return Ws(t)}function Ws(e){throw new Error(`AgentTrail has no credential file for the agent ${JSON.stringify(e)}.`)}function rn(e,t={},n="claude"){let r=t.readFile??(o=>Qs(o,"utf8"));try{let o=JSON.parse(r(me(e,n)));return Ys(o)?o:null}catch{return null}}function on(e,t,n={},r="claude"){let o=me(e,r),s=n.writeFile??((a,d,c)=>Ue(a,d,c!==void 0?{mode:c}:{}));return(n.mkdir??((a,d)=>Ks(a,{recursive:!0,mode:d})))(Gs(o),Hs),s(o,`${JSON.stringify(t,null,2)}
2
+ `,384),o}function Ys(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 zs,constants as sn,fchmodSync as qs,fstatSync as Zs,openSync as Js}from"fs";import{dirname as Xs,join as Xn,relative as ei,sep as ti}from"path";function ni(e,t=process.getuid?.()){if(t===void 0)return;let n;try{n=Js(e,sn.O_RDONLY|sn.O_DIRECTORY|sn.O_NOFOLLOW);let r=Zs(n);if(!r.isDirectory()||r.uid!==t)return;let o=r.mode&4095;if((o&63)===0)return;qs(n,o&-64)}catch{}finally{if(n!==void 0)try{zs(n)}catch{}}}function ri(e,t){let n=Xn(e,".agenttrail"),r=ei(n,Xs(me(e,t))),o=[n];for(let s of r===""?[]:r.split(ti))o.push(Xn(o[o.length-1],s));return o}function an(e,t,n=ni){for(let r of ri(e,t))n(r)}function er(e){throw new Error(`AgentTrail has no path for the agent ${JSON.stringify(e)}.`)}var oi=(e,t)=>fetch(e,t);function si(e,t){return`${e.replace(/\/$/,"")}${t}`}async function ii(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 dn(e,t,n=oi,r={}){let{ok:o,status:s,data:i}=await ii(n,si(e,"/auth/device/refresh"),{...r,refresh_token:t});if(!o||!ai(i)){let a=di(i)?i.error:`HTTP ${s}`;throw new Error(`device/refresh failed: ${a}`)}return i}function ai(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 di(e){return typeof e!="object"||e===null?!1:typeof e.error=="string"}import{closeSync as ci,openSync as ui,readFileSync as ip,rmSync as li,statSync as pi,writeSync as fi}from"fs";var mi=3e4,gi=(e,t)=>{let n=ui(e,"wx");try{fi(n,t)}finally{ci(n)}},yi=e=>{try{li(e,{force:!0})}catch{}},hi=e=>{try{let t=pi(e);return Date.now()-t.mtimeMs}catch{return null}};async function cn(e,t){let n=e.io??{},r=n.acquire??gi,o=n.release??yi,s=n.age??hi,i=n.now??(()=>Date.now()),a=n.sleep??(g=>new Promise(x=>setTimeout(x,g))),d=e.staleMs??mi,c=e.timeoutMs??1e4,u=e.retryMs??50,f=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()>=f)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 _p=1440*60*1e3;function tr(e,t={}){try{return e.device?.fields(e.agent,t)??{}}catch{return{}}}function nr(e,t,n,r=!1){try{e.device?.record(e.agent,t,n.device_name!==void 0?{typed:r}:void 0)}catch{}}function _i(e){switch(e){case"claude":case"cursor":case"codex":return!0}return er(e)}function un(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}:{},..._i(e.agent)?{api_endpoint:n.apiEndpoint}:{}}}function _t(e){return rn(e.homeDir,e.credentialsIO,"cursor")}import{mkdirSync as sr,readFileSync as Fi}from"fs";import{dirname as Bi,join as ir}from"path";var Si=["MacBook Pro","MacBook Air","Mac mini","iMac","Mac Studio","Mac Pro","Mac","Windows","Linux"];function St(e){return typeof e=="string"&&Si.includes(e)}import{execFileSync as Ri}from"child_process";var Ti=(e,t,n)=>Ri(e,[...t],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"],env:{PATH:"/usr/sbin:/usr/bin:/bin"}}),Ei=5e3,xi=1e3,bi={"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"},vi=[["MacBookPro","MacBook Pro"],["MacBookAir","MacBook Air"],["Macmini","Mac mini"],["MacPro","Mac Pro"],["iMac","iMac"]];function Ci(e){let t=e.trim(),n=bi[t];if(n)return n;for(let[r,o]of vi)if(t.startsWith(r)&&/^\d/.test(t.slice(r.length)))return o;return"Mac"}function Ii(e){if(typeof e!="string")return"Mac";let t=e.trim();return St(t)&&t!=="Windows"&&t!=="Linux"?t:"Mac"}var Ai=["SPHardwareDataType","-json","-detailLevel","mini"];function ki(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 Oi(e){try{let t=ki(e("/usr/sbin/system_profiler",Ai,Ei));if(t===void 0)return;let n=Ii(t.machine_name);return n==="Mac"?void 0:n}catch{return}}function Di(e){try{let t=Ci(e("/usr/sbin/sysctl",["-n","hw.model"],xi));return t==="Mac"?void 0:t}catch{return}}function rr(e={}){let t=e.platform??process.platform,n=e.exec??Ti;switch(t){case"darwin":return(e.thorough?Oi(n):void 0)??Di(n)??"Mac";case"win32":return"Windows";case"linux":return"Linux";default:return}}import{randomUUID as wi}from"crypto";import{readFileSync as Mi}from"fs";import{join as Ni}from"path";var Pi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ui(e){return Ni(e,".agenttrail","machine-id")}function ji(e,t){try{return(e.readFile??(n=>Mi(n,"utf8")))(t)}catch{return}}function Li(e,t,n){(e.writeFile??((o,s,i)=>Ue(o,s,i!==void 0?{mode:i}:{})))(t,n,384)}function or(e,t={}){let n=Ui(e),r=ji(t,n)?.trim();if(r&&Pi.test(r))return r;let o=wi();return Li(t,n,`${o}
4
+ `),o}function ar(e){return ir(e,".agenttrail","device.json")}var dr=["claude","cursor","codex"];function Je(e,t={}){let n=t.readFile??(r=>Fi(r,"utf8"));try{let r=JSON.parse(n(ar(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)?dr.filter(a=>o.named.includes(a)):[];return{...St(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 ln(e,t,n={}){let r=ar(e);try{(n.mkdir??((o,s)=>sr(o,{recursive:!0,mode:s})))(Bi(r),448),(n.writeFile??((o,s,i)=>Ue(o,s,i!==void 0?{mode:i}:{})))(r,`${JSON.stringify(t,null,2)}
5
+ `,384)}catch{}}function $i(e,t,n,r){if(t.device_model&&!r)return t.device_model;let o=rr({thorough:r,exec:n.exec,platform:n.platform})??t.device_model;return o!==void 0&&o!==t.device_model&&ln(e,{...t,device_model:o},n),o}function cr(e,t={}){return{fields(n,r={}){let o={};try{(t.mkdir??((s,i)=>sr(s,{recursive:!0,mode:i})))(ir(e,".agenttrail"),448),o.machine_id=or(e,t)}catch{}try{let s=Je(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=$i(e,s,t,r.thorough===!0);i!==void 0&&(o.device_model=i)}catch{}return o},record(n,r,o){try{let s=Je(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,f=o!==void 0&&!i||u;d={...s.device_model?{device_model:s.device_model}:{},device_name:a,...f?{name_chosen:!0}:{},named:dr.filter(g=>c.has(g))}}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&&ln(e,d,t)}catch{}},name(){return Je(e,t).device_name},confirmedName(n){let r=Je(e,t);return r.named?.includes(n)?r.device_name:void 0},forget(n){try{let r=Je(e,t);if(!r.named?.includes(n))return;ln(e,{...r,named:r.named.filter(o=>o!==n)},t)}catch{}}}}import{createHash as Id}from"crypto";var Vi=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,Ki=/[A-Z][a-z]{3,}|[a-z]{4,}|[A-Z]{4,}/g,Qi=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 Gi(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 Hi(e){let t=0;for(let n of e.match(Ki)??[])t+=n.length;return t/e.replace(/[-_]/g,"").length>=.7}function Wi(e){let t=e.split(/[-_]/);return t.length<5||t.some(n=>n.length>12)?!1:t.filter(n=>Qi.has(n.toLowerCase())).length>=3}function ur(e){return e.length<32||Vi.test(e)||/^sha(?:1|224|256|384|512)-/i.test(e)||Hi(e)||Wi(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:Gi(e)>=4}var Yi=/^(?:mysql\w*|mariadb[\w-]*)$/i,pn=/(?:^|[\s'"`(;|&/])(?:mysql\w*|mariadb[\w-]*)(?=$|[\s'"`);|&\\])/i,zi=/[\s,:}\]]/;function qi(e){let t=e[3],n=t==="\\"&&e[4]==='"'?e[5]:t==='"'||t==="'"?e[4]:void 0;return n!==void 0&&zi.test(n)}function Zi(e){return e.length===5?e.endsWith("''")||e.endsWith('""'):e.length===7&&e.endsWith('\\"\\"')}var lr=new RegExp(pn.source,"gi"),Ji=/^[A-Za-z_]\w*=/,Xi="\uE000",ea=new Set(["then","do","else","elif","!","{","RUN","CMD","ENTRYPOINT"]),ta=/^(?:[\w.-]+:|-|\*|\d+[.)]|[$%>#]|[\w.-]+@[\w.-]+:\S*[#$%>])$/,na=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"])]]),ra=new Set(["timeout","chroot","gosu","su-exec"]),pr=new Set(["-u","-w","-e","--user","--workdir","--env","--env-file","--detach-keys"]),oa=new Set([...pr,"-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"]),sa=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"]),ia=new Set(["-f","-p","--file","--project-name","--project-directory","--env-file","--profile","--ansi","--progress","--parallel"]),aa=new Set(["-u","-w","-e","-l","-v","-p","--user","--workdir","--env","--index","--label","--volume","--publish","--name","--entrypoint"]),da=new Set(["-b","-c","-D","-E","-e","-F","-I","-i","-J","-L","-l","-m","-O","-o","-p","-Q","-R","-S","-W","-w","-B"]),fr=new Set([";","|","&","(",")","`",`
6
+ `,"\r","{","}"]);function mr(e){let t=e.replace(/['"\\]/g,""),n=t.lastIndexOf("/");return(n===-1?t:t.slice(n+1)).toLowerCase()}function ca(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 je(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+=ca(o,n)?2:1}return r}function ua(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 la(e){let t=0,n=!0;for(let r=0;r<=e.length&&t<e.length;r++){let o=e[t];if(n&&ta.test(o)){t++;continue}if(n=!1,Ji.test(o)||ea.has(o)||o.includes(Xi)){t++;continue}let s=mr(o),i=na.get(s);if(i){t=je(e,t+1,i),ra.has(s)&&t++;continue}let a=s==="docker"||s==="podman"||s==="nerdctl",d=a?je(e,t+1,sa):t+1;if(a&&e[d]==="container"&&d++,s==="docker-compose"||a&&e[d]==="compose"){let c=je(e,s==="docker-compose"?t+1:d+1,ia);if(e[c]!=="exec"&&e[c]!=="run")return o;t=je(e,c+1,aa)+1;continue}if(a&&(e[d]==="exec"||e[d]==="run")){let c=e[d]==="run",u=je(e,d+1,c?oa:pr),f=c?ua(e,d+1,u):null;if(f!==null)return f;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=je(e,t+1,da)+1;continue}return o}return null}function gr(e){let t=la(e);return t!==null&&Yi.test(mr(t))}function pa(e,t,n,r){for(let o=n;o+t.length<=r;o++)if(yr(e,o)||e.startsWith(t,o)&&(t==='\\"'||e[o-1]!=="\\"))return o;return-1}function yr(e,t){let n=e[t];return n===`
7
+ `||n==="\r"?!0:n==="\\"&&(e[t+1]==="n"||e[t+1]==="r")}function fa(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===95||e===46||e===45}function ma(e,t,n){let r=e[t]==="\\",o=t+(r?2:1),s=o;for(;s<o+65&&s<n&&fa(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 ga(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 ya(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 ie=null;function ha(e,t){let n=Math.max(0,t-512),r,o,s,i,a,d;for(ie&&ie.text===e&&ie.i<=t&&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<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===`
8
+ `||u==="\r"){r+=2;continue}if(u==="u"&&e.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 g=ma(e,r,t);if(g>0){r+=g,o=r,s=!0,i=!0,a=null;continue}let x=e[r+f.length];if(f===a&&d&&(x===" "||x===" ")){r+=f.length,i=!1,a=null;continue}if(f===a||!i&&(x===","||x==="]"||x==="}")){r+=f.length,o=r,s=!0,i=!0,a=null;continue}if(i||ga(e,o,r)){r+=f.length,o=r,s=!0,i=!0,a=f,d=!0;continue}let A=pa(e,f,r+f.length,t);if(A===-1)return ie={text:e,i:r,at:o,found:s,blank:i,inside:a,word:d},{start:ya(e,r,o),unsure:!0,inside:a};if(yr(e,A)){r+=f.length,i=!1;continue}r=A+f.length,i=!1;continue}fr.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: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 Q=null;function _a(e,t,n){for((!Q||Q.text!==e||Q.end>n)&&(Q={text:e,last:-1,next:-1,end:n}),Q.end=n;Q.next<n;){Q.next!==-1&&(Q.last=Q.next),lr.lastIndex=Q.next===-1?0:Q.next+1;let r=lr.exec(e);Q.next=r?r.index:Number.POSITIVE_INFINITY}return Q.last>=t}function Sa(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&&!fr.has(a)&&a!=='"'&&a!=="'"?!1:pn.test(e.slice(o+1,n))}function Ra(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===`
10
+ `)break}if(r===-1)return!1;let o=e.slice(r+1,t).split(",").map(s=>s.trim().replace(/["\\]/g,""));return gr(o)}function hr(e,t,n){if(e[0]==="["||e[0]===",")return Ra(n,t,e);if(Zi(e))return!1;let r=ha(n,t);if(r.inside!==null&&e.startsWith(r.inside,3)||r.unsure&&qi(e))return!1;if(r.outside)return _a(n,r.start,t);let o=n.slice(r.start,t);if(r.unsure)return pn.test(o);let s=o.trim().split(/\s+/);return gr(s)||Sa(n,r.start)}function N(e,t){return t?`[REDACTED:${e}:${t}]`:`[REDACTED:${e}]`}var mn=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])`,Rr=`(?:\\b|${mn})`,gn=`(?:(?<![A-Za-z0-9_-])|${mn})`,Tr=String.raw`(?<!\[REDACTED:)`,Xe=String.raw`(?!["']?\[REDACTED:[a-z0-9:-]+\]["']?(?:[\s,;}\])]|$))`;function G(e,t){return new RegExp(`${Rr}${e}`,t)}var Ta=G(String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,"g"),Ea=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"),xa=G(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),ba=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"),va=G(String.raw`xox[baprs]-[A-Za-z0-9-]{10,255}\b`,"g"),Ca=G(String.raw`Bearer\s+([A-Za-z0-9._~+/-]{8,})=*`,"gi"),Ia=G(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),Aa=G(String.raw`eyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\b`,"g"),ka=/-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----[\s\S]{0,8192}?-----END (?:RSA |EC |DSA |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY-----/g,Oa=G(String.raw`(https?|ftp|wss?):\/\/[^\s/@:]+:[^\s]*@(?=[^\s/:@])`,"gi"),Da=(()=>{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(`${Rr}${Tr}${t}(["']?\\s*[=:]\\s*)${Xe}${n}`,"gi")})(),$="\uE000",wa=new RegExp(`${gn}${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*)${Xe}(?!["']?[~.]{0,2}/)(?:(")([^"${$}]{4,})"|(')([^'${$}]{4,})'|([^\\s"',;${$}]{4,}))`,"g"),Ma=new RegExp(`${gn}((?:Proxy-)?Authorization["']?\\s*[=:]\\s*["']?)((?:Basic|Token|Digest|Negotiate|ApiKey|Api-Key)\\s+)?(?!Bearer\\s)${Xe}([^\\s"',;${$}]{8,})`,"gi"),_r="(?:[Mm][Yy][Ss][Qq][Ll]|[Mm][Aa][Rr][Ii][Aa][Dd][Bb])",fn=`[^\\s"'\`;|&)\\\\${$}]`,Er='(?:\\\\\\\\|\\\\(?!["\\\\]))',xr=`${fn}*(?:${Er}${fn}*)*`,Na=`(?=${fn}|${Er})${xr}`,Pa=`(?:'[^'\\n${$}]*'|\\$'(?:[^'\\\\\\n${$}]|\\\\[^\\n${$}]){0,1024}'|\\\\"[^"\\\\\\n${$}]*\\\\"|"[^"\\n${$}]*")`,Ua=new RegExp(`(\\s-p)(?<=${_r}(?:\\\\\\n|[^\\n]){0,200}\\s-p)${Xe}(?:${Pa}${xr}|${Na})|([[,]\\s{0,8}\\\\?"-p)(?<=${_r}[^\\n]{0,200}"-p)${Xe}[^"\\\\\\n${$}]+(?=\\\\?")`,"g"),ja=new RegExp([`${gn}([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"),La=new RegExp(`(?:(?<![A-Za-z0-9_+/.%-])|${mn})(?<!==)(?<!sha(?:1|224|256|384|512)[-:])(?<!base64,)[A-Za-z0-9_-]{${32},}(?![A-Za-z0-9_+/=.%-])`,"g"),Fa=new RegExp(`[A-Za-z0-9_-]{${32}}`);function Rt(e,t,n,r){let o=n??"";return`${e}${t}${o}${r}${o}`}var Ba=G(String.raw`[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,255}\.[A-Za-z]{2,24}\b`,"g"),$a=G(String.raw`(?!000|666|9\d\d)\d{3}[- ](?!00)\d{2}[- ](?!0000)\d{4}\b`,"g"),Va=G(String.raw`(?:\d{13,19}\b|\d{3,6}([ -])\d{3,6}(?:\1\d{3,6}){1,3}\b)`,"g"),Ka=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:Ta,placeholder:()=>N("secret:aws")},{id:"pem-private-key",kind:"secret",category:"private-key",severity:"high",tier:"permissive",regex:ka,placeholder:()=>N("secret:private-key")},{id:"jwt",kind:"secret",category:"jwt",severity:"high",tier:"permissive",regex:Aa,placeholder:()=>N("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:ba,placeholder:()=>N("secret:github")},{id:"slack-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:va,placeholder:()=>N("secret:slack")},{id:"openai-key",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:xa,placeholder:()=>N("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:Ia,placeholder:()=>N("secret:connection-string")},{id:"basic-auth-url",kind:"secret",category:"basic-auth",severity:"high",tier:"permissive",regex:Oa,placeholder:e=>`${e[1].toLowerCase()}://${N("secret:basic-auth")}@`},{id:"bearer-token",kind:"secret",category:"token",severity:"medium",tier:"permissive",regex:Ca,placeholder:()=>`Bearer ${N("secret:bearer")}`},{id:"aws-secret-access-key",kind:"secret",category:"aws",severity:"medium",tier:"standard",regex:Ea,placeholder:e=>`${e[1]}${e[2]}${N("secret:aws-secret")}`},{id:"env-secret",kind:"secret",category:"env-secret",severity:"medium",tier:"standard",regex:Da,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:wa,prefilter:/_KEY|-key/i,placeholder:e=>Rt(e[1]??"",e[2]??"",e[3]??e[5],N("secret:env"))},{id:"authorization-header",kind:"secret",category:"token",severity:"medium",tier:"standard",regex:Ma,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:Ua,prefilter:/mysql|mariadb/i,accept:hr,placeholder:e=>`${e[1]??e[2]??""}${N("secret:password")}`},{id:"cloud-account-id",kind:"pii",category:"cloud-account",severity:"low",tier:"standard",regex:ja,prefilter:/account|project|owner-id|arn:aws/i,placeholder:e=>{let t=N("pii:account");return e[1]!==void 0?Rt(e[1],e[2]??"",e[3],t):e[5]!==void 0?Rt(e[5],e[6]??"",e[7],t):e[9]!==void 0?Rt(e[9],e[10]??"",e[11],t):t}},{id:"generic-secret",kind:"secret",category:"generic",severity:"low",tier:"standard",regex:La,prefilter:Fa,accept:ur,placeholder:()=>N("secret:generic")},{id:"email",kind:"pii",category:"email",severity:"low",tier:"standard",regex:Ba,placeholder:()=>N("pii:email")},{id:"ssn",kind:"pii",category:"ssn",severity:"high",tier:"standard",regex:$a,placeholder:()=>N("pii:ssn")},{id:"credit-card",kind:"pii",category:"credit-card",severity:"high",tier:"standard",regex:Va,placeholder:()=>N("pii:credit-card")},{id:"phone",kind:"pii",category:"phone",severity:"low",tier:"strict",regex:Ka,placeholder:()=>N("pii:phone")}],vr=new Set(["credit-card"]);function Cr(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 Qa={permissive:new Set(["permissive"]),standard:new Set(["permissive","standard"]),strict:new Set(["permissive","standard","strict"])},Le="\uE000",Ga=new RegExp(`${Le}(\\d+)${Le}`,"g");function Ir(e){return`${Le}${e}${Le}`}function Ha(e,t=!1){if(e==="off")return[];let n=Qa[e];return br.filter(r=>r.id==="phone"?n.has("strict")||t:n.has(r.tier))}function Wa(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 Ya(e,t,n,r){if(t.prefilter&&!t.prefilter.test(e))return e;let o=vr.has(t.id);return e.replace(t.regex,(...s)=>{let i=s[0];if(o&&!Cr(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)),Ir(d)})}function yn(e){return e.mode==="off"?null:{patterns:Ha(e.mode,e.enablePhone),denylist:Wa(e.denylistPatterns)}}function Ar(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}:za(e,n,r)}function za(e,t,n){let r={},o=[],s=e.includes(Le)?e.split(Le).join(""):e;for(let a of t)s=Ya(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]"),Ir(d)});if(o.length===0)return{text:e,redactions:{},total:0};s=s.replace(Ga,(a,d)=>o[Number(d)]);let i=0;for(let a in r)i+=r[a];return{text:s,redactions:r,total:i}}var hn=["snapshot","none"],_n=["allow","deny","require_approval"];var Sn=["proceed","deny","ask"],Rn=["pdp_refused","no_snapshot","credential_rejected","config_blank","misconfigured","hold_unavailable","watchdog"],Tn=["no_snapshot","hold_unavailable"],En=["timeout","unreachable","config_unavailable","evaluator_crash","rejected_request","waf_403","parse_error"];var et={maxOutcomes:500,maxDropDays:31,maxDropCount:1e5,maxAgeDays:30,maxFutureMinutes:5,clientDropRetentionDays:29};var kr="pubsub:sse:org:",qa=`${kr}*`;var Tt={mode:"standard"};function Or(e){return Object.entries(e).map(([t,n])=>({key:t,value:{stringValue:n}}))}function Et(e){return{resourceSpans:(Array.isArray(e)?e:[e]).map(n=>({resource:{attributes:Or(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:Or(r.attributes)};return r.error&&(o.status={code:2}),o})}]}))}}var Za=e=>new Promise(t=>setTimeout(t,e));function Ja(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 wr(e,t,n={}){if(t.dryRun)return{status:"skipped",attempts:0};let r=n.fetch??globalThis.fetch,o=n.sleep??Za,s=t.maxRetries??5,i=t.baseBackoffMs??500,a=`${t.endpoint.replace(/\/$/,"")}/v1/traces`,d=JSON.stringify(e),c=0,u="",f;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(A){if(u=A.message,f=void 0,c>s)break;await o(Dr(i,c,null));continue}if(f=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(Dr(i,c,Ja(g.headers)))}return{status:"failed",httpStatus:f,attempts:c,error:u}}function Dr(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 Mr(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 f=n.decisionTurnOf(d),g=n.turnOf(c);return d.toolUseId!==null&&d.toolUseId!==""&&f.conversationId===g.conversationId&&f.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((f,g)=>{s.has(g)||!o(f,d)||(c===void 0||f.decidedAtMs>c.decision.decidedAtMs)&&(c={index:g,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:Xa(a,t,n),filledToolUseId:i}}function Xa(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 km}from"fs";import{chmodSync as ed,existsSync as td,mkdirSync as Nr,readdirSync as nd,readFileSync as rd,renameSync as od,rmSync as Pr,writeFileSync as sd}from"fs";import{basename as id,dirname as jr,join as ad}from"path";var Lr=448,ae=384,Ur=0;function Fr(e,t=process.pid){return Ur+=1,ad(jr(e),`.${id(e)}.${t}.${Ur}.tmp`)}var P={readFile(e){return rd(e)},writeFileAtomic(e,t,n){Nr(jr(e),{recursive:!0,mode:Lr});let r=Fr(e);try{sd(r,t,{mode:n}),ed(r,n),od(r,e)}catch(o){throw Pr(r,{force:!0}),o}},mkdirp(e,t){Nr(e,{recursive:!0,mode:t})},remove(e){Pr(e,{recursive:!0,force:!0})},exists(e){return td(e)},readdir(e){return nd(e).sort()}};var xn=".dropped",dd="c";function Br(e){return e===dd?"queue-full":`mark-${e}`}import{createHash as Mm}from"crypto";import{join as U}from"path";function B(e,t){let n=U(e,".agenttrail",t),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 tt(e,t,n){return U(B(e,t).queue,n)}function xt(e,t,n){return U(B(e,t).turns,`${n}.json`)}import{randomBytes as cd}from"crypto";import{closeSync as ud,openSync as ld,readFileSync as pd,rmSync as fd,statSync as md,utimesSync as gd,writeSync as yd}from"fs";var $r=5e3,bn=2e4,nt={acquire(e,t){let n=ld(e,"wx",384);try{yd(n,t)}finally{ud(n)}},release(e){try{fd(e,{force:!0})}catch{}},age(e){try{return Date.now()-md(e).mtimeMs}catch{return null}},read(e){try{return pd(e,"utf8")}catch{return null}},touch(e){try{let t=new Date;gd(e,t,t)}catch{}},now:()=>Date.now()};function Vr(e,t=nt){let n=t.age(e);return n!==null&&n<=bn&&n>=-bn}function hd(e,t){return`${e} ${new Date(t).toISOString()} ${cd(8).toString("hex")}
11
+ `}function bt(e,t=nt,n=process.pid){let r=hd(n,t.now()),o=()=>{try{return t.acquire(e,r),!0}catch{return!1}};if(!o()&&(Vr(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<$r?!0:(s=i,t.read(e)!==r?!1:(t.touch(e),!0))},release(){t.read(e)===r&&t.release(e)}}}var rt=Object.freeze({v:1,dropped:Object.freeze({}),unknownKinds:Object.freeze({}),pepDecisions:Object.freeze({seen:0,filledToolUseId:0,orphaned:0}),projects:Object.freeze({})});function ot(){return{dropped:{},unknownKinds:{},pepDecisions:{seen:0,filledToolUseId:0,orphaned:0},projects:{}}}function In(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 ye(e,t){e[t]=(e[t]??0)+1}function st(e,t){let n=e.projects[t];if(n!==void 0)return n;let r={dropped:{}};return e.projects[t]=r,r}function ge(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vn(e){if(!ge(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 Kr(e){if(!ge(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 Fe(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}function Ct(e,t){return t!==void 0?{[e]:t}:{}}function vt(e,t){return e===void 0?void 0:e[t]}function Hr(e,t){if(e===void 0)return rt;let n;try{n=JSON.parse(e)}catch{return rt}if(!ge(n)||n.v!==1)return rt;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=Kr(u[t]),g=Fe(u.lastUploadAtMs);o[c]={...Ct(t,f),...g!==void 0?{lastUploadAtMs:g}:{},dropped:vn(u.dropped)}}let s=ge(n.lastError)?n.lastError:void 0,i=Fe(s?.atMs),a=Kr(n[t]),d=Fe(n.lastUploadAtMs);return{v:1,...d!==void 0?{lastUploadAtMs:d}:{},...i!==void 0&&typeof s?.message=="string"?{lastError:{atMs:i,message:s.message}}:{},dropped:vn(n.dropped),unknownKinds:vn(n.unknownKinds),pepDecisions:{seen:Fe(r.seen)??0,filledToolUseId:Fe(r.filledToolUseId)??0,orphaned:Fe(r.orphaned)??0},...Ct(t,a),projects:o}}function Wr(e){return`${JSON.stringify(e)}
12
+ `}function An(e,t,n,r=P){try{return Hr(r.readFile(B(e,t).senderState).toString("utf8"),n)}catch{return rt}}function kn(e,t,n,r=P){r.writeFileAtomic(B(e,t).senderState,Wr(n),ae)}function Cn(e,t){let n={...e};for(let[r,o]of Object.entries(t))n[r]=(n[r]??0)+o;return n}function Qr(e,t){return t===void 0?e:e===void 0||t.seenAtMs>=e.seenAtMs?t:e}function Gr(e,t){return t===void 0?e:e===void 0?t:Math.max(e,t)}function On(e,t,n){let r={...e.projects};for(let[a,d]of Object.entries(t.projects)){let c=r[a]??{},u=Qr(vt(c,n),vt(d,n)),f=Gr(c.lastUploadAtMs,d.lastUploadAtMs);r[a]={...Ct(n,u),...f!==void 0?{lastUploadAtMs:f}:{},dropped:Cn(c.dropped??{},d.dropped)}}let o=Object.values(t.projects).reduce((a,d)=>Qr(a,vt(d,n)),vt(e,n)),s=Gr(e.lastUploadAtMs,t.lastUploadAtMs),i=t.lastError??e.lastError;return{v:1,...s!==void 0?{lastUploadAtMs:s}:{},...i!==void 0?{lastError:i}:{},dropped:Cn(e.dropped,t.dropped),unknownKinds:Cn(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},...Ct(n,o),projects:r}}var _d=600*1e3,It=600*1e3,qr=1440*60*1e3,Sd={idleSweepMs:_d,orphanWindowMs:It,retentionMs:qr};function de(e,t){return`${e}\0${t??""}`}function Rd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Td(e){let t;try{t=JSON.parse(e)}catch{return}if(!(!Rd(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 Ed(e){return`${JSON.stringify(e)}
13
+ `}function Zr(e,t,n=P){let r=B(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=Td(n.readFile(d).toString("utf8"))}catch{c=void 0}c===void 0?i.push(d):s.push(c)}return{states:s,unreadable:i}}function it(e,t,n,r=P){r.writeFileAtomic(xt(e,t,n.traceId),Ed(n),ae)}function Dn(e,t,n,r=P){r.remove(xt(e,t,n))}function xd(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 bd(e){return[...e].sort((t,n)=>t.atMs-n.atMs||t.pid-n.pid||t.seq-n.seq||t.name.localeCompare(n.name))}function Jr(e,t,n=P,r,o=""){let s;try{s=n.readdir(e)}catch{return{files:[],other:[]}}let i=[],a=[];for(let d of s){let c=xd(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 g;try{g=t(n.readFile(`${e}/${d}`).toString("utf8"))}catch{g=void 0}let x={name:d,...c,entry:g};r?.set(u,x),i.push(x)}return{files:bd(i),other:a}}function vd(e,t,n,r,o){return{v:1,traceId:t,projectKey:e,conversationId:n,generationId:r,files:[],starts:{},sent:{},lastRecordAtMs:o}}function he(e){return e.records.reduce((t,n)=>Math.max(t,n.capturedAtMs),e.loaded.lastRecordAtMs)}function Xr(e,t){return e.records.find(n=>{if(!t.closesTurn(n))return!1;let r=t.turnOf(n);return r.conversationId!==null&&de(r.conversationId,r.generationId)===e.key})}function Yr(e,t,n){let r=Xr(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?he(e)>o.atMs:!0}function eo(e){let t=e.rules,n={...Sd,...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 T={key:de(m.conversationId,m.generationId),loaded:m,records:[],decisions:[],files:[]};r.push(T),o.set(T.key,T)}let u=(m,T)=>{s.add(T.name),m.files.push(T.name);let v=T.entry;v!==void 0&&(v.kind==="capture"?m.records.push(v):v.kind==="pep-decision"&&m.decisions.push(v))};for(let m of r)for(let T of m.loaded.files){let v=c.get(T);v!==void 0&&u(m,v)}for(let m of r)for(let T of m.records)zr(d,m,T,t);let f=(m,T)=>r.filter(v=>v.loaded.conversationId===m&&Yr(v,T,t)).sort((v,D)=>he(v)-he(D)).at(-1),g=m=>d.filter(T=>T.startAtMs<=m&&(T.stopAtMs===void 0||m<=T.stopAtMs)).sort((T,v)=>T.startAtMs-v.startAtMs).at(-1),x=(m,T)=>{let v=r.filter(D=>Yr(D,m.atMs,t)&&Math.abs(m.atMs-he(D))<=n.orphanWindowMs).sort((D,k)=>he(D)-he(k)).at(-1);if(v!==void 0){u(v,m);return}e.nowMs-m.atMs>=n.orphanWindowMs?a.push({file:m,reason:T}):i.push(m)};for(let m of e.files){if(s.has(m.name))continue;let T=m.entry;if(T===void 0){a.push({file:m,reason:"unreadable"});continue}if(T.kind==="unknown"){e.nowMs-m.atMs>=n.orphanWindowMs?a.push({file:m,reason:"unknown-kind"}):i.push(m);continue}if(T.kind==="pep-decision"){let O=t.decisionTurnOf(T),w=O.conversationId===null?void 0:o.get(de(O.conversationId,O.generationId));w!==void 0?u(w,m):e.nowMs-m.atMs>=n.orphanWindowMs?a.push({file:m,reason:"decision-orphan"}):i.push(m);continue}let v=T,D=t.subagentOf(v);if(D!==void 0){let O=D.parentConversationId,w=O===null?void 0:f(O,v.capturedAtMs);if(w===void 0){x(m,"orphan");continue}u(w,m),zr(d,w,v,t);continue}let k=t.turnOf(v);if(k.conversationId!==null){let O=o.get(de(k.conversationId,k.generationId));if(O!==void 0){u(O,m);continue}if(t.opensTurn(v)){let l=e.traceIdFor({conversationId:k.conversationId,generationId:k.generationId}),S={key:de(k.conversationId,k.generationId),loaded:vd(e.projectKey,l,k.conversationId,k.generationId,v.capturedAtMs),records:[],decisions:[],files:[]};r.push(S),o.set(S.key,S),u(S,m);continue}let w=g(v.capturedAtMs);if(w!==void 0){u(w.builder,m);continue}}x(m,"orphan")}return{turns:r.filter(m=>m.files.length>0||m.loaded.files.length>0).map(m=>Cd(m,e.nowMs,n,t)),pending:i,dropped:a,expired:[]}}function zr(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 Cd(e,t,n,r){let o=[...e.records].sort((c,u)=>c.capturedAtMs-u.capturedAtMs),s=he(e),i=Xr(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 to(e,t,n=qr){return e.filter(r=>r.files.length===0&&r.closed!==void 0&&t-r.lastRecordAtMs>=n)}var oo=35e5,Ad=new Set([400,413,422]),wn={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function Mn(e){return Id("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 so(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 io(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!==Mn(a)&&d?.startsWith("dropped:")!==!0&&(o.push(a),r[a.spanId]=a.startTimeUnixNano)}return{spans:o,starts:r}}function ao(e,t,n=oo){let r=[],o=[];for(let s of t){let i=[...o,s];if(Buffer.byteLength(JSON.stringify(Et({...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 At(e,t,n){ye(e.totals.dropped,n),ye(e.report,n),t!==void 0&&ye(st(e.totals,t).dropped,n)}async function kd(e,t,n){let r=async()=>(t.posts+=1,wr(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 Od(e,t,n,r){if(n.length===t.length)return!1;let o=new Set(n),s=de(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&&de(a.conversationId,a.generationId)===s})}function Dd(e){let{closed:t,...n}=e;return n}async function wd(e,t,n){let{adapter:r,deps:o,mem:s}=e,i=o.now(),a=Mr(n.records,n.decisions,r),d=r.holdBack(a.records,i),c=d.length!==a.records.length,u=n.state,f=Od(r,a.records,d,u)?Dd(u):u,g=f.closed===void 0;if(d.length===0)return u.closed===void 0||c?{state:u,sent:0,drained:!1,open:g}:no(e,t.project.orgId,u,n,a.filledToolUseId);let x=so(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&&(x={...x,usage:O})}let A=o.builder.build(x,{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:T,starts:v}=io(A.spans,u,m),D=0;for(let O of ao(A,T)){let w=await kd(o,t,Et({...A,spans:O}));if(w.ok){let l={...u.sent},S={...u.starts};for(let se of O)l[se.spanId]=Mn(se),S[se.spanId]=v[se.spanId]??se.startTimeUnixNano;u={...u,sent:l,starts:S},D+=O.length;let M=o.now();s.totals.lastUploadAtMs=M,st(s.totals,t.project.projectKey).lastUploadAtMs=M,it(o.home,r.stateDir,u,o.io);continue}if(w.status!==void 0&&Ad.has(w.status)){let l={...u.sent};for(let S of O)l[S.spanId]=`dropped:${w.status}`,At(s,t.project.projectKey,`rejected-${w.status}`);u={...u,sent:l},it(o.home,r.stateDir,u,o.io);continue}return{state:u,sent:D,drained:!1,open:g,fatal:w.status===401?"auth":"network",...w.error!==void 0?{error:w.error}:{}}}return u.closed!==void 0&&!c&&A.spans.every(O=>u.sent[O.spanId]!==void 0)?{...await no(e,t.project.orgId,u,n,a.filledToolUseId),sent:D}:{state:u,sent:D,drained:!1,open:g}}async function no(e,t,n,r,o){let{adapter:s,deps:i,mem:a}=e;await co(e,n.projectKey,t,r.decisions);let d={...n,files:[]};it(i.home,s.stateDir,d,i.io);let c=tt(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 co(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++)ye(e.mem.report,"outcome-queue-full")}catch{}}function Md(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=st(o.totals,t),a=i[r.versionKey];(a===void 0||s.seenAtMs>=a.seenAtMs)&&(i[r.versionKey]=s)}function Nd(e,t,n){let{deps:r,mem:o}=e,s=`${n}/${xn}`,i=`${s}.${r.pid}.${r.now()}`;if(r.claimFile(s,i)){try{for(let a of r.io.readFile(i).toString("utf8"))At(o,t,Br(a))}catch{}r.io.remove(i)}}function Pd(e,t){let n=/^\.(\d+)-\d+-\d+\.json\./.exec(e);if(!(n===null||!e.endsWith(".tmp")))return t-Number(n[1])}function ro(e){let{adapter:t,deps:n,mem:r}=e;if(!In(r.totals))try{if(!n.io.exists(B(n.home,t.stateDir).projects)){r.totals=ot();return}kn(n.home,t.stateDir,On(An(n.home,t.stateDir,t.versionKey,n.io),r.totals,t.versionKey),n.io),r.totals=ot()}catch{}}function uo(e,t,n){try{return n.readdir(B(e,t).queue)}catch{return[]}}async function Ud(e,t){let{adapter:n,deps:r,mem:o}=e,s=r.now(),i=r.credentials();if(i===null)return jd(s,{fatal:"credentials"});let a=n.readRegistry(r.home,r.io),d=0,c=0,u=0,f=0,g=!1,x,A;for(let m of uo(r.home,n.stateDir,r.io)){let T=tt(r.home,n.stateDir,m),{files:v,other:D}=Jr(T,l=>n.parseQueueEntry(l),r.io,o.cache,T);D.includes(xn)&&Nd(e,m,T);for(let l of D){let S=Pd(l,s);S!==void 0&&S>=It&&r.io.remove(`${T}/${l}`)}if(v.length===0)continue;for(let l of v)u=Math.max(u,l.atMs);Md(e,m,v);let k=eo({projectKey:m,files:v,states:[...o.states.values()],nowMs:s,traceIdFor:l=>r.builder.traceId(l),...t.closeOpenTurns===!0?{limits:{idleSweepMs:0}}:{},rules:n}),O=a.kind==="ok"?a.registry.projects[m]:void 0;for(let{file:l,reason:S}of k.dropped){At(o,m,S);let M=l.entry;M?.kind==="unknown"&&ye(o.totals.unknownKinds,M.rawKind),S==="decision-orphan"&&(o.totals.pepDecisions.orphaned+=1,o.totals.pepDecisions.seen+=1,O!==void 0&&M?.kind==="pep-decision"&&await co(e,m,O.orgId,[M])),r.io.remove(`${T}/${l.name}`),o.cache.delete(`${T}/${l.name}`)}if(d+=k.pending.length,O===void 0){if(d+=k.turns.reduce((l,S)=>l+S.files.length,0),a.kind==="ok"){for(let l of k.turns)if(!(s-l.state.lastRecordAtMs<It)){for(let S of l.files)At(o,m,"unregistered"),r.io.remove(`${T}/${S}`),o.cache.delete(`${T}/${S}`);o.states.delete(l.state.traceId),Dn(r.home,n.stateDir,l.state.traceId,r.io)}}continue}let w={project:O,credentials:i,posts:o.posts};for(let l of k.turns){let S;try{S=await wd(e,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)},Ld(e,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(`${T}/${M}`);else d+=l.files.length,S.open&&(c+=1);if(S.fatal!==void 0){g=!0,A=S.error??A,o.totals.lastError={atMs:r.now(),message:S.error??(S.fatal==="auth"?"not signed in":"upload failed")},S.fatal==="auth"&&(x="auth");break}}if(o.posts=w.posts,i=w.credentials,x!==void 0)break}return{entries:d,openTurns:c,newestRecordMs:u,sent:f,failed:g,...x!==void 0?{fatal:x}:{},...A!==void 0?{error:A}:{}}}function jd(e,t={}){return{entries:0,openTurns:0,newestRecordMs:e,sent:0,failed:!1,...t}}function Ld(e,t){try{it(e.deps.home,e.adapter.stateDir,t,e.deps.io)}catch{}}function Fd(e,t,n){for(let r of uo(e,t,n))try{if(n.readdir(tt(e,t,r)).some(s=>s.endsWith(".json")&&!s.startsWith(".")))return!0}catch{}return!1}function Bd(e,t,n,r){return e.failed?r:e.openTurns===0?t.pollIdleMs:n-e.newestRecordMs<=t.flowWindowMs?t.pollFlowingMs:t.pollOpenMs}async function lo(e,t,n={}){let r=B(t.home,e.stateDir),o=bt(r.senderLock,t.lockIO,t.pid);if(o===void 0)return{outcome:"locked",cycles:0,posts:0,spansSent:0,dropped:{}};let s=Zr(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:ot(),report:{},scrubbers:yn(Tt),posts:0},a={adapter:e,deps:t,mem:i},d=t.now(),c="done",u=0,f=0,g,x,A=t.limits.backoffMs;try{for(;;){if(!o.heartbeat()){c="lost-lock";break}let m=await Ud(a,n);u+=1,f+=m.sent,g=m.error??g,ro(a);for(let T of to([...i.states.values()],t.now()))Dn(t.home,e.stateDir,T.traceId,t.io),i.states.delete(T.traceId);if(m.fatal==="credentials"){c="no-credentials";break}if(m.failed){if(x??=t.now(),m.fatal==="auth"||t.now()-x>=t.limits.giveUpMs){c="send-failed";break}}else x=void 0,A=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,!Fd(t.home,e.stateDir,t.io)||(o=bt(r.senderLock,t.lockIO,t.pid),o===void 0))break;continue}await t.sleep(Bd(m,t.limits,t.now(),A)),m.failed&&(A=Math.min(A*2,t.limits.pollIdleMs*12))}}finally{ro(a),o?.release()}return{outcome:c,cycles:u,posts:i.posts,spansSent:f,dropped:i.report,...g!==void 0?{lastError:g}:{}}}function po(e,t,n){try{let r=JSON.parse(n.readFile(B(e,t).install).toString("utf8"));return typeof r.cliVersion=="string"?r.cliVersion:void 0}catch{return}}import{createHash as rc}from"crypto";import{join as ig}from"path";var $d="cursor",kt="cursor",_e="cursor",fo={agent:$d,vendor:kt,stateDir:_e};function Ot(e){return B(e,_e)}import{constants as dt,promises as at}from"fs";import{dirname as Vd,isAbsolute as go,join as wt}from"path";var Kd=2e3,Qd=1e3,mg=et.maxOutcomes;var Gd=10*6e4,Hd=864e5,yo=et.maxAgeDays*Hd,Wd=et.maxFutureMinutes*6e4,Yd=255,zd=128,qd=448,Zd=384,Jd=dt.O_NOFOLLOW??0,gg=dt.O_NONBLOCK??0,Xd=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/,Nn="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",ec=new RegExp(`^(\\d{15})-(${Nn})-(${Nn})\\.json$`),tc=new RegExp(`^\\.tmp-(\\d{15})-(${Nn})$`),ho={mkdir:(e,t)=>at.mkdir(e,t),readdir:e=>at.readdir(e),open:(e,t,n)=>at.open(e,t,n),rename:(e,t)=>at.rename(e,t),unlink:e=>at.unlink(e)};function _o(e){return wt(Vd(e),"pending-outcomes")}function mo(e){if(typeof e!="string")return;let t=e.toLowerCase();return Xd.test(t)?t:void 0}function Dt(e,t=Yd){return typeof e=="string"&&e.length>0&&e.length<=t?e:void 0}function Be(e,t){return e.includes(t)?t:void 0}function Pn(e,t=new Date){if(typeof e!="object"||e===null||Array.isArray(e))return;let n=e,r=mo(n.id),o=mo(n.org_id),s=yt(n.vendor)?n.vendor:void 0,i=Dt(n.session_id),a=Dt(n.correlation_id),d=Dt(n.tool_name),c=Be(hn,n.decided_via),u=Be(Sn,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 f=typeof n.decided_at=="string"?Date.parse(n.decided_at):Number.NaN;if(!Number.isFinite(f))return;let g=t.getTime();if(f<g-yo||f>g+Wd)return;let x;if(n.snapshot_age_seconds!==void 0){let k=n.snapshot_age_seconds;if(typeof k!="number"||!Number.isSafeInteger(k)||k<0)return;x=k}let A;if(n.fail_mode!==void 0&&(A=Be(["open","closed"],n.fail_mode),A===void 0))return;let m=n.fallback_cause===void 0?void 0:Be(En,n.fallback_cause);if(n.fallback_cause!==void 0&&m===void 0)return;let T={id:r,org_id:o,vendor:s,session_id:i,correlation_id:a,tool_name:d,answer:u,...x!==void 0?{snapshot_age_seconds:x}:{},...A!==void 0?{fail_mode:A}:{},decided_at:new Date(f).toISOString()};if(c==="snapshot"){let k=Be(_n,n.verdict),O=Dt(n.snapshot_version,zd);return k===void 0||O===void 0||m===void 0||n.cause!==void 0?void 0:{...T,decided_via:c,verdict:k,fallback_cause:m,snapshot_version:O}}let v=Be(Rn,n.cause);if(!(v===void 0||n.verdict!==void 0||n.snapshot_version!==void 0||Tn.includes(v)!==(m!==void 0)))return{...T,decided_via:c,cause:v,...m!==void 0?{fallback_cause:m}:{}}}function nc(e){return`${String(Date.parse(e.decided_at)).padStart(15,"0")}-${e.org_id}-${e.id}.json`}function So(e){let t=ec.exec(e);if(t!==null)return{decidedMs:Number(t[1]),orgId:t[2],id:t[3]}}async function Ro(e,t){try{return await e.readdir(t)}catch{return}}async function To(e,t){try{return await e.unlink(t),!0}catch{return!1}}async function Eo(e,t,n={}){let r=n.fs??ho,o=n.now??new Date;if(!go(e))return"failed";let s=Pn(t,o);if(s===void 0)return"invalid";let i;try{await r.mkdir(e,{recursive:!0,mode:qd});let a=await Ro(r,e);if(a===void 0)return"failed";let d=0,c=0;for(let x of a){let A=So(x);A!==void 0&&(d++,A.orgId===s.org_id&&c++)}if(d>=Kd||c>=Qd)return"queue_full";let u=String(o.getTime()).padStart(15,"0"),f=wt(e,`.tmp-${u}-${s.id}`),g=await r.open(f,dt.O_WRONLY|dt.O_CREAT|dt.O_EXCL|Jd,Zd);i=f;try{await g.writeFile(JSON.stringify(s),"utf8")}finally{await g.close()}return await r.rename(f,wt(e,nc(s))),"queued"}catch{return i!==void 0&&await To(r,i),"failed"}}async function xo(e,t={}){let n=t.fs??ho,r=(t.now??new Date).getTime();if(!go(e))return 0;let o=await Ro(n,e);if(o===void 0)return 0;let s=0;for(let i of o){let a=So(i),d;if(a!==void 0)d=a.decidedMs<r-yo;else{let c=tc.exec(i);d=c===null||Number(c[1])<r-Gd}d&&await To(n,wt(e,i))&&s++}return s}var oc=new Set(["preToolUse","beforeMCPExecution"]);function sc(e){if(!oc.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 ic(e,t){let n=rc("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 ac(e,t){let n=sc(e);if(n.kind==="skip")return{skip:n.reason};let r={id:ic(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=Pn(o,t.now??new Date);return s===void 0?{skip:"invalid"}:{item:s}}function dc(e){return _o(Ot(e).pepSnapshot)}async function cc(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=ac(i,{orgId:e.orgId,projectKey:e.projectKey,now:s})}catch{a={skip:"invalid"}}if("skip"in a){r++;continue}let d=await Eo(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=dc(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 xo(n,{now:s,...i})),cc({dir:n,...o,now:s,...i})}}import{createHash as bg}from"crypto";var Un="MCP:";var ct="user_prompt",fc="gen_ai.completion",q="full_command",$e="file_path",Se="gen_ai.tool.call.result",ut=new Set([ct,fc,q,$e,Se]);var Mt="secret-manager-output",Nt=`[REDACTED:secret:${Mt}]`,mc=[/^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|$)/],gc=/&&|\|\||;|\|/,yc=/^(?:[A-Za-z_][A-Za-z0-9_]*=\S*\s+)+/;function hc(e){let t=e.trimStart().replace(yc,"");return mc.some(n=>n.test(t))}function _c(e){if(e.length===0)return!1;for(let t of e.split(gc))if(hc(t))return!0;return!1}var Sc=new Set;function Io(e,t){let n=e[t.commandKey];if(typeof n!="string"||!_c(n))return Sc;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 Rc={commandKey:q,resultKeys:new Set([Se])};function Ao(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=Io(n.correlationCommand===void 0?e:{...e,[q]:n.correlationCommand},Rc);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]=Nt,o[Mt]=(o[Mt]??0)+1,s+=1;continue}if(!ut.has(a)){r[a]=d;continue}let c=Ar(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 Pt=8192;var Oo=16*1024,ko=Pt+Oo;function jn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Tc(e){return e.length>Pt?e.slice(0,Pt):e}function Ec(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 Do(e,t){let n={},r=new Map;for(let[a,d]of Object.entries(e))if(ut.has(a)&&d.length>ko){let c=d.slice(0,ko);n[a]=c,r.set(a,c)}else n[a]=d;let o=e[q],s=Ao(n,t,o===void 0?{}:{correlationCommand:o}),i={};for(let[a,d]of Object.entries(s.attributes)){if(!ut.has(a)){i[a]=d;continue}let c=r.get(a),u=d;if(c!==void 0&&u!==Nt){let f=Math.min(Oo,Ec(c,u));u=u.slice(0,u.length-f)}i[a]=Tc(u)}return{attributes:i,redactedCount:s.redactedCount,byType:s.byType}}function xc(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:jn(n)&&typeof n.vendorTool=="string"&&typeof n.argsHash=="string"&&jn(n.call)&&typeof n.call.tool=="string"}function bc(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 wo(e,t){let n;try{n=JSON.parse(e)}catch{return}if(!jn(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"&&xc(r,t)||r.kind==="pep-decision"&&bc(r)?r:o()}import{createHmac as zg,randomBytes as qg}from"crypto";var Mo=Object.freeze(["beforeSubmitPrompt","postToolUse","postToolUseFailure","afterMCPExecution","afterAgentResponse","afterFileEdit","subagentStart","subagentStop","stop"]);var Cc=new Set(Mo);function No(e){return wo(e,Cc)}function Ut(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Po(e){return typeof e=="string"&&e!==""}function Ic(e,t){if(!Ut(t))return{key:e};let n=Po(t.root)?t.root:void 0,r=Array.isArray(t.subfolders)?t.subfolders.map(o=>Ut(o)&&Po(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 Ac(e,t){let n;try{n=JSON.parse(e)}catch{return}if(!Ut(n)||n.v!==1||!Ut(n.projects))return;let r={},o=[];for(let[s,i]of Object.entries(n.projects))t(s,i)?r[s]=i:o.push(Ic(s,i));return{registry:{v:1,projects:r},skipped:o}}var kc=Object.freeze({v:1,projects:Object.freeze({})});function Uo(e,t,n=P){let r;try{if(!n.exists(e))return{kind:"missing"};r=n.readFile(e).toString("utf8")}catch{return{kind:"unreadable"}}let o=Ac(r,t);return o===void 0?{kind:"unreadable"}:{kind:"ok",registry:o.registry,skipped:o.skipped}}function jo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ee(e){return typeof e=="string"&&e!==""}function Lo(e){return e==="project"||e==="user"}var Oc=new Set(["flag","agenttrail-json","derived"]);function Dc(e){return jo(e)&&ee(e.path)&&ee(e.transcriptFolder)&&Lo(e.install)&&ee(e.registeredAt)}function wc(e,t){return jo(t)?t.projectKey===e&&ee(t.root)&&ee(t.transcriptFolder)&&ee(t.orgId)&&ee(t.projectSlug)&&ee(t.projectId)&&Oc.has(t.projectSource)&&typeof t.projectLabel=="string"&&(t.developerId===void 0||typeof t.developerId=="string")&&typeof t.captureContent=="boolean"&&Lo(t.install)&&ee(t.registeredAt)&&(t.subfolders===void 0||Array.isArray(t.subfolders)&&t.subfolders.every(Dc)):!1}function Fo(e,t=P){return Uo(Ot(e).projects,wc,t)}var Bo="cursorVersion";import{createHash as Ju}from"crypto";var $o=/^(?:[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 Mc(e){return typeof e=="string"&&$o.test(e)}var Vo=Mc;var j=[];for(let e=0;e<256;++e)j.push((e+256).toString(16).slice(1));function Ko(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 Nc(e){if(!Vo(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 Qo=Nc;function Pc(e){e=unescape(encodeURIComponent(e));let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var Uc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",jc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Ln(e,t,n){function r(o,s,i,a){var d;if(typeof o=="string"&&(o=Pc(o)),typeof s=="string"&&(s=Qo(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 Ko(c)}try{r.name=e}catch{}return r.DNS=Uc,r.URL=jc,r}import Lc from"crypto";function Fc(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),Lc.createHash("sha1").update(e).digest()}var Go=Fc;var Bc=Ln("v5",80,Go),jt=Bc;var fe={};ks(fe,{BRAND:()=>pu,DIRTY:()=>Re,EMPTY_PATH:()=>Qc,INVALID:()=>R,NEVER:()=>qu,OK:()=>F,ParseStatus:()=>L,Schema:()=>C,ZodAny:()=>le,ZodArray:()=>oe,ZodBigInt:()=>Ee,ZodBoolean:()=>xe,ZodBranded:()=>pt,ZodCatch:()=>Ne,ZodDate:()=>be,ZodDefault:()=>Me,ZodDiscriminatedUnion:()=>Bt,ZodEffects:()=>Y,ZodEnum:()=>De,ZodError:()=>V,ZodFirstPartyTypeKind:()=>E,ZodFunction:()=>Vt,ZodIntersection:()=>Ae,ZodIssueCode:()=>p,ZodLazy:()=>ke,ZodLiteral:()=>Oe,ZodMap:()=>We,ZodNaN:()=>ze,ZodNativeEnum:()=>we,ZodNever:()=>z,ZodNull:()=>Ce,ZodNullable:()=>X,ZodNumber:()=>Te,ZodObject:()=>K,ZodOptional:()=>H,ZodParsedType:()=>h,ZodPipeline:()=>ft,ZodPromise:()=>pe,ZodReadonly:()=>Pe,ZodRecord:()=>$t,ZodSchema:()=>C,ZodSet:()=>Ye,ZodString:()=>ue,ZodSymbol:()=>Ge,ZodTransformer:()=>Y,ZodTuple:()=>J,ZodType:()=>C,ZodUndefined:()=>ve,ZodUnion:()=>Ie,ZodUnknown:()=>re,ZodVoid:()=>He,addIssueToContext:()=>y,any:()=>Tu,array:()=>vu,bigint:()=>yu,boolean:()=>ns,coerce:()=>zu,custom:()=>Xo,date:()=>hu,datetimeRegex:()=>Zo,defaultErrorMap:()=>te,discriminatedUnion:()=>ku,effect:()=>$u,enum:()=>Lu,function:()=>Pu,getErrorMap:()=>Ve,getParsedType:()=>Z,instanceof:()=>mu,intersection:()=>Ou,isAborted:()=>Lt,isAsync:()=>Ke,isDirty:()=>Ft,isValid:()=>ce,late:()=>fu,lazy:()=>Uu,literal:()=>ju,makeIssue:()=>lt,map:()=>Mu,nan:()=>gu,nativeEnum:()=>Fu,never:()=>xu,null:()=>Ru,nullable:()=>Ku,number:()=>ts,object:()=>Cu,objectUtil:()=>Fn,oboolean:()=>Yu,onumber:()=>Wu,optional:()=>Vu,ostring:()=>Hu,pipeline:()=>Gu,preprocess:()=>Qu,promise:()=>Bu,quotelessJson:()=>$c,record:()=>wu,set:()=>Nu,setErrorMap:()=>Kc,strictObject:()=>Iu,string:()=>es,symbol:()=>_u,transformer:()=>$u,tuple:()=>Du,undefined:()=>Su,union:()=>Au,unknown:()=>Eu,util:()=>I,void:()=>bu});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 Fn;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Fn||(Fn={}));var h=I.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Z=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 p=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"]),$c=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 Vc=(e,t)=>{let n;switch(e.code){case p.invalid_type:e.received===h.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case p.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,I.jsonStringifyReplacer)}`;break;case p.unrecognized_keys:n=`Unrecognized key(s) in object: ${I.joinValues(e.keys,", ")}`;break;case p.invalid_union:n="Invalid input";break;case p.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${I.joinValues(e.options)}`;break;case p.invalid_enum_value:n=`Invalid enum value. Expected ${I.joinValues(e.options)}, received '${e.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 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 p.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 p.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 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 ${e.multipleOf}`;break;case p.not_finite:n="Number must be finite";break;default:n=t.defaultError,I.assertNever(e)}return{message:n}},te=Vc;var Ho=te;function Kc(e){Ho=e}function Ve(){return Ho}var lt=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}},Qc=[];function y(e,t){let n=Ve(),r=lt({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===te?void 0:te].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 R;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 R;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}}},R=Object.freeze({status:"aborted"}),Re=e=>({status:"dirty",value:e}),F=e=>({status:"valid",value:e}),Lt=e=>e.status==="aborted",Ft=e=>e.status==="dirty",ce=e=>e.status==="valid",Ke=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 W=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}},Wo=(e,t)=>{if(ce(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 b(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 C=class{get description(){return this._def.description}_getType(t){return Z(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:Z(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:Z(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ke(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:Z(t)},o=this._parseSync({data:t,path:r.path,parent:r});return Wo(r,o)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Z(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,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:t,path:[],parent:n}).then(r=>ce(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:Z(t)},o=this._parse({data:t,path:r.path,parent:r}),s=await(Ke(o)?o:Promise.resolve(o));return Wo(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:p.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:E.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 H.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(t){return Ie.create([this,t],this._def)}and(t){return Ae.create(this,t,this._def)}transform(t){return new Y({...b(this._def),schema:this,typeName:E.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new Me({...b(this._def),innerType:this,defaultValue:n,typeName:E.ZodDefault})}brand(){return new pt({typeName:E.ZodBranded,type:this,...b(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new Ne({...b(this._def),innerType:this,catchValue:n,typeName:E.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return ft.create(this,t)}readonly(){return Pe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Gc=/^c[^\s-]{8,}$/i,Hc=/^[0-9a-z]+$/,Wc=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yc=/^[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,zc=/^[a-z0-9_-]{21}$/i,qc=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Zc=/^[-+]?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)?)??$/,Jc=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xc="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Bn,eu=/^(?:(?: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])$/,tu=/^(?:(?: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])$/,nu=/^(([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]))$/,ru=/^(([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])$/,ou=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,su=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,zo="((\\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])))",iu=new RegExp(`^${zo}$`);function qo(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 au(e){return new RegExp(`^${qo(e)}$`)}function Zo(e){let t=`${zo}T${qo(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 du(e,t){return!!((t==="v4"||!t)&&eu.test(e)||(t==="v6"||!t)&&nu.test(e))}function cu(e,t){if(!qc.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 uu(e,t){return!!((t==="v4"||!t)&&tu.test(e)||(t==="v6"||!t)&&ru.test(e))}var ue=class e extends C{_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:p.invalid_type,expected:h.string,received:s.parsedType}),R}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:p.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:p.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:p.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&y(o,{code:p.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")Jc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"email",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Bn||(Bn=new RegExp(Xc,"u")),Bn.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"emoji",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")Yc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"uuid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")zc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"nanoid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")Gc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"cuid",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")Hc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"cuid2",code:p.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")Wc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"ulid",code:p.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:p.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:p.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:p.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:p.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:p.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?Zo(s).test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{code:p.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?iu.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{code:p.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?au(s).test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{code:p.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?Zc.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"duration",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?du(t.data,s.version)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"ip",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?cu(t.data,s.alg)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"jwt",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?uu(t.data,s.version)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"cidr",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?ou.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"base64",code:p.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?su.test(t.data)||(o=this._getOrReturnCtx(t,o),y(o,{validation:"base64url",code:p.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:p.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}};ue.create=e=>new ue({checks:[],typeName:E.ZodString,coerce:e?.coerce??!1,...b(e)});function lu(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 Te=class e extends C{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:p.invalid_type,expected:h.number,received:s.parsedType}),R}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:p.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:p.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:p.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?lu(t.data,s.value)!==0&&(r=this._getOrReturnCtx(t,r),y(r,{code:p.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:p.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)}};Te.create=e=>new Te({checks:[],typeName:E.ZodNumber,coerce:e?.coerce||!1,...b(e)});var Ee=class e extends C{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:p.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:p.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:p.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:p.invalid_type,expected:h.bigint,received:n.parsedType}),R}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}};Ee.create=e=>new Ee({checks:[],typeName:E.ZodBigInt,coerce:e?.coerce??!1,...b(e)});var xe=class extends C{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==h.boolean){let r=this._getOrReturnCtx(t);return y(r,{code:p.invalid_type,expected:h.boolean,received:r.parsedType}),R}return F(t.data)}};xe.create=e=>new xe({typeName:E.ZodBoolean,coerce:e?.coerce||!1,...b(e)});var be=class e extends C{_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:p.invalid_type,expected:h.date,received:s.parsedType}),R}if(Number.isNaN(t.data.getTime())){let s=this._getOrReturnCtx(t);return y(s,{code:p.invalid_date}),R}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:p.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:p.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}};be.create=e=>new be({checks:[],coerce:e?.coerce||!1,typeName:E.ZodDate,...b(e)});var Ge=class extends C{_parse(t){if(this._getType(t)!==h.symbol){let r=this._getOrReturnCtx(t);return y(r,{code:p.invalid_type,expected:h.symbol,received:r.parsedType}),R}return F(t.data)}};Ge.create=e=>new Ge({typeName:E.ZodSymbol,...b(e)});var ve=class extends C{_parse(t){if(this._getType(t)!==h.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:p.invalid_type,expected:h.undefined,received:r.parsedType}),R}return F(t.data)}};ve.create=e=>new ve({typeName:E.ZodUndefined,...b(e)});var Ce=class extends C{_parse(t){if(this._getType(t)!==h.null){let r=this._getOrReturnCtx(t);return y(r,{code:p.invalid_type,expected:h.null,received:r.parsedType}),R}return F(t.data)}};Ce.create=e=>new Ce({typeName:E.ZodNull,...b(e)});var le=class extends C{constructor(){super(...arguments),this._any=!0}_parse(t){return F(t.data)}};le.create=e=>new le({typeName:E.ZodAny,...b(e)});var re=class extends C{constructor(){super(...arguments),this._unknown=!0}_parse(t){return F(t.data)}};re.create=e=>new re({typeName:E.ZodUnknown,...b(e)});var z=class extends C{_parse(t){let n=this._getOrReturnCtx(t);return y(n,{code:p.invalid_type,expected:h.never,received:n.parsedType}),R}};z.create=e=>new z({typeName:E.ZodNever,...b(e)});var He=class extends C{_parse(t){if(this._getType(t)!==h.undefined){let r=this._getOrReturnCtx(t);return y(r,{code:p.invalid_type,expected:h.void,received:r.parsedType}),R}return F(t.data)}};He.create=e=>new He({typeName:E.ZodVoid,...b(e)});var oe=class e extends C{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),o=this._def;if(n.parsedType!==h.array)return y(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)&&(y(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&&(y(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&&(y(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 W(n,i,n.path,a)))).then(i=>L.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new W(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)}};oe.create=(e,t)=>new oe({type:e,minLength:null,maxLength:null,exactLength:null,typeName:E.ZodArray,...b(t)});function Qe(e){if(e instanceof K){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=H.create(Qe(r))}return new K({...e._def,shape:()=>t})}else return e instanceof oe?new oe({...e._def,type:Qe(e.element)}):e instanceof H?H.create(Qe(e.unwrap())):e instanceof X?X.create(Qe(e.unwrap())):e instanceof J?J.create(e.items.map(t=>Qe(t))):e}var K=class e extends C{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:p.invalid_type,expected:h.object,received:c.parsedType}),R}let{status:r,ctx:o}=this._processInputParams(t),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof z&&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 W(o,f,o.path,c)),alwaysSet:c in o.data})}if(this._def.catchall instanceof z){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: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 W(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,g=await u.value;c.push({key:f,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:E.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 Qe(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 H;)s=s._def.innerType;n[r]=s}return new e({...this._def,shape:()=>n})}keyof(){return Jo(I.objectKeys(this.shape))}};K.create=(e,t)=>new K({shape:()=>e,unknownKeys:"strip",catchall:z.create(),typeName:E.ZodObject,...b(t)});K.strictCreate=(e,t)=>new K({shape:()=>e,unknownKeys:"strict",catchall:z.create(),typeName:E.ZodObject,...b(t)});K.lazycreate=(e,t)=>new K({shape:e,unknownKeys:"strip",catchall:z.create(),typeName:E.ZodObject,...b(t)});var Ie=class extends C{_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: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 y(n,{code:p.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};Ie.create=(e,t)=>new Ie({options:e,typeName:E.ZodUnion,...b(t)});var ne=e=>e instanceof ke?ne(e.schema):e instanceof Y?ne(e.innerType()):e instanceof Oe?[e.value]:e instanceof De?e.options:e instanceof we?I.objectValues(e.enum):e instanceof Me?ne(e._def.innerType):e instanceof ve?[void 0]:e instanceof Ce?[null]:e instanceof H?[void 0,...ne(e.unwrap())]:e instanceof X?[null,...ne(e.unwrap())]:e instanceof pt||e instanceof Pe?ne(e.unwrap()):e instanceof Ne?ne(e._def.innerType):[],Bt=class e extends C{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==h.object)return y(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}):(y(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(t,n,r){let o=new Map;for(let s of n){let i=ne(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:E.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:o,...b(r)})}};function $n(e,t){let n=Z(e),r=Z(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=$n(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=$n(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 C{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),o=(s,i)=>{if(Lt(s)||Lt(i))return R;let a=$n(s.value,i.value);return a.valid?((Ft(s)||Ft(i))&&n.dirty(),{status:n.value,value:a.data}):(y(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=(e,t,n)=>new Ae({left:e,right:t,typeName:E.ZodIntersection,...b(n)});var J=class e extends C{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==h.array)return y(r,{code:p.invalid_type,expected:h.array,received:r.parsedType}),R;if(r.data.length<this._def.items.length)return y(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&&(y(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 W(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})}};J.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new J({items:e,typeName:E.ZodTuple,rest:null,...b(t)})};var $t=class e extends C{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: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 W(r,a,r.path,a)),value:i._parse(new W(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 C?new e({keyType:t,valueType:n,typeName:E.ZodRecord,...b(r)}):new e({keyType:ue.create(),valueType:t,typeName:E.ZodRecord,...b(n)})}},We=class extends C{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: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 W(r,a,r.path,[c,"key"])),value:s._parse(new W(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}}}};We.create=(e,t,n)=>new We({valueType:t,keyType:e,typeName:E.ZodMap,...b(n)});var Ye=class e extends C{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==h.set)return y(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&&(y(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&&(y(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 W(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)}};Ye.create=(e,t)=>new Ye({valueType:e,minSize:null,maxSize:null,typeName:E.ZodSet,...b(t)});var Vt=class e extends C{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==h.function)return y(n,{code:p.invalid_type,expected:h.function,received:n.parsedType}),R;function r(a,d){return lt({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ve(),te].filter(c=>!!c),issueData:{code:p.invalid_arguments,argumentsError:d}})}function o(a,d){return lt({data:a,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ve(),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 F(async function(...d){let c=new V([]),u=await a._def.args.parseAsync(d,s).catch(x=>{throw c.addIssue(r(d,x)),c}),f=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(f,s).catch(x=>{throw c.addIssue(o(f,x)),c})})}else{let a=this;return F(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(...t){return new e({...this._def,args:J.create(t).rest(re.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||J.create([]).rest(re.create()),returns:n||re.create(),typeName:E.ZodFunction,...b(r)})}},ke=class extends C{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})}};ke.create=(e,t)=>new ke({getter:e,typeName:E.ZodLazy,...b(t)});var Oe=class extends C{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return y(n,{received:n.data,code:p.invalid_literal,expected:this._def.value}),R}return{status:"valid",value:t.data}}get value(){return this._def.value}};Oe.create=(e,t)=>new Oe({value:e,typeName:E.ZodLiteral,...b(t)});function Jo(e,t){return new De({values:e,typeName:E.ZodEnum,...b(t)})}var De=class e extends C{_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:p.invalid_type}),R}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:p.invalid_enum_value,options:r}),R}return F(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})}};De.create=Jo;var we=class extends C{_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:p.invalid_type}),R}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:p.invalid_enum_value,options:o}),R}return F(t.data)}get enum(){return this._def.values}};we.create=(e,t)=>new we({values:e,typeName:E.ZodNativeEnum,...b(t)});var pe=class extends C{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:p.invalid_type,expected:h.promise,received:n.parsedType}),R;let r=n.parsedType===h.promise?n.data:Promise.resolve(n.data);return F(r.then(o=>this._def.type.parseAsync(o,{path:n.path,errorMap:n.common.contextualErrorMap})))}};pe.create=(e,t)=>new pe({type:e,typeName:E.ZodPromise,...b(t)});var Y=class extends C{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===E.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 R;let d=await this._def.schema._parseAsync({data:a,path:r.path,parent:r});return d.status==="aborted"?R:d.status==="dirty"?Re(d.value):n.value==="dirty"?Re(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"?Re(a.value):n.value==="dirty"?Re(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);I.assertNever(o)}};Y.create=(e,t,n)=>new Y({schema:e,typeName:E.ZodEffects,effect:t,...b(n)});Y.createWithPreprocess=(e,t,n)=>new Y({schema:t,effect:{type:"preprocess",transform:e},typeName:E.ZodEffects,...b(n)});var H=class extends C{_parse(t){return this._getType(t)===h.undefined?F(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};H.create=(e,t)=>new H({innerType:e,typeName:E.ZodOptional,...b(t)});var X=class extends C{_parse(t){return this._getType(t)===h.null?F(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};X.create=(e,t)=>new X({innerType:e,typeName:E.ZodNullable,...b(t)});var Me=class extends C{_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}};Me.create=(e,t)=>new Me({innerType:e,typeName:E.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...b(t)});var Ne=class extends C{_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 Ke(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}};Ne.create=(e,t)=>new Ne({innerType:e,typeName:E.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...b(t)});var ze=class extends C{_parse(t){if(this._getType(t)!==h.nan){let r=this._getOrReturnCtx(t);return y(r,{code:p.invalid_type,expected:h.nan,received:r.parsedType}),R}return{status:"valid",value:t.data}}};ze.create=e=>new ze({typeName:E.ZodNaN,...b(e)});var pu=Symbol("zod_brand"),pt=class extends C{_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}},ft=class e extends C{_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"?R:s.status==="dirty"?(n.dirty(),Re(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(t,n){return new e({in:t,out:n,typeName:E.ZodPipeline})}},Pe=class extends C{_parse(t){let n=this._def.innerType._parse(t),r=o=>(ce(o)&&(o.value=Object.freeze(o.value)),o);return Ke(n)?n.then(o=>r(o)):r(n)}unwrap(){return this._def.innerType}};Pe.create=(e,t)=>new Pe({innerType:e,typeName:E.ZodReadonly,...b(t)});function Yo(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function Xo(e,t={},n){return e?le.create().superRefine((r,o)=>{let s=e(r);if(s instanceof Promise)return s.then(i=>{if(!i){let a=Yo(t,r),d=a.fatal??n??!0;o.addIssue({code:"custom",...a,fatal:d})}});if(!s){let i=Yo(t,r),a=i.fatal??n??!0;o.addIssue({code:"custom",...i,fatal:a})}}):le.create()}var fu={object:K.lazycreate},E;(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"})(E||(E={}));var mu=(e,t={message:`Input not instance of ${e.name}`})=>Xo(n=>n instanceof e,t),es=ue.create,ts=Te.create,gu=ze.create,yu=Ee.create,ns=xe.create,hu=be.create,_u=Ge.create,Su=ve.create,Ru=Ce.create,Tu=le.create,Eu=re.create,xu=z.create,bu=He.create,vu=oe.create,Cu=K.create,Iu=K.strictCreate,Au=Ie.create,ku=Bt.create,Ou=Ae.create,Du=J.create,wu=$t.create,Mu=We.create,Nu=Ye.create,Pu=Vt.create,Uu=ke.create,ju=Oe.create,Lu=De.create,Fu=we.create,Bu=pe.create,$u=Y.create,Vu=H.create,Ku=X.create,Qu=Y.createWithPreprocess,Gu=ft.create,Hu=()=>es().optional(),Wu=()=>ts().optional(),Yu=()=>ns().optional(),zu={string:(e=>ue.create({...e,coerce:!0})),number:(e=>Te.create({...e,coerce:!0})),boolean:(e=>xe.create({...e,coerce:!0})),bigint:(e=>Ee.create({...e,coerce:!0})),date:(e=>be.create({...e,coerce:!0}))};var qu=R;var mt="agenttrail.ingest.mode",gt="agenttrail.ingest.batch_id",Kt="backfill";var Qt=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"),Zu=fe.string().min(1).refine(e=>e.startsWith("dlv_"),{message:"AgentTrail API key must start with 'dlv_'"}),t_=fe.object({orgId:Qt,projectSlug:fe.string().min(1),projectId:Qt.optional(),agentId:Qt.optional(),developerId:Qt.optional(),apiKey:Zu.optional(),captureContent:fe.boolean().optional()}).strict();function ss(e,t){return jt(`${e}:${t}`,en)}var is="agenttrail.org.id",as="agenttrail.project.id",ds="agenttrail.agent.id",cs="agenttrail.developer.id",us="agenttrail.project",ls="gen_ai.conversation.id",ps="session.id",fs="gen_ai.request.model",ms="llm_request.context",gs="tool_name",ys="gen_ai.tool.name",hs="gen_ai.tool.call.id",Vn="gen_ai.usage.input_tokens",Kn="gen_ai.usage.output_tokens",Qn="gen_ai.usage.cache_read.input_tokens",Gn="gen_ai.usage.cache_creation.input_tokens",Xu="interaction",rs=1,el=3,tl=Object.freeze({[is]:"metadata",[as]:"metadata",[ds]:"metadata",[ht]:"metadata",[cs]:"metadata",[us]:"metadata",[Ze]:"metadata",[mt]:"metadata",[gt]:"metadata",[Yt]:"metadata",[ls]:"metadata",[ps]:"metadata",[Zt]:"metadata",[fs]:"metadata",[ms]:"metadata",[zt]:"metadata",[Vn]:"metadata",[Kn]:"metadata",[Qn]:"metadata",[Gn]:"metadata",[gs]:"metadata",[ys]:"metadata",[Wt]:"metadata",[hs]:"metadata",[Jt]:"metadata",[Xt]:"metadata",[qt]:"metadata",[ct]:"content",[q]:"content",[$e]:"content",[Se]:"content"});function Gt(e,t,n){let r=n==="import"?`import:${t.conversationId}:${t.importKey??t.importOrdinal??0}`:`live:${t.conversationId}:${t.generationId??""}`;return jt(r,e).replace(/-/g,"")}function qe(e,t){let n=typeof t=="string"?t:`tool:${t.tool}`;return Ju("sha256").update(`${e}:${n}`).digest("hex").slice(0,16)}function Hn(e){return e.correlationId??`ordinal:${e.ordinal}`}function Wn(e,t){return qe(e,{tool:Hn(t)})}function os(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 nl(e,t,n){let r={...t};if(e.call.tool!==""&&(r[gs]=e.call.tool,r[ys]=e.call.tool),e.vendorTool!==""&&(r[Wt]=e.vendorTool),e.correlationId!==null&&(r[hs]=e.correlationId),e.mcpServerUnknown===!0&&(r[Jt]="true"),e.pepBlocked===!0&&e.failed&&(r[Xt]="true"),e.subagentConversationId!==void 0&&(r[qt]=e.subagentConversationId),n){let{full_command:o,file_path:s}=e.call.args;o!==void 0&&(r[q]=o),s!==void 0&&(r[$e]=s),e.output!==void 0&&(r[Se]=e.output)}return r}function rl(e,t,n){let r=n.mode==="import",o=Gt(e.traceNamespace,t,n.mode),s=qe(o,"root"),i=t.endMs,a=n.include,d=!r&&t.usage!==null&&t.model!==null,c={};t.conversationId!==""&&(c[ls]=t.conversationId,c[ps]=t.conversationId);let u=r?{[Yt]:"true",[mt]:Kt,...n.batchId?{[gt]:n.batchId}:{}}:{},f=[];if(i!==null&&(a?.root??!0)){let g=t.closedBy??(r?"import":void 0);f.push({spanId:s,parentSpanId:"",name:e.rootSpanName,kind:rs,startMs:t.startMs,endMs:i,attributes:{...c,...g!==void 0?{[Zt]:g}:{},...n.captureContent&&t.prompt?{[ct]:t.prompt}:{},...d?{}:{[Ze]:"false"},...u},error:t.status==="error"})}!r&&i!==null&&t.model!==null&&(a?.model??!0)&&f.push({spanId:qe(o,"model"),parentSpanId:s,name:`chat ${t.model.name}`,kind:el,startMs:t.startMs,endMs:t.model.endMs,attributes:{...c,[fs]:t.model.name,[ms]:Xu,[zt]:"true",...d&&t.usage!==null?e.usageAttributes(t.usage):{[Ze]:"false"}},error:!1});for(let g of t.tools){let x=g.endMs??i;x!==null&&(a?.toolKeys!==void 0&&!a.toolKeys.has(Hn(g))||f.push({spanId:Wn(o,g),parentSpanId:g.parentTaskKey===void 0?s:qe(o,{tool:g.parentTaskKey}),name:g.call.tool===""?"execute_tool":`execute_tool ${g.call.tool}`,kind:rs,startMs:g.startMs,endMs:x,attributes:{...nl(g,c,n.captureContent),...u},error:g.failed}))}return f}function _s(e,t,n,r){let o=n.mode==="import",s=Gt(e.traceNamespace,t,n.mode),i=n.resolvedScrubbers??null,a=0,d={},c=rl(e,t,n).map(f=>{let g=Do(f.attributes,i);a+=g.redactedCount;for(let[A,m]of Object.entries(g.byType))d[A]=(d[A]??0)+m;let x=g.attributes;return{traceId:s,spanId:f.spanId,parentSpanId:f.parentSpanId,name:f.name,kind:f.kind,startTimeUnixNano:os(f.startMs),endTimeUnixNano:os(Math.max(f.endMs,f.startMs)),attributes:x,error:f.error}});return{resource:{attributes:{[is]:n.orgId,[as]:n.project.projectId,[ds]:r,[ht]:e.vendor,...n.project.developerId?{[cs]:n.project.developerId}:{},...n.project.projectLabel?{[us]:n.project.projectLabel}:{},[Ze]:o?"false":"true",...o?{[mt]:Kt}:{},...o&&n.batchId?{[gt]:n.batchId}:{}}},scope:{name:e.scopeName,version:n.scopeVersion},spans:c,redactions:{total:a,byType:d}}}function ol(e){return ss(e,kt)}var sl="agenttrail-cursor";function zn(e,t){return Gt(Rs.traceNamespace,{conversationId:e.conversationId,generationId:e.generationId,...e.importOrdinal!==void 0?{importOrdinal:e.importOrdinal}:{}},t)}function il(e){if(!("importKey"in e))return e;let{importKey:t,...n}=e;return n}function qn(e,t){return qe(e,t)}function al(e,t){return Wn(e,t)}var Yn=new Set(["subagentStart","subagentStop"]),dl=new Set(["postToolUse","postToolUseFailure","afterFileEdit"]),cl=Object.freeze({conversationId:"",generationId:null,startMs:0,endMs:null,model:null,usage:null,tools:Object.freeze([])});function ul(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 Zn(e){let t=e.tool?.durationMs;return t!==void 0&&Number.isFinite(t)&&t>=0?e.capturedAtMs-t:e.capturedAtMs}function ll(e,t){for(let n=e.length-1;n>=0;n-=1){let r=e[n];if(t(r))return r}}function pl(e){let t=e.find(n=>n.event==="beforeSubmitPrompt"&&n.conversationId!==null);if(t?.conversationId)return t.conversationId;for(let n of e){if(!Yn.has(n.event))continue;let r=n.subagent?.parentConversationId??n.conversationId;if(r)return r}for(let n of["stop","afterAgentResponse"]){let r=ll(e,o=>o.event===n&&o.conversationId!==null);if(r?.conversationId)return r.conversationId}return e.find(n=>n.conversationId!==null)?.conversationId??""}function fl(e){switch(e){case"completed":return"success";case"aborted":return"aborted";case"error":return"error";default:return"unknown"}}function ml(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 gl(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:Zn(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 yl(e,t,n){let{post:r,start:o,stop:s}=e,i=o??s,a=o?.capturedAtMs??(r!==void 0?Zn(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 hl(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 Ss(e,t){let n=e.map((l,S)=>({record:l,index:S})).filter(({record:l})=>ul(l)).sort((l,S)=>l.record.capturedAtMs-S.record.capturedAtMs||l.index-S.index).map(({record:l})=>l);if(n.length===0)return cl;let r=pl(n),o=l=>l===null||l===r,s=n.find(l=>o(l.conversationId)&&!Yn.has(l.event)&&l.generationId!==null)?.generationId??null,i=zn({conversationId:r,generationId:s},"live"),a=l=>{let S=t?.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(dl.has(l.event)&&l.tool!==void 0){let S=u(l.tool.correlationId);S.post??=l}else if(Yn.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),g=new Set,x=d.map((l,S)=>{let M=l.start!==void 0||l.stop!==void 0?yl(l,S,o):gl(l.post,S,ml(l.post,f,g),o),se=a(al(i,M));return se===void 0?M:{...M,startMs:se}}),A=x.filter(l=>l.isTask),m=x.map(l=>{let S=l.foreignConversationId===void 0?void 0:hl(l,A);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}:{}}}),T,v,D,k=Number.POSITIVE_INFINITY;for(let l of n)k=Math.min(k,Zn(l)),o(l.conversationId)&&(l.event==="beforeSubmitPrompt"?T??=l.content?.prompt:l.event==="afterAgentResponse"?v=l:l.event==="stop"&&(D=l));let O=v?.model??D?.model??null,w=v?.capturedAtMs??D?.capturedAtMs;return{conversationId:r,generationId:s,startMs:a(qn(i,"root"))??k,endMs:D?.capturedAtMs??null,...D!==void 0?{closedBy:"stop",status:fl(D.status)}:{},...T!==void 0?{prompt:T}:{},model:O!==null&&w!==void 0?{name:O,endMs:w}:null,usage:D?.usage??null,tools:m}}function Ht(e){return e!==void 0&&Number.isFinite(e)&&e>0?Math.floor(e):0}function _l(e){let t=Ht(e.cacheReadTokens),n=Ht(e.cacheWriteTokens);return{[Vn]:String(Math.max(0,Ht(e.inputTokens)-t-n)),[Kn]:String(Ht(e.outputTokens)),[Qn]:String(t),[Gn]:String(n)}}var Rs={vendor:kt,scopeName:sl,traceNamespace:tn,rootSpanName:"invoke_agent Cursor",usageAttributes:_l};function Ts(e,t){return _s(Rs,il(e),t,ol(t.orgId))}function Es(e){return{conversationId:e.conversationId,generationId:e.generationId}}function xs(e){return{conversationId:e.conversationId,generationId:e.generationId}}function bs(e){return e.event==="beforeSubmitPrompt"}function vs(e){return e.event==="stop"}function Cs(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 Is(e){return e==="postToolUse"||e==="postToolUseFailure"}var Tl=2e3,El={traceId:e=>zn(e,"live"),spanId:(e,t)=>qn(e,t),assemble:e=>Ss(e),build:(e,t)=>Ts(e,t)};function xl(e,t,n=Tl){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(Un)||r.has(`${o.generationId??""}\0${s.vendorTool}`)?!0:t-o.capturedAtMs>=n})}function bl(e){if(e.cursorVersion!==null)return{version:e.cursorVersion,seenAtMs:e.capturedAtMs}}var vl={...fo,versionKey:Bo,versionOf:bl,readRegistry:(e,t)=>Fo(e,t),parseQueueEntry:e=>No(e),turnOf:Es,decisionTurnOf:xs,opensTurn:bs,closesTurn:vs,subagentOf:Cs,fillableEvent:Is,holdBack:(e,t)=>xl(e,t)};function Cl(e,t={}){return lo(vl,e,t)}async function Il(e,t,n){let r=_t({homeDir:e});return r===null?null:r.ingest_token!==t?r:cn({lockPath:`${me(e,"cursor")}.lock`},async()=>{let o=_t({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=tr(i),d=await dn(s,o.refresh_token,n,a),c=un(i,d,{apiEndpoint:s,ingestEndpoint:o.endpoint});return on(e,c,{},"cursor"),an(e,"cursor"),nr(i,d,a),c}catch{return null}})}function Al(e={}){let t=e.home??Rl(),n=e.io??P;return{home:t,io:n,lockIO:nt,now:()=>Date.now(),sleep:r=>new Promise(o=>setTimeout(o,r)),fetch:globalThis.fetch,builder:El,pid:process.pid,limits:wn,credentials:()=>_t({homeDir:t}),refresh:r=>Il(t,r),claimFile:(r,o)=>{try{return Sl(r,o),!0}catch{return!1}},scopeVersion:po(t,_e,n)??"0.0.0",retainDecisions:bo(t),...e}}async function kl(e={}){try{await Cl(Al(e.deps??{}),e)}catch{}return 0}function Ol(){return/flush\.(mjs|cjs|js)$/.test(process.argv[1]??"")}Ol()&&kl().then(e=>{process.exitCode=e});export{wn as DEFAULT_SENDER_LIMITS,oo as MAX_BODY_BYTES,Tl as MCP_JOIN_WAIT_MS,vl as cursorSenderAdapter,bl as cursorVersionOf,xl as holdUnjoinedMcp,El as liveTurnBuilder,Al as realSenderDeps,Il as refreshCursorToken,kl as runCursorSender,Cl as runSender,io as selectSpans,so as snapshotForState,Mn as spanFingerprint,ao as splitSpanBatches};