@agenttrail/cli 0.2.3 → 0.2.5

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 Ku}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 ju,resolve as ps}from"path";var pt="agenttrail.agent.vendor",Ft="agenttrail.tool.vendor_name";var Ye="agenttrail.usage.reported",Bt="agenttrail.time.approximate",$t="agenttrail.span.synthetic",Kt="agenttrail.subagent.conversation_id";var Vt="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 vs,openSync as Es,readFileSync as Yu,rmSync as As,statSync as Cs,writeSync as ks}from"fs";var Is=3e4,Os=(t,e)=>{let n=Es(t,"wx");try{ks(n,e)}finally{vs(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(E=>setTimeout(E,y))),d=t.staleMs??Is,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 jn(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 Fn,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 js=(t,e,n)=>Ps(t,[...e],{encoding:"utf8",timeout:n,stdio:["ignore","pipe","ignore"],env:{PATH:"/usr/sbin:/usr/bin:/bin"}}),Us=5e3,Ls=1e3,Fs={"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=Fs[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 Ks(t){if(typeof t!="string")return"Mac";let e=t.trim();return gt(e)&&e!=="Windows"&&e!=="Linux"?e:"Mac"}var Vs=["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",Vs,Us));if(e===void 0)return;let n=Ks(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"],Ls));return e==="Mac"?void 0:e}catch{return}}function Un(t={}){let e=t.platform??process.platform,n=t.exec??js;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 Ln(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}
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 Ku}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",Ft="agenttrail.tool.vendor_name";var Ye="agenttrail.usage.reported",Bt="agenttrail.time.approximate",$t="agenttrail.span.synthetic",Kt="agenttrail.subagent.conversation_id";var Vt="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 vs,openSync as Es,readFileSync as Yu,rmSync as As,statSync as Cs,writeSync as Is}from"fs";var ks=3e4,Os=(t,e)=>{let n=Es(t,"wx");try{Is(n,e)}finally{vs(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(E=>setTimeout(E,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 Fn,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,Ls=1e3,Fs={"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=Fs[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 Ks(t){if(typeof t!="string")return"Mac";let e=t.trim();return gt(e)&&e!=="Windows"&&e!=="Linux"?e:"Mac"}var Vs=["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",Vs,js));if(e===void 0)return;let n=Ks(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"],Ls));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 Ln(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
4
  `),o}function $n(t){return Bn(t,".agenttrail","device.json")}var Kn=["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)?Kn.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)=>Fn(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=Un({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 Vn(t,e={}){return{fields(n,r={}){let o={};try{(e.mkdir??((s,i)=>Fn(s,{recursive:!0,mode:i})))(Bn(t,".agenttrail"),448),o.machine_id=Ln(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:Kn.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 Ka}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([";","|","&","(",")","`",`
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 Vn(t,e={}){return{fields(n,r={}){let o={};try{(e.mkdir??((s,i)=>Fn(s,{recursive:!0,mode:i})))(Bn(t,".agenttrail"),448),o.machine_id=Ln(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:Kn.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 Ka}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
6
  `,"\r","{","}"]);function zn(t){let e=t.replace(/['"\\]/g,""),n=e.lastIndexOf("/");return(n===-1?e:e.slice(n+1)).toLowerCase()}function vi(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+=vi(o,n)?2:1}return r}function Ei(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?Ei(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 ki(t){return t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122||t===95||t===46||t===45}function Ii(t,e,n){let r=t[e]==="\\",o=e+(r?2:1),s=o;for(;s<o+65&&s<n&&ki(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=Ii(t,r,e);if(y>0){r+=y,o=r,s=!0,i=!0,a=null;continue}let E=t[r+f.length];if(f===a&&d&&(E===" "||E===" ")){r+=f.length,i=!1,a=null;continue}if(f===a||!i&&(E===","||E==="]"||E==="}")){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 k=Ci(t,f,r+f.length,e);if(k===-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,k)){r+=f.length,i=!1;continue}r=k+f.length,i=!1;continue}Hn.has(c)?(o=r+1,s=!0,i=!0,d=!1,(c===`
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 E=t[r+f.length];if(f===a&&d&&(E===" "||E===" ")){r+=f.length,i=!1,a=null;continue}if(f===a||!i&&(E===","||E==="]"||E==="}")){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
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 ji=G(String.raw`((?:AKIA|ABIA|ACCA|AGPA|AIDA|AIPA|ANPA|ANVA|AROA|ASCA|ASIA)[A-Z0-9]{16})\b`,"g"),Ui=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"),Li=G(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),Fi=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"),Ki=G(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),Vi=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:ji,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:Vi,placeholder:()=>N("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Fi,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:Li,placeholder:()=>N("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:Ki,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:Ui,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"])},je="\uE000",ia=new RegExp(`${je}(\\d+)${je}`,"g");function ar(t){return`${je}${t}${je}`}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(je)?t.split(je).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(k){if(u=k.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 Fp}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 Vp}from"crypto";import{join as j}from"path";function B(t,e){let n=j(t,".agenttrail",e),r=j(n,"runtime");return{root:n,credentials:j(n,"credentials.json"),install:j(n,"install.json"),projects:j(n,"projects.json"),runtime:r,captureHook:j(r,"capture-hook.mjs"),flush:j(r,"flush.mjs"),queueKey:j(n,"queue.key"),enforcement:j(n,"enforcement.json"),pepSnapshot:j(n,"pep-snapshot.json"),queue:j(n,"queue"),turns:j(n,"turns"),senderLock:j(n,"sender.lock"),senderState:j(n,"sender-state.json"),backfillState:j(n,"backfill-state.json")}}function Xe(t,e,n){return j(B(t,e).queue,n)}function _t(t,e,n){return j(B(t,e).turns,`${n}.json`)}import{randomBytes as va}from"crypto";import{closeSync as Ea,openSync as Aa,readFileSync as Ca,rmSync as ka,statSync as Ia,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{Ea(n)}},release(t){try{ka(t,{force:!0})}catch{}},age(t){try{return Date.now()-Ia(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()} ${va(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 Le(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 Ue(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=Ue(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=Ue(s?.atMs),a=br(n[e]),d=Ue(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:Ue(r.seen)??0,filledToolUseId:Ue(r.filledToolUseId)??0,orphaned:Ue(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 vr(t,e){return e===void 0?t:t===void 0||e.seenAtMs>=t.seenAtMs?e:t}function Er(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=vr(Rt(c,n),Rt(d,n)),f=Er(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)=>vr(a,Rt(d,n)),Rt(t,n)),s=Er(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 ja(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 Ua(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=ja(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),Ua(n),ae)}function mn(t,e,n,r=P){r.remove(_t(t,e,n))}function La(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 Fa(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=La(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 E={name:d,...c,entry:y};r?.set(u,E),i.push(E)}return{files:Fa(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 kr(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)Ir(d,g,x,e);let f=(g,x)=>r.filter(A=>A.loaded.conversationId===g&&kr(A,x,e)).sort((A,I)=>me(A)-me(I)).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),E=(g,x)=>{let A=r.filter(I=>kr(I,g.atMs,e)&&Math.abs(g.atMs-me(I))<=n.orphanWindowMs).sort((I,D)=>me(I)-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,I=e.subagentOf(A);if(I!==void 0){let O=I.parentConversationId,w=O===null?void 0:f(O,A.capturedAtMs);if(w===void 0){E(g,"orphan");continue}u(w,g),Ir(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}}E(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 Ir(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 Lr=35e5,Va=new Set([400,413,422]),yn={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function hn(t){return Ka("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 Fr(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=Lr){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){Le(t.totals.dropped,n),Le(t.report,n),e!==void 0&&Le(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}:jr(t,u,n,a.filledToolUseId);let E=Fr(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&&(E={...E,usage:O})}let k=o.builder.build(E,{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(k.spans,u,g),I=0;for(let O of $r(k,x)){let w=await Qa(o,e,ht({...k,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},I+=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&&Va.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:I,drained:!1,open:y,fatal:w.status===401?"auth":"network",...w.error!==void 0?{error:w.error}:{}}}return u.closed!==void 0&&!c&&k.spans.every(O=>u.sent[O.spanId]!==void 0)?{...jr(t,u,n,a.filledToolUseId),sent:I}:{state:u,sent:I,drained:!1,open:y}}function jr(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 Ur(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 Kr(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,E,k;for(let g of Kr(r.home,n.stateDir,r.io)){let x=Xe(r.home,n.stateDir,g),{files:A,other:I}=Dr(x,l=>n.parseQueueEntry(l),r.io,o.cache,x);I.includes(an)&&Ya(t,g,x);for(let l of I){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"&&Le(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,k=S.error??k,o.totals.lastError={atMs:r.now(),message:S.error??(S.fatal==="auth"?"not signed in":"upload failed")},S.fatal==="auth"&&(E="auth");break}}if(o.posts=w.posts,i=w.credentials,E!==void 0)break}return{entries:d,openTurns:c,newestRecordMs:u,sent:f,failed:y,...E!==void 0?{fatal:E}:{},...k!==void 0?{error:k}:{}}}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 Kr(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 Vr(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,E,k=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,Ur(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(E??=e.now(),g.fatal==="auth"||e.now()-E>=e.limits.giveUpMs){c="send-failed";break}}else E=void 0,k=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(),k)),g.failed&&(k=Math.min(k*2,e.limits.pollIdleMs*12))}}finally{Ur(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",vt="cursor",ye="cursor",Gr={agent:nd,vendor:vt,stateDir:ye};import{createHash as _f}from"crypto";var _n="MCP:";var st="user_prompt",id="gen_ai.completion",Z="full_command",Fe="file_path",he="gen_ai.tool.call.result",it=new Set([st,id,Z,Fe,he]);var Et="secret-manager-output",At=`[REDACTED:secret:${Et}]`,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[Et]=(o[Et]??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 Vf,randomBytes as Qf}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 kt(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function no(t){return typeof t=="string"&&t!==""}function Rd(t,e){if(!kt(e))return{key:t};let n=no(e.root)?e.root:void 0,r=Array.isArray(e.subfolders)?e.subfolders.map(o=>kt(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(!kt(n)||n.v!==1||!kt(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 Ng}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 vd(t){return so(t)&&ee(t.path)&&ee(t.transcriptFolder)&&io(t.install)&&ee(t.registeredAt)}function Ed(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(vd)):!1}function ao(t,e=P){return ro(oo(t).projects,Ed,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 U=[];for(let t=0;t<256;++t)U.push((t+256).toString(16).slice(1));function po(t,e=0){return U[t[e+0]]+U[t[e+1]]+U[t[e+2]]+U[t[e+3]]+"-"+U[t[e+4]]+U[t[e+5]]+"-"+U[t[e+6]]+U[t[e+7]]+"-"+U[t[e+8]]+U[t[e+9]]+"-"+U[t[e+10]]+U[t[e+11]]+U[t[e+12]]+U[t[e+13]]+U[t[e+14]]+U[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 kd(t){t=unescape(encodeURIComponent(t));let e=[];for(let n=0;n<t.length;++n)e.push(t.charCodeAt(n));return e}var Id="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=kd(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=Id,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),It=Md;var fe={};Jo(fe,{BRAND:()=>sc,DIRTY:()=>_e,EMPTY_PATH:()=>Ud,INVALID:()=>R,NEVER:()=>Vc,OK:()=>F,ParseStatus:()=>L,Schema:()=>v,ZodAny:()=>le,ZodArray:()=>oe,ZodBigInt:()=>Re,ZodBoolean:()=>Te,ZodBranded:()=>dt,ZodCatch:()=>De,ZodDate:()=>xe,ZodDefault:()=>we,ZodDiscriminatedUnion:()=>Dt,ZodEffects:()=>z,ZodEnum:()=>Ie,ZodError:()=>K,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>Nt,ZodIntersection:()=>Ae,ZodIssueCode:()=>p,ZodLazy:()=>Ce,ZodLiteral:()=>ke,ZodMap:()=>Ge,ZodNaN:()=>He,ZodNativeEnum:()=>Oe,ZodNever:()=>Y,ZodNull:()=>ve,ZodNullable:()=>X,ZodNumber:()=>Se,ZodObject:()=>V,ZodOptional:()=>W,ZodParsedType:()=>h,ZodPipeline:()=>ct,ZodPromise:()=>pe,ZodReadonly:()=>Me,ZodRecord:()=>Mt,ZodSchema:()=>v,ZodSet:()=>We,ZodString:()=>ue,ZodSymbol:()=>Ve,ZodTransformer:()=>z,ZodTuple:()=>J,ZodType:()=>v,ZodUndefined:()=>be,ZodUnion:()=>Ee,ZodUnknown:()=>re,ZodVoid:()=>Qe,addIssueToContext:()=>m,any:()=>gc,array:()=>_c,bigint:()=>cc,boolean:()=>Eo,coerce:()=>Kc,custom:()=>xo,date:()=>uc,datetimeRegex:()=>Ro,defaultErrorMap:()=>te,discriminatedUnion:()=>xc,effect:()=>Nc,enum:()=>wc,function:()=>kc,getErrorMap:()=>Be,getParsedType:()=>q,instanceof:()=>ac,intersection:()=>bc,isAborted:()=>Ot,isAsync:()=>$e,isDirty:()=>wt,isValid:()=>ce,late:()=>ic,lazy:()=>Ic,literal:()=>Oc,makeIssue:()=>at,map:()=>Ac,nan:()=>dc,nativeEnum:()=>Dc,never:()=>yc,null:()=>fc,nullable:()=>jc,number:()=>vo,object:()=>Sc,objectUtil:()=>Tn,oboolean:()=>$c,onumber:()=>Bc,optional:()=>Pc,ostring:()=>Fc,pipeline:()=>Lc,preprocess:()=>Uc,promise:()=>Mc,quotelessJson:()=>Nd,record:()=>Ec,set:()=>Cc,setErrorMap:()=>jd,strictObject:()=>Rc,string:()=>bo,symbol:()=>lc,transformer:()=>Nc,tuple:()=>vc,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:"),K=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()}};K.create=t=>new K(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 jd(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}},Ud=[];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 L=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}),F=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 K(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 v=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 L,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 Ee.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}},Ld=/^c[^\s-]{8,}$/i,Fd=/^[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,Kd=/^[a-z0-9_-]{21}$/i,Vd=/^[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(!Vd.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 v{_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 L,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")Kd.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")Ld.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")Fd.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 v{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 L;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 v{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 L;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 v{_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 F(e.data)}};Te.create=t=>new Te({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...b(t)});var xe=class t extends v{_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 L,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 Ve=class extends v{_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 F(e.data)}};Ve.create=t=>new Ve({typeName:T.ZodSymbol,...b(t)});var be=class extends v{_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 F(e.data)}};be.create=t=>new be({typeName:T.ZodUndefined,...b(t)});var ve=class extends v{_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 F(e.data)}};ve.create=t=>new ve({typeName:T.ZodNull,...b(t)});var le=class extends v{constructor(){super(...arguments),this._any=!0}_parse(e){return F(e.data)}};le.create=t=>new le({typeName:T.ZodAny,...b(t)});var re=class extends v{constructor(){super(...arguments),this._unknown=!0}_parse(e){return F(e.data)}};re.create=t=>new re({typeName:T.ZodUnknown,...b(t)});var Y=class extends v{_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 v{_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 F(e.data)}};Qe.create=t=>new Qe({typeName:T.ZodVoid,...b(t)});var oe=class t extends v{_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=>L.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new H(n,i,n.path,a)));return L.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 Ke(t){if(t instanceof V){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=W.create(Ke(r))}return new V({...t._def,shape:()=>e})}else return t instanceof oe?new oe({...t._def,type:Ke(t.element)}):t instanceof W?W.create(Ke(t.unwrap())):t instanceof X?X.create(Ke(t.unwrap())):t instanceof J?J.create(t.items.map(e=>Ke(e))):t}var V=class t extends v{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let 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=>L.mergeObjectSync(r,c)):L.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 Ke(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))}};V.create=(t,e)=>new V({shape:()=>t,unknownKeys:"strip",catchall:Y.create(),typeName:T.ZodObject,...b(e)});V.strictCreate=(t,e)=>new V({shape:()=>t,unknownKeys:"strict",catchall:Y.create(),typeName:T.ZodObject,...b(e)});V.lazycreate=(t,e)=>new V({shape:t,unknownKeys:"strip",catchall:Y.create(),typeName:T.ZodObject,...b(e)});var Ee=class extends v{_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 K(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 K(d));return m(n,{code:p.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};Ee.create=(t,e)=>new Ee({options:t,typeName:T.ZodUnion,...b(e)});var ne=t=>t instanceof Ce?ne(t.schema):t instanceof z?ne(t.innerType()):t instanceof ke?[t.value]:t instanceof Ie?t.options:t instanceof Oe?C.objectValues(t.enum):t instanceof we?ne(t._def.innerType):t instanceof be?[void 0]:t instanceof ve?[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 v{_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 v{_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 v{_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=>L.mergeArray(n,i)):L.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 v{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?L.mergeObjectAsync(n,o):L.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof v?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 v{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 v{_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 v{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 F(async function(...d){let c=new K([]),u=await a._def.args.parseAsync(d,s).catch(E=>{throw c.addIssue(r(d,E)),c}),f=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(f,s).catch(E=>{throw c.addIssue(o(f,E)),c})})}else{let a=this;return F(function(...d){let c=a._def.args.safeParse(d,s);if(!c.success)throw new K([r(d,c.error)]);let u=Reflect.apply(i,this,c.data),f=a._def.returns.safeParse(u,s);if(!f.success)throw new K([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 v{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 ke=class extends v{_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}};ke.create=(t,e)=>new ke({value:t,typeName:T.ZodLiteral,...b(e)});function To(t,e){return new Ie({values:t,typeName:T.ZodEnum,...b(e)})}var Ie=class t extends v{_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 F(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})}};Ie.create=To;var Oe=class extends v{_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 F(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 v{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 F(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 v{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 v{_parse(e){return this._getType(e)===h.undefined?F(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 v{_parse(e){return this._getType(e)===h.null?F(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 v{_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 v{_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 K(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new K(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 v{_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 v{_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 v{_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 v{_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:V.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,vo=Se.create,dc=He.create,cc=Re.create,Eo=Te.create,uc=xe.create,lc=Ve.create,pc=be.create,fc=ve.create,gc=le.create,mc=re.create,yc=Y.create,hc=Qe.create,_c=oe.create,Sc=V.create,Rc=V.strictCreate,Tc=Ee.create,xc=Dt.create,bc=Ae.create,vc=J.create,Ec=Mt.create,Ac=Ge.create,Cc=We.create,kc=Nt.create,Ic=Ce.create,Oc=ke.create,wc=Ie.create,Dc=Oe.create,Mc=pe.create,Nc=z.create,Pc=W.create,jc=X.create,Uc=z.createWithPreprocess,Lc=ct.create,Fc=()=>bo().optional(),Bc=()=>vo().optional(),$c=()=>Eo().optional(),Kc={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 Vc=R;var ut="agenttrail.ingest.mode",lt="agenttrail.ingest.batch_id",Pt="backfill";var jt=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_'"}),ny=fe.object({orgId:jt,projectSlug:fe.string().min(1),projectId:jt.optional(),agentId:jt.optional(),developerId:jt.optional(),apiKey:Qc.optional(),captureContent:fe.boolean().optional()}).strict();function ko(t,e){return It(`${t}:${e}`,Wt)}var Io="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",jo="gen_ai.request.model",Uo="llm_request.context",Lo="tool_name",Fo="gen_ai.tool.name",Bo="gen_ai.tool.call.id",vn="gen_ai.usage.input_tokens",En="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({[Io]:"metadata",[Oo]:"metadata",[wo]:"metadata",[pt]:"metadata",[Do]:"metadata",[Mo]:"metadata",[Ye]:"metadata",[ut]:"metadata",[lt]:"metadata",[Bt]:"metadata",[No]:"metadata",[Po]:"metadata",[Vt]:"metadata",[jo]:"metadata",[Uo]:"metadata",[$t]:"metadata",[vn]:"metadata",[En]:"metadata",[An]:"metadata",[Cn]:"metadata",[Lo]:"metadata",[Fo]:"metadata",[Ft]:"metadata",[Bo]:"metadata",[Qt]:"metadata",[Gt]:"metadata",[Kt]:"metadata",[st]:"content",[Z]:"content",[Fe]:"content",[he]:"content"});function Ut(t,e,n){let r=n==="import"?`import:${e.conversationId}:${e.importKey??e.importOrdinal??0}`:`live:${e.conversationId}:${e.generationId??""}`;return It(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 kn(t){return t.correlationId??`ordinal:${t.ordinal}`}function In(t,e){return ze(t,{tool:kn(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[Lo]=t.call.tool,r[Fo]=t.call.tool),t.vendorTool!==""&&(r[Ft]=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[Kt]=t.subagentConversationId),n){let{full_command:o,file_path:s}=t.call.args;o!==void 0&&(r[Z]=o),s!==void 0&&(r[Fe]=s),t.output!==void 0&&(r[he]=t.output)}return r}function Zc(t,e,n){let r=n.mode==="import",o=Ut(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?{[Vt]: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,[jo]:e.model.name,[Uo]:Wc,[$t]:"true",...d&&e.usage!==null?t.usageAttributes(e.usage):{[Ye]:"false"}},error:!1});for(let y of e.tools){let E=y.endMs??i;E!==null&&(a?.toolKeys!==void 0&&!a.toolKeys.has(kn(y))||f.push({spanId:In(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:E,attributes:{...Yc(y,c,n.captureContent),...u},error:y.failed}))}return f}function $o(t,e,n,r){let o=n.mode==="import",s=Ut(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[k,g]of Object.entries(y.byType))d[k]=(d[k]??0)+g;let E=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:E,error:f.error}});return{resource:{attributes:{[Io]: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 ko(t,vt)}var Jc="agenttrail-cursor";function wn(t,e){return Ut(Vo.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 In(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 Ko(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,E=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}}),k=E.filter(l=>l.isTask),g=E.map(l=>{let S=l.foreignConversationId===void 0?void 0:uu(l,k);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,I,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"&&(I=l));let O=A?.model??I?.model??null,w=A?.capturedAtMs??I?.capturedAtMs;return{conversationId:r,generationId:s,startMs:a(Dn(i,"root"))??D,endMs:I?.capturedAtMs??null,...I!==void 0?{closedBy:"stop",status:iu(I.status)}:{},...x!==void 0?{prompt:x}:{},model:O!==null&&w!==void 0?{name:O,endMs:w}:null,usage:I?.usage??null,tools:g}}function Lt(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):0}function lu(t){let e=Lt(t.cacheReadTokens),n=Lt(t.cacheWriteTokens);return{[vn]:String(Math.max(0,Lt(t.inputTokens)-e-n)),[En]:String(Lt(t.outputTokens)),[An]:String(e),[Cn]:String(n)}}var Vo={vendor:vt,scopeName:Jc,traceNamespace:Ht,rootSpanName:"invoke_agent Cursor",usageAttributes:lu};function Qo(t,e){return $o(Vo,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=>Ko(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 Vr(_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:Vn(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"),jn(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,Lr 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,Fr as snapshotForState,hn as spanFingerprint,$r as splitSpanBatches};
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"),Li=G(String.raw`sk-(?:proj-)?[A-Za-z0-9_-]{20,64}\b`,"g"),Fi=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"),Ki=G(String.raw`(postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|rediss|amqp|amqps):\/\/[^\s/@:]+:[^\s]*@([^\s/:@]+)`,"gi"),Vi=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:Vi,placeholder:()=>N("secret:jwt","claims-not-stored")},{id:"github-token",kind:"secret",category:"token",severity:"high",tier:"permissive",regex:Fi,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:Li,placeholder:()=>N("secret:api-key")},{id:"connection-string",kind:"secret",category:"connection-string",severity:"high",tier:"permissive",regex:Ki,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 Gp}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 Yp}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 va}from"crypto";import{closeSync as Ea,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{Ea(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()} ${va(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 Le(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 vr(t,e){return e===void 0?t:t===void 0||e.seenAtMs>=t.seenAtMs?e:t}function Er(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=vr(Rt(c,n),Rt(d,n)),f=Er(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)=>vr(a,Rt(d,n)),Rt(t,n)),s=Er(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 La(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 Fa(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=La(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 E={name:d,...c,entry:y};r?.set(u,E),i.push(E)}return{files:Fa(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),E=(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){E(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}}E(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 Lr=35e5,Va=new Set([400,413,422]),yn={pollFlowingMs:250,pollOpenMs:1e3,pollIdleMs:5e3,flowWindowMs:3e4,giveUpMs:5*6e4,backoffMs:1e3};function hn(t){return Ka("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 Fr(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=Lr){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){Le(t.totals.dropped,n),Le(t.report,n),e!==void 0&&Le(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 E=Fr(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&&(E={...E,usage:O})}let I=o.builder.build(E,{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&&Va.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 Kr(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,E,I;for(let g of Kr(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"&&Le(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"&&(E="auth");break}}if(o.posts=w.posts,i=w.credentials,E!==void 0)break}return{entries:d,openTurns:c,newestRecordMs:u,sent:f,failed:y,...E!==void 0?{fatal:E}:{},...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 Kr(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 Vr(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,E,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(E??=e.now(),g.fatal==="auth"||e.now()-E>=e.limits.giveUpMs){c="send-failed";break}}else E=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",vt="cursor",ye="cursor",Gr={agent:nd,vendor:vt,stateDir:ye};import{createHash as vf}from"crypto";var _n="MCP:";var st="user_prompt",id="gen_ai.completion",Z="full_command",Fe="file_path",he="gen_ai.tool.call.result",it=new Set([st,id,Z,Fe,he]);var Et="secret-manager-output",At=`[REDACTED:secret:${Et}]`,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[Et]=(o[Et]??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 Yf,randomBytes as Zf}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 Bg}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 vd(t){return so(t)&&ee(t.path)&&ee(t.transcriptFolder)&&io(t.install)&&ee(t.registeredAt)}function Ed(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(vd)):!1}function ao(t,e=P){return ro(oo(t).projects,Ed,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:()=>Vc,OK:()=>F,ParseStatus:()=>L,Schema:()=>v,ZodAny:()=>le,ZodArray:()=>oe,ZodBigInt:()=>Re,ZodBoolean:()=>Te,ZodBranded:()=>dt,ZodCatch:()=>De,ZodDate:()=>xe,ZodDefault:()=>we,ZodDiscriminatedUnion:()=>Dt,ZodEffects:()=>z,ZodEnum:()=>ke,ZodError:()=>K,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>Nt,ZodIntersection:()=>Ae,ZodIssueCode:()=>p,ZodLazy:()=>Ce,ZodLiteral:()=>Ie,ZodMap:()=>Ge,ZodNaN:()=>He,ZodNativeEnum:()=>Oe,ZodNever:()=>Y,ZodNull:()=>ve,ZodNullable:()=>X,ZodNumber:()=>Se,ZodObject:()=>V,ZodOptional:()=>W,ZodParsedType:()=>h,ZodPipeline:()=>ct,ZodPromise:()=>pe,ZodReadonly:()=>Me,ZodRecord:()=>Mt,ZodSchema:()=>v,ZodSet:()=>We,ZodString:()=>ue,ZodSymbol:()=>Ve,ZodTransformer:()=>z,ZodTuple:()=>J,ZodType:()=>v,ZodUndefined:()=>be,ZodUnion:()=>Ee,ZodUnknown:()=>re,ZodVoid:()=>Qe,addIssueToContext:()=>m,any:()=>gc,array:()=>_c,bigint:()=>cc,boolean:()=>Eo,coerce:()=>Kc,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:()=>vo,object:()=>Sc,objectUtil:()=>Tn,oboolean:()=>$c,onumber:()=>Bc,optional:()=>Pc,ostring:()=>Fc,pipeline:()=>Lc,preprocess:()=>jc,promise:()=>Mc,quotelessJson:()=>Nd,record:()=>Ec,set:()=>Cc,setErrorMap:()=>Ud,strictObject:()=>Rc,string:()=>bo,symbol:()=>lc,transformer:()=>Nc,tuple:()=>vc,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:"),K=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()}};K.create=t=>new K(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 L=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}),F=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 K(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 v=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 L,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 Ee.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}},Ld=/^c[^\s-]{8,}$/i,Fd=/^[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,Kd=/^[a-z0-9_-]{21}$/i,Vd=/^[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(!Vd.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 v{_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 L,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")Kd.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")Ld.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")Fd.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 v{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 L;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 v{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 L;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 v{_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 F(e.data)}};Te.create=t=>new Te({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...b(t)});var xe=class t extends v{_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 L,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 Ve=class extends v{_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 F(e.data)}};Ve.create=t=>new Ve({typeName:T.ZodSymbol,...b(t)});var be=class extends v{_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 F(e.data)}};be.create=t=>new be({typeName:T.ZodUndefined,...b(t)});var ve=class extends v{_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 F(e.data)}};ve.create=t=>new ve({typeName:T.ZodNull,...b(t)});var le=class extends v{constructor(){super(...arguments),this._any=!0}_parse(e){return F(e.data)}};le.create=t=>new le({typeName:T.ZodAny,...b(t)});var re=class extends v{constructor(){super(...arguments),this._unknown=!0}_parse(e){return F(e.data)}};re.create=t=>new re({typeName:T.ZodUnknown,...b(t)});var Y=class extends v{_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 v{_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 F(e.data)}};Qe.create=t=>new Qe({typeName:T.ZodVoid,...b(t)});var oe=class t extends v{_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=>L.mergeArray(r,i));let s=[...n.data].map((i,a)=>o.type._parseSync(new H(n,i,n.path,a)));return L.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 Ke(t){if(t instanceof V){let e={};for(let n in t.shape){let r=t.shape[n];e[n]=W.create(Ke(r))}return new V({...t._def,shape:()=>e})}else return t instanceof oe?new oe({...t._def,type:Ke(t.element)}):t instanceof W?W.create(Ke(t.unwrap())):t instanceof X?X.create(Ke(t.unwrap())):t instanceof J?J.create(t.items.map(e=>Ke(e))):t}var V=class t extends v{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let 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=>L.mergeObjectSync(r,c)):L.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 Ke(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))}};V.create=(t,e)=>new V({shape:()=>t,unknownKeys:"strip",catchall:Y.create(),typeName:T.ZodObject,...b(e)});V.strictCreate=(t,e)=>new V({shape:()=>t,unknownKeys:"strict",catchall:Y.create(),typeName:T.ZodObject,...b(e)});V.lazycreate=(t,e)=>new V({shape:t,unknownKeys:"strip",catchall:Y.create(),typeName:T.ZodObject,...b(e)});var Ee=class extends v{_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 K(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 K(d));return m(n,{code:p.invalid_union,unionErrors:a}),R}}get options(){return this._def.options}};Ee.create=(t,e)=>new Ee({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 ve?[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 v{_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 v{_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 v{_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=>L.mergeArray(n,i)):L.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 v{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?L.mergeObjectAsync(n,o):L.mergeObjectSync(n,o)}get element(){return this._def.valueType}static create(e,n,r){return n instanceof v?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 v{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 v{_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 v{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 F(async function(...d){let c=new K([]),u=await a._def.args.parseAsync(d,s).catch(E=>{throw c.addIssue(r(d,E)),c}),f=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(f,s).catch(E=>{throw c.addIssue(o(f,E)),c})})}else{let a=this;return F(function(...d){let c=a._def.args.safeParse(d,s);if(!c.success)throw new K([r(d,c.error)]);let u=Reflect.apply(i,this,c.data),f=a._def.returns.safeParse(u,s);if(!f.success)throw new K([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 v{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 v{_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 v{_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 F(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 v{_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 F(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 v{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 F(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 v{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 v{_parse(e){return this._getType(e)===h.undefined?F(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 v{_parse(e){return this._getType(e)===h.null?F(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 v{_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 v{_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 K(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new K(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 v{_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 v{_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 v{_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 v{_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:V.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,vo=Se.create,dc=He.create,cc=Re.create,Eo=Te.create,uc=xe.create,lc=Ve.create,pc=be.create,fc=ve.create,gc=le.create,mc=re.create,yc=Y.create,hc=Qe.create,_c=oe.create,Sc=V.create,Rc=V.strictCreate,Tc=Ee.create,xc=Dt.create,bc=Ae.create,vc=J.create,Ec=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,Lc=ct.create,Fc=()=>bo().optional(),Bc=()=>vo().optional(),$c=()=>Eo().optional(),Kc={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 Vc=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_'"}),dy=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",Lo="tool_name",Fo="gen_ai.tool.name",Bo="gen_ai.tool.call.id",vn="gen_ai.usage.input_tokens",En="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",[Vt]:"metadata",[Uo]:"metadata",[jo]:"metadata",[$t]:"metadata",[vn]:"metadata",[En]:"metadata",[An]:"metadata",[Cn]:"metadata",[Lo]:"metadata",[Fo]:"metadata",[Ft]:"metadata",[Bo]:"metadata",[Qt]:"metadata",[Gt]:"metadata",[Kt]:"metadata",[st]:"content",[Z]:"content",[Fe]:"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[Lo]=t.call.tool,r[Fo]=t.call.tool),t.vendorTool!==""&&(r[Ft]=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[Kt]=t.subagentConversationId),n){let{full_command:o,file_path:s}=t.call.args;o!==void 0&&(r[Z]=o),s!==void 0&&(r[Fe]=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?{[Vt]: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 E=y.endMs??i;E!==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:E,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 E=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:E,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,vt)}var Jc="agenttrail-cursor";function wn(t,e){return jt(Vo.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 Ko(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,E=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=E.filter(l=>l.isTask),g=E.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 Lt(t){return t!==void 0&&Number.isFinite(t)&&t>0?Math.floor(t):0}function lu(t){let e=Lt(t.cacheReadTokens),n=Lt(t.cacheWriteTokens);return{[vn]:String(Math.max(0,Lt(t.inputTokens)-e-n)),[En]:String(Lt(t.outputTokens)),[An]:String(e),[Cn]:String(n)}}var Vo={vendor:vt,scopeName:Jc,traceNamespace:Ht,rootSpanName:"invoke_agent Cursor",usageAttributes:lu};function Qo(t,e){return $o(Vo,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=>Ko(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 Vr(_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:Vn(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,Lr 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,Fr as snapshotForState,hn as spanFingerprint,$r as splitSpanBatches};