@agenttrail/cli 0.2.1 → 0.2.2

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