@honeybee-ai/waggle-cli 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -1,104 +1,104 @@
1
1
  #!/usr/bin/env node
2
2
  import{createRequire as __cr}from"node:module";import{fileURLToPath as __fu}from"node:url";import{dirname as __dn}from"node:path";var require=__cr(import.meta.url),__filename=__fu(import.meta.url),__dirname=__dn(__filename);
3
- var BC=Object.create;var Up=Object.defineProperty;var VC=Object.getOwnPropertyDescriptor;var GC=Object.getOwnPropertyNames;var WC=Object.getPrototypeOf,JC=Object.prototype.hasOwnProperty;var st=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var w=(t,e)=>()=>(t&&(e=t(t=0)),e);var O=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),X=(t,e)=>{for(var r in e)Up(t,r,{get:e[r],enumerable:!0})},KC=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of GC(e))!JC.call(t,o)&&o!==r&&Up(t,o,{get:()=>e[o],enumerable:!(n=VC(e,o))||n.enumerable});return t};var oo=(t,e,r)=>(r=t!=null?BC(WC(t)):{},KC(e||!t||!t.__esModule?Up(r,"default",{value:t,enumerable:!0}):r,t));function y(t,e){return`${A_[t]}${e}${A_.reset}`}function C(t){return`
4
- ${y("bold",y("cyan",t))}`}function z(t){return y("green",`\u2713 ${t}`)}function gn(t){return y("yellow",`\u26A0 ${t}`)}function b(t){return y("red",`\u2717 ${t}`)}function S(t,e){return` ${y("bold",t+":")} ${e}`}function br(t){let e=Math.max(...t.map(([r])=>r.length));return t.map(([r,n])=>` ${y("bold",r.padEnd(e))} ${n}`).join(`
5
- `)}var A_,Re=w(()=>{"use strict";A_={red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m"}});import{randomBytes as YC}from"node:crypto";function ac(){return`wgl_${YC(4).toString("hex")}`}var Fp=w(()=>{"use strict"});import{join as N_}from"node:path";import{homedir as z_}from"node:os";var ht,yn,os,Hp,ss,Bp,cc,so,is,lc,Vp,Gp,Wp,Jp,mi=w(()=>{ht=N_(z_(),".honeyb"),yn=N_(z_(),".wgl"),os="auth.json",Hp="integrations.json",ss=".honeyb",Bp=".honeybee",cc=[".wglrc.yaml",".wglrc.json",".wglrc"],so=".wgl.json",is="session.json",lc="brood.state.json",Vp="logs",Gp=10,Wp={HONEYB_PLATFORM:"platform",CARAPACE_PORT:"carapace.proxyPort",CARAPACE_UPSTREAM:"carapace.upstream",CARAPACE_MODE:"carapace.mode",CARAPACE_THRESHOLD:"carapace.threshold",TELEMETRY_ENDPOINT:"telemetry.endpoint",TELEMETRY_API_KEY:"telemetry.apiKey",INCUBATOR_PORT:"incubator.port"},Jp={platform:"https://hivemind.honeyb.dev",activeProfile:"personal",cli:{editor:"nano",hookTimeout:10,autoClaimFiles:!0},incubator:{port:3100,backend:"memory",verbose:!1,guard:!0},carapace:{mode:"block",threshold:100,proxyPort:8888},telemetry:{},pricing:{},servers:{}}});import{readFileSync as D_,writeFileSync as Kp,existsSync as Dt,mkdirSync as uc,copyFileSync as Yp,chmodSync as XC}from"node:fs";import{join as Yt,resolve as QC}from"node:path";import{homedir as j_}from"node:os";function Xp(){if(M_)return;M_=!0;let t=Yt(yn,"auth.json"),e=Yt(ht,os);Dt(t)&&!Dt(e)&&(Dt(ht)||uc(ht,{recursive:!0}),Yp(t,e),XC(e,384),console.error("[honeyb] Migrated auth store: ~/.wgl/auth.json \u2192 ~/.honeyb/auth.json"));let r=Yt(yn,"config.json"),n=j_(),o=Yt(n,".wglrc.json");if(Dt(r)&&!Dt(o))try{let a=JSON.parse(D_(r,"utf8")),c={};a.defaultPlatform&&(c.platform=a.defaultPlatform),a.defaultRole&&(c.role=a.defaultRole),a.activeProfile&&(c.activeProfile=a.activeProfile),a.editor&&(c.cli={...c.cli,editor:a.editor});let l=new Set(["defaultPlatform","defaultRole","activeProfile","editor"]);for(let[u,p]of Object.entries(a))!l.has(u)&&typeof p=="string"&&(c[u]=p);Object.keys(c).length>0&&(Kp(o,JSON.stringify(c,null,2)+`
6
- `),console.error("[honeyb] Migrated global config: ~/.wgl/config.json \u2192 ~/.wglrc.json"))}catch{}let s=Yt(j_(),".config","honeybee","integrations.json"),i=Yt(ht,Hp);Dt(s)&&!Dt(i)&&(Dt(ht)||uc(ht,{recursive:!0}),Yp(s,i),console.error("[honeyb] Migrated integrations: ~/.config/honeybee/integrations.json \u2192 ~/.honeyb/integrations.json"))}function Qp(t){let e=QC(t||process.cwd());if(L_.has(e))return;L_.add(e);let r=Yt(e,so),n=Yt(e,".wglrc.json"),o=Yt(e,ss),s=Yt(o,is);if(Dt(r)&&!Dt(n))try{let l=JSON.parse(D_(r,"utf8")),u={};l.server&&(u.server=l.server),l.namespace&&(u.namespace=l.namespace),l.role&&(u.role=l.role),(l.autoClaimFiles!==void 0||l.hookTimeout!==void 0)&&(u.cli={},l.autoClaimFiles!==void 0&&(u.cli.autoClaimFiles=l.autoClaimFiles),l.hookTimeout!==void 0&&(u.cli.hookTimeout=l.hookTimeout)),Object.keys(u).length>0&&Kp(n,JSON.stringify(u,null,2)+`
7
- `);let p={};l.agentId&&(p.agentId=l.agentId),l.lastEventCursor!==void 0&&(p.lastEventCursor=l.lastEventCursor),l.autoPublishDiscoveries!==void 0&&(p.autoPublishDiscoveries=l.autoPublishDiscoveries),Object.keys(p).length>0&&(Dt(o)||uc(o,{recursive:!0}),Kp(s,JSON.stringify(p,null,2)+`
8
- `)),console.error("[honeyb] Migrated project config: .wgl.json \u2192 .wglrc.json + .honeyb/session.json")}catch{}let i=Yt(e,Bp),a=Yt(i,"brood.state.json"),c=Yt(o,lc);Dt(a)&&!Dt(c)&&(Dt(o)||uc(o,{recursive:!0}),Yp(a,c),console.error("[honeyb] Migrated brood state: .honeybee/brood.state.json \u2192 .honeyb/brood.state.json"))}var M_,L_,ed=w(()=>{mi();M_=!1,L_=new Set});import{readFileSync as rd,writeFileSync as rI,existsSync as vn,mkdirSync as pc,readdirSync as nI,unlinkSync as oI}from"node:fs";import{join as wr,dirname as q_,resolve as hi,sep as sI}from"node:path";import{homedir as iI}from"node:os";function nd(t){let e=hi(t||process.cwd()),r=sI==="/"?"/":e.slice(0,3);for(;;){for(let o of cc){let s=wr(e,o);if(vn(s))return s}let n=q_(e);if(n===e||e===r)return null;e=n}}function Z_(){let t=iI();for(let e of cc){let r=wr(t,e);if(vn(r))return r}return null}function td(t){let e=rd(t,"utf8").trim();return e?t.endsWith(".yaml")?aI(e):t.endsWith(".json")?U_(e):lI(e):{}}function U_(t){try{let e=JSON.parse(t);return typeof e!="object"||e===null||Array.isArray(e)?{}:e}catch{return{}}}function aI(t){try{return cI(t)}catch{return U_(t)}}function cI(t){let e={},r=t.split(`
9
- `),n=[{indent:-1,obj:e}];for(let o of r){let s=o.replace(/#.*$/,"").trimEnd();if(!s)continue;let i=o.length-o.trimStart().length,a=s.match(/^(\s*)([^:]+):\s*(.*)$/);if(!a)continue;let c=a[2].trim(),l=a[3].trim();for(;n.length>1&&n[n.length-1].indent>=i;)n.pop();let u=n[n.length-1].obj;if(l===""){let p={};u[c]=p,n.push({indent:i,obj:p})}else u[c]=od(l)}return e}function lI(t){let e={};for(let r of t.split(`
10
- `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<1)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();gi(e,s,od(i))}return e}function od(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="")return"";let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}function gi(t,e,r){let n=e.split("."),o=t;for(let s=0;s<n.length-1;s++){let i=n[s];(typeof o[i]!="object"||o[i]===null)&&(o[i]={}),o=o[i]}o[n[n.length-1]]=r}function dc(t,e){let r=e.split("."),n=t;for(let o of r){if(typeof n!="object"||n===null)return;n=n[o]}return n}function io(t,e){let r={...t};for(let n of Object.keys(e)){let o=e[n],s=r[n];o==null?delete r[n]:typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?r[n]=io(s,o):r[n]=o}return r}function uI(){let t={};for(let[e,r]of Object.entries(Wp)){let n=process.env[e];n!==void 0&&n!==""&&gi(t,r,od(n))}return t}function Nr(t){Xp(),Qp(t);let e=structuredClone(Jp),r=Z_();r&&(e=io(e,td(r)));let n=nd(t);if(n&&(e=io(e,td(n))),!n){let o=pI(t);if(o){let s=dI(o);s&&(e=io(e,s))}}return e=io(e,uI()),Object.freeze(e)}function sd(){return vn(ht)||pc(ht,{recursive:!0}),ht}function F_(t){return hi(t||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}function H_(t){let e=F_(t),r=wr(sd(),"projects",e);return vn(r)||pc(r,{recursive:!0}),r}function B_(t){let e=hi(t||process.cwd()),r=wr(e,ss);return vn(r)||pc(r,{recursive:!0}),r}function id(t){let e=wr(hi(t||process.cwd()),ss),r=wr(e,is);if(!vn(r))return{};try{return JSON.parse(rd(r,"utf8"))}catch{return{}}}function ad(t,e){let r=B_(e),n=wr(r,is);rI(n,JSON.stringify(t,null,2)+`
11
- `)}function _n(t){let e=wr(H_(t),Vp);return vn(e)||pc(e,{recursive:!0}),e}function cd(t){let e=_n(t),r=new Date().toISOString().replace(/[:.]/g,"-");return wr(e,`${r}.jsonl`)}function ld(t){let e=_n(t);try{let r=nI(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();for(let n=Gp;n<r.length;n++)oI(wr(e,r[n]))}catch{}}function pI(t){let e=hi(t||process.cwd()),r="/";for(;;){let n=wr(e,so);if(vn(n))return n;let o=q_(e);if(o===e||e===r)return null;e=o}}function dI(t){try{let e=JSON.parse(rd(t,"utf8")),r={};return e.server&&(r.server=e.server),e.namespace&&(r.namespace=e.namespace),e.role&&(r.role=e.role),e.autoClaimFiles!==void 0&&(r.cli={...r.cli,autoClaimFiles:e.autoClaimFiles}),e.hookTimeout!==void 0&&(r.cli={...r.cli,hookTimeout:e.hookTimeout}),r}catch{return null}}var V_=w(()=>{mi();ed()});import{readFileSync as fI,writeFileSync as mI,existsSync as fc,mkdirSync as hI,chmodSync as gI}from"node:fs";import{join as ud}from"node:path";function yI(){let t=ud(ht,os);if(fc(t))return t;let e=ud(yn,"auth.json");return fc(e)?e:t}function as(){let t=yI();if(!fc(t))return{profiles:{}};try{return JSON.parse(fI(t,"utf8"))}catch{return{profiles:{}}}}function mc(t){fc(ht)||hI(ht,{recursive:!0});let e=ud(ht,os);mI(e,JSON.stringify(t,null,2)+`
12
- `,{mode:384}),gI(e,384)}function pd(t){return as().profiles[t]||null}function dd(t,e){let r=as();r.profiles[t]=e,mc(r)}function fd(t){let e=as();return t in e.profiles?(delete e.profiles[t],mc(e),!0):!1}function md(){let t=as();return Object.keys(t.profiles)}var G_=w(()=>{mi()});var bn=w(()=>{mi();V_();G_();ed()});import{writeFileSync as vI,existsSync as W_,unlinkSync as J_}from"node:fs";import{join as hd}from"node:path";function be(t){let e=Nr(t),r=id(t);return e.server?{server:e.server,namespace:e.namespace??"default",agentId:r.agentId??"",role:e.role??"developer",autoClaimFiles:e.cli.autoClaimFiles,autoPublishDiscoveries:r.autoPublishDiscoveries??!0,hookTimeout:e.cli.hookTimeout,lastEventCursor:r.lastEventCursor??0}:null}function hc(t,e){let r=e||process.cwd(),n={server:t.server,namespace:t.namespace,role:t.role,cli:{autoClaimFiles:t.autoClaimFiles,hookTimeout:t.hookTimeout}},o=hd(r,".wglrc.json");vI(o,JSON.stringify(n,null,2)+`
13
- `);let s={agentId:t.agentId,lastEventCursor:t.lastEventCursor,autoPublishDiscoveries:t.autoPublishDiscoveries};return ad(s,r),o}function K_(t){let e=t||process.cwd(),r=!1;for(let o of[".wglrc.json",".wglrc.yaml",".wglrc"]){let s=hd(e,o);W_(s)&&(J_(s),r=!0)}let n=hd(e,so);return W_(n)&&(J_(n),r=!0),r}function gc(t,e,r,n){return{server:t,namespace:n||"default",agentId:e,role:r,autoClaimFiles:!0,autoPublishDiscoveries:!0,hookTimeout:10,lastEventCursor:0}}var dt=w(()=>{"use strict";bn()});import{readFileSync as _I,writeFileSync as bI,existsSync as Y_,mkdirSync as wI}from"node:fs";import{join as xI,dirname as SI}from"node:path";function X_(){return xI(process.cwd(),".claude","settings.local.json")}function Q_(){let t=X_();if(!Y_(t))return{};try{return JSON.parse(_I(t,"utf8"))}catch{return{}}}function eb(t){let e=X_(),r=SI(e);Y_(r)||wI(r,{recursive:!0}),bI(e,JSON.stringify(t,null,2)+`
14
- `)}function yc(t){return t.includes("waggle-cli")||t.includes("/cli/hooks/")||t.includes(" hook ")}function cs(t=10){let e=process.argv[1],r=Q_();r.hooks||(r.hooks={});let n=[{event:"SessionStart",name:"session-start"},{event:"PreToolUse",name:"pre-tool-use",matcher:"Edit|Write"},{event:"PostToolUse",name:"post-tool-use",matcher:"Edit|Write"},{event:"Stop",name:"stop"},{event:"UserPromptSubmit",name:"prompt-submit"}];for(let o of n){let s=`node "${e}" hook ${o.name}`;r.hooks[o.event]||(r.hooks[o.event]=[]);let i=r.hooks[o.event].find(a=>yc(a.command));if(i)i.command=s,i.timeout=t,o.matcher&&(i.matcher=o.matcher);else{let a={type:"command",command:s,timeout:t};o.matcher&&(a.matcher=o.matcher),r.hooks[o.event].push(a)}}eb(r)}function vc(){let t=Q_();if(t.hooks){for(let e of Object.keys(t.hooks))t.hooks[e]=t.hooks[e].filter(r=>!yc(r.command)),t.hooks[e].length===0&&delete t.hooks[e];Object.keys(t.hooks).length===0&&delete t.hooks,eb(t)}}var yi=w(()=>{"use strict"});import{request as $I}from"node:http";import{request as kI}from"node:https";function Q(t){let e=t.server.replace(/\/$/,""),r=(t.namespace??"default")==="default"?"":`/${t.namespace}`;function n(o,s,i){return new Promise((a,c)=>{let l=new URL(`${e}/api${r}${s}`),p=l.protocol==="https:"?kI:$I,m={"X-Agent-Id":t.agentId},d;i!==void 0&&(d=JSON.stringify(i),m["Content-Type"]="application/json",m["Content-Length"]=Buffer.byteLength(d).toString());let f=p(l,{method:o,headers:m,timeout:EI},h=>{let g="";h.on("data",v=>g+=v),h.on("end",()=>{try{let v=g?JSON.parse(g):{};a({ok:h.statusCode>=200&&h.statusCode<300,status:h.statusCode,data:v})}catch{a({ok:!1,status:h.statusCode,data:{}})}})});f.on("error",h=>c(h)),f.on("timeout",()=>{f.destroy(),c(new Error("timeout"))}),d&&f.write(d),f.end()})}return{health:()=>n("GET","/health"),getControlStatus:()=>n("GET","/control/status"),halt:(o,s)=>n("POST","/control/halt",{reason:o,...s}),pause:(o,s)=>n("POST","/control/pause",{reason:o,...s}),resume:o=>n("POST","/control/resume",o??{}),claim:(o,s,i)=>n("POST","/claims",{resource:o,value:s||o,...i}),releaseClaim:o=>n("DELETE",`/claims/${encodeURIComponent(o)}`),getClaims:o=>{let s=o?`?pattern=${encodeURIComponent(o)}`:"";return n("GET",`/claims${s}`)},checkClaim:o=>n("GET",`/claims/${encodeURIComponent(o)}`),listClaims:o=>{let s=o?`?pattern=${encodeURIComponent(o)}`:"";return n("GET",`/claims${s}`)},publishEvent:(o,s)=>n("POST","/events",{type:o,data:s}),getEvents:(o,s)=>{let i=[];o!==void 0&&i.push(`since=${o}`),s?.type&&i.push(`type=${encodeURIComponent(s.type)}`);let a=i.length?`?${i.join("&")}`:"";return n("GET",`/events${a}`)},publishDiscovery:(o,s,i)=>n("POST","/discoveries",{topic:o,content:s,category:i}),getDiscoveries:()=>n("GET","/discoveries"),searchDiscoveries:o=>{let s=[];o?.query&&s.push(`query=${encodeURIComponent(o.query)}`),o?.category&&s.push(`category=${encodeURIComponent(o.category)}`);let i=s.length?`?${s.join("&")}`:"";return n("GET",`/discoveries${i}`)},sendMessage:(o,s,i)=>n("POST","/messages",{to:o,content:s,...i}),getMessages:o=>{let s=o?.since?`?since=${encodeURIComponent(o.since)}`:"";return n("GET",`/messages${s}`)},requestRole:(o,s)=>n("POST","/roles/request",{role:o,...s}),getRoles:()=>n("GET","/roles"),getHelp:()=>n("GET","/help"),requestHelp:(o,s,i)=>n("POST","/help",{problem:o,needs_capability:s,urgency:i}),claimHelp:o=>n("POST",`/help/${encodeURIComponent(o)}/claim`),resolveHelp:o=>n("POST",`/help/${encodeURIComponent(o)}/resolve`),reportProgress:(o,s,i)=>n("POST","/progress",{claim:o,progress:s,note:i}),getProtocol:o=>{let s=o?`?role=${encodeURIComponent(o)}`:"";return n("GET",`/protocol${s}`)},loadProtocol:o=>n("PUT","/protocol",o),getState:(o,s)=>{let i=[];o&&i.push(`pattern=${encodeURIComponent(o)}`),s&&i.push(`category=${encodeURIComponent(s)}`);let a=i.length?`?${i.join("&")}`:"";return n("GET",`/state${a}`)},getStateKey:o=>n("GET",`/state/${encodeURIComponent(o)}`),queryState:o=>{let s=[];o?.pattern&&s.push(`pattern=${encodeURIComponent(o.pattern)}`),o?.category&&s.push(`category=${encodeURIComponent(o.category)}`);let i=s.length?`?${s.join("&")}`:"";return n("GET",`/state${i}`)},setState:(o,s,i,a)=>n("PUT",`/state/${encodeURIComponent(o)}`,{value:s,category:i,ttlMs:a}),deleteState:o=>n("DELETE",`/state/${encodeURIComponent(o)}`),flagConflict:(o,s,i)=>n("POST","/conflicts",{discovery_a:o,discovery_b:s,reason:i}),requestReinforcement:(o,s)=>n("POST","/reinforcements",{role:o,...s}),requestApproval:(o,s)=>n("POST","/governance/approve",{action:o,...s}),escalate:(o,s)=>n("POST","/governance/escalate",{reason:o,context:s}),proposeAction:(o,s)=>n("POST","/governance/propose",{action:o,...s}),endorseAction:o=>n("POST",`/governance/endorse/${encodeURIComponent(o)}`),requestRollback:(o,s)=>n("POST","/governance/rollback",{reason:o,scope:s}),getTopics:()=>n("GET","/topics"),subscribeTopic:o=>n("POST","/topics/subscribe",{topic:o}),unsubscribeTopic:o=>n("DELETE",`/topics/subscribe/${encodeURIComponent(o)}`),publishTopic:o=>n("POST","/topics/publish",{topic:o}),unpublishTopic:o=>n("DELETE",`/topics/publish/${encodeURIComponent(o)}`),getNamespaces:()=>n("GET","/_ns"),createNamespace:o=>n("POST","/_ns",{name:o}),deleteNamespace:o=>n("DELETE",`/_ns/${encodeURIComponent(o)}`)}}var EI,tb=w(()=>{EI=3e3});var Xe=w(()=>{tb()});var rb={};X(rb,{init:()=>PI});import{createInterface as TI}from"node:readline";function gd(t,e,r){let n=r?` ${y("dim",`[${r}]`)}`:"";return new Promise(o=>{t.question(` ${e}${n}: `,s=>{o(s.trim()||r||"")})})}async function PI(t){be()&&(console.log(b("Already initialized. Run `wgl leave` first to reset.")),process.exit(1));let r=t.includes("--yes")||t.includes("-y"),n,o,s,i=t.findIndex(d=>d==="--server"||d==="-s"),a=t.findIndex(d=>d==="--namespace"||d==="-n"),c=t.findIndex(d=>d==="--role"||d==="-r");if(r)n=i>=0?t[i+1]:"http://localhost:3100",o=a>=0?t[a+1]:"default",s=c>=0?t[c+1]:"developer";else{let d=TI({input:process.stdin,output:process.stdout});console.log(C("waggle-cli setup")),console.log(),n=await gd(d,"Server URL","http://localhost:3100"),o=await gd(d,"Namespace","default"),s=await gd(d,"Role","developer"),d.close(),console.log()}let l=ac(),u=gc(n,l,s,o),p=Q(u);try{let d=await p.health();d.ok||(console.log(b(`Server returned ${d.status}. Check the URL and try again.`)),process.exit(1))}catch{console.log(b(`Cannot reach ${n}. Is the incubator running?`)),process.exit(1)}try{await p.requestRole(s)}catch{}let m=hc(u);cs(u.hookTimeout),console.log(z("Initialized waggle-cli")),console.log(S("Config",m)),console.log(S("Agent ID",l)),console.log(S("Server",n)),console.log(S("Namespace",o)),console.log(S("Role",s)),console.log(),console.log(` Hooks installed in ${y("dim",".claude/settings.local.json")}`),console.log(" Start a Claude Code session to begin coordinating.")}var nb=w(()=>{"use strict";Fp();dt();yi();Xe();Re()});var ob={};X(ob,{join:()=>RI});async function RI(t){be()&&(console.log(b("Already joined. Run `wgl leave` first.")),process.exit(1));let r=t.find(u=>u.startsWith("http"));r||(console.log(b("Usage: wgl join <server-url> [--role <role>] [--namespace <ns>]")),process.exit(1));let n=t.findIndex(u=>u==="--role"||u==="-r"),o=t.findIndex(u=>u==="--namespace"||u==="-n"),s=n>=0?t[n+1]:"developer",i=o>=0?t[o+1]:"default",a=ac(),c=gc(r,a,s,i),l=Q(c);try{let u=await l.health();u.ok||(console.log(b(`Server returned ${u.status}`)),process.exit(1))}catch{console.log(b(`Cannot reach ${r}`)),process.exit(1)}try{await l.requestRole(s)}catch{}hc(c),cs(c.hookTimeout),console.log(z("Joined coordination server")),console.log(S("Agent ID",a)),console.log(S("Server",r)),console.log(S("Role",s));try{let[u,p]=await Promise.all([l.getProtocol(),l.getRoles()]);if(u.ok&&u.data){let m=u.data;m.name&&(console.log(C("Protocol")),console.log(S("Name",m.name)),m.description&&console.log(S("Description",m.description)),m.phases?.length&&console.log(S("Phases",m.phases.map(d=>d.name).join(" \u2192 "))))}if(p.ok&&Array.isArray(p.data)&&p.data.length>0){console.log(C("Team"));for(let m of p.data){let d=m.agent===a?y("green"," (you)"):"";console.log(` ${y("bold",m.role)}: ${m.agent}${d}`)}}}catch{}console.log()}var sb=w(()=>{"use strict";Fp();dt();yi();Xe();Re()});var ib={};X(ib,{status:()=>OI});async function OI(){let t=be();t||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);console.log(C("waggle-cli status")),console.log(S("Agent ID",t.agentId)),console.log(S("Server",t.server)),console.log(S("Namespace",t.namespace)),console.log(S("Role",t.role));try{let[r,n,o]=await Promise.all([e.getControlStatus(),e.getClaims(),e.getEvents(t.lastEventCursor)]);if(r.ok){let s=r.data;console.log(C("Control")),s.halted?console.log(` ${y("red","HALTED")}${s.reason?` \u2014 ${s.reason}`:""}`):s.paused?console.log(` ${y("yellow","PAUSED")}${s.reason?` \u2014 ${s.reason}`:""}`):console.log(` ${y("green","RUNNING")}`)}if(n.ok&&Array.isArray(n.data)){let s=n.data,i=s.filter(c=>c.owner===t.agentId&&c.status==="active"),a=s.filter(c=>c.owner!==t.agentId&&c.status==="active");if(console.log(C("Claims")),i.length===0&&a.length===0)console.log(` ${y("dim","No active claims")}`);else{for(let c of i)console.log(` ${y("green","\u25CF")} ${c.resource} ${y("dim","(yours)")}`);for(let c of a)console.log(` ${y("yellow","\u25CF")} ${c.resource} ${y("dim",`(${c.owner})`)}`)}}if(o.ok&&Array.isArray(o.data)){let s=o.data;if(console.log(C("Recent Events")),s.length===0)console.log(` ${y("dim","No new events")}`);else{let i=s.slice(-10);for(let a of i)console.log(` ${y("dim",`#${a.id}`)} ${y("bold",a.type)} ${y("dim",`by ${a.publishedBy}`)}`);s.length>10&&console.log(` ${y("dim",`... and ${s.length-10} more`)}`)}}}catch{console.log(`
15
- ${y("yellow","Server unreachable")}`)}console.log()}var ab=w(()=>{"use strict";dt();Xe();Re()});var cb={};X(cb,{leave:()=>CI});async function CI(){let t=be();t||(console.log(b("Not initialized. Nothing to do.")),process.exit(1));let e=Q(t);try{let r=await e.getClaims();if(r.ok&&Array.isArray(r.data)){let n=r.data.filter(o=>o.owner===t.agentId&&o.status==="active");for(let o of n)await e.releaseClaim(o.resource)}}catch{}try{await e.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role})}catch{}vc(),K_(),console.log(z("Left coordination server. Hooks removed, config deleted."))}var lb=w(()=>{"use strict";dt();yi();Xe();Re()});var _c,yd=w(()=>{_c="1.0"});var ub={};X(ub,{SpecValidationError:()=>ao,normalizeAgents:()=>_d,normalizeRules:()=>vi,validateSpec:()=>vd});function vd(t){let e=[];if(!t||typeof t!="object")return["Spec must be a YAML/JSON object"];let r=t;if(!r.acp||typeof r.acp!="string")e.push('Missing or invalid "acp" version string');else if(!/^\d+\.\d+$/.test(r.acp))e.push(`Invalid "acp" version format: "${r.acp}" (expected "X.Y")`);else{let[n]=r.acp.split(".").map(Number),[o]=_c.split(".").map(Number);n!==o&&e.push(`Unsupported ACP version ${r.acp} (this parser supports ${_c})`)}if(!r.name||typeof r.name!="string"?e.push('Missing or invalid "name" string'):/^[a-z][a-z0-9-]*$/.test(r.name)||e.push(`Invalid "name": "${r.name}" (must be lowercase alphanumeric with hyphens, starting with a letter)`),(!r.title||typeof r.title!="string")&&e.push('Missing or invalid "title" string'),!r.roles||typeof r.roles!="object"||Array.isArray(r.roles))e.push('Missing or invalid "roles" object');else{let n=r.roles;Object.keys(n).length===0&&e.push('"roles" must have at least one role');for(let[o,s]of Object.entries(n)){if(!s||typeof s!="object"){e.push(`Role "${o}" must be an object`);continue}let i=s;if((!i.description||typeof i.description!="string")&&e.push(`Role "${o}" missing "description"`),i.count!==void 0&&typeof i.count!="string"&&e.push(`Role "${o}".count must be a string`),i.can_become!==void 0&&(Array.isArray(i.can_become)||e.push(`Role "${o}".can_become must be an array`)),i.scope!==void 0&&(!Array.isArray(i.scope)||i.scope.some(a=>typeof a!="string"||a===""))&&e.push(`Role "${o}".scope must be an array of non-empty strings`),i.capabilities!==void 0&&(!Array.isArray(i.capabilities)||i.capabilities.some(a=>typeof a!="string"||a===""))&&e.push(`Role "${o}".capabilities must be an array of non-empty strings`),i.agents!==void 0)if(typeof i.agents=="number")(!Number.isInteger(i.agents)||i.agents<1)&&e.push(`Role "${o}".agents must be a positive integer`);else if(Array.isArray(i.agents))i.agents.length!==2||!i.agents.every(a=>typeof a=="number"&&Number.isInteger(a)&&a>=1)?e.push(`Role "${o}".agents array must be [min, max] with positive integers`):i.agents[0]>i.agents[1]&&e.push(`Role "${o}".agents[0] (min) must be \u2264 agents[1] (max)`);else if(typeof i.agents=="object"&&i.agents!==null){let a=i.agents;for(let c of["default","min","max"])a[c]!==void 0&&(typeof a[c]!="number"||!Number.isInteger(a[c])||a[c]<1)&&e.push(`Role "${o}".agents.${c} must be a positive integer`);typeof a.min=="number"&&typeof a.max=="number"&&a.min>a.max&&e.push(`Role "${o}".agents.min must be \u2264 agents.max`),typeof a.default=="number"&&(typeof a.min=="number"&&a.default<a.min&&e.push(`Role "${o}".agents.default must be \u2265 agents.min`),typeof a.max=="number"&&a.default>a.max&&e.push(`Role "${o}".agents.default must be \u2264 agents.max`))}else e.push(`Role "${o}".agents must be a number, [min, max] array, or {default, min, max} object`);if(i.primitives!==void 0)if(typeof i.primitives!="object"||Array.isArray(i.primitives)||i.primitives===null)e.push(`Role "${o}".primitives must be an object`);else{let a=i.primitives;a.env!==void 0&&(!Array.isArray(a.env)||a.env.some(c=>typeof c!="string"||c===""))&&e.push(`Role "${o}".primitives.env must be an array of non-empty strings`),a.acp!==void 0&&(!Array.isArray(a.acp)||a.acp.some(c=>typeof c!="string"||c===""))&&e.push(`Role "${o}".primitives.acp must be an array of non-empty strings`)}if(i.wait!==void 0)if(typeof i.wait!="object"||Array.isArray(i.wait)||i.wait===null)e.push(`Role "${o}".wait must be an object`);else{let a=i.wait;a.types!==void 0&&(!Array.isArray(a.types)||a.types.some(c=>typeof c!="string"||c===""))&&e.push(`Role "${o}".wait.types must be an array of non-empty strings`),a.max_timeout!==void 0&&(typeof a.max_timeout!="number"||a.max_timeout<=0)&&e.push(`Role "${o}".wait.max_timeout must be a positive number`)}}}if(!r.phases||typeof r.phases!="object"||Array.isArray(r.phases))e.push('Missing or invalid "phases" object');else{let n=r.phases;Object.keys(n).length===0&&e.push('"phases" must have at least one phase');let o=!1;for(let[s,i]of Object.entries(n)){if(!i||typeof i!="object"){e.push(`Phase "${s}" must be an object`);continue}let a=i;(!a.description||typeof a.description!="string")&&e.push(`Phase "${s}" missing "description"`),a.terminal===!0&&(o=!0)}o||e.push("At least one phase must be terminal")}if(r.roles&&typeof r.roles=="object"&&!Array.isArray(r.roles)){let n=new Set(Object.keys(r.roles));for(let[o,s]of Object.entries(r.roles))if(s?.can_become&&Array.isArray(s.can_become))for(let i of s.can_become)typeof i=="string"&&!n.has(i)&&e.push(`Role "${o}".can_become references unknown role "${i}"`)}if(r.governance!==void 0)if(typeof r.governance!="object"||Array.isArray(r.governance)||r.governance===null)e.push('"governance" must be an object');else{let n=r.governance;if(n.budget!==void 0&&typeof n.budget=="object"&&n.budget!==null){let o=n.budget;o.warn_at!==void 0&&(typeof o.warn_at!="number"||o.warn_at<0||o.warn_at>1)&&e.push("governance.budget.warn_at must be a number between 0 and 1")}if(n.escalation!==void 0&&typeof n.escalation=="object"&&n.escalation!==null){let o=n.escalation;if(o.triggers!==void 0)if(!Array.isArray(o.triggers))e.push("governance.escalation.triggers must be an array");else{let s=new Set(["notify","halt","request_approval"]);for(let[i,a]of o.triggers.entries()){if(!a||typeof a!="object")continue;let c=a;(!c.condition||typeof c.condition!="string")&&e.push(`governance.escalation.triggers[${i}] missing "condition"`),(!c.action||typeof c.action!="string"||!s.has(c.action))&&e.push(`governance.escalation.triggers[${i}].action must be "notify", "halt", or "request_approval"`)}}}if(n.quorum!==void 0&&typeof n.quorum=="object"&&n.quorum!==null){let o=n.quorum;o.default!==void 0&&(typeof o.default!="number"||o.default<1||!Number.isInteger(o.default))&&e.push("governance.quorum.default must be a positive integer")}if(n.approval_gates!==void 0)if(!Array.isArray(n.approval_gates))e.push("governance.approval_gates must be an array");else{let o=r.roles&&typeof r.roles=="object"?new Set(Object.keys(r.roles)):new Set;for(let[s,i]of n.approval_gates.entries()){if(!i||typeof i!="object")continue;let a=i;(!a.action||typeof a.action!="string")&&e.push(`governance.approval_gates[${s}] missing "action"`),a.required_role!==void 0&&typeof a.required_role=="string"&&a.required_role!=="human"&&!o.has(a.required_role)&&e.push(`governance.approval_gates[${s}].required_role references unknown role "${a.required_role}"`)}}if(n.heartbeat!==void 0&&typeof n.heartbeat=="object"&&n.heartbeat!==null){let o=n.heartbeat;o.stale_after_ms!==void 0&&o.dead_after_ms!==void 0&&typeof o.stale_after_ms=="number"&&typeof o.dead_after_ms=="number"&&o.stale_after_ms>=o.dead_after_ms&&e.push("governance.heartbeat.stale_after_ms must be less than dead_after_ms")}}if(r.variables!==void 0)if(typeof r.variables!="object"||Array.isArray(r.variables)||r.variables===null)e.push('"variables" must be an object');else{let n=new Set(["string","number","boolean","array","object"]);for(let[o,s]of Object.entries(r.variables)){if(!s||typeof s!="object"){e.push(`Variable "${o}" must be an object`);continue}let i=s;(!i.type||typeof i.type!="string"||!n.has(i.type))&&e.push(`Variable "${o}".type must be one of: string, number, boolean, array, object`)}}if(r.topics!==void 0)if(typeof r.topics!="object"||Array.isArray(r.topics)||r.topics===null)e.push('"topics" must be an object');else{let n=r.topics;n.publishes!==void 0&&(Array.isArray(n.publishes)?n.publishes.some(o=>typeof o!="string"||o==="")&&e.push("topics.publishes must be an array of non-empty strings"):e.push("topics.publishes must be an array")),n.subscribes!==void 0&&(Array.isArray(n.subscribes)?n.subscribes.some(o=>typeof o!="string"||o==="")&&e.push("topics.subscribes must be an array of non-empty strings"):e.push("topics.subscribes must be an array"))}if(r.rules&&typeof r.rules=="object"){let n=r.roles&&typeof r.roles=="object"?new Set(Object.keys(r.roles)):new Set,o=r.phases&&typeof r.phases=="object"?new Set(Object.keys(r.phases)):new Set;for(let[s,i]of Object.entries(r.rules)){if(!n.has(s)){e.push(`Rules reference unknown role "${s}"`);continue}if(!(!i||typeof i!="object"))for(let a of Object.keys(i))o.has(a)||e.push(`Rules for role "${s}" reference unknown phase "${a}"`)}}return e}function vi(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){e[r]={};for(let[o,s]of Object.entries(n))Array.isArray(s)?e[r][o]={steps:s}:e[r][o]=s}return e}function _d(t){if(t===void 0)return{default:1,min:1,max:1};if(typeof t=="number")return{default:t,min:t,max:t};if(Array.isArray(t))return{default:t[0],min:t[0],max:t[1]};let e=t.min??1,r=t.default??e,n=t.max??Math.max(r,e);return{default:r,min:e,max:n}}var ao,bc=w(()=>{yd();ao=class extends Error{errors;constructor(e){super(`Invalid ACP spec:
3
+ var dI=Object.create;var Gp=Object.defineProperty;var fI=Object.getOwnPropertyDescriptor;var mI=Object.getOwnPropertyNames;var hI=Object.getPrototypeOf,gI=Object.prototype.hasOwnProperty;var st=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var w=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),K=(t,e)=>{for(var r in e)Gp(t,r,{get:e[r],enumerable:!0})},yI=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of mI(e))!gI.call(t,o)&&o!==r&&Gp(t,o,{get:()=>e[o],enumerable:!(n=fI(e,o))||n.enumerable});return t};var oo=(t,e,r)=>(r=t!=null?dI(hI(t)):{},yI(e||!t||!t.__esModule?Gp(r,"default",{value:t,enumerable:!0}):r,t));function y(t,e){return`${H_[t]}${e}${H_.reset}`}function C(t){return`
4
+ ${y("bold",y("cyan",t))}`}function N(t){return y("green",`\u2713 ${t}`)}function gn(t){return y("yellow",`\u26A0 ${t}`)}function _(t){return y("red",`\u2717 ${t}`)}function S(t,e){return` ${y("bold",t+":")} ${e}`}function sr(t){let e=Math.max(...t.map(([r])=>r.length));return t.map(([r,n])=>` ${y("bold",r.padEnd(e))} ${n}`).join(`
5
+ `)}var H_,Re=w(()=>{"use strict";H_={red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m"}});import{randomBytes as vI}from"node:crypto";function uc(){return`wgl_${vI(4).toString("hex")}`}var Vp=w(()=>{"use strict"});import{join as B_}from"node:path";import{homedir as G_}from"node:os";var ht,yn,ss,Wp,is,Jp,pc,so,as,dc,Kp,Yp,yi,Xp,Qp,ed,td,rd,io=w(()=>{ht=B_(G_(),".honeyb"),yn=B_(G_(),".wgl"),ss="auth.json",Wp="integrations.json",is=".honeyb",Jp=".honeybee",pc=[".wglrc.yaml",".wglrc.json",".wglrc"],so=".wgl.json",as="session.json",dc="brood.state.json",Kp="logs",Yp=10,yi="telemetry",Xp=30,Qp=3e5,ed=3e5,td={HONEYB_PLATFORM:"platform",CARAPACE_PORT:"carapace.proxyPort",CARAPACE_UPSTREAM:"carapace.upstream",CARAPACE_MODE:"carapace.mode",CARAPACE_THRESHOLD:"carapace.threshold",TELEMETRY_ENDPOINT:"telemetry.endpoint",TELEMETRY_API_KEY:"telemetry.apiKey",INCUBATOR_PORT:"incubator.port"},rd={platform:"https://hivemind.honeyb.dev",activeProfile:"personal",cli:{editor:"nano",hookTimeout:10,autoClaimFiles:!0},incubator:{port:3100,backend:"memory",verbose:!1,guard:!0},carapace:{mode:"block",threshold:100,proxyPort:8888},telemetry:{},pricing:{},servers:{}}});import{readFileSync as K_,writeFileSync as nd,existsSync as Dt,mkdirSync as fc,copyFileSync as od,chmodSync as _I}from"node:fs";import{join as Yt,resolve as bI}from"node:path";import{homedir as V_}from"node:os";function sd(){if(W_)return;W_=!0;let t=Yt(yn,"auth.json"),e=Yt(ht,ss);Dt(t)&&!Dt(e)&&(Dt(ht)||fc(ht,{recursive:!0}),od(t,e),_I(e,384),console.error("[honeyb] Migrated auth store: ~/.wgl/auth.json \u2192 ~/.honeyb/auth.json"));let r=Yt(yn,"config.json"),n=V_(),o=Yt(n,".wglrc.json");if(Dt(r)&&!Dt(o))try{let a=JSON.parse(K_(r,"utf8")),c={};a.defaultPlatform&&(c.platform=a.defaultPlatform),a.defaultRole&&(c.role=a.defaultRole),a.activeProfile&&(c.activeProfile=a.activeProfile),a.editor&&(c.cli={...c.cli,editor:a.editor});let l=new Set(["defaultPlatform","defaultRole","activeProfile","editor"]);for(let[u,p]of Object.entries(a))!l.has(u)&&typeof p=="string"&&(c[u]=p);Object.keys(c).length>0&&(nd(o,JSON.stringify(c,null,2)+`
6
+ `),console.error("[honeyb] Migrated global config: ~/.wgl/config.json \u2192 ~/.wglrc.json"))}catch{}let s=Yt(V_(),".config","honeybee","integrations.json"),i=Yt(ht,Wp);Dt(s)&&!Dt(i)&&(Dt(ht)||fc(ht,{recursive:!0}),od(s,i),console.error("[honeyb] Migrated integrations: ~/.config/honeybee/integrations.json \u2192 ~/.honeyb/integrations.json"))}function id(t){let e=bI(t||process.cwd());if(J_.has(e))return;J_.add(e);let r=Yt(e,so),n=Yt(e,".wglrc.json"),o=Yt(e,is),s=Yt(o,as);if(Dt(r)&&!Dt(n))try{let l=JSON.parse(K_(r,"utf8")),u={};l.server&&(u.server=l.server),l.namespace&&(u.namespace=l.namespace),l.role&&(u.role=l.role),(l.autoClaimFiles!==void 0||l.hookTimeout!==void 0)&&(u.cli={},l.autoClaimFiles!==void 0&&(u.cli.autoClaimFiles=l.autoClaimFiles),l.hookTimeout!==void 0&&(u.cli.hookTimeout=l.hookTimeout)),Object.keys(u).length>0&&nd(n,JSON.stringify(u,null,2)+`
7
+ `);let p={};l.agentId&&(p.agentId=l.agentId),l.lastEventCursor!==void 0&&(p.lastEventCursor=l.lastEventCursor),l.autoPublishDiscoveries!==void 0&&(p.autoPublishDiscoveries=l.autoPublishDiscoveries),Object.keys(p).length>0&&(Dt(o)||fc(o,{recursive:!0}),nd(s,JSON.stringify(p,null,2)+`
8
+ `)),console.error("[honeyb] Migrated project config: .wgl.json \u2192 .wglrc.json + .honeyb/session.json")}catch{}let i=Yt(e,Jp),a=Yt(i,"brood.state.json"),c=Yt(o,dc);Dt(a)&&!Dt(c)&&(Dt(o)||fc(o,{recursive:!0}),od(a,c),console.error("[honeyb] Migrated brood state: .honeybee/brood.state.json \u2192 .honeyb/brood.state.json"))}var W_,J_,ad=w(()=>{io();W_=!1,J_=new Set});import{readFileSync as ld,writeFileSync as SI,existsSync as vn,mkdirSync as mc,readdirSync as $I,unlinkSync as kI}from"node:fs";import{join as wr,dirname as Y_,resolve as vi,sep as EI}from"node:path";import{homedir as TI}from"node:os";function ud(t){let e=vi(t||process.cwd()),r=EI==="/"?"/":e.slice(0,3);for(;;){for(let o of pc){let s=wr(e,o);if(vn(s))return s}let n=Y_(e);if(n===e||e===r)return null;e=n}}function X_(){let t=TI();for(let e of pc){let r=wr(t,e);if(vn(r))return r}return null}function cd(t){let e=ld(t,"utf8").trim();return e?t.endsWith(".yaml")?PI(e):t.endsWith(".json")?Q_(e):OI(e):{}}function Q_(t){try{let e=JSON.parse(t);return typeof e!="object"||e===null||Array.isArray(e)?{}:e}catch{return{}}}function PI(t){try{return RI(t)}catch{return Q_(t)}}function RI(t){let e={},r=t.split(`
9
+ `),n=[{indent:-1,obj:e}];for(let o of r){let s=o.replace(/#.*$/,"").trimEnd();if(!s)continue;let i=o.length-o.trimStart().length,a=s.match(/^(\s*)([^:]+):\s*(.*)$/);if(!a)continue;let c=a[2].trim(),l=a[3].trim();for(;n.length>1&&n[n.length-1].indent>=i;)n.pop();let u=n[n.length-1].obj;if(l===""){let p={};u[c]=p,n.push({indent:i,obj:p})}else u[c]=pd(l)}return e}function OI(t){let e={};for(let r of t.split(`
10
+ `)){let n=r.trim();if(!n||n.startsWith("#"))continue;let o=n.indexOf("=");if(o<1)continue;let s=n.slice(0,o).trim(),i=n.slice(o+1).trim();_i(e,s,pd(i))}return e}function pd(t){if(t.startsWith('"')&&t.endsWith('"')||t.startsWith("'")&&t.endsWith("'"))return t.slice(1,-1);if(t==="true")return!0;if(t==="false")return!1;if(t==="null"||t==="")return"";let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}function _i(t,e,r){let n=e.split("."),o=t;for(let s=0;s<n.length-1;s++){let i=n[s];(typeof o[i]!="object"||o[i]===null)&&(o[i]={}),o=o[i]}o[n[n.length-1]]=r}function hc(t,e){let r=e.split("."),n=t;for(let o of r){if(typeof n!="object"||n===null)return;n=n[o]}return n}function ao(t,e){let r={...t};for(let n of Object.keys(e)){let o=e[n],s=r[n];o==null?delete r[n]:typeof s=="object"&&s!==null&&!Array.isArray(s)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?r[n]=ao(s,o):r[n]=o}return r}function CI(){let t={};for(let[e,r]of Object.entries(td)){let n=process.env[e];n!==void 0&&n!==""&&_i(t,r,pd(n))}return t}function Nr(t){sd(),id(t);let e=structuredClone(rd),r=X_();r&&(e=ao(e,cd(r)));let n=ud(t);if(n&&(e=ao(e,cd(n))),!n){let o=II(t);if(o){let s=AI(o);s&&(e=ao(e,s))}}return e=ao(e,CI()),Object.freeze(e)}function dd(){return vn(ht)||mc(ht,{recursive:!0}),ht}function eb(t){return vi(t||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}function cs(t){let e=eb(t),r=wr(dd(),"projects",e);return vn(r)||mc(r,{recursive:!0}),r}function tb(t){let e=vi(t||process.cwd()),r=wr(e,is);return vn(r)||mc(r,{recursive:!0}),r}function fd(t){let e=wr(vi(t||process.cwd()),is),r=wr(e,as);if(!vn(r))return{};try{return JSON.parse(ld(r,"utf8"))}catch{return{}}}function md(t,e){let r=tb(e),n=wr(r,as);SI(n,JSON.stringify(t,null,2)+`
11
+ `)}function _n(t){let e=wr(cs(t),Kp);return vn(e)||mc(e,{recursive:!0}),e}function hd(t){let e=_n(t),r=new Date().toISOString().replace(/[:.]/g,"-");return wr(e,`${r}.jsonl`)}function gd(t){let e=_n(t);try{let r=$I(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();for(let n=Yp;n<r.length;n++)kI(wr(e,r[n]))}catch{}}function II(t){let e=vi(t||process.cwd()),r="/";for(;;){let n=wr(e,so);if(vn(n))return n;let o=Y_(e);if(o===e||e===r)return null;e=o}}function AI(t){try{let e=JSON.parse(ld(t,"utf8")),r={};return e.server&&(r.server=e.server),e.namespace&&(r.namespace=e.namespace),e.role&&(r.role=e.role),e.autoClaimFiles!==void 0&&(r.cli={...r.cli,autoClaimFiles:e.autoClaimFiles}),e.hookTimeout!==void 0&&(r.cli={...r.cli,hookTimeout:e.hookTimeout}),r}catch{return null}}var gc=w(()=>{io();ad()});import{readFileSync as NI,writeFileSync as zI,existsSync as yc,mkdirSync as jI,chmodSync as MI}from"node:fs";import{join as yd}from"node:path";function LI(){let t=yd(ht,ss);if(yc(t))return t;let e=yd(yn,"auth.json");return yc(e)?e:t}function ls(){let t=LI();if(!yc(t))return{profiles:{}};try{return JSON.parse(NI(t,"utf8"))}catch{return{profiles:{}}}}function vc(t){yc(ht)||jI(ht,{recursive:!0});let e=yd(ht,ss);zI(e,JSON.stringify(t,null,2)+`
12
+ `,{mode:384}),MI(e,384)}function vd(t){return ls().profiles[t]||null}function _d(t,e){let r=ls();r.profiles[t]=e,vc(r)}function bd(t){let e=ls();return t in e.profiles?(delete e.profiles[t],vc(e),!0):!1}function wd(){let t=ls();return Object.keys(t.profiles)}var rb=w(()=>{io()});var bn=w(()=>{io();gc();rb();ad()});import{writeFileSync as DI,existsSync as nb,unlinkSync as ob}from"node:fs";import{join as xd}from"node:path";function be(t){let e=Nr(t),r=fd(t);return e.server?{server:e.server,namespace:e.namespace??"default",agentId:r.agentId??"",role:e.role??"developer",autoClaimFiles:e.cli.autoClaimFiles,autoPublishDiscoveries:r.autoPublishDiscoveries??!0,hookTimeout:e.cli.hookTimeout,lastEventCursor:r.lastEventCursor??0}:null}function _c(t,e){let r=e||process.cwd(),n={server:t.server,namespace:t.namespace,role:t.role,cli:{autoClaimFiles:t.autoClaimFiles,hookTimeout:t.hookTimeout}},o=xd(r,".wglrc.json");DI(o,JSON.stringify(n,null,2)+`
13
+ `);let s={agentId:t.agentId,lastEventCursor:t.lastEventCursor,autoPublishDiscoveries:t.autoPublishDiscoveries};return md(s,r),o}function sb(t){let e=t||process.cwd(),r=!1;for(let o of[".wglrc.json",".wglrc.yaml",".wglrc"]){let s=xd(e,o);nb(s)&&(ob(s),r=!0)}let n=xd(e,so);return nb(n)&&(ob(n),r=!0),r}function bc(t,e,r,n){return{server:t,namespace:n||"default",agentId:e,role:r,autoClaimFiles:!0,autoPublishDiscoveries:!0,hookTimeout:10,lastEventCursor:0}}var dt=w(()=>{"use strict";bn()});import{readFileSync as qI,writeFileSync as ZI,existsSync as ib,mkdirSync as UI}from"node:fs";import{join as FI,dirname as HI}from"node:path";function ab(){return FI(process.cwd(),".claude","settings.local.json")}function cb(){let t=ab();if(!ib(t))return{};try{return JSON.parse(qI(t,"utf8"))}catch{return{}}}function lb(t){let e=ab(),r=HI(e);ib(r)||UI(r,{recursive:!0}),ZI(e,JSON.stringify(t,null,2)+`
14
+ `)}function wc(t){return t.includes("waggle-cli")||t.includes("/cli/hooks/")||t.includes(" hook ")}function us(t=10){let e=process.argv[1],r=cb();r.hooks||(r.hooks={});let n=[{event:"SessionStart",name:"session-start"},{event:"PreToolUse",name:"pre-tool-use",matcher:"Edit|Write"},{event:"PostToolUse",name:"post-tool-use",matcher:"Edit|Write"},{event:"Stop",name:"stop"},{event:"UserPromptSubmit",name:"prompt-submit"}];for(let o of n){let s=`node "${e}" hook ${o.name}`;r.hooks[o.event]||(r.hooks[o.event]=[]);let i=r.hooks[o.event].find(a=>wc(a.command));if(i)i.command=s,i.timeout=t,o.matcher&&(i.matcher=o.matcher);else{let a={type:"command",command:s,timeout:t};o.matcher&&(a.matcher=o.matcher),r.hooks[o.event].push(a)}}lb(r)}function xc(){let t=cb();if(t.hooks){for(let e of Object.keys(t.hooks))t.hooks[e]=t.hooks[e].filter(r=>!wc(r.command)),t.hooks[e].length===0&&delete t.hooks[e];Object.keys(t.hooks).length===0&&delete t.hooks,lb(t)}}var bi=w(()=>{"use strict"});import{request as BI}from"node:http";import{request as GI}from"node:https";function Q(t){let e=t.server.replace(/\/$/,""),r=(t.namespace??"default")==="default"?"":`/${t.namespace}`;function n(o,s,i){return new Promise((a,c)=>{let l=new URL(`${e}/api${r}${s}`),p=l.protocol==="https:"?GI:BI,f={"X-Agent-Id":t.agentId},d;i!==void 0&&(d=JSON.stringify(i),f["Content-Type"]="application/json",f["Content-Length"]=Buffer.byteLength(d).toString());let m=p(l,{method:o,headers:f,timeout:VI},h=>{let g="";h.on("data",v=>g+=v),h.on("end",()=>{try{let v=g?JSON.parse(g):{};a({ok:h.statusCode>=200&&h.statusCode<300,status:h.statusCode,data:v})}catch{a({ok:!1,status:h.statusCode,data:{}})}})});m.on("error",h=>c(h)),m.on("timeout",()=>{m.destroy(),c(new Error("timeout"))}),d&&m.write(d),m.end()})}return{health:()=>n("GET","/health"),getControlStatus:()=>n("GET","/control/status"),halt:(o,s)=>n("POST","/control/halt",{reason:o,...s}),pause:(o,s)=>n("POST","/control/pause",{reason:o,...s}),resume:o=>n("POST","/control/resume",o??{}),claim:(o,s,i)=>n("POST","/claims",{resource:o,value:s||o,...i}),releaseClaim:o=>n("DELETE",`/claims/${encodeURIComponent(o)}`),getClaims:o=>{let s=o?`?pattern=${encodeURIComponent(o)}`:"";return n("GET",`/claims${s}`)},checkClaim:o=>n("GET",`/claims/${encodeURIComponent(o)}`),listClaims:o=>{let s=o?`?pattern=${encodeURIComponent(o)}`:"";return n("GET",`/claims${s}`)},publishEvent:(o,s)=>n("POST","/events",{type:o,data:s}),getEvents:(o,s)=>{let i=[];o!==void 0&&i.push(`since=${o}`),s?.type&&i.push(`type=${encodeURIComponent(s.type)}`);let a=i.length?`?${i.join("&")}`:"";return n("GET",`/events${a}`)},publishDiscovery:(o,s,i)=>n("POST","/discoveries",{topic:o,content:s,category:i}),getDiscoveries:()=>n("GET","/discoveries"),searchDiscoveries:o=>{let s=[];o?.query&&s.push(`query=${encodeURIComponent(o.query)}`),o?.category&&s.push(`category=${encodeURIComponent(o.category)}`);let i=s.length?`?${s.join("&")}`:"";return n("GET",`/discoveries${i}`)},sendMessage:(o,s,i)=>n("POST","/messages",{to:o,content:s,...i}),getMessages:o=>{let s=o?.since?`?since=${encodeURIComponent(o.since)}`:"";return n("GET",`/messages${s}`)},requestRole:(o,s)=>n("POST","/roles/request",{role:o,...s}),getRoles:()=>n("GET","/roles"),getHelp:()=>n("GET","/help"),requestHelp:(o,s,i)=>n("POST","/help",{problem:o,needs_capability:s,urgency:i}),claimHelp:o=>n("POST",`/help/${encodeURIComponent(o)}/claim`),resolveHelp:o=>n("POST",`/help/${encodeURIComponent(o)}/resolve`),reportProgress:(o,s,i)=>n("POST","/progress",{claim:o,progress:s,note:i}),getProtocol:o=>{let s=o?`?role=${encodeURIComponent(o)}`:"";return n("GET",`/protocol${s}`)},loadProtocol:o=>n("PUT","/protocol",o),getState:(o,s)=>{let i=[];o&&i.push(`pattern=${encodeURIComponent(o)}`),s&&i.push(`category=${encodeURIComponent(s)}`);let a=i.length?`?${i.join("&")}`:"";return n("GET",`/state${a}`)},getStateKey:o=>n("GET",`/state/${encodeURIComponent(o)}`),queryState:o=>{let s=[];o?.pattern&&s.push(`pattern=${encodeURIComponent(o.pattern)}`),o?.category&&s.push(`category=${encodeURIComponent(o.category)}`);let i=s.length?`?${s.join("&")}`:"";return n("GET",`/state${i}`)},setState:(o,s,i,a)=>n("PUT",`/state/${encodeURIComponent(o)}`,{value:s,category:i,ttlMs:a}),deleteState:o=>n("DELETE",`/state/${encodeURIComponent(o)}`),flagConflict:(o,s,i)=>n("POST","/conflicts",{discovery_a:o,discovery_b:s,reason:i}),requestReinforcement:(o,s)=>n("POST","/reinforcements",{role:o,...s}),requestApproval:(o,s)=>n("POST","/governance/approve",{action:o,...s}),escalate:(o,s)=>n("POST","/governance/escalate",{reason:o,context:s}),proposeAction:(o,s)=>n("POST","/governance/propose",{action:o,...s}),endorseAction:o=>n("POST",`/governance/endorse/${encodeURIComponent(o)}`),requestRollback:(o,s)=>n("POST","/governance/rollback",{reason:o,scope:s}),getTopics:()=>n("GET","/topics"),subscribeTopic:o=>n("POST","/topics/subscribe",{topic:o}),unsubscribeTopic:o=>n("DELETE",`/topics/subscribe/${encodeURIComponent(o)}`),publishTopic:o=>n("POST","/topics/publish",{topic:o}),unpublishTopic:o=>n("DELETE",`/topics/publish/${encodeURIComponent(o)}`),getNamespaces:()=>n("GET","/_ns"),createNamespace:o=>n("POST","/_ns",{name:o}),deleteNamespace:o=>n("DELETE",`/_ns/${encodeURIComponent(o)}`)}}var VI,ub=w(()=>{VI=3e3});var Qe=w(()=>{ub()});var pb={};K(pb,{init:()=>JI});import{createInterface as WI}from"node:readline";function Sd(t,e,r){let n=r?` ${y("dim",`[${r}]`)}`:"";return new Promise(o=>{t.question(` ${e}${n}: `,s=>{o(s.trim()||r||"")})})}async function JI(t){be()&&(console.log(_("Already initialized. Run `wgl leave` first to reset.")),process.exit(1));let r=t.includes("--yes")||t.includes("-y"),n,o,s,i=t.findIndex(d=>d==="--server"||d==="-s"),a=t.findIndex(d=>d==="--namespace"||d==="-n"),c=t.findIndex(d=>d==="--role"||d==="-r");if(r)n=i>=0?t[i+1]:"http://localhost:3100",o=a>=0?t[a+1]:"default",s=c>=0?t[c+1]:"developer";else{let d=WI({input:process.stdin,output:process.stdout});console.log(C("waggle-cli setup")),console.log(),n=await Sd(d,"Server URL","http://localhost:3100"),o=await Sd(d,"Namespace","default"),s=await Sd(d,"Role","developer"),d.close(),console.log()}let l=uc(),u=bc(n,l,s,o),p=Q(u);try{let d=await p.health();d.ok||(console.log(_(`Server returned ${d.status}. Check the URL and try again.`)),process.exit(1))}catch{console.log(_(`Cannot reach ${n}. Is the incubator running?`)),process.exit(1)}try{await p.requestRole(s)}catch{}let f=_c(u);us(u.hookTimeout),console.log(N("Initialized waggle-cli")),console.log(S("Config",f)),console.log(S("Agent ID",l)),console.log(S("Server",n)),console.log(S("Namespace",o)),console.log(S("Role",s)),console.log(),console.log(` Hooks installed in ${y("dim",".claude/settings.local.json")}`),console.log(" Start a Claude Code session to begin coordinating.")}var db=w(()=>{"use strict";Vp();dt();bi();Qe();Re()});var fb={};K(fb,{join:()=>KI});async function KI(t){be()&&(console.log(_("Already joined. Run `wgl leave` first.")),process.exit(1));let r=t.find(u=>u.startsWith("http"));r||(console.log(_("Usage: wgl join <server-url> [--role <role>] [--namespace <ns>]")),process.exit(1));let n=t.findIndex(u=>u==="--role"||u==="-r"),o=t.findIndex(u=>u==="--namespace"||u==="-n"),s=n>=0?t[n+1]:"developer",i=o>=0?t[o+1]:"default",a=uc(),c=bc(r,a,s,i),l=Q(c);try{let u=await l.health();u.ok||(console.log(_(`Server returned ${u.status}`)),process.exit(1))}catch{console.log(_(`Cannot reach ${r}`)),process.exit(1)}try{await l.requestRole(s)}catch{}_c(c),us(c.hookTimeout),console.log(N("Joined coordination server")),console.log(S("Agent ID",a)),console.log(S("Server",r)),console.log(S("Role",s));try{let[u,p]=await Promise.all([l.getProtocol(),l.getRoles()]);if(u.ok&&u.data){let f=u.data;f.name&&(console.log(C("Protocol")),console.log(S("Name",f.name)),f.description&&console.log(S("Description",f.description)),f.phases?.length&&console.log(S("Phases",f.phases.map(d=>d.name).join(" \u2192 "))))}if(p.ok&&Array.isArray(p.data)&&p.data.length>0){console.log(C("Team"));for(let f of p.data){let d=f.agent===a?y("green"," (you)"):"";console.log(` ${y("bold",f.role)}: ${f.agent}${d}`)}}}catch{}console.log()}var mb=w(()=>{"use strict";Vp();dt();bi();Qe();Re()});var hb={};K(hb,{status:()=>YI});async function YI(){let t=be();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);console.log(C("waggle-cli status")),console.log(S("Agent ID",t.agentId)),console.log(S("Server",t.server)),console.log(S("Namespace",t.namespace)),console.log(S("Role",t.role));try{let[r,n,o]=await Promise.all([e.getControlStatus(),e.getClaims(),e.getEvents(t.lastEventCursor)]);if(r.ok){let s=r.data;console.log(C("Control")),s.halted?console.log(` ${y("red","HALTED")}${s.reason?` \u2014 ${s.reason}`:""}`):s.paused?console.log(` ${y("yellow","PAUSED")}${s.reason?` \u2014 ${s.reason}`:""}`):console.log(` ${y("green","RUNNING")}`)}if(n.ok&&Array.isArray(n.data)){let s=n.data,i=s.filter(c=>c.owner===t.agentId&&c.status==="active"),a=s.filter(c=>c.owner!==t.agentId&&c.status==="active");if(console.log(C("Claims")),i.length===0&&a.length===0)console.log(` ${y("dim","No active claims")}`);else{for(let c of i)console.log(` ${y("green","\u25CF")} ${c.resource} ${y("dim","(yours)")}`);for(let c of a)console.log(` ${y("yellow","\u25CF")} ${c.resource} ${y("dim",`(${c.owner})`)}`)}}if(o.ok&&Array.isArray(o.data)){let s=o.data;if(console.log(C("Recent Events")),s.length===0)console.log(` ${y("dim","No new events")}`);else{let i=s.slice(-10);for(let a of i)console.log(` ${y("dim",`#${a.id}`)} ${y("bold",a.type)} ${y("dim",`by ${a.publishedBy}`)}`);s.length>10&&console.log(` ${y("dim",`... and ${s.length-10} more`)}`)}}}catch{console.log(`
15
+ ${y("yellow","Server unreachable")}`)}console.log()}var gb=w(()=>{"use strict";dt();Qe();Re()});var yb={};K(yb,{leave:()=>XI});async function XI(){let t=be();t||(console.log(_("Not initialized. Nothing to do.")),process.exit(1));let e=Q(t);try{let r=await e.getClaims();if(r.ok&&Array.isArray(r.data)){let n=r.data.filter(o=>o.owner===t.agentId&&o.status==="active");for(let o of n)await e.releaseClaim(o.resource)}}catch{}try{await e.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role})}catch{}xc(),sb(),console.log(N("Left coordination server. Hooks removed, config deleted."))}var vb=w(()=>{"use strict";dt();bi();Qe();Re()});var Sc,$d=w(()=>{Sc="1.0"});var _b={};K(_b,{SpecValidationError:()=>co,normalizeAgents:()=>Ed,normalizeRules:()=>wi,validateSpec:()=>kd});function kd(t){let e=[];if(!t||typeof t!="object")return["Spec must be a YAML/JSON object"];let r=t;if(!r.acp||typeof r.acp!="string")e.push('Missing or invalid "acp" version string');else if(!/^\d+\.\d+$/.test(r.acp))e.push(`Invalid "acp" version format: "${r.acp}" (expected "X.Y")`);else{let[n]=r.acp.split(".").map(Number),[o]=Sc.split(".").map(Number);n!==o&&e.push(`Unsupported ACP version ${r.acp} (this parser supports ${Sc})`)}if(!r.name||typeof r.name!="string"?e.push('Missing or invalid "name" string'):/^[a-z][a-z0-9-]*$/.test(r.name)||e.push(`Invalid "name": "${r.name}" (must be lowercase alphanumeric with hyphens, starting with a letter)`),(!r.title||typeof r.title!="string")&&e.push('Missing or invalid "title" string'),!r.roles||typeof r.roles!="object"||Array.isArray(r.roles))e.push('Missing or invalid "roles" object');else{let n=r.roles;Object.keys(n).length===0&&e.push('"roles" must have at least one role');for(let[o,s]of Object.entries(n)){if(!s||typeof s!="object"){e.push(`Role "${o}" must be an object`);continue}let i=s;if((!i.description||typeof i.description!="string")&&e.push(`Role "${o}" missing "description"`),i.count!==void 0&&typeof i.count!="string"&&e.push(`Role "${o}".count must be a string`),i.can_become!==void 0&&(Array.isArray(i.can_become)||e.push(`Role "${o}".can_become must be an array`)),i.scope!==void 0&&(!Array.isArray(i.scope)||i.scope.some(a=>typeof a!="string"||a===""))&&e.push(`Role "${o}".scope must be an array of non-empty strings`),i.capabilities!==void 0&&(!Array.isArray(i.capabilities)||i.capabilities.some(a=>typeof a!="string"||a===""))&&e.push(`Role "${o}".capabilities must be an array of non-empty strings`),i.agents!==void 0)if(typeof i.agents=="number")(!Number.isInteger(i.agents)||i.agents<1)&&e.push(`Role "${o}".agents must be a positive integer`);else if(Array.isArray(i.agents))i.agents.length!==2||!i.agents.every(a=>typeof a=="number"&&Number.isInteger(a)&&a>=1)?e.push(`Role "${o}".agents array must be [min, max] with positive integers`):i.agents[0]>i.agents[1]&&e.push(`Role "${o}".agents[0] (min) must be \u2264 agents[1] (max)`);else if(typeof i.agents=="object"&&i.agents!==null){let a=i.agents;for(let c of["default","min","max"])a[c]!==void 0&&(typeof a[c]!="number"||!Number.isInteger(a[c])||a[c]<1)&&e.push(`Role "${o}".agents.${c} must be a positive integer`);typeof a.min=="number"&&typeof a.max=="number"&&a.min>a.max&&e.push(`Role "${o}".agents.min must be \u2264 agents.max`),typeof a.default=="number"&&(typeof a.min=="number"&&a.default<a.min&&e.push(`Role "${o}".agents.default must be \u2265 agents.min`),typeof a.max=="number"&&a.default>a.max&&e.push(`Role "${o}".agents.default must be \u2264 agents.max`))}else e.push(`Role "${o}".agents must be a number, [min, max] array, or {default, min, max} object`);if(i.primitives!==void 0)if(typeof i.primitives!="object"||Array.isArray(i.primitives)||i.primitives===null)e.push(`Role "${o}".primitives must be an object`);else{let a=i.primitives;a.env!==void 0&&(!Array.isArray(a.env)||a.env.some(c=>typeof c!="string"||c===""))&&e.push(`Role "${o}".primitives.env must be an array of non-empty strings`),a.acp!==void 0&&(!Array.isArray(a.acp)||a.acp.some(c=>typeof c!="string"||c===""))&&e.push(`Role "${o}".primitives.acp must be an array of non-empty strings`)}if(i.wait!==void 0)if(typeof i.wait!="object"||Array.isArray(i.wait)||i.wait===null)e.push(`Role "${o}".wait must be an object`);else{let a=i.wait;a.types!==void 0&&(!Array.isArray(a.types)||a.types.some(c=>typeof c!="string"||c===""))&&e.push(`Role "${o}".wait.types must be an array of non-empty strings`),a.max_timeout!==void 0&&(typeof a.max_timeout!="number"||a.max_timeout<=0)&&e.push(`Role "${o}".wait.max_timeout must be a positive number`)}}}if(!r.phases||typeof r.phases!="object"||Array.isArray(r.phases))e.push('Missing or invalid "phases" object');else{let n=r.phases;Object.keys(n).length===0&&e.push('"phases" must have at least one phase');let o=!1;for(let[s,i]of Object.entries(n)){if(!i||typeof i!="object"){e.push(`Phase "${s}" must be an object`);continue}let a=i;(!a.description||typeof a.description!="string")&&e.push(`Phase "${s}" missing "description"`),a.terminal===!0&&(o=!0)}o||e.push("At least one phase must be terminal")}if(r.roles&&typeof r.roles=="object"&&!Array.isArray(r.roles)){let n=new Set(Object.keys(r.roles));for(let[o,s]of Object.entries(r.roles))if(s?.can_become&&Array.isArray(s.can_become))for(let i of s.can_become)typeof i=="string"&&!n.has(i)&&e.push(`Role "${o}".can_become references unknown role "${i}"`)}if(r.governance!==void 0)if(typeof r.governance!="object"||Array.isArray(r.governance)||r.governance===null)e.push('"governance" must be an object');else{let n=r.governance;if(n.budget!==void 0&&typeof n.budget=="object"&&n.budget!==null){let o=n.budget;o.warn_at!==void 0&&(typeof o.warn_at!="number"||o.warn_at<0||o.warn_at>1)&&e.push("governance.budget.warn_at must be a number between 0 and 1")}if(n.escalation!==void 0&&typeof n.escalation=="object"&&n.escalation!==null){let o=n.escalation;if(o.triggers!==void 0)if(!Array.isArray(o.triggers))e.push("governance.escalation.triggers must be an array");else{let s=new Set(["notify","halt","request_approval"]);for(let[i,a]of o.triggers.entries()){if(!a||typeof a!="object")continue;let c=a;(!c.condition||typeof c.condition!="string")&&e.push(`governance.escalation.triggers[${i}] missing "condition"`),(!c.action||typeof c.action!="string"||!s.has(c.action))&&e.push(`governance.escalation.triggers[${i}].action must be "notify", "halt", or "request_approval"`)}}}if(n.quorum!==void 0&&typeof n.quorum=="object"&&n.quorum!==null){let o=n.quorum;o.default!==void 0&&(typeof o.default!="number"||o.default<1||!Number.isInteger(o.default))&&e.push("governance.quorum.default must be a positive integer")}if(n.approval_gates!==void 0)if(!Array.isArray(n.approval_gates))e.push("governance.approval_gates must be an array");else{let o=r.roles&&typeof r.roles=="object"?new Set(Object.keys(r.roles)):new Set;for(let[s,i]of n.approval_gates.entries()){if(!i||typeof i!="object")continue;let a=i;(!a.action||typeof a.action!="string")&&e.push(`governance.approval_gates[${s}] missing "action"`),a.required_role!==void 0&&typeof a.required_role=="string"&&a.required_role!=="human"&&!o.has(a.required_role)&&e.push(`governance.approval_gates[${s}].required_role references unknown role "${a.required_role}"`)}}if(n.heartbeat!==void 0&&typeof n.heartbeat=="object"&&n.heartbeat!==null){let o=n.heartbeat;o.stale_after_ms!==void 0&&o.dead_after_ms!==void 0&&typeof o.stale_after_ms=="number"&&typeof o.dead_after_ms=="number"&&o.stale_after_ms>=o.dead_after_ms&&e.push("governance.heartbeat.stale_after_ms must be less than dead_after_ms")}}if(r.variables!==void 0)if(typeof r.variables!="object"||Array.isArray(r.variables)||r.variables===null)e.push('"variables" must be an object');else{let n=new Set(["string","number","boolean","array","object"]);for(let[o,s]of Object.entries(r.variables)){if(!s||typeof s!="object"){e.push(`Variable "${o}" must be an object`);continue}let i=s;(!i.type||typeof i.type!="string"||!n.has(i.type))&&e.push(`Variable "${o}".type must be one of: string, number, boolean, array, object`)}}if(r.topics!==void 0)if(typeof r.topics!="object"||Array.isArray(r.topics)||r.topics===null)e.push('"topics" must be an object');else{let n=r.topics;n.publishes!==void 0&&(Array.isArray(n.publishes)?n.publishes.some(o=>typeof o!="string"||o==="")&&e.push("topics.publishes must be an array of non-empty strings"):e.push("topics.publishes must be an array")),n.subscribes!==void 0&&(Array.isArray(n.subscribes)?n.subscribes.some(o=>typeof o!="string"||o==="")&&e.push("topics.subscribes must be an array of non-empty strings"):e.push("topics.subscribes must be an array"))}if(r.rules&&typeof r.rules=="object"){let n=r.roles&&typeof r.roles=="object"?new Set(Object.keys(r.roles)):new Set,o=r.phases&&typeof r.phases=="object"?new Set(Object.keys(r.phases)):new Set;for(let[s,i]of Object.entries(r.rules)){if(!n.has(s)){e.push(`Rules reference unknown role "${s}"`);continue}if(!(!i||typeof i!="object"))for(let a of Object.keys(i))o.has(a)||e.push(`Rules for role "${s}" reference unknown phase "${a}"`)}}return e}function wi(t){if(!t)return{};let e={};for(let[r,n]of Object.entries(t)){e[r]={};for(let[o,s]of Object.entries(n))Array.isArray(s)?e[r][o]={steps:s}:e[r][o]=s}return e}function Ed(t){if(t===void 0)return{default:1,min:1,max:1};if(typeof t=="number")return{default:t,min:t,max:t};if(Array.isArray(t))return{default:t[0],min:t[0],max:t[1]};let e=t.min??1,r=t.default??e,n=t.max??Math.max(r,e);return{default:r,min:e,max:n}}var co,$c=w(()=>{$d();co=class extends Error{errors;constructor(e){super(`Invalid ACP spec:
16
16
  - ${e.join(`
17
- - `)}`),this.errors=e,this.name="SpecValidationError"}}});import{readFile as II}from"node:fs/promises";async function AI(){if(!_i)try{let{createRequire:t}=await import("node:module");_i=t(import.meta.url)("js-yaml")}catch{}}function NI(t){if(_i)return _i.load(t,{schema:_i.JSON_SCHEMA});try{return JSON.parse(t)}catch{throw new Error(`Cannot parse YAML: install js-yaml for YAML support, or use .acp.json format.
18
- npm install js-yaml`)}}async function co(t,e){let{validateSpec:r,SpecValidationError:n}=await Promise.resolve().then(()=>(bc(),ub));await AI();let o=NI(t);(e?.variables||o&&typeof o=="object"&&o.variables)&&(o=pb(o,e?.variables??{}));let s=r(o);if(s.length>0)throw new n(s);return o}async function wc(t,e){let r=await II(t,"utf-8");return co(r,e)}function pb(t,e={}){if(!t||typeof t!="object")return t;let n=t.variables??{},o={};for(let[s,i]of Object.entries(n))s in e?o[s]=e[s]:i&&typeof i=="object"&&"default"in i&&(o[s]=i.default);for(let[s,i]of Object.entries(e))s in o||(o[s]=i);return bd(t,o)}function bd(t,e){if(typeof t=="string"){let r=t.match(zI);if(r){let n=r[1];if(n in e)return e[n]}return t}if(Array.isArray(t))return t.map(r=>bd(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=bd(o,e);return r}return t}var _i,zI,wd=w(()=>{bc();zI=/^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$/});async function xd(t,e,r,n){let o=await e.events.getCursor(),i=(await e.claims.list()).map(g=>g.resource),a=await e.discoveries.search(),c=new Set(a.map(g=>g.topic)),l=null;if(t.resources?.instances){let g=new Set(i);for(let v of t.resources.instances)if(!g.has(v)&&!c.has(v)){l=v;break}}let u=e.roles?await e.roles.getAssignments():[],p=u.find(g=>g.agent===r),m=n?.$role??p?.role??"",f=(m?t.roles[m]:void 0)?.capabilities??[];return{$self:r,$cursor:o,$role:m,$capabilities:f,$team:u,$active_claims:i,$completed_resources:a.map(g=>g.topic),...l!==null?{$next_unclaimed:l}:{},...n}}function bi(t,e){return t.replace(/\$[a-z_][a-z0-9_]*/gi,r=>{let n=e[r];return n===void 0?r:typeof n=="string"?n:JSON.stringify(n)})}var Sd=w(()=>{});function xc(t,e,r){return vi(t.rules)[e]?.[r]??{steps:[]}}function jI(t,e,r,n){let o=e+1,s=n(t.action),i=t.description?` \u2014 ${bi(t.description,r)}`:"",a=t.hint?`
19
- Hint: ${bi(t.hint,r)}`:"",c=`${o}. Call \`${s}\`${i}`;if(t.params){let l={};for(let[u,p]of Object.entries(t.params))l[u]=typeof p=="string"?bi(p,r):p;c+=`
17
+ - `)}`),this.errors=e,this.name="SpecValidationError"}}});import{readFile as QI}from"node:fs/promises";async function e1(){if(!xi)try{let{createRequire:t}=await import("node:module");xi=t(import.meta.url)("js-yaml")}catch{}}function t1(t){if(xi)return xi.load(t,{schema:xi.JSON_SCHEMA});try{return JSON.parse(t)}catch{throw new Error(`Cannot parse YAML: install js-yaml for YAML support, or use .acp.json format.
18
+ npm install js-yaml`)}}async function lo(t,e){let{validateSpec:r,SpecValidationError:n}=await Promise.resolve().then(()=>($c(),_b));await e1();let o=t1(t);(e?.variables||o&&typeof o=="object"&&o.variables)&&(o=bb(o,e?.variables??{}));let s=r(o);if(s.length>0)throw new n(s);return o}async function kc(t,e){let r=await QI(t,"utf-8");return lo(r,e)}function bb(t,e={}){if(!t||typeof t!="object")return t;let n=t.variables??{},o={};for(let[s,i]of Object.entries(n))s in e?o[s]=e[s]:i&&typeof i=="object"&&"default"in i&&(o[s]=i.default);for(let[s,i]of Object.entries(e))s in o||(o[s]=i);return Td(t,o)}function Td(t,e){if(typeof t=="string"){let r=t.match(r1);if(r){let n=r[1];if(n in e)return e[n]}return t}if(Array.isArray(t))return t.map(r=>Td(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=Td(o,e);return r}return t}var xi,r1,Pd=w(()=>{$c();r1=/^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$/});async function Rd(t,e,r,n){let o=await e.events.getCursor(),i=(await e.claims.list()).map(g=>g.resource),a=await e.discoveries.search(),c=new Set(a.map(g=>g.topic)),l=null;if(t.resources?.instances){let g=new Set(i);for(let v of t.resources.instances)if(!g.has(v)&&!c.has(v)){l=v;break}}let u=e.roles?await e.roles.getAssignments():[],p=u.find(g=>g.agent===r),f=n?.$role??p?.role??"",m=(f?t.roles[f]:void 0)?.capabilities??[];return{$self:r,$cursor:o,$role:f,$capabilities:m,$team:u,$active_claims:i,$completed_resources:a.map(g=>g.topic),...l!==null?{$next_unclaimed:l}:{},...n}}function Si(t,e){return t.replace(/\$[a-z_][a-z0-9_]*/gi,r=>{let n=e[r];return n===void 0?r:typeof n=="string"?n:JSON.stringify(n)})}var Od=w(()=>{});function Ec(t,e,r){return wi(t.rules)[e]?.[r]??{steps:[]}}function n1(t,e,r,n){let o=e+1,s=n(t.action),i=t.description?` \u2014 ${Si(t.description,r)}`:"",a=t.hint?`
19
+ Hint: ${Si(t.hint,r)}`:"",c=`${o}. Call \`${s}\`${i}`;if(t.params){let l={};for(let[u,p]of Object.entries(t.params))l[u]=typeof p=="string"?Si(p,r):p;c+=`
20
20
  Parameters: ${JSON.stringify(l)}`}if(t.on_rejected&&(t.on_rejected.skip?c+=`
21
21
  If rejected: skip to next step`:t.on_rejected.goto?c+=`
22
22
  If rejected: go to phase "${t.on_rejected.goto}"`:t.on_rejected.retry_after_ms&&(c+=`
23
23
  If rejected: retry after ${t.on_rejected.retry_after_ms}ms`)),t.on_match){let l=JSON.stringify(t.on_match.value);t.on_match.goto?c+=`
24
24
  If value equals ${l}: go to phase "${t.on_match.goto}"`:t.on_match.skip&&(c+=`
25
- If value equals ${l}: skip remaining steps`)}return c+=a,c}function MI(t){if(!t)return"";let e=[];if(t.claim_patterns){e.push("**Claim naming:**");for(let[r,n]of Object.entries(t.claim_patterns)){let o=typeof n=="string"?n:n.pattern??r;e.push(` - ${r}: \`${o}\``)}}if(t.discovery_topics){e.push("**Discovery topics:**");for(let[r,n]of Object.entries(t.discovery_topics)){let o=n.category?` (category: ${n.category})`:"";e.push(` - ${r}: \`${n.pattern}\`${o}`)}}if(t.event_types){e.push("**Event types:**");for(let[r,n]of Object.entries(t.event_types))e.push(` - ${r}: \`${n.type}\``)}if(t.state_keys){e.push("**State keys:**");for(let[r,n]of Object.entries(t.state_keys)){let o=n.type?` (${n.type})`:"";e.push(` - ${r}: \`${n.key}\`${o}`)}}if(t.instances){e.push(`**Resources to process:** ${t.instances.length} items`);for(let r of t.instances.slice(0,10))e.push(` - \`${r}\``);t.instances.length>10&&e.push(` - ... and ${t.instances.length-10} more`)}return e.length>0?`
25
+ If value equals ${l}: skip remaining steps`)}return c+=a,c}function o1(t){if(!t)return"";let e=[];if(t.claim_patterns){e.push("**Claim naming:**");for(let[r,n]of Object.entries(t.claim_patterns)){let o=typeof n=="string"?n:n.pattern??r;e.push(` - ${r}: \`${o}\``)}}if(t.discovery_topics){e.push("**Discovery topics:**");for(let[r,n]of Object.entries(t.discovery_topics)){let o=n.category?` (category: ${n.category})`:"";e.push(` - ${r}: \`${n.pattern}\`${o}`)}}if(t.event_types){e.push("**Event types:**");for(let[r,n]of Object.entries(t.event_types))e.push(` - ${r}: \`${n.type}\``)}if(t.state_keys){e.push("**State keys:**");for(let[r,n]of Object.entries(t.state_keys)){let o=n.type?` (${n.type})`:"";e.push(` - ${r}: \`${n.key}\`${o}`)}}if(t.instances){e.push(`**Resources to process:** ${t.instances.length} items`);for(let r of t.instances.slice(0,10))e.push(` - \`${r}\``);t.instances.length>10&&e.push(` - ... and ${t.instances.length-10} more`)}return e.length>0?`
26
26
 
27
27
  ## Resource Naming Conventions
28
28
 
29
29
  `+e.join(`
30
- `):""}function LI(t){if(!t)return"";let e=[`
30
+ `):""}function s1(t){if(!t)return"";let e=[`
31
31
 
32
32
  ## Error Handling
33
33
  `];for(let[r,n]of Object.entries(t)){if(!n)continue;let o=n.action;n.retry_after_ms&&(o+=` (after ${n.retry_after_ms}ms)`),e.push(`- **${r}**: ${o}`)}return e.join(`
34
- `)}function DI(t){if(!t)return"";let e=[`
34
+ `)}function i1(t){if(!t)return"";let e=[`
35
35
 
36
36
  ## Governance Rules
37
37
  `];if(t.budget){let r=t.budget,n=[];r.max_tokens&&n.push(`${r.max_tokens.toLocaleString()} tokens`),r.max_cost&&n.push(`$${r.max_cost}`),n.length>0&&e.push(`- **Budget**: ${n.join(", ")}`),r.warn_at&&e.push(` - Warning at ${Math.round(r.warn_at*100)}% usage`)}if(t.escalation?.triggers&&t.escalation.triggers.length>0){e.push("- **Escalation triggers**:");for(let r of t.escalation.triggers)e.push(` - ${r.condition} \u2192 ${r.action}`)}if(t.quorum&&(t.quorum.default&&e.push(`- **Quorum**: ${t.quorum.default} agents must agree by default`),t.quorum.actions))for(let[r,n]of Object.entries(t.quorum.actions))e.push(` - "${r}": requires ${n} endorsements`);if(t.approval_gates&&t.approval_gates.length>0){e.push("- **Approval gates** (require human/role sign-off):");for(let r of t.approval_gates){let n=r.required_role??"human",o=r.scope?` (scope: ${r.scope.join(", ")})`:"";e.push(` - "${r.action}" \u2192 approved by ${n}${o}`)}}if(t.heartbeat){let r=t.heartbeat,n=r.stale_after_ms?`${r.stale_after_ms/1e3}s`:"30s",o=r.dead_after_ms?`${r.dead_after_ms/1e3}s`:"60s";e.push(`- **Heartbeat**: stale after ${n}, dead after ${o}`)}return e.length>1?e.join(`
38
- `):""}function qI(t){if(!t)return"";let e=[];if(t.publishes&&t.publishes.length>0){e.push("This protocol publishes the following events to other namespaces:");for(let r of t.publishes)e.push(` - ${r}`)}if(t.subscribes&&t.subscribes.length>0){e.push("This protocol receives the following events from other namespaces:");for(let r of t.subscribes)e.push(` - ${r}`)}return e.length>0?`
38
+ `):""}function a1(t){if(!t)return"";let e=[];if(t.publishes&&t.publishes.length>0){e.push("This protocol publishes the following events to other namespaces:");for(let r of t.publishes)e.push(` - ${r}`)}if(t.subscribes&&t.subscribes.length>0){e.push("This protocol receives the following events from other namespaces:");for(let r of t.subscribes)e.push(` - ${r}`)}return e.length>0?`
39
39
 
40
40
  ## Cross-Namespace Topics
41
41
 
42
42
  `+e.join(`
43
- `):""}function ZI(t){if(!t||t.length===0)return"";let e=[`
43
+ `):""}function c1(t){if(!t||t.length===0)return"";let e=[`
44
44
 
45
45
  ## Team Composition
46
46
  `],r={};for(let n of t)(r[n.role]??=[]).push(n.agent);for(let[n,o]of Object.entries(r))e.push(`- **${n}**: ${o.map(s=>`\`${s}\``).join(", ")}`);return e.join(`
47
- `)}function $d(t,e,r,n,o){let s=o?.toolMapping??db,i=d=>s[d]??d,a=t.roles[e],c=t.phases[r],l=xc(t,e,r),u=[];u.push(`# ${t.title}`),t.description&&u.push(`
47
+ `)}function Cd(t,e,r,n,o){let s=o?.toolMapping??wb,i=d=>s[d]??d,a=t.roles[e],c=t.phases[r],l=Ec(t,e,r),u=[];u.push(`# ${t.title}`),t.description&&u.push(`
48
48
  ${t.description}`),u.push(`
49
49
  ## Your Role: ${e}`),u.push(a.description),u.push(`
50
50
  ## Current Phase: ${r}`),u.push(c.description),u.push(`
51
51
  ## Phase Overview
52
- `);let p=Object.keys(t.phases);for(let d of p){let f=t.phases[d],h=d===r?" **(current)**":"",g=f.terminal?" (terminal)":"";u.push(`- **${d}**${h}: ${f.description}${g}`)}if(l.steps&&l.steps.length>0){u.push(`
52
+ `);let p=Object.keys(t.phases);for(let d of p){let m=t.phases[d],h=d===r?" **(current)**":"",g=m.terminal?" (terminal)":"";u.push(`- **${d}**${h}: ${m.description}${g}`)}if(l.steps&&l.steps.length>0){u.push(`
53
53
  ## Steps for This Phase
54
54
  `),l.loop&&u.push(`Repeat these steps in a loop until the phase exit condition is met:
55
- `);for(let d=0;d<l.steps.length;d++)u.push(jI(l.steps[d],d,n,i))}else c.terminal?u.push(`
55
+ `);for(let d=0;d<l.steps.length;d++)u.push(n1(l.steps[d],d,n,i))}else c.terminal?u.push(`
56
56
  ## This is a terminal phase. The protocol is complete.`):u.push(`
57
- ## No specific steps defined for this phase. Use your judgment based on the phase description.`);if(u.push(MI(t.resources)),u.push(LI(t.errors)),a.can_become&&a.can_become.length>0&&(u.push(`
57
+ ## No specific steps defined for this phase. Use your judgment based on the phase description.`);if(u.push(o1(t.resources)),u.push(s1(t.errors)),a.can_become&&a.can_become.length>0&&(u.push(`
58
58
 
59
59
  ## Role Transitions
60
60
  `),u.push(`You can request to transition to: ${a.can_become.map(d=>`**${d}**`).join(", ")}`),u.push(`Use \`${i("requestRole")}\` to request a transition.`)),a.scope&&a.scope.length>0){u.push(`
61
61
 
62
62
  ## Scope Boundaries
63
- `),u.push("You may only work within these scopes:");for(let d of a.scope)u.push(`- \`${d}\``)}Array.isArray(n.$team)&&n.$team.length>0&&u.push(ZI(n.$team)),u.push(DI(t.governance)),u.push(qI(t.topics));let m=i("getProtocol");return u.push(`
63
+ `),u.push("You may only work within these scopes:");for(let d of a.scope)u.push(`- \`${d}\``)}Array.isArray(n.$team)&&n.$team.length>0&&u.push(c1(n.$team)),u.push(i1(t.governance)),u.push(a1(t.topics));let f=i("getProtocol");return u.push(`
64
64
 
65
65
  ## Phase Transitions
66
- `),u.push(`Call \`${m}\` again when you observe a phase change (via \`phase.changed\` event or state update) to get updated instructions for the new phase.`),u.push(`
66
+ `),u.push(`Call \`${f}\` again when you observe a phase change (via \`phase.changed\` event or state update) to get updated instructions for the new phase.`),u.push(`
67
67
 
68
68
  ## Current State
69
69
  `),u.push(`- Agent ID: \`${n.$self}\``),n.$role&&u.push(`- Role: \`${n.$role}\``),u.push(`- Event cursor: ${n.$cursor}`),"$next_unclaimed"in n&&u.push(`- Next unclaimed resource: \`${n.$next_unclaimed}\``),Array.isArray(n.$active_claims)&&n.$active_claims.length>0&&u.push(`- Active claims: ${n.$active_claims.map(d=>`\`${d}\``).join(", ")}`),Array.isArray(n.$capabilities)&&n.$capabilities.length>0&&u.push(`- Capabilities: ${n.$capabilities.join(", ")}`),u.join(`
70
- `)}var db,fb=w(()=>{wd();Sd();db={getState:"incubator_getState",setState:"incubator_setState",queryState:"incubator_queryState",deleteState:"incubator_deleteState",claim:"incubator_claim",releaseClaim:"incubator_releaseClaim",checkClaim:"incubator_checkClaim",listClaims:"incubator_listClaims",publishEvent:"incubator_publishEvent",getEvents:"incubator_getEvents",publishDiscovery:"incubator_publishDiscovery",searchDiscoveries:"incubator_searchDiscoveries",getProtocol:"incubator_getProtocol",requestRole:"incubator_requestRole",sendMessage:"incubator_sendMessage",getMessages:"incubator_getMessages",requestHelp:"incubator_requestHelp",claimHelp:"incubator_claimHelp",reportProgress:"incubator_reportProgress",flagConflict:"incubator_flagConflict",requestReinforcement:"incubator_requestReinforcement",requestApproval:"incubator_requestApproval",escalate:"incubator_escalate",proposeAction:"incubator_proposeAction",endorseAction:"incubator_endorseAction",requestRollback:"incubator_requestRollback",getTopics:"incubator_getTopics",subscribeTopic:"incubator_subscribeTopic",publishTopic:"incubator_publishTopic"}});var wi=w(()=>{yd();bc();wd();Sd();fb()});function Rb(t){return typeof t>"u"||t===null}function UI(t){return typeof t=="object"&&t!==null}function FI(t){return Array.isArray(t)?t:Rb(t)?[]:[t]}function HI(t,e){var r,n,o,s;if(e)for(s=Object.keys(e),r=0,n=s.length;r<n;r+=1)o=s[r],t[o]=e[o];return t}function BI(t,e){var r="",n;for(n=0;n<e;n+=1)r+=t;return r}function VI(t){return t===0&&Number.NEGATIVE_INFINITY===1/t}function Ob(t,e){var r="",n=t.reason||"(unknown reason)";return t.mark?(t.mark.name&&(r+='in "'+t.mark.name+'" '),r+="("+(t.mark.line+1)+":"+(t.mark.column+1)+")",!e&&t.mark.snippet&&(r+=`
70
+ `)}var wb,xb=w(()=>{Pd();Od();wb={getState:"incubator_getState",setState:"incubator_setState",queryState:"incubator_queryState",deleteState:"incubator_deleteState",claim:"incubator_claim",releaseClaim:"incubator_releaseClaim",checkClaim:"incubator_checkClaim",listClaims:"incubator_listClaims",publishEvent:"incubator_publishEvent",getEvents:"incubator_getEvents",publishDiscovery:"incubator_publishDiscovery",searchDiscoveries:"incubator_searchDiscoveries",getProtocol:"incubator_getProtocol",requestRole:"incubator_requestRole",sendMessage:"incubator_sendMessage",getMessages:"incubator_getMessages",requestHelp:"incubator_requestHelp",claimHelp:"incubator_claimHelp",reportProgress:"incubator_reportProgress",flagConflict:"incubator_flagConflict",requestReinforcement:"incubator_requestReinforcement",requestApproval:"incubator_requestApproval",escalate:"incubator_escalate",proposeAction:"incubator_proposeAction",endorseAction:"incubator_endorseAction",requestRollback:"incubator_requestRollback",getTopics:"incubator_getTopics",subscribeTopic:"incubator_subscribeTopic",publishTopic:"incubator_publishTopic"}});var $i=w(()=>{$d();$c();Pd();Od();xb()});function Lb(t){return typeof t>"u"||t===null}function l1(t){return typeof t=="object"&&t!==null}function u1(t){return Array.isArray(t)?t:Lb(t)?[]:[t]}function p1(t,e){var r,n,o,s;if(e)for(s=Object.keys(e),r=0,n=s.length;r<n;r+=1)o=s[r],t[o]=e[o];return t}function d1(t,e){var r="",n;for(n=0;n<e;n+=1)r+=t;return r}function f1(t){return t===0&&Number.NEGATIVE_INFINITY===1/t}function Db(t,e){var r="",n=t.reason||"(unknown reason)";return t.mark?(t.mark.name&&(r+='in "'+t.mark.name+'" '),r+="("+(t.mark.line+1)+":"+(t.mark.column+1)+")",!e&&t.mark.snippet&&(r+=`
71
71
 
72
- `+t.mark.snippet),n+" "+r):n}function Si(t,e){Error.call(this),this.name="YAMLException",this.reason=t,this.mark=e,this.message=Ob(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}function kd(t,e,r,n,o){var s="",i="",a=Math.floor(o/2)-1;return n-e>a&&(s=" ... ",e=n-a+s.length),r-n>a&&(i=" ...",r=n+a-i.length),{str:s+t.slice(e,r).replace(/\t/g,"\u2192")+i,pos:n-e+s.length}}function Ed(t,e){return lt.repeat(" ",e-t.length)+t}function QI(t,e){if(e=Object.create(e||null),!t.buffer)return null;e.maxLength||(e.maxLength=79),typeof e.indent!="number"&&(e.indent=1),typeof e.linesBefore!="number"&&(e.linesBefore=3),typeof e.linesAfter!="number"&&(e.linesAfter=2);for(var r=/\r?\n|\r|\0/g,n=[0],o=[],s,i=-1;s=r.exec(t.buffer);)o.push(s.index),n.push(s.index+s[0].length),t.position<=s.index&&i<0&&(i=n.length-2);i<0&&(i=n.length-1);var a="",c,l,u=Math.min(t.line+e.linesAfter,o.length).toString().length,p=e.maxLength-(e.indent+u+3);for(c=1;c<=e.linesBefore&&!(i-c<0);c++)l=kd(t.buffer,n[i-c],o[i-c],t.position-(n[i]-n[i-c]),p),a=lt.repeat(" ",e.indent)+Ed((t.line-c+1).toString(),u)+" | "+l.str+`
73
- `+a;for(l=kd(t.buffer,n[i],o[i],t.position,p),a+=lt.repeat(" ",e.indent)+Ed((t.line+1).toString(),u)+" | "+l.str+`
72
+ `+t.mark.snippet),n+" "+r):n}function Ei(t,e){Error.call(this),this.name="YAMLException",this.reason=t,this.mark=e,this.message=Db(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}function Id(t,e,r,n,o){var s="",i="",a=Math.floor(o/2)-1;return n-e>a&&(s=" ... ",e=n-a+s.length),r-n>a&&(i=" ...",r=n+a-i.length),{str:s+t.slice(e,r).replace(/\t/g,"\u2192")+i,pos:n-e+s.length}}function Ad(t,e){return lt.repeat(" ",e-t.length)+t}function b1(t,e){if(e=Object.create(e||null),!t.buffer)return null;e.maxLength||(e.maxLength=79),typeof e.indent!="number"&&(e.indent=1),typeof e.linesBefore!="number"&&(e.linesBefore=3),typeof e.linesAfter!="number"&&(e.linesAfter=2);for(var r=/\r?\n|\r|\0/g,n=[0],o=[],s,i=-1;s=r.exec(t.buffer);)o.push(s.index),n.push(s.index+s[0].length),t.position<=s.index&&i<0&&(i=n.length-2);i<0&&(i=n.length-1);var a="",c,l,u=Math.min(t.line+e.linesAfter,o.length).toString().length,p=e.maxLength-(e.indent+u+3);for(c=1;c<=e.linesBefore&&!(i-c<0);c++)l=Id(t.buffer,n[i-c],o[i-c],t.position-(n[i]-n[i-c]),p),a=lt.repeat(" ",e.indent)+Ad((t.line-c+1).toString(),u)+" | "+l.str+`
73
+ `+a;for(l=Id(t.buffer,n[i],o[i],t.position,p),a+=lt.repeat(" ",e.indent)+Ad((t.line+1).toString(),u)+" | "+l.str+`
74
74
  `,a+=lt.repeat("-",e.indent+u+3+l.pos)+`^
75
- `,c=1;c<=e.linesAfter&&!(i+c>=o.length);c++)l=kd(t.buffer,n[i+c],o[i+c],t.position-(n[i]-n[i+c]),p),a+=lt.repeat(" ",e.indent)+Ed((t.line+c+1).toString(),u)+" | "+l.str+`
76
- `;return a.replace(/\n$/,"")}function n1(t){var e={};return t!==null&&Object.keys(t).forEach(function(r){t[r].forEach(function(n){e[String(n)]=r})}),e}function o1(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(t1.indexOf(r)===-1)throw new Ot('Unknown option "'+r+'" is met in definition of "'+t+'" YAML type.')}),this.options=e,this.tag=t,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(r){return r},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.representName=e.representName||null,this.defaultStyle=e.defaultStyle||null,this.multi=e.multi||!1,this.styleAliases=n1(e.styleAliases||null),r1.indexOf(this.kind)===-1)throw new Ot('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}function mb(t,e){var r=[];return t[e].forEach(function(n){var o=r.length;r.forEach(function(s,i){s.tag===n.tag&&s.kind===n.kind&&s.multi===n.multi&&(o=i)}),r[o]=n}),r}function s1(){var t={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},e,r;function n(o){o.multi?(t.multi[o.kind].push(o),t.multi.fallback.push(o)):t[o.kind][o.tag]=t.fallback[o.tag]=o}for(e=0,r=arguments.length;e<r;e+=1)arguments[e].forEach(n);return t}function Pd(t){return this.extend(t)}function i1(t){if(t===null)return!0;var e=t.length;return e===1&&t==="~"||e===4&&(t==="null"||t==="Null"||t==="NULL")}function a1(){return null}function c1(t){return t===null}function l1(t){if(t===null)return!1;var e=t.length;return e===4&&(t==="true"||t==="True"||t==="TRUE")||e===5&&(t==="false"||t==="False"||t==="FALSE")}function u1(t){return t==="true"||t==="True"||t==="TRUE"}function p1(t){return Object.prototype.toString.call(t)==="[object Boolean]"}function d1(t){return 48<=t&&t<=57||65<=t&&t<=70||97<=t&&t<=102}function f1(t){return 48<=t&&t<=55}function m1(t){return 48<=t&&t<=57}function h1(t){if(t===null)return!1;var e=t.length,r=0,n=!1,o;if(!e)return!1;if(o=t[r],(o==="-"||o==="+")&&(o=t[++r]),o==="0"){if(r+1===e)return!0;if(o=t[++r],o==="b"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(o!=="0"&&o!=="1")return!1;n=!0}return n&&o!=="_"}if(o==="x"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!d1(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}if(o==="o"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!f1(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}}if(o==="_")return!1;for(;r<e;r++)if(o=t[r],o!=="_"){if(!m1(t.charCodeAt(r)))return!1;n=!0}return!(!n||o==="_")}function g1(t){var e=t,r=1,n;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),n=e[0],(n==="-"||n==="+")&&(n==="-"&&(r=-1),e=e.slice(1),n=e[0]),e==="0")return 0;if(n==="0"){if(e[1]==="b")return r*parseInt(e.slice(2),2);if(e[1]==="x")return r*parseInt(e.slice(2),16);if(e[1]==="o")return r*parseInt(e.slice(2),8)}return r*parseInt(e,10)}function y1(t){return Object.prototype.toString.call(t)==="[object Number]"&&t%1===0&&!lt.isNegativeZero(t)}function _1(t){return!(t===null||!v1.test(t)||t[t.length-1]==="_")}function b1(t){var e,r;return e=t.replace(/_/g,"").toLowerCase(),r=e[0]==="-"?-1:1,"+-".indexOf(e[0])>=0&&(e=e.slice(1)),e===".inf"?r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:e===".nan"?NaN:r*parseFloat(e,10)}function x1(t,e){var r;if(isNaN(t))switch(e){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===t)switch(e){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===t)switch(e){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(lt.isNegativeZero(t))return"-0.0";return r=t.toString(10),w1.test(r)?r.replace("e",".e"):r}function S1(t){return Object.prototype.toString.call(t)==="[object Number]"&&(t%1!==0||lt.isNegativeZero(t))}function $1(t){return t===null?!1:Ub.exec(t)!==null||Fb.exec(t)!==null}function k1(t){var e,r,n,o,s,i,a,c=0,l=null,u,p,m;if(e=Ub.exec(t),e===null&&(e=Fb.exec(t)),e===null)throw new Error("Date resolve error");if(r=+e[1],n=+e[2]-1,o=+e[3],!e[4])return new Date(Date.UTC(r,n,o));if(s=+e[4],i=+e[5],a=+e[6],e[7]){for(c=e[7].slice(0,3);c.length<3;)c+="0";c=+c}return e[9]&&(u=+e[10],p=+(e[11]||0),l=(u*60+p)*6e4,e[9]==="-"&&(l=-l)),m=new Date(Date.UTC(r,n,o,s,i,a,c)),l&&m.setTime(m.getTime()-l),m}function E1(t){return t.toISOString()}function T1(t){return t==="<<"||t===null}function P1(t){if(t===null)return!1;var e,r,n=0,o=t.length,s=Ad;for(r=0;r<o;r++)if(e=s.indexOf(t.charAt(r)),!(e>64)){if(e<0)return!1;n+=6}return n%8===0}function R1(t){var e,r,n=t.replace(/[\r\n=]/g,""),o=n.length,s=Ad,i=0,a=[];for(e=0;e<o;e++)e%4===0&&e&&(a.push(i>>16&255),a.push(i>>8&255),a.push(i&255)),i=i<<6|s.indexOf(n.charAt(e));return r=o%4*6,r===0?(a.push(i>>16&255),a.push(i>>8&255),a.push(i&255)):r===18?(a.push(i>>10&255),a.push(i>>2&255)):r===12&&a.push(i>>4&255),new Uint8Array(a)}function O1(t){var e="",r=0,n,o,s=t.length,i=Ad;for(n=0;n<s;n++)n%3===0&&n&&(e+=i[r>>18&63],e+=i[r>>12&63],e+=i[r>>6&63],e+=i[r&63]),r=(r<<8)+t[n];return o=s%3,o===0?(e+=i[r>>18&63],e+=i[r>>12&63],e+=i[r>>6&63],e+=i[r&63]):o===2?(e+=i[r>>10&63],e+=i[r>>4&63],e+=i[r<<2&63],e+=i[64]):o===1&&(e+=i[r>>2&63],e+=i[r<<4&63],e+=i[64],e+=i[64]),e}function C1(t){return Object.prototype.toString.call(t)==="[object Uint8Array]"}function N1(t){if(t===null)return!0;var e=[],r,n,o,s,i,a=t;for(r=0,n=a.length;r<n;r+=1){if(o=a[r],i=!1,A1.call(o)!=="[object Object]")return!1;for(s in o)if(I1.call(o,s))if(!i)i=!0;else return!1;if(!i)return!1;if(e.indexOf(s)===-1)e.push(s);else return!1}return!0}function z1(t){return t!==null?t:[]}function M1(t){if(t===null)return!0;var e,r,n,o,s,i=t;for(s=new Array(i.length),e=0,r=i.length;e<r;e+=1){if(n=i[e],j1.call(n)!=="[object Object]"||(o=Object.keys(n),o.length!==1))return!1;s[e]=[o[0],n[o[0]]]}return!0}function L1(t){if(t===null)return[];var e,r,n,o,s,i=t;for(s=new Array(i.length),e=0,r=i.length;e<r;e+=1)n=i[e],o=Object.keys(n),s[e]=[o[0],n[o[0]]];return s}function q1(t){if(t===null)return!0;var e,r=t;for(e in r)if(D1.call(r,e)&&r[e]!==null)return!1;return!0}function Z1(t){return t!==null?t:{}}function gb(t){return Object.prototype.toString.call(t)}function zr(t){return t===10||t===13}function uo(t){return t===9||t===32}function qt(t){return t===9||t===32||t===10||t===13}function us(t){return t===44||t===91||t===93||t===123||t===125}function V1(t){var e;return 48<=t&&t<=57?t-48:(e=t|32,97<=e&&e<=102?e-97+10:-1)}function G1(t){return t===120?2:t===117?4:t===85?8:0}function W1(t){return 48<=t&&t<=57?t-48:-1}function yb(t){return t===48?"\0":t===97?"\x07":t===98?"\b":t===116||t===9?" ":t===110?`
77
- `:t===118?"\v":t===102?"\f":t===114?"\r":t===101?"\x1B":t===32?" ":t===34?'"':t===47?"/":t===92?"\\":t===78?"\x85":t===95?"\xA0":t===76?"\u2028":t===80?"\u2029":""}function J1(t){return t<=65535?String.fromCharCode(t):String.fromCharCode((t-65536>>10)+55296,(t-65536&1023)+56320)}function ew(t,e,r){e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!0,value:r}):t[e]=r}function K1(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||Nd,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=t.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function nw(t,e){var r={name:t.filename,buffer:t.input.slice(0,-1),position:t.position,line:t.line,column:t.position-t.lineStart};return r.snippet=e1(r),new Ot(e,r)}function H(t,e){throw nw(t,e)}function kc(t,e){t.onWarning&&t.onWarning.call(null,nw(t,e))}function wn(t,e,r,n){var o,s,i,a;if(e<r){if(a=t.input.slice(e,r),n)for(o=0,s=a.length;o<s;o+=1)i=a.charCodeAt(o),i===9||32<=i&&i<=1114111||H(t,"expected valid JSON character");else F1.test(a)&&H(t,"the stream contains non-printable characters");t.result+=a}}function _b(t,e,r,n){var o,s,i,a;for(lt.isObject(r)||H(t,"cannot merge mappings; the provided source object is unacceptable"),o=Object.keys(r),i=0,a=o.length;i<a;i+=1)s=o[i],xn.call(e,s)||(ew(e,s,r[s]),n[s]=!0)}function ps(t,e,r,n,o,s,i,a,c){var l,u;if(Array.isArray(o))for(o=Array.prototype.slice.call(o),l=0,u=o.length;l<u;l+=1)Array.isArray(o[l])&&H(t,"nested arrays are not supported inside keys"),typeof o=="object"&&gb(o[l])==="[object Object]"&&(o[l]="[object Object]");if(typeof o=="object"&&gb(o)==="[object Object]"&&(o="[object Object]"),o=String(o),e===null&&(e={}),n==="tag:yaml.org,2002:merge")if(Array.isArray(s))for(l=0,u=s.length;l<u;l+=1)_b(t,e,s[l],r);else _b(t,e,s,r);else!t.json&&!xn.call(r,o)&&xn.call(e,o)&&(t.line=i||t.line,t.lineStart=a||t.lineStart,t.position=c||t.position,H(t,"duplicated mapping key")),ew(e,o,s),delete r[o];return e}function zd(t){var e;e=t.input.charCodeAt(t.position),e===10?t.position++:e===13?(t.position++,t.input.charCodeAt(t.position)===10&&t.position++):H(t,"a line break is expected"),t.line+=1,t.lineStart=t.position,t.firstTabInLine=-1}function it(t,e,r){for(var n=0,o=t.input.charCodeAt(t.position);o!==0;){for(;uo(o);)o===9&&t.firstTabInLine===-1&&(t.firstTabInLine=t.position),o=t.input.charCodeAt(++t.position);if(e&&o===35)do o=t.input.charCodeAt(++t.position);while(o!==10&&o!==13&&o!==0);if(zr(o))for(zd(t),o=t.input.charCodeAt(t.position),n++,t.lineIndent=0;o===32;)t.lineIndent++,o=t.input.charCodeAt(++t.position);else break}return r!==-1&&n!==0&&t.lineIndent<r&&kc(t,"deficient indentation"),n}function Pc(t){var e=t.position,r;return r=t.input.charCodeAt(e),!!((r===45||r===46)&&r===t.input.charCodeAt(e+1)&&r===t.input.charCodeAt(e+2)&&(e+=3,r=t.input.charCodeAt(e),r===0||qt(r)))}function jd(t,e){e===1?t.result+=" ":e>1&&(t.result+=lt.repeat(`
78
- `,e-1))}function Y1(t,e,r){var n,o,s,i,a,c,l,u,p=t.kind,m=t.result,d;if(d=t.input.charCodeAt(t.position),qt(d)||us(d)||d===35||d===38||d===42||d===33||d===124||d===62||d===39||d===34||d===37||d===64||d===96||(d===63||d===45)&&(o=t.input.charCodeAt(t.position+1),qt(o)||r&&us(o)))return!1;for(t.kind="scalar",t.result="",s=i=t.position,a=!1;d!==0;){if(d===58){if(o=t.input.charCodeAt(t.position+1),qt(o)||r&&us(o))break}else if(d===35){if(n=t.input.charCodeAt(t.position-1),qt(n))break}else{if(t.position===t.lineStart&&Pc(t)||r&&us(d))break;if(zr(d))if(c=t.line,l=t.lineStart,u=t.lineIndent,it(t,!1,-1),t.lineIndent>=e){a=!0,d=t.input.charCodeAt(t.position);continue}else{t.position=i,t.line=c,t.lineStart=l,t.lineIndent=u;break}}a&&(wn(t,s,i,!1),jd(t,t.line-c),s=i=t.position,a=!1),uo(d)||(i=t.position+1),d=t.input.charCodeAt(++t.position)}return wn(t,s,i,!1),t.result?!0:(t.kind=p,t.result=m,!1)}function X1(t,e){var r,n,o;if(r=t.input.charCodeAt(t.position),r!==39)return!1;for(t.kind="scalar",t.result="",t.position++,n=o=t.position;(r=t.input.charCodeAt(t.position))!==0;)if(r===39)if(wn(t,n,t.position,!0),r=t.input.charCodeAt(++t.position),r===39)n=t.position,t.position++,o=t.position;else return!0;else zr(r)?(wn(t,n,o,!0),jd(t,it(t,!1,e)),n=o=t.position):t.position===t.lineStart&&Pc(t)?H(t,"unexpected end of the document within a single quoted scalar"):(t.position++,o=t.position);H(t,"unexpected end of the stream within a single quoted scalar")}function Q1(t,e){var r,n,o,s,i,a;if(a=t.input.charCodeAt(t.position),a!==34)return!1;for(t.kind="scalar",t.result="",t.position++,r=n=t.position;(a=t.input.charCodeAt(t.position))!==0;){if(a===34)return wn(t,r,t.position,!0),t.position++,!0;if(a===92){if(wn(t,r,t.position,!0),a=t.input.charCodeAt(++t.position),zr(a))it(t,!1,e);else if(a<256&&tw[a])t.result+=rw[a],t.position++;else if((i=G1(a))>0){for(o=i,s=0;o>0;o--)a=t.input.charCodeAt(++t.position),(i=V1(a))>=0?s=(s<<4)+i:H(t,"expected hexadecimal character");t.result+=J1(s),t.position++}else H(t,"unknown escape sequence");r=n=t.position}else zr(a)?(wn(t,r,n,!0),jd(t,it(t,!1,e)),r=n=t.position):t.position===t.lineStart&&Pc(t)?H(t,"unexpected end of the document within a double quoted scalar"):(t.position++,n=t.position)}H(t,"unexpected end of the stream within a double quoted scalar")}function eA(t,e){var r=!0,n,o,s,i=t.tag,a,c=t.anchor,l,u,p,m,d,f=Object.create(null),h,g,v,_;if(_=t.input.charCodeAt(t.position),_===91)u=93,d=!1,a=[];else if(_===123)u=125,d=!0,a={};else return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=a),_=t.input.charCodeAt(++t.position);_!==0;){if(it(t,!0,e),_=t.input.charCodeAt(t.position),_===u)return t.position++,t.tag=i,t.anchor=c,t.kind=d?"mapping":"sequence",t.result=a,!0;r?_===44&&H(t,"expected the node content, but found ','"):H(t,"missed comma between flow collection entries"),g=h=v=null,p=m=!1,_===63&&(l=t.input.charCodeAt(t.position+1),qt(l)&&(p=m=!0,t.position++,it(t,!0,e))),n=t.line,o=t.lineStart,s=t.position,ds(t,e,Sc,!1,!0),g=t.tag,h=t.result,it(t,!0,e),_=t.input.charCodeAt(t.position),(m||t.line===n)&&_===58&&(p=!0,_=t.input.charCodeAt(++t.position),it(t,!0,e),ds(t,e,Sc,!1,!0),v=t.result),d?ps(t,a,f,g,h,v,n,o,s):p?a.push(ps(t,null,f,g,h,v,n,o,s)):a.push(h),it(t,!0,e),_=t.input.charCodeAt(t.position),_===44?(r=!0,_=t.input.charCodeAt(++t.position)):r=!1}H(t,"unexpected end of the stream within a flow collection")}function tA(t,e){var r,n,o=Td,s=!1,i=!1,a=e,c=0,l=!1,u,p;if(p=t.input.charCodeAt(t.position),p===124)n=!1;else if(p===62)n=!0;else return!1;for(t.kind="scalar",t.result="";p!==0;)if(p=t.input.charCodeAt(++t.position),p===43||p===45)Td===o?o=p===43?hb:U1:H(t,"repeat of a chomping mode identifier");else if((u=W1(p))>=0)u===0?H(t,"bad explicit indentation width of a block scalar; it cannot be less than one"):i?H(t,"repeat of an indentation width identifier"):(a=e+u-1,i=!0);else break;if(uo(p)){do p=t.input.charCodeAt(++t.position);while(uo(p));if(p===35)do p=t.input.charCodeAt(++t.position);while(!zr(p)&&p!==0)}for(;p!==0;){for(zd(t),t.lineIndent=0,p=t.input.charCodeAt(t.position);(!i||t.lineIndent<a)&&p===32;)t.lineIndent++,p=t.input.charCodeAt(++t.position);if(!i&&t.lineIndent>a&&(a=t.lineIndent),zr(p)){c++;continue}if(t.lineIndent<a){o===hb?t.result+=lt.repeat(`
79
- `,s?1+c:c):o===Td&&s&&(t.result+=`
80
- `);break}for(n?uo(p)?(l=!0,t.result+=lt.repeat(`
75
+ `,c=1;c<=e.linesAfter&&!(i+c>=o.length);c++)l=Id(t.buffer,n[i+c],o[i+c],t.position-(n[i]-n[i+c]),p),a+=lt.repeat(" ",e.indent)+Ad((t.line+c+1).toString(),u)+" | "+l.str+`
76
+ `;return a.replace(/\n$/,"")}function $1(t){var e={};return t!==null&&Object.keys(t).forEach(function(r){t[r].forEach(function(n){e[String(n)]=r})}),e}function k1(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(x1.indexOf(r)===-1)throw new Ot('Unknown option "'+r+'" is met in definition of "'+t+'" YAML type.')}),this.options=e,this.tag=t,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(r){return r},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.representName=e.representName||null,this.defaultStyle=e.defaultStyle||null,this.multi=e.multi||!1,this.styleAliases=$1(e.styleAliases||null),S1.indexOf(this.kind)===-1)throw new Ot('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}function Sb(t,e){var r=[];return t[e].forEach(function(n){var o=r.length;r.forEach(function(s,i){s.tag===n.tag&&s.kind===n.kind&&s.multi===n.multi&&(o=i)}),r[o]=n}),r}function E1(){var t={scalar:{},sequence:{},mapping:{},fallback:{},multi:{scalar:[],sequence:[],mapping:[],fallback:[]}},e,r;function n(o){o.multi?(t.multi[o.kind].push(o),t.multi.fallback.push(o)):t[o.kind][o.tag]=t.fallback[o.tag]=o}for(e=0,r=arguments.length;e<r;e+=1)arguments[e].forEach(n);return t}function zd(t){return this.extend(t)}function T1(t){if(t===null)return!0;var e=t.length;return e===1&&t==="~"||e===4&&(t==="null"||t==="Null"||t==="NULL")}function P1(){return null}function R1(t){return t===null}function O1(t){if(t===null)return!1;var e=t.length;return e===4&&(t==="true"||t==="True"||t==="TRUE")||e===5&&(t==="false"||t==="False"||t==="FALSE")}function C1(t){return t==="true"||t==="True"||t==="TRUE"}function I1(t){return Object.prototype.toString.call(t)==="[object Boolean]"}function A1(t){return 48<=t&&t<=57||65<=t&&t<=70||97<=t&&t<=102}function N1(t){return 48<=t&&t<=55}function z1(t){return 48<=t&&t<=57}function j1(t){if(t===null)return!1;var e=t.length,r=0,n=!1,o;if(!e)return!1;if(o=t[r],(o==="-"||o==="+")&&(o=t[++r]),o==="0"){if(r+1===e)return!0;if(o=t[++r],o==="b"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(o!=="0"&&o!=="1")return!1;n=!0}return n&&o!=="_"}if(o==="x"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!A1(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}if(o==="o"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!N1(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}}if(o==="_")return!1;for(;r<e;r++)if(o=t[r],o!=="_"){if(!z1(t.charCodeAt(r)))return!1;n=!0}return!(!n||o==="_")}function M1(t){var e=t,r=1,n;if(e.indexOf("_")!==-1&&(e=e.replace(/_/g,"")),n=e[0],(n==="-"||n==="+")&&(n==="-"&&(r=-1),e=e.slice(1),n=e[0]),e==="0")return 0;if(n==="0"){if(e[1]==="b")return r*parseInt(e.slice(2),2);if(e[1]==="x")return r*parseInt(e.slice(2),16);if(e[1]==="o")return r*parseInt(e.slice(2),8)}return r*parseInt(e,10)}function L1(t){return Object.prototype.toString.call(t)==="[object Number]"&&t%1===0&&!lt.isNegativeZero(t)}function q1(t){return!(t===null||!D1.test(t)||t[t.length-1]==="_")}function Z1(t){var e,r;return e=t.replace(/_/g,"").toLowerCase(),r=e[0]==="-"?-1:1,"+-".indexOf(e[0])>=0&&(e=e.slice(1)),e===".inf"?r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:e===".nan"?NaN:r*parseFloat(e,10)}function F1(t,e){var r;if(isNaN(t))switch(e){case"lowercase":return".nan";case"uppercase":return".NAN";case"camelcase":return".NaN"}else if(Number.POSITIVE_INFINITY===t)switch(e){case"lowercase":return".inf";case"uppercase":return".INF";case"camelcase":return".Inf"}else if(Number.NEGATIVE_INFINITY===t)switch(e){case"lowercase":return"-.inf";case"uppercase":return"-.INF";case"camelcase":return"-.Inf"}else if(lt.isNegativeZero(t))return"-0.0";return r=t.toString(10),U1.test(r)?r.replace("e",".e"):r}function H1(t){return Object.prototype.toString.call(t)==="[object Number]"&&(t%1!==0||lt.isNegativeZero(t))}function B1(t){return t===null?!1:Yb.exec(t)!==null||Xb.exec(t)!==null}function G1(t){var e,r,n,o,s,i,a,c=0,l=null,u,p,f;if(e=Yb.exec(t),e===null&&(e=Xb.exec(t)),e===null)throw new Error("Date resolve error");if(r=+e[1],n=+e[2]-1,o=+e[3],!e[4])return new Date(Date.UTC(r,n,o));if(s=+e[4],i=+e[5],a=+e[6],e[7]){for(c=e[7].slice(0,3);c.length<3;)c+="0";c=+c}return e[9]&&(u=+e[10],p=+(e[11]||0),l=(u*60+p)*6e4,e[9]==="-"&&(l=-l)),f=new Date(Date.UTC(r,n,o,s,i,a,c)),l&&f.setTime(f.getTime()-l),f}function V1(t){return t.toISOString()}function W1(t){return t==="<<"||t===null}function J1(t){if(t===null)return!1;var e,r,n=0,o=t.length,s=qd;for(r=0;r<o;r++)if(e=s.indexOf(t.charAt(r)),!(e>64)){if(e<0)return!1;n+=6}return n%8===0}function K1(t){var e,r,n=t.replace(/[\r\n=]/g,""),o=n.length,s=qd,i=0,a=[];for(e=0;e<o;e++)e%4===0&&e&&(a.push(i>>16&255),a.push(i>>8&255),a.push(i&255)),i=i<<6|s.indexOf(n.charAt(e));return r=o%4*6,r===0?(a.push(i>>16&255),a.push(i>>8&255),a.push(i&255)):r===18?(a.push(i>>10&255),a.push(i>>2&255)):r===12&&a.push(i>>4&255),new Uint8Array(a)}function Y1(t){var e="",r=0,n,o,s=t.length,i=qd;for(n=0;n<s;n++)n%3===0&&n&&(e+=i[r>>18&63],e+=i[r>>12&63],e+=i[r>>6&63],e+=i[r&63]),r=(r<<8)+t[n];return o=s%3,o===0?(e+=i[r>>18&63],e+=i[r>>12&63],e+=i[r>>6&63],e+=i[r&63]):o===2?(e+=i[r>>10&63],e+=i[r>>4&63],e+=i[r<<2&63],e+=i[64]):o===1&&(e+=i[r>>2&63],e+=i[r<<4&63],e+=i[64],e+=i[64]),e}function X1(t){return Object.prototype.toString.call(t)==="[object Uint8Array]"}function tA(t){if(t===null)return!0;var e=[],r,n,o,s,i,a=t;for(r=0,n=a.length;r<n;r+=1){if(o=a[r],i=!1,eA.call(o)!=="[object Object]")return!1;for(s in o)if(Q1.call(o,s))if(!i)i=!0;else return!1;if(!i)return!1;if(e.indexOf(s)===-1)e.push(s);else return!1}return!0}function rA(t){return t!==null?t:[]}function oA(t){if(t===null)return!0;var e,r,n,o,s,i=t;for(s=new Array(i.length),e=0,r=i.length;e<r;e+=1){if(n=i[e],nA.call(n)!=="[object Object]"||(o=Object.keys(n),o.length!==1))return!1;s[e]=[o[0],n[o[0]]]}return!0}function sA(t){if(t===null)return[];var e,r,n,o,s,i=t;for(s=new Array(i.length),e=0,r=i.length;e<r;e+=1)n=i[e],o=Object.keys(n),s[e]=[o[0],n[o[0]]];return s}function aA(t){if(t===null)return!0;var e,r=t;for(e in r)if(iA.call(r,e)&&r[e]!==null)return!1;return!0}function cA(t){return t!==null?t:{}}function kb(t){return Object.prototype.toString.call(t)}function zr(t){return t===10||t===13}function po(t){return t===9||t===32}function qt(t){return t===9||t===32||t===10||t===13}function ds(t){return t===44||t===91||t===93||t===123||t===125}function fA(t){var e;return 48<=t&&t<=57?t-48:(e=t|32,97<=e&&e<=102?e-97+10:-1)}function mA(t){return t===120?2:t===117?4:t===85?8:0}function hA(t){return 48<=t&&t<=57?t-48:-1}function Eb(t){return t===48?"\0":t===97?"\x07":t===98?"\b":t===116||t===9?" ":t===110?`
77
+ `:t===118?"\v":t===102?"\f":t===114?"\r":t===101?"\x1B":t===32?" ":t===34?'"':t===47?"/":t===92?"\\":t===78?"\x85":t===95?"\xA0":t===76?"\u2028":t===80?"\u2029":""}function gA(t){return t<=65535?String.fromCharCode(t):String.fromCharCode((t-65536>>10)+55296,(t-65536&1023)+56320)}function lw(t,e,r){e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!0,value:r}):t[e]=r}function yA(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||Zd,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=t.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.firstTabInLine=-1,this.documents=[]}function dw(t,e){var r={name:t.filename,buffer:t.input.slice(0,-1),position:t.position,line:t.line,column:t.position-t.lineStart};return r.snippet=w1(r),new Ot(e,r)}function H(t,e){throw dw(t,e)}function Rc(t,e){t.onWarning&&t.onWarning.call(null,dw(t,e))}function wn(t,e,r,n){var o,s,i,a;if(e<r){if(a=t.input.slice(e,r),n)for(o=0,s=a.length;o<s;o+=1)i=a.charCodeAt(o),i===9||32<=i&&i<=1114111||H(t,"expected valid JSON character");else uA.test(a)&&H(t,"the stream contains non-printable characters");t.result+=a}}function Pb(t,e,r,n){var o,s,i,a;for(lt.isObject(r)||H(t,"cannot merge mappings; the provided source object is unacceptable"),o=Object.keys(r),i=0,a=o.length;i<a;i+=1)s=o[i],xn.call(e,s)||(lw(e,s,r[s]),n[s]=!0)}function fs(t,e,r,n,o,s,i,a,c){var l,u;if(Array.isArray(o))for(o=Array.prototype.slice.call(o),l=0,u=o.length;l<u;l+=1)Array.isArray(o[l])&&H(t,"nested arrays are not supported inside keys"),typeof o=="object"&&kb(o[l])==="[object Object]"&&(o[l]="[object Object]");if(typeof o=="object"&&kb(o)==="[object Object]"&&(o="[object Object]"),o=String(o),e===null&&(e={}),n==="tag:yaml.org,2002:merge")if(Array.isArray(s))for(l=0,u=s.length;l<u;l+=1)Pb(t,e,s[l],r);else Pb(t,e,s,r);else!t.json&&!xn.call(r,o)&&xn.call(e,o)&&(t.line=i||t.line,t.lineStart=a||t.lineStart,t.position=c||t.position,H(t,"duplicated mapping key")),lw(e,o,s),delete r[o];return e}function Ud(t){var e;e=t.input.charCodeAt(t.position),e===10?t.position++:e===13?(t.position++,t.input.charCodeAt(t.position)===10&&t.position++):H(t,"a line break is expected"),t.line+=1,t.lineStart=t.position,t.firstTabInLine=-1}function it(t,e,r){for(var n=0,o=t.input.charCodeAt(t.position);o!==0;){for(;po(o);)o===9&&t.firstTabInLine===-1&&(t.firstTabInLine=t.position),o=t.input.charCodeAt(++t.position);if(e&&o===35)do o=t.input.charCodeAt(++t.position);while(o!==10&&o!==13&&o!==0);if(zr(o))for(Ud(t),o=t.input.charCodeAt(t.position),n++,t.lineIndent=0;o===32;)t.lineIndent++,o=t.input.charCodeAt(++t.position);else break}return r!==-1&&n!==0&&t.lineIndent<r&&Rc(t,"deficient indentation"),n}function Ic(t){var e=t.position,r;return r=t.input.charCodeAt(e),!!((r===45||r===46)&&r===t.input.charCodeAt(e+1)&&r===t.input.charCodeAt(e+2)&&(e+=3,r=t.input.charCodeAt(e),r===0||qt(r)))}function Fd(t,e){e===1?t.result+=" ":e>1&&(t.result+=lt.repeat(`
78
+ `,e-1))}function vA(t,e,r){var n,o,s,i,a,c,l,u,p=t.kind,f=t.result,d;if(d=t.input.charCodeAt(t.position),qt(d)||ds(d)||d===35||d===38||d===42||d===33||d===124||d===62||d===39||d===34||d===37||d===64||d===96||(d===63||d===45)&&(o=t.input.charCodeAt(t.position+1),qt(o)||r&&ds(o)))return!1;for(t.kind="scalar",t.result="",s=i=t.position,a=!1;d!==0;){if(d===58){if(o=t.input.charCodeAt(t.position+1),qt(o)||r&&ds(o))break}else if(d===35){if(n=t.input.charCodeAt(t.position-1),qt(n))break}else{if(t.position===t.lineStart&&Ic(t)||r&&ds(d))break;if(zr(d))if(c=t.line,l=t.lineStart,u=t.lineIndent,it(t,!1,-1),t.lineIndent>=e){a=!0,d=t.input.charCodeAt(t.position);continue}else{t.position=i,t.line=c,t.lineStart=l,t.lineIndent=u;break}}a&&(wn(t,s,i,!1),Fd(t,t.line-c),s=i=t.position,a=!1),po(d)||(i=t.position+1),d=t.input.charCodeAt(++t.position)}return wn(t,s,i,!1),t.result?!0:(t.kind=p,t.result=f,!1)}function _A(t,e){var r,n,o;if(r=t.input.charCodeAt(t.position),r!==39)return!1;for(t.kind="scalar",t.result="",t.position++,n=o=t.position;(r=t.input.charCodeAt(t.position))!==0;)if(r===39)if(wn(t,n,t.position,!0),r=t.input.charCodeAt(++t.position),r===39)n=t.position,t.position++,o=t.position;else return!0;else zr(r)?(wn(t,n,o,!0),Fd(t,it(t,!1,e)),n=o=t.position):t.position===t.lineStart&&Ic(t)?H(t,"unexpected end of the document within a single quoted scalar"):(t.position++,o=t.position);H(t,"unexpected end of the stream within a single quoted scalar")}function bA(t,e){var r,n,o,s,i,a;if(a=t.input.charCodeAt(t.position),a!==34)return!1;for(t.kind="scalar",t.result="",t.position++,r=n=t.position;(a=t.input.charCodeAt(t.position))!==0;){if(a===34)return wn(t,r,t.position,!0),t.position++,!0;if(a===92){if(wn(t,r,t.position,!0),a=t.input.charCodeAt(++t.position),zr(a))it(t,!1,e);else if(a<256&&uw[a])t.result+=pw[a],t.position++;else if((i=mA(a))>0){for(o=i,s=0;o>0;o--)a=t.input.charCodeAt(++t.position),(i=fA(a))>=0?s=(s<<4)+i:H(t,"expected hexadecimal character");t.result+=gA(s),t.position++}else H(t,"unknown escape sequence");r=n=t.position}else zr(a)?(wn(t,r,n,!0),Fd(t,it(t,!1,e)),r=n=t.position):t.position===t.lineStart&&Ic(t)?H(t,"unexpected end of the document within a double quoted scalar"):(t.position++,n=t.position)}H(t,"unexpected end of the stream within a double quoted scalar")}function wA(t,e){var r=!0,n,o,s,i=t.tag,a,c=t.anchor,l,u,p,f,d,m=Object.create(null),h,g,v,b;if(b=t.input.charCodeAt(t.position),b===91)u=93,d=!1,a=[];else if(b===123)u=125,d=!0,a={};else return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=a),b=t.input.charCodeAt(++t.position);b!==0;){if(it(t,!0,e),b=t.input.charCodeAt(t.position),b===u)return t.position++,t.tag=i,t.anchor=c,t.kind=d?"mapping":"sequence",t.result=a,!0;r?b===44&&H(t,"expected the node content, but found ','"):H(t,"missed comma between flow collection entries"),g=h=v=null,p=f=!1,b===63&&(l=t.input.charCodeAt(t.position+1),qt(l)&&(p=f=!0,t.position++,it(t,!0,e))),n=t.line,o=t.lineStart,s=t.position,ms(t,e,Tc,!1,!0),g=t.tag,h=t.result,it(t,!0,e),b=t.input.charCodeAt(t.position),(f||t.line===n)&&b===58&&(p=!0,b=t.input.charCodeAt(++t.position),it(t,!0,e),ms(t,e,Tc,!1,!0),v=t.result),d?fs(t,a,m,g,h,v,n,o,s):p?a.push(fs(t,null,m,g,h,v,n,o,s)):a.push(h),it(t,!0,e),b=t.input.charCodeAt(t.position),b===44?(r=!0,b=t.input.charCodeAt(++t.position)):r=!1}H(t,"unexpected end of the stream within a flow collection")}function xA(t,e){var r,n,o=Nd,s=!1,i=!1,a=e,c=0,l=!1,u,p;if(p=t.input.charCodeAt(t.position),p===124)n=!1;else if(p===62)n=!0;else return!1;for(t.kind="scalar",t.result="";p!==0;)if(p=t.input.charCodeAt(++t.position),p===43||p===45)Nd===o?o=p===43?$b:lA:H(t,"repeat of a chomping mode identifier");else if((u=hA(p))>=0)u===0?H(t,"bad explicit indentation width of a block scalar; it cannot be less than one"):i?H(t,"repeat of an indentation width identifier"):(a=e+u-1,i=!0);else break;if(po(p)){do p=t.input.charCodeAt(++t.position);while(po(p));if(p===35)do p=t.input.charCodeAt(++t.position);while(!zr(p)&&p!==0)}for(;p!==0;){for(Ud(t),t.lineIndent=0,p=t.input.charCodeAt(t.position);(!i||t.lineIndent<a)&&p===32;)t.lineIndent++,p=t.input.charCodeAt(++t.position);if(!i&&t.lineIndent>a&&(a=t.lineIndent),zr(p)){c++;continue}if(t.lineIndent<a){o===$b?t.result+=lt.repeat(`
79
+ `,s?1+c:c):o===Nd&&s&&(t.result+=`
80
+ `);break}for(n?po(p)?(l=!0,t.result+=lt.repeat(`
81
81
  `,s?1+c:c)):l?(l=!1,t.result+=lt.repeat(`
82
82
  `,c+1)):c===0?s&&(t.result+=" "):t.result+=lt.repeat(`
83
83
  `,c):t.result+=lt.repeat(`
84
- `,s?1+c:c),s=!0,i=!0,c=0,r=t.position;!zr(p)&&p!==0;)p=t.input.charCodeAt(++t.position);wn(t,r,t.position,!1)}return!0}function bb(t,e){var r,n=t.tag,o=t.anchor,s=[],i,a=!1,c;if(t.firstTabInLine!==-1)return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=s),c=t.input.charCodeAt(t.position);c!==0&&(t.firstTabInLine!==-1&&(t.position=t.firstTabInLine,H(t,"tab characters must not be used in indentation")),!(c!==45||(i=t.input.charCodeAt(t.position+1),!qt(i))));){if(a=!0,t.position++,it(t,!0,-1)&&t.lineIndent<=e){s.push(null),c=t.input.charCodeAt(t.position);continue}if(r=t.line,ds(t,e,Yb,!1,!0),s.push(t.result),it(t,!0,-1),c=t.input.charCodeAt(t.position),(t.line===r||t.lineIndent>e)&&c!==0)H(t,"bad indentation of a sequence entry");else if(t.lineIndent<e)break}return a?(t.tag=n,t.anchor=o,t.kind="sequence",t.result=s,!0):!1}function rA(t,e,r){var n,o,s,i,a,c,l=t.tag,u=t.anchor,p={},m=Object.create(null),d=null,f=null,h=null,g=!1,v=!1,_;if(t.firstTabInLine!==-1)return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=p),_=t.input.charCodeAt(t.position);_!==0;){if(!g&&t.firstTabInLine!==-1&&(t.position=t.firstTabInLine,H(t,"tab characters must not be used in indentation")),n=t.input.charCodeAt(t.position+1),s=t.line,(_===63||_===58)&&qt(n))_===63?(g&&(ps(t,p,m,d,f,null,i,a,c),d=f=h=null),v=!0,g=!0,o=!0):g?(g=!1,o=!0):H(t,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),t.position+=1,_=n;else{if(i=t.line,a=t.lineStart,c=t.position,!ds(t,r,Kb,!1,!0))break;if(t.line===s){for(_=t.input.charCodeAt(t.position);uo(_);)_=t.input.charCodeAt(++t.position);if(_===58)_=t.input.charCodeAt(++t.position),qt(_)||H(t,"a whitespace character is expected after the key-value separator within a block mapping"),g&&(ps(t,p,m,d,f,null,i,a,c),d=f=h=null),v=!0,g=!1,o=!1,d=t.tag,f=t.result;else if(v)H(t,"can not read an implicit mapping pair; a colon is missed");else return t.tag=l,t.anchor=u,!0}else if(v)H(t,"can not read a block mapping entry; a multiline key may not be an implicit key");else return t.tag=l,t.anchor=u,!0}if((t.line===s||t.lineIndent>e)&&(g&&(i=t.line,a=t.lineStart,c=t.position),ds(t,e,$c,!0,o)&&(g?f=t.result:h=t.result),g||(ps(t,p,m,d,f,h,i,a,c),d=f=h=null),it(t,!0,-1),_=t.input.charCodeAt(t.position)),(t.line===s||t.lineIndent>e)&&_!==0)H(t,"bad indentation of a mapping entry");else if(t.lineIndent<e)break}return g&&ps(t,p,m,d,f,null,i,a,c),v&&(t.tag=l,t.anchor=u,t.kind="mapping",t.result=p),v}function nA(t){var e,r=!1,n=!1,o,s,i;if(i=t.input.charCodeAt(t.position),i!==33)return!1;if(t.tag!==null&&H(t,"duplication of a tag property"),i=t.input.charCodeAt(++t.position),i===60?(r=!0,i=t.input.charCodeAt(++t.position)):i===33?(n=!0,o="!!",i=t.input.charCodeAt(++t.position)):o="!",e=t.position,r){do i=t.input.charCodeAt(++t.position);while(i!==0&&i!==62);t.position<t.length?(s=t.input.slice(e,t.position),i=t.input.charCodeAt(++t.position)):H(t,"unexpected end of the stream within a verbatim tag")}else{for(;i!==0&&!qt(i);)i===33&&(n?H(t,"tag suffix cannot contain exclamation marks"):(o=t.input.slice(e-1,t.position+1),Xb.test(o)||H(t,"named tag handle cannot contain such characters"),n=!0,e=t.position+1)),i=t.input.charCodeAt(++t.position);s=t.input.slice(e,t.position),B1.test(s)&&H(t,"tag suffix cannot contain flow indicator characters")}s&&!Qb.test(s)&&H(t,"tag name cannot contain such characters: "+s);try{s=decodeURIComponent(s)}catch{H(t,"tag name is malformed: "+s)}return r?t.tag=s:xn.call(t.tagMap,o)?t.tag=t.tagMap[o]+s:o==="!"?t.tag="!"+s:o==="!!"?t.tag="tag:yaml.org,2002:"+s:H(t,'undeclared tag handle "'+o+'"'),!0}function oA(t){var e,r;if(r=t.input.charCodeAt(t.position),r!==38)return!1;for(t.anchor!==null&&H(t,"duplication of an anchor property"),r=t.input.charCodeAt(++t.position),e=t.position;r!==0&&!qt(r)&&!us(r);)r=t.input.charCodeAt(++t.position);return t.position===e&&H(t,"name of an anchor node must contain at least one character"),t.anchor=t.input.slice(e,t.position),!0}function sA(t){var e,r,n;if(n=t.input.charCodeAt(t.position),n!==42)return!1;for(n=t.input.charCodeAt(++t.position),e=t.position;n!==0&&!qt(n)&&!us(n);)n=t.input.charCodeAt(++t.position);return t.position===e&&H(t,"name of an alias node must contain at least one character"),r=t.input.slice(e,t.position),xn.call(t.anchorMap,r)||H(t,'unidentified alias "'+r+'"'),t.result=t.anchorMap[r],it(t,!0,-1),!0}function ds(t,e,r,n,o){var s,i,a,c=1,l=!1,u=!1,p,m,d,f,h,g;if(t.listener!==null&&t.listener("open",t),t.tag=null,t.anchor=null,t.kind=null,t.result=null,s=i=a=$c===r||Yb===r,n&&it(t,!0,-1)&&(l=!0,t.lineIndent>e?c=1:t.lineIndent===e?c=0:t.lineIndent<e&&(c=-1)),c===1)for(;nA(t)||oA(t);)it(t,!0,-1)?(l=!0,a=s,t.lineIndent>e?c=1:t.lineIndent===e?c=0:t.lineIndent<e&&(c=-1)):a=!1;if(a&&(a=l||o),(c===1||$c===r)&&(Sc===r||Kb===r?h=e:h=e+1,g=t.position-t.lineStart,c===1?a&&(bb(t,g)||rA(t,g,h))||eA(t,h)?u=!0:(i&&tA(t,h)||X1(t,h)||Q1(t,h)?u=!0:sA(t)?(u=!0,(t.tag!==null||t.anchor!==null)&&H(t,"alias node should not have any properties")):Y1(t,h,Sc===r)&&(u=!0,t.tag===null&&(t.tag="?")),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):c===0&&(u=a&&bb(t,g))),t.tag===null)t.anchor!==null&&(t.anchorMap[t.anchor]=t.result);else if(t.tag==="?"){for(t.result!==null&&t.kind!=="scalar"&&H(t,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+t.kind+'"'),p=0,m=t.implicitTypes.length;p<m;p+=1)if(f=t.implicitTypes[p],f.resolve(t.result)){t.result=f.construct(t.result),t.tag=f.tag,t.anchor!==null&&(t.anchorMap[t.anchor]=t.result);break}}else if(t.tag!=="!"){if(xn.call(t.typeMap[t.kind||"fallback"],t.tag))f=t.typeMap[t.kind||"fallback"][t.tag];else for(f=null,d=t.typeMap.multi[t.kind||"fallback"],p=0,m=d.length;p<m;p+=1)if(t.tag.slice(0,d[p].tag.length)===d[p].tag){f=d[p];break}f||H(t,"unknown tag !<"+t.tag+">"),t.result!==null&&f.kind!==t.kind&&H(t,"unacceptable node kind for !<"+t.tag+'> tag; it should be "'+f.kind+'", not "'+t.kind+'"'),f.resolve(t.result,t.tag)?(t.result=f.construct(t.result,t.tag),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):H(t,"cannot resolve a node with !<"+t.tag+"> explicit tag")}return t.listener!==null&&t.listener("close",t),t.tag!==null||t.anchor!==null||u}function iA(t){var e=t.position,r,n,o,s=!1,i;for(t.version=null,t.checkLineBreaks=t.legacy,t.tagMap=Object.create(null),t.anchorMap=Object.create(null);(i=t.input.charCodeAt(t.position))!==0&&(it(t,!0,-1),i=t.input.charCodeAt(t.position),!(t.lineIndent>0||i!==37));){for(s=!0,i=t.input.charCodeAt(++t.position),r=t.position;i!==0&&!qt(i);)i=t.input.charCodeAt(++t.position);for(n=t.input.slice(r,t.position),o=[],n.length<1&&H(t,"directive name must not be less than one character in length");i!==0;){for(;uo(i);)i=t.input.charCodeAt(++t.position);if(i===35){do i=t.input.charCodeAt(++t.position);while(i!==0&&!zr(i));break}if(zr(i))break;for(r=t.position;i!==0&&!qt(i);)i=t.input.charCodeAt(++t.position);o.push(t.input.slice(r,t.position))}i!==0&&zd(t),xn.call(vb,n)?vb[n](t,n,o):kc(t,'unknown document directive "'+n+'"')}if(it(t,!0,-1),t.lineIndent===0&&t.input.charCodeAt(t.position)===45&&t.input.charCodeAt(t.position+1)===45&&t.input.charCodeAt(t.position+2)===45?(t.position+=3,it(t,!0,-1)):s&&H(t,"directives end mark is expected"),ds(t,t.lineIndent-1,$c,!1,!0),it(t,!0,-1),t.checkLineBreaks&&H1.test(t.input.slice(e,t.position))&&kc(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&Pc(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,it(t,!0,-1));return}if(t.position<t.length-1)H(t,"end of the stream or a document separator is expected");else return}function ow(t,e){t=String(t),e=e||{},t.length!==0&&(t.charCodeAt(t.length-1)!==10&&t.charCodeAt(t.length-1)!==13&&(t+=`
85
- `),t.charCodeAt(0)===65279&&(t=t.slice(1)));var r=new K1(t,e),n=t.indexOf("\0");for(n!==-1&&(r.position=n,H(r,"null byte is not allowed in input")),r.input+="\0";r.input.charCodeAt(r.position)===32;)r.lineIndent+=1,r.position+=1;for(;r.position<r.length-1;)iA(r);return r.documents}function aA(t,e,r){e!==null&&typeof e=="object"&&typeof r>"u"&&(r=e,e=null);var n=ow(t,r);if(typeof e!="function")return n;for(var o=0,s=n.length;o<s;o+=1)e(n[o])}function cA(t,e){var r=ow(t,e);if(r.length!==0){if(r.length===1)return r[0];throw new Ot("expected a single document in the stream, but found more")}}function RA(t,e){var r,n,o,s,i,a,c;if(e===null)return{};for(r={},n=Object.keys(e),o=0,s=n.length;o<s;o+=1)i=n[o],a=String(e[i]),i.slice(0,2)==="!!"&&(i="tag:yaml.org,2002:"+i.slice(2)),c=t.compiledTypeMap.fallback[i],c&&aw.call(c.styleAliases,a)&&(a=c.styleAliases[a]),r[i]=a;return r}function OA(t){var e,r,n;if(e=t.toString(16).toUpperCase(),t<=255)r="x",n=2;else if(t<=65535)r="u",n=4;else if(t<=4294967295)r="U",n=8;else throw new Ot("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+r+lt.repeat("0",n-e.length)+e}function IA(t){this.schema=t.schema||Nd,this.indent=Math.max(1,t.indent||2),this.noArrayIndent=t.noArrayIndent||!1,this.skipInvalid=t.skipInvalid||!1,this.flowLevel=lt.isNothing(t.flowLevel)?-1:t.flowLevel,this.styleMap=RA(this.schema,t.styles||null),this.sortKeys=t.sortKeys||!1,this.lineWidth=t.lineWidth||80,this.noRefs=t.noRefs||!1,this.noCompatMode=t.noCompatMode||!1,this.condenseFlow=t.condenseFlow||!1,this.quotingType=t.quotingType==='"'?ki:CA,this.forceQuotes=t.forceQuotes||!1,this.replacer=typeof t.replacer=="function"?t.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function wb(t,e){for(var r=lt.repeat(" ",e),n=0,o=-1,s="",i,a=t.length;n<a;)o=t.indexOf(`
84
+ `,s?1+c:c),s=!0,i=!0,c=0,r=t.position;!zr(p)&&p!==0;)p=t.input.charCodeAt(++t.position);wn(t,r,t.position,!1)}return!0}function Rb(t,e){var r,n=t.tag,o=t.anchor,s=[],i,a=!1,c;if(t.firstTabInLine!==-1)return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=s),c=t.input.charCodeAt(t.position);c!==0&&(t.firstTabInLine!==-1&&(t.position=t.firstTabInLine,H(t,"tab characters must not be used in indentation")),!(c!==45||(i=t.input.charCodeAt(t.position+1),!qt(i))));){if(a=!0,t.position++,it(t,!0,-1)&&t.lineIndent<=e){s.push(null),c=t.input.charCodeAt(t.position);continue}if(r=t.line,ms(t,e,iw,!1,!0),s.push(t.result),it(t,!0,-1),c=t.input.charCodeAt(t.position),(t.line===r||t.lineIndent>e)&&c!==0)H(t,"bad indentation of a sequence entry");else if(t.lineIndent<e)break}return a?(t.tag=n,t.anchor=o,t.kind="sequence",t.result=s,!0):!1}function SA(t,e,r){var n,o,s,i,a,c,l=t.tag,u=t.anchor,p={},f=Object.create(null),d=null,m=null,h=null,g=!1,v=!1,b;if(t.firstTabInLine!==-1)return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=p),b=t.input.charCodeAt(t.position);b!==0;){if(!g&&t.firstTabInLine!==-1&&(t.position=t.firstTabInLine,H(t,"tab characters must not be used in indentation")),n=t.input.charCodeAt(t.position+1),s=t.line,(b===63||b===58)&&qt(n))b===63?(g&&(fs(t,p,f,d,m,null,i,a,c),d=m=h=null),v=!0,g=!0,o=!0):g?(g=!1,o=!0):H(t,"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line"),t.position+=1,b=n;else{if(i=t.line,a=t.lineStart,c=t.position,!ms(t,r,sw,!1,!0))break;if(t.line===s){for(b=t.input.charCodeAt(t.position);po(b);)b=t.input.charCodeAt(++t.position);if(b===58)b=t.input.charCodeAt(++t.position),qt(b)||H(t,"a whitespace character is expected after the key-value separator within a block mapping"),g&&(fs(t,p,f,d,m,null,i,a,c),d=m=h=null),v=!0,g=!1,o=!1,d=t.tag,m=t.result;else if(v)H(t,"can not read an implicit mapping pair; a colon is missed");else return t.tag=l,t.anchor=u,!0}else if(v)H(t,"can not read a block mapping entry; a multiline key may not be an implicit key");else return t.tag=l,t.anchor=u,!0}if((t.line===s||t.lineIndent>e)&&(g&&(i=t.line,a=t.lineStart,c=t.position),ms(t,e,Pc,!0,o)&&(g?m=t.result:h=t.result),g||(fs(t,p,f,d,m,h,i,a,c),d=m=h=null),it(t,!0,-1),b=t.input.charCodeAt(t.position)),(t.line===s||t.lineIndent>e)&&b!==0)H(t,"bad indentation of a mapping entry");else if(t.lineIndent<e)break}return g&&fs(t,p,f,d,m,null,i,a,c),v&&(t.tag=l,t.anchor=u,t.kind="mapping",t.result=p),v}function $A(t){var e,r=!1,n=!1,o,s,i;if(i=t.input.charCodeAt(t.position),i!==33)return!1;if(t.tag!==null&&H(t,"duplication of a tag property"),i=t.input.charCodeAt(++t.position),i===60?(r=!0,i=t.input.charCodeAt(++t.position)):i===33?(n=!0,o="!!",i=t.input.charCodeAt(++t.position)):o="!",e=t.position,r){do i=t.input.charCodeAt(++t.position);while(i!==0&&i!==62);t.position<t.length?(s=t.input.slice(e,t.position),i=t.input.charCodeAt(++t.position)):H(t,"unexpected end of the stream within a verbatim tag")}else{for(;i!==0&&!qt(i);)i===33&&(n?H(t,"tag suffix cannot contain exclamation marks"):(o=t.input.slice(e-1,t.position+1),aw.test(o)||H(t,"named tag handle cannot contain such characters"),n=!0,e=t.position+1)),i=t.input.charCodeAt(++t.position);s=t.input.slice(e,t.position),dA.test(s)&&H(t,"tag suffix cannot contain flow indicator characters")}s&&!cw.test(s)&&H(t,"tag name cannot contain such characters: "+s);try{s=decodeURIComponent(s)}catch{H(t,"tag name is malformed: "+s)}return r?t.tag=s:xn.call(t.tagMap,o)?t.tag=t.tagMap[o]+s:o==="!"?t.tag="!"+s:o==="!!"?t.tag="tag:yaml.org,2002:"+s:H(t,'undeclared tag handle "'+o+'"'),!0}function kA(t){var e,r;if(r=t.input.charCodeAt(t.position),r!==38)return!1;for(t.anchor!==null&&H(t,"duplication of an anchor property"),r=t.input.charCodeAt(++t.position),e=t.position;r!==0&&!qt(r)&&!ds(r);)r=t.input.charCodeAt(++t.position);return t.position===e&&H(t,"name of an anchor node must contain at least one character"),t.anchor=t.input.slice(e,t.position),!0}function EA(t){var e,r,n;if(n=t.input.charCodeAt(t.position),n!==42)return!1;for(n=t.input.charCodeAt(++t.position),e=t.position;n!==0&&!qt(n)&&!ds(n);)n=t.input.charCodeAt(++t.position);return t.position===e&&H(t,"name of an alias node must contain at least one character"),r=t.input.slice(e,t.position),xn.call(t.anchorMap,r)||H(t,'unidentified alias "'+r+'"'),t.result=t.anchorMap[r],it(t,!0,-1),!0}function ms(t,e,r,n,o){var s,i,a,c=1,l=!1,u=!1,p,f,d,m,h,g;if(t.listener!==null&&t.listener("open",t),t.tag=null,t.anchor=null,t.kind=null,t.result=null,s=i=a=Pc===r||iw===r,n&&it(t,!0,-1)&&(l=!0,t.lineIndent>e?c=1:t.lineIndent===e?c=0:t.lineIndent<e&&(c=-1)),c===1)for(;$A(t)||kA(t);)it(t,!0,-1)?(l=!0,a=s,t.lineIndent>e?c=1:t.lineIndent===e?c=0:t.lineIndent<e&&(c=-1)):a=!1;if(a&&(a=l||o),(c===1||Pc===r)&&(Tc===r||sw===r?h=e:h=e+1,g=t.position-t.lineStart,c===1?a&&(Rb(t,g)||SA(t,g,h))||wA(t,h)?u=!0:(i&&xA(t,h)||_A(t,h)||bA(t,h)?u=!0:EA(t)?(u=!0,(t.tag!==null||t.anchor!==null)&&H(t,"alias node should not have any properties")):vA(t,h,Tc===r)&&(u=!0,t.tag===null&&(t.tag="?")),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):c===0&&(u=a&&Rb(t,g))),t.tag===null)t.anchor!==null&&(t.anchorMap[t.anchor]=t.result);else if(t.tag==="?"){for(t.result!==null&&t.kind!=="scalar"&&H(t,'unacceptable node kind for !<?> tag; it should be "scalar", not "'+t.kind+'"'),p=0,f=t.implicitTypes.length;p<f;p+=1)if(m=t.implicitTypes[p],m.resolve(t.result)){t.result=m.construct(t.result),t.tag=m.tag,t.anchor!==null&&(t.anchorMap[t.anchor]=t.result);break}}else if(t.tag!=="!"){if(xn.call(t.typeMap[t.kind||"fallback"],t.tag))m=t.typeMap[t.kind||"fallback"][t.tag];else for(m=null,d=t.typeMap.multi[t.kind||"fallback"],p=0,f=d.length;p<f;p+=1)if(t.tag.slice(0,d[p].tag.length)===d[p].tag){m=d[p];break}m||H(t,"unknown tag !<"+t.tag+">"),t.result!==null&&m.kind!==t.kind&&H(t,"unacceptable node kind for !<"+t.tag+'> tag; it should be "'+m.kind+'", not "'+t.kind+'"'),m.resolve(t.result,t.tag)?(t.result=m.construct(t.result,t.tag),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):H(t,"cannot resolve a node with !<"+t.tag+"> explicit tag")}return t.listener!==null&&t.listener("close",t),t.tag!==null||t.anchor!==null||u}function TA(t){var e=t.position,r,n,o,s=!1,i;for(t.version=null,t.checkLineBreaks=t.legacy,t.tagMap=Object.create(null),t.anchorMap=Object.create(null);(i=t.input.charCodeAt(t.position))!==0&&(it(t,!0,-1),i=t.input.charCodeAt(t.position),!(t.lineIndent>0||i!==37));){for(s=!0,i=t.input.charCodeAt(++t.position),r=t.position;i!==0&&!qt(i);)i=t.input.charCodeAt(++t.position);for(n=t.input.slice(r,t.position),o=[],n.length<1&&H(t,"directive name must not be less than one character in length");i!==0;){for(;po(i);)i=t.input.charCodeAt(++t.position);if(i===35){do i=t.input.charCodeAt(++t.position);while(i!==0&&!zr(i));break}if(zr(i))break;for(r=t.position;i!==0&&!qt(i);)i=t.input.charCodeAt(++t.position);o.push(t.input.slice(r,t.position))}i!==0&&Ud(t),xn.call(Tb,n)?Tb[n](t,n,o):Rc(t,'unknown document directive "'+n+'"')}if(it(t,!0,-1),t.lineIndent===0&&t.input.charCodeAt(t.position)===45&&t.input.charCodeAt(t.position+1)===45&&t.input.charCodeAt(t.position+2)===45?(t.position+=3,it(t,!0,-1)):s&&H(t,"directives end mark is expected"),ms(t,t.lineIndent-1,Pc,!1,!0),it(t,!0,-1),t.checkLineBreaks&&pA.test(t.input.slice(e,t.position))&&Rc(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&Ic(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,it(t,!0,-1));return}if(t.position<t.length-1)H(t,"end of the stream or a document separator is expected");else return}function fw(t,e){t=String(t),e=e||{},t.length!==0&&(t.charCodeAt(t.length-1)!==10&&t.charCodeAt(t.length-1)!==13&&(t+=`
85
+ `),t.charCodeAt(0)===65279&&(t=t.slice(1)));var r=new yA(t,e),n=t.indexOf("\0");for(n!==-1&&(r.position=n,H(r,"null byte is not allowed in input")),r.input+="\0";r.input.charCodeAt(r.position)===32;)r.lineIndent+=1,r.position+=1;for(;r.position<r.length-1;)TA(r);return r.documents}function PA(t,e,r){e!==null&&typeof e=="object"&&typeof r>"u"&&(r=e,e=null);var n=fw(t,r);if(typeof e!="function")return n;for(var o=0,s=n.length;o<s;o+=1)e(n[o])}function RA(t,e){var r=fw(t,e);if(r.length!==0){if(r.length===1)return r[0];throw new Ot("expected a single document in the stream, but found more")}}function KA(t,e){var r,n,o,s,i,a,c;if(e===null)return{};for(r={},n=Object.keys(e),o=0,s=n.length;o<s;o+=1)i=n[o],a=String(e[i]),i.slice(0,2)==="!!"&&(i="tag:yaml.org,2002:"+i.slice(2)),c=t.compiledTypeMap.fallback[i],c&&gw.call(c.styleAliases,a)&&(a=c.styleAliases[a]),r[i]=a;return r}function YA(t){var e,r,n;if(e=t.toString(16).toUpperCase(),t<=255)r="x",n=2;else if(t<=65535)r="u",n=4;else if(t<=4294967295)r="U",n=8;else throw new Ot("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+r+lt.repeat("0",n-e.length)+e}function QA(t){this.schema=t.schema||Zd,this.indent=Math.max(1,t.indent||2),this.noArrayIndent=t.noArrayIndent||!1,this.skipInvalid=t.skipInvalid||!1,this.flowLevel=lt.isNothing(t.flowLevel)?-1:t.flowLevel,this.styleMap=KA(this.schema,t.styles||null),this.sortKeys=t.sortKeys||!1,this.lineWidth=t.lineWidth||80,this.noRefs=t.noRefs||!1,this.noCompatMode=t.noCompatMode||!1,this.condenseFlow=t.condenseFlow||!1,this.quotingType=t.quotingType==='"'?Pi:XA,this.forceQuotes=t.forceQuotes||!1,this.replacer=typeof t.replacer=="function"?t.replacer:null,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result="",this.duplicates=[],this.usedDuplicates=null}function Ob(t,e){for(var r=lt.repeat(" ",e),n=0,o=-1,s="",i,a=t.length;n<a;)o=t.indexOf(`
86
86
  `,n),o===-1?(i=t.slice(n),n=a):(i=t.slice(n,o+1),n=o+1),i.length&&i!==`
87
- `&&(s+=r),s+=i;return s}function Od(t,e){return`
88
- `+lt.repeat(" ",t.indent*e)}function AA(t,e){var r,n,o;for(r=0,n=t.implicitTypes.length;r<n;r+=1)if(o=t.implicitTypes[r],o.resolve(e))return!0;return!1}function Tc(t){return t===fA||t===pA}function Ei(t){return 32<=t&&t<=126||161<=t&&t<=55295&&t!==8232&&t!==8233||57344<=t&&t<=65533&&t!==Md||65536<=t&&t<=1114111}function xb(t){return Ei(t)&&t!==Md&&t!==dA&&t!==$i}function Sb(t,e,r){var n=xb(t),o=n&&!Tc(t);return(r?n:n&&t!==cw&&t!==lw&&t!==uw&&t!==pw&&t!==dw)&&t!==Rd&&!(e===Ec&&!o)||xb(e)&&!Tc(e)&&t===Rd||e===Ec&&o}function NA(t){return Ei(t)&&t!==Md&&!Tc(t)&&t!==bA&&t!==SA&&t!==Ec&&t!==cw&&t!==lw&&t!==uw&&t!==pw&&t!==dw&&t!==Rd&&t!==yA&&t!==_A&&t!==mA&&t!==EA&&t!==wA&&t!==xA&&t!==vA&&t!==hA&&t!==gA&&t!==$A&&t!==kA}function zA(t){return!Tc(t)&&t!==Ec}function xi(t,e){var r=t.charCodeAt(e),n;return r>=55296&&r<=56319&&e+1<t.length&&(n=t.charCodeAt(e+1),n>=56320&&n<=57343)?(r-55296)*1024+n-56320+65536:r}function fw(t){var e=/^\n* /;return e.test(t)}function jA(t,e,r,n,o,s,i,a){var c,l=0,u=null,p=!1,m=!1,d=n!==-1,f=-1,h=NA(xi(t,0))&&zA(xi(t,t.length-1));if(e||i)for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=xi(t,c),!Ei(l))return ls;h=h&&Sb(l,u,a),u=l}else{for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=xi(t,c),l===$i)p=!0,d&&(m=m||c-f-1>n&&t[f+1]!==" ",f=c);else if(!Ei(l))return ls;h=h&&Sb(l,u,a),u=l}m=m||d&&c-f-1>n&&t[f+1]!==" "}return!p&&!m?h&&!i&&!o(t)?mw:s===ki?ls:Cd:r>9&&fw(t)?ls:i?s===ki?ls:Cd:m?gw:hw}function MA(t,e,r,n,o){t.dump=function(){if(e.length===0)return t.quotingType===ki?'""':"''";if(!t.noCompatMode&&(TA.indexOf(e)!==-1||PA.test(e)))return t.quotingType===ki?'"'+e+'"':"'"+e+"'";var s=t.indent*Math.max(1,r),i=t.lineWidth===-1?-1:Math.max(Math.min(t.lineWidth,40),t.lineWidth-s),a=n||t.flowLevel>-1&&r>=t.flowLevel;function c(l){return AA(t,l)}switch(jA(e,a,t.indent,i,c,t.quotingType,t.forceQuotes&&!n,o)){case mw:return e;case Cd:return"'"+e.replace(/'/g,"''")+"'";case hw:return"|"+$b(e,t.indent)+kb(wb(e,s));case gw:return">"+$b(e,t.indent)+kb(wb(LA(e,i),s));case ls:return'"'+DA(e)+'"';default:throw new Ot("impossible error: invalid scalar style")}}()}function $b(t,e){var r=fw(t)?String(e):"",n=t[t.length-1]===`
87
+ `&&(s+=r),s+=i;return s}function Md(t,e){return`
88
+ `+lt.repeat(" ",t.indent*e)}function eN(t,e){var r,n,o;for(r=0,n=t.implicitTypes.length;r<n;r+=1)if(o=t.implicitTypes[r],o.resolve(e))return!0;return!1}function Cc(t){return t===NA||t===IA}function Ri(t){return 32<=t&&t<=126||161<=t&&t<=55295&&t!==8232&&t!==8233||57344<=t&&t<=65533&&t!==Hd||65536<=t&&t<=1114111}function Cb(t){return Ri(t)&&t!==Hd&&t!==AA&&t!==Ti}function Ib(t,e,r){var n=Cb(t),o=n&&!Cc(t);return(r?n:n&&t!==yw&&t!==vw&&t!==_w&&t!==bw&&t!==ww)&&t!==jd&&!(e===Oc&&!o)||Cb(e)&&!Cc(e)&&t===jd||e===Oc&&o}function tN(t){return Ri(t)&&t!==Hd&&!Cc(t)&&t!==ZA&&t!==HA&&t!==Oc&&t!==yw&&t!==vw&&t!==_w&&t!==bw&&t!==ww&&t!==jd&&t!==LA&&t!==qA&&t!==zA&&t!==VA&&t!==UA&&t!==FA&&t!==DA&&t!==jA&&t!==MA&&t!==BA&&t!==GA}function rN(t){return!Cc(t)&&t!==Oc}function ki(t,e){var r=t.charCodeAt(e),n;return r>=55296&&r<=56319&&e+1<t.length&&(n=t.charCodeAt(e+1),n>=56320&&n<=57343)?(r-55296)*1024+n-56320+65536:r}function xw(t){var e=/^\n* /;return e.test(t)}function nN(t,e,r,n,o,s,i,a){var c,l=0,u=null,p=!1,f=!1,d=n!==-1,m=-1,h=tN(ki(t,0))&&rN(ki(t,t.length-1));if(e||i)for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=ki(t,c),!Ri(l))return ps;h=h&&Ib(l,u,a),u=l}else{for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=ki(t,c),l===Ti)p=!0,d&&(f=f||c-m-1>n&&t[m+1]!==" ",m=c);else if(!Ri(l))return ps;h=h&&Ib(l,u,a),u=l}f=f||d&&c-m-1>n&&t[m+1]!==" "}return!p&&!f?h&&!i&&!o(t)?Sw:s===Pi?ps:Ld:r>9&&xw(t)?ps:i?s===Pi?ps:Ld:f?kw:$w}function oN(t,e,r,n,o){t.dump=function(){if(e.length===0)return t.quotingType===Pi?'""':"''";if(!t.noCompatMode&&(WA.indexOf(e)!==-1||JA.test(e)))return t.quotingType===Pi?'"'+e+'"':"'"+e+"'";var s=t.indent*Math.max(1,r),i=t.lineWidth===-1?-1:Math.max(Math.min(t.lineWidth,40),t.lineWidth-s),a=n||t.flowLevel>-1&&r>=t.flowLevel;function c(l){return eN(t,l)}switch(nN(e,a,t.indent,i,c,t.quotingType,t.forceQuotes&&!n,o)){case Sw:return e;case Ld:return"'"+e.replace(/'/g,"''")+"'";case $w:return"|"+Ab(e,t.indent)+Nb(Ob(e,s));case kw:return">"+Ab(e,t.indent)+Nb(Ob(sN(e,i),s));case ps:return'"'+iN(e)+'"';default:throw new Ot("impossible error: invalid scalar style")}}()}function Ab(t,e){var r=xw(t)?String(e):"",n=t[t.length-1]===`
89
89
  `,o=n&&(t[t.length-2]===`
90
90
  `||t===`
91
91
  `),s=o?"+":n?"":"-";return r+s+`
92
- `}function kb(t){return t[t.length-1]===`
93
- `?t.slice(0,-1):t}function LA(t,e){for(var r=/(\n+)([^\n]*)/g,n=function(){var l=t.indexOf(`
94
- `);return l=l!==-1?l:t.length,r.lastIndex=l,Eb(t.slice(0,l),e)}(),o=t[0]===`
92
+ `}function Nb(t){return t[t.length-1]===`
93
+ `?t.slice(0,-1):t}function sN(t,e){for(var r=/(\n+)([^\n]*)/g,n=function(){var l=t.indexOf(`
94
+ `);return l=l!==-1?l:t.length,r.lastIndex=l,zb(t.slice(0,l),e)}(),o=t[0]===`
95
95
  `||t[0]===" ",s,i;i=r.exec(t);){var a=i[1],c=i[2];s=c[0]===" ",n+=a+(!o&&!s&&c!==""?`
96
- `:"")+Eb(c,e),o=s}return n}function Eb(t,e){if(t===""||t[0]===" ")return t;for(var r=/ [^ ]/g,n,o=0,s,i=0,a=0,c="";n=r.exec(t);)a=n.index,a-o>e&&(s=i>o?i:a,c+=`
96
+ `:"")+zb(c,e),o=s}return n}function zb(t,e){if(t===""||t[0]===" ")return t;for(var r=/ [^ ]/g,n,o=0,s,i=0,a=0,c="";n=r.exec(t);)a=n.index,a-o>e&&(s=i>o?i:a,c+=`
97
97
  `+t.slice(o,s),o=s+1),i=a;return c+=`
98
98
  `,t.length-o>e&&i>o?c+=t.slice(o,i)+`
99
- `+t.slice(i+1):c+=t.slice(o),c.slice(1)}function DA(t){for(var e="",r=0,n,o=0;o<t.length;r>=65536?o+=2:o++)r=xi(t,o),n=kt[r],!n&&Ei(r)?(e+=t[o],r>=65536&&(e+=t[o+1])):e+=n||OA(r);return e}function qA(t,e,r){var n="",o=t.tag,s,i,a;for(s=0,i=r.length;s<i;s+=1)a=r[s],t.replacer&&(a=t.replacer.call(r,String(s),a)),(Yr(t,e,a,!1,!1)||typeof a>"u"&&Yr(t,e,null,!1,!1))&&(n!==""&&(n+=","+(t.condenseFlow?"":" ")),n+=t.dump);t.tag=o,t.dump="["+n+"]"}function Tb(t,e,r,n){var o="",s=t.tag,i,a,c;for(i=0,a=r.length;i<a;i+=1)c=r[i],t.replacer&&(c=t.replacer.call(r,String(i),c)),(Yr(t,e+1,c,!0,!0,!1,!0)||typeof c>"u"&&Yr(t,e+1,null,!0,!0,!1,!0))&&((!n||o!=="")&&(o+=Od(t,e)),t.dump&&$i===t.dump.charCodeAt(0)?o+="-":o+="- ",o+=t.dump);t.tag=s,t.dump=o||"[]"}function ZA(t,e,r){var n="",o=t.tag,s=Object.keys(r),i,a,c,l,u;for(i=0,a=s.length;i<a;i+=1)u="",n!==""&&(u+=", "),t.condenseFlow&&(u+='"'),c=s[i],l=r[c],t.replacer&&(l=t.replacer.call(r,c,l)),Yr(t,e,c,!1,!1)&&(t.dump.length>1024&&(u+="? "),u+=t.dump+(t.condenseFlow?'"':"")+":"+(t.condenseFlow?"":" "),Yr(t,e,l,!1,!1)&&(u+=t.dump,n+=u));t.tag=o,t.dump="{"+n+"}"}function UA(t,e,r,n){var o="",s=t.tag,i=Object.keys(r),a,c,l,u,p,m;if(t.sortKeys===!0)i.sort();else if(typeof t.sortKeys=="function")i.sort(t.sortKeys);else if(t.sortKeys)throw new Ot("sortKeys must be a boolean or a function");for(a=0,c=i.length;a<c;a+=1)m="",(!n||o!=="")&&(m+=Od(t,e)),l=i[a],u=r[l],t.replacer&&(u=t.replacer.call(r,l,u)),Yr(t,e+1,l,!0,!0,!0)&&(p=t.tag!==null&&t.tag!=="?"||t.dump&&t.dump.length>1024,p&&(t.dump&&$i===t.dump.charCodeAt(0)?m+="?":m+="? "),m+=t.dump,p&&(m+=Od(t,e)),Yr(t,e+1,u,!0,p)&&(t.dump&&$i===t.dump.charCodeAt(0)?m+=":":m+=": ",m+=t.dump,o+=m));t.tag=s,t.dump=o||"{}"}function Pb(t,e,r){var n,o,s,i,a,c;for(o=r?t.explicitTypes:t.implicitTypes,s=0,i=o.length;s<i;s+=1)if(a=o[s],(a.instanceOf||a.predicate)&&(!a.instanceOf||typeof e=="object"&&e instanceof a.instanceOf)&&(!a.predicate||a.predicate(e))){if(r?a.multi&&a.representName?t.tag=a.representName(e):t.tag=a.tag:t.tag="?",a.represent){if(c=t.styleMap[a.tag]||a.defaultStyle,iw.call(a.represent)==="[object Function]")n=a.represent(e,c);else if(aw.call(a.represent,c))n=a.represent[c](e,c);else throw new Ot("!<"+a.tag+'> tag resolver accepts not "'+c+'" style');t.dump=n}return!0}return!1}function Yr(t,e,r,n,o,s,i){t.tag=null,t.dump=r,Pb(t,r,!1)||Pb(t,r,!0);var a=iw.call(t.dump),c=n,l;n&&(n=t.flowLevel<0||t.flowLevel>e);var u=a==="[object Object]"||a==="[object Array]",p,m;if(u&&(p=t.duplicates.indexOf(r),m=p!==-1),(t.tag!==null&&t.tag!=="?"||m||t.indent!==2&&e>0)&&(o=!1),m&&t.usedDuplicates[p])t.dump="*ref_"+p;else{if(u&&m&&!t.usedDuplicates[p]&&(t.usedDuplicates[p]=!0),a==="[object Object]")n&&Object.keys(t.dump).length!==0?(UA(t,e,t.dump,o),m&&(t.dump="&ref_"+p+t.dump)):(ZA(t,e,t.dump),m&&(t.dump="&ref_"+p+" "+t.dump));else if(a==="[object Array]")n&&t.dump.length!==0?(t.noArrayIndent&&!i&&e>0?Tb(t,e-1,t.dump,o):Tb(t,e,t.dump,o),m&&(t.dump="&ref_"+p+t.dump)):(qA(t,e,t.dump),m&&(t.dump="&ref_"+p+" "+t.dump));else if(a==="[object String]")t.tag!=="?"&&MA(t,t.dump,e,s,c);else{if(a==="[object Undefined]")return!1;if(t.skipInvalid)return!1;throw new Ot("unacceptable kind of an object to dump "+a)}t.tag!==null&&t.tag!=="?"&&(l=encodeURI(t.tag[0]==="!"?t.tag.slice(1):t.tag).replace(/!/g,"%21"),t.tag[0]==="!"?l="!"+l:l.slice(0,18)==="tag:yaml.org,2002:"?l="!!"+l.slice(18):l="!<"+l+">",t.dump=l+" "+t.dump)}return!0}function FA(t,e){var r=[],n=[],o,s;for(Id(t,r,n),o=0,s=n.length;o<s;o+=1)e.duplicates.push(r[n[o]]);e.usedDuplicates=new Array(s)}function Id(t,e,r){var n,o,s;if(t!==null&&typeof t=="object")if(o=e.indexOf(t),o!==-1)r.indexOf(o)===-1&&r.push(o);else if(e.push(t),Array.isArray(t))for(o=0,s=t.length;o<s;o+=1)Id(t[o],e,r);else for(n=Object.keys(t),o=0,s=n.length;o<s;o+=1)Id(t[n[o]],e,r)}function HA(t,e){e=e||{};var r=new IA(e);r.noRefs||FA(t,r);var n=t;return r.replacer&&(n=r.replacer.call({"":n},"",n)),Yr(r,0,n,!0,!0)?r.dump+`
100
- `:""}function Ld(t,e){return function(){throw new Error("Function yaml."+t+" is removed in js-yaml 4. Use yaml."+e+" instead, which is now safe by default.")}}var GI,WI,JI,KI,YI,XI,lt,Ot,e1,t1,r1,gt,Cb,Ib,Ab,Nb,zb,jb,Mb,Lb,v1,w1,Db,qb,Zb,Ub,Fb,Hb,Bb,Ad,Vb,I1,A1,Gb,j1,Wb,D1,Jb,Nd,xn,Sc,Kb,Yb,$c,Td,U1,hb,F1,H1,B1,Xb,Qb,tw,rw,lo,vb,lA,uA,sw,iw,aw,Md,pA,$i,dA,fA,mA,hA,Rd,gA,yA,vA,_A,cw,bA,Ec,wA,xA,SA,$A,lw,uw,kA,pw,EA,dw,kt,TA,PA,CA,ki,mw,Cd,hw,gw,ls,BA,VA,GA,WA,JA,KA,YA,XA,QA,eN,tN,rN,nN,oN,sN,iN,Xr,Ti=w(()=>{GI=Rb,WI=UI,JI=FI,KI=BI,YI=VI,XI=HI,lt={isNothing:GI,isObject:WI,toArray:JI,repeat:KI,isNegativeZero:YI,extend:XI};Si.prototype=Object.create(Error.prototype);Si.prototype.constructor=Si;Si.prototype.toString=function(e){return this.name+": "+Ob(this,e)};Ot=Si;e1=QI,t1=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],r1=["scalar","sequence","mapping"];gt=o1;Pd.prototype.extend=function(e){var r=[],n=[];if(e instanceof gt)n.push(e);else if(Array.isArray(e))n=n.concat(e);else if(e&&(Array.isArray(e.implicit)||Array.isArray(e.explicit)))e.implicit&&(r=r.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit));else throw new Ot("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");r.forEach(function(s){if(!(s instanceof gt))throw new Ot("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(s.loadKind&&s.loadKind!=="scalar")throw new Ot("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(s.multi)throw new Ot("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),n.forEach(function(s){if(!(s instanceof gt))throw new Ot("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var o=Object.create(Pd.prototype);return o.implicit=(this.implicit||[]).concat(r),o.explicit=(this.explicit||[]).concat(n),o.compiledImplicit=mb(o,"implicit"),o.compiledExplicit=mb(o,"explicit"),o.compiledTypeMap=s1(o.compiledImplicit,o.compiledExplicit),o};Cb=Pd,Ib=new gt("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Ab=new gt("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Nb=new gt("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),zb=new Cb({explicit:[Ib,Ab,Nb]});jb=new gt("tag:yaml.org,2002:null",{kind:"scalar",resolve:i1,construct:a1,predicate:c1,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});Mb=new gt("tag:yaml.org,2002:bool",{kind:"scalar",resolve:l1,construct:u1,predicate:p1,represent:{lowercase:function(t){return t?"true":"false"},uppercase:function(t){return t?"TRUE":"FALSE"},camelcase:function(t){return t?"True":"False"}},defaultStyle:"lowercase"});Lb=new gt("tag:yaml.org,2002:int",{kind:"scalar",resolve:h1,construct:g1,predicate:y1,represent:{binary:function(t){return t>=0?"0b"+t.toString(2):"-0b"+t.toString(2).slice(1)},octal:function(t){return t>=0?"0o"+t.toString(8):"-0o"+t.toString(8).slice(1)},decimal:function(t){return t.toString(10)},hexadecimal:function(t){return t>=0?"0x"+t.toString(16).toUpperCase():"-0x"+t.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),v1=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");w1=/^[-+]?[0-9]+e/;Db=new gt("tag:yaml.org,2002:float",{kind:"scalar",resolve:_1,construct:b1,predicate:S1,represent:x1,defaultStyle:"lowercase"}),qb=zb.extend({implicit:[jb,Mb,Lb,Db]}),Zb=qb,Ub=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),Fb=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");Hb=new gt("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:$1,construct:k1,instanceOf:Date,represent:E1});Bb=new gt("tag:yaml.org,2002:merge",{kind:"scalar",resolve:T1}),Ad=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
101
- \r`;Vb=new gt("tag:yaml.org,2002:binary",{kind:"scalar",resolve:P1,construct:R1,predicate:C1,represent:O1}),I1=Object.prototype.hasOwnProperty,A1=Object.prototype.toString;Gb=new gt("tag:yaml.org,2002:omap",{kind:"sequence",resolve:N1,construct:z1}),j1=Object.prototype.toString;Wb=new gt("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:M1,construct:L1}),D1=Object.prototype.hasOwnProperty;Jb=new gt("tag:yaml.org,2002:set",{kind:"mapping",resolve:q1,construct:Z1}),Nd=Zb.extend({implicit:[Hb,Bb],explicit:[Vb,Gb,Wb,Jb]}),xn=Object.prototype.hasOwnProperty,Sc=1,Kb=2,Yb=3,$c=4,Td=1,U1=2,hb=3,F1=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,H1=/[\x85\u2028\u2029]/,B1=/[,\[\]\{\}]/,Xb=/^(?:!|!!|![a-z\-]+!)$/i,Qb=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;tw=new Array(256),rw=new Array(256);for(lo=0;lo<256;lo++)tw[lo]=yb(lo)?1:0,rw[lo]=yb(lo);vb={YAML:function(e,r,n){var o,s,i;e.version!==null&&H(e,"duplication of %YAML directive"),n.length!==1&&H(e,"YAML directive accepts exactly one argument"),o=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),o===null&&H(e,"ill-formed argument of the YAML directive"),s=parseInt(o[1],10),i=parseInt(o[2],10),s!==1&&H(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=i<2,i!==1&&i!==2&&kc(e,"unsupported YAML version of the document")},TAG:function(e,r,n){var o,s;n.length!==2&&H(e,"TAG directive accepts exactly two arguments"),o=n[0],s=n[1],Xb.test(o)||H(e,"ill-formed tag handle (first argument) of the TAG directive"),xn.call(e.tagMap,o)&&H(e,'there is a previously declared suffix for "'+o+'" tag handle'),Qb.test(s)||H(e,"ill-formed tag prefix (second argument) of the TAG directive");try{s=decodeURIComponent(s)}catch{H(e,"tag prefix is malformed: "+s)}e.tagMap[o]=s}};lA=aA,uA=cA,sw={loadAll:lA,load:uA},iw=Object.prototype.toString,aw=Object.prototype.hasOwnProperty,Md=65279,pA=9,$i=10,dA=13,fA=32,mA=33,hA=34,Rd=35,gA=37,yA=38,vA=39,_A=42,cw=44,bA=45,Ec=58,wA=61,xA=62,SA=63,$A=64,lw=91,uw=93,kA=96,pw=123,EA=124,dw=125,kt={};kt[0]="\\0";kt[7]="\\a";kt[8]="\\b";kt[9]="\\t";kt[10]="\\n";kt[11]="\\v";kt[12]="\\f";kt[13]="\\r";kt[27]="\\e";kt[34]='\\"';kt[92]="\\\\";kt[133]="\\N";kt[160]="\\_";kt[8232]="\\L";kt[8233]="\\P";TA=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],PA=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;CA=1,ki=2;mw=1,Cd=2,hw=3,gw=4,ls=5;BA=HA,VA={dump:BA};GA=gt,WA=Cb,JA=zb,KA=qb,YA=Zb,XA=Nd,QA=sw.load,eN=sw.loadAll,tN=VA.dump,rN=Ot,nN={binary:Vb,float:Db,map:Nb,null:jb,pairs:Wb,set:Jb,timestamp:Hb,bool:Mb,int:Lb,merge:Bb,omap:Gb,seq:Ab,str:Ib},oN=Ld("safeLoad","load"),sN=Ld("safeLoadAll","loadAll"),iN=Ld("safeDump","dump"),Xr={Type:GA,Schema:WA,FAILSAFE_SCHEMA:JA,JSON_SCHEMA:KA,CORE_SCHEMA:YA,DEFAULT_SCHEMA:XA,load:QA,loadAll:eN,dump:tN,YAMLException:rN,types:nN,safeLoad:oN,safeLoadAll:sN,safeDump:iN}});var ww={};X(ww,{protocol:()=>uN});import{readFileSync as vw,writeFileSync as aN,existsSync as cN}from"node:fs";import{basename as lN}from"node:path";function _w(t){if(console.log(C("Protocol")),console.log(S("Name",t.name)),t.version&&console.log(S("Version",t.version)),t.description&&console.log(S("Description",t.description)),t.roles?.length){console.log(C("Roles"));for(let e of t.roles)console.log(` ${y("bold",e.name)}${e.description?` \u2014 ${e.description}`:""}`),e.capabilities?.length&&console.log(` ${y("dim",e.capabilities.join(", "))}`)}if(t.phases?.length){console.log(C("Phases"));for(let e=0;e<t.phases.length;e++){let r=t.phases[e];console.log(` ${y("cyan",`${e+1}.`)} ${y("bold",r.name)}${r.description?` \u2014 ${r.description}`:""}`),r.resources?.length&&console.log(` Resources: ${y("dim",r.resources.join(", "))}`)}}if(t.resources?.length){console.log(C("Resources"));for(let e of t.resources)console.log(` \u2022 ${e}`)}if(t.rules?.length){console.log(C("Rules"));for(let e of t.rules)console.log(` \u2022 ${e}`)}console.log()}async function bw(t){try{return await co(t)}catch{}try{return JSON.parse(t)}catch{}try{return Xr.load(t)}catch{}return null}async function uN(t=[]){let e=t[0];if(e==="validate"){await dN(t.slice(1));return}if(e==="load"){await fN(t.slice(1));return}if(e==="init"){await mN(t.slice(1));return}if(e==="--help"||e==="-h"){console.log(`
99
+ `+t.slice(i+1):c+=t.slice(o),c.slice(1)}function iN(t){for(var e="",r=0,n,o=0;o<t.length;r>=65536?o+=2:o++)r=ki(t,o),n=kt[r],!n&&Ri(r)?(e+=t[o],r>=65536&&(e+=t[o+1])):e+=n||YA(r);return e}function aN(t,e,r){var n="",o=t.tag,s,i,a;for(s=0,i=r.length;s<i;s+=1)a=r[s],t.replacer&&(a=t.replacer.call(r,String(s),a)),(Yr(t,e,a,!1,!1)||typeof a>"u"&&Yr(t,e,null,!1,!1))&&(n!==""&&(n+=","+(t.condenseFlow?"":" ")),n+=t.dump);t.tag=o,t.dump="["+n+"]"}function jb(t,e,r,n){var o="",s=t.tag,i,a,c;for(i=0,a=r.length;i<a;i+=1)c=r[i],t.replacer&&(c=t.replacer.call(r,String(i),c)),(Yr(t,e+1,c,!0,!0,!1,!0)||typeof c>"u"&&Yr(t,e+1,null,!0,!0,!1,!0))&&((!n||o!=="")&&(o+=Md(t,e)),t.dump&&Ti===t.dump.charCodeAt(0)?o+="-":o+="- ",o+=t.dump);t.tag=s,t.dump=o||"[]"}function cN(t,e,r){var n="",o=t.tag,s=Object.keys(r),i,a,c,l,u;for(i=0,a=s.length;i<a;i+=1)u="",n!==""&&(u+=", "),t.condenseFlow&&(u+='"'),c=s[i],l=r[c],t.replacer&&(l=t.replacer.call(r,c,l)),Yr(t,e,c,!1,!1)&&(t.dump.length>1024&&(u+="? "),u+=t.dump+(t.condenseFlow?'"':"")+":"+(t.condenseFlow?"":" "),Yr(t,e,l,!1,!1)&&(u+=t.dump,n+=u));t.tag=o,t.dump="{"+n+"}"}function lN(t,e,r,n){var o="",s=t.tag,i=Object.keys(r),a,c,l,u,p,f;if(t.sortKeys===!0)i.sort();else if(typeof t.sortKeys=="function")i.sort(t.sortKeys);else if(t.sortKeys)throw new Ot("sortKeys must be a boolean or a function");for(a=0,c=i.length;a<c;a+=1)f="",(!n||o!=="")&&(f+=Md(t,e)),l=i[a],u=r[l],t.replacer&&(u=t.replacer.call(r,l,u)),Yr(t,e+1,l,!0,!0,!0)&&(p=t.tag!==null&&t.tag!=="?"||t.dump&&t.dump.length>1024,p&&(t.dump&&Ti===t.dump.charCodeAt(0)?f+="?":f+="? "),f+=t.dump,p&&(f+=Md(t,e)),Yr(t,e+1,u,!0,p)&&(t.dump&&Ti===t.dump.charCodeAt(0)?f+=":":f+=": ",f+=t.dump,o+=f));t.tag=s,t.dump=o||"{}"}function Mb(t,e,r){var n,o,s,i,a,c;for(o=r?t.explicitTypes:t.implicitTypes,s=0,i=o.length;s<i;s+=1)if(a=o[s],(a.instanceOf||a.predicate)&&(!a.instanceOf||typeof e=="object"&&e instanceof a.instanceOf)&&(!a.predicate||a.predicate(e))){if(r?a.multi&&a.representName?t.tag=a.representName(e):t.tag=a.tag:t.tag="?",a.represent){if(c=t.styleMap[a.tag]||a.defaultStyle,hw.call(a.represent)==="[object Function]")n=a.represent(e,c);else if(gw.call(a.represent,c))n=a.represent[c](e,c);else throw new Ot("!<"+a.tag+'> tag resolver accepts not "'+c+'" style');t.dump=n}return!0}return!1}function Yr(t,e,r,n,o,s,i){t.tag=null,t.dump=r,Mb(t,r,!1)||Mb(t,r,!0);var a=hw.call(t.dump),c=n,l;n&&(n=t.flowLevel<0||t.flowLevel>e);var u=a==="[object Object]"||a==="[object Array]",p,f;if(u&&(p=t.duplicates.indexOf(r),f=p!==-1),(t.tag!==null&&t.tag!=="?"||f||t.indent!==2&&e>0)&&(o=!1),f&&t.usedDuplicates[p])t.dump="*ref_"+p;else{if(u&&f&&!t.usedDuplicates[p]&&(t.usedDuplicates[p]=!0),a==="[object Object]")n&&Object.keys(t.dump).length!==0?(lN(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):(cN(t,e,t.dump),f&&(t.dump="&ref_"+p+" "+t.dump));else if(a==="[object Array]")n&&t.dump.length!==0?(t.noArrayIndent&&!i&&e>0?jb(t,e-1,t.dump,o):jb(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):(aN(t,e,t.dump),f&&(t.dump="&ref_"+p+" "+t.dump));else if(a==="[object String]")t.tag!=="?"&&oN(t,t.dump,e,s,c);else{if(a==="[object Undefined]")return!1;if(t.skipInvalid)return!1;throw new Ot("unacceptable kind of an object to dump "+a)}t.tag!==null&&t.tag!=="?"&&(l=encodeURI(t.tag[0]==="!"?t.tag.slice(1):t.tag).replace(/!/g,"%21"),t.tag[0]==="!"?l="!"+l:l.slice(0,18)==="tag:yaml.org,2002:"?l="!!"+l.slice(18):l="!<"+l+">",t.dump=l+" "+t.dump)}return!0}function uN(t,e){var r=[],n=[],o,s;for(Dd(t,r,n),o=0,s=n.length;o<s;o+=1)e.duplicates.push(r[n[o]]);e.usedDuplicates=new Array(s)}function Dd(t,e,r){var n,o,s;if(t!==null&&typeof t=="object")if(o=e.indexOf(t),o!==-1)r.indexOf(o)===-1&&r.push(o);else if(e.push(t),Array.isArray(t))for(o=0,s=t.length;o<s;o+=1)Dd(t[o],e,r);else for(n=Object.keys(t),o=0,s=n.length;o<s;o+=1)Dd(t[n[o]],e,r)}function pN(t,e){e=e||{};var r=new QA(e);r.noRefs||uN(t,r);var n=t;return r.replacer&&(n=r.replacer.call({"":n},"",n)),Yr(r,0,n,!0,!0)?r.dump+`
100
+ `:""}function Bd(t,e){return function(){throw new Error("Function yaml."+t+" is removed in js-yaml 4. Use yaml."+e+" instead, which is now safe by default.")}}var m1,h1,g1,y1,v1,_1,lt,Ot,w1,x1,S1,gt,qb,Zb,Ub,Fb,Hb,Bb,Gb,Vb,D1,U1,Wb,Jb,Kb,Yb,Xb,Qb,ew,qd,tw,Q1,eA,rw,nA,nw,iA,ow,Zd,xn,Tc,sw,iw,Pc,Nd,lA,$b,uA,pA,dA,aw,cw,uw,pw,uo,Tb,OA,CA,mw,hw,gw,Hd,IA,Ti,AA,NA,zA,jA,jd,MA,LA,DA,qA,yw,ZA,Oc,UA,FA,HA,BA,vw,_w,GA,bw,VA,ww,kt,WA,JA,XA,Pi,Sw,Ld,$w,kw,ps,dN,fN,mN,hN,gN,yN,vN,_N,bN,wN,xN,SN,$N,kN,EN,TN,Xr,Oi=w(()=>{m1=Lb,h1=l1,g1=u1,y1=d1,v1=f1,_1=p1,lt={isNothing:m1,isObject:h1,toArray:g1,repeat:y1,isNegativeZero:v1,extend:_1};Ei.prototype=Object.create(Error.prototype);Ei.prototype.constructor=Ei;Ei.prototype.toString=function(e){return this.name+": "+Db(this,e)};Ot=Ei;w1=b1,x1=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],S1=["scalar","sequence","mapping"];gt=k1;zd.prototype.extend=function(e){var r=[],n=[];if(e instanceof gt)n.push(e);else if(Array.isArray(e))n=n.concat(e);else if(e&&(Array.isArray(e.implicit)||Array.isArray(e.explicit)))e.implicit&&(r=r.concat(e.implicit)),e.explicit&&(n=n.concat(e.explicit));else throw new Ot("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");r.forEach(function(s){if(!(s instanceof gt))throw new Ot("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(s.loadKind&&s.loadKind!=="scalar")throw new Ot("There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.");if(s.multi)throw new Ot("There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.")}),n.forEach(function(s){if(!(s instanceof gt))throw new Ot("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var o=Object.create(zd.prototype);return o.implicit=(this.implicit||[]).concat(r),o.explicit=(this.explicit||[]).concat(n),o.compiledImplicit=Sb(o,"implicit"),o.compiledExplicit=Sb(o,"explicit"),o.compiledTypeMap=E1(o.compiledImplicit,o.compiledExplicit),o};qb=zd,Zb=new gt("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Ub=new gt("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Fb=new gt("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),Hb=new qb({explicit:[Zb,Ub,Fb]});Bb=new gt("tag:yaml.org,2002:null",{kind:"scalar",resolve:T1,construct:P1,predicate:R1,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});Gb=new gt("tag:yaml.org,2002:bool",{kind:"scalar",resolve:O1,construct:C1,predicate:I1,represent:{lowercase:function(t){return t?"true":"false"},uppercase:function(t){return t?"TRUE":"FALSE"},camelcase:function(t){return t?"True":"False"}},defaultStyle:"lowercase"});Vb=new gt("tag:yaml.org,2002:int",{kind:"scalar",resolve:j1,construct:M1,predicate:L1,represent:{binary:function(t){return t>=0?"0b"+t.toString(2):"-0b"+t.toString(2).slice(1)},octal:function(t){return t>=0?"0o"+t.toString(8):"-0o"+t.toString(8).slice(1)},decimal:function(t){return t.toString(10)},hexadecimal:function(t){return t>=0?"0x"+t.toString(16).toUpperCase():"-0x"+t.toString(16).toUpperCase().slice(1)}},defaultStyle:"decimal",styleAliases:{binary:[2,"bin"],octal:[8,"oct"],decimal:[10,"dec"],hexadecimal:[16,"hex"]}}),D1=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");U1=/^[-+]?[0-9]+e/;Wb=new gt("tag:yaml.org,2002:float",{kind:"scalar",resolve:q1,construct:Z1,predicate:H1,represent:F1,defaultStyle:"lowercase"}),Jb=Hb.extend({implicit:[Bb,Gb,Vb,Wb]}),Kb=Jb,Yb=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),Xb=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\.([0-9]*))?(?:[ \\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$");Qb=new gt("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:B1,construct:G1,instanceOf:Date,represent:V1});ew=new gt("tag:yaml.org,2002:merge",{kind:"scalar",resolve:W1}),qd=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
101
+ \r`;tw=new gt("tag:yaml.org,2002:binary",{kind:"scalar",resolve:J1,construct:K1,predicate:X1,represent:Y1}),Q1=Object.prototype.hasOwnProperty,eA=Object.prototype.toString;rw=new gt("tag:yaml.org,2002:omap",{kind:"sequence",resolve:tA,construct:rA}),nA=Object.prototype.toString;nw=new gt("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:oA,construct:sA}),iA=Object.prototype.hasOwnProperty;ow=new gt("tag:yaml.org,2002:set",{kind:"mapping",resolve:aA,construct:cA}),Zd=Kb.extend({implicit:[Qb,ew],explicit:[tw,rw,nw,ow]}),xn=Object.prototype.hasOwnProperty,Tc=1,sw=2,iw=3,Pc=4,Nd=1,lA=2,$b=3,uA=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,pA=/[\x85\u2028\u2029]/,dA=/[,\[\]\{\}]/,aw=/^(?:!|!!|![a-z\-]+!)$/i,cw=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;uw=new Array(256),pw=new Array(256);for(uo=0;uo<256;uo++)uw[uo]=Eb(uo)?1:0,pw[uo]=Eb(uo);Tb={YAML:function(e,r,n){var o,s,i;e.version!==null&&H(e,"duplication of %YAML directive"),n.length!==1&&H(e,"YAML directive accepts exactly one argument"),o=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),o===null&&H(e,"ill-formed argument of the YAML directive"),s=parseInt(o[1],10),i=parseInt(o[2],10),s!==1&&H(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=i<2,i!==1&&i!==2&&Rc(e,"unsupported YAML version of the document")},TAG:function(e,r,n){var o,s;n.length!==2&&H(e,"TAG directive accepts exactly two arguments"),o=n[0],s=n[1],aw.test(o)||H(e,"ill-formed tag handle (first argument) of the TAG directive"),xn.call(e.tagMap,o)&&H(e,'there is a previously declared suffix for "'+o+'" tag handle'),cw.test(s)||H(e,"ill-formed tag prefix (second argument) of the TAG directive");try{s=decodeURIComponent(s)}catch{H(e,"tag prefix is malformed: "+s)}e.tagMap[o]=s}};OA=PA,CA=RA,mw={loadAll:OA,load:CA},hw=Object.prototype.toString,gw=Object.prototype.hasOwnProperty,Hd=65279,IA=9,Ti=10,AA=13,NA=32,zA=33,jA=34,jd=35,MA=37,LA=38,DA=39,qA=42,yw=44,ZA=45,Oc=58,UA=61,FA=62,HA=63,BA=64,vw=91,_w=93,GA=96,bw=123,VA=124,ww=125,kt={};kt[0]="\\0";kt[7]="\\a";kt[8]="\\b";kt[9]="\\t";kt[10]="\\n";kt[11]="\\v";kt[12]="\\f";kt[13]="\\r";kt[27]="\\e";kt[34]='\\"';kt[92]="\\\\";kt[133]="\\N";kt[160]="\\_";kt[8232]="\\L";kt[8233]="\\P";WA=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],JA=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;XA=1,Pi=2;Sw=1,Ld=2,$w=3,kw=4,ps=5;dN=pN,fN={dump:dN};mN=gt,hN=qb,gN=Hb,yN=Jb,vN=Kb,_N=Zd,bN=mw.load,wN=mw.loadAll,xN=fN.dump,SN=Ot,$N={binary:tw,float:Wb,map:Fb,null:Bb,pairs:nw,set:ow,timestamp:Qb,bool:Gb,int:Vb,merge:ew,omap:rw,seq:Ub,str:Zb},kN=Bd("safeLoad","load"),EN=Bd("safeLoadAll","loadAll"),TN=Bd("safeDump","dump"),Xr={Type:mN,Schema:hN,FAILSAFE_SCHEMA:gN,JSON_SCHEMA:yN,CORE_SCHEMA:vN,DEFAULT_SCHEMA:_N,load:bN,loadAll:wN,dump:xN,YAMLException:SN,types:$N,safeLoad:kN,safeLoadAll:EN,safeDump:TN}});var Ow={};K(Ow,{protocol:()=>CN});import{readFileSync as Tw,writeFileSync as PN,existsSync as RN}from"node:fs";import{basename as ON}from"node:path";function Pw(t){if(console.log(C("Protocol")),console.log(S("Name",t.name)),t.version&&console.log(S("Version",t.version)),t.description&&console.log(S("Description",t.description)),t.roles?.length){console.log(C("Roles"));for(let e of t.roles)console.log(` ${y("bold",e.name)}${e.description?` \u2014 ${e.description}`:""}`),e.capabilities?.length&&console.log(` ${y("dim",e.capabilities.join(", "))}`)}if(t.phases?.length){console.log(C("Phases"));for(let e=0;e<t.phases.length;e++){let r=t.phases[e];console.log(` ${y("cyan",`${e+1}.`)} ${y("bold",r.name)}${r.description?` \u2014 ${r.description}`:""}`),r.resources?.length&&console.log(` Resources: ${y("dim",r.resources.join(", "))}`)}}if(t.resources?.length){console.log(C("Resources"));for(let e of t.resources)console.log(` \u2022 ${e}`)}if(t.rules?.length){console.log(C("Rules"));for(let e of t.rules)console.log(` \u2022 ${e}`)}console.log()}async function Rw(t){try{return await lo(t)}catch{}try{return JSON.parse(t)}catch{}try{return Xr.load(t)}catch{}return null}async function CN(t=[]){let e=t[0];if(e==="validate"){await AN(t.slice(1));return}if(e==="load"){await NN(t.slice(1));return}if(e==="init"){await zN(t.slice(1));return}if(e==="--help"||e==="-h"){console.log(`
102
102
  ${y("bold","wgl protocol")} \u2014 protocol management
103
103
 
104
104
  ${y("cyan","USAGE:")}
@@ -113,32 +113,32 @@ ${y("cyan","TEMPLATES:")}
113
113
  code-review Code review workflow (author + reviewer)
114
114
  multi-agent Multi-agent coordination (lead + workers)
115
115
  pipeline Sequential pipeline (stages + handoffs)
116
- `);return}if(e==="show"||!e){await pN();return}console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl protocol --help` for usage"),process.exit(2)}async function pN(){let t=be();t||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);try{let r=await e.getProtocol();r.ok||(console.log(b(`Server returned ${r.status}`)),process.exit(1));let n=r.data;if(!n.name){console.log(` ${y("dim","No protocol loaded on server")}`);return}_w(n)}catch{console.log(b("Cannot reach server")),process.exit(1)}}async function dN(t){let e=t[0];e||(console.log(b("Usage: wgl protocol validate <file>")),process.exit(2));let r;try{r=vw(e,"utf8")}catch{console.log(b(`Cannot read file: ${e}`)),process.exit(1);return}let n=await bw(r);if(!n){console.log(b("Cannot parse protocol file (not valid JSON or YAML)")),process.exit(1);return}let o=n;if(!o.name){console.log(b('Protocol missing required "name" field')),process.exit(1);return}console.log(z(`Valid protocol: ${o.name}`)),_w(o)}async function fN(t){let e=t[0];e||(console.log(b("Usage: wgl protocol load <file>")),process.exit(2));let r=be();r||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n;try{n=vw(e,"utf8")}catch{console.log(b(`Cannot read file: ${e}`)),process.exit(1);return}let o=await bw(n);if(!o){console.log(b("Cannot parse protocol file")),process.exit(1);return}let s=Q(r);try{let i=await s.loadProtocol(o);i.ok||(console.log(b(`Server returned ${i.status}`)),process.exit(1)),console.log(z(`Loaded protocol: ${o.name||"unknown"}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}}async function mN(t){let e=t.indexOf("--template"),r=t.indexOf("--name"),n=e!==-1?t[e+1]:"basic",o=r!==-1?t[r+1]:void 0,s=yw[n];if(!s){console.log(b(`Unknown template: ${n}`)),console.log(y("dim",` Available: ${Object.keys(yw).join(", ")}`)),process.exit(2);return}let i={...s};o&&(i.name=o);let c=`${lN(i.name).replace(/[/\\]/g,"_")}.acp.json`;if(cN(c)){console.log(b(`File already exists: ${c}`)),process.exit(1);return}aN(c,JSON.stringify(i,null,2)+`
117
- `),console.log(z(`Created protocol: ${c}`)),console.log(y("dim",` Template: ${n}`)),console.log(y("dim",` Load it: wgl protocol load ${c}`)),console.log()}var yw,xw=w(()=>{"use strict";dt();Xe();Re();wi();Ti();yw={basic:{name:"my-protocol",version:"1.0.0",description:"A basic coordination protocol",roles:[{name:"developer",description:"Implements features and fixes",capabilities:["code","test"]}],phases:[{name:"planning",description:"Define scope and approach"},{name:"implementation",description:"Build the solution"},{name:"review",description:"Review and iterate"}],resources:[],rules:["Claim files before editing","Publish discoveries for team visibility"]},"code-review":{name:"code-review",version:"1.0.0",description:"Code review workflow with author and reviewer roles",roles:[{name:"author",description:"Writes and submits code",capabilities:["code","test"]},{name:"reviewer",description:"Reviews code and provides feedback",capabilities:["review","approve"]}],phases:[{name:"development",description:"Author implements changes",roles:["author"]},{name:"review",description:"Reviewer examines changes",roles:["reviewer"]},{name:"revision",description:"Author addresses feedback",roles:["author"]},{name:"approval",description:"Reviewer approves final version",roles:["reviewer"]}],resources:[],rules:["Author must claim files before editing","Reviewer must not modify code directly","All feedback via messages, not direct edits","Author addresses all review comments before re-requesting review"]},"multi-agent":{name:"multi-agent",version:"1.0.0",description:"Multi-agent coordination with a lead and workers",roles:[{name:"lead",description:"Coordinates work and resolves conflicts",capabilities:["plan","assign","review"]},{name:"worker",description:"Implements assigned tasks",capabilities:["code","test"]}],phases:[{name:"planning",description:"Lead breaks down work into tasks",roles:["lead"]},{name:"assignment",description:"Lead assigns tasks to workers",roles:["lead"]},{name:"execution",description:"Workers implement in parallel",roles:["worker"]},{name:"integration",description:"Lead reviews and integrates",roles:["lead"]}],resources:[],rules:["Workers must claim resources before working","Workers must not modify files claimed by others","Workers request help from lead if blocked","Lead resolves all conflicts and blockers"]},pipeline:{name:"pipeline",version:"1.0.0",description:"Sequential pipeline with stages and handoffs",roles:[{name:"stage-1",description:"First stage processor",capabilities:["process"]},{name:"stage-2",description:"Second stage processor",capabilities:["process"]},{name:"stage-3",description:"Third stage processor",capabilities:["process"]}],phases:[{name:"stage-1",description:"First stage processing",roles:["stage-1"]},{name:"stage-2",description:"Second stage processing",roles:["stage-2"]},{name:"stage-3",description:"Third stage processing",roles:["stage-3"]}],resources:[],rules:["Each stage must complete before the next begins","Stages communicate via shared state",'Set state "stage" to current stage name on entry',"Publish event on stage completion"]}}});var Sw={};X(Sw,{team:()=>hN});async function hN(){let t=be();t||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);try{let r=await e.getRoles();r.ok||(console.log(b(`Server returned ${r.status}`)),process.exit(1));let n=r.data;if(console.log(C("Team")),n.length===0)console.log(` ${y("dim","No agents connected")}`);else for(let o of n){let s=o.agent===t.agentId?y("green"," (you)"):"";console.log(` ${y("bold",o.role.padEnd(15))} ${o.agent}${s}`)}}catch{console.log(b("Cannot reach server")),process.exit(1)}console.log()}var $w=w(()=>{"use strict";dt();Xe();Re()});var kw={};X(kw,{claim:()=>gN});async function gN(t){let e=be();e||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t[0];r||(console.log(b("Usage: wgl claim <resource>")),process.exit(1));let n=Q(e);try{let o=await n.claim(r);o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1));let s=o.data;s.status==="approved"?console.log(z(`Claimed: ${r}`)):(console.log(b(`Rejected: ${r} \u2014 already claimed by ${s.claim?.owner||"another agent"}`)),process.exit(1))}catch{console.log(b("Cannot reach server")),process.exit(1)}}var Ew=w(()=>{"use strict";dt();Xe();Re()});var Tw={};X(Tw,{release:()=>yN});async function yN(t){let e=be();e||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t[0];r||(console.log(b("Usage: wgl release <resource>")),process.exit(1));let n=Q(e);try{let o=await n.releaseClaim(r);o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1)),console.log(z(`Released: ${r}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}}var Pw=w(()=>{"use strict";dt();Xe();Re()});var Rw={};X(Rw,{halt:()=>vN});async function vN(t){let e=be();e||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t.join(" ")||void 0,n=Q(e);try{let o=await n.halt(r);o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1)),console.log(z(`Halted${r?`: ${r}`:""}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}}var Ow=w(()=>{"use strict";dt();Xe();Re()});var Dd={};X(Dd,{pause:()=>_N,resume:()=>bN});async function _N(t){let e=be();e||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t.join(" ")||void 0,n=Q(e);try{let o=await n.pause(r);o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1)),console.log(z(`Paused${r?`: ${r}`:""}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}}async function bN(){let t=be();t||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);try{let r=await e.resume();r.ok||(console.log(b(`Server returned ${r.status}`)),process.exit(1)),console.log(z("Resumed"))}catch{console.log(b("Cannot reach server")),process.exit(1)}}var qd=w(()=>{"use strict";dt();Xe();Re()});var Iw={};X(Iw,{events:()=>wN});function Cw(t){let e=new Date(t.publishedAt).toLocaleTimeString();return` ${y("dim",`#${t.id}`)} ${y("bold",t.type)} by ${t.publishedBy} ${y("dim",e)}`}async function wN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
116
+ `);return}if(e==="show"||!e){await IN();return}console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl protocol --help` for usage"),process.exit(2)}async function IN(){let t=be();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);try{let r=await e.getProtocol();r.ok||(console.log(_(`Server returned ${r.status}`)),process.exit(1));let n=r.data;if(!n.name){console.log(` ${y("dim","No protocol loaded on server")}`);return}Pw(n)}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function AN(t){let e=t[0];e||(console.log(_("Usage: wgl protocol validate <file>")),process.exit(2));let r;try{r=Tw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let n=await Rw(r);if(!n){console.log(_("Cannot parse protocol file (not valid JSON or YAML)")),process.exit(1);return}let o=n;if(!o.name){console.log(_('Protocol missing required "name" field')),process.exit(1);return}console.log(N(`Valid protocol: ${o.name}`)),Pw(o)}async function NN(t){let e=t[0];e||(console.log(_("Usage: wgl protocol load <file>")),process.exit(2));let r=be();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n;try{n=Tw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let o=await Rw(n);if(!o){console.log(_("Cannot parse protocol file")),process.exit(1);return}let s=Q(r);try{let i=await s.loadProtocol(o);i.ok||(console.log(_(`Server returned ${i.status}`)),process.exit(1)),console.log(N(`Loaded protocol: ${o.name||"unknown"}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function zN(t){let e=t.indexOf("--template"),r=t.indexOf("--name"),n=e!==-1?t[e+1]:"basic",o=r!==-1?t[r+1]:void 0,s=Ew[n];if(!s){console.log(_(`Unknown template: ${n}`)),console.log(y("dim",` Available: ${Object.keys(Ew).join(", ")}`)),process.exit(2);return}let i={...s};o&&(i.name=o);let c=`${ON(i.name).replace(/[/\\]/g,"_")}.acp.json`;if(RN(c)){console.log(_(`File already exists: ${c}`)),process.exit(1);return}PN(c,JSON.stringify(i,null,2)+`
117
+ `),console.log(N(`Created protocol: ${c}`)),console.log(y("dim",` Template: ${n}`)),console.log(y("dim",` Load it: wgl protocol load ${c}`)),console.log()}var Ew,Cw=w(()=>{"use strict";dt();Qe();Re();$i();Oi();Ew={basic:{name:"my-protocol",version:"1.0.0",description:"A basic coordination protocol",roles:[{name:"developer",description:"Implements features and fixes",capabilities:["code","test"]}],phases:[{name:"planning",description:"Define scope and approach"},{name:"implementation",description:"Build the solution"},{name:"review",description:"Review and iterate"}],resources:[],rules:["Claim files before editing","Publish discoveries for team visibility"]},"code-review":{name:"code-review",version:"1.0.0",description:"Code review workflow with author and reviewer roles",roles:[{name:"author",description:"Writes and submits code",capabilities:["code","test"]},{name:"reviewer",description:"Reviews code and provides feedback",capabilities:["review","approve"]}],phases:[{name:"development",description:"Author implements changes",roles:["author"]},{name:"review",description:"Reviewer examines changes",roles:["reviewer"]},{name:"revision",description:"Author addresses feedback",roles:["author"]},{name:"approval",description:"Reviewer approves final version",roles:["reviewer"]}],resources:[],rules:["Author must claim files before editing","Reviewer must not modify code directly","All feedback via messages, not direct edits","Author addresses all review comments before re-requesting review"]},"multi-agent":{name:"multi-agent",version:"1.0.0",description:"Multi-agent coordination with a lead and workers",roles:[{name:"lead",description:"Coordinates work and resolves conflicts",capabilities:["plan","assign","review"]},{name:"worker",description:"Implements assigned tasks",capabilities:["code","test"]}],phases:[{name:"planning",description:"Lead breaks down work into tasks",roles:["lead"]},{name:"assignment",description:"Lead assigns tasks to workers",roles:["lead"]},{name:"execution",description:"Workers implement in parallel",roles:["worker"]},{name:"integration",description:"Lead reviews and integrates",roles:["lead"]}],resources:[],rules:["Workers must claim resources before working","Workers must not modify files claimed by others","Workers request help from lead if blocked","Lead resolves all conflicts and blockers"]},pipeline:{name:"pipeline",version:"1.0.0",description:"Sequential pipeline with stages and handoffs",roles:[{name:"stage-1",description:"First stage processor",capabilities:["process"]},{name:"stage-2",description:"Second stage processor",capabilities:["process"]},{name:"stage-3",description:"Third stage processor",capabilities:["process"]}],phases:[{name:"stage-1",description:"First stage processing",roles:["stage-1"]},{name:"stage-2",description:"Second stage processing",roles:["stage-2"]},{name:"stage-3",description:"Third stage processing",roles:["stage-3"]}],resources:[],rules:["Each stage must complete before the next begins","Stages communicate via shared state",'Set state "stage" to current stage name on entry',"Publish event on stage completion"]}}});var Iw={};K(Iw,{team:()=>jN});async function jN(){let t=be();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);try{let r=await e.getRoles();r.ok||(console.log(_(`Server returned ${r.status}`)),process.exit(1));let n=r.data;if(console.log(C("Team")),n.length===0)console.log(` ${y("dim","No agents connected")}`);else for(let o of n){let s=o.agent===t.agentId?y("green"," (you)"):"";console.log(` ${y("bold",o.role.padEnd(15))} ${o.agent}${s}`)}}catch{console.log(_("Cannot reach server")),process.exit(1)}console.log()}var Aw=w(()=>{"use strict";dt();Qe();Re()});var Nw={};K(Nw,{claim:()=>MN});async function MN(t){let e=be();e||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t[0];r||(console.log(_("Usage: wgl claim <resource>")),process.exit(1));let n=Q(e);try{let o=await n.claim(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1));let s=o.data;s.status==="approved"?console.log(N(`Claimed: ${r}`)):(console.log(_(`Rejected: ${r} \u2014 already claimed by ${s.claim?.owner||"another agent"}`)),process.exit(1))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var zw=w(()=>{"use strict";dt();Qe();Re()});var jw={};K(jw,{release:()=>LN});async function LN(t){let e=be();e||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t[0];r||(console.log(_("Usage: wgl release <resource>")),process.exit(1));let n=Q(e);try{let o=await n.releaseClaim(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1)),console.log(N(`Released: ${r}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var Mw=w(()=>{"use strict";dt();Qe();Re()});var Lw={};K(Lw,{halt:()=>DN});async function DN(t){let e=be();e||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t.join(" ")||void 0,n=Q(e);try{let o=await n.halt(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1)),console.log(N(`Halted${r?`: ${r}`:""}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var Dw=w(()=>{"use strict";dt();Qe();Re()});var Gd={};K(Gd,{pause:()=>qN,resume:()=>ZN});async function qN(t){let e=be();e||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let r=t.join(" ")||void 0,n=Q(e);try{let o=await n.pause(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1)),console.log(N(`Paused${r?`: ${r}`:""}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function ZN(){let t=be();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=Q(t);try{let r=await e.resume();r.ok||(console.log(_(`Server returned ${r.status}`)),process.exit(1)),console.log(N("Resumed"))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var Vd=w(()=>{"use strict";dt();Qe();Re()});var Zw={};K(Zw,{events:()=>UN});function qw(t){let e=new Date(t.publishedAt).toLocaleTimeString();return` ${y("dim",`#${t.id}`)} ${y("bold",t.type)} by ${t.publishedBy} ${y("dim",e)}`}async function UN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
118
118
  ${y("bold","wgl events")} \u2014 event management
119
119
 
120
120
  ${y("cyan","USAGE:")}
121
121
  wgl events list [--since N] [--type T] List events
122
122
  wgl events tail Live-stream events (polling)
123
123
  wgl events publish <type> [json-data] Publish an event
124
- `);return}let r=be();r||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"list":{let o=t.indexOf("--since"),s=o!==-1?parseInt(t[o+1],10):void 0,i=t.indexOf("--type"),a=i!==-1?t[i+1]:void 0;try{let c=await n.getEvents(s);c.ok||(console.log(b(`Server returned ${c.status}`)),process.exit(1));let l=c.data;if(a&&(l=l.filter(u=>u.type.includes(a))),l.length===0){console.log(` ${y("dim","No events")}`);return}console.log(C("Events"));for(let u of l)console.log(Cw(u));console.log()}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"tail":{let o=r.lastEventCursor||0;console.log(y("dim",`Tailing events (since #${o})... Ctrl+C to stop
125
- `));let s=async()=>{try{let a=await n.getEvents(o);if(a.ok){let c=a.data;for(let l of c)console.log(Cw(l)),l.id>o&&(o=l.id)}}catch{}};await s();let i=setInterval(s,2e3);process.on("SIGINT",()=>{clearInterval(i),console.log(y("dim",`
126
- Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{});break}case"publish":{let o=t[1];o||(console.log(b("Usage: wgl events publish <type> [json-data]")),process.exit(2));let s={},i=t.slice(2).join(" ");if(i)try{s=JSON.parse(i)}catch{console.log(b("Invalid JSON data")),process.exit(2)}try{let a=await n.publishEvent(o,s);a.ok||(console.log(b(`Server returned ${a.status}`)),process.exit(1));let c=a.data;console.log(z(`Published event #${c.id} (${o})`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl events --help` for usage"),process.exit(2)}}var Aw=w(()=>{"use strict";dt();Xe();Re()});var Nw={};X(Nw,{state:()=>xN});async function xN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
124
+ `);return}let r=be();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"list":{let o=t.indexOf("--since"),s=o!==-1?parseInt(t[o+1],10):void 0,i=t.indexOf("--type"),a=i!==-1?t[i+1]:void 0;try{let c=await n.getEvents(s);c.ok||(console.log(_(`Server returned ${c.status}`)),process.exit(1));let l=c.data;if(a&&(l=l.filter(u=>u.type.includes(a))),l.length===0){console.log(` ${y("dim","No events")}`);return}console.log(C("Events"));for(let u of l)console.log(qw(u));console.log()}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"tail":{let o=r.lastEventCursor||0;console.log(y("dim",`Tailing events (since #${o})... Ctrl+C to stop
125
+ `));let s=async()=>{try{let a=await n.getEvents(o);if(a.ok){let c=a.data;for(let l of c)console.log(qw(l)),l.id>o&&(o=l.id)}}catch{}};await s();let i=setInterval(s,2e3);process.on("SIGINT",()=>{clearInterval(i),console.log(y("dim",`
126
+ Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{});break}case"publish":{let o=t[1];o||(console.log(_("Usage: wgl events publish <type> [json-data]")),process.exit(2));let s={},i=t.slice(2).join(" ");if(i)try{s=JSON.parse(i)}catch{console.log(_("Invalid JSON data")),process.exit(2)}try{let a=await n.publishEvent(o,s);a.ok||(console.log(_(`Server returned ${a.status}`)),process.exit(1));let c=a.data;console.log(N(`Published event #${c.id} (${o})`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl events --help` for usage"),process.exit(2)}}var Uw=w(()=>{"use strict";dt();Qe();Re()});var Fw={};K(Fw,{state:()=>FN});async function FN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
127
127
  ${y("bold","wgl state")} \u2014 shared state management
128
128
 
129
129
  ${y("cyan","USAGE:")}
130
130
  wgl state get [key] Get all state or a specific key
131
131
  wgl state set <key> <value> Set a state value
132
132
  wgl state delete <key> Delete a state key
133
- `);return}let r=be();r||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"get":{let o=t[1];try{let s=await n.getState();s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1));let i=s.data;if(o)if(o in i){let a=i[o];console.log(typeof a=="string"?a:JSON.stringify(a,null,2))}else console.log(b(`Key not found: ${o}`)),process.exit(1);else{let a=Object.keys(i);if(a.length===0){console.log(` ${y("dim","No state entries")}`);return}console.log(C("State"));for(let c of a){let l=i[c],u=typeof l=="string"?l:JSON.stringify(l);console.log(S(c,u))}console.log()}}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"set":{let o=t[1],s=t.slice(2).join(" ");(!o||!s)&&(console.log(b("Usage: wgl state set <key> <value>")),process.exit(2));let i=s;try{i=JSON.parse(s)}catch{}try{let a=await n.setState(o,i);a.ok||(console.log(b(`Server returned ${a.status}`)),process.exit(1)),console.log(z(`Set ${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"delete":{let o=t[1];o||(console.log(b("Usage: wgl state delete <key>")),process.exit(2));try{let s=await n.deleteState(o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1)),console.log(z(`Deleted ${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl state --help` for usage"),process.exit(2)}}var zw=w(()=>{"use strict";dt();Xe();Re()});var jw={};X(jw,{msg:()=>$N});function SN(t,e){let r=new Date(t.sentAt).toLocaleTimeString(),n=t.from===e?y("green",t.from+" (you)"):y("bold",t.from),o=t.to==="*"?y("yellow","broadcast"):t.to===e?y("green","you"):t.to;return` ${y("dim",`#${t.id}`)} ${n} ${y("dim","->")} ${o}: ${t.content} ${y("dim",r)}`}async function $N(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
133
+ `);return}let r=be();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"get":{let o=t[1];try{let s=await n.getState();s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1));let i=s.data;if(o)if(o in i){let a=i[o];console.log(typeof a=="string"?a:JSON.stringify(a,null,2))}else console.log(_(`Key not found: ${o}`)),process.exit(1);else{let a=Object.keys(i);if(a.length===0){console.log(` ${y("dim","No state entries")}`);return}console.log(C("State"));for(let c of a){let l=i[c],u=typeof l=="string"?l:JSON.stringify(l);console.log(S(c,u))}console.log()}}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"set":{let o=t[1],s=t.slice(2).join(" ");(!o||!s)&&(console.log(_("Usage: wgl state set <key> <value>")),process.exit(2));let i=s;try{i=JSON.parse(s)}catch{}try{let a=await n.setState(o,i);a.ok||(console.log(_(`Server returned ${a.status}`)),process.exit(1)),console.log(N(`Set ${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"delete":{let o=t[1];o||(console.log(_("Usage: wgl state delete <key>")),process.exit(2));try{let s=await n.deleteState(o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1)),console.log(N(`Deleted ${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl state --help` for usage"),process.exit(2)}}var Hw=w(()=>{"use strict";dt();Qe();Re()});var Bw={};K(Bw,{msg:()=>BN});function HN(t,e){let r=new Date(t.sentAt).toLocaleTimeString(),n=t.from===e?y("green",t.from+" (you)"):y("bold",t.from),o=t.to==="*"?y("yellow","broadcast"):t.to===e?y("green","you"):t.to;return` ${y("dim",`#${t.id}`)} ${n} ${y("dim","->")} ${o}: ${t.content} ${y("dim",r)}`}async function BN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
134
134
  ${y("bold","wgl msg")} \u2014 agent messaging
135
135
 
136
136
  ${y("cyan","USAGE:")}
137
137
  wgl msg send <to> <content> Send a message to an agent
138
138
  wgl msg list List messages for this agent
139
139
  wgl msg broadcast <content> Send to all agents
140
- `);return}let r=be();r||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"send":{let o=t[1],s=t.slice(2).join(" ");(!o||!s)&&(console.log(b("Usage: wgl msg send <to> <content>")),process.exit(2));try{let i=await n.sendMessage(o,s);i.ok||(console.log(b(`Server returned ${i.status}`)),process.exit(1));let a=i.data;console.log(z(`Message #${a.id} sent to ${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"list":{try{let o=await n.getMessages();o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1));let i=o.data.filter(a=>a.to===r.agentId||a.to==="*"||a.from===r.agentId);if(i.length===0){console.log(` ${y("dim","No messages")}`);return}console.log(C("Messages"));for(let a of i)console.log(SN(a,r.agentId));console.log()}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"broadcast":{let o=t.slice(1).join(" ");o||(console.log(b("Usage: wgl msg broadcast <content>")),process.exit(2));try{let s=await n.sendMessage("*",o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1));let i=s.data;console.log(z(`Broadcast #${i.id} sent`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl msg --help` for usage"),process.exit(2)}}var Mw=w(()=>{"use strict";dt();Xe();Re()});var Lw={};X(Lw,{helpCmd:()=>TN});function EN(t,e){let r=kN[t.urgency||"normal"],n=t.status==="open"?y("yellow","open"):t.status==="claimed"?y("cyan",`claimed by ${t.claimedBy}`):y("green","resolved"),o=t.from===e?y("green"," (you)"):"";return` ${y("dim",`#${t.id}`)} ${y(r,`[${t.urgency||"normal"}]`)} ${t.problem}${o}
141
- ${n} \u2014 ${t.from} ${y("dim",new Date(t.createdAt).toLocaleTimeString())}`}async function TN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
140
+ `);return}let r=be();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"send":{let o=t[1],s=t.slice(2).join(" ");(!o||!s)&&(console.log(_("Usage: wgl msg send <to> <content>")),process.exit(2));try{let i=await n.sendMessage(o,s);i.ok||(console.log(_(`Server returned ${i.status}`)),process.exit(1));let a=i.data;console.log(N(`Message #${a.id} sent to ${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"list":{try{let o=await n.getMessages();o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1));let i=o.data.filter(a=>a.to===r.agentId||a.to==="*"||a.from===r.agentId);if(i.length===0){console.log(` ${y("dim","No messages")}`);return}console.log(C("Messages"));for(let a of i)console.log(HN(a,r.agentId));console.log()}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"broadcast":{let o=t.slice(1).join(" ");o||(console.log(_("Usage: wgl msg broadcast <content>")),process.exit(2));try{let s=await n.sendMessage("*",o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1));let i=s.data;console.log(N(`Broadcast #${i.id} sent`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl msg --help` for usage"),process.exit(2)}}var Gw=w(()=>{"use strict";dt();Qe();Re()});var Vw={};K(Vw,{helpCmd:()=>WN});function VN(t,e){let r=GN[t.urgency||"normal"],n=t.status==="open"?y("yellow","open"):t.status==="claimed"?y("cyan",`claimed by ${t.claimedBy}`):y("green","resolved"),o=t.from===e?y("green"," (you)"):"";return` ${y("dim",`#${t.id}`)} ${y(r,`[${t.urgency||"normal"}]`)} ${t.problem}${o}
141
+ ${n} \u2014 ${t.from} ${y("dim",new Date(t.createdAt).toLocaleTimeString())}`}async function WN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
142
142
  ${y("bold","wgl help")} \u2014 help request management
143
143
 
144
144
  ${y("cyan","USAGE:")}
@@ -146,26 +146,26 @@ ${y("cyan","USAGE:")}
146
146
  wgl help list Show open help requests
147
147
  wgl help claim <id> Claim a help request
148
148
  wgl help resolve <id> Resolve a help request
149
- `);return}let r=be();r||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"ask":{let o=t.slice(1).join(" ");o||(console.log(b("Usage: wgl help ask <problem>")),process.exit(2));try{let s=await n.requestHelp(o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1));let i=s.data;console.log(z(`Help request #${i.id} created`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"list":{try{let o=await n.getHelp();o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1));let s=o.data;if(s.length===0){console.log(` ${y("dim","No help requests")}`);return}console.log(C("Help Requests"));for(let i of s)console.log(EN(i,r.agentId));console.log()}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"claim":{let o=parseInt(t[1],10);isNaN(o)&&(console.log(b("Usage: wgl help claim <id>")),process.exit(2));try{let s=await n.claimHelp(o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1)),console.log(z(`Claimed help request #${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"resolve":{let o=parseInt(t[1],10);isNaN(o)&&(console.log(b("Usage: wgl help resolve <id>")),process.exit(2));try{let s=await n.resolveHelp(o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1)),console.log(z(`Resolved help request #${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl help --help` for usage"),process.exit(2)}}var kN,Dw=w(()=>{"use strict";dt();Xe();Re();kN={low:"dim",normal:"cyan",high:"red"}});var qw={};X(qw,{namespace:()=>PN});async function PN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
149
+ `);return}let r=be();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"ask":{let o=t.slice(1).join(" ");o||(console.log(_("Usage: wgl help ask <problem>")),process.exit(2));try{let s=await n.requestHelp(o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1));let i=s.data;console.log(N(`Help request #${i.id} created`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"list":{try{let o=await n.getHelp();o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1));let s=o.data;if(s.length===0){console.log(` ${y("dim","No help requests")}`);return}console.log(C("Help Requests"));for(let i of s)console.log(VN(i,r.agentId));console.log()}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"claim":{let o=parseInt(t[1],10);isNaN(o)&&(console.log(_("Usage: wgl help claim <id>")),process.exit(2));try{let s=await n.claimHelp(o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1)),console.log(N(`Claimed help request #${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"resolve":{let o=parseInt(t[1],10);isNaN(o)&&(console.log(_("Usage: wgl help resolve <id>")),process.exit(2));try{let s=await n.resolveHelp(o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1)),console.log(N(`Resolved help request #${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl help --help` for usage"),process.exit(2)}}var GN,Ww=w(()=>{"use strict";dt();Qe();Re();GN={low:"dim",normal:"cyan",high:"red"}});var Jw={};K(Jw,{namespace:()=>JN});async function JN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
150
150
  ${y("bold","wgl namespace")} \u2014 namespace management
151
151
 
152
152
  ${y("cyan","USAGE:")}
153
153
  wgl namespace list List namespaces on server
154
154
  wgl namespace create <name> Create a namespace
155
155
  wgl namespace delete <name> Delete a namespace
156
- `);return}let r=be();r||(console.log(b("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"list":{try{let o=await n.getNamespaces();o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1));let s=o.data;if(s.length===0){console.log(` ${y("dim","No namespaces")}`);return}console.log(C("Namespaces"));for(let i of s){let a=i===r.namespace?y("green"," (active)"):"";console.log(` ${y("bold",i)}${a}`)}console.log()}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"create":{let o=t[1];o||(console.log(b("Usage: wgl namespace create <name>")),process.exit(2));try{let s=await n.createNamespace(o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1)),console.log(z(`Created namespace: ${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}case"delete":{let o=t[1];o||(console.log(b("Usage: wgl namespace delete <name>")),process.exit(2));try{let s=await n.deleteNamespace(o);s.ok||(console.log(b(`Server returned ${s.status}`)),process.exit(1)),console.log(z(`Deleted namespace: ${o}`))}catch{console.log(b("Cannot reach server")),process.exit(1)}break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl namespace --help` for usage"),process.exit(2)}}var Zw=w(()=>{"use strict";dt();Xe();Re()});var Uw={};X(Uw,{hooksCmd:()=>IN});import{readFileSync as RN,existsSync as ON}from"node:fs";import{join as CN}from"node:path";async function IN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
156
+ `);return}let r=be();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=Q(r);switch(e){case"list":{try{let o=await n.getNamespaces();o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1));let s=o.data;if(s.length===0){console.log(` ${y("dim","No namespaces")}`);return}console.log(C("Namespaces"));for(let i of s){let a=i===r.namespace?y("green"," (active)"):"";console.log(` ${y("bold",i)}${a}`)}console.log()}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"create":{let o=t[1];o||(console.log(_("Usage: wgl namespace create <name>")),process.exit(2));try{let s=await n.createNamespace(o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1)),console.log(N(`Created namespace: ${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"delete":{let o=t[1];o||(console.log(_("Usage: wgl namespace delete <name>")),process.exit(2));try{let s=await n.deleteNamespace(o);s.ok||(console.log(_(`Server returned ${s.status}`)),process.exit(1)),console.log(N(`Deleted namespace: ${o}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl namespace --help` for usage"),process.exit(2)}}var Kw=w(()=>{"use strict";dt();Qe();Re()});var Yw={};K(Yw,{hooksCmd:()=>QN});import{readFileSync as KN,existsSync as YN}from"node:fs";import{join as XN}from"node:path";async function QN(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
157
157
  ${y("bold","wgl hooks")} \u2014 Claude Code hook management
158
158
 
159
159
  ${y("cyan","USAGE:")}
160
160
  wgl hooks install Install hooks to settings.local.json
161
161
  wgl hooks uninstall Remove hooks
162
162
  wgl hooks list Show installed hooks
163
- `);return}switch(e){case"install":{let n=be()?.hookTimeout||10;try{cs(n),console.log(z("Hooks installed"))}catch(o){console.log(b(`Failed to install hooks: ${o.message}`)),process.exit(1)}break}case"uninstall":{try{vc(),console.log(z("Hooks uninstalled"))}catch(r){console.log(b(`Failed to uninstall hooks: ${r.message}`)),process.exit(1)}break}case"list":{let r=CN(process.cwd(),".claude","settings.local.json");if(!ON(r)){console.log(` ${y("dim","No hooks installed (no settings.local.json)")}`);return}let n;try{n=JSON.parse(RN(r,"utf8"))}catch{console.log(b("Failed to read settings.local.json")),process.exit(1);return}if(!n.hooks||Object.keys(n.hooks).length===0){console.log(` ${y("dim","No hooks configured")}`);return}console.log(C("Installed Hooks"));for(let[o,s]of Object.entries(n.hooks))for(let i of s){let c=yc(i.command)?y("green"," [wgl]"):"";console.log(` ${y("bold",o)}${i.matcher?y("dim",` (${i.matcher})`):""}${c}`),console.log(` ${y("dim",i.command)}`),i.timeout&&console.log(` ${y("dim",`timeout: ${i.timeout}s`)}`)}console.log();break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl hooks --help` for usage"),process.exit(2)}}var Fw=w(()=>{"use strict";dt();yi();Re()});import{readFileSync as AN,existsSync as Hw}from"node:fs";import{join as NN,resolve as zN}from"node:path";function Vw(t){if(typeof t=="string")return{conditions:[{event:t,count:1}],timeout:Bw};let e=typeof t.timeout=="number"?t.timeout:Bw;if(t.all)return{conditions:t.all.map(n=>typeof n=="string"?{event:n,count:1}:{event:n.event,count:n.count??1}),timeout:e};if(t.event)return{conditions:[{event:t.event,count:t.count??1}],timeout:e};throw new Error("startOn must be a string, { event, count? }, or { all: [...] }")}function Gw(t){if(t){let e=zN(t);return Hw(e)?e:null}for(let e of jN){let r=NN(process.cwd(),e);if(Hw(r))return r}return null}async function Ww(t){let e=AN(t,"utf8"),r=t.endsWith(".json")?JSON.parse(e):MN(e);return LN(r)}function MN(t){return Xr.load(t)}function LN(t){if(!t||typeof t!="object")throw new Error("brood file must be a YAML/JSON object");let e=t;if(typeof e.name!="string"||!e.name)throw new Error('brood file requires a "name" field');if(!e.hives||typeof e.hives!="object")throw new Error('brood file requires a "hives" map');let r={},n=e.hives;for(let[u,p]of Object.entries(n)){if(!p||typeof p!="object")throw new Error(`hive "${u}" must be an object`);let m=p,d={};if(m.worktree!==void 0){if(typeof m.worktree!="string")throw new Error(`hive "${u}".worktree must be a string`);d.worktree=m.worktree}let f=m.acp??m.spec??m.protocol;if(f!==void 0)if(typeof f=="string")d.acp=f;else if(typeof f=="object"&&f!==null&&!Array.isArray(f))d.acp=f;else throw new Error(`hive "${u}".acp must be a string (file/URL) or inline spec object`);if(m.port!==void 0){if(typeof m.port!="number")throw new Error(`hive "${u}".port must be a number`);d.port=m.port}let h=m.workers??m.agents;if(h!==void 0){if(!Array.isArray(h))throw new Error(`hive "${u}".agents must be an array`);d.agents=h.map((_,x)=>{if(!_||typeof _!="object")throw new Error(`hive "${u}".agents[${x}] must be an object`);let k=_;if(typeof k.role!="string")throw new Error(`hive "${u}".agents[${x}].role must be a string`);let I;if(k.tools!==void 0)if(k.tools==="all")I="all";else if(Array.isArray(k.tools)&&k.tools.every(U=>typeof U=="string"))I=k.tools;else throw new Error(`hive "${u}".agents[${x}].tools must be 'all' or an array of strings`);let de;if(k.coordination!==void 0)if(typeof k.coordination=="string"&&["lite","full","none"].includes(k.coordination))de=k.coordination;else if(Array.isArray(k.coordination)&&k.coordination.every(U=>typeof U=="string"))de=k.coordination;else throw new Error(`hive "${u}".agents[${x}].coordination must be 'lite', 'full', 'none', or an array of strings`);let Y;if(k.type!==void 0){if(k.type!=="worker"&&k.type!=="drone"&&k.type!=="claude")throw new Error(`hive "${u}".agents[${x}].type must be 'worker', 'drone', or 'claude'`);Y=k.type}let ee=k.startOn!==void 0?k.startOn:void 0,ge;if(k.wake_on!==void 0){if(!k.wake_on||typeof k.wake_on!="object")throw new Error(`hive "${u}".agents[${x}].wake_on must be an object`);let U=k.wake_on;ge={types:Array.isArray(U.types)?U.types.filter(ne=>typeof ne=="string"):void 0,timeout:typeof U.timeout=="number"?U.timeout:void 0,max_wakes:typeof U.max_wakes=="number"?U.max_wakes:void 0}}return{role:k.role,count:typeof k.count=="number"?k.count:void 0,type:Y,model_hint:typeof k.model_hint=="string"?k.model_hint:void 0,prompt:typeof k.prompt=="string"?k.prompt:void 0,pluginDir:typeof k.plugin_dir=="string"?k.plugin_dir:void 0,tools:I,coordination:de,startOn:ee,wake_on:ge}})}let g=m.honeycomb??m.comb;if(g!==void 0){if(!g||typeof g!="object")throw new Error(`hive "${u}".honeycomb must be an object`);let _=g;d.honeycomb={publishes:Array.isArray(_.publishes)?_.publishes.filter(x=>typeof x=="string"):void 0,subscribes:Array.isArray(_.subscribes)?_.subscribes.filter(x=>typeof x=="string"):void 0}}let v=m.dances??m.logic;if(v!==void 0){if(typeof v!="string")throw new Error(`hive "${u}".dances must be a string (file path)`);d.dances=v}r[u]=d}let o;if(e.provider!==void 0){if(typeof e.provider!="string")throw new Error('"provider" must be a string (e.g. "ollama/qwen3:8b")');o=e.provider}let s;if(e.models!==void 0){if(!e.models||typeof e.models!="object"||Array.isArray(e.models))throw new Error('"models" must be an object mapping role names to provider strings');s={};for(let[u,p]of Object.entries(e.models)){if(typeof p!="string")throw new Error(`models.${u} must be a string`);s[u]=p}}let i;if(e.env!==void 0){if(!e.env||typeof e.env!="object"||Array.isArray(e.env))throw new Error('"env" must be an object mapping variable names to string values');i={};for(let[u,p]of Object.entries(e.env))i[u]=String(p)}let a;if(e.stagger!==void 0){if(typeof e.stagger!="number"||e.stagger<0)throw new Error('"stagger" must be a non-negative number (seconds between agent spawns)');a=e.stagger}let c,l=e.dances??e.logic;if(l!==void 0){if(typeof l!="string")throw new Error('"dances" must be a string (file path)');c=l}return{name:e.name,version:typeof e.version=="string"?e.version:void 0,provider:o,models:s,env:i,stagger:a,dances:c,hives:r}}var Bw,jN,Jw=w(()=>{"use strict";Ti();Bw=0;jN=["brood.yaml","brood.yml","brood.json"]});import{createServer as DN}from"node:net";var Rc,Kw=w(()=>{"use strict";Rc=class{server=null;hives=new Map;socketMap=new Map;onHiveConnect;onHiveDisconnect;constructor(e){this.onHiveConnect=e?.onHiveConnect,this.onHiveDisconnect=e?.onHiveDisconnect}async listen(e){return new Promise((r,n)=>{let o=DN(s=>this.onConnection(s));o.on("error",n),o.listen(e,()=>{this.server=o,r()})})}async close(){for(let e of this.hives.values())e.socket.end();if(this.hives.clear(),this.socketMap.clear(),this.server)return new Promise(e=>{this.server.close(()=>e())})}getConnectedHives(){return[...this.hives.keys()]}onConnection(e){let r="";e.setEncoding("utf8"),e.on("data",n=>{r+=n;let o=r.split(`
163
+ `);return}switch(e){case"install":{let n=be()?.hookTimeout||10;try{us(n),console.log(N("Hooks installed"))}catch(o){console.log(_(`Failed to install hooks: ${o.message}`)),process.exit(1)}break}case"uninstall":{try{xc(),console.log(N("Hooks uninstalled"))}catch(r){console.log(_(`Failed to uninstall hooks: ${r.message}`)),process.exit(1)}break}case"list":{let r=XN(process.cwd(),".claude","settings.local.json");if(!YN(r)){console.log(` ${y("dim","No hooks installed (no settings.local.json)")}`);return}let n;try{n=JSON.parse(KN(r,"utf8"))}catch{console.log(_("Failed to read settings.local.json")),process.exit(1);return}if(!n.hooks||Object.keys(n.hooks).length===0){console.log(` ${y("dim","No hooks configured")}`);return}console.log(C("Installed Hooks"));for(let[o,s]of Object.entries(n.hooks))for(let i of s){let c=wc(i.command)?y("green"," [wgl]"):"";console.log(` ${y("bold",o)}${i.matcher?y("dim",` (${i.matcher})`):""}${c}`),console.log(` ${y("dim",i.command)}`),i.timeout&&console.log(` ${y("dim",`timeout: ${i.timeout}s`)}`)}console.log();break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl hooks --help` for usage"),process.exit(2)}}var Xw=w(()=>{"use strict";dt();bi();Re()});import{readFileSync as ez,existsSync as Qw}from"node:fs";import{join as tz,resolve as rz}from"node:path";function tx(t){if(typeof t=="string")return{conditions:[{event:t,count:1}],timeout:ex};let e=typeof t.timeout=="number"?t.timeout:ex;if(t.all)return{conditions:t.all.map(n=>typeof n=="string"?{event:n,count:1}:{event:n.event,count:n.count??1}),timeout:e};if(t.event)return{conditions:[{event:t.event,count:t.count??1}],timeout:e};throw new Error("startOn must be a string, { event, count? }, or { all: [...] }")}function rx(t){if(t){let e=rz(t);return Qw(e)?e:null}for(let e of nz){let r=tz(process.cwd(),e);if(Qw(r))return r}return null}async function nx(t){let e=ez(t,"utf8"),r=t.endsWith(".json")?JSON.parse(e):oz(e);return sz(r)}function oz(t){return Xr.load(t)}function sz(t){if(!t||typeof t!="object")throw new Error("brood file must be a YAML/JSON object");let e=t;if(typeof e.name!="string"||!e.name)throw new Error('brood file requires a "name" field');if(!e.hives||typeof e.hives!="object")throw new Error('brood file requires a "hives" map');let r={},n=e.hives;for(let[u,p]of Object.entries(n)){if(!p||typeof p!="object")throw new Error(`hive "${u}" must be an object`);let f=p,d={};if(f.worktree!==void 0){if(typeof f.worktree!="string")throw new Error(`hive "${u}".worktree must be a string`);d.worktree=f.worktree}let m=f.acp??f.spec??f.protocol;if(m!==void 0)if(typeof m=="string")d.acp=m;else if(typeof m=="object"&&m!==null&&!Array.isArray(m))d.acp=m;else throw new Error(`hive "${u}".acp must be a string (file/URL) or inline spec object`);if(f.port!==void 0){if(typeof f.port!="number")throw new Error(`hive "${u}".port must be a number`);d.port=f.port}let h=f.workers??f.agents;if(h!==void 0){if(!Array.isArray(h))throw new Error(`hive "${u}".agents must be an array`);d.agents=h.map((b,x)=>{if(!b||typeof b!="object")throw new Error(`hive "${u}".agents[${x}] must be an object`);let $=b;if(typeof $.role!="string")throw new Error(`hive "${u}".agents[${x}].role must be a string`);let O;if($.tools!==void 0)if($.tools==="all")O="all";else if(Array.isArray($.tools)&&$.tools.every(U=>typeof U=="string"))O=$.tools;else throw new Error(`hive "${u}".agents[${x}].tools must be 'all' or an array of strings`);let ce;if($.coordination!==void 0)if(typeof $.coordination=="string"&&["lite","full","none"].includes($.coordination))ce=$.coordination;else if(Array.isArray($.coordination)&&$.coordination.every(U=>typeof U=="string"))ce=$.coordination;else throw new Error(`hive "${u}".agents[${x}].coordination must be 'lite', 'full', 'none', or an array of strings`);let X;if($.type!==void 0){if($.type!=="worker"&&$.type!=="drone"&&$.type!=="claude")throw new Error(`hive "${u}".agents[${x}].type must be 'worker', 'drone', or 'claude'`);X=$.type}let ee=$.startOn!==void 0?$.startOn:void 0,ge;if($.wake_on!==void 0){if(!$.wake_on||typeof $.wake_on!="object")throw new Error(`hive "${u}".agents[${x}].wake_on must be an object`);let U=$.wake_on;ge={types:Array.isArray(U.types)?U.types.filter(ne=>typeof ne=="string"):void 0,timeout:typeof U.timeout=="number"?U.timeout:void 0,max_wakes:typeof U.max_wakes=="number"?U.max_wakes:void 0}}return{role:$.role,count:typeof $.count=="number"?$.count:void 0,type:X,model_hint:typeof $.model_hint=="string"?$.model_hint:void 0,prompt:typeof $.prompt=="string"?$.prompt:void 0,pluginDir:typeof $.plugin_dir=="string"?$.plugin_dir:void 0,tools:O,coordination:ce,startOn:ee,wake_on:ge}})}let g=f.honeycomb??f.comb;if(g!==void 0){if(!g||typeof g!="object")throw new Error(`hive "${u}".honeycomb must be an object`);let b=g;d.honeycomb={publishes:Array.isArray(b.publishes)?b.publishes.filter(x=>typeof x=="string"):void 0,subscribes:Array.isArray(b.subscribes)?b.subscribes.filter(x=>typeof x=="string"):void 0}}let v=f.dances??f.logic;if(v!==void 0){if(typeof v!="string")throw new Error(`hive "${u}".dances must be a string (file path)`);d.dances=v}r[u]=d}let o;if(e.provider!==void 0){if(typeof e.provider!="string")throw new Error('"provider" must be a string (e.g. "ollama/qwen3:8b")');o=e.provider}let s;if(e.models!==void 0){if(!e.models||typeof e.models!="object"||Array.isArray(e.models))throw new Error('"models" must be an object mapping role names to provider strings');s={};for(let[u,p]of Object.entries(e.models)){if(typeof p!="string")throw new Error(`models.${u} must be a string`);s[u]=p}}let i;if(e.env!==void 0){if(!e.env||typeof e.env!="object"||Array.isArray(e.env))throw new Error('"env" must be an object mapping variable names to string values');i={};for(let[u,p]of Object.entries(e.env))i[u]=String(p)}let a;if(e.stagger!==void 0){if(typeof e.stagger!="number"||e.stagger<0)throw new Error('"stagger" must be a non-negative number (seconds between agent spawns)');a=e.stagger}let c,l=e.dances??e.logic;if(l!==void 0){if(typeof l!="string")throw new Error('"dances" must be a string (file path)');c=l}return{name:e.name,version:typeof e.version=="string"?e.version:void 0,provider:o,models:s,env:i,stagger:a,dances:c,hives:r}}var ex,nz,ox=w(()=>{"use strict";Oi();ex=0;nz=["brood.yaml","brood.yml","brood.json"]});import{createServer as iz}from"node:net";var Ac,sx=w(()=>{"use strict";Ac=class{server=null;hives=new Map;socketMap=new Map;onHiveConnect;onHiveDisconnect;constructor(e){this.onHiveConnect=e?.onHiveConnect,this.onHiveDisconnect=e?.onHiveDisconnect}async listen(e){return new Promise((r,n)=>{let o=iz(s=>this.onConnection(s));o.on("error",n),o.listen(e,()=>{this.server=o,r()})})}async close(){for(let e of this.hives.values())e.socket.end();if(this.hives.clear(),this.socketMap.clear(),this.server)return new Promise(e=>{this.server.close(()=>e())})}getConnectedHives(){return[...this.hives.keys()]}onConnection(e){let r="";e.setEncoding("utf8"),e.on("data",n=>{r+=n;let o=r.split(`
164
164
  `);r=o.pop();for(let s of o)if(s)try{this.handleMessage(e,JSON.parse(s))}catch{}}),e.on("close",()=>{let n=this.socketMap.get(e);n&&(this.hives.delete(n.name),this.socketMap.delete(e),this.onHiveDisconnect?.(n.name))}),e.on("error",()=>{})}handleMessage(e,r){if(r.type==="register"&&r.hive){let n={name:r.hive,socket:e,subscribes:new Set(r.subscribes??[])};this.hives.set(r.hive,n),this.socketMap.set(e,n),this.onHiveConnect?.(r.hive)}else r.type==="event"&&r.hive&&r.topic&&this.routeEvent(r.hive,r.topic,r.event)}routeEvent(e,r,n){for(let[o,s]of this.hives){if(o===e||!s.subscribes.has(r))continue;let i=JSON.stringify({type:"forward",topic:r,event:n})+`
165
- `;s.socket.write(i)}}}});import{createWriteStream as qN}from"node:fs";import{readdirSync as ZN,readFileSync as UN,existsSync as Yw}from"node:fs";import{join as FN}from"node:path";function Xw(t){if(!Yw(t))return[];let e=UN(t,"utf8").split(`
166
- `).filter(Boolean),r=[];for(let n of e)try{r.push(JSON.parse(n))}catch{}return r}function Zd(t){let e=_n(t);return Yw(e)?ZN(e).filter(r=>r.endsWith(".jsonl")).sort().reverse().map(r=>FN(e,r)):[]}function Qw(t){let e=t.ts.slice(11,23),r={debug:"\x1B[2m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"}[t.level]||"",n="\x1B[0m",o="\x1B[2m",s=`${o}${e}${n} ${r}${t.level.toUpperCase().padEnd(5)}${n} ${o}[${t.source}]${n} ${t.msg}`;if(t.data){let i=Object.entries(t.data).map(([a,c])=>`${a}=${typeof c=="object"?JSON.stringify(c):c}`).join(" ");s+=` ${o}${i}${n}`}return s}var HN,Oc,Ud=w(()=>{"use strict";bn();HN=/\x1b\[[0-9;]*m/g,Oc=class{stream;path;constructor(e){ld(e),this.path=cd(e),this.stream=qN(this.path,{flags:"a"})}write(e){this.stream.write(JSON.stringify(e)+`
165
+ `;s.socket.write(i)}}}});import{createWriteStream as az}from"node:fs";import{readdirSync as cz,readFileSync as lz,existsSync as ix}from"node:fs";import{join as uz}from"node:path";function ax(t){if(!ix(t))return[];let e=lz(t,"utf8").split(`
166
+ `).filter(Boolean),r=[];for(let n of e)try{r.push(JSON.parse(n))}catch{}return r}function Wd(t){let e=_n(t);return ix(e)?cz(e).filter(r=>r.endsWith(".jsonl")).sort().reverse().map(r=>uz(e,r)):[]}function cx(t){let e=t.ts.slice(11,23),r={debug:"\x1B[2m",info:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m"}[t.level]||"",n="\x1B[0m",o="\x1B[2m",s=`${o}${e}${n} ${r}${t.level.toUpperCase().padEnd(5)}${n} ${o}[${t.source}]${n} ${t.msg}`;if(t.data){let i=Object.entries(t.data).map(([a,c])=>`${a}=${typeof c=="object"?JSON.stringify(c):c}`).join(" ");s+=` ${o}${i}${n}`}return s}var pz,Nc,Jd=w(()=>{"use strict";bn();pz=/\x1b\[[0-9;]*m/g,Nc=class{stream;path;constructor(e){gd(e),this.path=hd(e),this.stream=az(this.path,{flags:"a"})}write(e){this.stream.write(JSON.stringify(e)+`
167
167
  `)}writeLine(e,r,n="info"){let o=e.trim();if(o){if(o.startsWith("{"))try{let s=JSON.parse(o);if(s.ts&&s.msg){this.stream.write(o+`
168
- `);return}}catch{}this.write({ts:new Date().toISOString(),level:n,source:r,msg:o.replace(HN,"")})}}close(){this.stream.end()}}});var sx={};X(sx,{up:()=>YN});import{spawn as BN}from"node:child_process";import{mkdirSync as Hd,writeFileSync as tx,existsSync as VN,unlinkSync as ex,readFileSync as GN}from"node:fs";import{join as Sn,dirname as fs,resolve as Pi}from"node:path";import{tmpdir as rx}from"node:os";import{randomBytes as nx}from"node:crypto";import{createRequire as WN}from"node:module";function KN(t,e){let r=[Sn(e,"__placeholder.js"),import.meta.url];for(let n of r)try{return WN(n).resolve(t)}catch{}return null}function ox(){return Sn(process.cwd(),".honeyb")}function Fd(){return Sn(ox(),"brood.state.json")}async function YN(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
168
+ `);return}}catch{}this.write({ts:new Date().toISOString(),level:n,source:r,msg:o.replace(pz,"")})}}close(){this.stream.end()}}});var mx={};K(mx,{up:()=>vz});import{spawn as dz}from"node:child_process";import{mkdirSync as Yd,writeFileSync as ux,existsSync as fz,unlinkSync as lx,readFileSync as mz}from"node:fs";import{join as Sn,dirname as hs,resolve as Ci}from"node:path";import{tmpdir as px}from"node:os";import{randomBytes as dx}from"node:crypto";import{createRequire as hz}from"node:module";function yz(t,e){let r=[Sn(e,"__placeholder.js"),import.meta.url];for(let n of r)try{return hz(n).resolve(t)}catch{}return null}function fx(){return Sn(process.cwd(),".honeyb")}function Kd(){return Sn(fx(),"brood.state.json")}async function vz(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
169
169
  ${y("bold","wgl up")} \u2014 start a local brood (multi-hive incubator cluster)
170
170
 
171
171
  ${y("cyan","USAGE:")}
@@ -193,12 +193,12 @@ ${y("cyan","EXAMPLES:")}
193
193
  wgl up
194
194
  wgl up --file ./my-project/brood.yaml
195
195
  wgl up --base-port 4000
196
- `);return}VN(Fd())&&(console.log(b("A brood is already running")),console.log(y("dim"," Run `wgl down` to stop it first")),process.exit(1));let e=t.indexOf("--file"),r=e!==-1?t[e+1]:void 0,n=t.indexOf("-f"),o=n!==-1?t[n+1]:void 0,s=t.indexOf("--base-port"),i=s!==-1?parseInt(t[s+1],10):3100,a=t.includes("--no-acp"),c=t.indexOf("--provider"),l=c!==-1?t[c+1]:void 0,u=t.indexOf("--spec"),p=u!==-1?t[u+1]:void 0,m=t.indexOf("--dances"),d=m!==-1?t[m+1]:void 0,f=l??process.env.WAGGLE_PROVIDER??void 0,h=p??process.env.WAGGLE_SPEC??void 0,g=d??process.env.WAGGLE_DANCES??void 0,v=Gw(o??r),_;if(v)try{_=await Ww(v)}catch(G){console.log(b(`Invalid brood file: ${G.message}`)),process.exit(1);return}else if(h){let G=h.replace(/\.(acp|yaml|yml|json)$/i,"").split("/").pop()??"default";_={name:G,provider:f??"ollama/qwen3:8b",dances:g,hives:{[G]:{acp:h,dances:g}}},v=Sn(process.cwd(),"brood.yaml")}else{console.log(b("No brood.yaml found and no --spec provided")),console.log(y("dim"," Create a brood.yaml or pass --spec <path>")),process.exit(1);return}let x=Object.keys(_.hives);if(x.length===0){console.log(b("brood.yaml has no hives defined")),process.exit(1);return}let k=x.filter(G=>(_.hives[G].agents?.length??0)>0),I=k.some(G=>_.hives[G].agents?.some(F=>!F.type||F.type==="worker"||F.type==="drone")),de=process.cwd(),Y=process.argv[1],ee=null;if(I&&(ee=KN(JN,de),!ee)){console.log(b("Hive not installed (required for worker/drone agents)")),console.log(`
196
+ `);return}fz(Kd())&&(console.log(_("A brood is already running")),console.log(y("dim"," Run `wgl down` to stop it first")),process.exit(1));let e=t.indexOf("--file"),r=e!==-1?t[e+1]:void 0,n=t.indexOf("-f"),o=n!==-1?t[n+1]:void 0,s=t.indexOf("--base-port"),i=s!==-1?parseInt(t[s+1],10):3100,a=t.includes("--no-acp"),c=t.indexOf("--provider"),l=c!==-1?t[c+1]:void 0,u=t.indexOf("--spec"),p=u!==-1?t[u+1]:void 0,f=t.indexOf("--dances"),d=f!==-1?t[f+1]:void 0,m=l??process.env.WAGGLE_PROVIDER??void 0,h=p??process.env.WAGGLE_SPEC??void 0,g=d??process.env.WAGGLE_DANCES??void 0,v=rx(o??r),b;if(v)try{b=await nx(v)}catch(V){console.log(_(`Invalid brood file: ${V.message}`)),process.exit(1);return}else if(h){let V=h.replace(/\.(acp|yaml|yml|json)$/i,"").split("/").pop()??"default";b={name:V,provider:m??"ollama/qwen3:8b",dances:g,hives:{[V]:{acp:h,dances:g}}},v=Sn(process.cwd(),"brood.yaml")}else{console.log(_("No brood.yaml found and no --spec provided")),console.log(y("dim"," Create a brood.yaml or pass --spec <path>")),process.exit(1);return}let x=Object.keys(b.hives);if(x.length===0){console.log(_("brood.yaml has no hives defined")),process.exit(1);return}let $=x.filter(V=>(b.hives[V].agents?.length??0)>0),O=$.some(V=>b.hives[V].agents?.some(F=>!F.type||F.type==="worker"||F.type==="drone")),ce=process.cwd(),X=process.argv[1],ee=null;if(O&&(ee=yz(gz,ce),!ee)){console.log(_("Hive not installed (required for worker/drone agents)")),console.log(`
197
197
  Install it with:
198
198
  ${y("cyan","npm install @honeybee-ai/hive")}
199
- `),process.exit(1);return}let ge={...process.env,..._.env};console.log(C(`Starting brood: ${_.name}`)),console.log(S("File",v)),console.log(S("Hives",x.join(", "))),f&&v&&(_.provider=f),_.provider&&console.log(S("Provider",_.provider)),_.env&&console.log(S("Env",Object.keys(_.env).join(", "))),k.length>0&&console.log(S("Agent hives",k.join(", "))),a&&console.log(S("Mode","no-acp (benchmark \u2014 LLM sees coordination tools)")),console.log();let U=nx(4).toString("hex"),ne=Sn(rx(),`honeybee-brood-${U}`);Hd(ne,{recursive:!0});let rt=Sn(ne,"broker.sock"),Mt=new Rc({onHiveConnect:G=>console.log(z(`Hive "${G}" connected to broker`)),onHiveDisconnect:G=>console.log(gn(`Hive "${G}" disconnected`))});await Mt.listen(rt),console.log(z("IPC broker started"));let te=new Map,fe={},Lt=i,se=i+100,le=null;try{le=new Oc,console.log(y("dim",` Logging to ${le.path}`))}catch{}for(let[G,F]of Object.entries(_.hives)){let me=F.port??Lt++,Jr=F.worktree?Pi(fs(v),F.worktree):fs(v),Be=QN(F,v,G),Oe=["--http",`--port=${me}`,"--log-format=json"];Be&&Oe.push(`--protocol=${Be}`);let Ar=g??F.dances??_.dances;if(Ar){let ot=Pi(fs(v),Ar);Oe.push(`--dances=${ot}`)}let Kr=F.agents?.length?F.agents:XN(Be);if(Kr.length){let ot=se++,Jt=F.worktree?Pi(fs(v),F.worktree):Pi(fs(v)),ie={provider:_.provider??"ollama/qwen3:8b",stagger:_.stagger??2,noAcp:a,propolisPort:ot,worktree:Jt,hiveEntry:ee??"",...Be?{protocolPath:Be}:{},agents:Kr.map(V=>({role:V.role,count:V.count,type:V.type,tools:V.tools,coordination:V.coordination,modelHint:V.model_hint??null,prompt:V.prompt??null,startOn:V.startOn?Vw(V.startOn):null,wakeOn:V.wake_on?{types:V.wake_on.types??null,timeout:V.wake_on.timeout??0,maxWakes:V.wake_on.max_wakes??0}:null})),models:_.models,env:_.env};Oe.push(`--agents=${JSON.stringify(ie)}`),Oe.push("--verbose");let oe=Kr.filter(V=>!V.type||V.type==="worker").reduce((V,$t)=>V+($t.count??1),0),je=Kr.filter(V=>V.type==="drone").reduce((V,$t)=>V+($t.count??1),0),ye=Kr.filter(V=>V.type==="claude").reduce((V,$t)=>V+($t.count??1),0),Ze=[];oe>0&&Ze.push(`${oe} worker${oe!==1?"s":""}`),je>0&&Ze.push(`${je} drone${je!==1?"s":""}`),ye>0&&Ze.push(`${ye} claude${ye!==1?"s":""}`),console.log(S(`${G}/agents`,`${Ze.join(" + ")} (delegated to incubator)`))}let hn={...ge,HONEYCOMB_BROKER_SOCKET:rt,HONEYCOMB_HIVE_NAME:G};F.honeycomb?.publishes?.length&&(hn.HONEYCOMB_PUBLISHES=F.honeycomb.publishes.join(",")),F.honeycomb?.subscribes?.length&&(hn.HONEYCOMB_SUBSCRIBES=F.honeycomb.subscribes.join(","));let nr=BN(process.execPath,[Y,"incubator",...Oe],{env:hn,cwd:Jr,stdio:["ignore","pipe","pipe"]});nr.stdout?.on("data",ot=>{for(let Jt of ot.toString().split(`
200
- `))Jt.trim()&&le?.writeLine(Jt,G,"info")}),nr.stderr?.on("data",ot=>{let Jt=ot.toString().trim();Jt&&(console.log(y("dim",`[${G}] ${Jt}`)),le?.writeLine(Jt,G,"info"))}),nr.on("exit",ot=>{te.delete(`incubator:${G}`),ot!==null&&ot!==0&&console.log(gn(`Hive "${G}" incubator exited with code ${ot}`))}),nr.pid&&(te.set(`incubator:${G}`,nr),fe[G]={pid:nr.pid,port:me},console.log(S(G,`incubator port ${me} (pid ${nr.pid})`)))}Hd(ox(),{recursive:!0});let ct={name:_.name,socketPath:rt,hives:fe,startedAt:new Date().toISOString()};tx(Fd(),JSON.stringify(ct,null,2)),console.log(),console.log(z(`Brood "${_.name}" running (${x.length} hive${x.length!==1?"s":""})`)),console.log(y("dim"," Press Ctrl+C or run `wgl down` to stop"));let Ir=async()=>{console.log(`
201
- `+y("dim","Shutting down..."));for(let[G,F]of te)F.kill("SIGTERM"),console.log(y("dim",` Stopped ${G}`));await Mt.close(),le?.close();try{ex(rt)}catch{}try{ex(Fd())}catch{}console.log(z("Brood stopped")),process.exit(0)};process.on("SIGINT",Ir),process.on("SIGTERM",Ir),await new Promise(()=>{})}function XN(t){if(!t||t.startsWith("http://")||t.startsWith("https://"))return[];try{let e=GN(t,"utf-8"),n=(t.endsWith(".json")?JSON.parse(e):Xr.load(e)).roles;if(!n)return[];let o=[];for(let[s,i]of Object.entries(n)){let a=typeof i.agents=="number"?i.agents:1;for(let c=0;c<a;c++)o.push({role:s})}return o}catch{return[]}}function QN(t,e,r){let n=t.acp??t.protocol;if(!n)return;if(typeof n=="string")return n.startsWith("http://")||n.startsWith("https://")?n:Pi(fs(e),n);let o=Sn(rx(),`honeybee-protocol-${nx(4).toString("hex")}`);Hd(o,{recursive:!0});let s=Sn(o,`${r}.acp.json`);return tx(s,JSON.stringify(n,null,2)),s}var JN,ix=w(()=>{"use strict";Re();Jw();Kw();Ud();Ti();JN="@honeybee-ai/hive"});var lx={};X(lx,{down:()=>nz});import{readFileSync as ez,existsSync as Bd,unlinkSync as ax,rmSync as tz}from"node:fs";import{join as cx}from"node:path";function rz(){let t=cx(process.cwd(),".honeyb","brood.state.json");if(Bd(t))return t;let e=cx(process.cwd(),".honeybee","brood.state.json");return Bd(e)?e:t}async function nz(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
199
+ `),process.exit(1);return}let ge={...process.env,...b.env};console.log(C(`Starting brood: ${b.name}`)),console.log(S("File",v)),console.log(S("Hives",x.join(", "))),m&&v&&(b.provider=m),b.provider&&console.log(S("Provider",b.provider)),b.env&&console.log(S("Env",Object.keys(b.env).join(", "))),$.length>0&&console.log(S("Agent hives",$.join(", "))),a&&console.log(S("Mode","no-acp (benchmark \u2014 LLM sees coordination tools)")),console.log();let U=dx(4).toString("hex"),ne=Sn(px(),`honeybee-brood-${U}`);Yd(ne,{recursive:!0});let rt=Sn(ne,"broker.sock"),Mt=new Ac({onHiveConnect:V=>console.log(N(`Hive "${V}" connected to broker`)),onHiveDisconnect:V=>console.log(gn(`Hive "${V}" disconnected`))});await Mt.listen(rt),console.log(N("IPC broker started"));let te=new Map,fe={},Lt=i,se=i+100,ue=null;try{ue=new Nc,console.log(y("dim",` Logging to ${ue.path}`))}catch{}for(let[V,F]of Object.entries(b.hives)){let me=F.port??Lt++,Jr=F.worktree?Ci(hs(v),F.worktree):hs(v),Be=bz(F,v,V),Oe=["--http",`--port=${me}`,"--log-format=json"];Be&&Oe.push(`--protocol=${Be}`);let Ar=g??F.dances??b.dances;if(Ar){let ot=Ci(hs(v),Ar);Oe.push(`--dances=${ot}`)}let Kr=F.agents?.length?F.agents:_z(Be);if(Kr.length){let ot=se++,Jt=F.worktree?Ci(hs(v),F.worktree):Ci(hs(v)),ie={provider:b.provider??"ollama/qwen3:8b",stagger:b.stagger??2,noAcp:a,propolisPort:ot,worktree:Jt,hiveEntry:ee??"",...Be?{protocolPath:Be}:{},agents:Kr.map(G=>({role:G.role,count:G.count,type:G.type,tools:G.tools,coordination:G.coordination,modelHint:G.model_hint??null,prompt:G.prompt??null,startOn:G.startOn?tx(G.startOn):null,wakeOn:G.wake_on?{types:G.wake_on.types??null,timeout:G.wake_on.timeout??0,maxWakes:G.wake_on.max_wakes??0}:null})),models:b.models,env:b.env};Oe.push(`--agents=${JSON.stringify(ie)}`),Oe.push("--verbose");let oe=Kr.filter(G=>!G.type||G.type==="worker").reduce((G,$t)=>G+($t.count??1),0),Me=Kr.filter(G=>G.type==="drone").reduce((G,$t)=>G+($t.count??1),0),ye=Kr.filter(G=>G.type==="claude").reduce((G,$t)=>G+($t.count??1),0),Ue=[];oe>0&&Ue.push(`${oe} worker${oe!==1?"s":""}`),Me>0&&Ue.push(`${Me} drone${Me!==1?"s":""}`),ye>0&&Ue.push(`${ye} claude${ye!==1?"s":""}`),console.log(S(`${V}/agents`,`${Ue.join(" + ")} (delegated to incubator)`))}let hn={...ge,HONEYCOMB_BROKER_SOCKET:rt,HONEYCOMB_HIVE_NAME:V};F.honeycomb?.publishes?.length&&(hn.HONEYCOMB_PUBLISHES=F.honeycomb.publishes.join(",")),F.honeycomb?.subscribes?.length&&(hn.HONEYCOMB_SUBSCRIBES=F.honeycomb.subscribes.join(","));let nr=dz(process.execPath,[X,"incubator",...Oe],{env:hn,cwd:Jr,stdio:["ignore","pipe","pipe"]});nr.stdout?.on("data",ot=>{for(let Jt of ot.toString().split(`
200
+ `))Jt.trim()&&ue?.writeLine(Jt,V,"info")}),nr.stderr?.on("data",ot=>{let Jt=ot.toString().trim();Jt&&(console.log(y("dim",`[${V}] ${Jt}`)),ue?.writeLine(Jt,V,"info"))}),nr.on("exit",ot=>{te.delete(`incubator:${V}`),ot!==null&&ot!==0&&console.log(gn(`Hive "${V}" incubator exited with code ${ot}`))}),nr.pid&&(te.set(`incubator:${V}`,nr),fe[V]={pid:nr.pid,port:me},console.log(S(V,`incubator port ${me} (pid ${nr.pid})`)))}Yd(fx(),{recursive:!0});let ct={name:b.name,socketPath:rt,hives:fe,startedAt:new Date().toISOString()};ux(Kd(),JSON.stringify(ct,null,2)),console.log(),console.log(N(`Brood "${b.name}" running (${x.length} hive${x.length!==1?"s":""})`)),console.log(y("dim"," Press Ctrl+C or run `wgl down` to stop"));let Ir=async()=>{console.log(`
201
+ `+y("dim","Shutting down..."));for(let[V,F]of te)F.kill("SIGTERM"),console.log(y("dim",` Stopped ${V}`));await Mt.close(),ue?.close();try{lx(rt)}catch{}try{lx(Kd())}catch{}console.log(N("Brood stopped")),process.exit(0)};process.on("SIGINT",Ir),process.on("SIGTERM",Ir),await new Promise(()=>{})}function _z(t){if(!t||t.startsWith("http://")||t.startsWith("https://"))return[];try{let e=mz(t,"utf-8"),n=(t.endsWith(".json")?JSON.parse(e):Xr.load(e)).roles;if(!n)return[];let o=[];for(let[s,i]of Object.entries(n)){let a=typeof i.agents=="number"?i.agents:1;for(let c=0;c<a;c++)o.push({role:s})}return o}catch{return[]}}function bz(t,e,r){let n=t.acp??t.protocol;if(!n)return;if(typeof n=="string")return n.startsWith("http://")||n.startsWith("https://")?n:Ci(hs(e),n);let o=Sn(px(),`honeybee-protocol-${dx(4).toString("hex")}`);Yd(o,{recursive:!0});let s=Sn(o,`${r}.acp.json`);return ux(s,JSON.stringify(n,null,2)),s}var gz,hx=w(()=>{"use strict";Re();ox();sx();Jd();Oi();gz="@honeybee-ai/hive"});var vx={};K(vx,{down:()=>$z});import{readFileSync as wz,existsSync as Xd,unlinkSync as gx,rmSync as xz}from"node:fs";import{join as yx}from"node:path";function Sz(){let t=yx(process.cwd(),".honeyb","brood.state.json");if(Xd(t))return t;let e=yx(process.cwd(),".honeybee","brood.state.json");return Xd(e)?e:t}async function $z(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
202
202
  ${y("bold","wgl down")} \u2014 stop a running brood
203
203
 
204
204
  ${y("cyan","USAGE:")}
@@ -211,7 +211,7 @@ ${y("cyan","DESCRIPTION:")}
211
211
 
212
212
  ${y("cyan","EXAMPLES:")}
213
213
  wgl down
214
- `);return}let e=rz();if(!Bd(e)){console.log(b("No running brood found")),console.log(y("dim"," No .honeyb/brood.state.json in current directory")),process.exit(1);return}let r;try{r=JSON.parse(ez(e,"utf8"))}catch{console.log(b("Corrupt state file")),process.exit(1);return}console.log(C(`Stopping brood: ${r.name}`));let n=0;for(let[s,i]of Object.entries(r.hives))try{process.kill(i.pid,"SIGTERM"),console.log(S(s,`incubator stopped (pid ${i.pid})`)),n++}catch{console.log(S(s,y("dim",`not running (pid ${i.pid})`)))}if(r.socketPath){try{ax(r.socketPath)}catch{}let{dirname:s}=await import("node:path");try{tz(s(r.socketPath),{recursive:!0,force:!0})}catch{}}try{ax(e)}catch{}let o=Object.keys(r.hives).length;console.log(),console.log(z(`Brood stopped (${o} hive${o!==1?"s":""} terminated)`))}var ux=w(()=>{"use strict";Re()});var px={};X(px,{logs:()=>lz});import{existsSync as oz,readdirSync as sz,unlinkSync as iz,statSync as az}from"node:fs";import{join as cz}from"node:path";async function lz(t){let e=t[0];if(e==="--help"||e==="-h"){console.log(`
214
+ `);return}let e=Sz();if(!Xd(e)){console.log(_("No running brood found")),console.log(y("dim"," No .honeyb/brood.state.json in current directory")),process.exit(1);return}let r;try{r=JSON.parse(wz(e,"utf8"))}catch{console.log(_("Corrupt state file")),process.exit(1);return}console.log(C(`Stopping brood: ${r.name}`));let n=0;for(let[s,i]of Object.entries(r.hives))try{process.kill(i.pid,"SIGTERM"),console.log(S(s,`incubator stopped (pid ${i.pid})`)),n++}catch{console.log(S(s,y("dim",`not running (pid ${i.pid})`)))}if(r.socketPath){try{gx(r.socketPath)}catch{}let{dirname:s}=await import("node:path");try{xz(s(r.socketPath),{recursive:!0,force:!0})}catch{}}try{gx(e)}catch{}let o=Object.keys(r.hives).length;console.log(),console.log(N(`Brood stopped (${o} hive${o!==1?"s":""} terminated)`))}var _x=w(()=>{"use strict";Re()});var bx={};K(bx,{logs:()=>Oz});import{existsSync as kz,readdirSync as Ez,unlinkSync as Tz,statSync as Pz}from"node:fs";import{join as Rz}from"node:path";async function Oz(t){let e=t[0];if(e==="--help"||e==="-h"){console.log(`
215
215
  ${y("bold","wgl logs")} \u2014 view brood run logs
216
216
 
217
217
  ${y("cyan","USAGE:")}
@@ -225,7 +225,7 @@ ${y("cyan","USAGE:")}
225
225
  wgl logs --json Raw JSONL output (default for pipe)
226
226
  wgl logs --clean Delete old log files
227
227
  wgl logs --list List available log files
228
- `);return}let r=uz(t);if(r.clean){await dz();return}if(r.list){await fz();return}let n=Zd();if(n.length===0){console.log(b("No log files found")),console.log(y("dim",` Log directory: ${_n()}`)),console.log(y("dim"," Logs are created when running `wgl up`")),process.exit(1);return}let o=r.last??0;if(o>=n.length){console.log(b(`Only ${n.length} log file(s) available`)),process.exit(1);return}let s=n[o],i=Xw(s),a=i;if(r.level){let l=pz(r.level);a=a.filter(u=>l.has(u.level))}r.source&&(a=a.filter(l=>l.source===r.source)),r.agent&&(a=a.filter(l=>l.data?l.data.agentId===r.agent||l.msg.includes(r.agent):!1));let c=r.json?!1:r.pretty??process.stdout.isTTY;c&&(console.log(C(`Logs: ${s.split("/").pop()}`)),console.log(y("dim",` ${a.length} entries (of ${i.length} total)`)),console.log());for(let l of a)console.log(c?Qw(l):JSON.stringify(l))}function uz(t){let e={};for(let r of t){if(r==="--last"){e.last=0;continue}if(r.startsWith("--last=")){e.last=parseInt(r.slice(7),10)||0;continue}if(r.startsWith("--level=")){e.level=r.slice(8);continue}if(r.startsWith("--source=")){e.source=r.slice(9);continue}if(r.startsWith("--agent=")){e.agent=r.slice(8);continue}if(r==="--pretty"){e.pretty=!0;continue}if(r==="--json"){e.json=!0;continue}if(r==="--clean"){e.clean=!0;continue}if(r==="--list"){e.list=!0;continue}if(r==="--follow"||r==="-f"){e.last=0;continue}}return e}function pz(t){let e=["debug","info","warn","error"],r=e.indexOf(t);return r<0?new Set(e):new Set(e.slice(r))}async function dz(){let t=_n();if(!oz(t)){console.log("No log directory found");return}let e=sz(t).filter(r=>r.endsWith(".jsonl"));for(let r of e)iz(cz(t,r));console.log(`Deleted ${e.length} log file(s)`)}async function fz(){let t=Zd();if(t.length===0){console.log("No log files");return}console.log(C("Log Files"));for(let e=0;e<t.length;e++){let r=t[e].split("/").pop(),n=az(t[e]),o=n.size<1024?`${n.size}B`:`${(n.size/1024).toFixed(1)}KB`,s=e===0?" (latest)":"";console.log(S(`${e}`,`${r} ${y("dim",o)}${s}`))}}var dx=w(()=>{"use strict";Re();Ud();bn()});var mx={};X(mx,{inspect:()=>mz});async function mz(t){let e=t[0]||"overview";if(e==="--help"||e==="-h"){console.log(`
228
+ `);return}let r=Cz(t);if(r.clean){await Az();return}if(r.list){await Nz();return}let n=Wd();if(n.length===0){console.log(_("No log files found")),console.log(y("dim",` Log directory: ${_n()}`)),console.log(y("dim"," Logs are created when running `wgl up`")),process.exit(1);return}let o=r.last??0;if(o>=n.length){console.log(_(`Only ${n.length} log file(s) available`)),process.exit(1);return}let s=n[o],i=ax(s),a=i;if(r.level){let l=Iz(r.level);a=a.filter(u=>l.has(u.level))}r.source&&(a=a.filter(l=>l.source===r.source)),r.agent&&(a=a.filter(l=>l.data?l.data.agentId===r.agent||l.msg.includes(r.agent):!1));let c=r.json?!1:r.pretty??process.stdout.isTTY;c&&(console.log(C(`Logs: ${s.split("/").pop()}`)),console.log(y("dim",` ${a.length} entries (of ${i.length} total)`)),console.log());for(let l of a)console.log(c?cx(l):JSON.stringify(l))}function Cz(t){let e={};for(let r of t){if(r==="--last"){e.last=0;continue}if(r.startsWith("--last=")){e.last=parseInt(r.slice(7),10)||0;continue}if(r.startsWith("--level=")){e.level=r.slice(8);continue}if(r.startsWith("--source=")){e.source=r.slice(9);continue}if(r.startsWith("--agent=")){e.agent=r.slice(8);continue}if(r==="--pretty"){e.pretty=!0;continue}if(r==="--json"){e.json=!0;continue}if(r==="--clean"){e.clean=!0;continue}if(r==="--list"){e.list=!0;continue}if(r==="--follow"||r==="-f"){e.last=0;continue}}return e}function Iz(t){let e=["debug","info","warn","error"],r=e.indexOf(t);return r<0?new Set(e):new Set(e.slice(r))}async function Az(){let t=_n();if(!kz(t)){console.log("No log directory found");return}let e=Ez(t).filter(r=>r.endsWith(".jsonl"));for(let r of e)Tz(Rz(t,r));console.log(`Deleted ${e.length} log file(s)`)}async function Nz(){let t=Wd();if(t.length===0){console.log("No log files");return}console.log(C("Log Files"));for(let e=0;e<t.length;e++){let r=t[e].split("/").pop(),n=Pz(t[e]),o=n.size<1024?`${n.size}B`:`${(n.size/1024).toFixed(1)}KB`,s=e===0?" (latest)":"";console.log(S(`${e}`,`${r} ${y("dim",o)}${s}`))}}var wx=w(()=>{"use strict";Re();Jd();bn()});var Sx={};K(Sx,{inspect:()=>zz});async function zz(t){let e=t[0]||"overview";if(e==="--help"||e==="-h"){console.log(`
229
229
  ${y("bold","wgl inspect")} \u2014 runtime introspection
230
230
 
231
231
  ${y("cyan","USAGE:")}
@@ -241,36 +241,36 @@ ${y("cyan","USAGE:")}
241
241
 
242
242
  ${y("cyan","OPTIONS:")}
243
243
  --server=URL Override incubator URL (default: from .wglrc or localhost:3100)
244
- `);return}let r=t.find(s=>s.startsWith("--server=")),n=Nr(),o=r?r.slice(9):n.server||`http://localhost:${n.incubator.port}`;switch(e){case"overview":return hz(o);case"agents":return gz(o);case"agent":return yz(o,t[1]);case"events":return vz(o,t);case"protocol":return _z(o);case"tokens":return bz(o,n);case"health":return wz(o);case"governance":return xz(o);default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl inspect --help` for usage"),process.exit(2)}}async function Xt(t,e){let r=`${t}${e}`,n=await fetch(r);if(!n.ok)throw new Error(`${n.status} from ${r}`);return n.json()}async function hz(t){try{let[e,r,n]=await Promise.all([Xt(t,"/api/health"),Xt(t,"/api/runs/summary"),Xt(t,"/api/protocol").catch(()=>null)]);console.log(C("Incubator Overview")),console.log(S("Server",t)),console.log(S("Uptime",Cc(e.uptime||0))),console.log(S("Event Cursor",String(e.eventCursor??0))),n?.protocol&&(console.log(S("Protocol",n.protocol.name||"(unnamed)")),console.log(S("Phase",n.currentPhase||"(none)"))),console.log(),console.log(C("Agents")),console.log(S("Total",String(r.agents))),console.log(S("Completed",String(r.completed))),console.log(S("Errors",String(r.errors))),console.log(S("Total Tokens",r.totalTokens.toLocaleString()))}catch(e){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function gz(t){try{let r=(await Xt(t,"/api/runs")).runs||[];if(r.length===0){console.log("No agents registered");return}console.log(C("Agents")),console.log();let n=fx("Agent ID","Role","Status","Iters","Tokens","Elapsed");console.log(y("dim",n)),console.log(y("dim","\u2500".repeat(n.length)));for(let o of r){let s=o.status==="running"?"green":o.status==="error"?"red":"dim";console.log(fx(o.agentId,o.role,y(s,o.status),String(o.iterations||0),(o.usage?.totalTokens||0).toLocaleString(),o.elapsed?Cc(o.elapsed):"-"))}}catch(e){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function yz(t,e){if(!e){console.log(b("Usage: wgl inspect agent <id>")),process.exit(2);return}try{let r=await Xt(t,`/api/runs/${encodeURIComponent(e)}`);if(!r.found){console.log(b(`Agent not found: ${e}`)),process.exit(1);return}let n=r.run;console.log(C(`Agent: ${n.agentId}`)),console.log(S("Role",n.role)),console.log(S("Status",n.status)),console.log(S("Started",n.startedAt)),n.completedAt&&console.log(S("Completed",n.completedAt)),n.elapsed&&console.log(S("Elapsed",Cc(n.elapsed))),console.log(S("Iterations",String(n.iterations||0))),n.usage&&(console.log(),console.log(C("Token Usage")),console.log(S("Prompt",n.usage.promptTokens.toLocaleString())),console.log(S("Completion",n.usage.completionTokens.toLocaleString())),console.log(S("Total",n.usage.totalTokens.toLocaleString()))),n.summary&&(console.log(),console.log(S("Summary",n.summary))),n.error&&console.log(S("Error",y("red",n.error)));try{let o=await Xt(t,`/api/runs/${encodeURIComponent(e)}/iterations`);if(o.iterations&&o.iterations.length>0){console.log(),console.log(C("Iterations"));for(let s of o.iterations)console.log(S(`#${s.index}`,`prompt=${s.promptTokens} completion=${s.completionTokens} total=${s.totalTokens}`))}}catch{}}catch(r){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${r.message}`)),process.exit(1)}}async function vz(t,e){let r=e.find(s=>s.startsWith("--type=")),n=r?r.slice(7):void 0,o=50;try{let s=new URLSearchParams;n&&s.set("type",n);let a=(await Xt(t,`/api/events?${s}`)).events||[],c=a.slice(-o);console.log(C(`Events (${c.length} of ${a.length})`)),console.log();for(let l of c){let u=l.timestamp?.slice(11,23)||"";console.log(`${y("dim",u)} ${y("cyan",l.type)} ${y("dim",`by ${l.agentId||"system"}`)}`)}}catch(s){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${s.message}`)),process.exit(1)}}async function _z(t){try{let e=await Xt(t,"/api/protocol");if(!e.protocol){console.log("No protocol loaded");return}let r=e.protocol;if(console.log(C("Protocol")),console.log(S("Name",r.name||"(unnamed)")),r.version&&console.log(S("Version",r.version)),console.log(S("Current Phase",e.currentPhase||"(none)")),r.roles){console.log(),console.log(C("Roles"));for(let[n,o]of Object.entries(r.roles)){let s=typeof o.agents=="number"?o.agents:"?";console.log(S(n,`agents: ${s}`))}}if(r.phases){console.log(),console.log(C("Phases"));for(let[n]of Object.entries(r.phases)){let o=n===e.currentPhase?" \u2190 current":"";console.log(S(n,o))}}try{let n=await Xt(t,"/api/roles");if(n.assignments?.length>0){console.log(),console.log(C("Team"));for(let o of n.assignments)console.log(S(o.agentId,o.role))}}catch{}}catch(e){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function bz(t,e){try{let n=(await Xt(t,"/api/runs")).runs||[];if(n.length===0){console.log("No agents have run yet");return}console.log(C("Token Usage")),console.log();let o=0,s=0,i=0,a=0,c=e.pricing||{};for(let l of n){if(!l.usage)continue;let u=l.usage.promptTokens||0,p=l.usage.completionTokens||0,m=l.usage.totalTokens||0;o+=u,s+=p,i+=m;let d=0;for(let[,f]of Object.entries(c)){if(f.input===0&&f.output===0){d=0;break}d=(u*f.input+p*f.output)/1e6;break}a+=d,console.log(S(l.agentId,`prompt=${u.toLocaleString()} completion=${p.toLocaleString()} total=${m.toLocaleString()}${d>0?` ~$${d.toFixed(4)}`:""}`))}console.log(),console.log(y("dim","\u2500".repeat(60))),console.log(S("Total",`prompt=${o.toLocaleString()} completion=${s.toLocaleString()} total=${i.toLocaleString()}${a>0?` ~$${a.toFixed(4)}`:""}`))}catch(r){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${r.message}`)),process.exit(1)}}async function wz(t){try{let e=await Xt(t,"/api/health");console.log(C("Server Health")),console.log(S("Server",t)),console.log(S("Uptime",Cc(e.uptime||0))),console.log(S("Active Agents",String(e.activeAgents??0))),console.log(S("Claims",String(e.claimsCount??0))),console.log(S("Event Cursor",String(e.eventCursor??0))),e.backend&&console.log(S("Backend",e.backend)),e.guard!==void 0&&console.log(S("Carapace Guard",e.guard?"enabled":"disabled"))}catch(e){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function xz(t){try{let[e,r]=await Promise.all([Xt(t,"/api/governance/proposals").catch(()=>({proposals:[]})),Xt(t,"/api/control/status").catch(()=>({}))]);console.log(C("Governance")),r.halted?(console.log(S("Status",y("red","HALTED"))),r.reason&&console.log(S("Reason",r.reason))):r.paused?console.log(S("Status",y("yellow","PAUSED"))):console.log(S("Status",y("green","RUNNING")));let n=e.proposals||[];if(n.length>0){console.log(),console.log(C("Active Proposals"));for(let o of n)console.log(S(o.id,`${o.action} by ${o.agentId} (${o.endorsements?.length||0}/${o.quorum} endorsements)`))}}catch(e){console.log(b(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}function Cc(t){if(t<1e3)return`${t}ms`;let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let r=Math.floor(e/60),n=e%60;if(r<60)return`${r}m ${n}s`;let o=Math.floor(r/60),s=r%60;return`${o}h ${s}m`}function fx(...t){let e=[20,14,12,6,12,10];return t.map((r,n)=>r.padEnd(e[n]||10)).join(" ")}var hx=w(()=>{"use strict";Re();bn()});function E(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Qt(t){return t&&Object.assign(Ic,t),Ic}var Sz,$z,Qr,Ic,ms=w(()=>{Sz=Object.freeze({status:"aborted"});$z=Symbol("zod_brand"),Qr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ic={}});var we={};X(we,{BIGINT_FORMAT_RANGES:()=>yx,Class:()=>Gd,NUMBER_FORMAT_RANGES:()=>ef,aborted:()=>fo,allowsEval:()=>Yd,assert:()=>Rz,assertEqual:()=>kz,assertIs:()=>Tz,assertNever:()=>Pz,assertNotEqual:()=>Ez,assignProp:()=>Kd,cached:()=>Ci,captureStackTrace:()=>Nc,cleanEnum:()=>Uz,cleanRegex:()=>Ai,clone:()=>er,createTransparentProxy:()=>zz,defineLazy:()=>Me,esc:()=>po,escapeRegex:()=>$n,extend:()=>Lz,finalizeIssue:()=>xr,floatSafeRemainder:()=>Jd,getElementAtPath:()=>Oz,getEnumValues:()=>Oi,getLengthableOrigin:()=>Ni,getParsedType:()=>Nz,getSizableOrigin:()=>vx,isObject:()=>hs,isPlainObject:()=>gs,issue:()=>tf,joinValues:()=>Ac,jsonStringifyReplacer:()=>Wd,merge:()=>Dz,normalizeParams:()=>W,nullish:()=>Ii,numKeys:()=>Az,omit:()=>Mz,optionalKeys:()=>Qd,partial:()=>qz,pick:()=>jz,prefixIssues:()=>jr,primitiveTypes:()=>gx,promiseAllObject:()=>Cz,propertyKeyTypes:()=>Xd,randomString:()=>Iz,required:()=>Zz,stringifyPrimitive:()=>zc,unwrapMessage:()=>Ri});function kz(t){return t}function Ez(t){return t}function Tz(t){}function Pz(t){throw new Error}function Rz(t){}function Oi(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Ac(t,e="|"){return t.map(r=>zc(r)).join(e)}function Wd(t,e){return typeof e=="bigint"?e.toString():e}function Ci(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ii(t){return t==null}function Ai(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Jd(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Me(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Kd(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Oz(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Cz(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function Iz(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function po(t){return JSON.stringify(t)}function hs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function gs(t){if(hs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(hs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Az(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function $n(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function er(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function W(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function zz(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function zc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Qd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function jz(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return er(t,{...t._zod.def,shape:r,checks:[]})}function Mz(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return er(t,{...t._zod.def,shape:r,checks:[]})}function Lz(t,e){if(!gs(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Kd(this,"shape",n),n},checks:[]};return er(t,r)}function Dz(t,e){return er(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Kd(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function qz(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return er(e,{...e._zod.def,shape:o,checks:[]})}function Zz(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return er(e,{...e._zod.def,shape:o,checks:[]})}function fo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ri(t){return typeof t=="string"?t:t?.message}function xr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ri(t.inst?._zod.def?.error?.(t))??Ri(e?.error?.(t))??Ri(r.customError?.(t))??Ri(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function vx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Ni(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function tf(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Uz(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Nc,Yd,Nz,Xd,gx,ef,yx,Gd,Mr=w(()=>{Nc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};Yd=Ci(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});Nz=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Xd=new Set(["string","number","symbol"]),gx=new Set(["string","number","bigint","boolean","symbol","undefined"]);ef={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},yx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Gd=class{constructor(...e){}}});function rf(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function nf(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var _x,jc,zi,of=w(()=>{ms();Mr();_x=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Wd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},jc=E("$ZodError",_x),zi=E("$ZodError",_x,{Parent:Error})});var sf,af,cf,lf,uf,mo,pf,ho,df=w(()=>{ms();of();Mr();sf=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Qr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xr(c,s,Qt())));throw Nc(a,o?.callee),a}return i.value},af=sf(zi),cf=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xr(c,s,Qt())));throw Nc(a,o?.callee),a}return i.value},lf=cf(zi),uf=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qr;return s.issues.length?{success:!1,error:new(t??jc)(s.issues.map(i=>xr(i,o,Qt())))}:{success:!0,data:s.value}},mo=uf(zi),pf=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>xr(i,o,Qt())))}:{success:!0,data:s.value}},ho=pf(zi)});function Rx(){return new RegExp(Hz,"u")}function Dx(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qx(t){return new RegExp(`^${Dx(t)}$`)}function Zx(t){let e=Dx({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Mx}T(?:${n})$`)}var bx,wx,xx,Sx,$x,kx,Ex,Tx,ff,Px,Hz,Ox,Cx,Ix,Ax,Nx,mf,zx,jx,Mx,Lx,Ux,Fx,Hx,Bx,Vx,Gx,Wx,Lc=w(()=>{bx=/^[cC][^\s-]{8,}$/,wx=/^[0-9a-z]+$/,xx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Sx=/^[0-9a-vA-V]{20}$/,$x=/^[A-Za-z0-9]{27}$/,kx=/^[a-zA-Z0-9_-]{21}$/,Ex=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Tx=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ff=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Px=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Hz="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Ox=/^(?:(?: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])$/,Cx=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Ix=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ax=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Nx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mf=/^[A-Za-z0-9_-]*$/,zx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,jx=/^\+(?:[0-9]){6,14}[0-9]$/,Mx="(?:(?:\\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])))",Lx=new RegExp(`^${Mx}$`);Ux=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Fx=/^\d+$/,Hx=/^-?\d+(?:\.\d+)?/i,Bx=/true|false/i,Vx=/null/i,Gx=/^[^A-Z]*$/,Wx=/^[^a-z]*$/});var yt,Jx,hf,gf,Kx,Yx,Xx,Qx,e0,ji,t0,r0,n0,o0,s0,i0,a0,Dc=w(()=>{ms();Lc();Mr();yt=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Jx={number:"number",bigint:"bigint",object:"date"},hf=E("$ZodCheckLessThan",(t,e)=>{yt.init(t,e);let r=Jx[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),gf=E("$ZodCheckGreaterThan",(t,e)=>{yt.init(t,e);let r=Jx[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Kx=E("$ZodCheckMultipleOf",(t,e)=>{yt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Jd(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Yx=E("$ZodCheckNumberFormat",(t,e)=>{yt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=ef[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Fx)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),Xx=E("$ZodCheckMaxLength",(t,e)=>{var r;yt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ii(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Ni(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),Qx=E("$ZodCheckMinLength",(t,e)=>{var r;yt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ii(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Ni(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),e0=E("$ZodCheckLengthEquals",(t,e)=>{var r;yt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ii(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Ni(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),ji=E("$ZodCheckStringFormat",(t,e)=>{var r,n;yt.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),t0=E("$ZodCheckRegex",(t,e)=>{ji.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),r0=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Gx),ji.init(t,e)}),n0=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Wx),ji.init(t,e)}),o0=E("$ZodCheckIncludes",(t,e)=>{yt.init(t,e);let r=$n(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),s0=E("$ZodCheckStartsWith",(t,e)=>{yt.init(t,e);let r=new RegExp(`^${$n(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),i0=E("$ZodCheckEndsWith",(t,e)=>{yt.init(t,e);let r=new RegExp(`.*${$n(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),a0=E("$ZodCheckOverwrite",(t,e)=>{yt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var qc,yf=w(()=>{qc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
244
+ `);return}let r=t.find(s=>s.startsWith("--server=")),n=Nr(),o=r?r.slice(9):n.server||`http://localhost:${n.incubator.port}`;switch(e){case"overview":return jz(o);case"agents":return Mz(o);case"agent":return Lz(o,t[1]);case"events":return Dz(o,t);case"protocol":return qz(o);case"tokens":return Zz(o,n);case"health":return Uz(o);case"governance":return Fz(o);default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl inspect --help` for usage"),process.exit(2)}}async function Xt(t,e){let r=`${t}${e}`,n=await fetch(r);if(!n.ok)throw new Error(`${n.status} from ${r}`);return n.json()}async function jz(t){try{let[e,r,n]=await Promise.all([Xt(t,"/api/health"),Xt(t,"/api/runs/summary"),Xt(t,"/api/protocol").catch(()=>null)]);console.log(C("Incubator Overview")),console.log(S("Server",t)),console.log(S("Uptime",zc(e.uptime||0))),console.log(S("Event Cursor",String(e.eventCursor??0))),n?.protocol&&(console.log(S("Protocol",n.protocol.name||"(unnamed)")),console.log(S("Phase",n.currentPhase||"(none)"))),console.log(),console.log(C("Agents")),console.log(S("Total",String(r.agents))),console.log(S("Completed",String(r.completed))),console.log(S("Errors",String(r.errors))),console.log(S("Total Tokens",r.totalTokens.toLocaleString()))}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function Mz(t){try{let r=(await Xt(t,"/api/runs")).runs||[];if(r.length===0){console.log("No agents registered");return}console.log(C("Agents")),console.log();let n=xx("Agent ID","Role","Status","Iters","Tokens","Elapsed");console.log(y("dim",n)),console.log(y("dim","\u2500".repeat(n.length)));for(let o of r){let s=o.status==="running"?"green":o.status==="error"?"red":"dim";console.log(xx(o.agentId,o.role,y(s,o.status),String(o.iterations||0),(o.usage?.totalTokens||0).toLocaleString(),o.elapsed?zc(o.elapsed):"-"))}}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function Lz(t,e){if(!e){console.log(_("Usage: wgl inspect agent <id>")),process.exit(2);return}try{let r=await Xt(t,`/api/runs/${encodeURIComponent(e)}`);if(!r.found){console.log(_(`Agent not found: ${e}`)),process.exit(1);return}let n=r.run;console.log(C(`Agent: ${n.agentId}`)),console.log(S("Role",n.role)),console.log(S("Status",n.status)),console.log(S("Started",n.startedAt)),n.completedAt&&console.log(S("Completed",n.completedAt)),n.elapsed&&console.log(S("Elapsed",zc(n.elapsed))),console.log(S("Iterations",String(n.iterations||0))),n.usage&&(console.log(),console.log(C("Token Usage")),console.log(S("Prompt",n.usage.promptTokens.toLocaleString())),console.log(S("Completion",n.usage.completionTokens.toLocaleString())),console.log(S("Total",n.usage.totalTokens.toLocaleString()))),n.summary&&(console.log(),console.log(S("Summary",n.summary))),n.error&&console.log(S("Error",y("red",n.error)));try{let o=await Xt(t,`/api/runs/${encodeURIComponent(e)}/iterations`);if(o.iterations&&o.iterations.length>0){console.log(),console.log(C("Iterations"));for(let s of o.iterations)console.log(S(`#${s.index}`,`prompt=${s.promptTokens} completion=${s.completionTokens} total=${s.totalTokens}`))}}catch{}}catch(r){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${r.message}`)),process.exit(1)}}async function Dz(t,e){let r=e.find(s=>s.startsWith("--type=")),n=r?r.slice(7):void 0,o=50;try{let s=new URLSearchParams;n&&s.set("type",n);let a=(await Xt(t,`/api/events?${s}`)).events||[],c=a.slice(-o);console.log(C(`Events (${c.length} of ${a.length})`)),console.log();for(let l of c){let u=l.timestamp?.slice(11,23)||"";console.log(`${y("dim",u)} ${y("cyan",l.type)} ${y("dim",`by ${l.agentId||"system"}`)}`)}}catch(s){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${s.message}`)),process.exit(1)}}async function qz(t){try{let e=await Xt(t,"/api/protocol");if(!e.protocol){console.log("No protocol loaded");return}let r=e.protocol;if(console.log(C("Protocol")),console.log(S("Name",r.name||"(unnamed)")),r.version&&console.log(S("Version",r.version)),console.log(S("Current Phase",e.currentPhase||"(none)")),r.roles){console.log(),console.log(C("Roles"));for(let[n,o]of Object.entries(r.roles)){let s=typeof o.agents=="number"?o.agents:"?";console.log(S(n,`agents: ${s}`))}}if(r.phases){console.log(),console.log(C("Phases"));for(let[n]of Object.entries(r.phases)){let o=n===e.currentPhase?" \u2190 current":"";console.log(S(n,o))}}try{let n=await Xt(t,"/api/roles");if(n.assignments?.length>0){console.log(),console.log(C("Team"));for(let o of n.assignments)console.log(S(o.agentId,o.role))}}catch{}}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function Zz(t,e){try{let n=(await Xt(t,"/api/runs")).runs||[];if(n.length===0){console.log("No agents have run yet");return}console.log(C("Token Usage")),console.log();let o=0,s=0,i=0,a=0,c=e.pricing||{};for(let l of n){if(!l.usage)continue;let u=l.usage.promptTokens||0,p=l.usage.completionTokens||0,f=l.usage.totalTokens||0;o+=u,s+=p,i+=f;let d=0;for(let[,m]of Object.entries(c)){if(m.input===0&&m.output===0){d=0;break}d=(u*m.input+p*m.output)/1e6;break}a+=d,console.log(S(l.agentId,`prompt=${u.toLocaleString()} completion=${p.toLocaleString()} total=${f.toLocaleString()}${d>0?` ~$${d.toFixed(4)}`:""}`))}console.log(),console.log(y("dim","\u2500".repeat(60))),console.log(S("Total",`prompt=${o.toLocaleString()} completion=${s.toLocaleString()} total=${i.toLocaleString()}${a>0?` ~$${a.toFixed(4)}`:""}`))}catch(r){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${r.message}`)),process.exit(1)}}async function Uz(t){try{let e=await Xt(t,"/api/health");console.log(C("Server Health")),console.log(S("Server",t)),console.log(S("Uptime",zc(e.uptime||0))),console.log(S("Active Agents",String(e.activeAgents??0))),console.log(S("Claims",String(e.claimsCount??0))),console.log(S("Event Cursor",String(e.eventCursor??0))),e.backend&&console.log(S("Backend",e.backend)),e.guard!==void 0&&console.log(S("Carapace Guard",e.guard?"enabled":"disabled"))}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}async function Fz(t){try{let[e,r]=await Promise.all([Xt(t,"/api/governance/proposals").catch(()=>({proposals:[]})),Xt(t,"/api/control/status").catch(()=>({}))]);console.log(C("Governance")),r.halted?(console.log(S("Status",y("red","HALTED"))),r.reason&&console.log(S("Reason",r.reason))):r.paused?console.log(S("Status",y("yellow","PAUSED"))):console.log(S("Status",y("green","RUNNING")));let n=e.proposals||[];if(n.length>0){console.log(),console.log(C("Active Proposals"));for(let o of n)console.log(S(o.id,`${o.action} by ${o.agentId} (${o.endorsements?.length||0}/${o.quorum} endorsements)`))}}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(y("dim",` ${e.message}`)),process.exit(1)}}function zc(t){if(t<1e3)return`${t}ms`;let e=Math.floor(t/1e3);if(e<60)return`${e}s`;let r=Math.floor(e/60),n=e%60;if(r<60)return`${r}m ${n}s`;let o=Math.floor(r/60),s=r%60;return`${o}h ${s}m`}function xx(...t){let e=[20,14,12,6,12,10];return t.map((r,n)=>r.padEnd(e[n]||10)).join(" ")}var $x=w(()=>{"use strict";Re();bn()});function E(t,e,r){function n(a,c){var l;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(l=a._zod).traits??(l.traits=new Set),a._zod.traits.add(t),e(a,c);for(let u in i.prototype)u in a||Object.defineProperty(a,u,{value:i.prototype[u].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let l=r?.Parent?new s:this;n(l,a),(c=l._zod).deferred??(c.deferred=[]);for(let u of l._zod.deferred)u();return l}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function Qt(t){return t&&Object.assign(jc,t),jc}var Hz,Bz,Qr,jc,gs=w(()=>{Hz=Object.freeze({status:"aborted"});Bz=Symbol("zod_brand"),Qr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},jc={}});var we={};K(we,{BIGINT_FORMAT_RANGES:()=>Ex,Class:()=>ef,NUMBER_FORMAT_RANGES:()=>cf,aborted:()=>mo,allowsEval:()=>of,assert:()=>Kz,assertEqual:()=>Gz,assertIs:()=>Wz,assertNever:()=>Jz,assertNotEqual:()=>Vz,assignProp:()=>nf,cached:()=>Ni,captureStackTrace:()=>Lc,cleanEnum:()=>lj,cleanRegex:()=>ji,clone:()=>er,createTransparentProxy:()=>rj,defineLazy:()=>Le,esc:()=>fo,escapeRegex:()=>$n,extend:()=>sj,finalizeIssue:()=>xr,floatSafeRemainder:()=>rf,getElementAtPath:()=>Yz,getEnumValues:()=>Ai,getLengthableOrigin:()=>Mi,getParsedType:()=>tj,getSizableOrigin:()=>Tx,isObject:()=>ys,isPlainObject:()=>vs,issue:()=>lf,joinValues:()=>Mc,jsonStringifyReplacer:()=>tf,merge:()=>ij,normalizeParams:()=>W,nullish:()=>zi,numKeys:()=>ej,omit:()=>oj,optionalKeys:()=>af,partial:()=>aj,pick:()=>nj,prefixIssues:()=>jr,primitiveTypes:()=>kx,promiseAllObject:()=>Xz,propertyKeyTypes:()=>sf,randomString:()=>Qz,required:()=>cj,stringifyPrimitive:()=>Dc,unwrapMessage:()=>Ii});function Gz(t){return t}function Vz(t){return t}function Wz(t){}function Jz(t){throw new Error}function Kz(t){}function Ai(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function Mc(t,e="|"){return t.map(r=>Dc(r)).join(e)}function tf(t,e){return typeof e=="bigint"?e.toString():e}function Ni(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function zi(t){return t==null}function ji(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function rf(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Le(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function nf(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Yz(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Xz(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function Qz(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function fo(t){return JSON.stringify(t)}function ys(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vs(t){if(ys(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ys(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function ej(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function $n(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function er(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function W(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function rj(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function Dc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function af(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function nj(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return er(t,{...t._zod.def,shape:r,checks:[]})}function oj(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return er(t,{...t._zod.def,shape:r,checks:[]})}function sj(t,e){if(!vs(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return nf(this,"shape",n),n},checks:[]};return er(t,r)}function ij(t,e){return er(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return nf(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function aj(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return er(e,{...e._zod.def,shape:o,checks:[]})}function cj(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return er(e,{...e._zod.def,shape:o,checks:[]})}function mo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function jr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ii(t){return typeof t=="string"?t:t?.message}function xr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ii(t.inst?._zod.def?.error?.(t))??Ii(e?.error?.(t))??Ii(r.customError?.(t))??Ii(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Tx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Mi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function lf(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function lj(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Lc,of,tj,sf,kx,cf,Ex,ef,Mr=w(()=>{Lc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};of=Ni(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});tj=t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},sf=new Set(["string","number","symbol"]),kx=new Set(["string","number","bigint","boolean","symbol","undefined"]);cf={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ex={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};ef=class{constructor(...e){}}});function uf(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function pf(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(t),n}var Px,qc,Li,df=w(()=>{gs();Mr();Px=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,tf,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},qc=E("$ZodError",Px),Li=E("$ZodError",Px,{Parent:Error})});var ff,mf,hf,gf,yf,ho,vf,go,_f=w(()=>{gs();df();Mr();ff=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Qr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xr(c,s,Qt())));throw Lc(a,o?.callee),a}return i.value},mf=ff(Li),hf=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>xr(c,s,Qt())));throw Lc(a,o?.callee),a}return i.value},gf=hf(Li),yf=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Qr;return s.issues.length?{success:!1,error:new(t??qc)(s.issues.map(i=>xr(i,o,Qt())))}:{success:!0,data:s.value}},ho=yf(Li),vf=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>xr(i,o,Qt())))}:{success:!0,data:s.value}},go=vf(Li)});function Lx(){return new RegExp(pj,"u")}function Wx(t){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Jx(t){return new RegExp(`^${Wx(t)}$`)}function Kx(t){let e=Wx({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Gx}T(?:${n})$`)}var Rx,Ox,Cx,Ix,Ax,Nx,zx,jx,bf,Mx,pj,Dx,qx,Zx,Ux,Fx,wf,Hx,Bx,Gx,Vx,Yx,Xx,Qx,e0,t0,r0,n0,Uc=w(()=>{Rx=/^[cC][^\s-]{8,}$/,Ox=/^[0-9a-z]+$/,Cx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ix=/^[0-9a-vA-V]{20}$/,Ax=/^[A-Za-z0-9]{27}$/,Nx=/^[a-zA-Z0-9_-]{21}$/,zx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jx=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,bf=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Mx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,pj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Dx=/^(?:(?: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])$/,qx=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,Zx=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,Ux=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Fx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,wf=/^[A-Za-z0-9_-]*$/,Hx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Bx=/^\+(?:[0-9]){6,14}[0-9]$/,Gx="(?:(?:\\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])))",Vx=new RegExp(`^${Gx}$`);Yx=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Xx=/^\d+$/,Qx=/^-?\d+(?:\.\d+)?/i,e0=/true|false/i,t0=/null/i,r0=/^[^A-Z]*$/,n0=/^[^a-z]*$/});var yt,o0,xf,Sf,s0,i0,a0,c0,l0,Di,u0,p0,d0,f0,m0,h0,g0,Fc=w(()=>{gs();Uc();Mr();yt=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),o0={number:"number",bigint:"bigint",object:"date"},xf=E("$ZodCheckLessThan",(t,e)=>{yt.init(t,e);let r=o0[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Sf=E("$ZodCheckGreaterThan",(t,e)=>{yt.init(t,e);let r=o0[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),s0=E("$ZodCheckMultipleOf",(t,e)=>{yt.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):rf(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),i0=E("$ZodCheckNumberFormat",(t,e)=>{yt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=cf[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Xx)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),a0=E("$ZodCheckMaxLength",(t,e)=>{var r;yt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Mi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),c0=E("$ZodCheckMinLength",(t,e)=>{var r;yt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Mi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),l0=E("$ZodCheckLengthEquals",(t,e)=>{var r;yt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!zi(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Mi(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Di=E("$ZodCheckStringFormat",(t,e)=>{var r,n;yt.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),u0=E("$ZodCheckRegex",(t,e)=>{Di.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),p0=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=r0),Di.init(t,e)}),d0=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=n0),Di.init(t,e)}),f0=E("$ZodCheckIncludes",(t,e)=>{yt.init(t,e);let r=$n(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),m0=E("$ZodCheckStartsWith",(t,e)=>{yt.init(t,e);let r=new RegExp(`^${$n(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),h0=E("$ZodCheckEndsWith",(t,e)=>{yt.init(t,e);let r=new RegExp(`.*${$n(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),g0=E("$ZodCheckOverwrite",(t,e)=>{yt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Hc,$f=w(()=>{Hc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
245
245
  `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
246
- `))}}});var l0,vf=w(()=>{l0={major:4,minor:0,patch:0}});function S0(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Bz(t){if(!mf.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return S0(r)}function Vz(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function u0(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function Zc(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function p0(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...jr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function d0(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>xr(s,n,Qt())))}),e}function _f(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(gs(t)&&gs(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=_f(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=_f(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function f0(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),fo(t))return t;let n=_f(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function m0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function h0(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function g0(t,e,r){return fo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function y0(t){return t.value=Object.freeze(t.value),t}function v0(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(tf(o))}}var Ae,Mi,Le,bf,wf,xf,Sf,$f,kf,Ef,Tf,Pf,Rf,Of,_0,b0,w0,x0,Cf,If,Af,Nf,zf,jf,Mf,Lf,Uc,Df,qf,Zf,Uf,Ff,Hf,Fc,Hc,Bf,Vf,Gf,Wf,Jf,Kf,Yf,Xf,Qf,em,tm,rm,nm,om,sm,$0=w(()=>{Dc();ms();yf();df();Lc();Mr();vf();Mr();Ae=E("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=l0;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=fo(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,m=u._zod.check(s);if(m instanceof Promise&&a?.async===!1)throw new Qr;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(c||(c=fo(s,p)))});else{if(s.issues.length===p)continue;c||(c=fo(s,p))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Qr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=mo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return ho(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Mi=E("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Ux(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Le=E("$ZodStringFormat",(t,e)=>{ji.init(t,e),Mi.init(t,e)}),bf=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Tx),Le.init(t,e)}),wf=E("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=ff(n))}else e.pattern??(e.pattern=ff());Le.init(t,e)}),xf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Px),Le.init(t,e)}),Sf=E("$ZodURL",(t,e)=>{Le.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:zx.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),$f=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Rx()),Le.init(t,e)}),kf=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=kx),Le.init(t,e)}),Ef=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=bx),Le.init(t,e)}),Tf=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=wx),Le.init(t,e)}),Pf=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=xx),Le.init(t,e)}),Rf=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Sx),Le.init(t,e)}),Of=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=$x),Le.init(t,e)}),_0=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Zx(e)),Le.init(t,e)}),b0=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Lx),Le.init(t,e)}),w0=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=qx(e)),Le.init(t,e)}),x0=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Ex),Le.init(t,e)}),Cf=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Ox),Le.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),If=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Cx),Le.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),Af=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Ix),Le.init(t,e)}),Nf=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ax),Le.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});zf=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Nx),Le.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{S0(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});jf=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=mf),Le.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Bz(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Mf=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=jx),Le.init(t,e)});Lf=E("$ZodJWT",(t,e)=>{Le.init(t,e),t._zod.check=r=>{Vz(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Uc=E("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??Hx,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Df=E("$ZodNumber",(t,e)=>{Yx.init(t,e),Uc.init(t,e)}),qf=E("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=Bx,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Zf=E("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=Vx,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Uf=E("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),Ff=E("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Hf=E("$ZodArray",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>u0(l,r,i))):u0(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Fc=E("$ZodObject",(t,e)=>{Ae.init(t,e);let r=Ci(()=>{let p=Object.keys(e.shape);for(let d of p)if(!(e.shape[d]instanceof Ae))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);let m=Qd(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});Me(t._zod,"propValues",()=>{let p=e.shape,m={};for(let d in p){let f=p[d]._zod;if(f.values){m[d]??(m[d]=new Set);for(let h of f.values)m[d].add(h)}}return m});let n=p=>{let m=new qc(["shape","payload","ctx"]),d=r.value,f=_=>{let x=po(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};m.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of d.keys)h[_]=`key_${g++}`;m.write("const newResult = {}");for(let _ of d.keys)if(d.optionalKeys.has(_)){let x=h[_];m.write(`const ${x} = ${f(_)};`);let k=po(_);m.write(`
246
+ `))}}});var v0,kf=w(()=>{v0={major:4,minor:0,patch:0}});function I0(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function dj(t){if(!wf.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return I0(r)}function fj(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function _0(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function Bc(t,e,r){t.issues.length&&e.issues.push(...jr(r,t.issues)),e.value[r]=t.value}function b0(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...jr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function w0(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>xr(s,n,Qt())))}),e}function Ef(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(vs(t)&&vs(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=Ef(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=Ef(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function x0(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),mo(t))return t;let n=Ef(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function S0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function $0(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function k0(t,e,r){return mo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function E0(t){return t.value=Object.freeze(t.value),t}function T0(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(lf(o))}}var Ae,qi,De,Tf,Pf,Rf,Of,Cf,If,Af,Nf,zf,jf,Mf,P0,R0,O0,C0,Lf,Df,qf,Zf,Uf,Ff,Hf,Bf,Gc,Gf,Vf,Wf,Jf,Kf,Yf,Vc,Wc,Xf,Qf,em,tm,rm,nm,om,sm,im,am,cm,lm,um,pm,dm,A0=w(()=>{Fc();gs();$f();_f();Uc();Mr();kf();Mr();Ae=E("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=v0;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=mo(s),l;for(let u of i){if(u._zod.def.when){if(!u._zod.def.when(s))continue}else if(c)continue;let p=s.issues.length,f=u._zod.check(s);if(f instanceof Promise&&a?.async===!1)throw new Qr;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=mo(s,p)))});else{if(s.issues.length===p)continue;c||(c=mo(s,p))}}return l?l.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Qr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=ho(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return go(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),qi=E("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Yx(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),De=E("$ZodStringFormat",(t,e)=>{Di.init(t,e),qi.init(t,e)}),Tf=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=jx),De.init(t,e)}),Pf=E("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=bf(n))}else e.pattern??(e.pattern=bf());De.init(t,e)}),Rf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Mx),De.init(t,e)}),Of=E("$ZodURL",(t,e)=>{De.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Hx.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),Cf=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Lx()),De.init(t,e)}),If=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Nx),De.init(t,e)}),Af=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Rx),De.init(t,e)}),Nf=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ox),De.init(t,e)}),zf=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Cx),De.init(t,e)}),jf=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ix),De.init(t,e)}),Mf=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ax),De.init(t,e)}),P0=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Kx(e)),De.init(t,e)}),R0=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Vx),De.init(t,e)}),O0=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Jx(e)),De.init(t,e)}),C0=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=zx),De.init(t,e)}),Lf=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Dx),De.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Df=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=qx),De.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),qf=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Zx),De.init(t,e)}),Zf=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Ux),De.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});Uf=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Fx),De.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{I0(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Ff=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=wf),De.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{dj(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Hf=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Bx),De.init(t,e)});Bf=E("$ZodJWT",(t,e)=>{De.init(t,e),t._zod.check=r=>{fj(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Gc=E("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??Qx,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Gf=E("$ZodNumber",(t,e)=>{i0.init(t,e),Gc.init(t,e)}),Vf=E("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=e0,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Wf=E("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=t0,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Jf=E("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),Kf=E("$ZodNever",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Yf=E("$ZodArray",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(l=>_0(l,r,i))):_0(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Vc=E("$ZodObject",(t,e)=>{Ae.init(t,e);let r=Ni(()=>{let p=Object.keys(e.shape);for(let d of p)if(!(e.shape[d]instanceof Ae))throw new Error(`Invalid element at key "${d}": expected a Zod schema`);let f=af(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(f)}});Le(t._zod,"propValues",()=>{let p=e.shape,f={};for(let d in p){let m=p[d]._zod;if(m.values){f[d]??(f[d]=new Set);for(let h of m.values)f[d].add(h)}}return f});let n=p=>{let f=new Hc(["shape","payload","ctx"]),d=r.value,m=b=>{let x=fo(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),g=0;for(let b of d.keys)h[b]=`key_${g++}`;f.write("const newResult = {}");for(let b of d.keys)if(d.optionalKeys.has(b)){let x=h[b];f.write(`const ${x} = ${m(b)};`);let $=fo(b);f.write(`
247
247
  if (${x}.issues.length) {
248
- if (input[${k}] === undefined) {
249
- if (${k} in input) {
250
- newResult[${k}] = undefined;
248
+ if (input[${$}] === undefined) {
249
+ if (${$} in input) {
250
+ newResult[${$}] = undefined;
251
251
  }
252
252
  } else {
253
253
  payload.issues = payload.issues.concat(
254
254
  ${x}.issues.map((iss) => ({
255
255
  ...iss,
256
- path: iss.path ? [${k}, ...iss.path] : [${k}],
256
+ path: iss.path ? [${$}, ...iss.path] : [${$}],
257
257
  }))
258
258
  );
259
259
  }
260
260
  } else if (${x}.value === undefined) {
261
- if (${k} in input) newResult[${k}] = undefined;
261
+ if (${$} in input) newResult[${$}] = undefined;
262
262
  } else {
263
- newResult[${k}] = ${x}.value;
263
+ newResult[${$}] = ${x}.value;
264
264
  }
265
- `)}else{let x=h[_];m.write(`const ${x} = ${f(_)};`),m.write(`
265
+ `)}else{let x=h[b];f.write(`const ${x} = ${m(b)};`),f.write(`
266
266
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
267
267
  ...iss,
268
- path: iss.path ? [${po(_)}, ...iss.path] : [${po(_)}]
269
- })));`),m.write(`newResult[${po(_)}] = ${x}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let v=m.compile();return(_,x)=>v(p,_,x)},o,s=hs,i=!Ic.jitless,c=i&&Yd.value,l=e.catchall,u;t._zod.parse=(p,m)=>{u??(u=r.value);let d=p.value;if(!s(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),p;let f=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)o||(o=n(e.shape)),p=o(p,m);else{p.value={};let x=u.shape;for(let k of u.keys){let I=x[k],de=I._zod.run({value:d[k],issues:[]},m),Y=I._zod.optin==="optional"&&I._zod.optout==="optional";de instanceof Promise?f.push(de.then(ee=>Y?p0(ee,p,k,d):Zc(ee,p,k))):Y?p0(de,p,k,d):Zc(de,p,k)}}if(!l)return f.length?Promise.all(f).then(()=>p):p;let h=[],g=u.keySet,v=l._zod,_=v.def.type;for(let x of Object.keys(d)){if(g.has(x))continue;if(_==="never"){h.push(x);continue}let k=v.run({value:d[x],issues:[]},m);k instanceof Promise?f.push(k.then(I=>Zc(I,p,x))):Zc(k,p,x)}return h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:d,inst:t}),f.length?Promise.all(f).then(()=>p):p}});Hc=E("$ZodUnion",(t,e)=>{Ae.init(t,e),Me(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Me(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Me(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Me(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ai(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>d0(i,r,t,n)):d0(s,r,t,n)}}),Bf=E("$ZodDiscriminatedUnion",(t,e)=>{Hc.init(t,e);let r=t._zod.parse;Me(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=Ci(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!hs(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Vf=E("$ZodIntersection",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>f0(r,c,l)):f0(r,s,i)}});Gf=E("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!gs(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...jr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...jr(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>xr(l,n,Qt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...jr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...jr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Wf=E("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Oi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Xd.has(typeof n)).map(n=>typeof n=="string"?$n(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Jf=E("$ZodLiteral",(t,e)=>{Ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?$n(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Kf=E("$ZodTransform",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Qr;return r.value=o,r}}),Yf=E("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ai(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),Xf=E("$ZodNullable",(t,e)=>{Ae.init(t,e),Me(t._zod,"optin",()=>e.innerType._zod.optin),Me(t._zod,"optout",()=>e.innerType._zod.optout),Me(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ai(r.source)}|null)$`):void 0}),Me(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Qf=E("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>m0(s,e)):m0(o,e)}});em=E("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),tm=E("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Me(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>h0(s,t)):h0(o,t)}});rm=E("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Me(t._zod,"optout",()=>e.innerType._zod.optout),Me(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>xr(i,n,Qt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>xr(s,n,Qt()))},input:r.value}),r.issues=[]),r)}}),nm=E("$ZodPipe",(t,e)=>{Ae.init(t,e),Me(t._zod,"values",()=>e.in._zod.values),Me(t._zod,"optin",()=>e.in._zod.optin),Me(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>g0(s,e,n)):g0(o,e,n)}});om=E("$ZodReadonly",(t,e)=>{Ae.init(t,e),Me(t._zod,"propValues",()=>e.innerType._zod.propValues),Me(t._zod,"values",()=>e.innerType._zod.values),Me(t._zod,"optin",()=>e.innerType._zod.optin),Me(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(y0):y0(o)}});sm=E("$ZodCustom",(t,e)=>{yt.init(t,e),Ae.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>v0(s,r,n,t));v0(o,r,n,t)}})});function k0(){return{localeError:Wz()}}var Gz,Wz,E0=w(()=>{Mr();Gz=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},Wz=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${Gz(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${zc(n.values[0])}`:`Invalid option: expected one of ${Ac(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Ac(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Bc=w(()=>{});function T0(){return new Li}var Jz,Kz,Li,kn,am=w(()=>{Jz=Symbol("ZodOutput"),Kz=Symbol("ZodInput"),Li=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};kn=T0()});function cm(t,e){return new t({type:"string",...W(e)})}function lm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...W(e)})}function Vc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...W(e)})}function um(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...W(e)})}function pm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(e)})}function dm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(e)})}function fm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(e)})}function mm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...W(e)})}function hm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...W(e)})}function gm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(e)})}function ym(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...W(e)})}function vm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(e)})}function _m(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...W(e)})}function bm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...W(e)})}function wm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(e)})}function xm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(e)})}function Sm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(e)})}function $m(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(e)})}function km(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(e)})}function Em(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...W(e)})}function Tm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...W(e)})}function Pm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...W(e)})}function Rm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...W(e)})}function P0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(e)})}function R0(t,e){return new t({type:"string",format:"date",check:"string_format",...W(e)})}function O0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...W(e)})}function C0(t,e){return new t({type:"string",format:"duration",check:"string_format",...W(e)})}function Om(t,e){return new t({type:"number",checks:[],...W(e)})}function Cm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...W(e)})}function Im(t,e){return new t({type:"boolean",...W(e)})}function Am(t,e){return new t({type:"null",...W(e)})}function Nm(t){return new t({type:"unknown"})}function zm(t,e){return new t({type:"never",...W(e)})}function Gc(t,e){return new hf({check:"less_than",...W(e),value:t,inclusive:!1})}function Di(t,e){return new hf({check:"less_than",...W(e),value:t,inclusive:!0})}function Wc(t,e){return new gf({check:"greater_than",...W(e),value:t,inclusive:!1})}function qi(t,e){return new gf({check:"greater_than",...W(e),value:t,inclusive:!0})}function Jc(t,e){return new Kx({check:"multiple_of",...W(e),value:t})}function Kc(t,e){return new Xx({check:"max_length",...W(e),maximum:t})}function ys(t,e){return new Qx({check:"min_length",...W(e),minimum:t})}function Yc(t,e){return new e0({check:"length_equals",...W(e),length:t})}function jm(t,e){return new t0({check:"string_format",format:"regex",...W(e),pattern:t})}function Mm(t){return new r0({check:"string_format",format:"lowercase",...W(t)})}function Lm(t){return new n0({check:"string_format",format:"uppercase",...W(t)})}function Dm(t,e){return new o0({check:"string_format",format:"includes",...W(e),includes:t})}function qm(t,e){return new s0({check:"string_format",format:"starts_with",...W(e),prefix:t})}function Zm(t,e){return new i0({check:"string_format",format:"ends_with",...W(e),suffix:t})}function go(t){return new a0({check:"overwrite",tx:t})}function Um(t){return go(e=>e.normalize(t))}function Fm(){return go(t=>t.trim())}function Hm(){return go(t=>t.toLowerCase())}function Bm(){return go(t=>t.toUpperCase())}function I0(t,e,r){return new t({type:"array",element:e,...W(r)})}function Vm(t,e,r){let n=W(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Gm(t,e,r){return new t({type:"custom",check:"custom",fn:e,...W(r)})}var A0=w(()=>{Dc();Mr()});var N0=w(()=>{});function Wm(t,e){if(t instanceof Li){let n=new Xc(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Xc(e);return r.process(t),r.emit(t,e)}function ut(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return ut(o.element,r);case"object":{for(let s in o.shape)if(ut(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(ut(s,r))return!0;return!1}case"intersection":return ut(o.left,r)||ut(o.right,r);case"tuple":{for(let s of o.items)if(ut(s,r))return!0;return!!(o.rest&&ut(o.rest,r))}case"record":return ut(o.keyType,r)||ut(o.valueType,r);case"map":return ut(o.keyType,r)||ut(o.valueType,r);case"set":return ut(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ut(o.innerType,r);case"lazy":return ut(o.getter(),r);case"default":return ut(o.innerType,r);case"prefault":return ut(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return ut(o.in,r)||ut(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Xc,z0=w(()=>{am();Mr();Xc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??kn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,e],path:r.path},m=e._zod.parent;if(m)a.ref=m,this.process(m,p),this.seen.get(m).isParent=!0;else{let d=a.schema;switch(o.type){case"string":{let f=d;f.type="string";let{minimum:h,maximum:g,format:v,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(f.minLength=h),typeof g=="number"&&(f.maxLength=g),v&&(f.format=s[v]??v,f.format===""&&delete f.format),x&&(f.contentEncoding=x),_&&_.size>0){let k=[..._];k.length===1?f.pattern=k[0].source:k.length>1&&(a.schema.allOf=[...k.map(I=>({...this.target==="draft-7"?{type:"string"}:{},pattern:I.source}))])}break}case"number":{let f=d,{minimum:h,maximum:g,format:v,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:k}=e._zod.bag;typeof v=="string"&&v.includes("int")?f.type="integer":f.type="number",typeof k=="number"&&(f.exclusiveMinimum=k),typeof h=="number"&&(f.minimum=h,typeof k=="number"&&(k>=h?delete f.minimum:delete f.exclusiveMinimum)),typeof x=="number"&&(f.exclusiveMaximum=x),typeof g=="number"&&(f.maximum=g,typeof x=="number"&&(x<=g?delete f.maximum:delete f.exclusiveMaximum)),typeof _=="number"&&(f.multipleOf=_);break}case"boolean":{let f=d;f.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let f=d,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(f.minItems=h),typeof g=="number"&&(f.maxItems=g),f.type="array",f.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let f=d;f.type="object",f.properties={};let h=o.shape;for(let _ in h)f.properties[_]=this.process(h[_],{...p,path:[...p.path,"properties",_]});let g=new Set(Object.keys(h)),v=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));v.size>0&&(f.required=Array.from(v)),o.catchall?._zod.def.type==="never"?f.additionalProperties=!1:o.catchall?o.catchall&&(f.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(f.additionalProperties=!1);break}case"union":{let f=d;f.anyOf=o.options.map((h,g)=>this.process(h,{...p,path:[...p.path,"anyOf",g]}));break}case"intersection":{let f=d,h=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),g=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),v=x=>"allOf"in x&&Object.keys(x).length===1,_=[...v(h)?h.allOf:[h],...v(g)?g.allOf:[g]];f.allOf=_;break}case"tuple":{let f=d;f.type="array";let h=o.items.map((_,x)=>this.process(_,{...p,path:[...p.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?f.prefixItems=h:f.items=h,o.rest){let _=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?f.items=_:f.additionalItems=_}o.rest&&(f.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:g,maximum:v}=e._zod.bag;typeof g=="number"&&(f.minItems=g),typeof v=="number"&&(f.maxItems=v);break}case"record":{let f=d;f.type="object",f.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),f.additionalProperties=this.process(o.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let f=d,h=Oi(o.entries);h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),f.enum=h;break}case"literal":{let f=d,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];f.type=g===null?"null":typeof g,f.const=g}else h.every(g=>typeof g=="number")&&(f.type="number"),h.every(g=>typeof g=="string")&&(f.type="string"),h.every(g=>typeof g=="boolean")&&(f.type="string"),h.every(g=>g===null)&&(f.type="null"),f.enum=h;break}case"file":{let f=d,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:v,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),v!==void 0&&(h.maxLength=v),_?_.length===1?(h.contentMediaType=_[0],Object.assign(f,h)):f.anyOf=_.map(x=>({...h,contentMediaType:x})):Object.assign(f,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let f=this.process(o.innerType,p);d.anyOf=[f,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let f=d;f.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,d.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let f;try{f=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=f;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let f=d,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");f.type="string",f.pattern=h.source;break}case"pipe":{let f=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(f,p),a.ref=f;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,d.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let f=e._zod.innerType;this.process(f,p),a.ref=f;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&ut(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(u[0])?.id,g=n.external.uri??(_=>_);if(h)return{ref:g(h)};let v=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=v,{defId:v,ref:`${g("__shared")}#/${p}/${v}`}}if(u[1]===o)return{ref:"#"};let d=`#/${p}/`,f=u[1].schema.id??`__schema${this.counter++}`;return{defId:f,ref:d+f}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:m,defId:d}=s(u);p.def={...p.schema},d&&(p.defId=d);let f=p.schema;for(let h in f)delete f[h];f.$ref=m};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
268
+ path: iss.path ? [${fo(b)}, ...iss.path] : [${fo(b)}]
269
+ })));`),f.write(`newResult[${fo(b)}] = ${x}.value`)}f.write("payload.value = newResult;"),f.write("return payload;");let v=f.compile();return(b,x)=>v(p,b,x)},o,s=ys,i=!jc.jitless,c=i&&of.value,l=e.catchall,u;t._zod.parse=(p,f)=>{u??(u=r.value);let d=p.value;if(!s(d))return p.issues.push({expected:"object",code:"invalid_type",input:d,inst:t}),p;let m=[];if(i&&c&&f?.async===!1&&f.jitless!==!0)o||(o=n(e.shape)),p=o(p,f);else{p.value={};let x=u.shape;for(let $ of u.keys){let O=x[$],ce=O._zod.run({value:d[$],issues:[]},f),X=O._zod.optin==="optional"&&O._zod.optout==="optional";ce instanceof Promise?m.push(ce.then(ee=>X?b0(ee,p,$,d):Bc(ee,p,$))):X?b0(ce,p,$,d):Bc(ce,p,$)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let h=[],g=u.keySet,v=l._zod,b=v.def.type;for(let x of Object.keys(d)){if(g.has(x))continue;if(b==="never"){h.push(x);continue}let $=v.run({value:d[x],issues:[]},f);$ instanceof Promise?m.push($.then(O=>Bc(O,p,x))):Bc($,p,x)}return h.length&&p.issues.push({code:"unrecognized_keys",keys:h,input:d,inst:t}),m.length?Promise.all(m).then(()=>p):p}});Wc=E("$ZodUnion",(t,e)=>{Ae.init(t,e),Le(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Le(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Le(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Le(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>ji(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>w0(i,r,t,n)):w0(s,r,t,n)}}),Xf=E("$ZodDiscriminatedUnion",(t,e)=>{Wc.init(t,e);let r=t._zod.parse;Le(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let l of c)o[a].add(l)}}return o});let n=Ni(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!ys(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Qf=E("$ZodIntersection",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,l])=>x0(r,c,l)):x0(r,s,i)}});em=E("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!vs(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let l=e.valueType._zod.run({value:o[c],issues:[]},n);l instanceof Promise?s.push(l.then(u=>{u.issues.length&&r.issues.push(...jr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...jr(c,l.issues)),r.value[c]=l.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(l=>xr(l,n,Qt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(l=>{l.issues.length&&r.issues.push(...jr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...jr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),tm=E("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Ai(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>sf.has(typeof n)).map(n=>typeof n=="string"?$n(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),rm=E("$ZodLiteral",(t,e)=>{Ae.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?$n(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),nm=E("$ZodTransform",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Qr;return r.value=o,r}}),om=E("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Le(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ji(r.source)})?$`):void 0}),t._zod.parse=(r,n)=>e.innerType._zod.optin==="optional"?e.innerType._zod.run(r,n):r.value===void 0?r:e.innerType._zod.run(r,n)}),sm=E("$ZodNullable",(t,e)=>{Ae.init(t,e),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ji(r.source)}|null)$`):void 0}),Le(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),im=E("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>S0(s,e)):S0(o,e)}});am=E("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),cm=E("$ZodNonOptional",(t,e)=>{Ae.init(t,e),Le(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>$0(s,t)):$0(o,t)}});lm=E("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",Le(t._zod,"optout",()=>e.innerType._zod.optout),Le(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>xr(i,n,Qt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>xr(s,n,Qt()))},input:r.value}),r.issues=[]),r)}}),um=E("$ZodPipe",(t,e)=>{Ae.init(t,e),Le(t._zod,"values",()=>e.in._zod.values),Le(t._zod,"optin",()=>e.in._zod.optin),Le(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>k0(s,e,n)):k0(o,e,n)}});pm=E("$ZodReadonly",(t,e)=>{Ae.init(t,e),Le(t._zod,"propValues",()=>e.innerType._zod.propValues),Le(t._zod,"values",()=>e.innerType._zod.values),Le(t._zod,"optin",()=>e.innerType._zod.optin),Le(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(E0):E0(o)}});dm=E("$ZodCustom",(t,e)=>{yt.init(t,e),Ae.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>T0(s,r,n,t));T0(o,r,n,t)}})});function N0(){return{localeError:hj()}}var mj,hj,z0=w(()=>{Mr();mj=t=>{let e=typeof t;switch(e){case"number":return Number.isNaN(t)?"NaN":"number";case"object":{if(Array.isArray(t))return"array";if(t===null)return"null";if(Object.getPrototypeOf(t)!==Object.prototype&&t.constructor)return t.constructor.name}}return e},hj=()=>{let t={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"}};function e(n){return t[n]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"};return n=>{switch(n.code){case"invalid_type":return`Invalid input: expected ${n.expected}, received ${mj(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Dc(n.values[0])}`:`Invalid option: expected one of ${Mc(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${Mc(n.keys,", ")}`;case"invalid_key":return`Invalid key in ${n.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${n.origin}`;default:return"Invalid input"}}}});var Jc=w(()=>{});function j0(){return new Zi}var gj,yj,Zi,kn,mm=w(()=>{gj=Symbol("ZodOutput"),yj=Symbol("ZodInput"),Zi=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...r){let n=r[0];if(this._map.set(e,n),n&&typeof n=="object"&&"id"in n){if(this._idmap.has(n.id))throw new Error(`ID ${n.id} already exists in the registry`);this._idmap.set(n.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){let r=this._map.get(e);return r&&typeof r=="object"&&"id"in r&&this._idmap.delete(r.id),this._map.delete(e),this}get(e){let r=e._zod.parent;if(r){let n={...this.get(r)??{}};return delete n.id,{...n,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};kn=j0()});function hm(t,e){return new t({type:"string",...W(e)})}function gm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...W(e)})}function Kc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...W(e)})}function ym(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...W(e)})}function vm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(e)})}function _m(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(e)})}function bm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(e)})}function wm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...W(e)})}function xm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...W(e)})}function Sm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(e)})}function $m(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...W(e)})}function km(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(e)})}function Em(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...W(e)})}function Tm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...W(e)})}function Pm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(e)})}function Rm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(e)})}function Om(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(e)})}function Cm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(e)})}function Im(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(e)})}function Am(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...W(e)})}function Nm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...W(e)})}function zm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...W(e)})}function jm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...W(e)})}function M0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(e)})}function L0(t,e){return new t({type:"string",format:"date",check:"string_format",...W(e)})}function D0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...W(e)})}function q0(t,e){return new t({type:"string",format:"duration",check:"string_format",...W(e)})}function Mm(t,e){return new t({type:"number",checks:[],...W(e)})}function Lm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...W(e)})}function Dm(t,e){return new t({type:"boolean",...W(e)})}function qm(t,e){return new t({type:"null",...W(e)})}function Zm(t){return new t({type:"unknown"})}function Um(t,e){return new t({type:"never",...W(e)})}function Yc(t,e){return new xf({check:"less_than",...W(e),value:t,inclusive:!1})}function Ui(t,e){return new xf({check:"less_than",...W(e),value:t,inclusive:!0})}function Xc(t,e){return new Sf({check:"greater_than",...W(e),value:t,inclusive:!1})}function Fi(t,e){return new Sf({check:"greater_than",...W(e),value:t,inclusive:!0})}function Qc(t,e){return new s0({check:"multiple_of",...W(e),value:t})}function el(t,e){return new a0({check:"max_length",...W(e),maximum:t})}function _s(t,e){return new c0({check:"min_length",...W(e),minimum:t})}function tl(t,e){return new l0({check:"length_equals",...W(e),length:t})}function Fm(t,e){return new u0({check:"string_format",format:"regex",...W(e),pattern:t})}function Hm(t){return new p0({check:"string_format",format:"lowercase",...W(t)})}function Bm(t){return new d0({check:"string_format",format:"uppercase",...W(t)})}function Gm(t,e){return new f0({check:"string_format",format:"includes",...W(e),includes:t})}function Vm(t,e){return new m0({check:"string_format",format:"starts_with",...W(e),prefix:t})}function Wm(t,e){return new h0({check:"string_format",format:"ends_with",...W(e),suffix:t})}function yo(t){return new g0({check:"overwrite",tx:t})}function Jm(t){return yo(e=>e.normalize(t))}function Km(){return yo(t=>t.trim())}function Ym(){return yo(t=>t.toLowerCase())}function Xm(){return yo(t=>t.toUpperCase())}function Z0(t,e,r){return new t({type:"array",element:e,...W(r)})}function Qm(t,e,r){let n=W(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function eh(t,e,r){return new t({type:"custom",check:"custom",fn:e,...W(r)})}var U0=w(()=>{Fc();Mr()});var F0=w(()=>{});function th(t,e){if(t instanceof Zi){let n=new rl(e),o={};for(let a of t._idmap.entries()){let[c,l]=a;n.process(l)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,l]=a;s[c]=n.emit(l,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new rl(e);return r.process(t),r.emit(t,e)}function ut(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return ut(o.element,r);case"object":{for(let s in o.shape)if(ut(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(ut(s,r))return!0;return!1}case"intersection":return ut(o.left,r)||ut(o.right,r);case"tuple":{for(let s of o.items)if(ut(s,r))return!0;return!!(o.rest&&ut(o.rest,r))}case"record":return ut(o.keyType,r)||ut(o.valueType,r);case"map":return ut(o.keyType,r)||ut(o.valueType,r);case"set":return ut(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return ut(o.innerType,r);case"lazy":return ut(o.getter(),r);case"default":return ut(o.innerType,r);case"prefault":return ut(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return ut(o.in,r)||ut(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var rl,H0=w(()=>{mm();Mr();rl=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??kn,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let p={...r,schemaPath:[...r.schemaPath,e],path:r.path},f=e._zod.parent;if(f)a.ref=f,this.process(f,p),this.seen.get(f).isParent=!0;else{let d=a.schema;switch(o.type){case"string":{let m=d;m.type="string";let{minimum:h,maximum:g,format:v,patterns:b,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),v&&(m.format=s[v]??v,m.format===""&&delete m.format),x&&(m.contentEncoding=x),b&&b.size>0){let $=[...b];$.length===1?m.pattern=$[0].source:$.length>1&&(a.schema.allOf=[...$.map(O=>({...this.target==="draft-7"?{type:"string"}:{},pattern:O.source}))])}break}case"number":{let m=d,{minimum:h,maximum:g,format:v,multipleOf:b,exclusiveMaximum:x,exclusiveMinimum:$}=e._zod.bag;typeof v=="string"&&v.includes("int")?m.type="integer":m.type="number",typeof $=="number"&&(m.exclusiveMinimum=$),typeof h=="number"&&(m.minimum=h,typeof $=="number"&&($>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof g=="number"&&(m.maximum=g,typeof x=="number"&&(x<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof b=="number"&&(m.multipleOf=b);break}case"boolean":{let m=d;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{d.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{d.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=d,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...p,path:[...p.path,"items"]});break}case"object":{let m=d;m.type="object",m.properties={};let h=o.shape;for(let b in h)m.properties[b]=this.process(h[b],{...p,path:[...p.path,"properties",b]});let g=new Set(Object.keys(h)),v=new Set([...g].filter(b=>{let x=o.shape[b]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));v.size>0&&(m.required=Array.from(v)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...p,path:[...p.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=d;m.anyOf=o.options.map((h,g)=>this.process(h,{...p,path:[...p.path,"anyOf",g]}));break}case"intersection":{let m=d,h=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),g=this.process(o.right,{...p,path:[...p.path,"allOf",1]}),v=x=>"allOf"in x&&Object.keys(x).length===1,b=[...v(h)?h.allOf:[h],...v(g)?g.allOf:[g]];m.allOf=b;break}case"tuple":{let m=d;m.type="array";let h=o.items.map((b,x)=>this.process(b,{...p,path:[...p.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,o.rest){let b=this.process(o.rest,{...p,path:[...p.path,"items"]});this.target==="draft-2020-12"?m.items=b:m.additionalItems=b}o.rest&&(m.items=this.process(o.rest,{...p,path:[...p.path,"items"]}));let{minimum:g,maximum:v}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof v=="number"&&(m.maxItems=v);break}case"record":{let m=d;m.type="object",m.propertyNames=this.process(o.keyType,{...p,path:[...p.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...p,path:[...p.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=d,h=Ai(o.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=d,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=d,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:v,mime:b}=e._zod.bag;g!==void 0&&(h.minLength=g),v!==void 0&&(h.maxLength=v),b?b.length===1?(h.contentMediaType=b[0],Object.assign(m,h)):m.anyOf=b.map(x=>({...h,contentMediaType:x})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,p);d.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"success":{let m=d;m.type="boolean";break}case"default":{this.process(o.innerType,p),a.ref=o.innerType,d.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,p),a.ref=o.innerType,this.io==="input"&&(d._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,p),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}d.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=d,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,p),a.ref=m;break}case"readonly":{this.process(o.innerType,p),a.ref=o.innerType,d.readOnly=!0;break}case"promise":{this.process(o.innerType,p),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,p),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,p),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let l=this.metadataRegistry.get(e);return l&&Object.assign(a.schema,l),this.io==="input"&&ut(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=u=>{let p=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(u[0])?.id,g=n.external.uri??(b=>b);if(h)return{ref:g(h)};let v=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=v,{defId:v,ref:`${g("__shared")}#/${p}/${v}`}}if(u[1]===o)return{ref:"#"};let d=`#/${p}/`,m=u[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:d+m}},i=u=>{if(u[1].schema.$ref)return;let p=u[1],{ref:f,defId:d}=s(u);p.def={...p.schema},d&&(p.defId=d);let m=p.schema;for(let h in m)delete m[h];m.$ref=f};if(n.cycles==="throw")for(let u of this.seen.entries()){let p=u[1];if(p.cycle)throw new Error(`Cycle detected: #/${p.cycle?.join("/")}/<root>
270
270
 
271
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let d=n.external.registry.get(u[0])?.id;if(e!==u[0]&&d){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let m=this.seen.get(u),d=m.def??m.schema,f={...d};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,p);let g=this.seen.get(h).schema;g.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(g)):(Object.assign(d,g),Object.assign(d,f))}m.isParent||this.override({zodSchema:u,jsonSchema:d,path:m.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let p=u[1];p.def&&p.defId&&(l[p.defId]=p.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var j0=w(()=>{});var Ct=w(()=>{ms();df();of();$0();Dc();vf();Mr();Lc();Bc();am();yf();N0();A0();z0();j0()});var Jm=w(()=>{Ct()});var Zi={};X(Zi,{ZodISODate:()=>L0,ZodISODateTime:()=>M0,ZodISODuration:()=>q0,ZodISOTime:()=>D0,date:()=>Ym,datetime:()=>Km,duration:()=>Qm,time:()=>Xm});function Km(t){return P0(M0,t)}function Ym(t){return R0(L0,t)}function Xm(t){return O0(D0,t)}function Qm(t){return C0(q0,t)}var M0,L0,D0,q0,eh=w(()=>{Ct();th();M0=E("ZodISODateTime",(t,e)=>{_0.init(t,e),Ve.init(t,e)});L0=E("ZodISODate",(t,e)=>{b0.init(t,e),Ve.init(t,e)});D0=E("ZodISOTime",(t,e)=>{w0.init(t,e),Ve.init(t,e)});q0=E("ZodISODuration",(t,e)=>{x0.init(t,e),Ve.init(t,e)})});var Z0,c5,Ui,rh=w(()=>{Ct();Ct();Z0=(t,e)=>{jc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>nf(t,r)},flatten:{value:r=>rf(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},c5=E("ZodError",Z0),Ui=E("ZodError",Z0,{Parent:Error})});var U0,F0,H0,B0,nh=w(()=>{Ct();rh();U0=sf(Ui),F0=cf(Ui),H0=uf(Ui),B0=pf(Ui)});function $(t){return cm(Mj,t)}function Ie(t){return Om(K0,t)}function G0(t){return Cm(tM,t)}function ft(t){return Im(rM,t)}function ih(t){return Am(nM,t)}function Ge(){return Nm(oM)}function iM(t){return zm(sM,t)}function xe(t,e){return I0(aM,t,e)}function j(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new Y0(r)}function It(t,e){return new Y0({type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},catchall:Ge(),...we.normalizeParams(e)})}function De(t,e){return new X0({type:"union",options:t,...we.normalizeParams(e)})}function ah(t,e,r){return new cM({type:"union",options:e,discriminator:t,...we.normalizeParams(r)})}function el(t,e){return new lM({type:"intersection",left:t,right:e})}function We(t,e,r){return new uM({type:"record",keyType:t,valueType:e,...we.normalizeParams(r)})}function Zt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new oh({type:"enum",entries:r,...we.normalizeParams(e)})}function q(t,e){return new pM({type:"literal",values:Array.isArray(t)?t:[t],...we.normalizeParams(e)})}function Q0(t){return new dM({type:"transform",transform:t})}function Qe(t){return new eS({type:"optional",innerType:t})}function W0(t){return new fM({type:"nullable",innerType:t})}function hM(t,e){return new mM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function yM(t,e){return new gM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function vM(t,e){return new tS({type:"nonoptional",innerType:t,...we.normalizeParams(e)})}function bM(t,e){return new _M({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function sh(t,e){return new wM({type:"pipe",in:t,out:e})}function SM(t){return new xM({type:"readonly",innerType:t})}function $M(t){let e=new yt({check:"custom"});return e._zod.check=t,e}function nS(t,e){return Vm(rS,t??(()=>!0),e)}function kM(t,e={}){return Gm(rS,t,e)}function EM(t){let e=$M(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(we.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(we.issue(o))}},t(r.value,r)));return e}function ch(t,e){return sh(Q0(t),e)}var et,J0,Mj,Ve,Lj,V0,Qc,Dj,qj,Zj,Uj,Fj,Hj,Bj,Vj,Gj,Wj,Jj,Kj,Yj,Xj,Qj,eM,K0,tM,rM,nM,oM,sM,aM,Y0,X0,cM,lM,uM,oh,pM,dM,eS,fM,mM,gM,tS,_M,wM,xM,rS,th=w(()=>{Ct();Ct();Jm();eh();nh();et=E("ZodType",(t,e)=>(Ae.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>er(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>U0(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>H0(t,r,n),t.parseAsync=async(r,n)=>F0(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>B0(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(kM(r,n)),t.superRefine=r=>t.check(EM(r)),t.overwrite=r=>t.check(go(r)),t.optional=()=>Qe(t),t.nullable=()=>W0(t),t.nullish=()=>Qe(W0(t)),t.nonoptional=r=>vM(t,r),t.array=()=>xe(t),t.or=r=>De([t,r]),t.and=r=>el(t,r),t.transform=r=>sh(t,Q0(r)),t.default=r=>hM(t,r),t.prefault=r=>yM(t,r),t.catch=r=>bM(t,r),t.pipe=r=>sh(t,r),t.readonly=()=>SM(t),t.describe=r=>{let n=t.clone();return kn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kn.get(t);let n=t.clone();return kn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),J0=E("_ZodString",(t,e)=>{Mi.init(t,e),et.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(jm(...n)),t.includes=(...n)=>t.check(Dm(...n)),t.startsWith=(...n)=>t.check(qm(...n)),t.endsWith=(...n)=>t.check(Zm(...n)),t.min=(...n)=>t.check(ys(...n)),t.max=(...n)=>t.check(Kc(...n)),t.length=(...n)=>t.check(Yc(...n)),t.nonempty=(...n)=>t.check(ys(1,...n)),t.lowercase=n=>t.check(Mm(n)),t.uppercase=n=>t.check(Lm(n)),t.trim=()=>t.check(Fm()),t.normalize=(...n)=>t.check(Um(...n)),t.toLowerCase=()=>t.check(Hm()),t.toUpperCase=()=>t.check(Bm())}),Mj=E("ZodString",(t,e)=>{Mi.init(t,e),J0.init(t,e),t.email=r=>t.check(lm(Lj,r)),t.url=r=>t.check(mm(Dj,r)),t.jwt=r=>t.check(Rm(eM,r)),t.emoji=r=>t.check(hm(qj,r)),t.guid=r=>t.check(Vc(V0,r)),t.uuid=r=>t.check(um(Qc,r)),t.uuidv4=r=>t.check(pm(Qc,r)),t.uuidv6=r=>t.check(dm(Qc,r)),t.uuidv7=r=>t.check(fm(Qc,r)),t.nanoid=r=>t.check(gm(Zj,r)),t.guid=r=>t.check(Vc(V0,r)),t.cuid=r=>t.check(ym(Uj,r)),t.cuid2=r=>t.check(vm(Fj,r)),t.ulid=r=>t.check(_m(Hj,r)),t.base64=r=>t.check(Em(Yj,r)),t.base64url=r=>t.check(Tm(Xj,r)),t.xid=r=>t.check(bm(Bj,r)),t.ksuid=r=>t.check(wm(Vj,r)),t.ipv4=r=>t.check(xm(Gj,r)),t.ipv6=r=>t.check(Sm(Wj,r)),t.cidrv4=r=>t.check($m(Jj,r)),t.cidrv6=r=>t.check(km(Kj,r)),t.e164=r=>t.check(Pm(Qj,r)),t.datetime=r=>t.check(Km(r)),t.date=r=>t.check(Ym(r)),t.time=r=>t.check(Xm(r)),t.duration=r=>t.check(Qm(r))});Ve=E("ZodStringFormat",(t,e)=>{Le.init(t,e),J0.init(t,e)}),Lj=E("ZodEmail",(t,e)=>{xf.init(t,e),Ve.init(t,e)}),V0=E("ZodGUID",(t,e)=>{bf.init(t,e),Ve.init(t,e)}),Qc=E("ZodUUID",(t,e)=>{wf.init(t,e),Ve.init(t,e)}),Dj=E("ZodURL",(t,e)=>{Sf.init(t,e),Ve.init(t,e)}),qj=E("ZodEmoji",(t,e)=>{$f.init(t,e),Ve.init(t,e)}),Zj=E("ZodNanoID",(t,e)=>{kf.init(t,e),Ve.init(t,e)}),Uj=E("ZodCUID",(t,e)=>{Ef.init(t,e),Ve.init(t,e)}),Fj=E("ZodCUID2",(t,e)=>{Tf.init(t,e),Ve.init(t,e)}),Hj=E("ZodULID",(t,e)=>{Pf.init(t,e),Ve.init(t,e)}),Bj=E("ZodXID",(t,e)=>{Rf.init(t,e),Ve.init(t,e)}),Vj=E("ZodKSUID",(t,e)=>{Of.init(t,e),Ve.init(t,e)}),Gj=E("ZodIPv4",(t,e)=>{Cf.init(t,e),Ve.init(t,e)}),Wj=E("ZodIPv6",(t,e)=>{If.init(t,e),Ve.init(t,e)}),Jj=E("ZodCIDRv4",(t,e)=>{Af.init(t,e),Ve.init(t,e)}),Kj=E("ZodCIDRv6",(t,e)=>{Nf.init(t,e),Ve.init(t,e)}),Yj=E("ZodBase64",(t,e)=>{zf.init(t,e),Ve.init(t,e)}),Xj=E("ZodBase64URL",(t,e)=>{jf.init(t,e),Ve.init(t,e)}),Qj=E("ZodE164",(t,e)=>{Mf.init(t,e),Ve.init(t,e)}),eM=E("ZodJWT",(t,e)=>{Lf.init(t,e),Ve.init(t,e)}),K0=E("ZodNumber",(t,e)=>{Uc.init(t,e),et.init(t,e),t.gt=(n,o)=>t.check(Wc(n,o)),t.gte=(n,o)=>t.check(qi(n,o)),t.min=(n,o)=>t.check(qi(n,o)),t.lt=(n,o)=>t.check(Gc(n,o)),t.lte=(n,o)=>t.check(Di(n,o)),t.max=(n,o)=>t.check(Di(n,o)),t.int=n=>t.check(G0(n)),t.safe=n=>t.check(G0(n)),t.positive=n=>t.check(Wc(0,n)),t.nonnegative=n=>t.check(qi(0,n)),t.negative=n=>t.check(Gc(0,n)),t.nonpositive=n=>t.check(Di(0,n)),t.multipleOf=(n,o)=>t.check(Jc(n,o)),t.step=(n,o)=>t.check(Jc(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});tM=E("ZodNumberFormat",(t,e)=>{Df.init(t,e),K0.init(t,e)});rM=E("ZodBoolean",(t,e)=>{qf.init(t,e),et.init(t,e)});nM=E("ZodNull",(t,e)=>{Zf.init(t,e),et.init(t,e)});oM=E("ZodUnknown",(t,e)=>{Uf.init(t,e),et.init(t,e)});sM=E("ZodNever",(t,e)=>{Ff.init(t,e),et.init(t,e)});aM=E("ZodArray",(t,e)=>{Hf.init(t,e),et.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ys(r,n)),t.nonempty=r=>t.check(ys(1,r)),t.max=(r,n)=>t.check(Kc(r,n)),t.length=(r,n)=>t.check(Yc(r,n)),t.unwrap=()=>t.element});Y0=E("ZodObject",(t,e)=>{Fc.init(t,e),et.init(t,e),we.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Zt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ge()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ge()}),t.strict=()=>t.clone({...t._zod.def,catchall:iM()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>we.extend(t,r),t.merge=r=>we.merge(t,r),t.pick=r=>we.pick(t,r),t.omit=r=>we.omit(t,r),t.partial=(...r)=>we.partial(eS,t,r[0]),t.required=(...r)=>we.required(tS,t,r[0])});X0=E("ZodUnion",(t,e)=>{Hc.init(t,e),et.init(t,e),t.options=e.options});cM=E("ZodDiscriminatedUnion",(t,e)=>{X0.init(t,e),Bf.init(t,e)});lM=E("ZodIntersection",(t,e)=>{Vf.init(t,e),et.init(t,e)});uM=E("ZodRecord",(t,e)=>{Gf.init(t,e),et.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});oh=E("ZodEnum",(t,e)=>{Wf.init(t,e),et.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new oh({...e,checks:[],...we.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new oh({...e,checks:[],...we.normalizeParams(o),entries:s})}});pM=E("ZodLiteral",(t,e)=>{Jf.init(t,e),et.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});dM=E("ZodTransform",(t,e)=>{Kf.init(t,e),et.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(we.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(we.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});eS=E("ZodOptional",(t,e)=>{Yf.init(t,e),et.init(t,e),t.unwrap=()=>t._zod.def.innerType});fM=E("ZodNullable",(t,e)=>{Xf.init(t,e),et.init(t,e),t.unwrap=()=>t._zod.def.innerType});mM=E("ZodDefault",(t,e)=>{Qf.init(t,e),et.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});gM=E("ZodPrefault",(t,e)=>{em.init(t,e),et.init(t,e),t.unwrap=()=>t._zod.def.innerType});tS=E("ZodNonOptional",(t,e)=>{tm.init(t,e),et.init(t,e),t.unwrap=()=>t._zod.def.innerType});_M=E("ZodCatch",(t,e)=>{rm.init(t,e),et.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});wM=E("ZodPipe",(t,e)=>{nm.init(t,e),et.init(t,e),t.in=e.in,t.out=e.out});xM=E("ZodReadonly",(t,e)=>{om.init(t,e),et.init(t,e)});rS=E("ZodCustom",(t,e)=>{sm.init(t,e),et.init(t,e)})});var oS=w(()=>{});var sS=w(()=>{});var iS=w(()=>{Ct();th();Jm();rh();nh();oS();Ct();E0();Bc();eh();sS();Qt(k0())});var aS=w(()=>{iS()});var cS=w(()=>{aS()});function SS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function $S(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var uh,lS,Fi,En,rl,vt,uS,pS,$5,RM,OM,ph,tr,Hi,dS,_t,sr,ir,bt,nl,fS,Tn,mS,hS,dh,en,B,fh,_s,Bi,k5,ol,CM,sl,IM,Vi,vs,gS,AM,NM,zM,jM,MM,LM,il,mh,DM,qM,hh,al,ZM,UM,cl,FM,Gi,Wi,HM,Ji,bs,BM,Ki,ll,ul,pl,E5,dl,fl,ml,yS,vS,_S,gh,bS,Yi,ws,wS,VM,hl,GM,gl,WM,yh,JM,yl,KM,YM,XM,QM,eL,tL,rL,nL,oL,sL,vl,iL,aL,_l,vh,_h,bh,cL,lL,uL,wh,pL,dL,fL,mL,hL,xS,bl,gL,wl,T5,yL,xs,vL,P5,Xi,_L,xh,bL,wL,xL,SL,$L,kL,EL,tl,TL,PL,RL,Sh,$h,OL,CL,IL,AL,NL,zL,jL,ML,LL,DL,qL,ZL,UL,FL,HL,BL,VL,GL,xl,WL,JL,KL,Sl,YL,XL,QL,kh,eD,R5,O5,C5,I5,A5,N5,D,lh,Ss=w(()=>{cS();uh="2025-11-25",lS="2025-03-26",Fi=[uh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],En="io.modelcontextprotocol/related-task",rl="2.0",vt=nS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),uS=De([$(),Ie().int()]),pS=$(),$5=It({ttl:De([Ie(),ih()]).optional(),pollInterval:Ie().optional()}),RM=j({ttl:Ie().optional()}),OM=j({taskId:$()}),ph=It({progressToken:uS.optional(),[En]:OM.optional()}),tr=j({_meta:ph.optional()}),Hi=tr.extend({task:RM.optional()}),dS=t=>Hi.safeParse(t).success,_t=j({method:$(),params:tr.loose().optional()}),sr=j({_meta:ph.optional()}),ir=j({method:$(),params:sr.loose().optional()}),bt=It({_meta:ph.optional()}),nl=De([$(),Ie().int()]),fS=j({jsonrpc:q(rl),id:nl,..._t.shape}).strict(),Tn=t=>fS.safeParse(t).success,mS=j({jsonrpc:q(rl),...ir.shape}).strict(),hS=t=>mS.safeParse(t).success,dh=j({jsonrpc:q(rl),id:nl,result:bt}).strict(),en=t=>dh.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(B||(B={}));fh=j({jsonrpc:q(rl),id:nl.optional(),error:j({code:Ie().int(),message:$(),data:Ge().optional()})}).strict(),_s=t=>fh.safeParse(t).success,Bi=De([fS,mS,dh,fh]),k5=De([dh,fh]),ol=bt.strict(),CM=sr.extend({requestId:nl.optional(),reason:$().optional()}),sl=ir.extend({method:q("notifications/cancelled"),params:CM}),IM=j({src:$(),mimeType:$().optional(),sizes:xe($()).optional(),theme:Zt(["light","dark"]).optional()}),Vi=j({icons:xe(IM).optional()}),vs=j({name:$(),title:$().optional()}),gS=vs.extend({...vs.shape,...Vi.shape,version:$(),websiteUrl:$().optional(),description:$().optional()}),AM=el(j({applyDefaults:ft().optional()}),We($(),Ge())),NM=ch(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,el(j({form:AM.optional(),url:vt.optional()}),We($(),Ge()).optional())),zM=It({list:vt.optional(),cancel:vt.optional(),requests:It({sampling:It({createMessage:vt.optional()}).optional(),elicitation:It({create:vt.optional()}).optional()}).optional()}),jM=It({list:vt.optional(),cancel:vt.optional(),requests:It({tools:It({call:vt.optional()}).optional()}).optional()}),MM=j({experimental:We($(),vt).optional(),sampling:j({context:vt.optional(),tools:vt.optional()}).optional(),elicitation:NM.optional(),roots:j({listChanged:ft().optional()}).optional(),tasks:zM.optional()}),LM=tr.extend({protocolVersion:$(),capabilities:MM,clientInfo:gS}),il=_t.extend({method:q("initialize"),params:LM}),mh=t=>il.safeParse(t).success,DM=j({experimental:We($(),vt).optional(),logging:vt.optional(),completions:vt.optional(),prompts:j({listChanged:ft().optional()}).optional(),resources:j({subscribe:ft().optional(),listChanged:ft().optional()}).optional(),tools:j({listChanged:ft().optional()}).optional(),tasks:jM.optional()}),qM=bt.extend({protocolVersion:$(),capabilities:DM,serverInfo:gS,instructions:$().optional()}),hh=ir.extend({method:q("notifications/initialized"),params:sr.optional()}),al=_t.extend({method:q("ping"),params:tr.optional()}),ZM=j({progress:Ie(),total:Qe(Ie()),message:Qe($())}),UM=j({...sr.shape,...ZM.shape,progressToken:uS}),cl=ir.extend({method:q("notifications/progress"),params:UM}),FM=tr.extend({cursor:pS.optional()}),Gi=_t.extend({params:FM.optional()}),Wi=bt.extend({nextCursor:pS.optional()}),HM=Zt(["working","input_required","completed","failed","cancelled"]),Ji=j({taskId:$(),status:HM,ttl:De([Ie(),ih()]),createdAt:$(),lastUpdatedAt:$(),pollInterval:Qe(Ie()),statusMessage:Qe($())}),bs=bt.extend({task:Ji}),BM=sr.merge(Ji),Ki=ir.extend({method:q("notifications/tasks/status"),params:BM}),ll=_t.extend({method:q("tasks/get"),params:tr.extend({taskId:$()})}),ul=bt.merge(Ji),pl=_t.extend({method:q("tasks/result"),params:tr.extend({taskId:$()})}),E5=bt.loose(),dl=Gi.extend({method:q("tasks/list")}),fl=Wi.extend({tasks:xe(Ji)}),ml=_t.extend({method:q("tasks/cancel"),params:tr.extend({taskId:$()})}),yS=bt.merge(Ji),vS=j({uri:$(),mimeType:Qe($()),_meta:We($(),Ge()).optional()}),_S=vS.extend({text:$()}),gh=$().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),bS=vS.extend({blob:gh}),Yi=Zt(["user","assistant"]),ws=j({audience:xe(Yi).optional(),priority:Ie().min(0).max(1).optional(),lastModified:Zi.datetime({offset:!0}).optional()}),wS=j({...vs.shape,...Vi.shape,uri:$(),description:Qe($()),mimeType:Qe($()),annotations:ws.optional(),_meta:Qe(It({}))}),VM=j({...vs.shape,...Vi.shape,uriTemplate:$(),description:Qe($()),mimeType:Qe($()),annotations:ws.optional(),_meta:Qe(It({}))}),hl=Gi.extend({method:q("resources/list")}),GM=Wi.extend({resources:xe(wS)}),gl=Gi.extend({method:q("resources/templates/list")}),WM=Wi.extend({resourceTemplates:xe(VM)}),yh=tr.extend({uri:$()}),JM=yh,yl=_t.extend({method:q("resources/read"),params:JM}),KM=bt.extend({contents:xe(De([_S,bS]))}),YM=ir.extend({method:q("notifications/resources/list_changed"),params:sr.optional()}),XM=yh,QM=_t.extend({method:q("resources/subscribe"),params:XM}),eL=yh,tL=_t.extend({method:q("resources/unsubscribe"),params:eL}),rL=sr.extend({uri:$()}),nL=ir.extend({method:q("notifications/resources/updated"),params:rL}),oL=j({name:$(),description:Qe($()),required:Qe(ft())}),sL=j({...vs.shape,...Vi.shape,description:Qe($()),arguments:Qe(xe(oL)),_meta:Qe(It({}))}),vl=Gi.extend({method:q("prompts/list")}),iL=Wi.extend({prompts:xe(sL)}),aL=tr.extend({name:$(),arguments:We($(),$()).optional()}),_l=_t.extend({method:q("prompts/get"),params:aL}),vh=j({type:q("text"),text:$(),annotations:ws.optional(),_meta:We($(),Ge()).optional()}),_h=j({type:q("image"),data:gh,mimeType:$(),annotations:ws.optional(),_meta:We($(),Ge()).optional()}),bh=j({type:q("audio"),data:gh,mimeType:$(),annotations:ws.optional(),_meta:We($(),Ge()).optional()}),cL=j({type:q("tool_use"),name:$(),id:$(),input:We($(),Ge()),_meta:We($(),Ge()).optional()}),lL=j({type:q("resource"),resource:De([_S,bS]),annotations:ws.optional(),_meta:We($(),Ge()).optional()}),uL=wS.extend({type:q("resource_link")}),wh=De([vh,_h,bh,uL,lL]),pL=j({role:Yi,content:wh}),dL=bt.extend({description:$().optional(),messages:xe(pL)}),fL=ir.extend({method:q("notifications/prompts/list_changed"),params:sr.optional()}),mL=j({title:$().optional(),readOnlyHint:ft().optional(),destructiveHint:ft().optional(),idempotentHint:ft().optional(),openWorldHint:ft().optional()}),hL=j({taskSupport:Zt(["required","optional","forbidden"]).optional()}),xS=j({...vs.shape,...Vi.shape,description:$().optional(),inputSchema:j({type:q("object"),properties:We($(),vt).optional(),required:xe($()).optional()}).catchall(Ge()),outputSchema:j({type:q("object"),properties:We($(),vt).optional(),required:xe($()).optional()}).catchall(Ge()).optional(),annotations:mL.optional(),execution:hL.optional(),_meta:We($(),Ge()).optional()}),bl=Gi.extend({method:q("tools/list")}),gL=Wi.extend({tools:xe(xS)}),wl=bt.extend({content:xe(wh).default([]),structuredContent:We($(),Ge()).optional(),isError:ft().optional()}),T5=wl.or(bt.extend({toolResult:Ge()})),yL=Hi.extend({name:$(),arguments:We($(),Ge()).optional()}),xs=_t.extend({method:q("tools/call"),params:yL}),vL=ir.extend({method:q("notifications/tools/list_changed"),params:sr.optional()}),P5=j({autoRefresh:ft().default(!0),debounceMs:Ie().int().nonnegative().default(300)}),Xi=Zt(["debug","info","notice","warning","error","critical","alert","emergency"]),_L=tr.extend({level:Xi}),xh=_t.extend({method:q("logging/setLevel"),params:_L}),bL=sr.extend({level:Xi,logger:$().optional(),data:Ge()}),wL=ir.extend({method:q("notifications/message"),params:bL}),xL=j({name:$().optional()}),SL=j({hints:xe(xL).optional(),costPriority:Ie().min(0).max(1).optional(),speedPriority:Ie().min(0).max(1).optional(),intelligencePriority:Ie().min(0).max(1).optional()}),$L=j({mode:Zt(["auto","required","none"]).optional()}),kL=j({type:q("tool_result"),toolUseId:$().describe("The unique identifier for the corresponding tool call."),content:xe(wh).default([]),structuredContent:j({}).loose().optional(),isError:ft().optional(),_meta:We($(),Ge()).optional()}),EL=ah("type",[vh,_h,bh]),tl=ah("type",[vh,_h,bh,cL,kL]),TL=j({role:Yi,content:De([tl,xe(tl)]),_meta:We($(),Ge()).optional()}),PL=Hi.extend({messages:xe(TL),modelPreferences:SL.optional(),systemPrompt:$().optional(),includeContext:Zt(["none","thisServer","allServers"]).optional(),temperature:Ie().optional(),maxTokens:Ie().int(),stopSequences:xe($()).optional(),metadata:vt.optional(),tools:xe(xS).optional(),toolChoice:$L.optional()}),RL=_t.extend({method:q("sampling/createMessage"),params:PL}),Sh=bt.extend({model:$(),stopReason:Qe(Zt(["endTurn","stopSequence","maxTokens"]).or($())),role:Yi,content:EL}),$h=bt.extend({model:$(),stopReason:Qe(Zt(["endTurn","stopSequence","maxTokens","toolUse"]).or($())),role:Yi,content:De([tl,xe(tl)])}),OL=j({type:q("boolean"),title:$().optional(),description:$().optional(),default:ft().optional()}),CL=j({type:q("string"),title:$().optional(),description:$().optional(),minLength:Ie().optional(),maxLength:Ie().optional(),format:Zt(["email","uri","date","date-time"]).optional(),default:$().optional()}),IL=j({type:Zt(["number","integer"]),title:$().optional(),description:$().optional(),minimum:Ie().optional(),maximum:Ie().optional(),default:Ie().optional()}),AL=j({type:q("string"),title:$().optional(),description:$().optional(),enum:xe($()),default:$().optional()}),NL=j({type:q("string"),title:$().optional(),description:$().optional(),oneOf:xe(j({const:$(),title:$()})),default:$().optional()}),zL=j({type:q("string"),title:$().optional(),description:$().optional(),enum:xe($()),enumNames:xe($()).optional(),default:$().optional()}),jL=De([AL,NL]),ML=j({type:q("array"),title:$().optional(),description:$().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({type:q("string"),enum:xe($())}),default:xe($()).optional()}),LL=j({type:q("array"),title:$().optional(),description:$().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({anyOf:xe(j({const:$(),title:$()}))}),default:xe($()).optional()}),DL=De([ML,LL]),qL=De([zL,jL,DL]),ZL=De([qL,OL,CL,IL]),UL=Hi.extend({mode:q("form").optional(),message:$(),requestedSchema:j({type:q("object"),properties:We($(),ZL),required:xe($()).optional()})}),FL=Hi.extend({mode:q("url"),message:$(),elicitationId:$(),url:$().url()}),HL=De([UL,FL]),BL=_t.extend({method:q("elicitation/create"),params:HL}),VL=sr.extend({elicitationId:$()}),GL=ir.extend({method:q("notifications/elicitation/complete"),params:VL}),xl=bt.extend({action:Zt(["accept","decline","cancel"]),content:ch(t=>t===null?void 0:t,We($(),De([$(),Ie(),ft(),xe($())])).optional())}),WL=j({type:q("ref/resource"),uri:$()}),JL=j({type:q("ref/prompt"),name:$()}),KL=tr.extend({ref:De([JL,WL]),argument:j({name:$(),value:$()}),context:j({arguments:We($(),$()).optional()}).optional()}),Sl=_t.extend({method:q("completion/complete"),params:KL});YL=bt.extend({completion:It({values:xe($()).max(100),total:Qe(Ie().int()),hasMore:Qe(ft())})}),XL=j({uri:$().startsWith("file://"),name:$().optional(),_meta:We($(),Ge()).optional()}),QL=_t.extend({method:q("roots/list"),params:tr.optional()}),kh=bt.extend({roots:xe(XL)}),eD=ir.extend({method:q("notifications/roots/list_changed"),params:sr.optional()}),R5=De([al,il,Sl,xh,_l,vl,hl,gl,yl,QM,tL,xs,bl,ll,pl,dl,ml]),O5=De([sl,cl,hh,eD,Ki]),C5=De([ol,Sh,$h,xl,kh,ul,fl,bs]),I5=De([al,RL,BL,QL,ll,pl,dl,ml]),A5=De([sl,cl,wL,nL,YM,vL,fL,Ki,GL]),N5=De([ol,qM,YL,dL,iL,GM,WM,KM,wl,gL,ul,fl,bs]),D=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===B.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new lh(o.elicitations,r)}return new t(e,r,n)}},lh=class extends D{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function tD(t){return Bi.parse(JSON.parse(t))}function kS(t){return JSON.stringify(t)+`
272
- `}var $l,ES=w(()=>{Ss();$l=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
273
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),tD(r)}clear(){this._buffer=void 0}}});import TS from"node:process";var kl,PS=w(()=>{ES();kl=class{constructor(e=TS.stdin,r=TS.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new $l,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=kS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});import{Http2ServerRequest as rD}from"http2";import{Http2ServerRequest as Eh}from"http2";import{Readable as RS}from"stream";import mD from"crypto";async function pD(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function AS(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(l){o(l)}}}function dD(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:AS(t.getReader(),e)}var vo,nD,oD,Qi,sD,CS,iD,Es,aD,El,Tl,cD,ks,lD,Pl,uD,OS,$s,_o,Ph,ea,NS,fD,Rh,hD,zS,Th,jS,MS,gD,yD,Oh,LS=w(()=>{vo=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},nD=t=>t instanceof vo?t:new vo(t.message,{cause:t}),oD=global.Request,Qi=class extends oD{constructor(t,e){typeof t=="object"&&Es in t&&(t=t[Es]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},sD=t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&e.push([o,s])}return new Headers(e)},CS=Symbol("wrapBodyStream"),iD=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new Qi(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[CS]){let i;s.body=new ReadableStream({async pull(a){try{i||=RS.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=RS.toWeb(n);return new Qi(e,s)},Es=Symbol("getRequestCache"),aD=Symbol("requestCache"),El=Symbol("incomingKey"),Tl=Symbol("urlKey"),cD=Symbol("headersKey"),ks=Symbol("abortControllerKey"),lD=Symbol("getAbortController"),Pl={get method(){return this[El].method||"GET"},get url(){return this[Tl]},get headers(){return this[cD]||=sD(this[El])},[lD](){return this[Es](),this[ks]},[Es](){return this[ks]||=new AbortController,this[aD]||=iD(this.method,this[Tl],this.headers,this[El],this[ks])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Pl,t,{get(){return this[Es]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Pl,t,{value:function(){return this[Es]()[t]()}})});Object.setPrototypeOf(Pl,Qi.prototype);uD=(t,e)=>{let r=Object.create(Pl);r[El]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Eh)throw new vo("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Tl]=a.href}catch(a){throw new vo("Invalid absolute URL",{cause:a})}return r}let o=(t instanceof Eh?t.authority:t.headers.host)||e;if(!o)throw new vo("Missing host header");let s;if(t instanceof Eh){if(s=t.scheme,!(s==="http"||s==="https"))throw new vo("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new vo("Invalid host header");return r[Tl]=i.href,r},OS=Symbol("responseCache"),$s=Symbol("getResponseCache"),_o=Symbol("cache"),Ph=global.Response,ea=class IS{#t;#e;[$s](){return delete this[_o],this[OS]||=new Ph(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof IS){let o=r[OS];if(o){this.#e=o,this[$s]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[_o]=[r?.status||200,e,n])}get headers(){let e=this[_o];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[$s]().headers}get status(){return this[_o]?.[0]??this[$s]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(ea.prototype,t,{get(){return this[$s]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(ea.prototype,t,{value:function(){return this[$s]()[t]()}})});Object.setPrototypeOf(ea,Ph);Object.setPrototypeOf(ea.prototype,Ph.prototype);NS=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,o]of t)n==="set-cookie"?r.push(o):e[n]=o;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},fD="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=mD);Rh=Symbol("outgoingEnded"),hD=()=>new Response(null,{status:400}),zS=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Th=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},jS=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},MS=async(t,e)=>{let[r,n,o]=t[_o];o instanceof Headers&&(o=NS(o)),typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size),e.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(jS(e),await dD(n,e)?.catch(s=>Th(s,e))),e[Rh]?.()},gD=t=>typeof t.then=="function",yD=async(t,e,r={})=>{if(gD(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(zS);if(_o in t)return MS(t,e);let n=NS(t.headers);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await pD(a).catch(p=>{console.error(p),i=!0});if(!u){if(l===1){await new Promise(p=>setTimeout(p)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&jS(e),await AS(o,e,a))}else n[fD]||(e.writeHead(t.status,n),e.end());e[Rh]?.()},Oh=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==Qi&&(Object.defineProperty(global,"Request",{value:Qi}),Object.defineProperty(global,"Response",{value:ea})),async(n,o)=>{let s,i;try{i=uD(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[CS]=!0,n.on("end",()=>{a=!0}),n instanceof rD&&(o[Rh]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{i[ks]&&(n.errored?i[ks].abort(n.errored.toString()):o.writableFinished||i[ks].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(i,{incoming:n,outgoing:o}),_o in s)return MS(s,o)}catch(a){if(s)return Th(a,o);if(e.errorHandler){if(s=await e.errorHandler(i?a:nD(a)),!s)return}else i?s=zS(a):s=hD()}try{return await yD(s,o,e)}catch(a){return Th(a,o)}}}});var Rl,DS=w(()=>{Ss();Rl=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,r,n,o){let s={code:r,message:n};return o?.data!==void 0&&(s.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=e.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=e.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(e,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,r);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
271
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let u of this.seen.entries()){let p=u[1];if(e===u[0]){i(u);continue}if(n.external){let d=n.external.registry.get(u[0])?.id;if(e!==u[0]&&d){i(u);continue}}if(this.metadataRegistry.get(u[0])?.id){i(u);continue}if(p.cycle){i(u);continue}if(p.count>1&&n.reused==="ref"){i(u);continue}}let a=(u,p)=>{let f=this.seen.get(u),d=f.def??f.schema,m={...d};if(f.ref===null)return;let h=f.ref;if(f.ref=null,h){a(h,p);let g=this.seen.get(h).schema;g.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(g)):(Object.assign(d,g),Object.assign(d,m))}f.isParent||this.override({zodSchema:u,jsonSchema:d,path:f.path??[]})};for(let u of[...this.seen.entries()].reverse())a(u[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let u=n.external.registry.get(e)?.id;if(!u)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(u)}Object.assign(c,o.def);let l=n.external?.defs??{};for(let u of this.seen.entries()){let p=u[1];p.def&&p.defId&&(l[p.defId]=p.def)}n.external||Object.keys(l).length>0&&(this.target==="draft-2020-12"?c.$defs=l:c.definitions=l);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var B0=w(()=>{});var Ct=w(()=>{gs();_f();df();A0();Fc();kf();Mr();Uc();Jc();mm();$f();F0();U0();H0();B0()});var rh=w(()=>{Ct()});var Hi={};K(Hi,{ZodISODate:()=>V0,ZodISODateTime:()=>G0,ZodISODuration:()=>J0,ZodISOTime:()=>W0,date:()=>oh,datetime:()=>nh,duration:()=>ih,time:()=>sh});function nh(t){return M0(G0,t)}function oh(t){return L0(V0,t)}function sh(t){return D0(W0,t)}function ih(t){return q0(J0,t)}var G0,V0,W0,J0,ah=w(()=>{Ct();ch();G0=E("ZodISODateTime",(t,e)=>{P0.init(t,e),Ge.init(t,e)});V0=E("ZodISODate",(t,e)=>{R0.init(t,e),Ge.init(t,e)});W0=E("ZodISOTime",(t,e)=>{O0.init(t,e),Ge.init(t,e)});J0=E("ZodISODuration",(t,e)=>{C0.init(t,e),Ge.init(t,e)})});var K0,BK,Bi,lh=w(()=>{Ct();Ct();K0=(t,e)=>{qc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>pf(t,r)},flatten:{value:r=>uf(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},BK=E("ZodError",K0),Bi=E("ZodError",K0,{Parent:Error})});var Y0,X0,Q0,eS,uh=w(()=>{Ct();lh();Y0=ff(Bi),X0=hf(Bi),Q0=yf(Bi),eS=vf(Bi)});function k(t){return hm(oM,t)}function Ie(t){return Mm(sS,t)}function rS(t){return Lm(xM,t)}function ft(t){return Dm(SM,t)}function fh(t){return qm($M,t)}function Ve(){return Zm(kM)}function TM(t){return Um(EM,t)}function xe(t,e){return Z0(PM,t,e)}function j(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new iS(r)}function It(t,e){return new iS({type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},catchall:Ve(),...we.normalizeParams(e)})}function qe(t,e){return new aS({type:"union",options:t,...we.normalizeParams(e)})}function mh(t,e,r){return new RM({type:"union",options:e,discriminator:t,...we.normalizeParams(r)})}function ol(t,e){return new OM({type:"intersection",left:t,right:e})}function We(t,e,r){return new CM({type:"record",keyType:t,valueType:e,...we.normalizeParams(r)})}function Zt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new ph({type:"enum",entries:r,...we.normalizeParams(e)})}function q(t,e){return new IM({type:"literal",values:Array.isArray(t)?t:[t],...we.normalizeParams(e)})}function cS(t){return new AM({type:"transform",transform:t})}function et(t){return new lS({type:"optional",innerType:t})}function nS(t){return new NM({type:"nullable",innerType:t})}function jM(t,e){return new zM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function LM(t,e){return new MM({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function DM(t,e){return new uS({type:"nonoptional",innerType:t,...we.normalizeParams(e)})}function ZM(t,e){return new qM({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function dh(t,e){return new UM({type:"pipe",in:t,out:e})}function HM(t){return new FM({type:"readonly",innerType:t})}function BM(t){let e=new yt({check:"custom"});return e._zod.check=t,e}function dS(t,e){return Qm(pS,t??(()=>!0),e)}function GM(t,e={}){return eh(pS,t,e)}function VM(t){let e=BM(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(we.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(we.issue(o))}},t(r.value,r)));return e}function hh(t,e){return dh(cS(t),e)}var tt,oS,oM,Ge,sM,tS,nl,iM,aM,cM,lM,uM,pM,dM,fM,mM,hM,gM,yM,vM,_M,bM,wM,sS,xM,SM,$M,kM,EM,PM,iS,aS,RM,OM,CM,ph,IM,AM,lS,NM,zM,MM,uS,qM,UM,FM,pS,ch=w(()=>{Ct();Ct();rh();ah();uh();tt=E("ZodType",(t,e)=>(Ae.init(t,e),t.def=e,Object.defineProperty(t,"_def",{value:e}),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>er(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>Y0(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Q0(t,r,n),t.parseAsync=async(r,n)=>X0(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>eS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(GM(r,n)),t.superRefine=r=>t.check(VM(r)),t.overwrite=r=>t.check(yo(r)),t.optional=()=>et(t),t.nullable=()=>nS(t),t.nullish=()=>et(nS(t)),t.nonoptional=r=>DM(t,r),t.array=()=>xe(t),t.or=r=>qe([t,r]),t.and=r=>ol(t,r),t.transform=r=>dh(t,cS(r)),t.default=r=>jM(t,r),t.prefault=r=>LM(t,r),t.catch=r=>ZM(t,r),t.pipe=r=>dh(t,r),t.readonly=()=>HM(t),t.describe=r=>{let n=t.clone();return kn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return kn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return kn.get(t);let n=t.clone();return kn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),oS=E("_ZodString",(t,e)=>{qi.init(t,e),tt.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(Fm(...n)),t.includes=(...n)=>t.check(Gm(...n)),t.startsWith=(...n)=>t.check(Vm(...n)),t.endsWith=(...n)=>t.check(Wm(...n)),t.min=(...n)=>t.check(_s(...n)),t.max=(...n)=>t.check(el(...n)),t.length=(...n)=>t.check(tl(...n)),t.nonempty=(...n)=>t.check(_s(1,...n)),t.lowercase=n=>t.check(Hm(n)),t.uppercase=n=>t.check(Bm(n)),t.trim=()=>t.check(Km()),t.normalize=(...n)=>t.check(Jm(...n)),t.toLowerCase=()=>t.check(Ym()),t.toUpperCase=()=>t.check(Xm())}),oM=E("ZodString",(t,e)=>{qi.init(t,e),oS.init(t,e),t.email=r=>t.check(gm(sM,r)),t.url=r=>t.check(wm(iM,r)),t.jwt=r=>t.check(jm(wM,r)),t.emoji=r=>t.check(xm(aM,r)),t.guid=r=>t.check(Kc(tS,r)),t.uuid=r=>t.check(ym(nl,r)),t.uuidv4=r=>t.check(vm(nl,r)),t.uuidv6=r=>t.check(_m(nl,r)),t.uuidv7=r=>t.check(bm(nl,r)),t.nanoid=r=>t.check(Sm(cM,r)),t.guid=r=>t.check(Kc(tS,r)),t.cuid=r=>t.check($m(lM,r)),t.cuid2=r=>t.check(km(uM,r)),t.ulid=r=>t.check(Em(pM,r)),t.base64=r=>t.check(Am(vM,r)),t.base64url=r=>t.check(Nm(_M,r)),t.xid=r=>t.check(Tm(dM,r)),t.ksuid=r=>t.check(Pm(fM,r)),t.ipv4=r=>t.check(Rm(mM,r)),t.ipv6=r=>t.check(Om(hM,r)),t.cidrv4=r=>t.check(Cm(gM,r)),t.cidrv6=r=>t.check(Im(yM,r)),t.e164=r=>t.check(zm(bM,r)),t.datetime=r=>t.check(nh(r)),t.date=r=>t.check(oh(r)),t.time=r=>t.check(sh(r)),t.duration=r=>t.check(ih(r))});Ge=E("ZodStringFormat",(t,e)=>{De.init(t,e),oS.init(t,e)}),sM=E("ZodEmail",(t,e)=>{Rf.init(t,e),Ge.init(t,e)}),tS=E("ZodGUID",(t,e)=>{Tf.init(t,e),Ge.init(t,e)}),nl=E("ZodUUID",(t,e)=>{Pf.init(t,e),Ge.init(t,e)}),iM=E("ZodURL",(t,e)=>{Of.init(t,e),Ge.init(t,e)}),aM=E("ZodEmoji",(t,e)=>{Cf.init(t,e),Ge.init(t,e)}),cM=E("ZodNanoID",(t,e)=>{If.init(t,e),Ge.init(t,e)}),lM=E("ZodCUID",(t,e)=>{Af.init(t,e),Ge.init(t,e)}),uM=E("ZodCUID2",(t,e)=>{Nf.init(t,e),Ge.init(t,e)}),pM=E("ZodULID",(t,e)=>{zf.init(t,e),Ge.init(t,e)}),dM=E("ZodXID",(t,e)=>{jf.init(t,e),Ge.init(t,e)}),fM=E("ZodKSUID",(t,e)=>{Mf.init(t,e),Ge.init(t,e)}),mM=E("ZodIPv4",(t,e)=>{Lf.init(t,e),Ge.init(t,e)}),hM=E("ZodIPv6",(t,e)=>{Df.init(t,e),Ge.init(t,e)}),gM=E("ZodCIDRv4",(t,e)=>{qf.init(t,e),Ge.init(t,e)}),yM=E("ZodCIDRv6",(t,e)=>{Zf.init(t,e),Ge.init(t,e)}),vM=E("ZodBase64",(t,e)=>{Uf.init(t,e),Ge.init(t,e)}),_M=E("ZodBase64URL",(t,e)=>{Ff.init(t,e),Ge.init(t,e)}),bM=E("ZodE164",(t,e)=>{Hf.init(t,e),Ge.init(t,e)}),wM=E("ZodJWT",(t,e)=>{Bf.init(t,e),Ge.init(t,e)}),sS=E("ZodNumber",(t,e)=>{Gc.init(t,e),tt.init(t,e),t.gt=(n,o)=>t.check(Xc(n,o)),t.gte=(n,o)=>t.check(Fi(n,o)),t.min=(n,o)=>t.check(Fi(n,o)),t.lt=(n,o)=>t.check(Yc(n,o)),t.lte=(n,o)=>t.check(Ui(n,o)),t.max=(n,o)=>t.check(Ui(n,o)),t.int=n=>t.check(rS(n)),t.safe=n=>t.check(rS(n)),t.positive=n=>t.check(Xc(0,n)),t.nonnegative=n=>t.check(Fi(0,n)),t.negative=n=>t.check(Yc(0,n)),t.nonpositive=n=>t.check(Ui(0,n)),t.multipleOf=(n,o)=>t.check(Qc(n,o)),t.step=(n,o)=>t.check(Qc(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});xM=E("ZodNumberFormat",(t,e)=>{Gf.init(t,e),sS.init(t,e)});SM=E("ZodBoolean",(t,e)=>{Vf.init(t,e),tt.init(t,e)});$M=E("ZodNull",(t,e)=>{Wf.init(t,e),tt.init(t,e)});kM=E("ZodUnknown",(t,e)=>{Jf.init(t,e),tt.init(t,e)});EM=E("ZodNever",(t,e)=>{Kf.init(t,e),tt.init(t,e)});PM=E("ZodArray",(t,e)=>{Yf.init(t,e),tt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(_s(r,n)),t.nonempty=r=>t.check(_s(1,r)),t.max=(r,n)=>t.check(el(r,n)),t.length=(r,n)=>t.check(tl(r,n)),t.unwrap=()=>t.element});iS=E("ZodObject",(t,e)=>{Vc.init(t,e),tt.init(t,e),we.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Zt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ve()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ve()}),t.strict=()=>t.clone({...t._zod.def,catchall:TM()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>we.extend(t,r),t.merge=r=>we.merge(t,r),t.pick=r=>we.pick(t,r),t.omit=r=>we.omit(t,r),t.partial=(...r)=>we.partial(lS,t,r[0]),t.required=(...r)=>we.required(uS,t,r[0])});aS=E("ZodUnion",(t,e)=>{Wc.init(t,e),tt.init(t,e),t.options=e.options});RM=E("ZodDiscriminatedUnion",(t,e)=>{aS.init(t,e),Xf.init(t,e)});OM=E("ZodIntersection",(t,e)=>{Qf.init(t,e),tt.init(t,e)});CM=E("ZodRecord",(t,e)=>{em.init(t,e),tt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});ph=E("ZodEnum",(t,e)=>{tm.init(t,e),tt.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new ph({...e,checks:[],...we.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new ph({...e,checks:[],...we.normalizeParams(o),entries:s})}});IM=E("ZodLiteral",(t,e)=>{rm.init(t,e),tt.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});AM=E("ZodTransform",(t,e)=>{nm.init(t,e),tt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(we.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(we.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});lS=E("ZodOptional",(t,e)=>{om.init(t,e),tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});NM=E("ZodNullable",(t,e)=>{sm.init(t,e),tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});zM=E("ZodDefault",(t,e)=>{im.init(t,e),tt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});MM=E("ZodPrefault",(t,e)=>{am.init(t,e),tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});uS=E("ZodNonOptional",(t,e)=>{cm.init(t,e),tt.init(t,e),t.unwrap=()=>t._zod.def.innerType});qM=E("ZodCatch",(t,e)=>{lm.init(t,e),tt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});UM=E("ZodPipe",(t,e)=>{um.init(t,e),tt.init(t,e),t.in=e.in,t.out=e.out});FM=E("ZodReadonly",(t,e)=>{pm.init(t,e),tt.init(t,e)});pS=E("ZodCustom",(t,e)=>{dm.init(t,e),tt.init(t,e)})});var fS=w(()=>{});var mS=w(()=>{});var hS=w(()=>{Ct();ch();rh();lh();uh();fS();Ct();z0();Jc();ah();mS();Qt(N0())});var gS=w(()=>{hS()});var yS=w(()=>{gS()});function IS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function AS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var yh,vS,Gi,En,il,vt,_S,bS,a5,KM,YM,vh,tr,Vi,wS,_t,ir,ar,bt,al,xS,Tn,SS,$S,_h,en,B,bh,ws,Wi,c5,cl,XM,ll,QM,Ji,bs,kS,eL,tL,rL,nL,oL,sL,ul,wh,iL,aL,xh,pl,cL,lL,dl,uL,Ki,Yi,pL,Xi,xs,dL,Qi,fl,ml,hl,l5,gl,yl,vl,ES,TS,PS,Sh,RS,ea,Ss,OS,fL,_l,mL,bl,hL,$h,gL,wl,yL,vL,_L,bL,wL,xL,SL,$L,kL,EL,xl,TL,PL,Sl,kh,Eh,Th,RL,OL,CL,Ph,IL,AL,NL,zL,jL,CS,$l,ML,kl,u5,LL,$s,DL,p5,ta,qL,Rh,ZL,UL,FL,HL,BL,GL,VL,sl,WL,JL,KL,Oh,Ch,YL,XL,QL,eD,tD,rD,nD,oD,sD,iD,aD,cD,lD,uD,pD,dD,fD,mD,El,hD,gD,yD,Tl,vD,_D,bD,Ih,wD,d5,f5,m5,h5,g5,y5,D,gh,ks=w(()=>{yS();yh="2025-11-25",vS="2025-03-26",Gi=[yh,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],En="io.modelcontextprotocol/related-task",il="2.0",vt=dS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),_S=qe([k(),Ie().int()]),bS=k(),a5=It({ttl:qe([Ie(),fh()]).optional(),pollInterval:Ie().optional()}),KM=j({ttl:Ie().optional()}),YM=j({taskId:k()}),vh=It({progressToken:_S.optional(),[En]:YM.optional()}),tr=j({_meta:vh.optional()}),Vi=tr.extend({task:KM.optional()}),wS=t=>Vi.safeParse(t).success,_t=j({method:k(),params:tr.loose().optional()}),ir=j({_meta:vh.optional()}),ar=j({method:k(),params:ir.loose().optional()}),bt=It({_meta:vh.optional()}),al=qe([k(),Ie().int()]),xS=j({jsonrpc:q(il),id:al,..._t.shape}).strict(),Tn=t=>xS.safeParse(t).success,SS=j({jsonrpc:q(il),...ar.shape}).strict(),$S=t=>SS.safeParse(t).success,_h=j({jsonrpc:q(il),id:al,result:bt}).strict(),en=t=>_h.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(B||(B={}));bh=j({jsonrpc:q(il),id:al.optional(),error:j({code:Ie().int(),message:k(),data:Ve().optional()})}).strict(),ws=t=>bh.safeParse(t).success,Wi=qe([xS,SS,_h,bh]),c5=qe([_h,bh]),cl=bt.strict(),XM=ir.extend({requestId:al.optional(),reason:k().optional()}),ll=ar.extend({method:q("notifications/cancelled"),params:XM}),QM=j({src:k(),mimeType:k().optional(),sizes:xe(k()).optional(),theme:Zt(["light","dark"]).optional()}),Ji=j({icons:xe(QM).optional()}),bs=j({name:k(),title:k().optional()}),kS=bs.extend({...bs.shape,...Ji.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),eL=ol(j({applyDefaults:ft().optional()}),We(k(),Ve())),tL=hh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ol(j({form:eL.optional(),url:vt.optional()}),We(k(),Ve()).optional())),rL=It({list:vt.optional(),cancel:vt.optional(),requests:It({sampling:It({createMessage:vt.optional()}).optional(),elicitation:It({create:vt.optional()}).optional()}).optional()}),nL=It({list:vt.optional(),cancel:vt.optional(),requests:It({tools:It({call:vt.optional()}).optional()}).optional()}),oL=j({experimental:We(k(),vt).optional(),sampling:j({context:vt.optional(),tools:vt.optional()}).optional(),elicitation:tL.optional(),roots:j({listChanged:ft().optional()}).optional(),tasks:rL.optional()}),sL=tr.extend({protocolVersion:k(),capabilities:oL,clientInfo:kS}),ul=_t.extend({method:q("initialize"),params:sL}),wh=t=>ul.safeParse(t).success,iL=j({experimental:We(k(),vt).optional(),logging:vt.optional(),completions:vt.optional(),prompts:j({listChanged:ft().optional()}).optional(),resources:j({subscribe:ft().optional(),listChanged:ft().optional()}).optional(),tools:j({listChanged:ft().optional()}).optional(),tasks:nL.optional()}),aL=bt.extend({protocolVersion:k(),capabilities:iL,serverInfo:kS,instructions:k().optional()}),xh=ar.extend({method:q("notifications/initialized"),params:ir.optional()}),pl=_t.extend({method:q("ping"),params:tr.optional()}),cL=j({progress:Ie(),total:et(Ie()),message:et(k())}),lL=j({...ir.shape,...cL.shape,progressToken:_S}),dl=ar.extend({method:q("notifications/progress"),params:lL}),uL=tr.extend({cursor:bS.optional()}),Ki=_t.extend({params:uL.optional()}),Yi=bt.extend({nextCursor:bS.optional()}),pL=Zt(["working","input_required","completed","failed","cancelled"]),Xi=j({taskId:k(),status:pL,ttl:qe([Ie(),fh()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:et(Ie()),statusMessage:et(k())}),xs=bt.extend({task:Xi}),dL=ir.merge(Xi),Qi=ar.extend({method:q("notifications/tasks/status"),params:dL}),fl=_t.extend({method:q("tasks/get"),params:tr.extend({taskId:k()})}),ml=bt.merge(Xi),hl=_t.extend({method:q("tasks/result"),params:tr.extend({taskId:k()})}),l5=bt.loose(),gl=Ki.extend({method:q("tasks/list")}),yl=Yi.extend({tasks:xe(Xi)}),vl=_t.extend({method:q("tasks/cancel"),params:tr.extend({taskId:k()})}),ES=bt.merge(Xi),TS=j({uri:k(),mimeType:et(k()),_meta:We(k(),Ve()).optional()}),PS=TS.extend({text:k()}),Sh=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),RS=TS.extend({blob:Sh}),ea=Zt(["user","assistant"]),Ss=j({audience:xe(ea).optional(),priority:Ie().min(0).max(1).optional(),lastModified:Hi.datetime({offset:!0}).optional()}),OS=j({...bs.shape,...Ji.shape,uri:k(),description:et(k()),mimeType:et(k()),annotations:Ss.optional(),_meta:et(It({}))}),fL=j({...bs.shape,...Ji.shape,uriTemplate:k(),description:et(k()),mimeType:et(k()),annotations:Ss.optional(),_meta:et(It({}))}),_l=Ki.extend({method:q("resources/list")}),mL=Yi.extend({resources:xe(OS)}),bl=Ki.extend({method:q("resources/templates/list")}),hL=Yi.extend({resourceTemplates:xe(fL)}),$h=tr.extend({uri:k()}),gL=$h,wl=_t.extend({method:q("resources/read"),params:gL}),yL=bt.extend({contents:xe(qe([PS,RS]))}),vL=ar.extend({method:q("notifications/resources/list_changed"),params:ir.optional()}),_L=$h,bL=_t.extend({method:q("resources/subscribe"),params:_L}),wL=$h,xL=_t.extend({method:q("resources/unsubscribe"),params:wL}),SL=ir.extend({uri:k()}),$L=ar.extend({method:q("notifications/resources/updated"),params:SL}),kL=j({name:k(),description:et(k()),required:et(ft())}),EL=j({...bs.shape,...Ji.shape,description:et(k()),arguments:et(xe(kL)),_meta:et(It({}))}),xl=Ki.extend({method:q("prompts/list")}),TL=Yi.extend({prompts:xe(EL)}),PL=tr.extend({name:k(),arguments:We(k(),k()).optional()}),Sl=_t.extend({method:q("prompts/get"),params:PL}),kh=j({type:q("text"),text:k(),annotations:Ss.optional(),_meta:We(k(),Ve()).optional()}),Eh=j({type:q("image"),data:Sh,mimeType:k(),annotations:Ss.optional(),_meta:We(k(),Ve()).optional()}),Th=j({type:q("audio"),data:Sh,mimeType:k(),annotations:Ss.optional(),_meta:We(k(),Ve()).optional()}),RL=j({type:q("tool_use"),name:k(),id:k(),input:We(k(),Ve()),_meta:We(k(),Ve()).optional()}),OL=j({type:q("resource"),resource:qe([PS,RS]),annotations:Ss.optional(),_meta:We(k(),Ve()).optional()}),CL=OS.extend({type:q("resource_link")}),Ph=qe([kh,Eh,Th,CL,OL]),IL=j({role:ea,content:Ph}),AL=bt.extend({description:k().optional(),messages:xe(IL)}),NL=ar.extend({method:q("notifications/prompts/list_changed"),params:ir.optional()}),zL=j({title:k().optional(),readOnlyHint:ft().optional(),destructiveHint:ft().optional(),idempotentHint:ft().optional(),openWorldHint:ft().optional()}),jL=j({taskSupport:Zt(["required","optional","forbidden"]).optional()}),CS=j({...bs.shape,...Ji.shape,description:k().optional(),inputSchema:j({type:q("object"),properties:We(k(),vt).optional(),required:xe(k()).optional()}).catchall(Ve()),outputSchema:j({type:q("object"),properties:We(k(),vt).optional(),required:xe(k()).optional()}).catchall(Ve()).optional(),annotations:zL.optional(),execution:jL.optional(),_meta:We(k(),Ve()).optional()}),$l=Ki.extend({method:q("tools/list")}),ML=Yi.extend({tools:xe(CS)}),kl=bt.extend({content:xe(Ph).default([]),structuredContent:We(k(),Ve()).optional(),isError:ft().optional()}),u5=kl.or(bt.extend({toolResult:Ve()})),LL=Vi.extend({name:k(),arguments:We(k(),Ve()).optional()}),$s=_t.extend({method:q("tools/call"),params:LL}),DL=ar.extend({method:q("notifications/tools/list_changed"),params:ir.optional()}),p5=j({autoRefresh:ft().default(!0),debounceMs:Ie().int().nonnegative().default(300)}),ta=Zt(["debug","info","notice","warning","error","critical","alert","emergency"]),qL=tr.extend({level:ta}),Rh=_t.extend({method:q("logging/setLevel"),params:qL}),ZL=ir.extend({level:ta,logger:k().optional(),data:Ve()}),UL=ar.extend({method:q("notifications/message"),params:ZL}),FL=j({name:k().optional()}),HL=j({hints:xe(FL).optional(),costPriority:Ie().min(0).max(1).optional(),speedPriority:Ie().min(0).max(1).optional(),intelligencePriority:Ie().min(0).max(1).optional()}),BL=j({mode:Zt(["auto","required","none"]).optional()}),GL=j({type:q("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:xe(Ph).default([]),structuredContent:j({}).loose().optional(),isError:ft().optional(),_meta:We(k(),Ve()).optional()}),VL=mh("type",[kh,Eh,Th]),sl=mh("type",[kh,Eh,Th,RL,GL]),WL=j({role:ea,content:qe([sl,xe(sl)]),_meta:We(k(),Ve()).optional()}),JL=Vi.extend({messages:xe(WL),modelPreferences:HL.optional(),systemPrompt:k().optional(),includeContext:Zt(["none","thisServer","allServers"]).optional(),temperature:Ie().optional(),maxTokens:Ie().int(),stopSequences:xe(k()).optional(),metadata:vt.optional(),tools:xe(CS).optional(),toolChoice:BL.optional()}),KL=_t.extend({method:q("sampling/createMessage"),params:JL}),Oh=bt.extend({model:k(),stopReason:et(Zt(["endTurn","stopSequence","maxTokens"]).or(k())),role:ea,content:VL}),Ch=bt.extend({model:k(),stopReason:et(Zt(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:ea,content:qe([sl,xe(sl)])}),YL=j({type:q("boolean"),title:k().optional(),description:k().optional(),default:ft().optional()}),XL=j({type:q("string"),title:k().optional(),description:k().optional(),minLength:Ie().optional(),maxLength:Ie().optional(),format:Zt(["email","uri","date","date-time"]).optional(),default:k().optional()}),QL=j({type:Zt(["number","integer"]),title:k().optional(),description:k().optional(),minimum:Ie().optional(),maximum:Ie().optional(),default:Ie().optional()}),eD=j({type:q("string"),title:k().optional(),description:k().optional(),enum:xe(k()),default:k().optional()}),tD=j({type:q("string"),title:k().optional(),description:k().optional(),oneOf:xe(j({const:k(),title:k()})),default:k().optional()}),rD=j({type:q("string"),title:k().optional(),description:k().optional(),enum:xe(k()),enumNames:xe(k()).optional(),default:k().optional()}),nD=qe([eD,tD]),oD=j({type:q("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({type:q("string"),enum:xe(k())}),default:xe(k()).optional()}),sD=j({type:q("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({anyOf:xe(j({const:k(),title:k()}))}),default:xe(k()).optional()}),iD=qe([oD,sD]),aD=qe([rD,nD,iD]),cD=qe([aD,YL,XL,QL]),lD=Vi.extend({mode:q("form").optional(),message:k(),requestedSchema:j({type:q("object"),properties:We(k(),cD),required:xe(k()).optional()})}),uD=Vi.extend({mode:q("url"),message:k(),elicitationId:k(),url:k().url()}),pD=qe([lD,uD]),dD=_t.extend({method:q("elicitation/create"),params:pD}),fD=ir.extend({elicitationId:k()}),mD=ar.extend({method:q("notifications/elicitation/complete"),params:fD}),El=bt.extend({action:Zt(["accept","decline","cancel"]),content:hh(t=>t===null?void 0:t,We(k(),qe([k(),Ie(),ft(),xe(k())])).optional())}),hD=j({type:q("ref/resource"),uri:k()}),gD=j({type:q("ref/prompt"),name:k()}),yD=tr.extend({ref:qe([gD,hD]),argument:j({name:k(),value:k()}),context:j({arguments:We(k(),k()).optional()}).optional()}),Tl=_t.extend({method:q("completion/complete"),params:yD});vD=bt.extend({completion:It({values:xe(k()).max(100),total:et(Ie().int()),hasMore:et(ft())})}),_D=j({uri:k().startsWith("file://"),name:k().optional(),_meta:We(k(),Ve()).optional()}),bD=_t.extend({method:q("roots/list"),params:tr.optional()}),Ih=bt.extend({roots:xe(_D)}),wD=ar.extend({method:q("notifications/roots/list_changed"),params:ir.optional()}),d5=qe([pl,ul,Tl,Rh,Sl,xl,_l,bl,wl,bL,xL,$s,$l,fl,hl,gl,vl]),f5=qe([ll,dl,xh,wD,Qi]),m5=qe([cl,Oh,Ch,El,Ih,ml,yl,xs]),h5=qe([pl,KL,dD,bD,fl,hl,gl,vl]),g5=qe([ll,dl,UL,$L,vL,DL,NL,Qi,mD]),y5=qe([cl,aL,vD,AL,TL,mL,hL,yL,kl,ML,ml,yl,xs]),D=class t extends Error{constructor(e,r,n){super(`MCP error ${e}: ${r}`),this.code=e,this.data=n,this.name="McpError"}static fromError(e,r,n){if(e===B.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new gh(o.elicitations,r)}return new t(e,r,n)}},gh=class extends D{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function xD(t){return Wi.parse(JSON.parse(t))}function NS(t){return JSON.stringify(t)+`
272
+ `}var Pl,zS=w(()=>{ks();Pl=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
273
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),xD(r)}clear(){this._buffer=void 0}}});import jS from"node:process";var Rl,MS=w(()=>{zS();Rl=class{constructor(e=jS.stdin,r=jS.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Pl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=NS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});import{Http2ServerRequest as SD}from"http2";import{Http2ServerRequest as Ah}from"http2";import{Readable as LS}from"stream";import zD from"crypto";async function ID(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function US(t,e,r){let n=a=>{t.cancel(a).catch(()=>{})};return e.on("close",n),e.on("error",n),(r??t.read()).then(i,o),t.closed.finally(()=>{e.off("close",n),e.off("error",n)});function o(a){a&&e.destroy(a)}function s(){t.read().then(i,o)}function i({done:a,value:c}){try{if(a)e.end();else if(!e.write(c))e.once("drain",s);else return t.read().then(i,o)}catch(l){o(l)}}}function AD(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:US(t.getReader(),e)}var _o,$D,kD,ra,ED,qS,TD,Ps,PD,Ol,Cl,RD,Ts,OD,Il,CD,DS,Es,bo,zh,na,FS,ND,jh,jD,HS,Nh,BS,GS,MD,LD,Mh,VS=w(()=>{_o=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},$D=t=>t instanceof _o?t:new _o(t.message,{cause:t}),kD=global.Request,ra=class extends kD{constructor(t,e){typeof t=="object"&&Ps in t&&(t=t[Ps]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},ED=t=>{let e=[],r=t.rawHeaders;for(let n=0;n<r.length;n+=2){let{[n]:o,[n+1]:s}=r;o.charCodeAt(0)!==58&&e.push([o,s])}return new Headers(e)},qS=Symbol("wrapBodyStream"),TD=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ra(e,s);return Object.defineProperty(i,"method",{get(){return"TRACE"}}),i}if(!(t==="GET"||t==="HEAD"))if("rawBody"in n&&n.rawBody instanceof Buffer)s.body=new ReadableStream({start(i){i.enqueue(n.rawBody),i.close()}});else if(n[qS]){let i;s.body=new ReadableStream({async pull(a){try{i||=LS.toWeb(n).getReader();let{done:c,value:l}=await i.read();c?a.close():a.enqueue(l)}catch(c){a.error(c)}}})}else s.body=LS.toWeb(n);return new ra(e,s)},Ps=Symbol("getRequestCache"),PD=Symbol("requestCache"),Ol=Symbol("incomingKey"),Cl=Symbol("urlKey"),RD=Symbol("headersKey"),Ts=Symbol("abortControllerKey"),OD=Symbol("getAbortController"),Il={get method(){return this[Ol].method||"GET"},get url(){return this[Cl]},get headers(){return this[RD]||=ED(this[Ol])},[OD](){return this[Ps](),this[Ts]},[Ps](){return this[Ts]||=new AbortController,this[PD]||=TD(this.method,this[Cl],this.headers,this[Ol],this[Ts])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Il,t,{get(){return this[Ps]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Il,t,{value:function(){return this[Ps]()[t]()}})});Object.setPrototypeOf(Il,ra.prototype);CD=(t,e)=>{let r=Object.create(Il);r[Ol]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Ah)throw new _o("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Cl]=a.href}catch(a){throw new _o("Invalid absolute URL",{cause:a})}return r}let o=(t instanceof Ah?t.authority:t.headers.host)||e;if(!o)throw new _o("Missing host header");let s;if(t instanceof Ah){if(s=t.scheme,!(s==="http"||s==="https"))throw new _o("Unsupported scheme")}else s=t.socket&&t.socket.encrypted?"https":"http";let i=new URL(`${s}://${o}${n}`);if(i.hostname.length!==o.length&&i.hostname!==o.replace(/:\d+$/,""))throw new _o("Invalid host header");return r[Cl]=i.href,r},DS=Symbol("responseCache"),Es=Symbol("getResponseCache"),bo=Symbol("cache"),zh=global.Response,na=class ZS{#t;#e;[Es](){return delete this[bo],this[DS]||=new zh(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof ZS){let o=r[DS];if(o){this.#e=o,this[Es]();return}else this.#e=r.#e,n=new Headers(r.#e.headers)}else this.#e=r;(typeof e=="string"||typeof e?.getReader<"u"||e instanceof Blob||e instanceof Uint8Array)&&(n||=r?.headers||{"content-type":"text/plain; charset=UTF-8"},this[bo]=[r?.status||200,e,n])}get headers(){let e=this[bo];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[Es]().headers}get status(){return this[bo]?.[0]??this[Es]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(na.prototype,t,{get(){return this[Es]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(na.prototype,t,{value:function(){return this[Es]()[t]()}})});Object.setPrototypeOf(na,zh);Object.setPrototypeOf(na.prototype,zh.prototype);FS=t=>{let e={};t instanceof Headers||(t=new Headers(t??void 0));let r=[];for(let[n,o]of t)n==="set-cookie"?r.push(o):e[n]=o;return r.length>0&&(e["set-cookie"]=r),e["content-type"]??="text/plain; charset=UTF-8",e},ND="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=zD);jh=Symbol("outgoingEnded"),jD=()=>new Response(null,{status:400}),HS=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Nh=(t,e)=>{let r=t instanceof Error?t:new Error("unknown error",{cause:t});r.code==="ERR_STREAM_PREMATURE_CLOSE"?console.info("The user aborted a request."):(console.error(t),e.headersSent||e.writeHead(500,{"Content-Type":"text/plain"}),e.end(`Error: ${r.message}`),e.destroy(r))},BS=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},GS=async(t,e)=>{let[r,n,o]=t[bo];o instanceof Headers&&(o=FS(o)),typeof n=="string"?o["Content-Length"]=Buffer.byteLength(n):n instanceof Uint8Array?o["Content-Length"]=n.byteLength:n instanceof Blob&&(o["Content-Length"]=n.size),e.writeHead(r,o),typeof n=="string"||n instanceof Uint8Array?e.end(n):n instanceof Blob?e.end(new Uint8Array(await n.arrayBuffer())):(BS(e),await AD(n,e)?.catch(s=>Nh(s,e))),e[jh]?.()},MD=t=>typeof t.then=="function",LD=async(t,e,r={})=>{if(MD(t))if(r.errorHandler)try{t=await t}catch(o){let s=await r.errorHandler(o);if(!s)return;t=s}else t=await t.catch(HS);if(bo in t)return GS(t,e);let n=FS(t.headers);if(t.body){let o=t.body.getReader(),s=[],i=!1,a;if(n["transfer-encoding"]!=="chunked"){let c=2;for(let l=0;l<c;l++){a||=o.read();let u=await ID(a).catch(p=>{console.error(p),i=!0});if(!u){if(l===1){await new Promise(p=>setTimeout(p)),c=3;continue}break}if(a=void 0,u.value&&s.push(u.value),u.done){i=!0;break}}i&&!("content-length"in n)&&(n["content-length"]=s.reduce((l,u)=>l+u.length,0))}e.writeHead(t.status,n),s.forEach(c=>{e.write(c)}),i?e.end():(s.length===0&&BS(e),await US(o,e,a))}else n[ND]||(e.writeHead(t.status,n),e.end());e[jh]?.()},Mh=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ra&&(Object.defineProperty(global,"Request",{value:ra}),Object.defineProperty(global,"Response",{value:na})),async(n,o)=>{let s,i;try{i=CD(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[qS]=!0,n.on("end",()=>{a=!0}),n instanceof SD&&(o[jh]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{i[Ts]&&(n.errored?i[Ts].abort(n.errored.toString()):o.writableFinished||i[Ts].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(i,{incoming:n,outgoing:o}),bo in s)return GS(s,o)}catch(a){if(s)return Nh(a,o);if(e.errorHandler){if(s=await e.errorHandler(i?a:$D(a)),!s)return}else i?s=HS(a):s=jD()}try{return await LD(s,o,e)}catch(a){return Nh(a,o)}}}});var Al,WS=w(()=>{ks();Al=class{constructor(e={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(e,r,n,o){let s={code:r,message:n};return o?.data!==void 0&&(s.data=o.data),new Response(JSON.stringify({jsonrpc:"2.0",error:s,id:null}),{status:e,headers:{"Content-Type":"application/json",...o?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=e.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=e.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(e,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case"POST":return this.handlePostRequest(e,r);case"GET":return this.handleGetRequest(e);case"DELETE":return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,r,n,o){if(!this._eventStore||o<"2025-11-25")return;let s=await this._eventStore.storeEvent(n,{}),i=`id: ${s}
274
274
  data:
275
275
 
276
276
  `;this._retryInterval!==void 0&&(i=`id: ${s}
@@ -281,18 +281,18 @@ data:
281
281
  `;return o&&(s+=`id: ${o}
282
282
  `),s+=`data: ${JSON.stringify(n)}
283
283
 
284
- `,e.enqueue(r.encode(s)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!o||!o.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries())},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>Bi.parse(v)):a=[Bi.parse(i)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=a.some(mh);if(c){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let _=this.validateProtocolVersion(e);if(_)return _}if(!a.some(Tn)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let u=crypto.randomUUID(),p=a.find(v=>mh(v)),m=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??lS;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(u,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(u)}});for(let _ of a)Tn(_)&&this._requestToStreamMapping.set(_.id,u);for(let _ of a)this.onmessage?.(_,{authInfo:r?.authInfo,requestInfo:s})});let d=new TextEncoder,f,h=new ReadableStream({start:v=>{f=v},cancel:()=>{this._streamMapping.delete(u)}}),g={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(g["mcp-session-id"]=this.sessionId);for(let v of a)Tn(v)&&(this._streamMapping.set(u,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(u);try{f.close()}catch{}}}),this._requestToStreamMapping.set(v.id,u));await this.writePrimingEvent(f,d,u,m);for(let v of a){let _,x;Tn(v)&&this._eventStore&&m>="2025-11-25"&&(_=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:_,closeStandaloneSSEStream:x})}return new Response(h,{status:200,headers:g})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!Fi.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Fi.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((en(e)||_s(e))&&(n=e.id),n===void 0){if(en(e)||_s(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse&&s?.controller&&s?.encoder){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e)),this.writeSSEEvent(s.controller,s.encoder,e,i)}if(en(e)||_s(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,l])=>l===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let l=i.map(u=>this._requestResponseMap.get(u));l.length===1?s.resolveJson(new Response(JSON.stringify(l[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(l),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c)}}}}});var Ol,qS=w(()=>{LS();DS();Ol=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Rl(e),this._requestListener=Oh(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await Oh(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var _e,Ch,N,Lr,ta=w(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,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 n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(_e||(_e={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ch||(Ch={}));N=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Lr=t=>{switch(typeof t){case"undefined":return N.undefined;case"string":return N.string;case"number":return Number.isNaN(t)?N.nan:N.number;case"boolean":return N.boolean;case"function":return N.function;case"bigint":return N.bigint;case"symbol":return N.symbol;case"object":return Array.isArray(t)?N.array:t===null?N.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?N.promise:typeof Map<"u"&&t instanceof Map?N.map:typeof Set<"u"&&t instanceof Set?N.set:typeof Date<"u"&&t instanceof Date?N.date:N.object;default:return N.unknown}}});var T,vD,Ut,Cl=w(()=>{ta();T=_e.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"]),vD=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ut=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_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)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}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,_e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ut.create=t=>new Ut(t)});var _D,tn,Ih=w(()=>{Cl();ta();_D=(t,e)=>{let r;switch(t.code){case T.invalid_type:t.received===N.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,_e.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:r=`Unrecognized key(s) in object: ${_e.joinValues(t.keys,", ")}`;break;case T.invalid_union:r="Invalid input";break;case T.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${_e.joinValues(t.options)}`;break;case T.invalid_enum_value:r=`Invalid enum value. Expected ${_e.joinValues(t.options)}, received '${t.received}'`;break;case T.invalid_arguments:r="Invalid function arguments";break;case T.invalid_return_type:r="Invalid function return type";break;case T.invalid_date:r="Invalid date";break;case T.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:_e.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case T.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case T.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case T.custom:r="Invalid input";break;case T.invalid_intersection_types:r="Intersection results could not be merged";break;case T.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case T.not_finite:r="Number must be finite";break;default:r=e.defaultError,_e.assertNever(t)}return{message:r}},tn=_D});function bD(t){ZS=t}function Ts(){return ZS}var ZS,Il=w(()=>{Ih();ZS=tn});function A(t,e){let r=Ts(),n=ra({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===tn?void 0:tn].filter(o=>!!o)});t.common.issues.push(n)}var ra,wD,wt,J,bo,Et,Al,Nl,Pn,Ps,Ah=w(()=>{Il();Ih();ra=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},wD=[];wt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return J;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return J;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},J=Object.freeze({status:"aborted"}),bo=t=>({status:"dirty",value:t}),Et=t=>({status:"valid",value:t}),Al=t=>t.status==="aborted",Nl=t=>t.status==="dirty",Pn=t=>t.status==="valid",Ps=t=>typeof Promise<"u"&&t instanceof Promise});var US=w(()=>{});var L,FS=w(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}))});function ae(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))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:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function GS(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function LD(t){return new RegExp(`^${GS(t)}$`)}function WS(t){let e=`${VS}T${GS(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function DD(t,e){return!!((e==="v4"||!e)&&CD.test(t)||(e==="v6"||!e)&&AD.test(t))}function qD(t,e){if(!TD.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function ZD(t,e){return!!((e==="v4"||!e)&&ID.test(t)||(e==="v6"||!e)&&ND.test(t))}function UD(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Rs(t){if(t instanceof Ht){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ft.create(Rs(n))}return new Ht({...t._def,shape:()=>e})}else return t instanceof on?new on({...t._def,type:Rs(t.element)}):t instanceof Ft?Ft.create(Rs(t.unwrap())):t instanceof qr?qr.create(Rs(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>Rs(e))):t}function zh(t,e){let r=Lr(t),n=Lr(e);if(t===e)return{valid:!0,data:t};if(r===N.object&&n===N.object){let o=_e.objectKeys(e),s=_e.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=zh(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===N.array&&n===N.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],c=zh(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===N.date&&n===N.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function JS(t,e){return new Co({values:t,typeName:P.ZodEnum,...ae(e)})}function BS(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function KS(t,e={},r){return t?On.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=BS(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=BS(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):On.create()}var ar,HS,ue,xD,SD,$D,kD,ED,TD,PD,RD,OD,Nh,CD,ID,AD,ND,zD,jD,VS,MD,Rn,wo,xo,So,$o,Os,ko,Eo,On,nn,Sr,Cs,on,Ht,To,rn,zl,Po,Dr,jl,Is,As,Ml,Ro,Oo,Co,Io,Cn,cr,Ft,qr,Ao,No,Ns,FD,na,oa,zo,HD,P,BD,YS,XS,VD,GD,QS,WD,JD,KD,YD,XD,QD,e2,t2,r2,jh,n2,o2,s2,i2,a2,c2,l2,u2,p2,d2,f2,m2,h2,g2,y2,v2,_2,b2,w2,x2,S2,$2,k2,E2,e$=w(()=>{Cl();Il();FS();Ah();ta();ar=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,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}},HS=(t,e)=>{if(Pn(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 r=new Ut(t.common.issues);return this._error=r,this._error}}};ue=class{get description(){return this._def.description}_getType(e){return Lr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new wt,ctx:{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ps(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return HS(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Pn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Pn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Ps(o)?o:Promise.resolve(o));return HS(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:T.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new cr({schema:this,typeName:P.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:r=>this["~validate"](r)}}optional(){return Ft.create(this,this._def)}nullable(){return qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return on.create(this)}promise(){return Cn.create(this,this._def)}or(e){return To.create([this,e],this._def)}and(e){return Po.create(this,e,this._def)}transform(e){return new cr({...ae(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Ao({...ae(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new na({typeName:P.ZodBranded,type:this,...ae(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new No({...ae(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return oa.create(this,e)}readonly(){return zo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},xD=/^c[^\s-]{8,}$/i,SD=/^[0-9a-z]+$/,$D=/^[0-9A-HJKMNP-TV-Z]{26}$/i,kD=/^[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,ED=/^[a-z0-9_-]{21}$/i,TD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,PD=/^[-+]?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)?)??$/,RD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",CD=/^(?:(?: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])$/,ID=/^(?:(?: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])$/,AD=/^(([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]))$/,ND=/^(([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])$/,zD=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,VS="((\\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])))",MD=new RegExp(`^${VS}$`);Rn=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==N.string){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_type,expected:N.string,received:s.parsedType}),J}let n=new wt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.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?A(o,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&A(o,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")RD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"email",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Nh||(Nh=new RegExp(OD,"u")),Nh.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"emoji",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")kD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"uuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")ED.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"nanoid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")xD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")SD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid2",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")$D.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"ulid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),A(o,{validation:"url",code:T.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"regex",code:T.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.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),A(o,{code:T.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?WS(s).test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?MD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?LD(s).test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?PD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"duration",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?DD(e.data,s.version)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"ip",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?qD(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"jwt",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?ZD(e.data,s.version)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"cidr",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?zD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"base64",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?jD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"base64url",code:T.invalid_string,message:s.message}),n.dirty()):_e.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:T.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rn.create=t=>new Rn({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...ae(t)});wo=class t extends ue{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)!==N.number){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_type,expected:N.number,received:s.parsedType}),J}let n,o=new wt;for(let s of this._def.checks)s.kind==="int"?_e.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.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)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?UD(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:s.message}),o.dirty()):_e.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&_e.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};wo.create=t=>new wo({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...ae(t)});xo=class t extends ue{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)!==N.bigint)return this._getInvalidInput(e);let n,o=new wt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.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)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):_e.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return A(r,{code:T.invalid_type,expected:N.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};xo.create=t=>new xo({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...ae(t)});So=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==N.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:N.boolean,received:n.parsedType}),J}return Et(e.data)}};So.create=t=>new So({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...ae(t)});$o=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==N.date){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_type,expected:N.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_date}),J}let n=new wt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):_e.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};$o.create=t=>new $o({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...ae(t)});Os=class extends ue{_parse(e){if(this._getType(e)!==N.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:N.symbol,received:n.parsedType}),J}return Et(e.data)}};Os.create=t=>new Os({typeName:P.ZodSymbol,...ae(t)});ko=class extends ue{_parse(e){if(this._getType(e)!==N.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:N.undefined,received:n.parsedType}),J}return Et(e.data)}};ko.create=t=>new ko({typeName:P.ZodUndefined,...ae(t)});Eo=class extends ue{_parse(e){if(this._getType(e)!==N.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:N.null,received:n.parsedType}),J}return Et(e.data)}};Eo.create=t=>new Eo({typeName:P.ZodNull,...ae(t)});On=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return Et(e.data)}};On.create=t=>new On({typeName:P.ZodAny,...ae(t)});nn=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Et(e.data)}};nn.create=t=>new nn({typeName:P.ZodUnknown,...ae(t)});Sr=class extends ue{_parse(e){let r=this._getOrReturnCtx(e);return A(r,{code:T.invalid_type,expected:N.never,received:r.parsedType}),J}};Sr.create=t=>new Sr({typeName:P.ZodNever,...ae(t)});Cs=class extends ue{_parse(e){if(this._getType(e)!==N.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:N.void,received:n.parsedType}),J}return Et(e.data)}};Cs.create=t=>new Cs({typeName:P.ZodVoid,...ae(t)});on=class t extends ue{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==N.array)return A(r,{code:T.invalid_type,expected:N.array,received:r.parsedType}),J;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(A(r,{code:i?T.too_big:T.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}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(A(r,{code:T.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(A(r,{code:T.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new ar(r,i,r.path,a)))).then(i=>wt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new ar(r,i,r.path,a)));return wt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};on.create=(t,e)=>new on({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...ae(e)});Ht=class t extends ue{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(),r=_e.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==N.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:N.object,received:l.parsedType}),J}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Sr&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new ar(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Sr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(A(o,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new ar(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,m=await u.value;l.push({key:p,value:m,alwaysSet:u.alwaysSet})}return l}).then(l=>wt.mergeObjectSync(n,l)):wt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:L.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:P.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of _e.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of _e.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Rs(this)}partial(e){let r={};for(let n of _e.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of _e.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ft;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return JS(_e.objectKeys(this.shape))}};Ht.create=(t,e)=>new Ht({shape:()=>t,unknownKeys:"strip",catchall:Sr.create(),typeName:P.ZodObject,...ae(e)});Ht.strictCreate=(t,e)=>new Ht({shape:()=>t,unknownKeys:"strict",catchall:Sr.create(),typeName:P.ZodObject,...ae(e)});Ht.lazycreate=(t,e)=>new Ht({shape:t,unknownKeys:"strip",catchall:Sr.create(),typeName:P.ZodObject,...ae(e)});To=class extends ue{_parse(e){let{ctx:r}=this._processInputParams(e),n=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 r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ut(a.ctx.common.issues));return A(r,{code:T.invalid_union,unionErrors:i}),J}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ut(c));return A(r,{code:T.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};To.create=(t,e)=>new To({options:t,typeName:P.ZodUnion,...ae(e)});rn=t=>t instanceof Ro?rn(t.schema):t instanceof cr?rn(t.innerType()):t instanceof Oo?[t.value]:t instanceof Co?t.options:t instanceof Io?_e.objectValues(t.enum):t instanceof Ao?rn(t._def.innerType):t instanceof ko?[void 0]:t instanceof Eo?[null]:t instanceof Ft?[void 0,...rn(t.unwrap())]:t instanceof qr?[null,...rn(t.unwrap())]:t instanceof na||t instanceof zo?rn(t.unwrap()):t instanceof No?rn(t._def.innerType):[],zl=class t extends ue{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==N.object)return A(r,{code:T.invalid_type,expected:N.object,received:r.parsedType}),J;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(A(r,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=rn(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:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ae(n)})}};Po=class extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Al(s)||Al(i))return J;let a=zh(s.value,i.value);return a.valid?((Nl(s)||Nl(i))&&r.dirty(),{status:r.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),J)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Po.create=(t,e,r)=>new Po({left:t,right:e,typeName:P.ZodIntersection,...ae(r)});Dr=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.array)return A(n,{code:T.invalid_type,expected:N.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new ar(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>wt.mergeArray(r,i)):wt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:P.ZodTuple,rest:null,...ae(e)})};jl=class t extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.object)return A(n,{code:T.invalid_type,expected:N.object,received:n.parsedType}),J;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new ar(n,a,n.path,a)),value:i._parse(new ar(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?wt.mergeObjectAsync(r,o):wt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ue?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...ae(n)}):new t({keyType:Rn.create(),valueType:e,typeName:P.ZodRecord,...ae(r)})}},Is=class extends ue{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.map)return A(n,{code:T.invalid_type,expected:N.map,received:n.parsedType}),J;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new ar(n,a,n.path,[l,"key"])),value:s._parse(new ar(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return J;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return J;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Is.create=(t,e,r)=>new Is({valueType:e,keyType:t,typeName:P.ZodMap,...ae(r)});As=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==N.set)return A(n,{code:T.invalid_type,expected:N.set,received:n.parsedType}),J;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(A(n,{code:T.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(A(n,{code:T.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return J;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new ar(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};As.create=(t,e)=>new As({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...ae(e)});Ml=class t extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==N.function)return A(r,{code:T.invalid_type,expected:N.function,received:r.parsedType}),J;function n(a,c){return ra({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),tn].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function o(a,c){return ra({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ts(),tn].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Cn){let a=this;return Et(async function(...c){let l=new Ut([]),u=await a._def.args.parseAsync(c,s).catch(d=>{throw l.addIssue(n(c,d)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(d=>{throw l.addIssue(o(p,d)),l})})}else{let a=this;return Et(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Ut([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new Ut([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dr.create(e).rest(nn.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,r,n){return new t({args:e||Dr.create([]).rest(nn.create()),returns:r||nn.create(),typeName:P.ZodFunction,...ae(n)})}},Ro=class extends ue{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Ro.create=(t,e)=>new Ro({getter:t,typeName:P.ZodLazy,...ae(e)});Oo=class extends ue{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return A(r,{received:r.data,code:T.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};Oo.create=(t,e)=>new Oo({value:t,typeName:P.ZodLiteral,...ae(e)});Co=class t extends ue{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{expected:_e.joinValues(n),received:r.parsedType,code:T.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{received:r.data,code:T.invalid_enum_value,options:n}),J}return Et(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Co.create=JS;Io=class extends ue{_parse(e){let r=_e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==N.string&&n.parsedType!==N.number){let o=_e.objectValues(r);return A(n,{expected:_e.joinValues(o),received:n.parsedType,code:T.invalid_type}),J}if(this._cache||(this._cache=new Set(_e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=_e.objectValues(r);return A(n,{received:n.data,code:T.invalid_enum_value,options:o}),J}return Et(e.data)}get enum(){return this._def.values}};Io.create=(t,e)=>new Io({values:t,typeName:P.ZodNativeEnum,...ae(e)});Cn=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==N.promise&&r.common.async===!1)return A(r,{code:T.invalid_type,expected:N.promise,received:r.parsedType}),J;let n=r.parsedType===N.promise?r.data:Promise.resolve(r.data);return Et(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cn.create=(t,e)=>new Cn({type:t,typeName:P.ZodPromise,...ae(e)});cr=class extends ue{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{A(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return J;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?bo(c.value):r.value==="dirty"?bo(c.value):c});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"?bo(a.value):r.value==="dirty"?bo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Pn(i))return J;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:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Pn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);_e.assertNever(o)}};cr.create=(t,e,r)=>new cr({schema:t,typeName:P.ZodEffects,effect:e,...ae(r)});cr.createWithPreprocess=(t,e,r)=>new cr({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...ae(r)});Ft=class extends ue{_parse(e){return this._getType(e)===N.undefined?Et(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:P.ZodOptional,...ae(e)});qr=class extends ue{_parse(e){return this._getType(e)===N.null?Et(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qr.create=(t,e)=>new qr({innerType:t,typeName:P.ZodNullable,...ae(e)});Ao=class extends ue{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===N.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Ao.create=(t,e)=>new Ao({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ae(e)});No=class extends ue{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ps(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ut(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ut(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};No.create=(t,e)=>new No({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ae(e)});Ns=class extends ue{_parse(e){if(this._getType(e)!==N.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:N.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Ns.create=t=>new Ns({typeName:P.ZodNaN,...ae(t)});FD=Symbol("zod_brand"),na=class extends ue{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},oa=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?(r.dirty(),bo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?J:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},zo=class extends ue{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pn(o)&&(o.value=Object.freeze(o.value)),o);return Ps(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};zo.create=(t,e)=>new zo({innerType:t,typeName:P.ZodReadonly,...ae(e)});HD={object:Ht.lazycreate};(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"})(P||(P={}));BD=(t,e={message:`Input not instance of ${t.name}`})=>KS(r=>r instanceof t,e),YS=Rn.create,XS=wo.create,VD=Ns.create,GD=xo.create,QS=So.create,WD=$o.create,JD=Os.create,KD=ko.create,YD=Eo.create,XD=On.create,QD=nn.create,e2=Sr.create,t2=Cs.create,r2=on.create,jh=Ht.create,n2=Ht.strictCreate,o2=To.create,s2=zl.create,i2=Po.create,a2=Dr.create,c2=jl.create,l2=Is.create,u2=As.create,p2=Ml.create,d2=Ro.create,f2=Oo.create,m2=Co.create,h2=Io.create,g2=Cn.create,y2=cr.create,v2=Ft.create,_2=qr.create,b2=cr.createWithPreprocess,w2=oa.create,x2=()=>YS().optional(),S2=()=>XS().optional(),$2=()=>QS().optional(),k2={string:t=>Rn.create({...t,coerce:!0}),number:t=>wo.create({...t,coerce:!0}),boolean:t=>So.create({...t,coerce:!0}),bigint:t=>xo.create({...t,coerce:!0}),date:t=>$o.create({...t,coerce:!0})},E2=J});var M={};X(M,{BRAND:()=>FD,DIRTY:()=>bo,EMPTY_PATH:()=>wD,INVALID:()=>J,NEVER:()=>E2,OK:()=>Et,ParseStatus:()=>wt,Schema:()=>ue,ZodAny:()=>On,ZodArray:()=>on,ZodBigInt:()=>xo,ZodBoolean:()=>So,ZodBranded:()=>na,ZodCatch:()=>No,ZodDate:()=>$o,ZodDefault:()=>Ao,ZodDiscriminatedUnion:()=>zl,ZodEffects:()=>cr,ZodEnum:()=>Co,ZodError:()=>Ut,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Ml,ZodIntersection:()=>Po,ZodIssueCode:()=>T,ZodLazy:()=>Ro,ZodLiteral:()=>Oo,ZodMap:()=>Is,ZodNaN:()=>Ns,ZodNativeEnum:()=>Io,ZodNever:()=>Sr,ZodNull:()=>Eo,ZodNullable:()=>qr,ZodNumber:()=>wo,ZodObject:()=>Ht,ZodOptional:()=>Ft,ZodParsedType:()=>N,ZodPipeline:()=>oa,ZodPromise:()=>Cn,ZodReadonly:()=>zo,ZodRecord:()=>jl,ZodSchema:()=>ue,ZodSet:()=>As,ZodString:()=>Rn,ZodSymbol:()=>Os,ZodTransformer:()=>cr,ZodTuple:()=>Dr,ZodType:()=>ue,ZodUndefined:()=>ko,ZodUnion:()=>To,ZodUnknown:()=>nn,ZodVoid:()=>Cs,addIssueToContext:()=>A,any:()=>XD,array:()=>r2,bigint:()=>GD,boolean:()=>QS,coerce:()=>k2,custom:()=>KS,date:()=>WD,datetimeRegex:()=>WS,defaultErrorMap:()=>tn,discriminatedUnion:()=>s2,effect:()=>y2,enum:()=>m2,function:()=>p2,getErrorMap:()=>Ts,getParsedType:()=>Lr,instanceof:()=>BD,intersection:()=>i2,isAborted:()=>Al,isAsync:()=>Ps,isDirty:()=>Nl,isValid:()=>Pn,late:()=>HD,lazy:()=>d2,literal:()=>f2,makeIssue:()=>ra,map:()=>l2,nan:()=>VD,nativeEnum:()=>h2,never:()=>e2,null:()=>YD,nullable:()=>_2,number:()=>XS,object:()=>jh,objectUtil:()=>Ch,oboolean:()=>$2,onumber:()=>S2,optional:()=>v2,ostring:()=>x2,pipeline:()=>w2,preprocess:()=>b2,promise:()=>g2,quotelessJson:()=>vD,record:()=>c2,set:()=>u2,setErrorMap:()=>bD,strictObject:()=>n2,string:()=>YS,symbol:()=>JD,transformer:()=>y2,tuple:()=>a2,undefined:()=>KD,union:()=>o2,unknown:()=>QD,util:()=>_e,void:()=>t2});var Ll=w(()=>{Il();Ah();US();ta();e$();Cl()});var sa=w(()=>{Ll()});var Mh=w(()=>{Ct()});function Lh(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new O2(r)}var R2,O2,t$=w(()=>{Ct();Ct();Mh();R2=E("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>af(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>mo(t,r,n),t.parseAsync=async(r,n)=>lf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>ho(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>er(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)}),O2=E("ZodMiniObject",(t,e)=>{Fc.init(t,e),R2.init(t,e),we.defineLazy(t,"shape",()=>e.shape)})});var r$=w(()=>{});var n$=w(()=>{});var o$=w(()=>{});var s$=w(()=>{Ct();Mh();t$();r$();Ct();Bc();n$();o$()});var i$=w(()=>{s$()});var Dh=w(()=>{i$()});function lr(t){return!!t._zod}function jo(t){let e=Object.values(t);if(e.length===0)return Lh({});let r=e.every(lr),n=e.every(o=>!lr(o));if(r)return Lh(t);if(n)return jh(t);throw new Error("Mixed Zod versions detected in object shape.")}function In(t,e){return lr(t)?mo(t,e):t.safeParse(e)}async function Dl(t,e){return lr(t)?await ho(t,e):await t.safeParseAsync(e)}function An(t){if(!t)return;let e;if(lr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function zs(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return jo(t)}}if(lr(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function ql(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function c$(t){return t.description}function l$(t){if(lr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Zl(t){if(lr(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var ia=w(()=>{sa();Dh()});function Nn(t){return t==="completed"||t==="failed"||t==="cancelled"}var u$=w(()=>{});var d$,p$,f$,Ul=w(()=>{d$=Symbol("Let zodToJsonSchema decide on which parser to use"),p$={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},f$=t=>typeof t=="string"?{...p$,name:t}:{...p$,...t}});var m$,qh=w(()=>{Ul();m$=t=>{let e=f$(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Zh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Se(t,e,r,n,o){t[e]=r,Zh(t,e,n,o)}var zn=w(()=>{});var Fl,Hl=w(()=>{Fl=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function Je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Fl(e,t.currentPath):e.join("/")}}var ur=w(()=>{Hl()});function h$(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=K(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Se(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Se(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Se(r,"minItems",t.exactLength.value,t.exactLength.message,e),Se(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Uh=w(()=>{sa();zn();at()});function g$(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Se(r,"minimum",n.value,n.message,e):Se(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Se(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Se(r,"maximum",n.value,n.message,e):Se(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Se(r,"maximum",n.value,n.message,e));break;case"multipleOf":Se(r,"multipleOf",n.value,n.message,e);break}return r}var Fh=w(()=>{zn()});function y$(){return{type:"boolean"}}var Hh=w(()=>{});function Bl(t,e){return K(t.type._def,e)}var Vl=w(()=>{at()});var v$,Bh=w(()=>{at();v$=(t,e)=>K(t.innerType._def,e)});function Vh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Vh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return A2(t,e)}}var A2,Gh=w(()=>{zn();A2=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Se(r,"minimum",n.value,n.message,e);break;case"max":Se(r,"maximum",n.value,n.message,e);break}return r}});function _$(t,e){return{...K(t.innerType._def,e),default:t.defaultValue()}}var Wh=w(()=>{at()});function b$(t,e){return e.effectStrategy==="input"?K(t.schema._def,e):Je(e)}var Jh=w(()=>{at();ur()});function w$(t){return{type:"string",enum:Array.from(t.values)}}var Kh=w(()=>{});function x$(t,e){let r=[K(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),K(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(N2(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var N2,Yh=w(()=>{at();N2=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function S$(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var Xh=w(()=>{});function Gl(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Se(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Se(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":kr(r,"email",n.message,e);break;case"format:idn-email":kr(r,"idn-email",n.message,e);break;case"pattern:zod":At(r,$r.email,n.message,e);break}break;case"url":kr(r,"uri",n.message,e);break;case"uuid":kr(r,"uuid",n.message,e);break;case"regex":At(r,n.regex,n.message,e);break;case"cuid":At(r,$r.cuid,n.message,e);break;case"cuid2":At(r,$r.cuid2,n.message,e);break;case"startsWith":At(r,RegExp(`^${eg(n.value,e)}`),n.message,e);break;case"endsWith":At(r,RegExp(`${eg(n.value,e)}$`),n.message,e);break;case"datetime":kr(r,"date-time",n.message,e);break;case"date":kr(r,"date",n.message,e);break;case"time":kr(r,"time",n.message,e);break;case"duration":kr(r,"duration",n.message,e);break;case"length":Se(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Se(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{At(r,RegExp(eg(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&kr(r,"ipv4",n.message,e),n.version!=="v4"&&kr(r,"ipv6",n.message,e);break}case"base64url":At(r,$r.base64url,n.message,e);break;case"jwt":At(r,$r.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&At(r,$r.ipv4Cidr,n.message,e),n.version!=="v4"&&At(r,$r.ipv6Cidr,n.message,e);break}case"emoji":At(r,$r.emoji(),n.message,e);break;case"ulid":{At(r,$r.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{kr(r,"binary",n.message,e);break}case"contentEncoding:base64":{Se(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{At(r,$r.base64,n.message,e);break}}break}case"nanoid":At(r,$r.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function eg(t,e){return e.patternStrategy==="escape"?j2(t):t}function j2(t){let e="";for(let r=0;r<t.length;r++)z2.has(t[r])||(e+="\\"),e+=t[r];return e}function kr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Se(t,"format",e,r,n)}function At(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:$$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Se(t,"pattern",$$(e,n),r,n)}function $$(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
284
+ `,e.enqueue(r.encode(s)),!0}catch{return!1}}handleUnsupportedRequest(){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(e,r){try{let n=e.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let o=e.headers.get("content-type");if(!o||!o.includes("application/json"))return this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let s={headers:Object.fromEntries(e.headers.entries())},i;if(r?.parsedBody!==void 0)i=r.parsedBody;else try{i=await e.json()}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let a;try{Array.isArray(i)?a=i.map(v=>Wi.parse(v)):a=[Wi.parse(i)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=a.some(wh);if(c){if(this._initialized&&this.sessionId!==void 0)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(a.length>1)return this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!c){let v=this.validateSession(e);if(v)return v;let b=this.validateProtocolVersion(e);if(b)return b}if(!a.some(Tn)){for(let v of a)this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s});return new Response(null,{status:202})}let u=crypto.randomUUID(),p=a.find(v=>wh(v)),f=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??vS;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(u,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(u)}});for(let b of a)Tn(b)&&this._requestToStreamMapping.set(b.id,u);for(let b of a)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:s})});let d=new TextEncoder,m,h=new ReadableStream({start:v=>{m=v},cancel:()=>{this._streamMapping.delete(u)}}),g={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(g["mcp-session-id"]=this.sessionId);for(let v of a)Tn(v)&&(this._streamMapping.set(u,{controller:m,encoder:d,cleanup:()=>{this._streamMapping.delete(u);try{m.close()}catch{}}}),this._requestToStreamMapping.set(v.id,u));await this.writePrimingEvent(m,d,u,f);for(let v of a){let b,x;Tn(v)&&this._eventStore&&f>="2025-11-25"&&(b=()=>{this.closeSSEStream(v.id)},x=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(v,{authInfo:r?.authInfo,requestInfo:s,closeSSEStream:b,closeStandaloneSSEStream:x})}return new Response(h,{status:200,headers:g})}catch(n){return this.onerror?.(n),this.createJsonErrorResponse(400,-32700,"Parse error",{data:String(n)})}}async handleDeleteRequest(e){let r=this.validateSession(e);if(r)return r;let n=this.validateProtocolVersion(e);return n||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Server not initialized");let r=e.headers.get("mcp-session-id");if(!r)return this.createJsonErrorResponse(400,-32e3,"Bad Request: Mcp-Session-Id header is required");if(r!==this.sessionId)return this.createJsonErrorResponse(404,-32001,"Session not found")}validateProtocolVersion(e){let r=e.headers.get("mcp-protocol-version");if(r!==null&&!Gi.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Gi.join(", ")})`)}async close(){this._streamMapping.forEach(({cleanup:e})=>{e()}),this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let r=this._requestToStreamMapping.get(e);if(!r)return;let n=this._streamMapping.get(r);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,r){let n=r?.relatedRequestId;if((en(e)||ws(e))&&(n=e.id),n===void 0){if(en(e)||ws(e))throw new Error("Cannot send a response on a standalone SSE stream unless resuming a previous client request");let i;this._eventStore&&(i=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let a=this._streamMapping.get(this._standaloneSseStreamId);if(a===void 0)return;a.controller&&a.encoder&&this.writeSSEEvent(a.controller,a.encoder,e,i);return}let o=this._requestToStreamMapping.get(n);if(!o)throw new Error(`No connection established for request ID: ${String(n)}`);let s=this._streamMapping.get(o);if(!this._enableJsonResponse&&s?.controller&&s?.encoder){let i;this._eventStore&&(i=await this._eventStore.storeEvent(o,e)),this.writeSSEEvent(s.controller,s.encoder,e,i)}if(en(e)||ws(e)){this._requestResponseMap.set(n,e);let i=Array.from(this._requestToStreamMapping.entries()).filter(([c,l])=>l===o).map(([c])=>c);if(i.every(c=>this._requestResponseMap.has(c))){if(!s)throw new Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&s.resolveJson){let c={"Content-Type":"application/json"};this.sessionId!==void 0&&(c["mcp-session-id"]=this.sessionId);let l=i.map(u=>this._requestResponseMap.get(u));l.length===1?s.resolveJson(new Response(JSON.stringify(l[0]),{status:200,headers:c})):s.resolveJson(new Response(JSON.stringify(l),{status:200,headers:c}))}else s.cleanup();for(let c of i)this._requestResponseMap.delete(c),this._requestToStreamMapping.delete(c)}}}}});var Nl,JS=w(()=>{VS();WS();Nl=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Al(e),this._requestListener=Mh(async r=>{let n=this._requestContext.get(r);return this._webStandardTransport.handleRequest(r,{authInfo:n?.authInfo,parsedBody:n?.parsedBody})},{overrideGlobalObjects:!1})}get sessionId(){return this._webStandardTransport.sessionId}set onclose(e){this._webStandardTransport.onclose=e}get onclose(){return this._webStandardTransport.onclose}set onerror(e){this._webStandardTransport.onerror=e}get onerror(){return this._webStandardTransport.onerror}set onmessage(e){this._webStandardTransport.onmessage=e}get onmessage(){return this._webStandardTransport.onmessage}async start(){return this._webStandardTransport.start()}async close(){return this._webStandardTransport.close()}async send(e,r){return this._webStandardTransport.send(e,r)}async handleRequest(e,r,n){let o=e.auth;await Mh(async i=>this._webStandardTransport.handleRequest(i,{authInfo:o,parsedBody:n}),{overrideGlobalObjects:!1})(e,r)}closeSSEStream(e){this._webStandardTransport.closeSSEStream(e)}closeStandaloneSSEStream(){this._webStandardTransport.closeStandaloneSSEStream()}}});var _e,Lh,z,Lr,oa=w(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,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 n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(_e||(_e={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Lh||(Lh={}));z=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Lr=t=>{switch(typeof t){case"undefined":return z.undefined;case"string":return z.string;case"number":return Number.isNaN(t)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(t)?z.array:t===null?z.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?z.promise:typeof Map<"u"&&t instanceof Map?z.map:typeof Set<"u"&&t instanceof Set?z.set:typeof Date<"u"&&t instanceof Date?z.date:z.object;default:return z.unknown}}});var T,DD,Ut,zl=w(()=>{oa();T=_e.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"]),DD=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ut=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_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)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let l=i.path[c];c===i.path.length-1?(a[l]=a[l]||{_errors:[]},a[l]._errors.push(r(i))):a[l]=a[l]||{_errors:[]},a=a[l],c++}}};return o(this),n}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,_e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};Ut.create=t=>new Ut(t)});var qD,tn,Dh=w(()=>{zl();oa();qD=(t,e)=>{let r;switch(t.code){case T.invalid_type:t.received===z.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case T.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,_e.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:r=`Unrecognized key(s) in object: ${_e.joinValues(t.keys,", ")}`;break;case T.invalid_union:r="Invalid input";break;case T.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${_e.joinValues(t.options)}`;break;case T.invalid_enum_value:r=`Invalid enum value. Expected ${_e.joinValues(t.options)}, received '${t.received}'`;break;case T.invalid_arguments:r="Invalid function arguments";break;case T.invalid_return_type:r="Invalid function return type";break;case T.invalid_date:r="Invalid date";break;case T.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:_e.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case T.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case T.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case T.custom:r="Invalid input";break;case T.invalid_intersection_types:r="Intersection results could not be merged";break;case T.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case T.not_finite:r="Number must be finite";break;default:r=e.defaultError,_e.assertNever(t)}return{message:r}},tn=qD});function ZD(t){KS=t}function Rs(){return KS}var KS,jl=w(()=>{Dh();KS=tn});function A(t,e){let r=Rs(),n=sa({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===tn?void 0:tn].filter(o=>!!o)});t.common.issues.push(n)}var sa,UD,wt,J,wo,Et,Ml,Ll,Pn,Os,qh=w(()=>{jl();Dh();sa=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(l=>!!l).slice().reverse();for(let l of c)a=l(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},UD=[];wt=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return J;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return J;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},J=Object.freeze({status:"aborted"}),wo=t=>({status:"dirty",value:t}),Et=t=>({status:"valid",value:t}),Ml=t=>t.status==="aborted",Ll=t=>t.status==="dirty",Pn=t=>t.status==="valid",Os=t=>typeof Promise<"u"&&t instanceof Promise});var YS=w(()=>{});var L,XS=w(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(L||(L={}))});function ae(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))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:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function r$(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function s2(t){return new RegExp(`^${r$(t)}$`)}function n$(t){let e=`${t$}T${r$(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function i2(t,e){return!!((e==="v4"||!e)&&XD.test(t)||(e==="v6"||!e)&&e2.test(t))}function a2(t,e){if(!WD.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function c2(t,e){return!!((e==="v4"||!e)&&QD.test(t)||(e==="v6"||!e)&&t2.test(t))}function l2(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function Cs(t){if(t instanceof Ht){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Ft.create(Cs(n))}return new Ht({...t._def,shape:()=>e})}else return t instanceof on?new on({...t._def,type:Cs(t.element)}):t instanceof Ft?Ft.create(Cs(t.unwrap())):t instanceof qr?qr.create(Cs(t.unwrap())):t instanceof Dr?Dr.create(t.items.map(e=>Cs(e))):t}function Uh(t,e){let r=Lr(t),n=Lr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=_e.objectKeys(e),s=_e.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Uh(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===z.array&&n===z.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],c=Uh(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===z.date&&n===z.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function o$(t,e){return new Io({values:t,typeName:P.ZodEnum,...ae(e)})}function e$(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function s$(t,e={},r){return t?On.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=e$(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=e$(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):On.create()}var cr,QS,pe,FD,HD,BD,GD,VD,WD,JD,KD,YD,Zh,XD,QD,e2,t2,r2,n2,t$,o2,Rn,xo,So,$o,ko,Is,Eo,To,On,nn,Sr,As,on,Ht,Po,rn,Dl,Ro,Dr,ql,Ns,zs,Zl,Oo,Co,Io,Ao,Cn,lr,Ft,qr,No,zo,js,u2,ia,aa,jo,p2,P,d2,i$,a$,f2,m2,c$,h2,g2,y2,v2,_2,b2,w2,x2,S2,Fh,$2,k2,E2,T2,P2,R2,O2,C2,I2,A2,N2,z2,j2,M2,L2,D2,q2,Z2,U2,F2,H2,B2,G2,V2,l$=w(()=>{zl();jl();XS();qh();oa();cr=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,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}},QS=(t,e)=>{if(Pn(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 r=new Ut(t.common.issues);return this._error=r,this._error}}};pe=class{get description(){return this._def.description}_getType(e){return Lr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new wt,ctx:{common:e.parent.common,data:e.data,parsedType:Lr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Os(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return QS(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Pn(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Pn(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Lr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Os(o)?o:Promise.resolve(o));return QS(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:T.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new lr({schema:this,typeName:P.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:r=>this["~validate"](r)}}optional(){return Ft.create(this,this._def)}nullable(){return qr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return on.create(this)}promise(){return Cn.create(this,this._def)}or(e){return Po.create([this,e],this._def)}and(e){return Ro.create(this,e,this._def)}transform(e){return new lr({...ae(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new No({...ae(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new ia({typeName:P.ZodBranded,type:this,...ae(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new zo({...ae(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return aa.create(this,e)}readonly(){return jo.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},FD=/^c[^\s-]{8,}$/i,HD=/^[0-9a-z]+$/,BD=/^[0-9A-HJKMNP-TV-Z]{26}$/i,GD=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,VD=/^[a-z0-9_-]{21}$/i,WD=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,JD=/^[-+]?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)?)??$/,KD=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,YD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",XD=/^(?:(?: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])$/,QD=/^(?:(?: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])$/,e2=/^(([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]))$/,t2=/^(([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])$/,r2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,n2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,t$="((\\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])))",o2=new RegExp(`^${t$}$`);Rn=class t extends pe{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new wt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.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?A(o,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&A(o,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")KD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"email",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Zh||(Zh=new RegExp(YD,"u")),Zh.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"emoji",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")GD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"uuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")VD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"nanoid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")FD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")HD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"cuid2",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")BD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"ulid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),A(o,{validation:"url",code:T.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"regex",code:T.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.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),A(o,{code:T.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?n$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?o2.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?s2(s).test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{code:T.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?JD.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"duration",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?i2(e.data,s.version)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"ip",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?a2(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"jwt",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?c2(e.data,s.version)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"cidr",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?r2.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"base64",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?n2.test(e.data)||(o=this._getOrReturnCtx(e,o),A(o,{validation:"base64url",code:T.invalid_string,message:s.message}),n.dirty()):_e.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:T.invalid_string,...L.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...L.errToObj(e)})}url(e){return this._addCheck({kind:"url",...L.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...L.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...L.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...L.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...L.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...L.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...L.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...L.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...L.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...L.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...L.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...L.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,...L.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,...L.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...L.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...L.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...L.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...L.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...L.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...L.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...L.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...L.errToObj(r)})}nonempty(e){return this.min(1,L.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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Rn.create=t=>new Rn({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...ae(t)});xo=class t extends pe{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)!==z.number){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new wt;for(let s of this._def.checks)s.kind==="int"?_e.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.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)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?l2(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_finite,message:s.message}),o.dirty()):_e.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:L.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:L.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&_e.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};xo.create=t=>new xo({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...ae(t)});So=class t extends pe{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)!==z.bigint)return this._getInvalidInput(e);let n,o=new wt;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.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)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),A(n,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):_e.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return A(r,{code:T.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,L.toString(r))}gt(e,r){return this.setLimit("min",e,!1,L.toString(r))}lte(e,r){return this.setLimit("max",e,!0,L.toString(r))}lt(e,r){return this.setLimit("max",e,!1,L.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:L.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:L.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:L.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};So.create=t=>new So({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...ae(t)});$o=class extends pe{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:z.boolean,received:n.parsedType}),J}return Et(e.data)}};$o.create=t=>new $o({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...ae(t)});ko=class t extends pe{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return A(s,{code:T.invalid_date}),J}let n=new wt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),A(o,{code:T.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):_e.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:L.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:L.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ko.create=t=>new ko({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...ae(t)});Is=class extends pe{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:z.symbol,received:n.parsedType}),J}return Et(e.data)}};Is.create=t=>new Is({typeName:P.ZodSymbol,...ae(t)});Eo=class extends pe{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:z.undefined,received:n.parsedType}),J}return Et(e.data)}};Eo.create=t=>new Eo({typeName:P.ZodUndefined,...ae(t)});To=class extends pe{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:z.null,received:n.parsedType}),J}return Et(e.data)}};To.create=t=>new To({typeName:P.ZodNull,...ae(t)});On=class extends pe{constructor(){super(...arguments),this._any=!0}_parse(e){return Et(e.data)}};On.create=t=>new On({typeName:P.ZodAny,...ae(t)});nn=class extends pe{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Et(e.data)}};nn.create=t=>new nn({typeName:P.ZodUnknown,...ae(t)});Sr=class extends pe{_parse(e){let r=this._getOrReturnCtx(e);return A(r,{code:T.invalid_type,expected:z.never,received:r.parsedType}),J}};Sr.create=t=>new Sr({typeName:P.ZodNever,...ae(t)});As=class extends pe{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:z.void,received:n.parsedType}),J}return Et(e.data)}};As.create=t=>new As({typeName:P.ZodVoid,...ae(t)});on=class t extends pe{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return A(r,{code:T.invalid_type,expected:z.array,received:r.parsedType}),J;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(A(r,{code:i?T.too_big:T.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}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(A(r,{code:T.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(A(r,{code:T.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new cr(r,i,r.path,a)))).then(i=>wt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new cr(r,i,r.path,a)));return wt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:L.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:L.toString(r)}})}nonempty(e){return this.min(1,e)}};on.create=(t,e)=>new on({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...ae(e)});Ht=class t extends pe{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(),r=_e.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return A(l,{code:T.invalid_type,expected:z.object,received:l.parsedType}),J}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Sr&&this._def.unknownKeys==="strip"))for(let l in o.data)i.includes(l)||a.push(l);let c=[];for(let l of i){let u=s[l],p=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new cr(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Sr){let l=this._def.unknownKeys;if(l==="passthrough")for(let u of a)c.push({key:{status:"valid",value:u},value:{status:"valid",value:o.data[u]}});else if(l==="strict")a.length>0&&(A(o,{code:T.unrecognized_keys,keys:a}),n.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let u of a){let p=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new cr(o,p,o.path,u)),alwaysSet:u in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let u of c){let p=await u.key,f=await u.value;l.push({key:p,value:f,alwaysSet:u.alwaysSet})}return l}).then(l=>wt.mergeObjectSync(n,l)):wt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return L.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:L.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:P.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of _e.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of _e.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Cs(this)}partial(e){let r={};for(let n of _e.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of _e.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Ft;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return o$(_e.objectKeys(this.shape))}};Ht.create=(t,e)=>new Ht({shape:()=>t,unknownKeys:"strip",catchall:Sr.create(),typeName:P.ZodObject,...ae(e)});Ht.strictCreate=(t,e)=>new Ht({shape:()=>t,unknownKeys:"strict",catchall:Sr.create(),typeName:P.ZodObject,...ae(e)});Ht.lazycreate=(t,e)=>new Ht({shape:t,unknownKeys:"strip",catchall:Sr.create(),typeName:P.ZodObject,...ae(e)});Po=class extends pe{_parse(e){let{ctx:r}=this._processInputParams(e),n=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 r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new Ut(a.ctx.common.issues));return A(r,{code:T.invalid_union,unionErrors:i}),J}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let l={...r,common:{...r.common,issues:[]},parent:null},u=c._parseSync({data:r.data,path:r.path,parent:l});if(u.status==="valid")return u;u.status==="dirty"&&!s&&(s={result:u,ctx:l}),l.common.issues.length&&i.push(l.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new Ut(c));return A(r,{code:T.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};Po.create=(t,e)=>new Po({options:t,typeName:P.ZodUnion,...ae(e)});rn=t=>t instanceof Oo?rn(t.schema):t instanceof lr?rn(t.innerType()):t instanceof Co?[t.value]:t instanceof Io?t.options:t instanceof Ao?_e.objectValues(t.enum):t instanceof No?rn(t._def.innerType):t instanceof Eo?[void 0]:t instanceof To?[null]:t instanceof Ft?[void 0,...rn(t.unwrap())]:t instanceof qr?[null,...rn(t.unwrap())]:t instanceof ia||t instanceof jo?rn(t.unwrap()):t instanceof zo?rn(t._def.innerType):[],Dl=class t extends pe{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return A(r,{code:T.invalid_type,expected:z.object,received:r.parsedType}),J;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(A(r,{code:T.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),J)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=rn(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:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...ae(n)})}};Ro=class extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Ml(s)||Ml(i))return J;let a=Uh(s.value,i.value);return a.valid?((Ll(s)||Ll(i))&&r.dirty(),{status:r.value,value:a.data}):(A(n,{code:T.invalid_intersection_types}),J)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Ro.create=(t,e,r)=>new Ro({left:t,right:e,typeName:P.ZodIntersection,...ae(r)});Dr=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return A(n,{code:T.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return A(n,{code:T.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),J;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:T.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new cr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>wt.mergeArray(r,i)):wt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Dr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Dr({items:t,typeName:P.ZodTuple,rest:null,...ae(e)})};ql=class t extends pe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.object)return A(n,{code:T.invalid_type,expected:z.object,received:n.parsedType}),J;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new cr(n,a,n.path,a)),value:i._parse(new cr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?wt.mergeObjectAsync(r,o):wt.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof pe?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...ae(n)}):new t({keyType:Rn.create(),valueType:e,typeName:P.ZodRecord,...ae(r)})}},Ns=class extends pe{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.map)return A(n,{code:T.invalid_type,expected:z.map,received:n.parsedType}),J;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],l)=>({key:o._parse(new cr(n,a,n.path,[l,"key"])),value:s._parse(new cr(n,c,n.path,[l,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let l=await c.key,u=await c.value;if(l.status==="aborted"||u.status==="aborted")return J;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let l=c.key,u=c.value;if(l.status==="aborted"||u.status==="aborted")return J;(l.status==="dirty"||u.status==="dirty")&&r.dirty(),a.set(l.value,u.value)}return{status:r.value,value:a}}}};Ns.create=(t,e,r)=>new Ns({valueType:e,keyType:t,typeName:P.ZodMap,...ae(r)});zs=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return A(n,{code:T.invalid_type,expected:z.set,received:n.parsedType}),J;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(A(n,{code:T.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(A(n,{code:T.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let l=new Set;for(let u of c){if(u.status==="aborted")return J;u.status==="dirty"&&r.dirty(),l.add(u.value)}return{status:r.value,value:l}}let a=[...n.data.values()].map((c,l)=>s._parse(new cr(n,c,n.path,l)));return n.common.async?Promise.all(a).then(c=>i(c)):i(a)}min(e,r){return new t({...this._def,minSize:{value:e,message:L.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:L.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};zs.create=(t,e)=>new zs({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...ae(e)});Zl=class t extends pe{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return A(r,{code:T.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return sa({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Rs(),tn].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function o(a,c){return sa({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Rs(),tn].filter(l=>!!l),issueData:{code:T.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Cn){let a=this;return Et(async function(...c){let l=new Ut([]),u=await a._def.args.parseAsync(c,s).catch(d=>{throw l.addIssue(n(c,d)),l}),p=await Reflect.apply(i,this,u);return await a._def.returns._def.type.parseAsync(p,s).catch(d=>{throw l.addIssue(o(p,d)),l})})}else{let a=this;return Et(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Ut([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new Ut([o(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:Dr.create(e).rest(nn.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,r,n){return new t({args:e||Dr.create([]).rest(nn.create()),returns:r||nn.create(),typeName:P.ZodFunction,...ae(n)})}},Oo=class extends pe{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Oo.create=(t,e)=>new Oo({getter:t,typeName:P.ZodLazy,...ae(e)});Co=class extends pe{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return A(r,{received:r.data,code:T.invalid_literal,expected:this._def.value}),J}return{status:"valid",value:e.data}}get value(){return this._def.value}};Co.create=(t,e)=>new Co({value:t,typeName:P.ZodLiteral,...ae(e)});Io=class t extends pe{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{expected:_e.joinValues(n),received:r.parsedType,code:T.invalid_type}),J}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{received:r.data,code:T.invalid_enum_value,options:n}),J}return Et(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};Io.create=o$;Ao=class extends pe{_parse(e){let r=_e.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=_e.objectValues(r);return A(n,{expected:_e.joinValues(o),received:n.parsedType,code:T.invalid_type}),J}if(this._cache||(this._cache=new Set(_e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=_e.objectValues(r);return A(n,{received:n.data,code:T.invalid_enum_value,options:o}),J}return Et(e.data)}get enum(){return this._def.values}};Ao.create=(t,e)=>new Ao({values:t,typeName:P.ZodNativeEnum,...ae(e)});Cn=class extends pe{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return A(r,{code:T.invalid_type,expected:z.promise,received:r.parsedType}),J;let n=r.parsedType===z.promise?r.data:Promise.resolve(r.data);return Et(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Cn.create=(t,e)=>new Cn({type:t,typeName:P.ZodPromise,...ae(e)});lr=class extends pe{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{A(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return J;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?J:c.status==="dirty"?wo(c.value):r.value==="dirty"?wo(c.value):c});{if(r.value==="aborted")return J;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?J:a.status==="dirty"?wo(a.value):r.value==="dirty"?wo(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?J:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Pn(i))return J;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:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Pn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);_e.assertNever(o)}};lr.create=(t,e,r)=>new lr({schema:t,typeName:P.ZodEffects,effect:e,...ae(r)});lr.createWithPreprocess=(t,e,r)=>new lr({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...ae(r)});Ft=class extends pe{_parse(e){return this._getType(e)===z.undefined?Et(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ft.create=(t,e)=>new Ft({innerType:t,typeName:P.ZodOptional,...ae(e)});qr=class extends pe{_parse(e){return this._getType(e)===z.null?Et(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};qr.create=(t,e)=>new qr({innerType:t,typeName:P.ZodNullable,...ae(e)});No=class extends pe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===z.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};No.create=(t,e)=>new No({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ae(e)});zo=class extends pe{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Os(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ut(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ut(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};zo.create=(t,e)=>new zo({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ae(e)});js=class extends pe{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return A(n,{code:T.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};js.create=t=>new js({typeName:P.ZodNaN,...ae(t)});u2=Symbol("zod_brand"),ia=class extends pe{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},aa=class t extends pe{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?J:s.status==="dirty"?(r.dirty(),wo(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?J:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},jo=class extends pe{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pn(o)&&(o.value=Object.freeze(o.value)),o);return Os(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};jo.create=(t,e)=>new jo({innerType:t,typeName:P.ZodReadonly,...ae(e)});p2={object:Ht.lazycreate};(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"})(P||(P={}));d2=(t,e={message:`Input not instance of ${t.name}`})=>s$(r=>r instanceof t,e),i$=Rn.create,a$=xo.create,f2=js.create,m2=So.create,c$=$o.create,h2=ko.create,g2=Is.create,y2=Eo.create,v2=To.create,_2=On.create,b2=nn.create,w2=Sr.create,x2=As.create,S2=on.create,Fh=Ht.create,$2=Ht.strictCreate,k2=Po.create,E2=Dl.create,T2=Ro.create,P2=Dr.create,R2=ql.create,O2=Ns.create,C2=zs.create,I2=Zl.create,A2=Oo.create,N2=Co.create,z2=Io.create,j2=Ao.create,M2=Cn.create,L2=lr.create,D2=Ft.create,q2=qr.create,Z2=lr.createWithPreprocess,U2=aa.create,F2=()=>i$().optional(),H2=()=>a$().optional(),B2=()=>c$().optional(),G2={string:t=>Rn.create({...t,coerce:!0}),number:t=>xo.create({...t,coerce:!0}),boolean:t=>$o.create({...t,coerce:!0}),bigint:t=>So.create({...t,coerce:!0}),date:t=>ko.create({...t,coerce:!0})},V2=J});var M={};K(M,{BRAND:()=>u2,DIRTY:()=>wo,EMPTY_PATH:()=>UD,INVALID:()=>J,NEVER:()=>V2,OK:()=>Et,ParseStatus:()=>wt,Schema:()=>pe,ZodAny:()=>On,ZodArray:()=>on,ZodBigInt:()=>So,ZodBoolean:()=>$o,ZodBranded:()=>ia,ZodCatch:()=>zo,ZodDate:()=>ko,ZodDefault:()=>No,ZodDiscriminatedUnion:()=>Dl,ZodEffects:()=>lr,ZodEnum:()=>Io,ZodError:()=>Ut,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Zl,ZodIntersection:()=>Ro,ZodIssueCode:()=>T,ZodLazy:()=>Oo,ZodLiteral:()=>Co,ZodMap:()=>Ns,ZodNaN:()=>js,ZodNativeEnum:()=>Ao,ZodNever:()=>Sr,ZodNull:()=>To,ZodNullable:()=>qr,ZodNumber:()=>xo,ZodObject:()=>Ht,ZodOptional:()=>Ft,ZodParsedType:()=>z,ZodPipeline:()=>aa,ZodPromise:()=>Cn,ZodReadonly:()=>jo,ZodRecord:()=>ql,ZodSchema:()=>pe,ZodSet:()=>zs,ZodString:()=>Rn,ZodSymbol:()=>Is,ZodTransformer:()=>lr,ZodTuple:()=>Dr,ZodType:()=>pe,ZodUndefined:()=>Eo,ZodUnion:()=>Po,ZodUnknown:()=>nn,ZodVoid:()=>As,addIssueToContext:()=>A,any:()=>_2,array:()=>S2,bigint:()=>m2,boolean:()=>c$,coerce:()=>G2,custom:()=>s$,date:()=>h2,datetimeRegex:()=>n$,defaultErrorMap:()=>tn,discriminatedUnion:()=>E2,effect:()=>L2,enum:()=>z2,function:()=>I2,getErrorMap:()=>Rs,getParsedType:()=>Lr,instanceof:()=>d2,intersection:()=>T2,isAborted:()=>Ml,isAsync:()=>Os,isDirty:()=>Ll,isValid:()=>Pn,late:()=>p2,lazy:()=>A2,literal:()=>N2,makeIssue:()=>sa,map:()=>O2,nan:()=>f2,nativeEnum:()=>j2,never:()=>w2,null:()=>v2,nullable:()=>q2,number:()=>a$,object:()=>Fh,objectUtil:()=>Lh,oboolean:()=>B2,onumber:()=>H2,optional:()=>D2,ostring:()=>F2,pipeline:()=>U2,preprocess:()=>Z2,promise:()=>M2,quotelessJson:()=>DD,record:()=>R2,set:()=>C2,setErrorMap:()=>ZD,strictObject:()=>$2,string:()=>i$,symbol:()=>g2,transformer:()=>L2,tuple:()=>P2,undefined:()=>y2,union:()=>k2,unknown:()=>b2,util:()=>_e,void:()=>x2});var Ul=w(()=>{jl();qh();YS();oa();l$();zl()});var ca=w(()=>{Ul()});var Hh=w(()=>{Ct()});function Bh(t,e){let r={type:"object",get shape(){return we.assignProp(this,"shape",{...t}),this.shape},...we.normalizeParams(e)};return new Y2(r)}var K2,Y2,u$=w(()=>{Ct();Ct();Hh();K2=E("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");Ae.init(t,e),t.def=e,t.parse=(r,n)=>mf(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ho(t,r,n),t.parseAsync=async(r,n)=>gf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>go(t,r,n),t.check=(...r)=>t.clone({...e,checks:[...e.checks??[],...r.map(n=>typeof n=="function"?{_zod:{check:n,def:{check:"custom"},onattach:[]}}:n)]}),t.clone=(r,n)=>er(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)}),Y2=E("ZodMiniObject",(t,e)=>{Vc.init(t,e),K2.init(t,e),we.defineLazy(t,"shape",()=>e.shape)})});var p$=w(()=>{});var d$=w(()=>{});var f$=w(()=>{});var m$=w(()=>{Ct();Hh();u$();p$();Ct();Jc();d$();f$()});var h$=w(()=>{m$()});var Gh=w(()=>{h$()});function ur(t){return!!t._zod}function Mo(t){let e=Object.values(t);if(e.length===0)return Bh({});let r=e.every(ur),n=e.every(o=>!ur(o));if(r)return Bh(t);if(n)return Fh(t);throw new Error("Mixed Zod versions detected in object shape.")}function In(t,e){return ur(t)?ho(t,e):t.safeParse(e)}async function Fl(t,e){return ur(t)?await go(t,e):await t.safeParseAsync(e)}function An(t){if(!t)return;let e;if(ur(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ms(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Mo(t)}}if(ur(t)){let r=t._zod?.def;if(r&&(r.type==="object"||r.shape!==void 0))return t}else if(t.shape!==void 0)return t}}function Hl(t){if(t&&typeof t=="object"){if("message"in t&&typeof t.message=="string")return t.message;if("issues"in t&&Array.isArray(t.issues)&&t.issues.length>0){let e=t.issues[0];if(e&&typeof e=="object"&&"message"in e)return String(e.message)}try{return JSON.stringify(t)}catch{return String(t)}}return String(t)}function y$(t){return t.description}function v$(t){if(ur(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Bl(t){if(ur(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var la=w(()=>{ca();Gh()});function Nn(t){return t==="completed"||t==="failed"||t==="cancelled"}var _$=w(()=>{});var w$,b$,x$,Gl=w(()=>{w$=Symbol("Let zodToJsonSchema decide on which parser to use"),b$={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},x$=t=>typeof t=="string"?{...b$,name:t}:{...b$,...t}});var S$,Vh=w(()=>{Gl();S$=t=>{let e=x$(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function Wh(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function Se(t,e,r,n,o){t[e]=r,Wh(t,e,n,o)}var zn=w(()=>{});var Vl,Wl=w(()=>{Vl=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function Je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Vl(e,t.currentPath):e.join("/")}}var pr=w(()=>{Wl()});function $$(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=Y(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Se(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Se(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Se(r,"minItems",t.exactLength.value,t.exactLength.message,e),Se(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Jh=w(()=>{ca();zn();at()});function k$(t,e){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"min":e.target==="jsonSchema7"?n.inclusive?Se(r,"minimum",n.value,n.message,e):Se(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Se(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Se(r,"maximum",n.value,n.message,e):Se(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Se(r,"maximum",n.value,n.message,e));break;case"multipleOf":Se(r,"multipleOf",n.value,n.message,e);break}return r}var Kh=w(()=>{zn()});function E$(){return{type:"boolean"}}var Yh=w(()=>{});function Jl(t,e){return Y(t.type._def,e)}var Kl=w(()=>{at()});var T$,Xh=w(()=>{at();T$=(t,e)=>Y(t.innerType._def,e)});function Qh(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>Qh(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return eq(t,e)}}var eq,eg=w(()=>{zn();eq=(t,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let n of t.checks)switch(n.kind){case"min":Se(r,"minimum",n.value,n.message,e);break;case"max":Se(r,"maximum",n.value,n.message,e);break}return r}});function P$(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var tg=w(()=>{at()});function R$(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Je(e)}var rg=w(()=>{at();pr()});function O$(t){return{type:"string",enum:Array.from(t.values)}}var ng=w(()=>{});function C$(t,e){let r=[Y(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),Y(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(tq(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var tq,og=w(()=>{at();tq=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function I$(t,e){let r=typeof t.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[t.value]}:{type:r==="bigint"?"integer":r,const:t.value}}var sg=w(()=>{});function Yl(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":Se(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":Se(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"email":switch(e.emailStrategy){case"format:email":kr(r,"email",n.message,e);break;case"format:idn-email":kr(r,"idn-email",n.message,e);break;case"pattern:zod":At(r,$r.email,n.message,e);break}break;case"url":kr(r,"uri",n.message,e);break;case"uuid":kr(r,"uuid",n.message,e);break;case"regex":At(r,n.regex,n.message,e);break;case"cuid":At(r,$r.cuid,n.message,e);break;case"cuid2":At(r,$r.cuid2,n.message,e);break;case"startsWith":At(r,RegExp(`^${ag(n.value,e)}`),n.message,e);break;case"endsWith":At(r,RegExp(`${ag(n.value,e)}$`),n.message,e);break;case"datetime":kr(r,"date-time",n.message,e);break;case"date":kr(r,"date",n.message,e);break;case"time":kr(r,"time",n.message,e);break;case"duration":kr(r,"duration",n.message,e);break;case"length":Se(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),Se(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{At(r,RegExp(ag(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&kr(r,"ipv4",n.message,e),n.version!=="v4"&&kr(r,"ipv6",n.message,e);break}case"base64url":At(r,$r.base64url,n.message,e);break;case"jwt":At(r,$r.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&At(r,$r.ipv4Cidr,n.message,e),n.version!=="v4"&&At(r,$r.ipv6Cidr,n.message,e);break}case"emoji":At(r,$r.emoji(),n.message,e);break;case"ulid":{At(r,$r.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{kr(r,"binary",n.message,e);break}case"contentEncoding:base64":{Se(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{At(r,$r.base64,n.message,e);break}}break}case"nanoid":At(r,$r.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function ag(t,e){return e.patternStrategy==="escape"?nq(t):t}function nq(t){let e="";for(let r=0;r<t.length;r++)rq.has(t[r])||(e+="\\"),e+=t[r];return e}function kr(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):Se(t,"format",e,r,n)}function At(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:A$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):Se(t,"pattern",A$(e,n),r,n)}function A$(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
285
285
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
286
286
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
287
287
  `:`[${n[c]}\r
288
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var Qh,$r,z2,Wl=w(()=>{zn();$r={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Qh===void 0&&(Qh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Qh),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};z2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Jl(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Gl(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Bl(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var Kl=w(()=>{sa();at();Wl();Vl();ur()});function k$(t,e){if(e.mapStrategy==="record")return Jl(t,e);let r=K(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Je(e),n=K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var tg=w(()=>{at();Kl();ur()});function E$(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var rg=w(()=>{});function T$(t){return t.target==="openAi"?void 0:{not:Je({...t,currentPath:[...t.currentPath,"not"]})}}var ng=w(()=>{ur()});function P$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var og=w(()=>{});function O$(t,e){if(e.target==="openApi3")return R$(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in aa&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=aa[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return R$(t,e)}var aa,R$,Yl=w(()=>{at();aa={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};R$=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>K(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function C$(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:aa[t.innerType._def.typeName],nullable:!0}:{type:[aa[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=K(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var sg=w(()=>{at();Yl()});function I$(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Zh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Se(r,"minimum",n.value,n.message,e):Se(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Se(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Se(r,"maximum",n.value,n.message,e):Se(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Se(r,"maximum",n.value,n.message,e));break;case"multipleOf":Se(r,"multipleOf",n.value,n.message,e);break}return r}var ig=w(()=>{zn()});function A$(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=L2(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=K(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=M2(t,e);return i!==void 0&&(n.additionalProperties=i),n}function M2(t,e){if(t.catchall._def.typeName!=="ZodNever")return K(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function L2(t){try{return t.isOptional()}catch{return!0}}var ag=w(()=>{at()});var N$,cg=w(()=>{at();ur();N$=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return K(t.innerType._def,e);let r=K(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Je(e)},r]}:Je(e)}});var z$,lg=w(()=>{at();z$=(t,e)=>{if(e.pipeStrategy==="input")return K(t.in._def,e);if(e.pipeStrategy==="output")return K(t.out._def,e);let r=K(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=K(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function j$(t,e){return K(t.type._def,e)}var ug=w(()=>{at()});function M$(t,e){let n={type:"array",uniqueItems:!0,items:K(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Se(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Se(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var pg=w(()=>{zn();at()});function L$(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:K(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>K(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var dg=w(()=>{at()});function D$(t){return{not:Je(t)}}var fg=w(()=>{ur()});function q$(t){return Je(t)}var mg=w(()=>{ur()});var Z$,hg=w(()=>{at();Z$=(t,e)=>K(t.innerType._def,e)});var U$,gg=w(()=>{sa();ur();Uh();Fh();Hh();Vl();Bh();Gh();Wh();Jh();Kh();Yh();Xh();tg();rg();ng();og();sg();ig();ag();cg();lg();ug();Kl();pg();Wl();dg();fg();Yl();mg();hg();U$=(t,e,r)=>{switch(e){case P.ZodString:return Gl(t,r);case P.ZodNumber:return I$(t,r);case P.ZodObject:return A$(t,r);case P.ZodBigInt:return g$(t,r);case P.ZodBoolean:return y$();case P.ZodDate:return Vh(t,r);case P.ZodUndefined:return D$(r);case P.ZodNull:return P$(r);case P.ZodArray:return h$(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return O$(t,r);case P.ZodIntersection:return x$(t,r);case P.ZodTuple:return L$(t,r);case P.ZodRecord:return Jl(t,r);case P.ZodLiteral:return S$(t,r);case P.ZodEnum:return w$(t);case P.ZodNativeEnum:return E$(t);case P.ZodNullable:return C$(t,r);case P.ZodOptional:return N$(t,r);case P.ZodMap:return k$(t,r);case P.ZodSet:return M$(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return j$(t,r);case P.ZodNaN:case P.ZodNever:return T$(r);case P.ZodEffects:return b$(t,r);case P.ZodAny:return Je(r);case P.ZodUnknown:return q$(r);case P.ZodDefault:return _$(t,r);case P.ZodBranded:return Bl(t,r);case P.ZodReadonly:return Z$(t,r);case P.ZodCatch:return v$(t,r);case P.ZodPipeline:return z$(t,r);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(n=>{})(e)}}});function K(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==d$)return a}if(n&&!r){let a=D2(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=U$(t,t.typeName,e),i=typeof s=="function"?K(s(),e):s;if(i&&q2(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var D2,q2,at=w(()=>{Ul();gg();Hl();ur();D2=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Fl(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Je(e)):e.$refStrategy==="seen"?Je(e):void 0}},q2=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var F$=w(()=>{});var yg,vg=w(()=>{at();qh();ur();yg=(t,e)=>{let r=m$(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:K(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Je(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=K(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Je(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var H$=w(()=>{Ul();qh();zn();Hl();at();F$();ur();Uh();Fh();Hh();Vl();Bh();Gh();Wh();Jh();Kh();Yh();Xh();tg();rg();ng();og();sg();ig();ag();cg();lg();ug();hg();Kl();pg();Wl();dg();fg();Yl();mg();gg();vg();vg()});function Z2(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function _g(t,e){return lr(t)?Wm(t,{target:Z2(e?.target),io:e?.pipeStrategy??"input"}):yg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function bg(t){let r=An(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zl(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function wg(t,e){let r=In(t,e);if(!r.success)throw r.error;return r.data}var xg=w(()=>{Dh();ia();H$()});function B$(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function V$(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];B$(i)&&B$(s)?r[o]={...i,...s}:r[o]=s}return r}var U2,Xl,G$=w(()=>{ia();Ss();u$();xg();U2=6e4,Xl=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(sl,r=>{this._oncancel(r)}),this.setNotificationHandler(cl,r=>{this._onprogress(r)}),this.setRequestHandler(al,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(ll,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(B.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(pl,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,m=new D(p.error.code,p.error.message,p.error.data);u(m)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new D(B.InvalidParams,`Task not found: ${s}`);if(!Nn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Nn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[En]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(dl,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new D(B.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(ml,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(B.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nn(o.status))throw new D(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new D(B.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof D?o:new D(B.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),D.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),en(s)||_s(s)?this._onresponse(s):Tn(s)?this._onrequest(s,i):hS(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=D.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[En]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:B.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=dS(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,m)=>{if(i.signal.aborted)throw new D(B.ConnectionClosed,"Request was cancelled");let d={...m,relatedRequestId:e.id};s&&!d.relatedTask&&(d.relatedTask={taskId:s});let f=d.relatedTask?.taskId??s;return f&&c&&await c.updateTaskStatus(f,"input_required"),await this.request(u,p,d)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:B.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),en(e))n(e);else{let i=new D(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(en(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),en(e))o(e);else{let i=D.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof D?i:new D(B.InternalError,String(i))}}return}let s;try{let i=await this.request(e,bs,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new D(B.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Nn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new D(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new D(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof D?i:new D(B.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=_=>{u(_)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){p(_);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(d.params={...d.params,task:a}),c&&(d.params={...d.params,_meta:{...d.params?._meta||{},[En]:c}});let f=_=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let x=_ instanceof D?_:new D(B.RequestTimeout,String(_));u(x)};this._responseHandlers.set(m,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return u(_);try{let x=In(r,_.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),n?.signal?.addEventListener("abort",()=>{f(n?.signal?.reason)});let h=n?.timeout??U2,g=()=>f(D.fromError(B.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let _=x=>{let k=this._responseHandlers.get(m);k?k(x):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,_),this._enqueueTaskMessage(v,{type:"request",message:d,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(m),u(x)})}else this._transport.send(d,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(m),u(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ul,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},fl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},yS,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=bg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=wg(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=bg(e);this._notificationHandlers.set(n,o=>{let s=wg(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Tn(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new D(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new D(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new D(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new D(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Ki.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Nn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new D(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Nn(a.status))throw new D(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Ki.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Nn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ua=O(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.regexpCode=Te.getEsmExportName=Te.getProperty=Te.safeStringify=Te.stringify=Te.strConcat=Te.addCodeArg=Te.str=Te._=Te.nil=Te._Code=Te.Name=Te.IDENTIFIER=Te._CodeOrName=void 0;var ca=class{};Te._CodeOrName=ca;Te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Mo=class extends ca{constructor(e){if(super(),!Te.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Te.Name=Mo;var pr=class extends ca{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Mo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Te._Code=pr;Te.nil=new pr("");function W$(t,...e){let r=[t[0]],n=0;for(;n<e.length;)$g(r,e[n]),r.push(t[++n]);return new pr(r)}Te._=W$;var Sg=new pr("+");function J$(t,...e){let r=[la(t[0])],n=0;for(;n<e.length;)r.push(Sg),$g(r,e[n]),r.push(Sg,la(t[++n]));return F2(r),new pr(r)}Te.str=J$;function $g(t,e){e instanceof pr?t.push(...e._items):e instanceof Mo?t.push(e):t.push(V2(e))}Te.addCodeArg=$g;function F2(t){let e=1;for(;e<t.length-1;){if(t[e]===Sg){let r=H2(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function H2(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Mo||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Mo))return`"${t}${e.slice(1)}`}function B2(t,e){return e.emptyStr()?t:t.emptyStr()?e:J$`${t}${e}`}Te.strConcat=B2;function V2(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:la(Array.isArray(t)?t.join(","):t)}function G2(t){return new pr(la(t))}Te.stringify=G2;function la(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Te.safeStringify=la;function W2(t){return typeof t=="string"&&Te.IDENTIFIER.test(t)?new pr(`.${t}`):W$`[${t}]`}Te.getProperty=W2;function J2(t){if(typeof t=="string"&&Te.IDENTIFIER.test(t))return new pr(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Te.getEsmExportName=J2;function K2(t){return new pr(t.toString())}Te.regexpCode=K2});var Tg=O(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.ValueScope=Vt.ValueScopeName=Vt.Scope=Vt.varKinds=Vt.UsedValueState=void 0;var Bt=ua(),kg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},Ql;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(Ql||(Vt.UsedValueState=Ql={}));Vt.varKinds={const:new Bt.Name("const"),let:new Bt.Name("let"),var:new Bt.Name("var")};var eu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Bt.Name?e:this.name(e)}name(e){return new Bt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Vt.Scope=eu;var tu=class extends Bt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Bt._)`.${new Bt.Name(r)}[${n}]`}};Vt.ValueScopeName=tu;var Y2=(0,Bt._)`\n`,Eg=class extends eu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Y2:Bt.nil}}get(){return this._scope}name(e){return new tu(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Bt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Bt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,Ql.Started);let u=r(l);if(u){let p=this.opts.es5?Vt.varKinds.var:Vt.varKinds.const;s=(0,Bt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Bt._)`${s}${u}${this.opts._n}`;else throw new kg(l);c.set(l,Ql.Completed)})}return s}};Vt.ValueScope=Eg});var pe=O(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.or=he.and=he.not=he.CodeGen=he.operators=he.varKinds=he.ValueScopeName=he.ValueScope=he.Scope=he.Name=he.regexpCode=he.stringify=he.getProperty=he.nil=he.strConcat=he.str=he._=void 0;var $e=ua(),Er=Tg(),jn=ua();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return jn._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return jn.str}});Object.defineProperty(he,"strConcat",{enumerable:!0,get:function(){return jn.strConcat}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return jn.nil}});Object.defineProperty(he,"getProperty",{enumerable:!0,get:function(){return jn.getProperty}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return jn.stringify}});Object.defineProperty(he,"regexpCode",{enumerable:!0,get:function(){return jn.regexpCode}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return jn.Name}});var su=Tg();Object.defineProperty(he,"Scope",{enumerable:!0,get:function(){return su.Scope}});Object.defineProperty(he,"ValueScope",{enumerable:!0,get:function(){return su.ValueScope}});Object.defineProperty(he,"ValueScopeName",{enumerable:!0,get:function(){return su.ValueScopeName}});Object.defineProperty(he,"varKinds",{enumerable:!0,get:function(){return su.varKinds}});he.operators={GT:new $e._Code(">"),GTE:new $e._Code(">="),LT:new $e._Code("<"),LTE:new $e._Code("<="),EQ:new $e._Code("==="),NEQ:new $e._Code("!=="),NOT:new $e._Code("!"),OR:new $e._Code("||"),AND:new $e._Code("&&"),ADD:new $e._Code("+")};var sn=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Pg=class extends sn{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Er.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ms(this.rhs,e,r)),this}get names(){return this.rhs instanceof $e._CodeOrName?this.rhs.names:{}}},ru=class extends sn{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof $e.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ms(this.rhs,e,r),this}get names(){let e=this.lhs instanceof $e.Name?{}:{...this.lhs.names};return ou(e,this.rhs)}},Rg=class extends ru{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Og=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Cg=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ig=class extends sn{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ag=class extends sn{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Ms(this.code,e,r),this}get names(){return this.code instanceof $e._CodeOrName?this.code.names:{}}},pa=class extends sn{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(X2(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>qo(e,r.names),{})}},an=class extends pa{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Ng=class extends pa{},js=class extends an{};js.kind="else";var Lo=class t extends an{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new js(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(K$(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Ms(this.condition,e,r),this}get names(){let e=super.names;return ou(e,this.condition),this.else&&qo(e,this.else.names),e}};Lo.kind="if";var Do=class extends an{};Do.kind="for";var zg=class extends Do{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Ms(this.iteration,e,r),this}get names(){return qo(super.names,this.iteration.names)}},jg=class extends Do{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Er.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=ou(super.names,this.from);return ou(e,this.to)}},nu=class extends Do{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Ms(this.iterable,e,r),this}get names(){return qo(super.names,this.iterable.names)}},da=class extends an{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};da.kind="func";var fa=class extends pa{render(e){return"return "+super.render(e)}};fa.kind="return";var Mg=class extends an{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&qo(e,this.catch.names),this.finally&&qo(e,this.finally.names),e}},ma=class extends an{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ma.kind="catch";var ha=class extends an{render(e){return"finally"+super.render(e)}};ha.kind="finally";var Lg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
289
- `:""},this._extScope=e,this._scope=new Er.Scope({parent:e}),this._nodes=[new Ng]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new Pg(e,s,n)),s}const(e,r,n){return this._def(Er.varKinds.const,e,r,n)}let(e,r,n){return this._def(Er.varKinds.let,e,r,n)}var(e,r,n){return this._def(Er.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new ru(e,r,n))}add(e,r){return this._leafNode(new Rg(e,he.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==$e.nil&&this._leafNode(new Ag(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,$e.addCodeArg)(r,o));return r.push("}"),new $e._Code(r)}if(e,r,n){if(this._blockNode(new Lo(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Lo(e))}else(){return this._elseNode(new js)}endIf(){return this._endBlockNode(Lo,js)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new zg(e),r)}forRange(e,r,n,o,s=this.opts.es5?Er.varKinds.var:Er.varKinds.let){let i=this._scope.toName(e);return this._for(new jg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Er.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof $e.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,$e._)`${i}.length`,a=>{this.var(s,(0,$e._)`${i}[${a}]`),n(s)})}return this._for(new nu("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Er.varKinds.var:Er.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,$e._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new nu("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Do)}label(e){return this._leafNode(new Og(e))}break(e){return this._leafNode(new Cg(e))}return(e){let r=new fa;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(fa)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Mg;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ma(s),r(s)}return n&&(this._currNode=o.finally=new ha,this.code(n)),this._endBlockNode(ma,ha)}throw(e){return this._leafNode(new Ig(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=$e.nil,n,o){return this._blockNode(new da(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(da)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Lo))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};he.CodeGen=Lg;function qo(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function ou(t,e){return e instanceof $e._CodeOrName?qo(t,e.names):t}function Ms(t,e,r){if(t instanceof $e.Name)return n(t);if(!o(t))return t;return new $e._Code(t._items.reduce((s,i)=>(i instanceof $e.Name&&(i=n(i)),i instanceof $e._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof $e._Code&&s._items.some(i=>i instanceof $e.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function X2(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function K$(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,$e._)`!${Dg(t)}`}he.not=K$;var Q2=Y$(he.operators.AND);function eq(...t){return t.reduce(Q2)}he.and=eq;var tq=Y$(he.operators.OR);function rq(...t){return t.reduce(tq)}he.or=rq;function Y$(t){return(e,r)=>e===$e.nil?r:r===$e.nil?e:(0,$e._)`${Dg(e)} ${t} ${Dg(r)}`}function Dg(t){return t instanceof $e.Name?t:(0,$e._)`(${t})`}});var Pe=O(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.checkStrictMode=ve.getErrorPath=ve.Type=ve.useFunc=ve.setEvaluated=ve.evaluatedPropsToName=ve.mergeEvaluated=ve.eachItem=ve.unescapeJsonPointer=ve.escapeJsonPointer=ve.escapeFragment=ve.unescapeFragment=ve.schemaRefOrVal=ve.schemaHasRulesButRef=ve.schemaHasRules=ve.checkUnknownRules=ve.alwaysValidSchema=ve.toHash=void 0;var ze=pe(),nq=ua();function oq(t){let e={};for(let r of t)e[r]=!0;return e}ve.toHash=oq;function sq(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(ek(t,e),!tk(e,t.self.RULES.all))}ve.alwaysValidSchema=sq;function ek(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||ok(t,`unknown keyword: "${s}"`)}ve.checkUnknownRules=ek;function tk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ve.schemaHasRules=tk;function iq(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ve.schemaHasRulesButRef=iq;function aq({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ze._)`${r}`}return(0,ze._)`${t}${e}${(0,ze.getProperty)(n)}`}ve.schemaRefOrVal=aq;function cq(t){return rk(decodeURIComponent(t))}ve.unescapeFragment=cq;function lq(t){return encodeURIComponent(Zg(t))}ve.escapeFragment=lq;function Zg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ve.escapeJsonPointer=Zg;function rk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ve.unescapeJsonPointer=rk;function uq(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ve.eachItem=uq;function X$({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ze.Name?(s instanceof ze.Name?t(o,s,i):e(o,s,i),i):s instanceof ze.Name?(e(o,i,s),s):r(s,i);return a===ze.Name&&!(c instanceof ze.Name)?n(o,c):c}}ve.mergeEvaluated={props:X$({mergeNames:(t,e,r)=>t.if((0,ze._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ze._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ze._)`${r} || {}`).code((0,ze._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ze._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ze._)`${r} || {}`),Ug(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:nk}),items:X$({mergeNames:(t,e,r)=>t.if((0,ze._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ze._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ze._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ze._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function nk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ze._)`{}`);return e!==void 0&&Ug(t,r,e),r}ve.evaluatedPropsToName=nk;function Ug(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ze._)`${e}${(0,ze.getProperty)(n)}`,!0))}ve.setEvaluated=Ug;var Q$={};function pq(t,e){return t.scopeValue("func",{ref:e,code:Q$[e.code]||(Q$[e.code]=new nq._Code(e.code))})}ve.useFunc=pq;var qg;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(qg||(ve.Type=qg={}));function dq(t,e,r){if(t instanceof ze.Name){let n=e===qg.Num;return r?n?(0,ze._)`"[" + ${t} + "]"`:(0,ze._)`"['" + ${t} + "']"`:n?(0,ze._)`"/" + ${t}`:(0,ze._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ze.getProperty)(t).toString():"/"+Zg(t)}ve.getErrorPath=dq;function ok(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ve.checkStrictMode=ok});var cn=O(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var Tt=pe(),fq={data:new Tt.Name("data"),valCxt:new Tt.Name("valCxt"),instancePath:new Tt.Name("instancePath"),parentData:new Tt.Name("parentData"),parentDataProperty:new Tt.Name("parentDataProperty"),rootData:new Tt.Name("rootData"),dynamicAnchors:new Tt.Name("dynamicAnchors"),vErrors:new Tt.Name("vErrors"),errors:new Tt.Name("errors"),this:new Tt.Name("this"),self:new Tt.Name("self"),scope:new Tt.Name("scope"),json:new Tt.Name("json"),jsonPos:new Tt.Name("jsonPos"),jsonLen:new Tt.Name("jsonLen"),jsonPart:new Tt.Name("jsonPart")};Fg.default=fq});var ga=O(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendErrors=Pt.resetErrorsCount=Pt.reportExtraError=Pt.reportError=Pt.keyword$DataError=Pt.keywordError=void 0;var ke=pe(),iu=Pe(),Nt=cn();Pt.keywordError={message:({keyword:t})=>(0,ke.str)`must pass "${t}" keyword validation`};Pt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ke.str)`"${t}" keyword must be ${e} ($data)`:(0,ke.str)`"${t}" keyword is invalid ($data)`};function mq(t,e=Pt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=ak(t,e,r);n??(i||a)?sk(s,c):ik(o,(0,ke._)`[${c}]`)}Pt.reportError=mq;function hq(t,e=Pt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=ak(t,e,r);sk(o,a),s||i||ik(n,Nt.default.vErrors)}Pt.reportExtraError=hq;function gq(t,e){t.assign(Nt.default.errors,e),t.if((0,ke._)`${Nt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ke._)`${Nt.default.vErrors}.length`,e),()=>t.assign(Nt.default.vErrors,null)))}Pt.resetErrorsCount=gq;function yq({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Nt.default.errors,a=>{t.const(i,(0,ke._)`${Nt.default.vErrors}[${a}]`),t.if((0,ke._)`${i}.instancePath === undefined`,()=>t.assign((0,ke._)`${i}.instancePath`,(0,ke.strConcat)(Nt.default.instancePath,s.errorPath))),t.assign((0,ke._)`${i}.schemaPath`,(0,ke.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ke._)`${i}.schema`,r),t.assign((0,ke._)`${i}.data`,n))})}Pt.extendErrors=yq;function sk(t,e){let r=t.const("err",e);t.if((0,ke._)`${Nt.default.vErrors} === null`,()=>t.assign(Nt.default.vErrors,(0,ke._)`[${r}]`),(0,ke._)`${Nt.default.vErrors}.push(${r})`),t.code((0,ke._)`${Nt.default.errors}++`)}function ik(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ke._)`new ${t.ValidationError}(${e})`):(r.assign((0,ke._)`${n}.errors`,e),r.return(!1))}var Zo={keyword:new ke.Name("keyword"),schemaPath:new ke.Name("schemaPath"),params:new ke.Name("params"),propertyName:new ke.Name("propertyName"),message:new ke.Name("message"),schema:new ke.Name("schema"),parentSchema:new ke.Name("parentSchema")};function ak(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ke._)`{}`:vq(t,e,r)}function vq(t,e,r={}){let{gen:n,it:o}=t,s=[_q(o,r),bq(t,r)];return wq(t,e,s),n.object(...s)}function _q({errorPath:t},{instancePath:e}){let r=e?(0,ke.str)`${t}${(0,iu.getErrorPath)(e,iu.Type.Str)}`:t;return[Nt.default.instancePath,(0,ke.strConcat)(Nt.default.instancePath,r)]}function bq({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ke.str)`${e}/${t}`;return r&&(o=(0,ke.str)`${o}${(0,iu.getErrorPath)(r,iu.Type.Str)}`),[Zo.schemaPath,o]}function wq(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Zo.keyword,o],[Zo.params,typeof e=="function"?e(t):e||(0,ke._)`{}`]),c.messages&&n.push([Zo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Zo.schema,i],[Zo.parentSchema,(0,ke._)`${u}${p}`],[Nt.default.data,s]),l&&n.push([Zo.propertyName,l])}});var lk=O(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.boolOrEmptySchema=Ls.topBoolOrEmptySchema=void 0;var xq=ga(),Sq=pe(),$q=cn(),kq={message:"boolean schema is false"};function Eq(t){let{gen:e,schema:r,validateName:n}=t;r===!1?ck(t,!1):typeof r=="object"&&r.$async===!0?e.return($q.default.data):(e.assign((0,Sq._)`${n}.errors`,null),e.return(!0))}Ls.topBoolOrEmptySchema=Eq;function Tq(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),ck(t)):r.var(e,!0)}Ls.boolOrEmptySchema=Tq;function ck(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,xq.reportError)(o,kq,void 0,e)}});var Hg=O(Ds=>{"use strict";Object.defineProperty(Ds,"__esModule",{value:!0});Ds.getRules=Ds.isJSONType=void 0;var Pq=["string","number","integer","boolean","null","object","array"],Rq=new Set(Pq);function Oq(t){return typeof t=="string"&&Rq.has(t)}Ds.isJSONType=Oq;function Cq(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Ds.getRules=Cq});var Bg=O(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.shouldUseRule=Mn.shouldUseGroup=Mn.schemaHasRulesForType=void 0;function Iq({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&uk(t,n)}Mn.schemaHasRulesForType=Iq;function uk(t,e){return e.rules.some(r=>pk(t,r))}Mn.shouldUseGroup=uk;function pk(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Mn.shouldUseRule=pk});var ya=O(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.reportTypeError=Rt.checkDataTypes=Rt.checkDataType=Rt.coerceAndCheckDataType=Rt.getJSONTypes=Rt.getSchemaTypes=Rt.DataType=void 0;var Aq=Hg(),Nq=Bg(),zq=ga(),ce=pe(),dk=Pe(),qs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(qs||(Rt.DataType=qs={}));function jq(t){let e=fk(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Rt.getSchemaTypes=jq;function fk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(Aq.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Rt.getJSONTypes=fk;function Mq(t,e){let{gen:r,data:n,opts:o}=t,s=Lq(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,Nq.schemaHasRulesForType)(t,e[0]));if(i){let a=Gg(e,n,o.strictNumbers,qs.Wrong);r.if(a,()=>{s.length?Dq(t,e,s):Wg(t)})}return i}Rt.coerceAndCheckDataType=Mq;var mk=new Set(["string","number","integer","boolean","null"]);function Lq(t,e){return e?t.filter(r=>mk.has(r)||e==="array"&&r==="array"):[]}function Dq(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,ce._)`typeof ${o}`),a=n.let("coerced",(0,ce._)`undefined`);s.coerceTypes==="array"&&n.if((0,ce._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,ce._)`${o}[0]`).assign(i,(0,ce._)`typeof ${o}`).if(Gg(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ce._)`${a} !== undefined`);for(let l of r)(mk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),Wg(t),n.endIf(),n.if((0,ce._)`${a} !== undefined`,()=>{n.assign(o,a),qq(t,a)});function c(l){switch(l){case"string":n.elseIf((0,ce._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,ce._)`"" + ${o}`).elseIf((0,ce._)`${o} === null`).assign(a,(0,ce._)`""`);return;case"number":n.elseIf((0,ce._)`${i} == "boolean" || ${o} === null
290
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ce._)`+${o}`);return;case"integer":n.elseIf((0,ce._)`${i} === "boolean" || ${o} === null
291
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,ce._)`+${o}`);return;case"boolean":n.elseIf((0,ce._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,ce._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,ce._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,ce._)`${i} === "string" || ${i} === "number"
292
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,ce._)`[${o}]`)}}}function qq({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ce._)`${e} !== undefined`,()=>t.assign((0,ce._)`${e}[${r}]`,n))}function Vg(t,e,r,n=qs.Correct){let o=n===qs.Correct?ce.operators.EQ:ce.operators.NEQ,s;switch(t){case"null":return(0,ce._)`${e} ${o} null`;case"array":s=(0,ce._)`Array.isArray(${e})`;break;case"object":s=(0,ce._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,ce._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,ce._)`typeof ${e} ${o} ${t}`}return n===qs.Correct?s:(0,ce.not)(s);function i(a=ce.nil){return(0,ce.and)((0,ce._)`typeof ${e} == "number"`,a,r?(0,ce._)`isFinite(${e})`:ce.nil)}}Rt.checkDataType=Vg;function Gg(t,e,r,n){if(t.length===1)return Vg(t[0],e,r,n);let o,s=(0,dk.toHash)(t);if(s.array&&s.object){let i=(0,ce._)`typeof ${e} != "object"`;o=s.null?i:(0,ce._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=ce.nil;s.number&&delete s.integer;for(let i in s)o=(0,ce.and)(o,Vg(i,e,r,n));return o}Rt.checkDataTypes=Gg;var Zq={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ce._)`{type: ${t}}`:(0,ce._)`{type: ${e}}`};function Wg(t){let e=Uq(t);(0,zq.reportError)(e,Zq)}Rt.reportTypeError=Wg;function Uq(t){let{gen:e,data:r,schema:n}=t,o=(0,dk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var gk=O(au=>{"use strict";Object.defineProperty(au,"__esModule",{value:!0});au.assignDefaults=void 0;var Zs=pe(),Fq=Pe();function Hq(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)hk(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>hk(t,s,o.default))}au.assignDefaults=Hq;function hk(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Zs._)`${s}${(0,Zs.getProperty)(e)}`;if(o){(0,Fq.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Zs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Zs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Zs._)`${a} = ${(0,Zs.stringify)(r)}`)}});var dr=O(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.validateUnion=Ne.validateArray=Ne.usePattern=Ne.callValidateCode=Ne.schemaProperties=Ne.allSchemaProperties=Ne.noPropertyInData=Ne.propertyInData=Ne.isOwnProperty=Ne.hasPropFunc=Ne.reportMissingProp=Ne.checkMissingProp=Ne.checkReportMissingProp=void 0;var Ue=pe(),Jg=Pe(),Ln=cn(),Bq=Pe();function Vq(t,e){let{gen:r,data:n,it:o}=t;r.if(Yg(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ue._)`${e}`},!0),t.error()})}Ne.checkReportMissingProp=Vq;function Gq({gen:t,data:e,it:{opts:r}},n,o){return(0,Ue.or)(...n.map(s=>(0,Ue.and)(Yg(t,e,s,r.ownProperties),(0,Ue._)`${o} = ${s}`)))}Ne.checkMissingProp=Gq;function Wq(t,e){t.setParams({missingProperty:e},!0),t.error()}Ne.reportMissingProp=Wq;function yk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ue._)`Object.prototype.hasOwnProperty`})}Ne.hasPropFunc=yk;function Kg(t,e,r){return(0,Ue._)`${yk(t)}.call(${e}, ${r})`}Ne.isOwnProperty=Kg;function Jq(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} !== undefined`;return n?(0,Ue._)`${o} && ${Kg(t,e,r)}`:o}Ne.propertyInData=Jq;function Yg(t,e,r,n){let o=(0,Ue._)`${e}${(0,Ue.getProperty)(r)} === undefined`;return n?(0,Ue.or)(o,(0,Ue.not)(Kg(t,e,r))):o}Ne.noPropertyInData=Yg;function vk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ne.allSchemaProperties=vk;function Kq(t,e){return vk(e).filter(r=>!(0,Jg.alwaysValidSchema)(t,e[r]))}Ne.schemaProperties=Kq;function Yq({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Ue._)`${t}, ${e}, ${n}${o}`:e,p=[[Ln.default.instancePath,(0,Ue.strConcat)(Ln.default.instancePath,s)],[Ln.default.parentData,i.parentData],[Ln.default.parentDataProperty,i.parentDataProperty],[Ln.default.rootData,Ln.default.rootData]];i.opts.dynamicRef&&p.push([Ln.default.dynamicAnchors,Ln.default.dynamicAnchors]);let m=(0,Ue._)`${u}, ${r.object(...p)}`;return c!==Ue.nil?(0,Ue._)`${a}.call(${c}, ${m})`:(0,Ue._)`${a}(${m})`}Ne.callValidateCode=Yq;var Xq=(0,Ue._)`new RegExp`;function Qq({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ue._)`${o.code==="new RegExp"?Xq:(0,Bq.useFunc)(t,o)}(${r}, ${n})`})}Ne.usePattern=Qq;function eZ(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ue._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:Jg.Type.Num},s),e.if((0,Ue.not)(s),a)})}}Ne.validateArray=eZ;function tZ(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Jg.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,Ue._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Ue.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ne.validateUnion=tZ});var wk=O(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.validateKeywordUsage=Zr.validSchemaType=Zr.funcKeywordCode=Zr.macroKeywordCode=void 0;var zt=pe(),Uo=cn(),rZ=dr(),nZ=ga();function oZ(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=bk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:zt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Zr.macroKeywordCode=oZ;function sZ(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;aZ(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=bk(n,o,l),p=n.let("valid");t.block$data(p,m),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function m(){if(e.errors===!1)h(),e.modifying&&_k(t),g(()=>t.error());else{let v=e.async?d():f();e.modifying&&_k(t),g(()=>iZ(t,v))}}function d(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,zt._)`await `),_=>n.assign(p,!1).if((0,zt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,zt._)`${_}.errors`),()=>n.throw(_))),v}function f(){let v=(0,zt._)`${u}.errors`;return n.assign(v,null),h(zt.nil),v}function h(v=e.async?(0,zt._)`await `:zt.nil){let _=c.opts.passContext?Uo.default.this:Uo.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,zt._)`${v}${(0,rZ.callValidateCode)(t,u,_,x)}`,e.modifying)}function g(v){var _;n.if((0,zt.not)((_=e.valid)!==null&&_!==void 0?_:p),v)}}Zr.funcKeywordCode=sZ;function _k(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,zt._)`${n.parentData}[${n.parentDataProperty}]`))}function iZ(t,e){let{gen:r}=t;r.if((0,zt._)`Array.isArray(${e})`,()=>{r.assign(Uo.default.vErrors,(0,zt._)`${Uo.default.vErrors} === null ? ${e} : ${Uo.default.vErrors}.concat(${e})`).assign(Uo.default.errors,(0,zt._)`${Uo.default.vErrors}.length`),(0,nZ.extendErrors)(t)},()=>t.error())}function aZ({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function bk(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,zt.stringify)(r)})}function cZ(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Zr.validSchemaType=cZ;function lZ({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Zr.validateKeywordUsage=lZ});var Sk=O(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.extendSubschemaMode=Dn.extendSubschemaData=Dn.getSubschema=void 0;var Ur=pe(),xk=Pe();function uZ(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ur._)`${t.schemaPath}${(0,Ur.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ur._)`${t.schemaPath}${(0,Ur.getProperty)(e)}${(0,Ur.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,xk.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Dn.getSubschema=uZ;function pZ(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:p}=e,m=a.let("data",(0,Ur._)`${e.data}${(0,Ur.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Ur.str)`${l}${(0,xk.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,Ur._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Ur.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Dn.extendSubschemaData=pZ;function dZ(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Dn.extendSubschemaMode=dZ});var Xg=O((tX,$k)=>{"use strict";$k.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var Ek=O((rX,kk)=>{"use strict";var qn=kk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};cu(e,n,o,t,"",t)};qn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};qn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};qn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};qn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function cu(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var p=n[u];if(Array.isArray(p)){if(u in qn.arrayKeywords)for(var m=0;m<p.length;m++)cu(t,e,r,p[m],o+"/"+u+"/"+m,s,o,u,n,m)}else if(u in qn.propsKeywords){if(p&&typeof p=="object")for(var d in p)cu(t,e,r,p[d],o+"/"+u+"/"+fZ(d),s,o,u,n,d)}else(u in qn.keywords||t.allKeys&&!(u in qn.skipKeywords))&&cu(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function fZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var va=O(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.getSchemaRefs=Gt.resolveUrl=Gt.normalizeId=Gt._getFullPath=Gt.getFullPath=Gt.inlineRef=void 0;var mZ=Pe(),hZ=Xg(),gZ=Ek(),yZ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function vZ(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Qg(t):e?Tk(t)<=e:!1}Gt.inlineRef=vZ;var _Z=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qg(t){for(let e in t){if(_Z.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Qg)||typeof r=="object"&&Qg(r))return!0}return!1}function Tk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!yZ.has(r)&&(typeof t[r]=="object"&&(0,mZ.eachItem)(t[r],n=>e+=Tk(n)),e===1/0))return 1/0}return e}function Pk(t,e="",r){r!==!1&&(e=Us(e));let n=t.parse(e);return Rk(t,n)}Gt.getFullPath=Pk;function Rk(t,e){return t.serialize(e).split("#")[0]+"#"}Gt._getFullPath=Rk;var bZ=/#\/?$/;function Us(t){return t?t.replace(bZ,""):""}Gt.normalizeId=Us;function wZ(t,e,r){return r=Us(r),t.resolve(e,r)}Gt.resolveUrl=wZ;var xZ=/^[a-z_][-a-z0-9._]*$/i;function SZ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Us(t[r]||e),s={"":o},i=Pk(n,o,!1),a={},c=new Set;return gZ(t,{allKeys:!0},(p,m,d,f)=>{if(f===void 0)return;let h=i+m,g=s[f];typeof p[r]=="string"&&(g=v.call(this,p[r])),_.call(this,p.$anchor),_.call(this,p.$dynamicAnchor),s[m]=g;function v(x){let k=this.opts.uriResolver.resolve;if(x=Us(g?k(g,x):x),c.has(x))throw u(x);c.add(x);let I=this.refs[x];return typeof I=="string"&&(I=this.refs[I]),typeof I=="object"?l(p,I.schema,x):x!==Us(h)&&(x[0]==="#"?(l(p,a[x],x),a[x]=p):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!xZ.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`)}}}),a;function l(p,m,d){if(m!==void 0&&!hZ(p,m))throw u(d)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Gt.getSchemaRefs=SZ});var wa=O(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.getData=Zn.KeywordCxt=Zn.validateFunctionCode=void 0;var Nk=lk(),Ok=ya(),ty=Bg(),lu=ya(),$Z=gk(),ba=wk(),ey=Sk(),Z=pe(),re=cn(),kZ=va(),ln=Pe(),_a=ga();function EZ(t){if(Mk(t)&&(Lk(t),jk(t))){RZ(t);return}zk(t,()=>(0,Nk.topBoolOrEmptySchema)(t))}Zn.validateFunctionCode=EZ;function zk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${Ck(r,o)}`),PZ(t,o),t.code(s)}):t.func(e,(0,Z._)`${re.default.data}, ${TZ(o)}`,n.$async,()=>t.code(Ck(r,o)).code(s))}function TZ(t){return(0,Z._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${t.dynamicRef?(0,Z._)`, ${re.default.dynamicAnchors}={}`:Z.nil}}={}`}function PZ(t,e){t.if(re.default.valCxt,()=>{t.var(re.default.instancePath,(0,Z._)`${re.default.valCxt}.${re.default.instancePath}`),t.var(re.default.parentData,(0,Z._)`${re.default.valCxt}.${re.default.parentData}`),t.var(re.default.parentDataProperty,(0,Z._)`${re.default.valCxt}.${re.default.parentDataProperty}`),t.var(re.default.rootData,(0,Z._)`${re.default.valCxt}.${re.default.rootData}`),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,Z._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{t.var(re.default.instancePath,(0,Z._)`""`),t.var(re.default.parentData,(0,Z._)`undefined`),t.var(re.default.parentDataProperty,(0,Z._)`undefined`),t.var(re.default.rootData,re.default.data),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,Z._)`{}`)})}function RZ(t){let{schema:e,opts:r,gen:n}=t;zk(t,()=>{r.$comment&&e.$comment&&qk(t),NZ(t),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated&&OZ(t),Dk(t),MZ(t)})}function OZ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function Ck(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function CZ(t,e){if(Mk(t)&&(Lk(t),jk(t))){IZ(t,e);return}(0,Nk.boolOrEmptySchema)(t,e)}function jk({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Mk(t){return typeof t.schema!="boolean"}function IZ(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&qk(t),zZ(t),jZ(t);let s=n.const("_errs",re.default.errors);Dk(t,s),n.var(e,(0,Z._)`${s} === ${re.default.errors}`)}function Lk(t){(0,ln.checkUnknownRules)(t),AZ(t)}function Dk(t,e){if(t.opts.jtd)return Ik(t,[],!1,e);let r=(0,Ok.getSchemaTypes)(t.schema),n=(0,Ok.coerceAndCheckDataType)(t,r);Ik(t,r,!n,e)}function AZ(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ln.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function NZ(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ln.checkStrictMode)(t,"default is ignored in the schema root")}function zZ(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,kZ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function jZ(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function qk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${re.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${re.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function MZ(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${re.default.errors} === 0`,()=>e.return(re.default.data),()=>e.throw((0,Z._)`new ${o}(${re.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,re.default.vErrors),s.unevaluated&&LZ(t),e.return((0,Z._)`${re.default.errors} === 0`))}function LZ({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function Ik(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ln.schemaHasRulesButRef)(s,u))){o.block(()=>Uk(t,"$ref",u.all.$ref.definition));return}c.jtd||DZ(t,e),o.block(()=>{for(let m of u.rules)p(m);p(u.post)});function p(m){(0,ty.shouldUseGroup)(s,m)&&(m.type?(o.if((0,lu.checkDataType)(m.type,i,c.strictNumbers)),Ak(t,m),e.length===1&&e[0]===m.type&&r&&(o.else(),(0,lu.reportTypeError)(t)),o.endIf()):Ak(t,m),a||o.if((0,Z._)`${re.default.errors} === ${n||0}`))}}function Ak(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,$Z.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,ty.shouldUseRule)(n,s)&&Uk(t,s.keyword,s.definition,e.type)})}function DZ(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(qZ(t,e),t.opts.allowUnionTypes||ZZ(t,e),UZ(t,t.dataTypes))}function qZ(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Zk(t.dataTypes,r)||ry(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),HZ(t,e)}}function ZZ(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ry(t,"use allowUnionTypes to allow union type keyword")}function UZ(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,ty.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>FZ(e,i))&&ry(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function FZ(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Zk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function HZ(t,e){let r=[];for(let n of t.dataTypes)Zk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ry(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ln.checkStrictMode)(t,e,t.opts.strictTypes)}var uu=class{constructor(e,r,n){if((0,ba.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ln.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Fk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,ba.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",re.default.errors))}result(e,r,n){this.failResult((0,Z.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Z.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Z._)`${r} !== undefined && (${(0,Z.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?_a.reportExtraError:_a.reportError)(this,this.def.error,r)}$dataError(){(0,_a.reportError)(this,this.def.$dataError||_a.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,_a.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,lu.checkDataTypes)(c,r,s.opts.strictNumbers,lu.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,ey.getSubschema)(this.it,e);(0,ey.extendSubschemaData)(n,this.it,e),(0,ey.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return CZ(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ln.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ln.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,Z.Name)),!0}};Zn.KeywordCxt=uu;function Uk(t,e,r,n){let o=new uu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,ba.funcKeywordCode)(o,r):"macro"in r?(0,ba.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,ba.funcKeywordCode)(o,r)}var BZ=/^\/(?:[^~]|~0|~1)*$/,VZ=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Fk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return re.default.rootData;if(t[0]==="/"){if(!BZ.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=re.default.rootData}else{let l=VZ.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,Z._)`${s}${(0,Z.getProperty)((0,ln.unescapeJsonPointer)(l))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Zn.getData=Fk});var pu=O(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0});var ny=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};oy.default=ny});var xa=O(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});var sy=va(),iy=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,sy.resolveUrl)(e,r,n),this.missingSchema=(0,sy.normalizeId)((0,sy.getFullPath)(e,this.missingRef))}};ay.default=iy});var fu=O(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.resolveSchema=fr.getCompilingSchema=fr.resolveRef=fr.compileSchema=fr.SchemaEnv=void 0;var Tr=pe(),GZ=pu(),Fo=cn(),Pr=va(),Hk=Pe(),WZ=wa(),Fs=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};fr.SchemaEnv=Fs;function ly(t){let e=Bk.call(this,t);if(e)return e;let r=(0,Pr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Tr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:GZ.default,code:(0,Tr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Fo.default.data,parentData:Fo.default.parentData,parentDataProperty:Fo.default.parentDataProperty,dataNames:[Fo.default.data],dataPathArr:[Tr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Tr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Tr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,WZ.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Fo.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let d=new Function(`${Fo.default.self}`,`${Fo.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:d}),d.errors=null,d.schema=t.schema,d.schemaEnv=t,t.$async&&(d.$async=!0),this.opts.code.source===!0&&(d.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:f,items:h}=l;d.evaluated={props:f instanceof Tr.Name?void 0:f,items:h instanceof Tr.Name?void 0:h,dynamicProps:f instanceof Tr.Name,dynamicItems:h instanceof Tr.Name},d.source&&(d.source.evaluated=(0,Tr.stringify)(d.evaluated))}return t.validate=d,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}fr.compileSchema=ly;function JZ(t,e,r){var n;r=(0,Pr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=XZ.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Fs({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=KZ.call(this,s)}fr.resolveRef=JZ;function KZ(t){return(0,Pr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ly.call(this,t)}function Bk(t){for(let e of this._compilations)if(YZ(e,t))return e}fr.getCompilingSchema=Bk;function YZ(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function XZ(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||du.call(this,t,e)}function du(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pr._getFullPath)(this.opts.uriResolver,r),o=(0,Pr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return cy.call(this,r,t);let s=(0,Pr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=du.call(this,t,i);return typeof a?.schema!="object"?void 0:cy.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ly.call(this,i),s===(0,Pr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Pr.resolveUrl)(this.opts.uriResolver,o,l)),new Fs({schema:a,schemaId:c,root:t,baseId:o})}return cy.call(this,r,i)}}fr.resolveSchema=du;var QZ=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function cy(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Hk.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!QZ.has(a)&&l&&(e=(0,Pr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Hk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=du.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Fs({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var Vk=O((cX,eU)=>{eU.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var py=O((lX,Kk)=>{"use strict";var tU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Wk=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function uy(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var rU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Gk(t){return t.length=0,!0}function nU(t,e,r){if(t.length){let n=uy(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function oU(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=nU;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=Gk}else{o.push(l);continue}}return o.length&&(a===Gk?r.zone=o.join(""):i?n.push(o.join("")):n.push(uy(o))),r.address=n.join(""),r}function Jk(t){if(sU(t,":")<2)return{host:t,isIPV6:!1};let e=oU(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function sU(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function iU(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function aU(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function cU(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Wk(r)){let n=Jk(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}Kk.exports={nonSimpleDomain:rU,recomposeAuthority:cU,normalizeComponentEncoding:aU,removeDotSegments:iU,isIPv4:Wk,isUUID:tU,normalizeIPv6:Jk,stringArrayToHexStripped:uy}});var tE=O((uX,eE)=>{"use strict";var{isUUID:lU}=py(),uU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,pU=["http","https","ws","wss","urn","urn:uuid"];function dU(t){return pU.indexOf(t)!==-1}function dy(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function Yk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Xk(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function fU(t){return t.secure=dy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function mU(t){if((t.port===(dy(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function hU(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(uU);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=fy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function gU(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=fy(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function yU(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!lU(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function vU(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Qk={scheme:"http",domainHost:!0,parse:Yk,serialize:Xk},_U={scheme:"https",domainHost:Qk.domainHost,parse:Yk,serialize:Xk},mu={scheme:"ws",domainHost:!0,parse:fU,serialize:mU},bU={scheme:"wss",domainHost:mu.domainHost,parse:mu.parse,serialize:mu.serialize},wU={scheme:"urn",parse:hU,serialize:gU,skipNormalize:!0},xU={scheme:"urn:uuid",parse:yU,serialize:vU,skipNormalize:!0},hu={http:Qk,https:_U,ws:mu,wss:bU,urn:wU,"urn:uuid":xU};Object.setPrototypeOf(hu,null);function fy(t){return t&&(hu[t]||hu[t.toLowerCase()])||void 0}eE.exports={wsIsSecure:dy,SCHEMES:hu,isValidSchemeName:dU,getSchemeHandler:fy}});var oE=O((pX,yu)=>{"use strict";var{normalizeIPv6:SU,removeDotSegments:Sa,recomposeAuthority:$U,normalizeComponentEncoding:gu,isIPv4:kU,nonSimpleDomain:EU}=py(),{SCHEMES:TU,getSchemeHandler:rE}=tE();function PU(t,e){return typeof t=="string"?t=Fr(un(t,e),e):typeof t=="object"&&(t=un(Fr(t,e),e)),t}function RU(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=nE(un(t,n),un(e,n),n,!0);return n.skipEscape=!0,Fr(o,n)}function nE(t,e,r,n){let o={};return n||(t=un(Fr(t,r),r),e=un(Fr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Sa(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Sa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Sa(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Sa(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function OU(t,e,r){return typeof t=="string"?(t=unescape(t),t=Fr(gu(un(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Fr(gu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Fr(gu(un(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Fr(gu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Fr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=rE(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=$U(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Sa(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var CU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function un(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(CU);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(kU(n.host)===!1){let c=SU(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=rE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&EU(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var my={SCHEMES:TU,normalize:PU,resolve:RU,resolveComponent:nE,equal:OU,serialize:Fr,parse:un};yu.exports=my;yu.exports.default=my;yu.exports.fastUri=my});var iE=O(hy=>{"use strict";Object.defineProperty(hy,"__esModule",{value:!0});var sE=oE();sE.code='require("ajv/dist/runtime/uri").default';hy.default=sE});var mE=O(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.CodeGen=xt.Name=xt.nil=xt.stringify=xt.str=xt._=xt.KeywordCxt=void 0;var IU=wa();Object.defineProperty(xt,"KeywordCxt",{enumerable:!0,get:function(){return IU.KeywordCxt}});var Hs=pe();Object.defineProperty(xt,"_",{enumerable:!0,get:function(){return Hs._}});Object.defineProperty(xt,"str",{enumerable:!0,get:function(){return Hs.str}});Object.defineProperty(xt,"stringify",{enumerable:!0,get:function(){return Hs.stringify}});Object.defineProperty(xt,"nil",{enumerable:!0,get:function(){return Hs.nil}});Object.defineProperty(xt,"Name",{enumerable:!0,get:function(){return Hs.Name}});Object.defineProperty(xt,"CodeGen",{enumerable:!0,get:function(){return Hs.CodeGen}});var AU=pu(),pE=xa(),NU=Hg(),$a=fu(),zU=pe(),ka=va(),vu=ya(),yy=Pe(),aE=Vk(),jU=iE(),dE=(t,e)=>new RegExp(t,e);dE.code="new RegExp";var MU=["removeAdditional","useDefaults","coerceTypes"],LU=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),DU={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},qU={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},cE=200;function ZU(t){var e,r,n,o,s,i,a,c,l,u,p,m,d,f,h,g,v,_,x,k,I,de,Y,ee,ge;let U=t.strict,ne=(e=t.code)===null||e===void 0?void 0:e.optimize,rt=ne===!0||ne===void 0?1:ne||0,Mt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:dE,te=(o=t.uriResolver)!==null&&o!==void 0?o:jU.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:U)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:U)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:U)!==null&&u!==void 0?u:"log",strictTuples:(m=(p=t.strictTuples)!==null&&p!==void 0?p:U)!==null&&m!==void 0?m:"log",strictRequired:(f=(d=t.strictRequired)!==null&&d!==void 0?d:U)!==null&&f!==void 0?f:!1,code:t.code?{...t.code,optimize:rt,regExp:Mt}:{optimize:rt,regExp:Mt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:cE,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:cE,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(I=t.addUsedSchema)!==null&&I!==void 0?I:!0,validateSchema:(de=t.validateSchema)!==null&&de!==void 0?de:!0,validateFormats:(Y=t.validateFormats)!==null&&Y!==void 0?Y:!0,unicodeRegExp:(ee=t.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(ge=t.int32range)!==null&&ge!==void 0?ge:!0,uriResolver:te}}var Ea=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...ZU(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new zU.ValueScope({scope:{},prefixes:LU,es5:r,lines:n}),this.logger=GU(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,NU.getRules)(),lE.call(this,DU,e,"NOT SUPPORTED"),lE.call(this,qU,e,"DEPRECATED","warn"),this._metaOpts=BU.call(this),e.formats&&FU.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&HU.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),UU.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=aE;n==="id"&&(o={...aE},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,p){await s.call(this,u.$schema);let m=this._addSchema(u,p);return m.validate||i.call(this,m)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof pE.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,ka.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=uE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new $a.SchemaEnv({schema:{},schemaId:n});if(r=$a.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=uE.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,ka.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(JU.call(this,n,r),!r)return(0,yy.eachItem)(n,s=>gy.call(this,s)),this;YU.call(this,r);let o={...r,type:(0,vu.getJSONTypes)(r.type),schemaType:(0,vu.getJSONTypes)(r.schemaType)};return(0,yy.eachItem)(n,o.type.length===0?s=>gy.call(this,s,o):s=>o.type.forEach(i=>gy.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=fE(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,ka.normalizeId)(i||n);let l=ka.getSchemaRefs.call(this,e,n);return c=new $a.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):$a.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{$a.compileSchema.call(this,e)}finally{this.opts=r}}};Ea.ValidationError=AU.default;Ea.MissingRefError=pE.default;xt.default=Ea;function lE(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function uE(t){return t=(0,ka.normalizeId)(t),this.schemas[t]||this.refs[t]}function UU(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function FU(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function HU(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function BU(){let t={...this.opts};for(let e of MU)delete t[e];return t}var VU={log(){},warn(){},error(){}};function GU(t){if(t===!1)return VU;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var WU=/^[a-z_$][a-z0-9_$:-]*$/i;function JU(t,e){let{RULES:r}=this;if((0,yy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!WU.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function gy(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,vu.getJSONTypes)(e.type),schemaType:(0,vu.getJSONTypes)(e.schemaType)}};e.before?KU.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function KU(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function YU(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=fE(e)),t.validateSchema=this.compile(e,!0))}var XU={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function fE(t){return{anyOf:[t,XU]}}});var hE=O(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});var QU={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};vy.default=QU});var _E=O(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.callRef=Ho.getValidate=void 0;var eF=xa(),gE=dr(),Wt=pe(),Bs=cn(),yE=fu(),_u=Pe(),tF={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return p();let u=yE.resolveRef.call(c,l,o,r);if(u===void 0)throw new eF.default(n.opts.uriResolver,o,r);if(u instanceof yE.SchemaEnv)return m(u);return d(u);function p(){if(s===l)return bu(t,i,s,s.$async);let f=e.scopeValue("root",{ref:l});return bu(t,(0,Wt._)`${f}.validate`,l,l.$async)}function m(f){let h=vE(t,f);bu(t,h,f,f.$async)}function d(f){let h=e.scopeValue("schema",a.code.source===!0?{ref:f,code:(0,Wt.stringify)(f)}:{ref:f}),g=e.name("valid"),v=t.subschema({schema:f,dataTypes:[],schemaPath:Wt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(v),t.ok(g)}}};function vE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Wt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Ho.getValidate=vE;function bu(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Bs.default.this:Wt.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let f=o.let("valid");o.try(()=>{o.code((0,Wt._)`await ${(0,gE.callValidateCode)(t,e,l)}`),d(e),i||o.assign(f,!0)},h=>{o.if((0,Wt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),m(h),i||o.assign(f,!1)}),t.ok(f)}function p(){t.result((0,gE.callValidateCode)(t,e,l),()=>d(e),()=>m(e))}function m(f){let h=(0,Wt._)`${f}.errors`;o.assign(Bs.default.vErrors,(0,Wt._)`${Bs.default.vErrors} === null ? ${h} : ${Bs.default.vErrors}.concat(${h})`),o.assign(Bs.default.errors,(0,Wt._)`${Bs.default.vErrors}.length`)}function d(f){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=_u.mergeEvaluated.props(o,g.props,s.props));else{let v=o.var("props",(0,Wt._)`${f}.evaluated.props`);s.props=_u.mergeEvaluated.props(o,v,s.props,Wt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=_u.mergeEvaluated.items(o,g.items,s.items));else{let v=o.var("items",(0,Wt._)`${f}.evaluated.items`);s.items=_u.mergeEvaluated.items(o,v,s.items,Wt.Name)}}}Ho.callRef=bu;Ho.default=tF});var bE=O(_y=>{"use strict";Object.defineProperty(_y,"__esModule",{value:!0});var rF=hE(),nF=_E(),oF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",rF.default,nF.default];_y.default=oF});var wE=O(by=>{"use strict";Object.defineProperty(by,"__esModule",{value:!0});var wu=pe(),Un=wu.operators,xu={maximum:{okStr:"<=",ok:Un.LTE,fail:Un.GT},minimum:{okStr:">=",ok:Un.GTE,fail:Un.LT},exclusiveMaximum:{okStr:"<",ok:Un.LT,fail:Un.GTE},exclusiveMinimum:{okStr:">",ok:Un.GT,fail:Un.LTE}},sF={message:({keyword:t,schemaCode:e})=>(0,wu.str)`must be ${xu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,wu._)`{comparison: ${xu[t].okStr}, limit: ${e}}`},iF={keyword:Object.keys(xu),type:"number",schemaType:"number",$data:!0,error:sF,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,wu._)`${r} ${xu[e].fail} ${n} || isNaN(${r})`)}};by.default=iF});var xE=O(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var Ta=pe(),aF={message:({schemaCode:t})=>(0,Ta.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ta._)`{multipleOf: ${t}}`},cF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:aF,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Ta._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Ta._)`${i} !== parseInt(${i})`;t.fail$data((0,Ta._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};wy.default=cF});var $E=O(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});function SE(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}xy.default=SE;SE.code='require("ajv/dist/runtime/ucs2length").default'});var kE=O(Sy=>{"use strict";Object.defineProperty(Sy,"__esModule",{value:!0});var Bo=pe(),lF=Pe(),uF=$E(),pF={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Bo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Bo._)`{limit: ${t}}`},dF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:pF,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Bo.operators.GT:Bo.operators.LT,i=o.opts.unicode===!1?(0,Bo._)`${r}.length`:(0,Bo._)`${(0,lF.useFunc)(t.gen,uF.default)}(${r})`;t.fail$data((0,Bo._)`${i} ${s} ${n}`)}};Sy.default=dF});var EE=O($y=>{"use strict";Object.defineProperty($y,"__esModule",{value:!0});var fF=dr(),Su=pe(),mF={message:({schemaCode:t})=>(0,Su.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Su._)`{pattern: ${t}}`},hF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:mF,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Su._)`(new RegExp(${o}, ${i}))`:(0,fF.usePattern)(t,n);t.fail$data((0,Su._)`!${a}.test(${e})`)}};$y.default=hF});var TE=O(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var Pa=pe(),gF={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Pa.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Pa._)`{limit: ${t}}`},yF={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:gF,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Pa.operators.GT:Pa.operators.LT;t.fail$data((0,Pa._)`Object.keys(${r}).length ${o} ${n}`)}};ky.default=yF});var PE=O(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});var Ra=dr(),Oa=pe(),vF=Pe(),_F={message:({params:{missingProperty:t}})=>(0,Oa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Oa._)`{missingProperty: ${t}}`},bF={keyword:"required",type:"object",schemaType:"array",$data:!0,error:_F,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let d=t.parentSchema.properties,{definedProperties:f}=t.it;for(let h of r)if(d?.[h]===void 0&&!f.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,vF.checkStrictMode)(i,v,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Oa.nil,p);else for(let d of r)(0,Ra.checkReportMissingProp)(t,d)}function u(){let d=e.let("missing");if(c||s){let f=e.let("valid",!0);t.block$data(f,()=>m(d,f)),t.ok(f)}else e.if((0,Ra.checkMissingProp)(t,r,d)),(0,Ra.reportMissingProp)(t,d),e.else()}function p(){e.forOf("prop",n,d=>{t.setParams({missingProperty:d}),e.if((0,Ra.noPropertyInData)(e,o,d,a.ownProperties),()=>t.error())})}function m(d,f){t.setParams({missingProperty:d}),e.forOf(d,n,()=>{e.assign(f,(0,Ra.propertyInData)(e,o,d,a.ownProperties)),e.if((0,Oa.not)(f),()=>{t.error(),e.break()})},Oa.nil)}}};Ey.default=bF});var RE=O(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});var Ca=pe(),wF={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ca.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ca._)`{limit: ${t}}`},xF={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:wF,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ca.operators.GT:Ca.operators.LT;t.fail$data((0,Ca._)`${r}.length ${o} ${n}`)}};Ty.default=xF});var $u=O(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var OE=Xg();OE.code='require("ajv/dist/runtime/equal").default';Py.default=OE});var CE=O(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});var Ry=ya(),St=pe(),SF=Pe(),$F=$u(),kF={message:({params:{i:t,j:e}})=>(0,St.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,St._)`{i: ${t}, j: ${e}}`},EF={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:kF,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,Ry.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,St._)`${i} === false`),t.ok(c);function u(){let f=e.let("i",(0,St._)`${r}.length`),h=e.let("j");t.setParams({i:f,j:h}),e.assign(c,!0),e.if((0,St._)`${f} > 1`,()=>(p()?m:d)(f,h))}function p(){return l.length>0&&!l.some(f=>f==="object"||f==="array")}function m(f,h){let g=e.name("item"),v=(0,Ry.checkDataTypes)(l,g,a.opts.strictNumbers,Ry.DataType.Wrong),_=e.const("indices",(0,St._)`{}`);e.for((0,St._)`;${f}--;`,()=>{e.let(g,(0,St._)`${r}[${f}]`),e.if(v,(0,St._)`continue`),l.length>1&&e.if((0,St._)`typeof ${g} == "string"`,(0,St._)`${g} += "_"`),e.if((0,St._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,St._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,St._)`${_}[${g}] = ${f}`)})}function d(f,h){let g=(0,SF.useFunc)(e,$F.default),v=e.name("outer");e.label(v).for((0,St._)`;${f}--;`,()=>e.for((0,St._)`${h} = ${f}; ${h}--;`,()=>e.if((0,St._)`${g}(${r}[${f}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};Oy.default=EF});var IE=O(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});var Cy=pe(),TF=Pe(),PF=$u(),RF={message:"must be equal to constant",params:({schemaCode:t})=>(0,Cy._)`{allowedValue: ${t}}`},OF={keyword:"const",$data:!0,error:RF,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Cy._)`!${(0,TF.useFunc)(e,PF.default)}(${r}, ${o})`):t.fail((0,Cy._)`${s} !== ${r}`)}};Iy.default=OF});var AE=O(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var Ia=pe(),CF=Pe(),IF=$u(),AF={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ia._)`{allowedValues: ${t}}`},NF={keyword:"enum",schemaType:"array",$data:!0,error:AF,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,CF.useFunc)(e,IF.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let d=e.const("vSchema",s);u=(0,Ia.or)(...o.map((f,h)=>m(d,h)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,d=>e.if((0,Ia._)`${l()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function m(d,f){let h=o[f];return typeof h=="object"&&h!==null?(0,Ia._)`${l()}(${r}, ${d}[${f}])`:(0,Ia._)`${r} === ${h}`}}};Ay.default=NF});var NE=O(Ny=>{"use strict";Object.defineProperty(Ny,"__esModule",{value:!0});var zF=wE(),jF=xE(),MF=kE(),LF=EE(),DF=TE(),qF=PE(),ZF=RE(),UF=CE(),FF=IE(),HF=AE(),BF=[zF.default,jF.default,MF.default,LF.default,DF.default,qF.default,ZF.default,UF.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},FF.default,HF.default];Ny.default=BF});var jy=O(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.validateAdditionalItems=void 0;var Vo=pe(),zy=Pe(),VF={message:({params:{len:t}})=>(0,Vo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Vo._)`{limit: ${t}}`},GF={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:VF,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,zy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}zE(t,n)}};function zE(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Vo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Vo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,zy.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Vo._)`${a} <= ${e.length}`);r.if((0,Vo.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:zy.Type.Num},l),i.allErrors||r.if((0,Vo.not)(l),()=>r.break())})}}Aa.validateAdditionalItems=zE;Aa.default=GF});var My=O(Na=>{"use strict";Object.defineProperty(Na,"__esModule",{value:!0});Na.validateTuple=void 0;var jE=pe(),ku=Pe(),WF=dr(),JF={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return ME(t,"additionalItems",e);r.items=!0,!(0,ku.alwaysValidSchema)(r,e)&&t.ok((0,WF.validateArray)(t))}};function ME(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=ku.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,jE._)`${s}.length`);r.forEach((p,m)=>{(0,ku.alwaysValidSchema)(a,p)||(n.if((0,jE._)`${l} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function u(p){let{opts:m,errSchemaPath:d}=a,f=r.length,h=f===p.minItems&&(f===p.maxItems||p[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${f}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,ku.checkStrictMode)(a,g,m.strictTuples)}}}Na.validateTuple=ME;Na.default=JF});var LE=O(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var KF=My(),YF={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,KF.validateTuple)(t,"items")};Ly.default=YF});var qE=O(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var DE=pe(),XF=Pe(),QF=dr(),e4=jy(),t4={message:({params:{len:t}})=>(0,DE.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,DE._)`{limit: ${t}}`},r4={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:t4,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,XF.alwaysValidSchema)(n,e)&&(o?(0,e4.validateAdditionalItems)(t,o):t.ok((0,QF.validateArray)(t)))}};Dy.default=r4});var ZE=O(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var mr=pe(),Eu=Pe(),n4={message:({params:{min:t,max:e}})=>e===void 0?(0,mr.str)`must contain at least ${t} valid item(s)`:(0,mr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,mr._)`{minContains: ${t}}`:(0,mr._)`{minContains: ${t}, maxContains: ${e}}`},o4={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:n4,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,mr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Eu.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Eu.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Eu.alwaysValidSchema)(s,r)){let h=(0,mr._)`${u} >= ${i}`;a!==void 0&&(h=(0,mr._)`${h} && ${u} <= ${a}`),t.pass(h);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?d(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,mr._)`${o}.length > 0`,m)):(e.let(p,!1),m()),t.result(p,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);d(h,()=>e.if(h,()=>f(g)))}function d(h,g){e.forRange("i",0,u,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Eu.Type.Num,compositeRule:!0},h),g()})}function f(h){e.code((0,mr._)`${h}++`),a===void 0?e.if((0,mr._)`${h} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,mr._)`${h} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,mr._)`${h} >= ${i}`,()=>e.assign(p,!0)))}}};qy.default=o4});var HE=O(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.validateSchemaDeps=Hr.validatePropertyDeps=Hr.error=void 0;var Zy=pe(),s4=Pe(),za=dr();Hr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Zy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Zy._)`{property: ${t},
288
+ ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var ig,$r,rq,Xl=w(()=>{zn();$r={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(ig===void 0&&(ig=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),ig),uuid:/^[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}$/,ipv4:/^(?:(?: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])$/,ipv4Cidr:/^(?:(?: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])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([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])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};rq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Ql(t,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&t.keyType?._def.typeName===P.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Je(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=Yl(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=Jl(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var eu=w(()=>{ca();at();Xl();Kl();pr()});function N$(t,e){if(e.mapStrategy==="record")return Ql(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Je(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var cg=w(()=>{at();eu();pr()});function z$(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var lg=w(()=>{});function j$(t){return t.target==="openAi"?void 0:{not:Je({...t,currentPath:[...t.currentPath,"not"]})}}var ug=w(()=>{pr()});function M$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var pg=w(()=>{});function D$(t,e){if(e.target==="openApi3")return L$(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ua&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ua[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];case"symbol":case"undefined":case"function":default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return L$(t,e)}var ua,L$,tu=w(()=>{at();ua={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};L$=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>Y(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function q$(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:ua[t.innerType._def.typeName],nullable:!0}:{type:[ua[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=Y(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var dg=w(()=>{at();tu()});function Z$(t,e){let r={type:"number"};if(!t.checks)return r;for(let n of t.checks)switch(n.kind){case"int":r.type="integer",Wh(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?Se(r,"minimum",n.value,n.message,e):Se(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),Se(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?Se(r,"maximum",n.value,n.message,e):Se(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),Se(r,"maximum",n.value,n.message,e));break;case"multipleOf":Se(r,"multipleOf",n.value,n.message,e);break}return r}var fg=w(()=>{zn()});function U$(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let l=sq(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=Y(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});u!==void 0&&(n.properties[a]=u,l||o.push(a))}o.length&&(n.required=o);let i=oq(t,e);return i!==void 0&&(n.additionalProperties=i),n}function oq(t,e){if(t.catchall._def.typeName!=="ZodNever")return Y(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function sq(t){try{return t.isOptional()}catch{return!0}}var mg=w(()=>{at()});var F$,hg=w(()=>{at();pr();F$=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return Y(t.innerType._def,e);let r=Y(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Je(e)},r]}:Je(e)}});var H$,gg=w(()=>{at();H$=(t,e)=>{if(e.pipeStrategy==="input")return Y(t.in._def,e);if(e.pipeStrategy==="output")return Y(t.out._def,e);let r=Y(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=Y(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function B$(t,e){return Y(t.type._def,e)}var yg=w(()=>{at()});function G$(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Se(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Se(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var vg=w(()=>{zn();at()});function V$(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:Y(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>Y(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var _g=w(()=>{at()});function W$(t){return{not:Je(t)}}var bg=w(()=>{pr()});function J$(t){return Je(t)}var wg=w(()=>{pr()});var K$,xg=w(()=>{at();K$=(t,e)=>Y(t.innerType._def,e)});var Y$,Sg=w(()=>{ca();pr();Jh();Kh();Yh();Kl();Xh();eg();tg();rg();ng();og();sg();cg();lg();ug();pg();dg();fg();mg();hg();gg();yg();eu();vg();Xl();_g();bg();tu();wg();xg();Y$=(t,e,r)=>{switch(e){case P.ZodString:return Yl(t,r);case P.ZodNumber:return Z$(t,r);case P.ZodObject:return U$(t,r);case P.ZodBigInt:return k$(t,r);case P.ZodBoolean:return E$();case P.ZodDate:return Qh(t,r);case P.ZodUndefined:return W$(r);case P.ZodNull:return M$(r);case P.ZodArray:return $$(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return D$(t,r);case P.ZodIntersection:return C$(t,r);case P.ZodTuple:return V$(t,r);case P.ZodRecord:return Ql(t,r);case P.ZodLiteral:return I$(t,r);case P.ZodEnum:return O$(t);case P.ZodNativeEnum:return z$(t);case P.ZodNullable:return q$(t,r);case P.ZodOptional:return F$(t,r);case P.ZodMap:return N$(t,r);case P.ZodSet:return G$(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return B$(t,r);case P.ZodNaN:case P.ZodNever:return j$(r);case P.ZodEffects:return R$(t,r);case P.ZodAny:return Je(r);case P.ZodUnknown:return J$(r);case P.ZodDefault:return P$(t,r);case P.ZodBranded:return Jl(t,r);case P.ZodReadonly:return K$(t,r);case P.ZodCatch:return T$(t,r);case P.ZodPipeline:return H$(t,r);case P.ZodFunction:case P.ZodVoid:case P.ZodSymbol:return;default:return(n=>{})(e)}}});function Y(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==w$)return a}if(n&&!r){let a=iq(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=Y$(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&aq(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var iq,aq,at=w(()=>{Gl();Sg();Wl();pr();iq=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Vl(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Je(e)):e.$refStrategy==="seen"?Je(e):void 0}},aq=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var X$=w(()=>{});var $g,kg=w(()=>{at();Vh();pr();$g=(t,e)=>{let r=S$(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:Y(u._def,{...r,currentPath:[...r.basePath,r.definitionPath,l]},!0)??Je(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=Y(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Je(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var Q$=w(()=>{Gl();Vh();zn();Wl();at();X$();pr();Jh();Kh();Yh();Kl();Xh();eg();tg();rg();ng();og();sg();cg();lg();ug();pg();dg();fg();mg();hg();gg();yg();xg();eu();vg();Xl();_g();bg();tu();wg();Sg();kg();kg()});function cq(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Eg(t,e){return ur(t)?th(t,{target:cq(e?.target),io:e?.pipeStrategy??"input"}):$g(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Tg(t){let r=An(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Bl(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Pg(t,e){let r=In(t,e);if(!r.success)throw r.error;return r.data}var Rg=w(()=>{Gh();la();Q$()});function ek(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function tk(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];ek(i)&&ek(s)?r[o]={...i,...s}:r[o]=s}return r}var lq,ru,rk=w(()=>{la();ks();_$();Rg();lq=6e4,ru=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(ll,r=>{this._oncancel(r)}),this.setNotificationHandler(dl,r=>{this._onprogress(r)}),this.setRequestHandler(pl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(fl,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(B.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(hl,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,l=c.id,u=this._requestResolvers.get(l);if(u)if(this._requestResolvers.delete(l),a.type==="response")u(c);else{let p=c,f=new D(p.error.code,p.error.message,p.error.data);u(f)}else{let p=a.type==="response"?"Response":"Error";this._onerror(new Error(`${p} handler missing for request ${l}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new D(B.InvalidParams,`Task not found: ${s}`);if(!Nn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Nn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[En]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(gl,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new D(B.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(vl,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(B.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nn(o.status))throw new D(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new D(B.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof D?o:new D(B.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),D.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),en(s)||ws(s)?this._onresponse(s):Tn(s)?this._onrequest(s,i):$S(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=D.fromError(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[En]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:B.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=wS(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,l={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async u=>{if(i.signal.aborted)return;let p={relatedRequestId:e.id};s&&(p.relatedTask={taskId:s}),await this.notification(u,p)},sendRequest:async(u,p,f)=>{if(i.signal.aborted)throw new D(B.ConnectionClosed,"Request was cancelled");let d={...f,relatedRequestId:e.id};s&&!d.relatedTask&&(d.relatedTask={taskId:s});let m=d.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,d)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:B.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),en(e))n(e);else{let i=new D(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(en(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),en(e))o(e);else{let i=D.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof D?i:new D(B.InternalError,String(i))}}return}let s;try{let i=await this.request(e,xs,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new D(B.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Nn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new D(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new D(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof D?i:new D(B.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=b=>{u(b)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){p(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(d.params={...d.params,task:a}),c&&(d.params={...d.params,_meta:{...d.params?._meta||{},[En]:c}});let m=b=>{this._responseHandlers.delete(f),this._progressHandlers.delete(f),this._cleanupTimeout(f),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:f,reason:String(b)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch($=>this._onerror(new Error(`Failed to send cancellation: ${$}`)));let x=b instanceof D?b:new D(B.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=In(r,b.result);x.success?l(x.data):u(x.error)}catch(x){u(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??lq,g=()=>m(D.fromError(B.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let v=c?.taskId;if(v){let b=x=>{let $=this._responseHandlers.get(f);$?$(x):this._onerror(new Error(`Response handler missing for side-channeled request ${f}`))};this._requestResolvers.set(f,b),this._enqueueTaskMessage(v,{type:"request",message:d,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(f),u(x)})}else this._transport.send(d,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(f),u(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},ml,r)}async getTaskResult(e,r,n){return this.request({method:"tasks/result",params:e},r,n)}async listTasks(e,r){return this.request({method:"tasks/list",params:e},yl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ES,r)}async notification(e,r){if(!this._transport)throw new Error("Not connected");this.assertNotificationCapability(e.method);let n=r?.relatedTask?.taskId;if(n){let a={...e,jsonrpc:"2.0",params:{...e.params,_meta:{...e.params?._meta||{},[En]:r.relatedTask}}};await this._enqueueTaskMessage(n,{type:"notification",message:a,timestamp:Date.now()});return}if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!r?.relatedRequestId&&!r?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let a={...e,jsonrpc:"2.0"};r?.relatedTask&&(a={...a,params:{...a.params,_meta:{...a.params?._meta||{},[En]:r.relatedTask}}}),this._transport?.send(a,r).catch(c=>this._onerror(c))});return}let i={...e,jsonrpc:"2.0"};r?.relatedTask&&(i={...i,params:{...i.params,_meta:{...i.params?._meta||{},[En]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Tg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Pg(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Tg(e);this._notificationHandlers.set(n,o=>{let s=Pg(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Tn(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new D(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new D(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new D(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new D(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Qi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Nn(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new D(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Nn(a.status))throw new D(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=Qi.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Nn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var fa=I(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.regexpCode=Te.getEsmExportName=Te.getProperty=Te.safeStringify=Te.stringify=Te.strConcat=Te.addCodeArg=Te.str=Te._=Te.nil=Te._Code=Te.Name=Te.IDENTIFIER=Te._CodeOrName=void 0;var pa=class{};Te._CodeOrName=pa;Te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Lo=class extends pa{constructor(e){if(super(),!Te.IDENTIFIER.test(e))throw new Error("CodeGen: name must be a valid identifier");this.str=e}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};Te.Name=Lo;var dr=class extends pa{constructor(e){super(),this._items=typeof e=="string"?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===""||e==='""'}get str(){var e;return(e=this._str)!==null&&e!==void 0?e:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var e;return(e=this._names)!==null&&e!==void 0?e:this._names=this._items.reduce((r,n)=>(n instanceof Lo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Te._Code=dr;Te.nil=new dr("");function nk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Cg(r,e[n]),r.push(t[++n]);return new dr(r)}Te._=nk;var Og=new dr("+");function ok(t,...e){let r=[da(t[0])],n=0;for(;n<e.length;)r.push(Og),Cg(r,e[n]),r.push(Og,da(t[++n]));return uq(r),new dr(r)}Te.str=ok;function Cg(t,e){e instanceof dr?t.push(...e._items):e instanceof Lo?t.push(e):t.push(fq(e))}Te.addCodeArg=Cg;function uq(t){let e=1;for(;e<t.length-1;){if(t[e]===Og){let r=pq(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function pq(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Lo||t[t.length-1]!=='"'?void 0:typeof e!="string"?`${t.slice(0,-1)}${e}"`:e[0]==='"'?t.slice(0,-1)+e.slice(1):void 0;if(typeof e=="string"&&e[0]==='"'&&!(t instanceof Lo))return`"${t}${e.slice(1)}`}function dq(t,e){return e.emptyStr()?t:t.emptyStr()?e:ok`${t}${e}`}Te.strConcat=dq;function fq(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:da(Array.isArray(t)?t.join(","):t)}function mq(t){return new dr(da(t))}Te.stringify=mq;function da(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Te.safeStringify=da;function hq(t){return typeof t=="string"&&Te.IDENTIFIER.test(t)?new dr(`.${t}`):nk`[${t}]`}Te.getProperty=hq;function gq(t){if(typeof t=="string"&&Te.IDENTIFIER.test(t))return new dr(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Te.getEsmExportName=gq;function yq(t){return new dr(t.toString())}Te.regexpCode=yq});var Ng=I(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.ValueScope=Gt.ValueScopeName=Gt.Scope=Gt.varKinds=Gt.UsedValueState=void 0;var Bt=fa(),Ig=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},nu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(nu||(Gt.UsedValueState=nu={}));Gt.varKinds={const:new Bt.Name("const"),let:new Bt.Name("let"),var:new Bt.Name("var")};var ou=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Bt.Name?e:this.name(e)}name(e){return new Bt.Name(this._newName(e))}_newName(e){let r=this._names[e]||this._nameGroup(e);return`${e}${r.index++}`}_nameGroup(e){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(e)||this._prefixes&&!this._prefixes.has(e))throw new Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};Gt.Scope=ou;var su=class extends Bt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Bt._)`.${new Bt.Name(r)}[${n}]`}};Gt.ValueScopeName=su;var vq=(0,Bt._)`\n`,Ag=class extends ou{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?vq:Bt.nil}}get(){return this._scope}name(e){return new su(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let u=a.get(i);if(u)return u}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),l=c.length;return c[l]=r.ref,o.setValue(r,{property:s,itemIndex:l}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Bt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=Bt.nil;for(let i in e){let a=e[i];if(!a)continue;let c=n[i]=n[i]||new Map;a.forEach(l=>{if(c.has(l))return;c.set(l,nu.Started);let u=r(l);if(u){let p=this.opts.es5?Gt.varKinds.var:Gt.varKinds.const;s=(0,Bt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Bt._)`${s}${u}${this.opts._n}`;else throw new Ig(l);c.set(l,nu.Completed)})}return s}};Gt.ValueScope=Ag});var de=I(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.or=he.and=he.not=he.CodeGen=he.operators=he.varKinds=he.ValueScopeName=he.ValueScope=he.Scope=he.Name=he.regexpCode=he.stringify=he.getProperty=he.nil=he.strConcat=he.str=he._=void 0;var $e=fa(),Er=Ng(),jn=fa();Object.defineProperty(he,"_",{enumerable:!0,get:function(){return jn._}});Object.defineProperty(he,"str",{enumerable:!0,get:function(){return jn.str}});Object.defineProperty(he,"strConcat",{enumerable:!0,get:function(){return jn.strConcat}});Object.defineProperty(he,"nil",{enumerable:!0,get:function(){return jn.nil}});Object.defineProperty(he,"getProperty",{enumerable:!0,get:function(){return jn.getProperty}});Object.defineProperty(he,"stringify",{enumerable:!0,get:function(){return jn.stringify}});Object.defineProperty(he,"regexpCode",{enumerable:!0,get:function(){return jn.regexpCode}});Object.defineProperty(he,"Name",{enumerable:!0,get:function(){return jn.Name}});var lu=Ng();Object.defineProperty(he,"Scope",{enumerable:!0,get:function(){return lu.Scope}});Object.defineProperty(he,"ValueScope",{enumerable:!0,get:function(){return lu.ValueScope}});Object.defineProperty(he,"ValueScopeName",{enumerable:!0,get:function(){return lu.ValueScopeName}});Object.defineProperty(he,"varKinds",{enumerable:!0,get:function(){return lu.varKinds}});he.operators={GT:new $e._Code(">"),GTE:new $e._Code(">="),LT:new $e._Code("<"),LTE:new $e._Code("<="),EQ:new $e._Code("==="),NEQ:new $e._Code("!=="),NOT:new $e._Code("!"),OR:new $e._Code("||"),AND:new $e._Code("&&"),ADD:new $e._Code("+")};var sn=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},zg=class extends sn{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Er.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=Ds(this.rhs,e,r)),this}get names(){return this.rhs instanceof $e._CodeOrName?this.rhs.names:{}}},iu=class extends sn{constructor(e,r,n){super(),this.lhs=e,this.rhs=r,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,r){if(!(this.lhs instanceof $e.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Ds(this.rhs,e,r),this}get names(){let e=this.lhs instanceof $e.Name?{}:{...this.lhs.names};return cu(e,this.rhs)}},jg=class extends iu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Mg=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Lg=class extends sn{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Dg=class extends sn{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},qg=class extends sn{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,r){return this.code=Ds(this.code,e,r),this}get names(){return this.code instanceof $e._CodeOrName?this.code.names:{}}},ma=class extends sn{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(_q(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Zo(e,r.names),{})}},an=class extends ma{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Zg=class extends ma{},Ls=class extends an{};Ls.kind="else";var Do=class t extends an{constructor(e,r){super(r),this.condition=e}render(e){let r=`if(${this.condition})`+super.render(e);return this.else&&(r+="else "+this.else.render(e)),r}optimizeNodes(){super.optimizeNodes();let e=this.condition;if(e===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Ls(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(sk(e),r instanceof t?[r]:r.nodes);if(!(e===!1||!this.nodes.length))return this}optimizeNames(e,r){var n;if(this.else=(n=this.else)===null||n===void 0?void 0:n.optimizeNames(e,r),!!(super.optimizeNames(e,r)||this.else))return this.condition=Ds(this.condition,e,r),this}get names(){let e=super.names;return cu(e,this.condition),this.else&&Zo(e,this.else.names),e}};Do.kind="if";var qo=class extends an{};qo.kind="for";var Ug=class extends qo{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iteration=Ds(this.iteration,e,r),this}get names(){return Zo(super.names,this.iteration.names)}},Fg=class extends qo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Er.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=cu(super.names,this.from);return cu(e,this.to)}},au=class extends qo{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=Ds(this.iterable,e,r),this}get names(){return Zo(super.names,this.iterable.names)}},ha=class extends an{constructor(e,r,n){super(),this.name=e,this.args=r,this.async=n}render(e){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(e)}};ha.kind="func";var ga=class extends ma{render(e){return"return "+super.render(e)}};ga.kind="return";var Hg=class extends an{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Zo(e,this.catch.names),this.finally&&Zo(e,this.finally.names),e}},ya=class extends an{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ya.kind="catch";var va=class extends an{render(e){return"finally"+super.render(e)}};va.kind="finally";var Bg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
289
+ `:""},this._extScope=e,this._scope=new Er.Scope({parent:e}),this._nodes=[new Zg]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new zg(e,s,n)),s}const(e,r,n){return this._def(Er.varKinds.const,e,r,n)}let(e,r,n){return this._def(Er.varKinds.let,e,r,n)}var(e,r,n){return this._def(Er.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new iu(e,r,n))}add(e,r){return this._leafNode(new jg(e,he.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==$e.nil&&this._leafNode(new qg(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,$e.addCodeArg)(r,o));return r.push("}"),new $e._Code(r)}if(e,r,n){if(this._blockNode(new Do(e)),r&&n)this.code(r).else().code(n).endIf();else if(r)this.code(r).endIf();else if(n)throw new Error('CodeGen: "else" body without "then" body');return this}elseIf(e){return this._elseNode(new Do(e))}else(){return this._elseNode(new Ls)}endIf(){return this._endBlockNode(Do,Ls)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ug(e),r)}forRange(e,r,n,o,s=this.opts.es5?Er.varKinds.var:Er.varKinds.let){let i=this._scope.toName(e);return this._for(new Fg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Er.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof $e.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,$e._)`${i}.length`,a=>{this.var(s,(0,$e._)`${i}[${a}]`),n(s)})}return this._for(new au("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Er.varKinds.var:Er.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,$e._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new au("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(qo)}label(e){return this._leafNode(new Mg(e))}break(e){return this._leafNode(new Lg(e))}return(e){let r=new ga;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ga)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Hg;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ya(s),r(s)}return n&&(this._currNode=o.finally=new va,this.code(n)),this._endBlockNode(ya,va)}throw(e){return this._leafNode(new Dg(e))}block(e,r){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(r),this}endBlock(e){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||e!==void 0&&n!==e)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=r,this}func(e,r=$e.nil,n,o){return this._blockNode(new ha(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ha)}optimize(e=1){for(;e-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,r){let n=this._currNode;if(n instanceof e||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${e.kind}/${r.kind}`:e.kind}"`)}_elseNode(e){let r=this._currNode;if(!(r instanceof Do))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let r=this._nodes;r[r.length-1]=e}};he.CodeGen=Bg;function Zo(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function cu(t,e){return e instanceof $e._CodeOrName?Zo(t,e.names):t}function Ds(t,e,r){if(t instanceof $e.Name)return n(t);if(!o(t))return t;return new $e._Code(t._items.reduce((s,i)=>(i instanceof $e.Name&&(i=n(i)),i instanceof $e._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof $e._Code&&s._items.some(i=>i instanceof $e.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function _q(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function sk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,$e._)`!${Gg(t)}`}he.not=sk;var bq=ik(he.operators.AND);function wq(...t){return t.reduce(bq)}he.and=wq;var xq=ik(he.operators.OR);function Sq(...t){return t.reduce(xq)}he.or=Sq;function ik(t){return(e,r)=>e===$e.nil?r:r===$e.nil?e:(0,$e._)`${Gg(e)} ${t} ${Gg(r)}`}function Gg(t){return t instanceof $e.Name?t:(0,$e._)`(${t})`}});var Pe=I(ve=>{"use strict";Object.defineProperty(ve,"__esModule",{value:!0});ve.checkStrictMode=ve.getErrorPath=ve.Type=ve.useFunc=ve.setEvaluated=ve.evaluatedPropsToName=ve.mergeEvaluated=ve.eachItem=ve.unescapeJsonPointer=ve.escapeJsonPointer=ve.escapeFragment=ve.unescapeFragment=ve.schemaRefOrVal=ve.schemaHasRulesButRef=ve.schemaHasRules=ve.checkUnknownRules=ve.alwaysValidSchema=ve.toHash=void 0;var ze=de(),$q=fa();function kq(t){let e={};for(let r of t)e[r]=!0;return e}ve.toHash=kq;function Eq(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(lk(t,e),!uk(e,t.self.RULES.all))}ve.alwaysValidSchema=Eq;function lk(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||fk(t,`unknown keyword: "${s}"`)}ve.checkUnknownRules=lk;function uk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ve.schemaHasRules=uk;function Tq(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ve.schemaHasRulesButRef=Tq;function Pq({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ze._)`${r}`}return(0,ze._)`${t}${e}${(0,ze.getProperty)(n)}`}ve.schemaRefOrVal=Pq;function Rq(t){return pk(decodeURIComponent(t))}ve.unescapeFragment=Rq;function Oq(t){return encodeURIComponent(Wg(t))}ve.escapeFragment=Oq;function Wg(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ve.escapeJsonPointer=Wg;function pk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ve.unescapeJsonPointer=pk;function Cq(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ve.eachItem=Cq;function ak({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof ze.Name?(s instanceof ze.Name?t(o,s,i):e(o,s,i),i):s instanceof ze.Name?(e(o,i,s),s):r(s,i);return a===ze.Name&&!(c instanceof ze.Name)?n(o,c):c}}ve.mergeEvaluated={props:ak({mergeNames:(t,e,r)=>t.if((0,ze._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ze._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ze._)`${r} || {}`).code((0,ze._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ze._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ze._)`${r} || {}`),Jg(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:dk}),items:ak({mergeNames:(t,e,r)=>t.if((0,ze._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ze._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ze._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ze._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function dk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ze._)`{}`);return e!==void 0&&Jg(t,r,e),r}ve.evaluatedPropsToName=dk;function Jg(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ze._)`${e}${(0,ze.getProperty)(n)}`,!0))}ve.setEvaluated=Jg;var ck={};function Iq(t,e){return t.scopeValue("func",{ref:e,code:ck[e.code]||(ck[e.code]=new $q._Code(e.code))})}ve.useFunc=Iq;var Vg;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Vg||(ve.Type=Vg={}));function Aq(t,e,r){if(t instanceof ze.Name){let n=e===Vg.Num;return r?n?(0,ze._)`"[" + ${t} + "]"`:(0,ze._)`"['" + ${t} + "']"`:n?(0,ze._)`"/" + ${t}`:(0,ze._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ze.getProperty)(t).toString():"/"+Wg(t)}ve.getErrorPath=Aq;function fk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ve.checkStrictMode=fk});var cn=I(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var Tt=de(),Nq={data:new Tt.Name("data"),valCxt:new Tt.Name("valCxt"),instancePath:new Tt.Name("instancePath"),parentData:new Tt.Name("parentData"),parentDataProperty:new Tt.Name("parentDataProperty"),rootData:new Tt.Name("rootData"),dynamicAnchors:new Tt.Name("dynamicAnchors"),vErrors:new Tt.Name("vErrors"),errors:new Tt.Name("errors"),this:new Tt.Name("this"),self:new Tt.Name("self"),scope:new Tt.Name("scope"),json:new Tt.Name("json"),jsonPos:new Tt.Name("jsonPos"),jsonLen:new Tt.Name("jsonLen"),jsonPart:new Tt.Name("jsonPart")};Kg.default=Nq});var _a=I(Pt=>{"use strict";Object.defineProperty(Pt,"__esModule",{value:!0});Pt.extendErrors=Pt.resetErrorsCount=Pt.reportExtraError=Pt.reportError=Pt.keyword$DataError=Pt.keywordError=void 0;var ke=de(),uu=Pe(),Nt=cn();Pt.keywordError={message:({keyword:t})=>(0,ke.str)`must pass "${t}" keyword validation`};Pt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ke.str)`"${t}" keyword must be ${e} ($data)`:(0,ke.str)`"${t}" keyword is invalid ($data)`};function zq(t,e=Pt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=gk(t,e,r);n??(i||a)?mk(s,c):hk(o,(0,ke._)`[${c}]`)}Pt.reportError=zq;function jq(t,e=Pt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=gk(t,e,r);mk(o,a),s||i||hk(n,Nt.default.vErrors)}Pt.reportExtraError=jq;function Mq(t,e){t.assign(Nt.default.errors,e),t.if((0,ke._)`${Nt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ke._)`${Nt.default.vErrors}.length`,e),()=>t.assign(Nt.default.vErrors,null)))}Pt.resetErrorsCount=Mq;function Lq({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,Nt.default.errors,a=>{t.const(i,(0,ke._)`${Nt.default.vErrors}[${a}]`),t.if((0,ke._)`${i}.instancePath === undefined`,()=>t.assign((0,ke._)`${i}.instancePath`,(0,ke.strConcat)(Nt.default.instancePath,s.errorPath))),t.assign((0,ke._)`${i}.schemaPath`,(0,ke.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ke._)`${i}.schema`,r),t.assign((0,ke._)`${i}.data`,n))})}Pt.extendErrors=Lq;function mk(t,e){let r=t.const("err",e);t.if((0,ke._)`${Nt.default.vErrors} === null`,()=>t.assign(Nt.default.vErrors,(0,ke._)`[${r}]`),(0,ke._)`${Nt.default.vErrors}.push(${r})`),t.code((0,ke._)`${Nt.default.errors}++`)}function hk(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ke._)`new ${t.ValidationError}(${e})`):(r.assign((0,ke._)`${n}.errors`,e),r.return(!1))}var Uo={keyword:new ke.Name("keyword"),schemaPath:new ke.Name("schemaPath"),params:new ke.Name("params"),propertyName:new ke.Name("propertyName"),message:new ke.Name("message"),schema:new ke.Name("schema"),parentSchema:new ke.Name("parentSchema")};function gk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ke._)`{}`:Dq(t,e,r)}function Dq(t,e,r={}){let{gen:n,it:o}=t,s=[qq(o,r),Zq(t,r)];return Uq(t,e,s),n.object(...s)}function qq({errorPath:t},{instancePath:e}){let r=e?(0,ke.str)`${t}${(0,uu.getErrorPath)(e,uu.Type.Str)}`:t;return[Nt.default.instancePath,(0,ke.strConcat)(Nt.default.instancePath,r)]}function Zq({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ke.str)`${e}/${t}`;return r&&(o=(0,ke.str)`${o}${(0,uu.getErrorPath)(r,uu.Type.Str)}`),[Uo.schemaPath,o]}function Uq(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:l,topSchemaRef:u,schemaPath:p}=a;n.push([Uo.keyword,o],[Uo.params,typeof e=="function"?e(t):e||(0,ke._)`{}`]),c.messages&&n.push([Uo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Uo.schema,i],[Uo.parentSchema,(0,ke._)`${u}${p}`],[Nt.default.data,s]),l&&n.push([Uo.propertyName,l])}});var vk=I(qs=>{"use strict";Object.defineProperty(qs,"__esModule",{value:!0});qs.boolOrEmptySchema=qs.topBoolOrEmptySchema=void 0;var Fq=_a(),Hq=de(),Bq=cn(),Gq={message:"boolean schema is false"};function Vq(t){let{gen:e,schema:r,validateName:n}=t;r===!1?yk(t,!1):typeof r=="object"&&r.$async===!0?e.return(Bq.default.data):(e.assign((0,Hq._)`${n}.errors`,null),e.return(!0))}qs.topBoolOrEmptySchema=Vq;function Wq(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),yk(t)):r.var(e,!0)}qs.boolOrEmptySchema=Wq;function yk(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,Fq.reportError)(o,Gq,void 0,e)}});var Yg=I(Zs=>{"use strict";Object.defineProperty(Zs,"__esModule",{value:!0});Zs.getRules=Zs.isJSONType=void 0;var Jq=["string","number","integer","boolean","null","object","array"],Kq=new Set(Jq);function Yq(t){return typeof t=="string"&&Kq.has(t)}Zs.isJSONType=Yq;function Xq(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Zs.getRules=Xq});var Xg=I(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.shouldUseRule=Mn.shouldUseGroup=Mn.schemaHasRulesForType=void 0;function Qq({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&_k(t,n)}Mn.schemaHasRulesForType=Qq;function _k(t,e){return e.rules.some(r=>bk(t,r))}Mn.shouldUseGroup=_k;function bk(t,e){var r;return t[e.keyword]!==void 0||((r=e.definition.implements)===null||r===void 0?void 0:r.some(n=>t[n]!==void 0))}Mn.shouldUseRule=bk});var ba=I(Rt=>{"use strict";Object.defineProperty(Rt,"__esModule",{value:!0});Rt.reportTypeError=Rt.checkDataTypes=Rt.checkDataType=Rt.coerceAndCheckDataType=Rt.getJSONTypes=Rt.getSchemaTypes=Rt.DataType=void 0;var eZ=Yg(),tZ=Xg(),rZ=_a(),le=de(),wk=Pe(),Us;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Us||(Rt.DataType=Us={}));function nZ(t){let e=xk(t.type);if(e.includes("null")){if(t.nullable===!1)throw new Error("type: null contradicts nullable: false")}else{if(!e.length&&t.nullable!==void 0)throw new Error('"nullable" cannot be used without "type"');t.nullable===!0&&e.push("null")}return e}Rt.getSchemaTypes=nZ;function xk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(eZ.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}Rt.getJSONTypes=xk;function oZ(t,e){let{gen:r,data:n,opts:o}=t,s=sZ(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,tZ.schemaHasRulesForType)(t,e[0]));if(i){let a=ey(e,n,o.strictNumbers,Us.Wrong);r.if(a,()=>{s.length?iZ(t,e,s):ty(t)})}return i}Rt.coerceAndCheckDataType=oZ;var Sk=new Set(["string","number","integer","boolean","null"]);function sZ(t,e){return e?t.filter(r=>Sk.has(r)||e==="array"&&r==="array"):[]}function iZ(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,le._)`typeof ${o}`),a=n.let("coerced",(0,le._)`undefined`);s.coerceTypes==="array"&&n.if((0,le._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,le._)`${o}[0]`).assign(i,(0,le._)`typeof ${o}`).if(ey(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,le._)`${a} !== undefined`);for(let l of r)(Sk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),ty(t),n.endIf(),n.if((0,le._)`${a} !== undefined`,()=>{n.assign(o,a),aZ(t,a)});function c(l){switch(l){case"string":n.elseIf((0,le._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,le._)`"" + ${o}`).elseIf((0,le._)`${o} === null`).assign(a,(0,le._)`""`);return;case"number":n.elseIf((0,le._)`${i} == "boolean" || ${o} === null
290
+ || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,le._)`+${o}`);return;case"integer":n.elseIf((0,le._)`${i} === "boolean" || ${o} === null
291
+ || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,le._)`+${o}`);return;case"boolean":n.elseIf((0,le._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,le._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,le._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,le._)`${i} === "string" || ${i} === "number"
292
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,le._)`[${o}]`)}}}function aZ({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,le._)`${e} !== undefined`,()=>t.assign((0,le._)`${e}[${r}]`,n))}function Qg(t,e,r,n=Us.Correct){let o=n===Us.Correct?le.operators.EQ:le.operators.NEQ,s;switch(t){case"null":return(0,le._)`${e} ${o} null`;case"array":s=(0,le._)`Array.isArray(${e})`;break;case"object":s=(0,le._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,le._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,le._)`typeof ${e} ${o} ${t}`}return n===Us.Correct?s:(0,le.not)(s);function i(a=le.nil){return(0,le.and)((0,le._)`typeof ${e} == "number"`,a,r?(0,le._)`isFinite(${e})`:le.nil)}}Rt.checkDataType=Qg;function ey(t,e,r,n){if(t.length===1)return Qg(t[0],e,r,n);let o,s=(0,wk.toHash)(t);if(s.array&&s.object){let i=(0,le._)`typeof ${e} != "object"`;o=s.null?i:(0,le._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=le.nil;s.number&&delete s.integer;for(let i in s)o=(0,le.and)(o,Qg(i,e,r,n));return o}Rt.checkDataTypes=ey;var cZ={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,le._)`{type: ${t}}`:(0,le._)`{type: ${e}}`};function ty(t){let e=lZ(t);(0,rZ.reportError)(e,cZ)}Rt.reportTypeError=ty;function lZ(t){let{gen:e,data:r,schema:n}=t,o=(0,wk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var kk=I(pu=>{"use strict";Object.defineProperty(pu,"__esModule",{value:!0});pu.assignDefaults=void 0;var Fs=de(),uZ=Pe();function pZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)$k(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>$k(t,s,o.default))}pu.assignDefaults=pZ;function $k(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Fs._)`${s}${(0,Fs.getProperty)(e)}`;if(o){(0,uZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Fs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Fs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fs._)`${a} = ${(0,Fs.stringify)(r)}`)}});var fr=I(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.validateUnion=Ne.validateArray=Ne.usePattern=Ne.callValidateCode=Ne.schemaProperties=Ne.allSchemaProperties=Ne.noPropertyInData=Ne.propertyInData=Ne.isOwnProperty=Ne.hasPropFunc=Ne.reportMissingProp=Ne.checkMissingProp=Ne.checkReportMissingProp=void 0;var Fe=de(),ry=Pe(),Ln=cn(),dZ=Pe();function fZ(t,e){let{gen:r,data:n,it:o}=t;r.if(oy(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Fe._)`${e}`},!0),t.error()})}Ne.checkReportMissingProp=fZ;function mZ({gen:t,data:e,it:{opts:r}},n,o){return(0,Fe.or)(...n.map(s=>(0,Fe.and)(oy(t,e,s,r.ownProperties),(0,Fe._)`${o} = ${s}`)))}Ne.checkMissingProp=mZ;function hZ(t,e){t.setParams({missingProperty:e},!0),t.error()}Ne.reportMissingProp=hZ;function Ek(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Fe._)`Object.prototype.hasOwnProperty`})}Ne.hasPropFunc=Ek;function ny(t,e,r){return(0,Fe._)`${Ek(t)}.call(${e}, ${r})`}Ne.isOwnProperty=ny;function gZ(t,e,r,n){let o=(0,Fe._)`${e}${(0,Fe.getProperty)(r)} !== undefined`;return n?(0,Fe._)`${o} && ${ny(t,e,r)}`:o}Ne.propertyInData=gZ;function oy(t,e,r,n){let o=(0,Fe._)`${e}${(0,Fe.getProperty)(r)} === undefined`;return n?(0,Fe.or)(o,(0,Fe.not)(ny(t,e,r))):o}Ne.noPropertyInData=oy;function Tk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ne.allSchemaProperties=Tk;function yZ(t,e){return Tk(e).filter(r=>!(0,ry.alwaysValidSchema)(t,e[r]))}Ne.schemaProperties=yZ;function vZ({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,Fe._)`${t}, ${e}, ${n}${o}`:e,p=[[Ln.default.instancePath,(0,Fe.strConcat)(Ln.default.instancePath,s)],[Ln.default.parentData,i.parentData],[Ln.default.parentDataProperty,i.parentDataProperty],[Ln.default.rootData,Ln.default.rootData]];i.opts.dynamicRef&&p.push([Ln.default.dynamicAnchors,Ln.default.dynamicAnchors]);let f=(0,Fe._)`${u}, ${r.object(...p)}`;return c!==Fe.nil?(0,Fe._)`${a}.call(${c}, ${f})`:(0,Fe._)`${a}(${f})`}Ne.callValidateCode=vZ;var _Z=(0,Fe._)`new RegExp`;function bZ({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Fe._)`${o.code==="new RegExp"?_Z:(0,dZ.useFunc)(t,o)}(${r}, ${n})`})}Ne.usePattern=bZ;function wZ(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Fe._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:ry.Type.Num},s),e.if((0,Fe.not)(s),a)})}}Ne.validateArray=wZ;function xZ(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,ry.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,l)=>{let u=t.subschema({keyword:n,schemaProp:l,compositeRule:!0},a);e.assign(i,(0,Fe._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,Fe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ne.validateUnion=xZ});var Ok=I(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.validateKeywordUsage=Zr.validSchemaType=Zr.funcKeywordCode=Zr.macroKeywordCode=void 0;var zt=de(),Fo=cn(),SZ=fr(),$Z=_a();function kZ(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Rk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:zt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Zr.macroKeywordCode=kZ;function EZ(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;PZ(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Rk(n,o,l),p=n.let("valid");t.block$data(p,f),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function f(){if(e.errors===!1)h(),e.modifying&&Pk(t),g(()=>t.error());else{let v=e.async?d():m();e.modifying&&Pk(t),g(()=>TZ(t,v))}}function d(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,zt._)`await `),b=>n.assign(p,!1).if((0,zt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,zt._)`${b}.errors`),()=>n.throw(b))),v}function m(){let v=(0,zt._)`${u}.errors`;return n.assign(v,null),h(zt.nil),v}function h(v=e.async?(0,zt._)`await `:zt.nil){let b=c.opts.passContext?Fo.default.this:Fo.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,zt._)`${v}${(0,SZ.callValidateCode)(t,u,b,x)}`,e.modifying)}function g(v){var b;n.if((0,zt.not)((b=e.valid)!==null&&b!==void 0?b:p),v)}}Zr.funcKeywordCode=EZ;function Pk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,zt._)`${n.parentData}[${n.parentDataProperty}]`))}function TZ(t,e){let{gen:r}=t;r.if((0,zt._)`Array.isArray(${e})`,()=>{r.assign(Fo.default.vErrors,(0,zt._)`${Fo.default.vErrors} === null ? ${e} : ${Fo.default.vErrors}.concat(${e})`).assign(Fo.default.errors,(0,zt._)`${Fo.default.vErrors}.length`),(0,$Z.extendErrors)(t)},()=>t.error())}function PZ({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Rk(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,zt.stringify)(r)})}function RZ(t,e,r=!1){return!e.length||e.some(n=>n==="array"?Array.isArray(t):n==="object"?t&&typeof t=="object"&&!Array.isArray(t):typeof t==n||r&&typeof t>"u")}Zr.validSchemaType=RZ;function OZ({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}Zr.validateKeywordUsage=OZ});var Ik=I(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.extendSubschemaMode=Dn.extendSubschemaData=Dn.getSubschema=void 0;var Ur=de(),Ck=Pe();function CZ(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,Ur._)`${t.schemaPath}${(0,Ur.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Ur._)`${t.schemaPath}${(0,Ur.getProperty)(e)}${(0,Ur.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Ck.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}Dn.getSubschema=CZ;function IZ(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:l,dataPathArr:u,opts:p}=e,f=a.let("data",(0,Ur._)`${e.data}${(0,Ur.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Ur.str)`${l}${(0,Ck.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,Ur._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Ur.Name?o:a.let("data",o,!0);c(l),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(l){t.data=l,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,l]}}Dn.extendSubschemaData=IZ;function AZ(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}Dn.extendSubschemaMode=AZ});var sy=I((LX,Ak)=>{"use strict";Ak.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var zk=I((DX,Nk)=>{"use strict";var qn=Nk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};du(e,n,o,t,"",t)};qn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};qn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};qn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};qn.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function du(t,e,r,n,o,s,i,a,c,l){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,l);for(var u in n){var p=n[u];if(Array.isArray(p)){if(u in qn.arrayKeywords)for(var f=0;f<p.length;f++)du(t,e,r,p[f],o+"/"+u+"/"+f,s,o,u,n,f)}else if(u in qn.propsKeywords){if(p&&typeof p=="object")for(var d in p)du(t,e,r,p[d],o+"/"+u+"/"+NZ(d),s,o,u,n,d)}else(u in qn.keywords||t.allKeys&&!(u in qn.skipKeywords))&&du(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function NZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var wa=I(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.getSchemaRefs=Vt.resolveUrl=Vt.normalizeId=Vt._getFullPath=Vt.getFullPath=Vt.inlineRef=void 0;var zZ=Pe(),jZ=sy(),MZ=zk(),LZ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function DZ(t,e=!0){return typeof t=="boolean"?!0:e===!0?!iy(t):e?jk(t)<=e:!1}Vt.inlineRef=DZ;var qZ=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function iy(t){for(let e in t){if(qZ.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(iy)||typeof r=="object"&&iy(r))return!0}return!1}function jk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!LZ.has(r)&&(typeof t[r]=="object"&&(0,zZ.eachItem)(t[r],n=>e+=jk(n)),e===1/0))return 1/0}return e}function Mk(t,e="",r){r!==!1&&(e=Hs(e));let n=t.parse(e);return Lk(t,n)}Vt.getFullPath=Mk;function Lk(t,e){return t.serialize(e).split("#")[0]+"#"}Vt._getFullPath=Lk;var ZZ=/#\/?$/;function Hs(t){return t?t.replace(ZZ,""):""}Vt.normalizeId=Hs;function UZ(t,e,r){return r=Hs(r),t.resolve(e,r)}Vt.resolveUrl=UZ;var FZ=/^[a-z_][-a-z0-9._]*$/i;function HZ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Hs(t[r]||e),s={"":o},i=Mk(n,o,!1),a={},c=new Set;return MZ(t,{allKeys:!0},(p,f,d,m)=>{if(m===void 0)return;let h=i+f,g=s[m];typeof p[r]=="string"&&(g=v.call(this,p[r])),b.call(this,p.$anchor),b.call(this,p.$dynamicAnchor),s[f]=g;function v(x){let $=this.opts.uriResolver.resolve;if(x=Hs(g?$(g,x):x),c.has(x))throw u(x);c.add(x);let O=this.refs[x];return typeof O=="string"&&(O=this.refs[O]),typeof O=="object"?l(p,O.schema,x):x!==Hs(h)&&(x[0]==="#"?(l(p,a[x],x),a[x]=p):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!FZ.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`)}}}),a;function l(p,f,d){if(f!==void 0&&!jZ(p,f))throw u(d)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Vt.getSchemaRefs=HZ});var $a=I(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.getData=Zn.KeywordCxt=Zn.validateFunctionCode=void 0;var Fk=vk(),Dk=ba(),cy=Xg(),fu=ba(),BZ=kk(),Sa=Ok(),ay=Ik(),Z=de(),re=cn(),GZ=wa(),ln=Pe(),xa=_a();function VZ(t){if(Gk(t)&&(Vk(t),Bk(t))){KZ(t);return}Hk(t,()=>(0,Fk.topBoolOrEmptySchema)(t))}Zn.validateFunctionCode=VZ;function Hk({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${qk(r,o)}`),JZ(t,o),t.code(s)}):t.func(e,(0,Z._)`${re.default.data}, ${WZ(o)}`,n.$async,()=>t.code(qk(r,o)).code(s))}function WZ(t){return(0,Z._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${t.dynamicRef?(0,Z._)`, ${re.default.dynamicAnchors}={}`:Z.nil}}={}`}function JZ(t,e){t.if(re.default.valCxt,()=>{t.var(re.default.instancePath,(0,Z._)`${re.default.valCxt}.${re.default.instancePath}`),t.var(re.default.parentData,(0,Z._)`${re.default.valCxt}.${re.default.parentData}`),t.var(re.default.parentDataProperty,(0,Z._)`${re.default.valCxt}.${re.default.parentDataProperty}`),t.var(re.default.rootData,(0,Z._)`${re.default.valCxt}.${re.default.rootData}`),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,Z._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{t.var(re.default.instancePath,(0,Z._)`""`),t.var(re.default.parentData,(0,Z._)`undefined`),t.var(re.default.parentDataProperty,(0,Z._)`undefined`),t.var(re.default.rootData,re.default.data),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,Z._)`{}`)})}function KZ(t){let{schema:e,opts:r,gen:n}=t;Hk(t,()=>{r.$comment&&e.$comment&&Jk(t),tU(t),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated&&YZ(t),Wk(t),oU(t)})}function YZ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function qk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function XZ(t,e){if(Gk(t)&&(Vk(t),Bk(t))){QZ(t,e);return}(0,Fk.boolOrEmptySchema)(t,e)}function Bk({schema:t,self:e}){if(typeof t=="boolean")return!t;for(let r in t)if(e.RULES.all[r])return!0;return!1}function Gk(t){return typeof t.schema!="boolean"}function QZ(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&Jk(t),rU(t),nU(t);let s=n.const("_errs",re.default.errors);Wk(t,s),n.var(e,(0,Z._)`${s} === ${re.default.errors}`)}function Vk(t){(0,ln.checkUnknownRules)(t),eU(t)}function Wk(t,e){if(t.opts.jtd)return Zk(t,[],!1,e);let r=(0,Dk.getSchemaTypes)(t.schema),n=(0,Dk.coerceAndCheckDataType)(t,r);Zk(t,r,!n,e)}function eU(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,ln.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function tU(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,ln.checkStrictMode)(t,"default is ignored in the schema root")}function rU(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,GZ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function nU(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function Jk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${re.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${re.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function oU(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${re.default.errors} === 0`,()=>e.return(re.default.data),()=>e.throw((0,Z._)`new ${o}(${re.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,re.default.vErrors),s.unevaluated&&sU(t),e.return((0,Z._)`${re.default.errors} === 0`))}function sU({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function Zk(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:l}=t,{RULES:u}=l;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,ln.schemaHasRulesButRef)(s,u))){o.block(()=>Yk(t,"$ref",u.all.$ref.definition));return}c.jtd||iU(t,e),o.block(()=>{for(let f of u.rules)p(f);p(u.post)});function p(f){(0,cy.shouldUseGroup)(s,f)&&(f.type?(o.if((0,fu.checkDataType)(f.type,i,c.strictNumbers)),Uk(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,fu.reportTypeError)(t)),o.endIf()):Uk(t,f),a||o.if((0,Z._)`${re.default.errors} === ${n||0}`))}}function Uk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,BZ.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,cy.shouldUseRule)(n,s)&&Yk(t,s.keyword,s.definition,e.type)})}function iU(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(aU(t,e),t.opts.allowUnionTypes||cU(t,e),lU(t,t.dataTypes))}function aU(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{Kk(t.dataTypes,r)||ly(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),pU(t,e)}}function cU(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&ly(t,"use allowUnionTypes to allow union type keyword")}function lU(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,cy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>uU(e,i))&&ly(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function uU(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function Kk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function pU(t,e){let r=[];for(let n of t.dataTypes)Kk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function ly(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,ln.checkStrictMode)(t,e,t.opts.strictTypes)}var mu=class{constructor(e,r,n){if((0,Sa.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,ln.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",Xk(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Sa.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",re.default.errors))}result(e,r,n){this.failResult((0,Z.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Z.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Z._)`${r} !== undefined && (${(0,Z.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?xa.reportExtraError:xa.reportError)(this,this.def.error,r)}$dataError(){(0,xa.reportError)(this,this.def.$dataError||xa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,xa.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,fu.checkDataTypes)(c,r,s.opts.strictNumbers,fu.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,ay.getSubschema)(this.it,e);(0,ay.extendSubschemaData)(n,this.it,e),(0,ay.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return XZ(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=ln.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=ln.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,Z.Name)),!0}};Zn.KeywordCxt=mu;function Yk(t,e,r,n){let o=new mu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Sa.funcKeywordCode)(o,r):"macro"in r?(0,Sa.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Sa.funcKeywordCode)(o,r)}var dU=/^\/(?:[^~]|~0|~1)*$/,fU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Xk(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return re.default.rootData;if(t[0]==="/"){if(!dU.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=re.default.rootData}else{let l=fU.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,Z._)`${s}${(0,Z.getProperty)((0,ln.unescapeJsonPointer)(l))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Zn.getData=Xk});var hu=I(py=>{"use strict";Object.defineProperty(py,"__esModule",{value:!0});var uy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};py.default=uy});var ka=I(my=>{"use strict";Object.defineProperty(my,"__esModule",{value:!0});var dy=wa(),fy=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,dy.resolveUrl)(e,r,n),this.missingSchema=(0,dy.normalizeId)((0,dy.getFullPath)(e,this.missingRef))}};my.default=fy});var yu=I(mr=>{"use strict";Object.defineProperty(mr,"__esModule",{value:!0});mr.resolveSchema=mr.getCompilingSchema=mr.resolveRef=mr.compileSchema=mr.SchemaEnv=void 0;var Tr=de(),mU=hu(),Ho=cn(),Pr=wa(),Qk=Pe(),hU=$a(),Bs=class{constructor(e){var r;this.refs={},this.dynamicAnchors={};let n;typeof e.schema=="object"&&(n=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=(r=e.baseId)!==null&&r!==void 0?r:(0,Pr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};mr.SchemaEnv=Bs;function gy(t){let e=eE.call(this,t);if(e)return e;let r=(0,Pr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Tr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:mU.default,code:(0,Tr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Ho.default.data,parentData:Ho.default.parentData,parentDataProperty:Ho.default.parentDataProperty,dataNames:[Ho.default.data],dataPathArr:[Tr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Tr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Tr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Tr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,hU.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Ho.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let d=new Function(`${Ho.default.self}`,`${Ho.default.scope}`,u)(this,this.scope.get());if(this.scope.value(c,{ref:d}),d.errors=null,d.schema=t.schema,d.schemaEnv=t,t.$async&&(d.$async=!0),this.opts.code.source===!0&&(d.source={validateName:c,validateCode:p,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:h}=l;d.evaluated={props:m instanceof Tr.Name?void 0:m,items:h instanceof Tr.Name?void 0:h,dynamicProps:m instanceof Tr.Name,dynamicItems:h instanceof Tr.Name},d.source&&(d.source.evaluated=(0,Tr.stringify)(d.evaluated))}return t.validate=d,t}catch(p){throw delete t.validate,delete t.validateName,u&&this.logger.error("Error compiling schema, function code:",u),p}finally{this._compilations.delete(t)}}mr.compileSchema=gy;function gU(t,e,r){var n;r=(0,Pr.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=_U.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Bs({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=yU.call(this,s)}mr.resolveRef=gU;function yU(t){return(0,Pr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:gy.call(this,t)}function eE(t){for(let e of this._compilations)if(vU(e,t))return e}mr.getCompilingSchema=eE;function vU(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function _U(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||gu.call(this,t,e)}function gu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Pr._getFullPath)(this.opts.uriResolver,r),o=(0,Pr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return hy.call(this,r,t);let s=(0,Pr.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=gu.call(this,t,i);return typeof a?.schema!="object"?void 0:hy.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||gy.call(this,i),s===(0,Pr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Pr.resolveUrl)(this.opts.uriResolver,o,l)),new Bs({schema:a,schemaId:c,root:t,baseId:o})}return hy.call(this,r,i)}}mr.resolveSchema=gu;var bU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function hy(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,Qk.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!bU.has(a)&&l&&(e=(0,Pr.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,Qk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Pr.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=gu.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Bs({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var tE=I((BX,wU)=>{wU.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var vy=I((GX,sE)=>{"use strict";var xU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),nE=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function yy(t){let e="",r=0,n=0;for(n=0;n<t.length;n++)if(r=t[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n];break}for(n+=1;n<t.length;n++){if(r=t[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";e+=t[n]}return e}var SU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function rE(t){return t.length=0,!0}function $U(t,e,r){if(t.length){let n=yy(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function kU(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=$U;for(let c=0;c<t.length;c++){let l=t[c];if(!(l==="["||l==="]"))if(l===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(l==="%"){if(!a(o,n,r))break;a=rE}else{o.push(l);continue}}return o.length&&(a===rE?r.zone=o.join(""):i?n.push(o.join("")):n.push(yy(o))),r.address=n.join(""),r}function oE(t){if(EU(t,":")<2)return{host:t,isIPV6:!1};let e=kU(t);if(e.error)return{host:t,isIPV6:!1};{let r=e.address,n=e.address;return e.zone&&(r+="%"+e.zone,n+="%25"+e.zone),{host:r,isIPV6:!0,escapedHost:n}}}function EU(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function TU(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function PU(t,e){let r=e!==!0?escape:unescape;return t.scheme!==void 0&&(t.scheme=r(t.scheme)),t.userinfo!==void 0&&(t.userinfo=r(t.userinfo)),t.host!==void 0&&(t.host=r(t.host)),t.path!==void 0&&(t.path=r(t.path)),t.query!==void 0&&(t.query=r(t.query)),t.fragment!==void 0&&(t.fragment=r(t.fragment)),t}function RU(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!nE(r)){let n=oE(r);n.isIPV6===!0?r=`[${n.escapedHost}]`:r=t.host}e.push(r)}return(typeof t.port=="number"||typeof t.port=="string")&&(e.push(":"),e.push(String(t.port))),e.length?e.join(""):void 0}sE.exports={nonSimpleDomain:SU,recomposeAuthority:RU,normalizeComponentEncoding:PU,removeDotSegments:TU,isIPv4:nE,isUUID:xU,normalizeIPv6:oE,stringArrayToHexStripped:yy}});var uE=I((VX,lE)=>{"use strict";var{isUUID:OU}=vy(),CU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,IU=["http","https","ws","wss","urn","urn:uuid"];function AU(t){return IU.indexOf(t)!==-1}function _y(t){return t.secure===!0?!0:t.secure===!1?!1:t.scheme?t.scheme.length===3&&(t.scheme[0]==="w"||t.scheme[0]==="W")&&(t.scheme[1]==="s"||t.scheme[1]==="S")&&(t.scheme[2]==="s"||t.scheme[2]==="S"):!1}function iE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function aE(t){let e=String(t.scheme).toLowerCase()==="https";return(t.port===(e?443:80)||t.port==="")&&(t.port=void 0),t.path||(t.path="/"),t}function NU(t){return t.secure=_y(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function zU(t){if((t.port===(_y(t)?443:80)||t.port==="")&&(t.port=void 0),typeof t.secure=="boolean"&&(t.scheme=t.secure?"wss":"ws",t.secure=void 0),t.resourceName){let[e,r]=t.resourceName.split("?");t.path=e&&e!=="/"?e:void 0,t.query=r,t.resourceName=void 0}return t.fragment=void 0,t}function jU(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(CU);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=by(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function MU(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=by(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function LU(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!OU(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function DU(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var cE={scheme:"http",domainHost:!0,parse:iE,serialize:aE},qU={scheme:"https",domainHost:cE.domainHost,parse:iE,serialize:aE},vu={scheme:"ws",domainHost:!0,parse:NU,serialize:zU},ZU={scheme:"wss",domainHost:vu.domainHost,parse:vu.parse,serialize:vu.serialize},UU={scheme:"urn",parse:jU,serialize:MU,skipNormalize:!0},FU={scheme:"urn:uuid",parse:LU,serialize:DU,skipNormalize:!0},_u={http:cE,https:qU,ws:vu,wss:ZU,urn:UU,"urn:uuid":FU};Object.setPrototypeOf(_u,null);function by(t){return t&&(_u[t]||_u[t.toLowerCase()])||void 0}lE.exports={wsIsSecure:_y,SCHEMES:_u,isValidSchemeName:AU,getSchemeHandler:by}});var fE=I((WX,wu)=>{"use strict";var{normalizeIPv6:HU,removeDotSegments:Ea,recomposeAuthority:BU,normalizeComponentEncoding:bu,isIPv4:GU,nonSimpleDomain:VU}=vy(),{SCHEMES:WU,getSchemeHandler:pE}=uE();function JU(t,e){return typeof t=="string"?t=Fr(un(t,e),e):typeof t=="object"&&(t=un(Fr(t,e),e)),t}function KU(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=dE(un(t,n),un(e,n),n,!0);return n.skipEscape=!0,Fr(o,n)}function dE(t,e,r,n){let o={};return n||(t=un(Fr(t,r),r),e=un(Fr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ea(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=Ea(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ea(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=Ea(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function YU(t,e,r){return typeof t=="string"?(t=unescape(t),t=Fr(bu(un(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Fr(bu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Fr(bu(un(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Fr(bu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Fr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=pE(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=BU(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=Ea(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var XU=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function un(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(XU);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(GU(n.host)===!1){let c=HU(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=pE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&VU(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(a){n.error=n.error||"Host's domain name can not be converted to ASCII: "+a}(!i||i&&!i.skipNormalize)&&(t.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),i&&i.parse&&i.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}var wy={SCHEMES:WU,normalize:JU,resolve:KU,resolveComponent:dE,equal:YU,serialize:Fr,parse:un};wu.exports=wy;wu.exports.default=wy;wu.exports.fastUri=wy});var hE=I(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});var mE=fE();mE.code='require("ajv/dist/runtime/uri").default';xy.default=mE});var SE=I(xt=>{"use strict";Object.defineProperty(xt,"__esModule",{value:!0});xt.CodeGen=xt.Name=xt.nil=xt.stringify=xt.str=xt._=xt.KeywordCxt=void 0;var QU=$a();Object.defineProperty(xt,"KeywordCxt",{enumerable:!0,get:function(){return QU.KeywordCxt}});var Gs=de();Object.defineProperty(xt,"_",{enumerable:!0,get:function(){return Gs._}});Object.defineProperty(xt,"str",{enumerable:!0,get:function(){return Gs.str}});Object.defineProperty(xt,"stringify",{enumerable:!0,get:function(){return Gs.stringify}});Object.defineProperty(xt,"nil",{enumerable:!0,get:function(){return Gs.nil}});Object.defineProperty(xt,"Name",{enumerable:!0,get:function(){return Gs.Name}});Object.defineProperty(xt,"CodeGen",{enumerable:!0,get:function(){return Gs.CodeGen}});var eF=hu(),bE=ka(),tF=Yg(),Ta=yu(),rF=de(),Pa=wa(),xu=ba(),$y=Pe(),gE=tE(),nF=hE(),wE=(t,e)=>new RegExp(t,e);wE.code="new RegExp";var oF=["removeAdditional","useDefaults","coerceTypes"],sF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),iF={errorDataPath:"",format:"`validateFormats: false` can be used instead.",nullable:'"nullable" keyword is supported by default.',jsonPointers:"Deprecated jsPropertySyntax can be used instead.",extendRefs:"Deprecated ignoreKeywordsWithRef can be used instead.",missingRefs:"Pass empty schema with $id that should be ignored to ajv.addSchema.",processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:'"uniqueItems" keyword is always validated.',unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:"Map is used as cache, schema object as key.",serialize:"Map is used as cache, schema object as key.",ajvErrors:"It is default now."},aF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},yE=200;function cF(t){var e,r,n,o,s,i,a,c,l,u,p,f,d,m,h,g,v,b,x,$,O,ce,X,ee,ge;let U=t.strict,ne=(e=t.code)===null||e===void 0?void 0:e.optimize,rt=ne===!0||ne===void 0?1:ne||0,Mt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:wE,te=(o=t.uriResolver)!==null&&o!==void 0?o:nF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:U)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:U)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:U)!==null&&u!==void 0?u:"log",strictTuples:(f=(p=t.strictTuples)!==null&&p!==void 0?p:U)!==null&&f!==void 0?f:"log",strictRequired:(m=(d=t.strictRequired)!==null&&d!==void 0?d:U)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:rt,regExp:Mt}:{optimize:rt,regExp:Mt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:yE,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:yE,meta:(v=t.meta)!==null&&v!==void 0?v:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:($=t.schemaId)!==null&&$!==void 0?$:"$id",addUsedSchema:(O=t.addUsedSchema)!==null&&O!==void 0?O:!0,validateSchema:(ce=t.validateSchema)!==null&&ce!==void 0?ce:!0,validateFormats:(X=t.validateFormats)!==null&&X!==void 0?X:!0,unicodeRegExp:(ee=t.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(ge=t.int32range)!==null&&ge!==void 0?ge:!0,uriResolver:te}}var Ra=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...cF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new rF.ValueScope({scope:{},prefixes:sF,es5:r,lines:n}),this.logger=mF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,tF.getRules)(),vE.call(this,iF,e,"NOT SUPPORTED"),vE.call(this,aF,e,"DEPRECATED","warn"),this._metaOpts=dF.call(this),e.formats&&uF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&pF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),lF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=gE;n==="id"&&(o={...gE},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(u,p){await s.call(this,u.$schema);let f=this._addSchema(u,p);return f.validate||i.call(this,f)}async function s(u){u&&!this.getSchema(u)&&await o.call(this,{$ref:u},!0)}async function i(u){try{return this._compileSchemaEnv(u)}catch(p){if(!(p instanceof bE.default))throw p;return a.call(this,p),await c.call(this,p.missingSchema),i.call(this,u)}}function a({missingSchema:u,missingRef:p}){if(this.refs[u])throw new Error(`AnySchema ${u} is loaded but ${p} cannot be resolved`)}async function c(u){let p=await l.call(this,u);this.refs[u]||await s.call(this,p.$schema),this.refs[u]||this.addSchema(p,u,r)}async function l(u){let p=this._loading[u];if(p)return p;try{return await(this._loading[u]=n(u))}finally{delete this._loading[u]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,Pa.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=_E.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Ta.SchemaEnv({schema:{},schemaId:n});if(r=Ta.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=_E.call(this,e);return typeof r=="object"&&this._cache.delete(r.schema),delete this.schemas[e],delete this.refs[e],this}case"object":{let r=e;this._cache.delete(r);let n=e[this.opts.schemaId];return n&&(n=(0,Pa.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(gF.call(this,n,r),!r)return(0,$y.eachItem)(n,s=>Sy.call(this,s)),this;vF.call(this,r);let o={...r,type:(0,xu.getJSONTypes)(r.type),schemaType:(0,xu.getJSONTypes)(r.schemaType)};return(0,$y.eachItem)(n,o.type.length===0?s=>Sy.call(this,s,o):s=>o.type.forEach(i=>Sy.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:l}=c.definition,u=i[a];l&&u&&(i[a]=xE(u))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,Pa.normalizeId)(i||n);let l=Pa.getSchemaRefs.call(this,e,n);return c=new Ta.SchemaEnv({schema:e,schemaId:a,meta:r,baseId:n,localRefs:l}),this._cache.set(c.schema,c),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):Ta.compileSchema.call(this,e),!e.validate)throw new Error("ajv implementation error");return e.validate}_compileMetaSchema(e){let r=this.opts;this.opts=this._metaOpts;try{Ta.compileSchema.call(this,e)}finally{this.opts=r}}};Ra.ValidationError=eF.default;Ra.MissingRefError=bE.default;xt.default=Ra;function vE(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function _E(t){return t=(0,Pa.normalizeId)(t),this.schemas[t]||this.refs[t]}function lF(){let t=this.opts.schemas;if(t)if(Array.isArray(t))this.addSchema(t);else for(let e in t)this.addSchema(t[e],e)}function uF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function pF(t){if(Array.isArray(t)){this.addVocabulary(t);return}this.logger.warn("keywords option as map is deprecated, pass array");for(let e in t){let r=t[e];r.keyword||(r.keyword=e),this.addKeyword(r)}}function dF(){let t={...this.opts};for(let e of oF)delete t[e];return t}var fF={log(){},warn(){},error(){}};function mF(t){if(t===!1)return fF;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var hF=/^[a-z_$][a-z0-9_$:-]*$/i;function gF(t,e){let{RULES:r}=this;if((0,$y.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!hF.test(n))throw new Error(`Keyword ${n} has invalid name`)}),!!e&&e.$data&&!("code"in e||"validate"in e))throw new Error('$data keyword must have "code" or "validate" function')}function Sy(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,xu.getJSONTypes)(e.type),schemaType:(0,xu.getJSONTypes)(e.schemaType)}};e.before?yF.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function yF(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function vF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=xE(e)),t.validateSchema=this.compile(e,!0))}var _F={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function xE(t){return{anyOf:[t,_F]}}});var $E=I(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var bF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};ky.default=bF});var PE=I(Bo=>{"use strict";Object.defineProperty(Bo,"__esModule",{value:!0});Bo.callRef=Bo.getValidate=void 0;var wF=ka(),kE=fr(),Wt=de(),Vs=cn(),EE=yu(),Su=Pe(),xF={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return p();let u=EE.resolveRef.call(c,l,o,r);if(u===void 0)throw new wF.default(n.opts.uriResolver,o,r);if(u instanceof EE.SchemaEnv)return f(u);return d(u);function p(){if(s===l)return $u(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return $u(t,(0,Wt._)`${m}.validate`,l,l.$async)}function f(m){let h=TE(t,m);$u(t,h,m,m.$async)}function d(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Wt.stringify)(m)}:{ref:m}),g=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:Wt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(v),t.ok(g)}}};function TE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Wt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Bo.getValidate=TE;function $u(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Vs.default.this:Wt.nil;n?u():p();function u(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,Wt._)`await ${(0,kE.callValidateCode)(t,e,l)}`),d(e),i||o.assign(m,!0)},h=>{o.if((0,Wt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,kE.callValidateCode)(t,e,l),()=>d(e),()=>f(e))}function f(m){let h=(0,Wt._)`${m}.errors`;o.assign(Vs.default.vErrors,(0,Wt._)`${Vs.default.vErrors} === null ? ${h} : ${Vs.default.vErrors}.concat(${h})`),o.assign(Vs.default.errors,(0,Wt._)`${Vs.default.vErrors}.length`)}function d(m){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Su.mergeEvaluated.props(o,g.props,s.props));else{let v=o.var("props",(0,Wt._)`${m}.evaluated.props`);s.props=Su.mergeEvaluated.props(o,v,s.props,Wt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Su.mergeEvaluated.items(o,g.items,s.items));else{let v=o.var("items",(0,Wt._)`${m}.evaluated.items`);s.items=Su.mergeEvaluated.items(o,v,s.items,Wt.Name)}}}Bo.callRef=$u;Bo.default=xF});var RE=I(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});var SF=$E(),$F=PE(),kF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",SF.default,$F.default];Ey.default=kF});var OE=I(Ty=>{"use strict";Object.defineProperty(Ty,"__esModule",{value:!0});var ku=de(),Un=ku.operators,Eu={maximum:{okStr:"<=",ok:Un.LTE,fail:Un.GT},minimum:{okStr:">=",ok:Un.GTE,fail:Un.LT},exclusiveMaximum:{okStr:"<",ok:Un.LT,fail:Un.GTE},exclusiveMinimum:{okStr:">",ok:Un.GT,fail:Un.LTE}},EF={message:({keyword:t,schemaCode:e})=>(0,ku.str)`must be ${Eu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,ku._)`{comparison: ${Eu[t].okStr}, limit: ${e}}`},TF={keyword:Object.keys(Eu),type:"number",schemaType:"number",$data:!0,error:EF,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,ku._)`${r} ${Eu[e].fail} ${n} || isNaN(${r})`)}};Ty.default=TF});var CE=I(Py=>{"use strict";Object.defineProperty(Py,"__esModule",{value:!0});var Oa=de(),PF={message:({schemaCode:t})=>(0,Oa.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Oa._)`{multipleOf: ${t}}`},RF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:PF,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Oa._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Oa._)`${i} !== parseInt(${i})`;t.fail$data((0,Oa._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Py.default=RF});var AE=I(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});function IE(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Ry.default=IE;IE.code='require("ajv/dist/runtime/ucs2length").default'});var NE=I(Oy=>{"use strict";Object.defineProperty(Oy,"__esModule",{value:!0});var Go=de(),OF=Pe(),CF=AE(),IF={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Go.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Go._)`{limit: ${t}}`},AF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:IF,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Go.operators.GT:Go.operators.LT,i=o.opts.unicode===!1?(0,Go._)`${r}.length`:(0,Go._)`${(0,OF.useFunc)(t.gen,CF.default)}(${r})`;t.fail$data((0,Go._)`${i} ${s} ${n}`)}};Oy.default=AF});var zE=I(Cy=>{"use strict";Object.defineProperty(Cy,"__esModule",{value:!0});var NF=fr(),Tu=de(),zF={message:({schemaCode:t})=>(0,Tu.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Tu._)`{pattern: ${t}}`},jF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:zF,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Tu._)`(new RegExp(${o}, ${i}))`:(0,NF.usePattern)(t,n);t.fail$data((0,Tu._)`!${a}.test(${e})`)}};Cy.default=jF});var jE=I(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});var Ca=de(),MF={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ca.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ca._)`{limit: ${t}}`},LF={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:MF,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ca.operators.GT:Ca.operators.LT;t.fail$data((0,Ca._)`Object.keys(${r}).length ${o} ${n}`)}};Iy.default=LF});var ME=I(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var Ia=fr(),Aa=de(),DF=Pe(),qF={message:({params:{missingProperty:t}})=>(0,Aa.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Aa._)`{missingProperty: ${t}}`},ZF={keyword:"required",type:"object",schemaType:"array",$data:!0,error:qF,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?l():u(),a.strictRequired){let d=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(d?.[h]===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,DF.checkStrictMode)(i,v,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Aa.nil,p);else for(let d of r)(0,Ia.checkReportMissingProp)(t,d)}function u(){let d=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>f(d,m)),t.ok(m)}else e.if((0,Ia.checkMissingProp)(t,r,d)),(0,Ia.reportMissingProp)(t,d),e.else()}function p(){e.forOf("prop",n,d=>{t.setParams({missingProperty:d}),e.if((0,Ia.noPropertyInData)(e,o,d,a.ownProperties),()=>t.error())})}function f(d,m){t.setParams({missingProperty:d}),e.forOf(d,n,()=>{e.assign(m,(0,Ia.propertyInData)(e,o,d,a.ownProperties)),e.if((0,Aa.not)(m),()=>{t.error(),e.break()})},Aa.nil)}}};Ay.default=ZF});var LE=I(Ny=>{"use strict";Object.defineProperty(Ny,"__esModule",{value:!0});var Na=de(),UF={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Na.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Na._)`{limit: ${t}}`},FF={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:UF,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Na.operators.GT:Na.operators.LT;t.fail$data((0,Na._)`${r}.length ${o} ${n}`)}};Ny.default=FF});var Pu=I(zy=>{"use strict";Object.defineProperty(zy,"__esModule",{value:!0});var DE=sy();DE.code='require("ajv/dist/runtime/equal").default';zy.default=DE});var qE=I(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var jy=ba(),St=de(),HF=Pe(),BF=Pu(),GF={message:({params:{i:t,j:e}})=>(0,St.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,St._)`{i: ${t}, j: ${e}}`},VF={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:GF,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),l=s.items?(0,jy.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,St._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,St._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,St._)`${m} > 1`,()=>(p()?f:d)(m,h))}function p(){return l.length>0&&!l.some(m=>m==="object"||m==="array")}function f(m,h){let g=e.name("item"),v=(0,jy.checkDataTypes)(l,g,a.opts.strictNumbers,jy.DataType.Wrong),b=e.const("indices",(0,St._)`{}`);e.for((0,St._)`;${m}--;`,()=>{e.let(g,(0,St._)`${r}[${m}]`),e.if(v,(0,St._)`continue`),l.length>1&&e.if((0,St._)`typeof ${g} == "string"`,(0,St._)`${g} += "_"`),e.if((0,St._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(h,(0,St._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,St._)`${b}[${g}] = ${m}`)})}function d(m,h){let g=(0,HF.useFunc)(e,BF.default),v=e.name("outer");e.label(v).for((0,St._)`;${m}--;`,()=>e.for((0,St._)`${h} = ${m}; ${h}--;`,()=>e.if((0,St._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};My.default=VF});var ZE=I(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Ly=de(),WF=Pe(),JF=Pu(),KF={message:"must be equal to constant",params:({schemaCode:t})=>(0,Ly._)`{allowedValue: ${t}}`},YF={keyword:"const",$data:!0,error:KF,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Ly._)`!${(0,WF.useFunc)(e,JF.default)}(${r}, ${o})`):t.fail((0,Ly._)`${s} !== ${r}`)}};Dy.default=YF});var UE=I(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var za=de(),XF=Pe(),QF=Pu(),e4={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,za._)`{allowedValues: ${t}}`},t4={keyword:"enum",schemaType:"array",$data:!0,error:e4,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,l=()=>c??(c=(0,XF.useFunc)(e,QF.default)),u;if(a||n)u=e.let("valid"),t.block$data(u,p);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let d=e.const("vSchema",s);u=(0,za.or)(...o.map((m,h)=>f(d,h)))}t.pass(u);function p(){e.assign(u,!1),e.forOf("v",s,d=>e.if((0,za._)`${l()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function f(d,m){let h=o[m];return typeof h=="object"&&h!==null?(0,za._)`${l()}(${r}, ${d}[${m}])`:(0,za._)`${r} === ${h}`}}};qy.default=t4});var FE=I(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var r4=OE(),n4=CE(),o4=NE(),s4=zE(),i4=jE(),a4=ME(),c4=LE(),l4=qE(),u4=ZE(),p4=UE(),d4=[r4.default,n4.default,o4.default,s4.default,i4.default,a4.default,c4.default,l4.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},u4.default,p4.default];Zy.default=d4});var Fy=I(ja=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});ja.validateAdditionalItems=void 0;var Vo=de(),Uy=Pe(),f4={message:({params:{len:t}})=>(0,Vo.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Vo._)`{limit: ${t}}`},m4={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:f4,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Uy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}HE(t,n)}};function HE(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Vo._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Vo._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Uy.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Vo._)`${a} <= ${e.length}`);r.if((0,Vo.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Uy.Type.Num},l),i.allErrors||r.if((0,Vo.not)(l),()=>r.break())})}}ja.validateAdditionalItems=HE;ja.default=m4});var Hy=I(Ma=>{"use strict";Object.defineProperty(Ma,"__esModule",{value:!0});Ma.validateTuple=void 0;var BE=de(),Ru=Pe(),h4=fr(),g4={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return GE(t,"additionalItems",e);r.items=!0,!(0,Ru.alwaysValidSchema)(r,e)&&t.ok((0,h4.validateArray)(t))}};function GE(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;u(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Ru.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,BE._)`${s}.length`);r.forEach((p,f)=>{(0,Ru.alwaysValidSchema)(a,p)||(n.if((0,BE._)`${l} > ${f}`,()=>t.subschema({keyword:i,schemaProp:f,dataProp:f},c)),t.ok(c))});function u(p){let{opts:f,errSchemaPath:d}=a,m=r.length,h=m===p.minItems&&(m===p.maxItems||p[e]===!1);if(f.strictTuples&&!h){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,Ru.checkStrictMode)(a,g,f.strictTuples)}}}Ma.validateTuple=GE;Ma.default=g4});var VE=I(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var y4=Hy(),v4={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,y4.validateTuple)(t,"items")};By.default=v4});var JE=I(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var WE=de(),_4=Pe(),b4=fr(),w4=Fy(),x4={message:({params:{len:t}})=>(0,WE.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,WE._)`{limit: ${t}}`},S4={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:x4,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,_4.alwaysValidSchema)(n,e)&&(o?(0,w4.validateAdditionalItems)(t,o):t.ok((0,b4.validateArray)(t)))}};Gy.default=S4});var KE=I(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var hr=de(),Ou=Pe(),$4={message:({params:{min:t,max:e}})=>e===void 0?(0,hr.str)`must contain at least ${t} valid item(s)`:(0,hr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,hr._)`{minContains: ${t}}`:(0,hr._)`{minContains: ${t}, maxContains: ${e}}`},k4={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:$4,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:l}=n;s.opts.next?(i=c===void 0?1:c,a=l):i=1;let u=e.const("len",(0,hr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Ou.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ou.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ou.alwaysValidSchema)(s,r)){let h=(0,hr._)`${u} >= ${i}`;a!==void 0&&(h=(0,hr._)`${h} && ${u} <= ${a}`),t.pass(h);return}s.items=!0;let p=e.name("valid");a===void 0&&i===1?d(p,()=>e.if(p,()=>e.break())):i===0?(e.let(p,!0),a!==void 0&&e.if((0,hr._)`${o}.length > 0`,f)):(e.let(p,!1),f()),t.result(p,()=>t.reset());function f(){let h=e.name("_valid"),g=e.let("count",0);d(h,()=>e.if(h,()=>m(g)))}function d(h,g){e.forRange("i",0,u,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Ou.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,hr._)`${h}++`),a===void 0?e.if((0,hr._)`${h} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,hr._)`${h} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,hr._)`${h} >= ${i}`,()=>e.assign(p,!0)))}}};Vy.default=k4});var QE=I(Hr=>{"use strict";Object.defineProperty(Hr,"__esModule",{value:!0});Hr.validateSchemaDeps=Hr.validatePropertyDeps=Hr.error=void 0;var Wy=de(),E4=Pe(),La=fr();Hr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Wy.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Wy._)`{property: ${t},
293
293
  missingProperty: ${n},
294
294
  depsCount: ${e},
295
- deps: ${r}}`};var i4={keyword:"dependencies",type:"object",schemaType:"object",error:Hr.error,code(t){let[e,r]=a4(t);UE(t,e),FE(t,r)}};function a4({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function UE(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,za.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,za.checkReportMissingProp)(t,l)}):(r.if((0,Zy._)`${c} && (${(0,za.checkMissingProp)(t,a,s)})`),(0,za.reportMissingProp)(t,s),r.else())}}Hr.validatePropertyDeps=UE;function FE(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,s4.alwaysValidSchema)(s,e[a])||(r.if((0,za.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Hr.validateSchemaDeps=FE;Hr.default=i4});var VE=O(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var BE=pe(),c4=Pe(),l4={message:"property name must be valid",params:({params:t})=>(0,BE._)`{propertyName: ${t.propertyName}}`},u4={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:l4,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,c4.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,BE.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Uy.default=u4});var Hy=O(Fy=>{"use strict";Object.defineProperty(Fy,"__esModule",{value:!0});var Tu=dr(),Rr=pe(),p4=cn(),Pu=Pe(),d4={message:"must NOT have additional properties",params:({params:t})=>(0,Rr._)`{additionalProperty: ${t.additionalProperty}}`},f4={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:d4,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Pu.alwaysValidSchema)(i,r))return;let l=(0,Tu.allSchemaProperties)(n.properties),u=(0,Tu.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Rr._)`${s} === ${p4.default.errors}`);function p(){e.forIn("key",o,g=>{!l.length&&!u.length?f(g):e.if(m(g),()=>f(g))})}function m(g){let v;if(l.length>8){let _=(0,Pu.schemaRefOrVal)(i,n.properties,"properties");v=(0,Tu.isOwnProperty)(e,_,g)}else l.length?v=(0,Rr.or)(...l.map(_=>(0,Rr._)`${g} === ${_}`)):v=Rr.nil;return u.length&&(v=(0,Rr.or)(v,...u.map(_=>(0,Rr._)`${(0,Tu.usePattern)(t,_)}.test(${g})`))),(0,Rr.not)(v)}function d(g){e.code((0,Rr._)`delete ${o}[${g}]`)}function f(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){d(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Pu.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(g,v,!1),e.if((0,Rr.not)(v),()=>{t.reset(),d(g)})):(h(g,v),a||e.if((0,Rr.not)(v),()=>e.break()))}}function h(g,v,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:Pu.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,v)}}};Fy.default=f4});var JE=O(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var m4=wa(),GE=dr(),By=Pe(),WE=Hy(),h4={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&WE.default.code(new m4.KeywordCxt(s,WE.default,"additionalProperties"));let i=(0,GE.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=By.mergeEvaluated.props(e,(0,By.toHash)(i),s.props));let a=i.filter(p=>!(0,By.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,GE.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Vy.default=h4});var QE=O(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var KE=dr(),Ru=pe(),YE=Pe(),XE=Pe(),g4={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,KE.allSchemaProperties)(r),c=a.filter(h=>(0,YE.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Ru.Name)&&(s.props=(0,XE.evaluatedPropsToName)(e,s.props));let{props:p}=s;m();function m(){for(let h of a)l&&d(h),s.allErrors?f(h):(e.var(u,!0),f(h),e.if(u))}function d(h){for(let g in l)new RegExp(h).test(g)&&(0,YE.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function f(h){e.forIn("key",n,g=>{e.if((0,Ru._)`${(0,KE.usePattern)(t,h)}.test(${g})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:XE.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Ru._)`${p}[${g}]`,!0):!v&&!s.allErrors&&e.if((0,Ru.not)(u),()=>e.break())})})}}};Gy.default=g4});var eT=O(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});var y4=Pe(),v4={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,y4.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};Wy.default=v4});var tT=O(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var _4=dr(),b4={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:_4.validateUnion,error:{message:"must match a schema in anyOf"}};Jy.default=b4});var rT=O(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var Ou=pe(),w4=Pe(),x4={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Ou._)`{passingSchemas: ${t.passing}}`},S4={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:x4,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,p)=>{let m;(0,w4.alwaysValidSchema)(o,u)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Ou._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Ou._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),m&&t.mergeEvaluated(m,Ou.Name)})})}}};Ky.default=S4});var nT=O(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var $4=Pe(),k4={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,$4.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};Yy.default=k4});var iT=O(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var Cu=pe(),sT=Pe(),E4={message:({params:t})=>(0,Cu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Cu._)`{failingKeyword: ${t.ifClause}}`},T4={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:E4,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,sT.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=oT(n,"then"),s=oT(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,Cu.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,p){return()=>{let m=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(m,i),p?e.assign(p,(0,Cu._)`${u}`):t.setParams({ifClause:u})}}}};function oT(t,e){let r=t.schema[e];return r!==void 0&&!(0,sT.alwaysValidSchema)(t,r)}Xy.default=T4});var aT=O(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var P4=Pe(),R4={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,P4.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Qy.default=R4});var cT=O(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});var O4=jy(),C4=LE(),I4=My(),A4=qE(),N4=ZE(),z4=HE(),j4=VE(),M4=Hy(),L4=JE(),D4=QE(),q4=eT(),Z4=tT(),U4=rT(),F4=nT(),H4=iT(),B4=aT();function V4(t=!1){let e=[q4.default,Z4.default,U4.default,F4.default,H4.default,B4.default,j4.default,M4.default,z4.default,L4.default,D4.default];return t?e.push(C4.default,A4.default):e.push(O4.default,I4.default),e.push(N4.default),e}ev.default=V4});var lT=O(tv=>{"use strict";Object.defineProperty(tv,"__esModule",{value:!0});var nt=pe(),G4={message:({schemaCode:t})=>(0,nt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,nt._)`{format: ${t}}`},W4={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:G4,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?m():d();function m(){let f=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),h=r.const("fDef",(0,nt._)`${f}[${i}]`),g=r.let("fType"),v=r.let("format");r.if((0,nt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,nt._)`${h}.type || "string"`).assign(v,(0,nt._)`${h}.validate`),()=>r.assign(g,(0,nt._)`"string"`).assign(v,h)),t.fail$data((0,nt.or)(_(),x()));function _(){return c.strictSchema===!1?nt.nil:(0,nt._)`${i} && !${v}`}function x(){let k=u.$async?(0,nt._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,nt._)`${v}(${n})`,I=(0,nt._)`(typeof ${v} == "function" ? ${k} : ${v}.test(${n}))`;return(0,nt._)`${v} && ${v} !== true && ${g} === ${e} && !${I}`}}function d(){let f=p.formats[s];if(!f){_();return}if(f===!0)return;let[h,g,v]=x(f);h===e&&t.pass(k());function _(){if(c.strictSchema===!1){p.logger.warn(I());return}throw new Error(I());function I(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function x(I){let de=I instanceof RegExp?(0,nt.regexpCode)(I):c.code.formats?(0,nt._)`${c.code.formats}${(0,nt.getProperty)(s)}`:void 0,Y=r.scopeValue("formats",{key:s,ref:I,code:de});return typeof I=="object"&&!(I instanceof RegExp)?[I.type||"string",I.validate,(0,nt._)`${Y}.validate`]:["string",I,Y]}function k(){if(typeof f=="object"&&!(f instanceof RegExp)&&f.async){if(!u.$async)throw new Error("async format in sync schema");return(0,nt._)`await ${v}(${n})`}return typeof g=="function"?(0,nt._)`${v}(${n})`:(0,nt._)`${v}.test(${n})`}}}};tv.default=W4});var uT=O(rv=>{"use strict";Object.defineProperty(rv,"__esModule",{value:!0});var J4=lT(),K4=[J4.default];rv.default=K4});var pT=O(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.contentVocabulary=Vs.metadataVocabulary=void 0;Vs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Vs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var fT=O(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});var Y4=bE(),X4=NE(),Q4=cT(),e9=uT(),dT=pT(),t9=[Y4.default,X4.default,(0,Q4.default)(),e9.default,dT.metadataVocabulary,dT.contentVocabulary];nv.default=t9});var hT=O(Iu=>{"use strict";Object.defineProperty(Iu,"__esModule",{value:!0});Iu.DiscrError=void 0;var mT;(function(t){t.Tag="tag",t.Mapping="mapping"})(mT||(Iu.DiscrError=mT={}))});var yT=O(sv=>{"use strict";Object.defineProperty(sv,"__esModule",{value:!0});var Gs=pe(),ov=hT(),gT=fu(),r9=xa(),n9=Pe(),o9={message:({params:{discrError:t,tagName:e}})=>t===ov.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Gs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},s9={keyword:"discriminator",type:"object",schemaType:"object",error:o9,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Gs._)`${r}${(0,Gs.getProperty)(a)}`);e.if((0,Gs._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:ov.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let d=m();e.if(!1);for(let f in d)e.elseIf((0,Gs._)`${l} === ${f}`),e.assign(c,p(d[f]));e.else(),t.error(!1,{discrError:ov.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(d){let f=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:d},f);return t.mergeEvaluated(h,Gs.Name),f}function m(){var d;let f={},h=v(o),g=!0;for(let k=0;k<i.length;k++){let I=i[k];if(I?.$ref&&!(0,n9.schemaHasRulesButRef)(I,s.self.RULES)){let Y=I.$ref;if(I=gT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Y),I instanceof gT.SchemaEnv&&(I=I.schema),I===void 0)throw new r9.default(s.opts.uriResolver,s.baseId,Y)}let de=(d=I?.properties)===null||d===void 0?void 0:d[a];if(typeof de!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||v(I)),_(de,k)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return f;function v({required:k}){return Array.isArray(k)&&k.includes(a)}function _(k,I){if(k.const)x(k.const,I);else if(k.enum)for(let de of k.enum)x(de,I);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(k,I){if(typeof k!="string"||k in f)throw new Error(`discriminator: "${a}" values must be unique strings`);f[k]=I}}}};sv.default=s9});var vT=O((QX,i9)=>{i9.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var av=O((Fe,iv)=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.MissingRefError=Fe.ValidationError=Fe.CodeGen=Fe.Name=Fe.nil=Fe.stringify=Fe.str=Fe._=Fe.KeywordCxt=Fe.Ajv=void 0;var a9=mE(),c9=fT(),l9=yT(),_T=vT(),u9=["/properties"],Au="http://json-schema.org/draft-07/schema",Ws=class extends a9.default{_addVocabularies(){super._addVocabularies(),c9.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(l9.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(_T,u9):_T;this.addMetaSchema(e,Au,!1),this.refs["http://json-schema.org/schema"]=Au}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Au)?Au:void 0)}};Fe.Ajv=Ws;iv.exports=Fe=Ws;iv.exports.Ajv=Ws;Object.defineProperty(Fe,"__esModule",{value:!0});Fe.default=Ws;var p9=wa();Object.defineProperty(Fe,"KeywordCxt",{enumerable:!0,get:function(){return p9.KeywordCxt}});var Js=pe();Object.defineProperty(Fe,"_",{enumerable:!0,get:function(){return Js._}});Object.defineProperty(Fe,"str",{enumerable:!0,get:function(){return Js.str}});Object.defineProperty(Fe,"stringify",{enumerable:!0,get:function(){return Js.stringify}});Object.defineProperty(Fe,"nil",{enumerable:!0,get:function(){return Js.nil}});Object.defineProperty(Fe,"Name",{enumerable:!0,get:function(){return Js.Name}});Object.defineProperty(Fe,"CodeGen",{enumerable:!0,get:function(){return Js.CodeGen}});var d9=pu();Object.defineProperty(Fe,"ValidationError",{enumerable:!0,get:function(){return d9.default}});var f9=xa();Object.defineProperty(Fe,"MissingRefError",{enumerable:!0,get:function(){return f9.default}})});var TT=O(Vr=>{"use strict";Object.defineProperty(Vr,"__esModule",{value:!0});Vr.formatNames=Vr.fastFormats=Vr.fullFormats=void 0;function Br(t,e){return{validate:t,compare:e}}Vr.fullFormats={date:Br(ST,pv),time:Br(lv(!0),dv),"date-time":Br(bT(!0),kT),"iso-time":Br(lv(),$T),"iso-date-time":Br(bT(),ET),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_9,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:E9,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:b9,int32:{type:"number",validate:S9},int64:{type:"number",validate:$9},float:{type:"number",validate:xT},double:{type:"number",validate:xT},password:!0,binary:!0};Vr.fastFormats={...Vr.fullFormats,date:Br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,pv),time:Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,dv),"date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,kT),"iso-time":Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,$T),"iso-date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,ET),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Vr.formatNames=Object.keys(Vr.fullFormats);function m9(t){return t%4===0&&(t%100!==0||t%400===0)}var h9=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,g9=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ST(t){let e=h9.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&m9(r)?29:g9[n])}function pv(t,e){if(t&&e)return t>e?1:t<e?-1:0}var cv=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function lv(t){return function(r){let n=cv.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let p=s-u*c,m=o-l*c-(p<0?1:0);return(m===23||m===-1)&&(p===59||p===-1)&&i<61}}function dv(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function $T(t,e){if(!(t&&e))return;let r=cv.exec(t),n=cv.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var uv=/t|\s/i;function bT(t){let e=lv(t);return function(n){let o=n.split(uv);return o.length===2&&ST(o[0])&&e(o[1])}}function kT(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function ET(t,e){if(!(t&&e))return;let[r,n]=t.split(uv),[o,s]=e.split(uv),i=pv(r,o);if(i!==void 0)return i||dv(n,s)}var y9=/\/|:/,v9=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _9(t){return y9.test(t)&&v9.test(t)}var wT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function b9(t){return wT.lastIndex=0,wT.test(t)}var w9=-(2**31),x9=2**31-1;function S9(t){return Number.isInteger(t)&&t<=x9&&t>=w9}function $9(t){return Number.isInteger(t)}function xT(){return!0}var k9=/[^\\]\\Z/;function E9(t){if(k9.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var PT=O(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.formatLimitDefinition=void 0;var T9=av(),Or=pe(),Fn=Or.operators,Nu={formatMaximum:{okStr:"<=",ok:Fn.LTE,fail:Fn.GT},formatMinimum:{okStr:">=",ok:Fn.GTE,fail:Fn.LT},formatExclusiveMaximum:{okStr:"<",ok:Fn.LT,fail:Fn.GTE},formatExclusiveMinimum:{okStr:">",ok:Fn.GT,fail:Fn.LTE}},P9={message:({keyword:t,schemaCode:e})=>(0,Or.str)`should be ${Nu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Or._)`{comparison: ${Nu[t].okStr}, limit: ${e}}`};Ks.formatLimitDefinition={keyword:Object.keys(Nu),type:"string",schemaType:"string",$data:!0,error:P9,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new T9.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),d=e.const("fmt",(0,Or._)`${m}[${c.schemaCode}]`);t.fail$data((0,Or.or)((0,Or._)`typeof ${d} != "object"`,(0,Or._)`${d} instanceof RegExp`,(0,Or._)`typeof ${d}.compare != "function"`,p(d)))}function u(){let m=c.schema,d=a.formats[m];if(!d||d===!0)return;if(typeof d!="object"||d instanceof RegExp||typeof d.compare!="function")throw new Error(`"${o}": format "${m}" does not define "compare" function`);let f=e.scopeValue("formats",{key:m,ref:d,code:i.code.formats?(0,Or._)`${i.code.formats}${(0,Or.getProperty)(m)}`:void 0});t.fail$data(p(f))}function p(m){return(0,Or._)`${m}.compare(${r}, ${n}) ${Nu[o].fail} 0`}},dependencies:["format"]};var R9=t=>(t.addKeyword(Ks.formatLimitDefinition),t);Ks.default=R9});var IT=O((ja,CT)=>{"use strict";Object.defineProperty(ja,"__esModule",{value:!0});var Ys=TT(),O9=PT(),fv=pe(),RT=new fv.Name("fullFormats"),C9=new fv.Name("fastFormats"),mv=(t,e={keywords:!0})=>{if(Array.isArray(e))return OT(t,e,Ys.fullFormats,RT),t;let[r,n]=e.mode==="fast"?[Ys.fastFormats,C9]:[Ys.fullFormats,RT],o=e.formats||Ys.formatNames;return OT(t,o,r,n),e.keywords&&(0,O9.default)(t),t};mv.get=(t,e="full")=>{let n=(e==="fast"?Ys.fastFormats:Ys.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function OT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,fv._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}CT.exports=ja=mv;Object.defineProperty(ja,"__esModule",{value:!0});ja.default=mv});function I9(){let t=new AT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,NT.default)(t),t}var AT,NT,zu,zT=w(()=>{AT=oo(av(),1),NT=oo(IT(),1);zu=class{constructor(e){this._ajv=e??I9()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var ju,jT=w(()=>{ju=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function MT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function LT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var DT=w(()=>{});var Mu,qT=w(()=>{G$();Ss();zT();ia();jT();DT();Mu=class extends Xl{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Xi.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new zu,this.setRequestHandler(il,n=>this._oninitialize(n)),this.setNotificationHandler(hh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(xh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Xi.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new ju(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=V$(this._capabilities,e)}setRequestHandler(e,r){let o=An(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(lr(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=In(xs,c);if(!u.success){let f=u.error instanceof Error?u.error.message:String(u.error);throw new D(B.InvalidParams,`Invalid tools/call request: ${f}`)}let{params:p}=u.data,m=await Promise.resolve(r(c,l));if(p.task){let f=In(bs,m);if(!f.success){let h=f.error instanceof Error?f.error.message:String(f.error);throw new D(B.InvalidParams,`Invalid task creation result: ${h}`)}return f.data}let d=In(wl,m);if(!d.success){let f=d.error instanceof Error?d.error.message:String(d.error);throw new D(B.InvalidParams,`Invalid tools/call result: ${f}`)}return d.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){LT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&MT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Fi.includes(r)?r:uh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},ol)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},$h,r):this.request({method:"sampling/createMessage",params:e},Sh,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},xl,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},xl,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new D(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof D?i:new D(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},kh,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function hv(t){return!!t&&typeof t=="object"&&UT in t}function FT(t){return t[UT]?.complete}var UT,ZT,HT=w(()=>{UT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(ZT||(ZT={}))});var BT=w(()=>{});function N9(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!A9.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function z9(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function gv(t){let e=N9(t);return z9(t,e.warnings),e.isValid}var A9,VT=w(()=>{A9=/^[A-Za-z0-9._-]{1,128}$/});var Lu,GT=w(()=>{Lu=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Du=w(()=>{Ll();Ll()});function KT(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function M9(t){return"_def"in t||"_zod"in t||KT(t)}function yv(t){return typeof t!="object"||t===null||M9(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(KT)}function WT(t){if(t)return yv(t)?jo(t):t}function L9(t){let e=An(t);return e?Object.entries(e).map(([r,n])=>{let o=c$(n),s=l$(n);return{name:r,description:o,required:!s}}):[]}function Hn(t){let r=An(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Zl(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function JT(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var qu,j9,Ma,YT=w(()=>{qT();ia();xg();Ss();HT();BT();VT();GT();Du();qu=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Mu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Lu(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(bl)),this.server.assertCanSetRequestHandler(Hn(xs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(bl,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=zs(r.inputSchema);return o?_g(o,{strictUnions:!0,pipeStrategy:"input"}):j9})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=zs(r.outputSchema);o&&(n.outputSchema=_g(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(xs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new D(B.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new D(B.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new D(B.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new D(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof D&&n.code===B.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=zs(e.inputSchema)??e.inputSchema,i=await Dl(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=ql(a);throw new D(B.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new D(B.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=zs(e.outputSchema),s=await Dl(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=ql(i);throw new D(B.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(m=>setTimeout(m,u));let p=await n.taskStore.getTask(c);if(!p)throw new D(B.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Hn(Sl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Sl,async e=>{switch(e.params.ref.type){case"ref/prompt":return SS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return $S(e),this.handleResourceCompletion(e,e.params.ref);default:throw new D(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new D(B.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new D(B.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ma;let s=An(n.argsSchema)?.[e.params.argument.name];if(!hv(s))return Ma;let i=FT(s);if(!i)return Ma;let a=await i(e.params.argument.value,e.params.context);return JT(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return Ma;throw new D(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ma;let s=await o(e.params.argument.value,e.params.context);return JT(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(hl)),this.server.assertCanSetRequestHandler(Hn(gl)),this.server.assertCanSetRequestHandler(Hn(yl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(hl,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(gl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(yl,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new D(B.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new D(B.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(vl)),this.server.assertCanSetRequestHandler(Hn(_l)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(vl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?L9(r.argsSchema):void 0}))})),this.server.setRequestHandler(_l,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new D(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new D(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=zs(n.argsSchema),s=await Dl(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=ql(c);throw new D(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:jo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=jo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof Ft?c._def?.innerType:c;return hv(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){gv(e);let u={title:r,description:n,inputSchema:WT(o),outputSchema:WT(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&gv(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=jo(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=jo(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];yv(c)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!yv(r[0])&&(i=r.shift())):typeof c=="object"&&c!==null&&(i=r.shift())}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},j9={type:"object",properties:{}};Ma={completion:{values:[],hasMore:!1}}});function Xs(){return`${Date.now()}-${++D9}`}function hr(t,e){let r=0,n=0,o=-1,s=-1;for(;n<e.length;)if(r<t.length&&(t[r]==="?"||t[r]===e[n]))r++,n++;else if(r<t.length&&t[r]==="*")o=r++,s=n;else if(o>=0)r=o+1,n=++s;else return!1;for(;r<t.length&&t[r]==="*";)r++;return r===t.length}function qe(t,e){if(!e)return!1;let r=new Date(t).getTime();return Date.now()>r+e}var D9,Gr=w(()=>{D9=0});var Zu,XT=w(()=>{Gr();Zu=class{entries=new Map;async get(e){let r=this.entries.get(e);return r?qe(r.setAt,r.ttlMs)?(this.entries.delete(e),null):r:null}async set(e,r,n,o,s){let i=new Date().toISOString(),a=this.entries.get(e),c={key:e,value:r,category:o,setBy:n,setAt:a?.setAt??i,updatedAt:i,ttlMs:s};return this.entries.set(e,c),c}async delete(e){return this.entries.delete(e)}async query(e,r){let n=[];for(let o of this.entries.values()){if(qe(o.setAt,o.ttlMs)){this.entries.delete(o.key);continue}e&&!hr(e,o.key)||r&&o.category!==r||n.push(o)}return n}async getAll(){let e=[];for(let r of this.entries.values())qe(r.setAt,r.ttlMs)||e.push(r);return e}async load(e){this.entries.clear();for(let r of e)qe(r.setAt,r.ttlMs)||this.entries.set(r.key,r)}}});var Uu,QT=w(()=>{Gr();Uu=class{claims=new Map;eventStore;constructor(e){this.eventStore=e}async claim(e,r,n,o){let s=this.claims.get(e);if(s&&s.status==="active"&&!qe(s.claimedAt,s.ttlMs))return s.owner!==n?{status:"rejected",claim:s}:(s.value=r,s.ttlMs=o,{status:"approved",claim:s});let i={resource:e,value:r,owner:n,status:"active",claimedAt:new Date().toISOString(),ttlMs:o};return this.claims.set(e,i),await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),{status:"approved",claim:i}}async release(e,r){let n=this.claims.get(e);return!n||n.status!=="active"||n.owner!==r?null:(n.status="released",await this.eventStore.publish("claim.released",{resource:e,owner:r},r),n)}async check(e){let r=this.claims.get(e);return r?(r.status==="active"&&qe(r.claimedAt,r.ttlMs)&&(r.status="expired"),r):null}async list(e){let r=[];for(let n of this.claims.values())n.status==="active"&&qe(n.claimedAt,n.ttlMs)&&(n.status="expired"),n.status==="active"&&(e&&!hr(e,n.resource)||r.push(n));return r}async getAll(){return[...this.claims.values()]}async load(e){this.claims.clear();for(let r of e)this.claims.set(r.resource,r)}}});var Fu,eP=w(()=>{Fu=class{events=[];cursor=0;async publish(e,r,n){let o={id:++this.cursor,type:e,data:r,publishedBy:n,publishedAt:new Date().toISOString()};return this.events.push(o),this.events.length>1e4&&(this.events=this.events.slice(-1e4)),o}async getEvents(e,r){let n=this.events;return e!==void 0&&(n=n.filter(o=>o.id>e)),r&&(n=n.filter(o=>o.type===r)),{events:n,cursor:this.cursor}}async getCursor(){return this.cursor}async getAll(){return[...this.events]}async load(e,r){this.events=e,this.cursor=r}}});var Hu,tP=w(()=>{Gr();Hu=class{discoveries=[];eventStore;constructor(e){this.eventStore=e}async publish(e,r,n,o){let s={id:Xs(),topic:e,content:r,category:o,publishedBy:n,publishedAt:new Date().toISOString()};return this.discoveries.push(s),await this.eventStore.publish("discovery.published",{id:s.id,topic:e,category:o},n),s}async search(e,r){let n=this.discoveries;if(r&&(n=n.filter(o=>o.category===r)),e){let o=e.toLowerCase();n=n.filter(s=>s.topic.toLowerCase().includes(o)||s.content.toLowerCase().includes(o))}return n}async getAll(){return[...this.discoveries]}async load(e){this.discoveries=e}}});import{randomBytes as q9}from"node:crypto";var Bn,Bu=w(()=>{Bn=class{messages=[];async send(e,r,n,o){let s={id:q9(8).toString("hex"),from:e,to:r,content:n,replyTo:o,sentAt:new Date().toISOString()};return this.messages.push(s),s}async getFor(e,r){return this.messages.filter(n=>!(n.to!==e||r&&n.sentAt<=r))}async getAll(){return[...this.messages]}}});import{randomBytes as Z9}from"node:crypto";var Vn,Vu=w(()=>{Vn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:Z9(8).toString("hex"),from:e,problem:r,needs_capability:n,urgency:o??"normal",status:"open",createdAt:new Date().toISOString()};return this.requests.set(s.id,s),await this.eventStore.publish("help.requested",{request_id:s.id,from:e,problem:r,needs_capability:n,urgency:s.urgency},e),s}async claim(e,r){let n=this.requests.get(e);return!n||n.status!=="open"?null:(n.status="claimed",n.claimedBy=r,await this.eventStore.publish("help.claimed",{request_id:e,claimed_by:r},r),n)}async resolve(e,r){let n=this.requests.get(e);return!n||n.status!=="claimed"?null:(n.status="resolved",await this.eventStore.publish("help.resolved",{request_id:e,resolved_by:r},r),n)}async list(e){let r=[...this.requests.values()];return e?r.filter(n=>n.status===e):r}}});var Gn,Gu=w(()=>{Gn=class{reports=new Map;async report(e,r,n,o){let s={claim:e,agent:r,progress:Math.max(0,Math.min(1,n)),note:o,updatedAt:new Date().toISOString()};return this.reports.set(e,s),s}async get(e){return this.reports.get(e)??null}async list(){return[...this.reports.values()]}}});import{randomBytes as U9}from"node:crypto";var Wn,Wu=w(()=>{Wn=class{conflicts=new Map;eventStore;constructor(e){this.eventStore=e}async flag(e,r,n,o){let s={id:U9(8).toString("hex"),flaggedBy:e,discovery_a:r,discovery_b:n,reason:o,status:"open",createdAt:new Date().toISOString()};return this.conflicts.set(s.id,s),await this.eventStore.publish("conflict.flagged",{conflict_id:s.id,flagged_by:e,discovery_a:r,discovery_b:n},e),s}async resolve(e,r,n){let o=this.conflicts.get(e);return!o||o.status!=="open"?null:(o.status="resolved",o.resolvedBy=r,o.resolution=n,await this.eventStore.publish("conflict.resolved",{conflict_id:e,resolved_by:r,resolution:n},r),o)}async list(e){let r=[...this.conflicts.values()];return e?r.filter(n=>n.status===e):r}}});var Jn,Ju=w(()=>{Jn=class{assignments=new Map;async assign(e,r){let n={agent:e,role:r,assignedAt:new Date().toISOString()};return this.assignments.set(e,n),n}async getAssignments(){return[...this.assignments.values()]}async getByAgent(e){return this.assignments.get(e)??null}async remove(e){return this.assignments.delete(e)}}});import{randomBytes as F9}from"node:crypto";var Kn,Ku=w(()=>{Kn=class{proposals=new Map;eventStore;constructor(e){this.eventStore=e}async propose(e,r,n,o){let s={id:F9(8).toString("hex"),proposedBy:e,action:r,detail:n,requires_quorum:o??2,endorsements:[e],status:"open",createdAt:new Date().toISOString()};return this.proposals.set(s.id,s),await this.eventStore.publish("governance.proposal.created",{proposal_id:s.id,action:r,proposedBy:e,requires_quorum:s.requires_quorum},e),s}async endorse(e,r){let n=this.proposals.get(e);return!n||n.status!=="open"?null:(n.endorsements.includes(r)||n.endorsements.push(r),n.endorsements.length>=n.requires_quorum&&(n.status="approved",await this.eventStore.publish("governance.proposal.approved",{proposal_id:e,action:n.action,endorsements:n.endorsements},r)),n)}async list(e){let r=[...this.proposals.values()];return e?r.filter(n=>n.status===e):r}async get(e){return this.proposals.get(e)??null}}});import{randomBytes as H9}from"node:crypto";var Yn,Yu=w(()=>{Yn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:H9(8).toString("hex"),requestedBy:e,role:r,count:Math.max(1,n),reason:o,status:"pending",createdAt:new Date().toISOString()};return this.requests.set(s.id,s),s}async approve(e){let r=this.requests.get(e);return!r||r.status!=="pending"?null:(r.status="approved",await this.eventStore.publish("reinforcement.approved",{request_id:e,role:r.role,count:r.count},"server"),r)}async deny(e,r){let n=this.requests.get(e);return!n||n.status!=="pending"?null:(n.status="denied",n.denialReason=r,await this.eventStore.publish("reinforcement.denied",{request_id:e,role:n.role,reason:r},"server"),n)}async list(){return[...this.requests.values()]}}});var Xn,Xu=w(()=>{Xn=class{protocolHalt=null;agentHalts=new Map;protocolPause=null;agentPauses=new Map;events;constructor(e){this.events=e}async halt(e,r,n="completed",o){let s={halted:!0,reason:e,status:n,haltedBy:r,haltedAt:new Date().toISOString()};return o?(this.agentHalts.set(o,s),await this.events.publish("agent.halted",{agent:o,reason:e,status:n,halted_by:r},r)):(this.protocolHalt=s,await this.events.publish("protocol.halt",{reason:e,status:n,halted_by:r},r)),s}async pause(e,r,n){let o={paused:!0,reason:e,pausedBy:r,pausedAt:new Date().toISOString()};return n?(this.agentPauses.set(n,o),await this.events.publish("agent.paused",{agent:n,reason:e,paused_by:r},r)):(this.protocolPause=o,await this.events.publish("protocol.paused",{reason:e,paused_by:r},r)),o}async resume(e,r,n){return n?this.agentPauses.has(n)?(this.agentPauses.delete(n),await this.events.publish("agent.resumed",{agent:n,reason:r,resumed_by:e},e),!0):!1:this.protocolPause?(this.protocolPause=null,await this.events.publish("protocol.resumed",{reason:r,resumed_by:e},e),!0):!1}getStatus(e){if(this.protocolHalt)return{halted:!0,paused:!1,haltReason:this.protocolHalt.reason,haltStatus:this.protocolHalt.status};if(e&&this.agentHalts.has(e)){let r=this.agentHalts.get(e);return{halted:!0,paused:!1,haltReason:r.reason,haltStatus:r.status}}return this.protocolPause?{halted:!1,paused:!0,pauseReason:this.protocolPause.reason}:e&&this.agentPauses.has(e)?{halted:!1,paused:!0,pauseReason:this.agentPauses.get(e).reason}:{halted:!1,paused:!1}}}});var Qn,Qu=w(()=>{Qn=class{runs=new Map;async start(e,r){let n={agentId:e,role:r,status:"running",startedAt:new Date().toISOString()};return this.runs.set(e,n),n}async complete(e,r){let n=this.runs.get(e);return n?(Object.assign(n,r,{completedAt:new Date().toISOString()}),(!n.status||n.status==="running")&&(n.status="completed"),n):null}async get(e){return this.runs.get(e)??null}async list(e){let r=[...this.runs.values()];return e?r.filter(n=>n.status===e):r}async summary(){let e=0,r=0,n=0,o=0;for(let s of this.runs.values())(s.status==="completed"||s.status==="halted")&&e++,s.status==="error"&&r++,s.usage&&(n+=s.usage.totalTokens),s.elapsed&&(o+=s.elapsed);return{agents:this.runs.size,completed:e,errors:r,totalTokens:n,totalDuration:o}}}});function rP(){let t=new Fu,e=new Zu,r=new Uu(t),n=new Hu(t),o=new Bn,s=new Vn(t),i=new Gn,a=new Wn(t),c=new Jn,l=new Kn(t),u=new Yn(t),p=new Xn(t),m=new Qn;return{events:t,state:e,claims:r,discoveries:n,messages:o,help:s,progress:i,conflicts:a,roles:c,proposals:l,reinforcements:u,control:p,runs:m}}function vv(t,e={}){let r=e.agentId??"agent_default",n=e.namespace&&e.namespace!=="default"?`@${e.namespace}`:"",o=new qu({name:"incubator",version:"1.0.0"});function s(){return r}function i(){e.onSave&&e.onSave()}function a(c,l,u){if(e.verbose){let p=new Date().toISOString().slice(11,23);console.error(` ${p} [${l}${n}] ${c} ${u}`)}}return o.registerTool("incubator_getState",{description:"Read a shared state value by key. Check state before making decisions to avoid conflicts with other agents.",inputSchema:{key:M.string().describe("The state key to read")}},async c=>{let l=await t.state.get(c.key);return a("getState",s(),`key=${c.key} ${l?"HIT":"MISS"}`),l?{content:[{type:"text",text:JSON.stringify({found:!0,entry:l})}]}:{content:[{type:"text",text:JSON.stringify({found:!1,key:c.key})}]}}),o.registerTool("incubator_setState",{description:"Write a shared state value. Last-writer-wins. Use this to share decisions, progress, or context with other agents. Use claims for mutual exclusion instead.",inputSchema:{key:M.string().describe("The state key to write"),value:M.unknown().describe("The value to store (any JSON-serializable value)"),category:M.string().optional().describe('Optional category for grouping (e.g. "config", "progress")'),ttlMs:M.number().optional().describe("Optional time-to-live in milliseconds")}},async c=>{let l=await t.state.set(c.key,c.value,s(),c.category,c.ttlMs);return a("setState",s(),`key=${c.key} val=${JSON.stringify(c.value).slice(0,60)}`),i(),{content:[{type:"text",text:JSON.stringify({success:!0,entry:l})}]}}),o.registerTool("incubator_queryState",{description:"Search shared state by glob pattern and/or category. Use to discover what other agents have shared.",inputSchema:{pattern:M.string().optional().describe('Glob pattern to match keys (e.g. "agent_*", "config.*")'),category:M.string().optional().describe("Filter by category")}},async c=>{let l=await t.state.query(c.pattern,c.category);return{content:[{type:"text",text:JSON.stringify({count:l.length,entries:l})}]}}),o.registerTool("incubator_deleteState",{description:"Remove a shared state value.",inputSchema:{key:M.string().describe("The state key to delete")}},async c=>{let l=await t.state.delete(c.key);return i(),{content:[{type:"text",text:JSON.stringify({deleted:l})}]}}),o.registerTool("incubator_claim",{description:"Claim exclusive access to a resource (file, variable, function, etc). First-come-first-served. If rejected, the response includes who owns it so you can coordinate. Always claim before modifying shared resources.",inputSchema:{resource:M.string().describe("Resource identifier (e.g. file path, variable name, function name)"),value:M.string().describe("What you plan to do with the resource"),ttlMs:M.number().optional().describe("Optional auto-expire in milliseconds (default: no expiry)")}},async c=>{let l=await t.claims.claim(c.resource,c.value,s(),c.ttlMs);return a("claim",s(),`resource=${c.resource} \u2192 ${l.status}${l.status==="rejected"?` (owner: ${l.claim.owner})`:""}`),i(),{content:[{type:"text",text:JSON.stringify(l)}]}}),o.registerTool("incubator_releaseClaim",{description:"Release a claim when done with a resource. Always release claims promptly.",inputSchema:{resource:M.string().describe("The resource to release")}},async c=>{let l=await t.claims.release(c.resource,s());return a("releaseClaim",s(),`resource=${c.resource} ${l?"OK":"NOT_OWNER"}`),i(),l?{content:[{type:"text",text:JSON.stringify({released:!0,claim:l})}]}:{content:[{type:"text",text:JSON.stringify({released:!1,reason:"No active claim found or not owner"})}]}}),o.registerTool("incubator_checkClaim",{description:"Check who owns a resource without claiming it. Use to check before attempting a claim.",inputSchema:{resource:M.string().describe("The resource to check")}},async c=>{let l=await t.claims.check(c.resource);return l?{content:[{type:"text",text:JSON.stringify({claimed:l.status==="active",claim:l})}]}:{content:[{type:"text",text:JSON.stringify({claimed:!1,resource:c.resource})}]}}),o.registerTool("incubator_listClaims",{description:"List all active claims, optionally filtered by glob pattern. Use to see what resources are locked.",inputSchema:{pattern:M.string().optional().describe('Glob pattern to filter resources (e.g. "src/*.ts", "var_*")')}},async c=>{let l=await t.claims.list(c.pattern);return{content:[{type:"text",text:JSON.stringify({count:l.length,claims:l})}]}}),o.registerTool("incubator_publishEvent",{description:"Broadcast an event to all agents. Use for: conflicts detected, work completed, blockers found, warnings. Other agents poll for events with getEvents.",inputSchema:{type:M.string().describe('Event type (e.g. "conflict", "completed", "blocker", "warning")'),data:M.unknown().describe("Event payload (any JSON-serializable data)")}},async c=>{let l=await t.events.publish(c.type,c.data,s());return a("publishEvent",s(),`type=${c.type}`),i(),{content:[{type:"text",text:JSON.stringify({published:!0,event:l})}]}}),o.registerTool("incubator_getEvents",{description:"Poll for events since your last cursor. Call periodically to stay aware of other agents' activity. Save the returned cursor for next call.",inputSchema:{since:M.number().optional().describe("Cursor from previous call (omit for all events)"),type:M.string().optional().describe("Filter by event type")}},async c=>{let l=await t.events.getEvents(c.since,c.type);return{content:[{type:"text",text:JSON.stringify(l)}]}}),o.registerTool("incubator_publishDiscovery",{description:"Share a finding that other agents should know about. Use for: naming conventions found, patterns discovered, gotchas encountered, decisions made.",inputSchema:{topic:M.string().describe("Short topic/title for the discovery"),content:M.string().describe("Detailed content of the discovery"),category:M.string().optional().describe('Optional category (e.g. "naming", "pattern", "warning")')}},async c=>{let l=await t.discoveries.publish(c.topic,c.content,s(),c.category);return a("publishDiscovery",s(),`"${c.topic}" ${c.category?`[${c.category}]`:""}`),i(),{content:[{type:"text",text:JSON.stringify({published:!0,discovery:l})}]}}),o.registerTool("incubator_searchDiscoveries",{description:"Search discoveries shared by all agents. Text search across topics and content. Check before making decisions that might conflict.",inputSchema:{query:M.string().optional().describe("Text search query (searches topic and content)"),category:M.string().optional().describe("Filter by category")}},async c=>{let l=await t.discoveries.search(c.query,c.category);return a("searchDiscoveries",s(),`query=${c.query??"*"} \u2192 ${l.length} results`),{content:[{type:"text",text:JSON.stringify({count:l.length,discoveries:l})}]}}),o.registerTool("incubator_getProtocol",{description:"Get the coordination protocol for your role. Returns current phase, steps to follow, resource naming conventions, and natural language instructions. Call this on startup and again when you observe a phase change event.",inputSchema:{role:M.string().optional().describe("Your role name (if not specified, uses the first role in the spec)")}},async c=>{let l=e.getProtocol?.();if(!l)return{content:[{type:"text",text:JSON.stringify({error:"No protocol loaded for this namespace"})}]};let u=Object.keys(l.roles),p=c.role??u[0],m=l.roles[p];if(!m)return{content:[{type:"text",text:JSON.stringify({error:`Unknown role "${p}". Available roles: ${u.join(", ")}`})}]};let d=await t.state.get("phase"),f=Object.keys(l.phases),h=d?.value??f[0];if(!l.phases[h])return{content:[{type:"text",text:JSON.stringify({error:`Unknown phase "${h}". Available phases: ${f.join(", ")}`})}]};let g=await xd(l,t,s()),v=xc(l,p,h),_=$d(l,p,h,g),x={};for(let[de,Y]of Object.entries(l.phases))x[de]={description:Y.description,...Y.terminal?{terminal:!0}:{}};let k=await t.roles.getAssignments(),I={protocol:{name:l.name,title:l.title,acp:l.acp},role:{name:p,description:m.description},current_phase:h,rules:v.steps??[],loop:v.loop??!1,resources:l.resources??{},variables:g,instructions:_,phases:x,...l.errors?{errors:l.errors}:{},...l.governance?{governance:l.governance}:{},...k.length>0?{team:k}:{}};return a("getProtocol",s(),`role=${p} phase=${h}`),{content:[{type:"text",text:JSON.stringify(I)}]}}),o.registerTool("incubator_requestHalt",{description:"Halt the entire protocol or a specific agent. Protocol-wide halt ends the run. Per-agent halt fires that agent (claims auto-released, role removed).",inputSchema:{reason:M.string().describe("Why the halt is being requested"),status:M.enum(["completed","failed"]).optional().describe("Whether this is a successful completion or failure (default: completed)"),target:M.string().optional().describe("Agent ID to halt (omit for protocol-wide halt)")}},async c=>{let l=s(),u=c.status??"completed";if(c.target){let m=await t.claims.list();for(let d of m)d.owner===c.target&&d.status==="active"&&await t.claims.release(d.resource,c.target);await t.roles.remove(c.target)}let p=await t.control.halt(c.reason,l,u,c.target);return a("requestHalt",l,`target=${c.target??"protocol"} status=${u}`),i(),{content:[{type:"text",text:JSON.stringify({halted:!0,info:p})}]}}),o.registerTool("incubator_requestPause",{description:"Pause the entire protocol or a specific agent. Paused agents stop iterating until resumed.",inputSchema:{reason:M.string().describe("Why the pause is being requested"),target:M.string().optional().describe("Agent ID to pause (omit for protocol-wide pause)")}},async c=>{let l=s(),u=await t.control.pause(c.reason,l,c.target);return a("requestPause",l,`target=${c.target??"protocol"}`),i(),{content:[{type:"text",text:JSON.stringify({paused:!0,info:u})}]}}),o.registerTool("incubator_resumeAgent",{description:"Resume a paused agent or the entire protocol.",inputSchema:{reason:M.string().describe("Why the agent/protocol is being resumed"),target:M.string().optional().describe("Agent ID to resume (omit for protocol-wide resume)")}},async c=>{let l=s(),u=await t.control.resume(l,c.reason,c.target);return a("resumeAgent",l,`target=${c.target??"protocol"} \u2192 ${u}`),i(),{content:[{type:"text",text:JSON.stringify({resumed:u})}]}}),o.registerTool("incubator_getTopics",{description:"List published and subscribed cross-namespace topics for this namespace. Topics enable event routing between separate protocol namespaces.",inputSchema:{}},async()=>{let c=e.getTopicRouter?.(),l=e.namespace??"default";if(!c)return{content:[{type:"text",text:JSON.stringify({error:"Topic routing not enabled"})}]};let u=c.getTopics(l);return a("getTopics",s(),`pub=${u.publishes.length} sub=${u.subscribes.length}`),{content:[{type:"text",text:JSON.stringify(u)}]}}),o.registerTool("incubator_subscribeTopic",{description:"Subscribe this namespace to a cross-namespace topic at runtime. Events published to this topic in other namespaces will appear in your event stream.",inputSchema:{topic:M.string().describe("The topic (event type) to subscribe to")}},async c=>{let l=e.getTopicRouter?.(),u=e.namespace??"default";return l?(l.subscribe(u,c.topic),a("subscribeTopic",s(),`topic=${c.topic}`),{content:[{type:"text",text:JSON.stringify({subscribed:!0,topic:c.topic})}]}):{content:[{type:"text",text:JSON.stringify({error:"Topic routing not enabled"})}]}}),o.registerTool("incubator_publishTopic",{description:"Declare this namespace as publishing a cross-namespace topic at runtime. Events matching this topic will be routed to subscribing namespaces.",inputSchema:{topic:M.string().describe("The topic (event type) to publish")}},async c=>{let l=e.getTopicRouter?.(),u=e.namespace??"default";return l?(l.publish(u,c.topic),a("publishTopic",s(),`topic=${c.topic}`),{content:[{type:"text",text:JSON.stringify({published:!0,topic:c.topic})}]}):{content:[{type:"text",text:JSON.stringify({error:"Topic routing not enabled"})}]}}),o}var _v=w(()=>{YT();Du();XT();QT();eP();tP();Bu();Vu();Gu();Wu();Ju();Ku();Yu();Xu();Qu();wi()});import{createRequire as B9}from"node:module";function nP(t){let r=B9(import.meta.url)("@honeybee-ai/carapace");return t&&console.error("[incubator] carapace loaded"),r}function Qs(t,e,r){let n=e.filter(Boolean).join(" ");if(!n)return;let o=t.scan(n);if(r&&o.findings.length>0){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] score=${o.score} action=${o.action} findings=${o.findings.length}`)}if(o.action==="BLOCK")throw new La(o);if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}}function Go(t,e,r){let n=e.filter(Boolean).join(" ");if(!n)return!0;let o=t.scan(n);if(o.action==="BLOCK"){if(r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] READ BLOCKED: score=${o.score} \u2014 poisoned entry filtered out`)}return!1}return!0}function Wo(t){return typeof t=="string"?t:t==null?"":JSON.stringify(t)}function oP(t,e,r){return{state:{...t.state,set:async(n,o,s,i,a)=>(Qs(e,[n,Wo(o),i],r),t.state.set(n,o,s,i,a)),get:async n=>{let o=await t.state.get(n);return!o||!Go(e,[o.key,Wo(o.value),o.category],r)?null:o},query:async(n,o)=>(await t.state.query(n,o)).filter(i=>Go(e,[i.key,Wo(i.value),i.category],r))},events:{...t.events,publish:async(n,o,s)=>(Qs(e,[n,Wo(o)],r),t.events.publish(n,o,s)),getEvents:async(n,o)=>{let s=await t.events.getEvents(n,o);return{events:s.events.filter(i=>Go(e,[i.type,Wo(i.data)],r)),cursor:s.cursor}}},claims:{...t.claims,claim:async(n,o,s,i)=>(Qs(e,[n,o],r),t.claims.claim(n,o,s,i)),check:async n=>{let o=await t.claims.check(n);return!o||!Go(e,[o.resource,o.value],r)?null:o},list:async n=>(await t.claims.list(n)).filter(s=>Go(e,[s.resource,s.value],r))},discoveries:{...t.discoveries,publish:async(n,o,s,i)=>(Qs(e,[n,o,i],r),t.discoveries.publish(n,o,s,i)),search:async(n,o)=>(await t.discoveries.search(n,o)).filter(i=>Go(e,[i.topic,i.content,i.category],r))},messages:{...t.messages,send:async(n,o,s,i)=>(Qs(e,[s],r),t.messages.send(n,o,s,i))},help:{...t.help,request:async(n,o,s,i)=>(Qs(e,[o,s],r),t.help.request(n,o,s,i))},progress:t.progress,conflicts:t.conflicts,roles:t.roles,proposals:t.proposals,reinforcements:t.reinforcements,control:t.control,runs:t.runs}}function sP(t,e,r){let n=0,o=(s,i)=>s.filter(a=>Go(e,i(a),r)?!0:(n++,!1));return t.state=o(t.state,s=>[s.key,Wo(s.value),s.category]),t.claims=o(t.claims,s=>[s.resource,s.value]),t.events=o(t.events,s=>[s.type,Wo(s.data)]),t.discoveries=o(t.discoveries,s=>[s.topic,s.content,s.category]),n>0&&console.error(`[incubator] Carapace: ${n} poisoned entries removed from snapshot`),{blocked:n}}var La,ep=w(()=>{La=class extends Error{score;action;findings;constructor(e){super(`[carapace] Blocked: ${e.summary}`),this.name="CarapaceBlockedError",this.score=e.score,this.action=e.action,this.findings=e.findings}}});function V9(t){let e=t.headers.origin||"";if(/^https?:\/\/localhost(:\d+)?$/.test(e)||/^https:\/\/[a-z0-9-]+\.honeyb\.dev$/.test(e))return e;let r=process.env.INCUBATOR_CORS_ORIGINS;if(r)for(let n of r.split(",")){let o=n.trim();if(o&&e===o)return e;if(o.startsWith("*.")){let s=o.slice(1);if(new RegExp(`^https://[a-z0-9-]+${s.replace(/\./g,"\\.")}(:\\d+)?$`).test(e))return e}}return""}function R(t,e,r,n){let o=n?V9(n):"http://localhost:5173",s={"Content-Type":"application/json","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, X-Agent-Id, X-Namespace"};o&&(s["Access-Control-Allow-Origin"]=o),t.writeHead(e,s),t.end(JSON.stringify(r))}function Ke(t,e){let r=e.agentId??t.headers["x-agent-id"]??"rest_anonymous";return r.startsWith("honeycomb:")?"rest_anonymous":r}async function W9(t){return t.method==="GET"?{}:new Promise((e,r)=>{let n="",o=0;t.on("data",s=>{if(o+=s.length,o>G9){t.destroy(),r(new Error("Payload too large"));return}n+=s.toString()}),t.on("end",()=>{if(!n){e({});return}try{e(JSON.parse(n))}catch{e({})}})})}function Y9(t){let e=t.slice(5),r=e.indexOf("/"),n=r===-1?e:e.slice(0,r);if(n==="_ns")return{namespace:null,rewrittenPath:t};if(J9.has(n))return{namespace:"default",rewrittenPath:t};let o=r===-1?"":e.slice(r);return{namespace:n,rewrittenPath:`/api${o}`}}async function iP(t,e,r,n){let o=t.url??"/";if(!o.startsWith("/api/"))return!1;if(t.method==="OPTIONS")return R(e,204,""),!0;let s=await W9(t),i=new URL(o,"http://localhost").pathname;if(i==="/api/_ns"&&t.method==="GET"){let d=[];for(let f of r.list()){let h=r.get(f),g=await h.state.query(),v=await h.claims.list(),_=await h.events.getEvents(),x=await h.discoveries.search();d.push({name:f,state:g.length,claims:v.length,events:_.cursor,discoveries:x.length})}return R(e,200,{namespaces:d}),!0}let a=i.match(/^\/api\/_ns\/(.+)$/);if(a&&t.method==="DELETE"){let d=decodeURIComponent(a[1]),f=r.delete(d);return R(e,200,{deleted:f}),!0}let{namespace:c,rewrittenPath:l}=Y9(i);if(c===null)return R(e,404,{error:`No route: ${t.method} ${i}`}),!0;let u;try{u=r.get(c)}catch(d){return R(e,400,{error:d.message}),!0}if(l==="/api/protocol"){if(t.method==="GET"){let d=r.getProtocol(c);if(!d)R(e,200,{loaded:!1});else{let f=await u.roles.getAssignments();R(e,200,{loaded:!0,spec:d,...f.length>0?{team:f}:{}})}return!0}if(t.method==="PUT"){try{let d;if(typeof s.spec=="string")d=await co(s.spec);else if(s.acp&&s.name)d=await co(JSON.stringify(s));else return R(e,400,{error:'Missing "spec" field (YAML/JSON string) or direct spec object'}),!0;let f=[],h=d;if(h.roles&&typeof h.roles=="object")for(let g of Object.values(h.roles))g?.description&&f.push(String(g.description)),g?.instructions&&f.push(String(g.instructions));if(h.phases&&typeof h.phases=="object")for(let g of Object.values(h.phases))g?.description&&f.push(String(g.description));if(f.length>0){let g=`__spec_scan_${Date.now()}`;await u.state.set(g,f.join(" "),Ke(t,s),"__scan"),await u.state.delete(g)}r.setProtocol(c,d),R(e,200,{loaded:!0,name:d.name,title:d.title})}catch(d){d instanceof ao?R(e,400,{error:"Invalid spec",details:d.errors}):R(e,400,{error:d.message})}return!0}}let p=l.match(/^\/api\/topics(?:\/(.+))?$/);if(p){let d=r.getRouter();if(!d)return R(e,501,{error:"Honeycomb topic routing not enabled (no notification bus)"}),!0;let f=p[1];if(t.method==="GET"&&!f){let v=d.getTopics(c);return R(e,200,v),!0}if(t.method==="POST"&&f==="subscribe"){let v=s.topic;return v?(d.subscribe(c,v),R(e,200,{subscribed:!0,topic:v}),!0):(R(e,400,{error:"Missing required field: topic"}),!0)}if(t.method==="POST"&&f==="publish"){let v=s.topic;return v?(d.publish(c,v),R(e,200,{published:!0,topic:v}),!0):(R(e,400,{error:"Missing required field: topic"}),!0)}let h=f?.match(/^subscribe\/(.+)$/);if(t.method==="DELETE"&&h){let v=decodeURIComponent(h[1]);return d.unsubscribe(c,v),R(e,200,{unsubscribed:!0,topic:v}),!0}let g=f?.match(/^publish\/(.+)$/);if(t.method==="DELETE"&&g){let v=decodeURIComponent(g[1]);return d.unpublish(c,v),R(e,200,{unpublished:!0,topic:v}),!0}return R(e,404,{error:`No route: ${t.method} ${i}`}),!0}if(l.match(/^\/api\/dance\/(.+)$/)&&t.method==="POST")return R(e,501,{error:"Dance tool calls via REST not yet implemented (use WebSocket)"},t),!0;for(let d of K9){if(t.method!==d.method)continue;let f=l.match(d.pattern);if(f){if(n){let h=new Date().toISOString().slice(11,23),g=Ke(t,s),v=c==="default"?"":`@${c}`;console.error(` ${h} [${g}${v}] REST ${t.method} ${i}`)}try{await d.handler(t,e,u,f,s)}catch(h){if(h instanceof La)R(e,403,{error:"prompt_injection_detected",message:h.message,score:h.score,action:h.action,findings:h.findings});else throw h}return!0}}return R(e,404,{error:`No route: ${t.method} ${i}`}),!0}var G9,J9,K9,aP=w(()=>{ep();wi();G9=1024*1024;J9=new Set(["state","claims","events","discoveries","health","protocol","messages","help","progress","conflicts","roles","reinforcements","governance","control","topics","runs"]),K9=[{method:"GET",pattern:/^\/api\/health$/,handler:async(t,e,r)=>{let n=await r.claims.list(),o=await r.events.getEvents(),s=await r.state.query();R(e,200,{status:"ok",uptime:process.uptime(),agents:new Set([...s.map(i=>i.setBy),...n.map(i=>i.owner),...o.events.map(i=>i.publishedBy)]).size,claims:n.length,events:o.cursor})}},{method:"GET",pattern:/^\/api\/state$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=n.searchParams.get("pattern")??void 0,s=n.searchParams.get("category")??void 0,i=await r.state.query(o,s);R(e,200,{count:i.length,entries:i})}},{method:"GET",pattern:/^\/api\/state\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.state.get(o);if(!s){R(e,200,{found:!1,key:o});return}R(e,200,{found:!0,entry:s})}},{method:"PUT",pattern:/^\/api\/state\/(.+)$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]);if(!("value"in o)){R(e,400,{error:"Missing required field: value"});return}let i=Ke(t,o),a=await r.state.set(s,o.value,i,o.category,o.ttlMs);R(e,200,{success:!0,entry:a})}},{method:"DELETE",pattern:/^\/api\/state\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.state.delete(o);R(e,200,{deleted:s})}},{method:"POST",pattern:/^\/api\/claims$/,handler:async(t,e,r,n,o)=>{let s=o.resource,i=o.value;if(!s||!i){R(e,400,{error:"Missing required fields: resource, value"});return}let a=Ke(t,o),c=await r.claims.claim(s,i,a,o.ttlMs);R(e,200,c)}},{method:"DELETE",pattern:/^\/api\/claims\/(.+)$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.claims.release(s,i);if(!a){R(e,200,{released:!1,reason:"No active claim found or not owner"});return}R(e,200,{released:!0,claim:a})}},{method:"GET",pattern:/^\/api\/claims\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.claims.check(o);if(!s){R(e,200,{claimed:!1,resource:o});return}R(e,200,{claimed:s.status==="active",claim:s})}},{method:"GET",pattern:/^\/api\/claims$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("pattern")??void 0,s=await r.claims.list(o);R(e,200,{count:s.length,claims:s})}},{method:"POST",pattern:/^\/api\/events$/,handler:async(t,e,r,n,o)=>{let s=o.type;if(!s){R(e,400,{error:"Missing required field: type"});return}let i=Ke(t,o),a=await r.events.publish(s,o.data??null,i);R(e,200,{published:!0,event:a})}},{method:"GET",pattern:/^\/api\/events$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=n.searchParams.get("since"),s=n.searchParams.get("type")??void 0,i=await r.events.getEvents(o?parseInt(o,10):void 0,s);R(e,200,i)}},{method:"POST",pattern:/^\/api\/discoveries$/,handler:async(t,e,r,n,o)=>{let s=o.topic,i=o.content;if(!s||!i){R(e,400,{error:"Missing required fields: topic, content"});return}let a=Ke(t,o),c=await r.discoveries.publish(s,i,a,o.category);R(e,200,{published:!0,discovery:c})}},{method:"GET",pattern:/^\/api\/discoveries$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=n.searchParams.get("query")??void 0,s=n.searchParams.get("category")??void 0,i=await r.discoveries.search(o,s);R(e,200,{count:i.length,discoveries:i})}},{method:"POST",pattern:/^\/api\/messages$/,handler:async(t,e,r,n,o)=>{let s=o.to,i=o.content;if(!s||!i){R(e,400,{error:"Missing required fields: to, content"});return}let a=Ke(t,o),c=await r.messages.send(a,s,i,o.replyTo);R(e,200,{sent:!0,message:c})}},{method:"GET",pattern:/^\/api\/messages$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=t.headers["x-agent-id"]??"rest_anonymous",s=n.searchParams.get("since")??void 0,i=await r.messages.getFor(o,s);R(e,200,{count:i.length,messages:i})}},{method:"POST",pattern:/^\/api\/roles\/request$/,handler:async(t,e,r,n,o)=>{let s=o.role;if(!s){R(e,400,{error:"Missing required field: role"});return}let i=Ke(t,o),c=(await r.roles.getByAgent(i))?.role;await r.roles.assign(i,s),await r.events.publish("role.transition",{agent:i,from:c??null,to:s,reason:o.reason??null},i),R(e,200,{approved:!0,from:c??null,to:s})}},{method:"GET",pattern:/^\/api\/roles$/,handler:async(t,e,r)=>{let n=await r.roles.getAssignments();R(e,200,{count:n.length,assignments:n})}},{method:"POST",pattern:/^\/api\/help$/,handler:async(t,e,r,n,o)=>{let s=o.problem;if(!s){R(e,400,{error:"Missing required field: problem"});return}let i=Ke(t,o),a=await r.help.request(i,s,o.needs_capability,o.urgency);R(e,200,{created:!0,request:a})}},{method:"POST",pattern:/^\/api\/help\/([^/]+)\/claim$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.help.claim(s,i);if(!a){R(e,200,{claimed:!1,reason:"Request not found or not open"});return}R(e,200,{claimed:!0,request:a})}},{method:"POST",pattern:/^\/api\/help\/([^/]+)\/resolve$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.help.resolve(s,i);if(!a){R(e,200,{resolved:!1,reason:"Request not found or not claimed"});return}R(e,200,{resolved:!0,request:a})}},{method:"GET",pattern:/^\/api\/help$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.help.list(o);R(e,200,{count:s.length,requests:s})}},{method:"POST",pattern:/^\/api\/progress$/,handler:async(t,e,r,n,o)=>{let s=o.claim,i=o.progress;if(!s||i===void 0){R(e,400,{error:"Missing required fields: claim, progress"});return}let a=Ke(t,o),c=await r.progress.report(s,a,i,o.note);R(e,200,{reported:!0,report:c})}},{method:"GET",pattern:/^\/api\/progress\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.progress.get(o);if(!s){R(e,200,{found:!1,claim:o});return}R(e,200,{found:!0,report:s})}},{method:"GET",pattern:/^\/api\/progress$/,handler:async(t,e,r)=>{let n=await r.progress.list();R(e,200,{count:n.length,reports:n})}},{method:"POST",pattern:/^\/api\/conflicts$/,handler:async(t,e,r,n,o)=>{let s=o.discovery_a,i=o.discovery_b,a=o.reason;if(!s||!i||!a){R(e,400,{error:"Missing required fields: discovery_a, discovery_b, reason"});return}let c=Ke(t,o),l=await r.conflicts.flag(c,s,i,a);R(e,200,{flagged:!0,conflict:l})}},{method:"POST",pattern:/^\/api\/conflicts\/([^/]+)\/resolve$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=o.resolution;if(!i){R(e,400,{error:"Missing required field: resolution"});return}let a=Ke(t,o),c=await r.conflicts.resolve(s,a,i);if(!c){R(e,200,{resolved:!1,reason:"Conflict not found or not open"});return}R(e,200,{resolved:!0,conflict:c})}},{method:"GET",pattern:/^\/api\/conflicts$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.conflicts.list(o);R(e,200,{count:s.length,conflicts:s})}},{method:"POST",pattern:/^\/api\/reinforcements$/,handler:async(t,e,r,n,o)=>{let s=o.role;if(!s){R(e,400,{error:"Missing required field: role"});return}let i=Ke(t,o),a=o.count??1,c=await r.reinforcements.request(i,s,a,o.reason);R(e,200,{requested:!0,request:c})}},{method:"GET",pattern:/^\/api\/reinforcements$/,handler:async(t,e,r)=>{let n=await r.reinforcements.list();R(e,200,{count:n.length,requests:n})}},{method:"POST",pattern:/^\/api\/governance\/approve$/,handler:async(t,e,r,n,o)=>{let s=o.action;if(!s){R(e,400,{error:"Missing required field: action"});return}let i=Ke(t,o);await r.events.publish("governance.approval_requested",{action:s,detail:o.detail,files:o.files,requested_by:i},i),R(e,200,{requested:!0,action:s})}},{method:"POST",pattern:/^\/api\/governance\/escalate$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o);await r.events.publish("governance.escalated",{reason:s,context:o.context,escalated_by:i},i),R(e,200,{escalated:!0,reason:s})}},{method:"POST",pattern:/^\/api\/governance\/propose$/,handler:async(t,e,r,n,o)=>{let s=o.action;if(!s){R(e,400,{error:"Missing required field: action"});return}let i=Ke(t,o),a=await r.proposals.propose(i,s,o.detail,o.requires_quorum);R(e,200,{proposed:!0,proposal:a})}},{method:"POST",pattern:/^\/api\/governance\/endorse\/([^/]+)$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.proposals.endorse(s,i);if(!a){R(e,200,{endorsed:!1,reason:"Proposal not found or not open"});return}R(e,200,{endorsed:!0,proposal:a})}},{method:"GET",pattern:/^\/api\/governance\/proposals$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.proposals.list(o);R(e,200,{count:s.length,proposals:s})}},{method:"POST",pattern:/^\/api\/governance\/rollback$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o);await r.events.publish("governance.rollback.requested",{reason:s,scope:o.scope,requested_by:i},i),R(e,200,{requested:!0,reason:s})}},{method:"POST",pattern:/^\/api\/control\/halt$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o),a=o.status??"completed",c=o.target;if(c){let u=await r.claims.list();for(let p of u)p.owner===c&&p.status==="active"&&await r.claims.release(p.resource,c);await r.roles.remove(c)}let l=await r.control.halt(s,i,a,c);R(e,200,{halted:!0,info:l})}},{method:"POST",pattern:/^\/api\/control\/pause$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o),a=o.target,c=await r.control.pause(s,i,a);R(e,200,{paused:!0,info:c})}},{method:"POST",pattern:/^\/api\/control\/resume$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o),a=o.target,c=await r.control.resume(i,s,a);R(e,200,{resumed:c})}},{method:"GET",pattern:/^\/api\/control\/status$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("agentId")??t.headers["x-agent-id"]??void 0,s=r.control.getStatus(o);R(e,200,s)}},{method:"GET",pattern:/^\/api\/runs\/summary$/,handler:async(t,e,r)=>{let n=await r.runs.summary();R(e,200,n)}},{method:"GET",pattern:/^\/api\/runs\/([^/]+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.runs.get(o);if(!s){R(e,200,{found:!1,agentId:o});return}R(e,200,{found:!0,run:s})}},{method:"GET",pattern:/^\/api\/runs$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.runs.list(o);R(e,200,{count:s.length,runs:s})}}]});import{createRequire as X9}from"node:module";import{resolve as Q9}from"node:path";function lP(t){let e=t===":memory:"?t:Q9(t),r=cP.get(e);if(r)return r;let o=X9(import.meta.url)("better-sqlite3"),s=new o(e);return s.pragma("journal_mode = WAL"),eH(s),e!==":memory:"&&cP.set(e,s),s}function eH(t){t.exec(`
295
+ deps: ${r}}`};var T4={keyword:"dependencies",type:"object",schemaType:"object",error:Hr.error,code(t){let[e,r]=P4(t);YE(t,e),XE(t,r)}};function P4({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function YE(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,La.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let l of a)(0,La.checkReportMissingProp)(t,l)}):(r.if((0,Wy._)`${c} && (${(0,La.checkMissingProp)(t,a,s)})`),(0,La.reportMissingProp)(t,s),r.else())}}Hr.validatePropertyDeps=YE;function XE(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,E4.alwaysValidSchema)(s,e[a])||(r.if((0,La.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}Hr.validateSchemaDeps=XE;Hr.default=T4});var tT=I(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var eT=de(),R4=Pe(),O4={message:"property name must be valid",params:({params:t})=>(0,eT._)`{propertyName: ${t.propertyName}}`},C4={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:O4,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,R4.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,eT.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};Jy.default=C4});var Yy=I(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var Cu=fr(),Rr=de(),I4=cn(),Iu=Pe(),A4={message:"must NOT have additional properties",params:({params:t})=>(0,Rr._)`{additionalProperty: ${t.additionalProperty}}`},N4={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:A4,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Iu.alwaysValidSchema)(i,r))return;let l=(0,Cu.allSchemaProperties)(n.properties),u=(0,Cu.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Rr._)`${s} === ${I4.default.errors}`);function p(){e.forIn("key",o,g=>{!l.length&&!u.length?m(g):e.if(f(g),()=>m(g))})}function f(g){let v;if(l.length>8){let b=(0,Iu.schemaRefOrVal)(i,n.properties,"properties");v=(0,Cu.isOwnProperty)(e,b,g)}else l.length?v=(0,Rr.or)(...l.map(b=>(0,Rr._)`${g} === ${b}`)):v=Rr.nil;return u.length&&(v=(0,Rr.or)(v,...u.map(b=>(0,Rr._)`${(0,Cu.usePattern)(t,b)}.test(${g})`))),(0,Rr.not)(v)}function d(g){e.code((0,Rr._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){d(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Iu.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(g,v,!1),e.if((0,Rr.not)(v),()=>{t.reset(),d(g)})):(h(g,v),a||e.if((0,Rr.not)(v),()=>e.break()))}}function h(g,v,b){let x={keyword:"additionalProperties",dataProp:g,dataPropType:Iu.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,v)}}};Ky.default=N4});var oT=I(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var z4=$a(),rT=fr(),Xy=Pe(),nT=Yy(),j4={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&nT.default.code(new z4.KeywordCxt(s,nT.default,"additionalProperties"));let i=(0,rT.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=Xy.mergeEvaluated.props(e,(0,Xy.toHash)(i),s.props));let a=i.filter(p=>!(0,Xy.alwaysValidSchema)(s,r[p]));if(a.length===0)return;let c=e.name("valid");for(let p of a)l(p)?u(p):(e.if((0,rT.propertyInData)(e,o,p,s.opts.ownProperties)),u(p),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(p),t.ok(c);function l(p){return s.opts.useDefaults&&!s.compositeRule&&r[p].default!==void 0}function u(p){t.subschema({keyword:"properties",schemaProp:p,dataProp:p},c)}}};Qy.default=j4});var cT=I(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});var sT=fr(),Au=de(),iT=Pe(),aT=Pe(),M4={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,sT.allSchemaProperties)(r),c=a.filter(h=>(0,iT.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let l=i.strictSchema&&!i.allowMatchingProperties&&o.properties,u=e.name("valid");s.props!==!0&&!(s.props instanceof Au.Name)&&(s.props=(0,aT.evaluatedPropsToName)(e,s.props));let{props:p}=s;f();function f(){for(let h of a)l&&d(h),s.allErrors?m(h):(e.var(u,!0),m(h),e.if(u))}function d(h){for(let g in l)new RegExp(h).test(g)&&(0,iT.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,g=>{e.if((0,Au._)`${(0,sT.usePattern)(t,h)}.test(${g})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:aT.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Au._)`${p}[${g}]`,!0):!v&&!s.allErrors&&e.if((0,Au.not)(u),()=>e.break())})})}}};ev.default=M4});var lT=I(tv=>{"use strict";Object.defineProperty(tv,"__esModule",{value:!0});var L4=Pe(),D4={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,L4.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};tv.default=D4});var uT=I(rv=>{"use strict";Object.defineProperty(rv,"__esModule",{value:!0});var q4=fr(),Z4={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:q4.validateUnion,error:{message:"must match a schema in anyOf"}};rv.default=Z4});var pT=I(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});var Nu=de(),U4=Pe(),F4={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Nu._)`{passingSchemas: ${t.passing}}`},H4={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:F4,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(l),t.result(i,()=>t.reset(),()=>t.error(!0));function l(){s.forEach((u,p)=>{let f;(0,U4.alwaysValidSchema)(o,u)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Nu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Nu._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),f&&t.mergeEvaluated(f,Nu.Name)})})}}};nv.default=H4});var dT=I(ov=>{"use strict";Object.defineProperty(ov,"__esModule",{value:!0});var B4=Pe(),G4={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,B4.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};ov.default=G4});var hT=I(sv=>{"use strict";Object.defineProperty(sv,"__esModule",{value:!0});var zu=de(),mT=Pe(),V4={message:({params:t})=>(0,zu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,zu._)`{failingKeyword: ${t.ifClause}}`},W4={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:V4,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,mT.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=fT(n,"then"),s=fT(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let u=e.let("ifClause");t.setParams({ifClause:u}),e.if(a,l("then",u),l("else",u))}else o?e.if(a,l("then")):e.if((0,zu.not)(a),l("else"));t.pass(i,()=>t.error(!0));function c(){let u=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(u)}function l(u,p){return()=>{let f=t.subschema({keyword:u},a);e.assign(i,a),t.mergeValidEvaluated(f,i),p?e.assign(p,(0,zu._)`${u}`):t.setParams({ifClause:u})}}}};function fT(t,e){let r=t.schema[e];return r!==void 0&&!(0,mT.alwaysValidSchema)(t,r)}sv.default=W4});var gT=I(iv=>{"use strict";Object.defineProperty(iv,"__esModule",{value:!0});var J4=Pe(),K4={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,J4.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};iv.default=K4});var yT=I(av=>{"use strict";Object.defineProperty(av,"__esModule",{value:!0});var Y4=Fy(),X4=VE(),Q4=Hy(),eH=JE(),tH=KE(),rH=QE(),nH=tT(),oH=Yy(),sH=oT(),iH=cT(),aH=lT(),cH=uT(),lH=pT(),uH=dT(),pH=hT(),dH=gT();function fH(t=!1){let e=[aH.default,cH.default,lH.default,uH.default,pH.default,dH.default,nH.default,oH.default,rH.default,sH.default,iH.default];return t?e.push(X4.default,eH.default):e.push(Y4.default,Q4.default),e.push(tH.default),e}av.default=fH});var vT=I(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});var nt=de(),mH={message:({schemaCode:t})=>(0,nt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,nt._)`{format: ${t}}`},hH={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:mH,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:l,schemaEnv:u,self:p}=a;if(!c.validateFormats)return;o?f():d();function f(){let m=r.scopeValue("formats",{ref:p.formats,code:c.code.formats}),h=r.const("fDef",(0,nt._)`${m}[${i}]`),g=r.let("fType"),v=r.let("format");r.if((0,nt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,nt._)`${h}.type || "string"`).assign(v,(0,nt._)`${h}.validate`),()=>r.assign(g,(0,nt._)`"string"`).assign(v,h)),t.fail$data((0,nt.or)(b(),x()));function b(){return c.strictSchema===!1?nt.nil:(0,nt._)`${i} && !${v}`}function x(){let $=u.$async?(0,nt._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,nt._)`${v}(${n})`,O=(0,nt._)`(typeof ${v} == "function" ? ${$} : ${v}.test(${n}))`;return(0,nt._)`${v} && ${v} !== true && ${g} === ${e} && !${O}`}}function d(){let m=p.formats[s];if(!m){b();return}if(m===!0)return;let[h,g,v]=x(m);h===e&&t.pass($());function b(){if(c.strictSchema===!1){p.logger.warn(O());return}throw new Error(O());function O(){return`unknown format "${s}" ignored in schema at path "${l}"`}}function x(O){let ce=O instanceof RegExp?(0,nt.regexpCode)(O):c.code.formats?(0,nt._)`${c.code.formats}${(0,nt.getProperty)(s)}`:void 0,X=r.scopeValue("formats",{key:s,ref:O,code:ce});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,nt._)`${X}.validate`]:["string",O,X]}function $(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,nt._)`await ${v}(${n})`}return typeof g=="function"?(0,nt._)`${v}(${n})`:(0,nt._)`${v}.test(${n})`}}}};cv.default=hH});var _T=I(lv=>{"use strict";Object.defineProperty(lv,"__esModule",{value:!0});var gH=vT(),yH=[gH.default];lv.default=yH});var bT=I(Ws=>{"use strict";Object.defineProperty(Ws,"__esModule",{value:!0});Ws.contentVocabulary=Ws.metadataVocabulary=void 0;Ws.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ws.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var xT=I(uv=>{"use strict";Object.defineProperty(uv,"__esModule",{value:!0});var vH=RE(),_H=FE(),bH=yT(),wH=_T(),wT=bT(),xH=[vH.default,_H.default,(0,bH.default)(),wH.default,wT.metadataVocabulary,wT.contentVocabulary];uv.default=xH});var $T=I(ju=>{"use strict";Object.defineProperty(ju,"__esModule",{value:!0});ju.DiscrError=void 0;var ST;(function(t){t.Tag="tag",t.Mapping="mapping"})(ST||(ju.DiscrError=ST={}))});var ET=I(dv=>{"use strict";Object.defineProperty(dv,"__esModule",{value:!0});var Js=de(),pv=$T(),kT=yu(),SH=ka(),$H=Pe(),kH={message:({params:{discrError:t,tagName:e}})=>t===pv.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Js._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},EH={keyword:"discriminator",type:"object",schemaType:"object",error:kH,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),l=e.const("tag",(0,Js._)`${r}${(0,Js.getProperty)(a)}`);e.if((0,Js._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:pv.DiscrError.Tag,tag:l,tagName:a})),t.ok(c);function u(){let d=f();e.if(!1);for(let m in d)e.elseIf((0,Js._)`${l} === ${m}`),e.assign(c,p(d[m]));e.else(),t.error(!1,{discrError:pv.DiscrError.Mapping,tag:l,tagName:a}),e.endIf()}function p(d){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:d},m);return t.mergeEvaluated(h,Js.Name),m}function f(){var d;let m={},h=v(o),g=!0;for(let $=0;$<i.length;$++){let O=i[$];if(O?.$ref&&!(0,$H.schemaHasRulesButRef)(O,s.self.RULES)){let X=O.$ref;if(O=kT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,X),O instanceof kT.SchemaEnv&&(O=O.schema),O===void 0)throw new SH.default(s.opts.uriResolver,s.baseId,X)}let ce=(d=O?.properties)===null||d===void 0?void 0:d[a];if(typeof ce!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||v(O)),b(ce,$)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function v({required:$}){return Array.isArray($)&&$.includes(a)}function b($,O){if($.const)x($.const,O);else if($.enum)for(let ce of $.enum)x(ce,O);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x($,O){if(typeof $!="string"||$ in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[$]=O}}}};dv.default=EH});var TT=I((jQ,TH)=>{TH.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var mv=I((He,fv)=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.MissingRefError=He.ValidationError=He.CodeGen=He.Name=He.nil=He.stringify=He.str=He._=He.KeywordCxt=He.Ajv=void 0;var PH=SE(),RH=xT(),OH=ET(),PT=TT(),CH=["/properties"],Mu="http://json-schema.org/draft-07/schema",Ks=class extends PH.default{_addVocabularies(){super._addVocabularies(),RH.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(OH.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(PT,CH):PT;this.addMetaSchema(e,Mu,!1),this.refs["http://json-schema.org/schema"]=Mu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mu)?Mu:void 0)}};He.Ajv=Ks;fv.exports=He=Ks;fv.exports.Ajv=Ks;Object.defineProperty(He,"__esModule",{value:!0});He.default=Ks;var IH=$a();Object.defineProperty(He,"KeywordCxt",{enumerable:!0,get:function(){return IH.KeywordCxt}});var Ys=de();Object.defineProperty(He,"_",{enumerable:!0,get:function(){return Ys._}});Object.defineProperty(He,"str",{enumerable:!0,get:function(){return Ys.str}});Object.defineProperty(He,"stringify",{enumerable:!0,get:function(){return Ys.stringify}});Object.defineProperty(He,"nil",{enumerable:!0,get:function(){return Ys.nil}});Object.defineProperty(He,"Name",{enumerable:!0,get:function(){return Ys.Name}});Object.defineProperty(He,"CodeGen",{enumerable:!0,get:function(){return Ys.CodeGen}});var AH=hu();Object.defineProperty(He,"ValidationError",{enumerable:!0,get:function(){return AH.default}});var NH=ka();Object.defineProperty(He,"MissingRefError",{enumerable:!0,get:function(){return NH.default}})});var jT=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.formatNames=Gr.fastFormats=Gr.fullFormats=void 0;function Br(t,e){return{validate:t,compare:e}}Gr.fullFormats={date:Br(IT,vv),time:Br(gv(!0),_v),"date-time":Br(RT(!0),NT),"iso-time":Br(gv(),AT),"iso-date-time":Br(RT(),zT),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:qH,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:VH,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:ZH,int32:{type:"number",validate:HH},int64:{type:"number",validate:BH},float:{type:"number",validate:CT},double:{type:"number",validate:CT},password:!0,binary:!0};Gr.fastFormats={...Gr.fullFormats,date:Br(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,vv),time:Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,_v),"date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,NT),"iso-time":Br(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,AT),"iso-date-time":Br(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,zT),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i};Gr.formatNames=Object.keys(Gr.fullFormats);function zH(t){return t%4===0&&(t%100!==0||t%400===0)}var jH=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,MH=[0,31,28,31,30,31,30,31,31,30,31,30,31];function IT(t){let e=jH.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&zH(r)?29:MH[n])}function vv(t,e){if(t&&e)return t>e?1:t<e?-1:0}var hv=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function gv(t){return function(r){let n=hv.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let p=s-u*c,f=o-l*c-(p<0?1:0);return(f===23||f===-1)&&(p===59||p===-1)&&i<61}}function _v(t,e){if(!(t&&e))return;let r=new Date("2020-01-01T"+t).valueOf(),n=new Date("2020-01-01T"+e).valueOf();if(r&&n)return r-n}function AT(t,e){if(!(t&&e))return;let r=hv.exec(t),n=hv.exec(e);if(r&&n)return t=r[1]+r[2]+r[3],e=n[1]+n[2]+n[3],t>e?1:t<e?-1:0}var yv=/t|\s/i;function RT(t){let e=gv(t);return function(n){let o=n.split(yv);return o.length===2&&IT(o[0])&&e(o[1])}}function NT(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function zT(t,e){if(!(t&&e))return;let[r,n]=t.split(yv),[o,s]=e.split(yv),i=vv(r,o);if(i!==void 0)return i||_v(n,s)}var LH=/\/|:/,DH=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function qH(t){return LH.test(t)&&DH.test(t)}var OT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function ZH(t){return OT.lastIndex=0,OT.test(t)}var UH=-(2**31),FH=2**31-1;function HH(t){return Number.isInteger(t)&&t<=FH&&t>=UH}function BH(t){return Number.isInteger(t)}function CT(){return!0}var GH=/[^\\]\\Z/;function VH(t){if(GH.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var MT=I(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.formatLimitDefinition=void 0;var WH=mv(),Or=de(),Fn=Or.operators,Lu={formatMaximum:{okStr:"<=",ok:Fn.LTE,fail:Fn.GT},formatMinimum:{okStr:">=",ok:Fn.GTE,fail:Fn.LT},formatExclusiveMaximum:{okStr:"<",ok:Fn.LT,fail:Fn.GTE},formatExclusiveMinimum:{okStr:">",ok:Fn.GT,fail:Fn.LTE}},JH={message:({keyword:t,schemaCode:e})=>(0,Or.str)`should be ${Lu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Or._)`{comparison: ${Lu[t].okStr}, limit: ${e}}`};Xs.formatLimitDefinition={keyword:Object.keys(Lu),type:"string",schemaType:"string",$data:!0,error:JH,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new WH.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?l():u();function l(){let f=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),d=e.const("fmt",(0,Or._)`${f}[${c.schemaCode}]`);t.fail$data((0,Or.or)((0,Or._)`typeof ${d} != "object"`,(0,Or._)`${d} instanceof RegExp`,(0,Or._)`typeof ${d}.compare != "function"`,p(d)))}function u(){let f=c.schema,d=a.formats[f];if(!d||d===!0)return;if(typeof d!="object"||d instanceof RegExp||typeof d.compare!="function")throw new Error(`"${o}": format "${f}" does not define "compare" function`);let m=e.scopeValue("formats",{key:f,ref:d,code:i.code.formats?(0,Or._)`${i.code.formats}${(0,Or.getProperty)(f)}`:void 0});t.fail$data(p(m))}function p(f){return(0,Or._)`${f}.compare(${r}, ${n}) ${Lu[o].fail} 0`}},dependencies:["format"]};var KH=t=>(t.addKeyword(Xs.formatLimitDefinition),t);Xs.default=KH});var ZT=I((Da,qT)=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});var Qs=jT(),YH=MT(),bv=de(),LT=new bv.Name("fullFormats"),XH=new bv.Name("fastFormats"),wv=(t,e={keywords:!0})=>{if(Array.isArray(e))return DT(t,e,Qs.fullFormats,LT),t;let[r,n]=e.mode==="fast"?[Qs.fastFormats,XH]:[Qs.fullFormats,LT],o=e.formats||Qs.formatNames;return DT(t,o,r,n),e.keywords&&(0,YH.default)(t),t};wv.get=(t,e="full")=>{let n=(e==="fast"?Qs.fastFormats:Qs.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function DT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,bv._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}qT.exports=Da=wv;Object.defineProperty(Da,"__esModule",{value:!0});Da.default=wv});function QH(){let t=new UT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,FT.default)(t),t}var UT,FT,Du,HT=w(()=>{UT=oo(mv(),1),FT=oo(ZT(),1);Du=class{constructor(e){this._ajv=e??QH()}getValidator(e){let r="$id"in e&&typeof e.$id=="string"?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return n=>r(n)?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(r.errors)}}}});var qu,BT=w(()=>{qu=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}async getTask(e,r){return this._server.getTask({taskId:e},r)}async getTaskResult(e,r,n){return this._server.getTaskResult({taskId:e},r,n)}async listTasks(e,r){return this._server.listTasks(e?{cursor:e}:void 0,r)}async cancelTask(e,r){return this._server.cancelTask({taskId:e},r)}}});function GT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"tools/call":if(!t.tools?.call)throw new Error(`${r} does not support task creation for tools/call (required for ${e})`);break;default:break}}function VT(t,e,r){if(!t)throw new Error(`${r} does not support task creation (required for ${e})`);switch(e){case"sampling/createMessage":if(!t.sampling?.createMessage)throw new Error(`${r} does not support task creation for sampling/createMessage (required for ${e})`);break;case"elicitation/create":if(!t.elicitation?.create)throw new Error(`${r} does not support task creation for elicitation/create (required for ${e})`);break;default:break}}var WT=w(()=>{});var Zu,JT=w(()=>{rk();ks();HT();la();BT();WT();Zu=class extends ru{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ta.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Du,this.setRequestHandler(ul,n=>this._oninitialize(n)),this.setNotificationHandler(xh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Rh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ta.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new qu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=tk(this._capabilities,e)}setRequestHandler(e,r){let o=An(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(ur(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,l)=>{let u=In($s,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new D(B.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,f=await Promise.resolve(r(c,l));if(p.task){let m=In(xs,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new D(B.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let d=In(kl,f);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new D(B.InvalidParams,`Invalid tools/call result: ${m}`)}return d.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){VT(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&GT(this._capabilities.tasks?.requests,e,"Server")}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Gi.includes(r)?r:yh,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},cl)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(l=>l.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(l=>l.type==="tool_use");if(s){if(o.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let l=new Set(a.filter(p=>p.type==="tool_use").map(p=>p.id)),u=new Set(o.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==u.size||![...l].every(p=>u.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},Ch,r):this.request({method:"sampling/createMessage",params:e},Oh,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},El,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},El,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new D(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof D?i:new D(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Ih,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))return this.notification({method:"notifications/message",params:e})}async sendResourceUpdated(e){return this.notification({method:"notifications/resources/updated",params:e})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}}});function xv(t){return!!t&&typeof t=="object"&&YT in t}function XT(t){return t[YT]?.complete}var YT,KT,QT=w(()=>{YT=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(KT||(KT={}))});var eP=w(()=>{});function t9(t){let e=[];if(t.length===0)return{isValid:!1,warnings:["Tool name cannot be empty"]};if(t.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${t.length})`]};if(t.includes(" ")&&e.push("Tool name contains spaces, which may cause parsing issues"),t.includes(",")&&e.push("Tool name contains commas, which may cause parsing issues"),(t.startsWith("-")||t.endsWith("-"))&&e.push("Tool name starts or ends with a dash, which may cause parsing issues in some contexts"),(t.startsWith(".")||t.endsWith("."))&&e.push("Tool name starts or ends with a dot, which may cause parsing issues in some contexts"),!e9.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function r9(t,e){if(e.length>0){console.warn(`Tool name validation warning for "${t}":`);for(let r of e)console.warn(` - ${r}`);console.warn("Tool registration will proceed, but this may cause compatibility issues."),console.warn("Consider updating the tool name to conform to the MCP tool naming standard."),console.warn("See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.")}}function Sv(t){let e=t9(t);return r9(t,e.warnings),e.isValid}var e9,tP=w(()=>{e9=/^[A-Za-z0-9._-]{1,128}$/});var Uu,rP=w(()=>{Uu=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var Fu=w(()=>{Ul();Ul()});function sP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function o9(t){return"_def"in t||"_zod"in t||sP(t)}function $v(t){return typeof t!="object"||t===null||o9(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(sP)}function nP(t){if(t)return $v(t)?Mo(t):t}function s9(t){let e=An(t);return e?Object.entries(e).map(([r,n])=>{let o=y$(n),s=v$(n);return{name:r,description:o,required:!s}}):[]}function Hn(t){let r=An(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Bl(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function oP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Hu,n9,qa,iP=w(()=>{JT();la();Rg();ks();QT();eP();tP();rP();Fu();Hu=class{constructor(e,r){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new Zu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Uu(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn($l)),this.server.assertCanSetRequestHandler(Hn($s)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler($l,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Ms(r.inputSchema);return o?Eg(o,{strictUnions:!0,pipeStrategy:"input"}):n9})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Ms(r.outputSchema);o&&(n.outputSchema=Eg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler($s,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new D(B.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new D(B.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new D(B.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new D(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof D&&n.code===B.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Ms(e.inputSchema)??e.inputSchema,i=await Fl(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Hl(a);throw new D(B.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new D(B.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Ms(e.outputSchema),s=await Fl(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Hl(i);throw new D(B.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let p=await n.taskStore.getTask(c);if(!p)throw new D(B.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Hn(Tl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Tl,async e=>{switch(e.params.ref.type){case"ref/prompt":return IS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return AS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new D(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new D(B.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new D(B.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return qa;let s=An(n.argsSchema)?.[e.params.argument.name];if(!xv(s))return qa;let i=XT(s);if(!i)return qa;let a=await i(e.params.argument.value,e.params.context);return oP(a)}async handleResourceCompletion(e,r){let n=Object.values(this._registeredResourceTemplates).find(i=>i.resourceTemplate.uriTemplate.toString()===r.uri);if(!n){if(this._registeredResources[r.uri])return qa;throw new D(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return qa;let s=await o(e.params.argument.value,e.params.context);return oP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(_l)),this.server.assertCanSetRequestHandler(Hn(bl)),this.server.assertCanSetRequestHandler(Hn(wl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(_l,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(bl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(wl,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new D(B.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new D(B.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(xl)),this.server.assertCanSetRequestHandler(Hn(Sl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(xl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?s9(r.argsSchema):void 0}))})),this.server.setRequestHandler(Sl,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new D(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new D(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Ms(n.argsSchema),s=await Fl(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Hl(c);throw new D(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Mo(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Mo(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let l=c instanceof Ft?c._def?.innerType:c;return xv(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Sv(e);let u={title:r,description:n,inputSchema:nP(o),outputSchema:nP(s),annotations:i,execution:a,_meta:c,handler:l,enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:p=>{typeof p.name<"u"&&p.name!==e&&(typeof p.name=="string"&&Sv(p.name),delete this._registeredTools[e],p.name&&(this._registeredTools[p.name]=u)),typeof p.title<"u"&&(u.title=p.title),typeof p.description<"u"&&(u.description=p.description),typeof p.paramsSchema<"u"&&(u.inputSchema=Mo(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Mo(p.outputSchema)),typeof p.callback<"u"&&(u.handler=p.callback),typeof p.annotations<"u"&&(u.annotations=p.annotations),typeof p._meta<"u"&&(u._meta=p._meta),typeof p.enabled<"u"&&(u.enabled=p.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];$v(c)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!$v(r[0])&&(i=r.shift())):typeof c=="object"&&c!==null&&(i=r.shift())}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:l}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},l,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},n9={type:"object",properties:{}};qa={completion:{values:[],hasMore:!1}}});function ei(){return`${Date.now()}-${++i9}`}function gr(t,e){let r=0,n=0,o=-1,s=-1;for(;n<e.length;)if(r<t.length&&(t[r]==="?"||t[r]===e[n]))r++,n++;else if(r<t.length&&t[r]==="*")o=r++,s=n;else if(o>=0)r=o+1,n=++s;else return!1;for(;r<t.length&&t[r]==="*";)r++;return r===t.length}function Ze(t,e){if(!e)return!1;let r=new Date(t).getTime();return Date.now()>r+e}var i9,Vr=w(()=>{i9=0});var Bu,aP=w(()=>{Vr();Bu=class{entries=new Map;async get(e){let r=this.entries.get(e);return r?Ze(r.setAt,r.ttlMs)?(this.entries.delete(e),null):r:null}async set(e,r,n,o,s){let i=new Date().toISOString(),a=this.entries.get(e),c={key:e,value:r,category:o,setBy:n,setAt:a?.setAt??i,updatedAt:i,ttlMs:s};return this.entries.set(e,c),c}async delete(e){return this.entries.delete(e)}async query(e,r){let n=[];for(let o of this.entries.values()){if(Ze(o.setAt,o.ttlMs)){this.entries.delete(o.key);continue}e&&!gr(e,o.key)||r&&o.category!==r||n.push(o)}return n}async getAll(){let e=[];for(let r of this.entries.values())Ze(r.setAt,r.ttlMs)||e.push(r);return e}async load(e){this.entries.clear();for(let r of e)Ze(r.setAt,r.ttlMs)||this.entries.set(r.key,r)}}});var Gu,cP=w(()=>{Vr();Gu=class{claims=new Map;eventStore;constructor(e){this.eventStore=e}async claim(e,r,n,o){let s=this.claims.get(e);if(s&&s.status==="active"&&!Ze(s.claimedAt,s.ttlMs))return s.owner!==n?{status:"rejected",claim:s}:(s.value=r,s.ttlMs=o,{status:"approved",claim:s});let i={resource:e,value:r,owner:n,status:"active",claimedAt:new Date().toISOString(),ttlMs:o};return this.claims.set(e,i),await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),{status:"approved",claim:i}}async release(e,r){let n=this.claims.get(e);return!n||n.status!=="active"||n.owner!==r?null:(n.status="released",await this.eventStore.publish("claim.released",{resource:e,owner:r},r),n)}async check(e){let r=this.claims.get(e);return r?(r.status==="active"&&Ze(r.claimedAt,r.ttlMs)&&(r.status="expired"),r):null}async list(e){let r=[];for(let n of this.claims.values())n.status==="active"&&Ze(n.claimedAt,n.ttlMs)&&(n.status="expired"),n.status==="active"&&(e&&!gr(e,n.resource)||r.push(n));return r}async getAll(){return[...this.claims.values()]}async load(e){this.claims.clear();for(let r of e)this.claims.set(r.resource,r)}}});var Vu,lP=w(()=>{Vu=class{events=[];cursor=0;async publish(e,r,n){let o={id:++this.cursor,type:e,data:r,publishedBy:n,publishedAt:new Date().toISOString()};return this.events.push(o),this.events.length>1e4&&(this.events=this.events.slice(-1e4)),o}async getEvents(e,r){let n=this.events;return e!==void 0&&(n=n.filter(o=>o.id>e)),r&&(n=n.filter(o=>o.type===r)),{events:n,cursor:this.cursor}}async getCursor(){return this.cursor}async getAll(){return[...this.events]}async load(e,r){this.events=e,this.cursor=r}}});var Wu,uP=w(()=>{Vr();Wu=class{discoveries=[];eventStore;constructor(e){this.eventStore=e}async publish(e,r,n,o){let s={id:ei(),topic:e,content:r,category:o,publishedBy:n,publishedAt:new Date().toISOString()};return this.discoveries.push(s),await this.eventStore.publish("discovery.published",{id:s.id,topic:e,category:o},n),s}async search(e,r){let n=this.discoveries;if(r&&(n=n.filter(o=>o.category===r)),e){let o=e.toLowerCase();n=n.filter(s=>s.topic.toLowerCase().includes(o)||s.content.toLowerCase().includes(o))}return n}async getAll(){return[...this.discoveries]}async load(e){this.discoveries=e}}});import{randomBytes as a9}from"node:crypto";var Bn,Ju=w(()=>{Bn=class{messages=[];async send(e,r,n,o){let s={id:a9(8).toString("hex"),from:e,to:r,content:n,replyTo:o,sentAt:new Date().toISOString()};return this.messages.push(s),s}async getFor(e,r){return this.messages.filter(n=>!(n.to!==e||r&&n.sentAt<=r))}async getAll(){return[...this.messages]}}});import{randomBytes as c9}from"node:crypto";var Gn,Ku=w(()=>{Gn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:c9(8).toString("hex"),from:e,problem:r,needs_capability:n,urgency:o??"normal",status:"open",createdAt:new Date().toISOString()};return this.requests.set(s.id,s),await this.eventStore.publish("help.requested",{request_id:s.id,from:e,problem:r,needs_capability:n,urgency:s.urgency},e),s}async claim(e,r){let n=this.requests.get(e);return!n||n.status!=="open"?null:(n.status="claimed",n.claimedBy=r,await this.eventStore.publish("help.claimed",{request_id:e,claimed_by:r},r),n)}async resolve(e,r){let n=this.requests.get(e);return!n||n.status!=="claimed"?null:(n.status="resolved",await this.eventStore.publish("help.resolved",{request_id:e,resolved_by:r},r),n)}async list(e){let r=[...this.requests.values()];return e?r.filter(n=>n.status===e):r}}});var Vn,Yu=w(()=>{Vn=class{reports=new Map;async report(e,r,n,o){let s={claim:e,agent:r,progress:Math.max(0,Math.min(1,n)),note:o,updatedAt:new Date().toISOString()};return this.reports.set(e,s),s}async get(e){return this.reports.get(e)??null}async list(){return[...this.reports.values()]}}});import{randomBytes as l9}from"node:crypto";var Wn,Xu=w(()=>{Wn=class{conflicts=new Map;eventStore;constructor(e){this.eventStore=e}async flag(e,r,n,o){let s={id:l9(8).toString("hex"),flaggedBy:e,discovery_a:r,discovery_b:n,reason:o,status:"open",createdAt:new Date().toISOString()};return this.conflicts.set(s.id,s),await this.eventStore.publish("conflict.flagged",{conflict_id:s.id,flagged_by:e,discovery_a:r,discovery_b:n},e),s}async resolve(e,r,n){let o=this.conflicts.get(e);return!o||o.status!=="open"?null:(o.status="resolved",o.resolvedBy=r,o.resolution=n,await this.eventStore.publish("conflict.resolved",{conflict_id:e,resolved_by:r,resolution:n},r),o)}async list(e){let r=[...this.conflicts.values()];return e?r.filter(n=>n.status===e):r}}});var Jn,Qu=w(()=>{Jn=class{assignments=new Map;async assign(e,r){let n={agent:e,role:r,assignedAt:new Date().toISOString()};return this.assignments.set(e,n),n}async getAssignments(){return[...this.assignments.values()]}async getByAgent(e){return this.assignments.get(e)??null}async remove(e){return this.assignments.delete(e)}}});import{randomBytes as u9}from"node:crypto";var Kn,ep=w(()=>{Kn=class{proposals=new Map;eventStore;constructor(e){this.eventStore=e}async propose(e,r,n,o){let s={id:u9(8).toString("hex"),proposedBy:e,action:r,detail:n,requires_quorum:o??2,endorsements:[e],status:"open",createdAt:new Date().toISOString()};return this.proposals.set(s.id,s),await this.eventStore.publish("governance.proposal.created",{proposal_id:s.id,action:r,proposedBy:e,requires_quorum:s.requires_quorum},e),s}async endorse(e,r){let n=this.proposals.get(e);return!n||n.status!=="open"?null:(n.endorsements.includes(r)||n.endorsements.push(r),n.endorsements.length>=n.requires_quorum&&(n.status="approved",await this.eventStore.publish("governance.proposal.approved",{proposal_id:e,action:n.action,endorsements:n.endorsements},r)),n)}async list(e){let r=[...this.proposals.values()];return e?r.filter(n=>n.status===e):r}async get(e){return this.proposals.get(e)??null}}});import{randomBytes as p9}from"node:crypto";var Yn,tp=w(()=>{Yn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:p9(8).toString("hex"),requestedBy:e,role:r,count:Math.max(1,n),reason:o,status:"pending",createdAt:new Date().toISOString()};return this.requests.set(s.id,s),s}async approve(e){let r=this.requests.get(e);return!r||r.status!=="pending"?null:(r.status="approved",await this.eventStore.publish("reinforcement.approved",{request_id:e,role:r.role,count:r.count},"server"),r)}async deny(e,r){let n=this.requests.get(e);return!n||n.status!=="pending"?null:(n.status="denied",n.denialReason=r,await this.eventStore.publish("reinforcement.denied",{request_id:e,role:n.role,reason:r},"server"),n)}async list(){return[...this.requests.values()]}}});var Xn,rp=w(()=>{Xn=class{protocolHalt=null;agentHalts=new Map;protocolPause=null;agentPauses=new Map;events;constructor(e){this.events=e}async halt(e,r,n="completed",o){let s={halted:!0,reason:e,status:n,haltedBy:r,haltedAt:new Date().toISOString()};return o?(this.agentHalts.set(o,s),await this.events.publish("agent.halted",{agent:o,reason:e,status:n,halted_by:r},r)):(this.protocolHalt=s,await this.events.publish("protocol.halt",{reason:e,status:n,halted_by:r},r)),s}async pause(e,r,n){let o={paused:!0,reason:e,pausedBy:r,pausedAt:new Date().toISOString()};return n?(this.agentPauses.set(n,o),await this.events.publish("agent.paused",{agent:n,reason:e,paused_by:r},r)):(this.protocolPause=o,await this.events.publish("protocol.paused",{reason:e,paused_by:r},r)),o}async resume(e,r,n){return n?this.agentPauses.has(n)?(this.agentPauses.delete(n),await this.events.publish("agent.resumed",{agent:n,reason:r,resumed_by:e},e),!0):!1:this.protocolPause?(this.protocolPause=null,await this.events.publish("protocol.resumed",{reason:r,resumed_by:e},e),!0):!1}getStatus(e){if(this.protocolHalt)return{halted:!0,paused:!1,haltReason:this.protocolHalt.reason,haltStatus:this.protocolHalt.status};if(e&&this.agentHalts.has(e)){let r=this.agentHalts.get(e);return{halted:!0,paused:!1,haltReason:r.reason,haltStatus:r.status}}return this.protocolPause?{halted:!1,paused:!0,pauseReason:this.protocolPause.reason}:e&&this.agentPauses.has(e)?{halted:!1,paused:!0,pauseReason:this.agentPauses.get(e).reason}:{halted:!1,paused:!1}}}});var Qn,np=w(()=>{Qn=class{runs=new Map;async start(e,r){let n={agentId:e,role:r,status:"running",startedAt:new Date().toISOString()};return this.runs.set(e,n),n}async complete(e,r){let n=this.runs.get(e);return n?(Object.assign(n,r,{completedAt:new Date().toISOString()}),(!n.status||n.status==="running")&&(n.status="completed"),n):null}async get(e){return this.runs.get(e)??null}async list(e){let r=[...this.runs.values()];return e?r.filter(n=>n.status===e):r}async summary(){let e=0,r=0,n=0,o=0;for(let s of this.runs.values())(s.status==="completed"||s.status==="halted")&&e++,s.status==="error"&&r++,s.usage&&(n+=s.usage.totalTokens),s.elapsed&&(o+=s.elapsed);return{agents:this.runs.size,completed:e,errors:r,totalTokens:n,totalDuration:o}}}});function pP(){let t=new Vu,e=new Bu,r=new Gu(t),n=new Wu(t),o=new Bn,s=new Gn(t),i=new Vn,a=new Wn(t),c=new Jn,l=new Kn(t),u=new Yn(t),p=new Xn(t),f=new Qn;return{events:t,state:e,claims:r,discoveries:n,messages:o,help:s,progress:i,conflicts:a,roles:c,proposals:l,reinforcements:u,control:p,runs:f}}function kv(t,e={}){let r=e.agentId??"agent_default",n=e.namespace&&e.namespace!=="default"?`@${e.namespace}`:"",o=new Hu({name:"incubator",version:"1.0.0"});function s(){return r}function i(){e.onSave&&e.onSave()}function a(c,l,u){if(e.verbose){let p=new Date().toISOString().slice(11,23);console.error(` ${p} [${l}${n}] ${c} ${u}`)}}return o.registerTool("incubator_getState",{description:"Read a shared state value by key. Check state before making decisions to avoid conflicts with other agents.",inputSchema:{key:M.string().describe("The state key to read")}},async c=>{let l=await t.state.get(c.key);return a("getState",s(),`key=${c.key} ${l?"HIT":"MISS"}`),l?{content:[{type:"text",text:JSON.stringify({found:!0,entry:l})}]}:{content:[{type:"text",text:JSON.stringify({found:!1,key:c.key})}]}}),o.registerTool("incubator_setState",{description:"Write a shared state value. Last-writer-wins. Use this to share decisions, progress, or context with other agents. Use claims for mutual exclusion instead.",inputSchema:{key:M.string().describe("The state key to write"),value:M.unknown().describe("The value to store (any JSON-serializable value)"),category:M.string().optional().describe('Optional category for grouping (e.g. "config", "progress")'),ttlMs:M.number().optional().describe("Optional time-to-live in milliseconds")}},async c=>{let l=await t.state.set(c.key,c.value,s(),c.category,c.ttlMs);return a("setState",s(),`key=${c.key} val=${JSON.stringify(c.value).slice(0,60)}`),i(),{content:[{type:"text",text:JSON.stringify({success:!0,entry:l})}]}}),o.registerTool("incubator_queryState",{description:"Search shared state by glob pattern and/or category. Use to discover what other agents have shared.",inputSchema:{pattern:M.string().optional().describe('Glob pattern to match keys (e.g. "agent_*", "config.*")'),category:M.string().optional().describe("Filter by category")}},async c=>{let l=await t.state.query(c.pattern,c.category);return{content:[{type:"text",text:JSON.stringify({count:l.length,entries:l})}]}}),o.registerTool("incubator_deleteState",{description:"Remove a shared state value.",inputSchema:{key:M.string().describe("The state key to delete")}},async c=>{let l=await t.state.delete(c.key);return i(),{content:[{type:"text",text:JSON.stringify({deleted:l})}]}}),o.registerTool("incubator_claim",{description:"Claim exclusive access to a resource (file, variable, function, etc). First-come-first-served. If rejected, the response includes who owns it so you can coordinate. Always claim before modifying shared resources.",inputSchema:{resource:M.string().describe("Resource identifier (e.g. file path, variable name, function name)"),value:M.string().describe("What you plan to do with the resource"),ttlMs:M.number().optional().describe("Optional auto-expire in milliseconds (default: no expiry)")}},async c=>{let l=await t.claims.claim(c.resource,c.value,s(),c.ttlMs);return a("claim",s(),`resource=${c.resource} \u2192 ${l.status}${l.status==="rejected"?` (owner: ${l.claim.owner})`:""}`),i(),{content:[{type:"text",text:JSON.stringify(l)}]}}),o.registerTool("incubator_releaseClaim",{description:"Release a claim when done with a resource. Always release claims promptly.",inputSchema:{resource:M.string().describe("The resource to release")}},async c=>{let l=await t.claims.release(c.resource,s());return a("releaseClaim",s(),`resource=${c.resource} ${l?"OK":"NOT_OWNER"}`),i(),l?{content:[{type:"text",text:JSON.stringify({released:!0,claim:l})}]}:{content:[{type:"text",text:JSON.stringify({released:!1,reason:"No active claim found or not owner"})}]}}),o.registerTool("incubator_checkClaim",{description:"Check who owns a resource without claiming it. Use to check before attempting a claim.",inputSchema:{resource:M.string().describe("The resource to check")}},async c=>{let l=await t.claims.check(c.resource);return l?{content:[{type:"text",text:JSON.stringify({claimed:l.status==="active",claim:l})}]}:{content:[{type:"text",text:JSON.stringify({claimed:!1,resource:c.resource})}]}}),o.registerTool("incubator_listClaims",{description:"List all active claims, optionally filtered by glob pattern. Use to see what resources are locked.",inputSchema:{pattern:M.string().optional().describe('Glob pattern to filter resources (e.g. "src/*.ts", "var_*")')}},async c=>{let l=await t.claims.list(c.pattern);return{content:[{type:"text",text:JSON.stringify({count:l.length,claims:l})}]}}),o.registerTool("incubator_publishEvent",{description:"Broadcast an event to all agents. Use for: conflicts detected, work completed, blockers found, warnings. Other agents poll for events with getEvents.",inputSchema:{type:M.string().describe('Event type (e.g. "conflict", "completed", "blocker", "warning")'),data:M.unknown().describe("Event payload (any JSON-serializable data)")}},async c=>{let l=await t.events.publish(c.type,c.data,s());return a("publishEvent",s(),`type=${c.type}`),i(),{content:[{type:"text",text:JSON.stringify({published:!0,event:l})}]}}),o.registerTool("incubator_getEvents",{description:"Poll for events since your last cursor. Call periodically to stay aware of other agents' activity. Save the returned cursor for next call.",inputSchema:{since:M.number().optional().describe("Cursor from previous call (omit for all events)"),type:M.string().optional().describe("Filter by event type")}},async c=>{let l=await t.events.getEvents(c.since,c.type);return{content:[{type:"text",text:JSON.stringify(l)}]}}),o.registerTool("incubator_publishDiscovery",{description:"Share a finding that other agents should know about. Use for: naming conventions found, patterns discovered, gotchas encountered, decisions made.",inputSchema:{topic:M.string().describe("Short topic/title for the discovery"),content:M.string().describe("Detailed content of the discovery"),category:M.string().optional().describe('Optional category (e.g. "naming", "pattern", "warning")')}},async c=>{let l=await t.discoveries.publish(c.topic,c.content,s(),c.category);return a("publishDiscovery",s(),`"${c.topic}" ${c.category?`[${c.category}]`:""}`),i(),{content:[{type:"text",text:JSON.stringify({published:!0,discovery:l})}]}}),o.registerTool("incubator_searchDiscoveries",{description:"Search discoveries shared by all agents. Text search across topics and content. Check before making decisions that might conflict.",inputSchema:{query:M.string().optional().describe("Text search query (searches topic and content)"),category:M.string().optional().describe("Filter by category")}},async c=>{let l=await t.discoveries.search(c.query,c.category);return a("searchDiscoveries",s(),`query=${c.query??"*"} \u2192 ${l.length} results`),{content:[{type:"text",text:JSON.stringify({count:l.length,discoveries:l})}]}}),o.registerTool("incubator_getProtocol",{description:"Get the coordination protocol for your role. Returns current phase, steps to follow, resource naming conventions, and natural language instructions. Call this on startup and again when you observe a phase change event.",inputSchema:{role:M.string().optional().describe("Your role name (if not specified, uses the first role in the spec)")}},async c=>{let l=e.getProtocol?.();if(!l)return{content:[{type:"text",text:JSON.stringify({error:"No protocol loaded for this namespace"})}]};let u=Object.keys(l.roles),p=c.role??u[0],f=l.roles[p];if(!f)return{content:[{type:"text",text:JSON.stringify({error:`Unknown role "${p}". Available roles: ${u.join(", ")}`})}]};let d=await t.state.get("phase"),m=Object.keys(l.phases),h=d?.value??m[0];if(!l.phases[h])return{content:[{type:"text",text:JSON.stringify({error:`Unknown phase "${h}". Available phases: ${m.join(", ")}`})}]};let g=await Rd(l,t,s()),v=Ec(l,p,h),b=Cd(l,p,h,g),x={};for(let[ce,X]of Object.entries(l.phases))x[ce]={description:X.description,...X.terminal?{terminal:!0}:{}};let $=await t.roles.getAssignments(),O={protocol:{name:l.name,title:l.title,acp:l.acp},role:{name:p,description:f.description},current_phase:h,rules:v.steps??[],loop:v.loop??!1,resources:l.resources??{},variables:g,instructions:b,phases:x,...l.errors?{errors:l.errors}:{},...l.governance?{governance:l.governance}:{},...$.length>0?{team:$}:{}};return a("getProtocol",s(),`role=${p} phase=${h}`),{content:[{type:"text",text:JSON.stringify(O)}]}}),o.registerTool("incubator_requestHalt",{description:"Halt the entire protocol or a specific agent. Protocol-wide halt ends the run. Per-agent halt fires that agent (claims auto-released, role removed).",inputSchema:{reason:M.string().describe("Why the halt is being requested"),status:M.enum(["completed","failed"]).optional().describe("Whether this is a successful completion or failure (default: completed)"),target:M.string().optional().describe("Agent ID to halt (omit for protocol-wide halt)")}},async c=>{let l=s(),u=c.status??"completed";if(c.target){let f=await t.claims.list();for(let d of f)d.owner===c.target&&d.status==="active"&&await t.claims.release(d.resource,c.target);await t.roles.remove(c.target)}let p=await t.control.halt(c.reason,l,u,c.target);return a("requestHalt",l,`target=${c.target??"protocol"} status=${u}`),i(),{content:[{type:"text",text:JSON.stringify({halted:!0,info:p})}]}}),o.registerTool("incubator_requestPause",{description:"Pause the entire protocol or a specific agent. Paused agents stop iterating until resumed.",inputSchema:{reason:M.string().describe("Why the pause is being requested"),target:M.string().optional().describe("Agent ID to pause (omit for protocol-wide pause)")}},async c=>{let l=s(),u=await t.control.pause(c.reason,l,c.target);return a("requestPause",l,`target=${c.target??"protocol"}`),i(),{content:[{type:"text",text:JSON.stringify({paused:!0,info:u})}]}}),o.registerTool("incubator_resumeAgent",{description:"Resume a paused agent or the entire protocol.",inputSchema:{reason:M.string().describe("Why the agent/protocol is being resumed"),target:M.string().optional().describe("Agent ID to resume (omit for protocol-wide resume)")}},async c=>{let l=s(),u=await t.control.resume(l,c.reason,c.target);return a("resumeAgent",l,`target=${c.target??"protocol"} \u2192 ${u}`),i(),{content:[{type:"text",text:JSON.stringify({resumed:u})}]}}),o.registerTool("incubator_getTopics",{description:"List published and subscribed cross-namespace topics for this namespace. Topics enable event routing between separate protocol namespaces.",inputSchema:{}},async()=>{let c=e.getTopicRouter?.(),l=e.namespace??"default";if(!c)return{content:[{type:"text",text:JSON.stringify({error:"Topic routing not enabled"})}]};let u=c.getTopics(l);return a("getTopics",s(),`pub=${u.publishes.length} sub=${u.subscribes.length}`),{content:[{type:"text",text:JSON.stringify(u)}]}}),o.registerTool("incubator_subscribeTopic",{description:"Subscribe this namespace to a cross-namespace topic at runtime. Events published to this topic in other namespaces will appear in your event stream.",inputSchema:{topic:M.string().describe("The topic (event type) to subscribe to")}},async c=>{let l=e.getTopicRouter?.(),u=e.namespace??"default";return l?(l.subscribe(u,c.topic),a("subscribeTopic",s(),`topic=${c.topic}`),{content:[{type:"text",text:JSON.stringify({subscribed:!0,topic:c.topic})}]}):{content:[{type:"text",text:JSON.stringify({error:"Topic routing not enabled"})}]}}),o.registerTool("incubator_publishTopic",{description:"Declare this namespace as publishing a cross-namespace topic at runtime. Events matching this topic will be routed to subscribing namespaces.",inputSchema:{topic:M.string().describe("The topic (event type) to publish")}},async c=>{let l=e.getTopicRouter?.(),u=e.namespace??"default";return l?(l.publish(u,c.topic),a("publishTopic",s(),`topic=${c.topic}`),{content:[{type:"text",text:JSON.stringify({published:!0,topic:c.topic})}]}):{content:[{type:"text",text:JSON.stringify({error:"Topic routing not enabled"})}]}}),o}var Ev=w(()=>{iP();Fu();aP();cP();lP();uP();Ju();Ku();Yu();Xu();Qu();ep();tp();rp();np();$i()});import{createRequire as d9}from"node:module";function dP(t){let r=d9(import.meta.url)("@honeybee-ai/carapace");return t&&console.error("[incubator] carapace loaded"),r}function ti(t,e,r){let n=e.filter(Boolean).join(" ");if(!n)return;let o=t.scan(n);if(r&&o.findings.length>0){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] score=${o.score} action=${o.action} findings=${o.findings.length}`)}if(o.action==="BLOCK")throw new Za(o);if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}}function Wo(t,e,r){let n=e.filter(Boolean).join(" ");if(!n)return!0;let o=t.scan(n);if(o.action==="BLOCK"){if(r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] READ BLOCKED: score=${o.score} \u2014 poisoned entry filtered out`)}return!1}return!0}function Jo(t){return typeof t=="string"?t:t==null?"":JSON.stringify(t)}function fP(t,e,r){return{state:{...t.state,set:async(n,o,s,i,a)=>(ti(e,[n,Jo(o),i],r),t.state.set(n,o,s,i,a)),get:async n=>{let o=await t.state.get(n);return!o||!Wo(e,[o.key,Jo(o.value),o.category],r)?null:o},query:async(n,o)=>(await t.state.query(n,o)).filter(i=>Wo(e,[i.key,Jo(i.value),i.category],r))},events:{...t.events,publish:async(n,o,s)=>(ti(e,[n,Jo(o)],r),t.events.publish(n,o,s)),getEvents:async(n,o)=>{let s=await t.events.getEvents(n,o);return{events:s.events.filter(i=>Wo(e,[i.type,Jo(i.data)],r)),cursor:s.cursor}}},claims:{...t.claims,claim:async(n,o,s,i)=>(ti(e,[n,o],r),t.claims.claim(n,o,s,i)),check:async n=>{let o=await t.claims.check(n);return!o||!Wo(e,[o.resource,o.value],r)?null:o},list:async n=>(await t.claims.list(n)).filter(s=>Wo(e,[s.resource,s.value],r))},discoveries:{...t.discoveries,publish:async(n,o,s,i)=>(ti(e,[n,o,i],r),t.discoveries.publish(n,o,s,i)),search:async(n,o)=>(await t.discoveries.search(n,o)).filter(i=>Wo(e,[i.topic,i.content,i.category],r))},messages:{...t.messages,send:async(n,o,s,i)=>(ti(e,[s],r),t.messages.send(n,o,s,i))},help:{...t.help,request:async(n,o,s,i)=>(ti(e,[o,s],r),t.help.request(n,o,s,i))},progress:t.progress,conflicts:t.conflicts,roles:t.roles,proposals:t.proposals,reinforcements:t.reinforcements,control:t.control,runs:t.runs}}function mP(t,e,r){let n=0,o=(s,i)=>s.filter(a=>Wo(e,i(a),r)?!0:(n++,!1));return t.state=o(t.state,s=>[s.key,Jo(s.value),s.category]),t.claims=o(t.claims,s=>[s.resource,s.value]),t.events=o(t.events,s=>[s.type,Jo(s.data)]),t.discoveries=o(t.discoveries,s=>[s.topic,s.content,s.category]),n>0&&console.error(`[incubator] Carapace: ${n} poisoned entries removed from snapshot`),{blocked:n}}var Za,op=w(()=>{Za=class extends Error{score;action;findings;constructor(e){super(`[carapace] Blocked: ${e.summary}`),this.name="CarapaceBlockedError",this.score=e.score,this.action=e.action,this.findings=e.findings}}});function f9(t){let e=t.headers.origin||"";if(/^https?:\/\/localhost(:\d+)?$/.test(e)||/^https:\/\/[a-z0-9-]+\.honeyb\.dev$/.test(e))return e;let r=process.env.INCUBATOR_CORS_ORIGINS;if(r)for(let n of r.split(",")){let o=n.trim();if(o&&e===o)return e;if(o.startsWith("*.")){let s=o.slice(1);if(new RegExp(`^https://[a-z0-9-]+${s.replace(/\./g,"\\.")}(:\\d+)?$`).test(e))return e}}return""}function R(t,e,r,n){let o=n?f9(n):"http://localhost:5173",s={"Content-Type":"application/json","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, X-Agent-Id, X-Namespace"};o&&(s["Access-Control-Allow-Origin"]=o),t.writeHead(e,s),t.end(JSON.stringify(r))}function Ke(t,e){let r=e.agentId??t.headers["x-agent-id"]??"rest_anonymous";return r.startsWith("honeycomb:")?"rest_anonymous":r}async function h9(t){return t.method==="GET"?{}:new Promise((e,r)=>{let n="",o=0;t.on("data",s=>{if(o+=s.length,o>m9){t.destroy(),r(new Error("Payload too large"));return}n+=s.toString()}),t.on("end",()=>{if(!n){e({});return}try{e(JSON.parse(n))}catch{e({})}})})}function v9(t){let e=t.slice(5),r=e.indexOf("/"),n=r===-1?e:e.slice(0,r);if(n==="_ns")return{namespace:null,rewrittenPath:t};if(g9.has(n))return{namespace:"default",rewrittenPath:t};let o=r===-1?"":e.slice(r);return{namespace:n,rewrittenPath:`/api${o}`}}async function hP(t,e,r,n){let o=t.url??"/";if(!o.startsWith("/api/"))return!1;if(t.method==="OPTIONS")return R(e,204,""),!0;let s=await h9(t),i=new URL(o,"http://localhost").pathname;if(i==="/api/_ns"&&t.method==="GET"){let d=[];for(let m of r.list()){let h=r.get(m),g=await h.state.query(),v=await h.claims.list(),b=await h.events.getEvents(),x=await h.discoveries.search();d.push({name:m,state:g.length,claims:v.length,events:b.cursor,discoveries:x.length})}return R(e,200,{namespaces:d}),!0}let a=i.match(/^\/api\/_ns\/(.+)$/);if(a&&t.method==="DELETE"){let d=decodeURIComponent(a[1]),m=r.delete(d);return R(e,200,{deleted:m}),!0}let{namespace:c,rewrittenPath:l}=v9(i);if(c===null)return R(e,404,{error:`No route: ${t.method} ${i}`}),!0;let u;try{u=r.get(c)}catch(d){return R(e,400,{error:d.message}),!0}if(l==="/api/protocol"){if(t.method==="GET"){let d=r.getProtocol(c);if(!d)R(e,200,{loaded:!1});else{let m=await u.roles.getAssignments();R(e,200,{loaded:!0,spec:d,...m.length>0?{team:m}:{}})}return!0}if(t.method==="PUT"){try{let d;if(typeof s.spec=="string")d=await lo(s.spec);else if(s.acp&&s.name)d=await lo(JSON.stringify(s));else return R(e,400,{error:'Missing "spec" field (YAML/JSON string) or direct spec object'}),!0;let m=[],h=d;if(h.roles&&typeof h.roles=="object")for(let g of Object.values(h.roles))g?.description&&m.push(String(g.description)),g?.instructions&&m.push(String(g.instructions));if(h.phases&&typeof h.phases=="object")for(let g of Object.values(h.phases))g?.description&&m.push(String(g.description));if(m.length>0){let g=`__spec_scan_${Date.now()}`;await u.state.set(g,m.join(" "),Ke(t,s),"__scan"),await u.state.delete(g)}r.setProtocol(c,d),R(e,200,{loaded:!0,name:d.name,title:d.title})}catch(d){d instanceof co?R(e,400,{error:"Invalid spec",details:d.errors}):R(e,400,{error:d.message})}return!0}}let p=l.match(/^\/api\/topics(?:\/(.+))?$/);if(p){let d=r.getRouter();if(!d)return R(e,501,{error:"Honeycomb topic routing not enabled (no notification bus)"}),!0;let m=p[1];if(t.method==="GET"&&!m){let v=d.getTopics(c);return R(e,200,v),!0}if(t.method==="POST"&&m==="subscribe"){let v=s.topic;return v?(d.subscribe(c,v),R(e,200,{subscribed:!0,topic:v}),!0):(R(e,400,{error:"Missing required field: topic"}),!0)}if(t.method==="POST"&&m==="publish"){let v=s.topic;return v?(d.publish(c,v),R(e,200,{published:!0,topic:v}),!0):(R(e,400,{error:"Missing required field: topic"}),!0)}let h=m?.match(/^subscribe\/(.+)$/);if(t.method==="DELETE"&&h){let v=decodeURIComponent(h[1]);return d.unsubscribe(c,v),R(e,200,{unsubscribed:!0,topic:v}),!0}let g=m?.match(/^publish\/(.+)$/);if(t.method==="DELETE"&&g){let v=decodeURIComponent(g[1]);return d.unpublish(c,v),R(e,200,{unpublished:!0,topic:v}),!0}return R(e,404,{error:`No route: ${t.method} ${i}`}),!0}if(l.match(/^\/api\/dance\/(.+)$/)&&t.method==="POST")return R(e,501,{error:"Dance tool calls via REST not yet implemented (use WebSocket)"},t),!0;for(let d of y9){if(t.method!==d.method)continue;let m=l.match(d.pattern);if(m){if(n){let h=new Date().toISOString().slice(11,23),g=Ke(t,s),v=c==="default"?"":`@${c}`;console.error(` ${h} [${g}${v}] REST ${t.method} ${i}`)}try{await d.handler(t,e,u,m,s)}catch(h){if(h instanceof Za)R(e,403,{error:"prompt_injection_detected",message:h.message,score:h.score,action:h.action,findings:h.findings});else throw h}return!0}}return R(e,404,{error:`No route: ${t.method} ${i}`}),!0}var m9,g9,y9,gP=w(()=>{op();$i();m9=1024*1024;g9=new Set(["state","claims","events","discoveries","health","protocol","messages","help","progress","conflicts","roles","reinforcements","governance","control","topics","runs"]),y9=[{method:"GET",pattern:/^\/api\/health$/,handler:async(t,e,r)=>{let n=await r.claims.list(),o=await r.events.getEvents(),s=await r.state.query();R(e,200,{status:"ok",uptime:process.uptime(),agents:new Set([...s.map(i=>i.setBy),...n.map(i=>i.owner),...o.events.map(i=>i.publishedBy)]).size,claims:n.length,events:o.cursor})}},{method:"GET",pattern:/^\/api\/state$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=n.searchParams.get("pattern")??void 0,s=n.searchParams.get("category")??void 0,i=await r.state.query(o,s);R(e,200,{count:i.length,entries:i})}},{method:"GET",pattern:/^\/api\/state\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.state.get(o);if(!s){R(e,200,{found:!1,key:o});return}R(e,200,{found:!0,entry:s})}},{method:"PUT",pattern:/^\/api\/state\/(.+)$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]);if(!("value"in o)){R(e,400,{error:"Missing required field: value"});return}let i=Ke(t,o),a=await r.state.set(s,o.value,i,o.category,o.ttlMs);R(e,200,{success:!0,entry:a})}},{method:"DELETE",pattern:/^\/api\/state\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.state.delete(o);R(e,200,{deleted:s})}},{method:"POST",pattern:/^\/api\/claims$/,handler:async(t,e,r,n,o)=>{let s=o.resource,i=o.value;if(!s||!i){R(e,400,{error:"Missing required fields: resource, value"});return}let a=Ke(t,o),c=await r.claims.claim(s,i,a,o.ttlMs);R(e,200,c)}},{method:"DELETE",pattern:/^\/api\/claims\/(.+)$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.claims.release(s,i);if(!a){R(e,200,{released:!1,reason:"No active claim found or not owner"});return}R(e,200,{released:!0,claim:a})}},{method:"GET",pattern:/^\/api\/claims\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.claims.check(o);if(!s){R(e,200,{claimed:!1,resource:o});return}R(e,200,{claimed:s.status==="active",claim:s})}},{method:"GET",pattern:/^\/api\/claims$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("pattern")??void 0,s=await r.claims.list(o);R(e,200,{count:s.length,claims:s})}},{method:"POST",pattern:/^\/api\/events$/,handler:async(t,e,r,n,o)=>{let s=o.type;if(!s){R(e,400,{error:"Missing required field: type"});return}let i=Ke(t,o),a=await r.events.publish(s,o.data??null,i);R(e,200,{published:!0,event:a})}},{method:"GET",pattern:/^\/api\/events$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=n.searchParams.get("since"),s=n.searchParams.get("type")??void 0,i=await r.events.getEvents(o?parseInt(o,10):void 0,s);R(e,200,i)}},{method:"POST",pattern:/^\/api\/discoveries$/,handler:async(t,e,r,n,o)=>{let s=o.topic,i=o.content;if(!s||!i){R(e,400,{error:"Missing required fields: topic, content"});return}let a=Ke(t,o),c=await r.discoveries.publish(s,i,a,o.category);R(e,200,{published:!0,discovery:c})}},{method:"GET",pattern:/^\/api\/discoveries$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=n.searchParams.get("query")??void 0,s=n.searchParams.get("category")??void 0,i=await r.discoveries.search(o,s);R(e,200,{count:i.length,discoveries:i})}},{method:"POST",pattern:/^\/api\/messages$/,handler:async(t,e,r,n,o)=>{let s=o.to,i=o.content;if(!s||!i){R(e,400,{error:"Missing required fields: to, content"});return}let a=Ke(t,o),c=await r.messages.send(a,s,i,o.replyTo);R(e,200,{sent:!0,message:c})}},{method:"GET",pattern:/^\/api\/messages$/,handler:async(t,e,r)=>{let n=new URL(t.url,"http://localhost"),o=t.headers["x-agent-id"]??"rest_anonymous",s=n.searchParams.get("since")??void 0,i=await r.messages.getFor(o,s);R(e,200,{count:i.length,messages:i})}},{method:"POST",pattern:/^\/api\/roles\/request$/,handler:async(t,e,r,n,o)=>{let s=o.role;if(!s){R(e,400,{error:"Missing required field: role"});return}let i=Ke(t,o),c=(await r.roles.getByAgent(i))?.role;await r.roles.assign(i,s),await r.events.publish("role.transition",{agent:i,from:c??null,to:s,reason:o.reason??null},i),R(e,200,{approved:!0,from:c??null,to:s})}},{method:"GET",pattern:/^\/api\/roles$/,handler:async(t,e,r)=>{let n=await r.roles.getAssignments();R(e,200,{count:n.length,assignments:n})}},{method:"POST",pattern:/^\/api\/help$/,handler:async(t,e,r,n,o)=>{let s=o.problem;if(!s){R(e,400,{error:"Missing required field: problem"});return}let i=Ke(t,o),a=await r.help.request(i,s,o.needs_capability,o.urgency);R(e,200,{created:!0,request:a})}},{method:"POST",pattern:/^\/api\/help\/([^/]+)\/claim$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.help.claim(s,i);if(!a){R(e,200,{claimed:!1,reason:"Request not found or not open"});return}R(e,200,{claimed:!0,request:a})}},{method:"POST",pattern:/^\/api\/help\/([^/]+)\/resolve$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.help.resolve(s,i);if(!a){R(e,200,{resolved:!1,reason:"Request not found or not claimed"});return}R(e,200,{resolved:!0,request:a})}},{method:"GET",pattern:/^\/api\/help$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.help.list(o);R(e,200,{count:s.length,requests:s})}},{method:"POST",pattern:/^\/api\/progress$/,handler:async(t,e,r,n,o)=>{let s=o.claim,i=o.progress;if(!s||i===void 0){R(e,400,{error:"Missing required fields: claim, progress"});return}let a=Ke(t,o),c=await r.progress.report(s,a,i,o.note);R(e,200,{reported:!0,report:c})}},{method:"GET",pattern:/^\/api\/progress\/(.+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.progress.get(o);if(!s){R(e,200,{found:!1,claim:o});return}R(e,200,{found:!0,report:s})}},{method:"GET",pattern:/^\/api\/progress$/,handler:async(t,e,r)=>{let n=await r.progress.list();R(e,200,{count:n.length,reports:n})}},{method:"POST",pattern:/^\/api\/conflicts$/,handler:async(t,e,r,n,o)=>{let s=o.discovery_a,i=o.discovery_b,a=o.reason;if(!s||!i||!a){R(e,400,{error:"Missing required fields: discovery_a, discovery_b, reason"});return}let c=Ke(t,o),l=await r.conflicts.flag(c,s,i,a);R(e,200,{flagged:!0,conflict:l})}},{method:"POST",pattern:/^\/api\/conflicts\/([^/]+)\/resolve$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=o.resolution;if(!i){R(e,400,{error:"Missing required field: resolution"});return}let a=Ke(t,o),c=await r.conflicts.resolve(s,a,i);if(!c){R(e,200,{resolved:!1,reason:"Conflict not found or not open"});return}R(e,200,{resolved:!0,conflict:c})}},{method:"GET",pattern:/^\/api\/conflicts$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.conflicts.list(o);R(e,200,{count:s.length,conflicts:s})}},{method:"POST",pattern:/^\/api\/reinforcements$/,handler:async(t,e,r,n,o)=>{let s=o.role;if(!s){R(e,400,{error:"Missing required field: role"});return}let i=Ke(t,o),a=o.count??1,c=await r.reinforcements.request(i,s,a,o.reason);R(e,200,{requested:!0,request:c})}},{method:"GET",pattern:/^\/api\/reinforcements$/,handler:async(t,e,r)=>{let n=await r.reinforcements.list();R(e,200,{count:n.length,requests:n})}},{method:"POST",pattern:/^\/api\/governance\/approve$/,handler:async(t,e,r,n,o)=>{let s=o.action;if(!s){R(e,400,{error:"Missing required field: action"});return}let i=Ke(t,o);await r.events.publish("governance.approval_requested",{action:s,detail:o.detail,files:o.files,requested_by:i},i),R(e,200,{requested:!0,action:s})}},{method:"POST",pattern:/^\/api\/governance\/escalate$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o);await r.events.publish("governance.escalated",{reason:s,context:o.context,escalated_by:i},i),R(e,200,{escalated:!0,reason:s})}},{method:"POST",pattern:/^\/api\/governance\/propose$/,handler:async(t,e,r,n,o)=>{let s=o.action;if(!s){R(e,400,{error:"Missing required field: action"});return}let i=Ke(t,o),a=await r.proposals.propose(i,s,o.detail,o.requires_quorum);R(e,200,{proposed:!0,proposal:a})}},{method:"POST",pattern:/^\/api\/governance\/endorse\/([^/]+)$/,handler:async(t,e,r,n,o)=>{let s=decodeURIComponent(n[1]),i=Ke(t,o),a=await r.proposals.endorse(s,i);if(!a){R(e,200,{endorsed:!1,reason:"Proposal not found or not open"});return}R(e,200,{endorsed:!0,proposal:a})}},{method:"GET",pattern:/^\/api\/governance\/proposals$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.proposals.list(o);R(e,200,{count:s.length,proposals:s})}},{method:"POST",pattern:/^\/api\/governance\/rollback$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o);await r.events.publish("governance.rollback.requested",{reason:s,scope:o.scope,requested_by:i},i),R(e,200,{requested:!0,reason:s})}},{method:"POST",pattern:/^\/api\/control\/halt$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o),a=o.status??"completed",c=o.target;if(c){let u=await r.claims.list();for(let p of u)p.owner===c&&p.status==="active"&&await r.claims.release(p.resource,c);await r.roles.remove(c)}let l=await r.control.halt(s,i,a,c);R(e,200,{halted:!0,info:l})}},{method:"POST",pattern:/^\/api\/control\/pause$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o),a=o.target,c=await r.control.pause(s,i,a);R(e,200,{paused:!0,info:c})}},{method:"POST",pattern:/^\/api\/control\/resume$/,handler:async(t,e,r,n,o)=>{let s=o.reason;if(!s){R(e,400,{error:"Missing required field: reason"});return}let i=Ke(t,o),a=o.target,c=await r.control.resume(i,s,a);R(e,200,{resumed:c})}},{method:"GET",pattern:/^\/api\/control\/status$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("agentId")??t.headers["x-agent-id"]??void 0,s=r.control.getStatus(o);R(e,200,s)}},{method:"GET",pattern:/^\/api\/runs\/summary$/,handler:async(t,e,r)=>{let n=await r.runs.summary();R(e,200,n)}},{method:"GET",pattern:/^\/api\/runs\/([^/]+)$/,handler:async(t,e,r,n)=>{let o=decodeURIComponent(n[1]),s=await r.runs.get(o);if(!s){R(e,200,{found:!1,agentId:o});return}R(e,200,{found:!0,run:s})}},{method:"GET",pattern:/^\/api\/runs$/,handler:async(t,e,r)=>{let o=new URL(t.url,"http://localhost").searchParams.get("status")??void 0,s=await r.runs.list(o);R(e,200,{count:s.length,runs:s})}}]});import{createRequire as _9}from"node:module";import{resolve as b9}from"node:path";function vP(t){let e=t===":memory:"?t:b9(t),r=yP.get(e);if(r)return r;let o=_9(import.meta.url)("better-sqlite3"),s=new o(e);return s.pragma("journal_mode = WAL"),w9(s),e!==":memory:"&&yP.set(e,s),s}function w9(t){t.exec(`
296
296
  CREATE TABLE IF NOT EXISTS state (
297
297
  namespace TEXT NOT NULL,
298
298
  key TEXT NOT NULL,
@@ -346,7 +346,7 @@ data:
346
346
  CREATE INDEX IF NOT EXISTS idx_events_ns_type ON events (namespace, type);
347
347
  CREATE INDEX IF NOT EXISTS idx_claims_ns_status ON claims (namespace, status);
348
348
  CREATE INDEX IF NOT EXISTS idx_discoveries_ns_cat ON discoveries (namespace, category);
349
- `)}var cP,uP=w(()=>{cP=new Map});var tp,pP=w(()=>{Gr();tp=class{db;ns;constructor(e,r){this.db=e,this.ns=r}async get(e){let r=this.db.prepare("SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ? AND key = ?").get(this.ns,e);if(!r)return null;let n=this.rowToEntry(r);return qe(n.setAt,n.ttlMs)?(this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,e),null):n}async set(e,r,n,o,s){let i=new Date().toISOString(),c=(await this.get(e))?.setAt??i;return this.db.prepare(`
349
+ `)}var yP,_P=w(()=>{yP=new Map});var sp,bP=w(()=>{Vr();sp=class{db;ns;constructor(e,r){this.db=e,this.ns=r}async get(e){let r=this.db.prepare("SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ? AND key = ?").get(this.ns,e);if(!r)return null;let n=this.rowToEntry(r);return Ze(n.setAt,n.ttlMs)?(this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,e),null):n}async set(e,r,n,o,s){let i=new Date().toISOString(),c=(await this.get(e))?.setAt??i;return this.db.prepare(`
350
350
  INSERT INTO state (namespace, key, value, category, set_by, set_at, updated_at, ttl_ms)
351
351
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
352
352
  ON CONFLICT(namespace, key) DO UPDATE SET
@@ -355,7 +355,7 @@ data:
355
355
  set_by = excluded.set_by,
356
356
  updated_at = excluded.updated_at,
357
357
  ttl_ms = excluded.ttl_ms
358
- `).run(this.ns,e,JSON.stringify(r),o??null,n,c,i,s??null),{key:e,value:r,category:o,setBy:n,setAt:c,updatedAt:i,ttlMs:s}}async delete(e){return this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,e).changes>0}async query(e,r){let n="SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ?",o=[this.ns];r&&(n+=" AND category = ?",o.push(r));let s=this.db.prepare(n).all(...o),i=[];for(let a of s){let c=this.rowToEntry(a);if(qe(c.setAt,c.ttlMs)){this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,c.key);continue}e&&!hr(e,c.key)||i.push(c)}return i}async getAll(){return this.db.prepare("SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ?").all(this.ns).map(r=>this.rowToEntry(r)).filter(r=>!qe(r.setAt,r.ttlMs))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM state WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO state (namespace, key, value, category, set_by, set_at, updated_at, ttl_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");for(let o of e)qe(o.setAt,o.ttlMs)||n.run(this.ns,o.key,JSON.stringify(o.value),o.category??null,o.setBy,o.setAt,o.updatedAt,o.ttlMs??null)})()}rowToEntry(e){return{key:e.key,value:JSON.parse(e.value),category:e.category??void 0,setBy:e.set_by,setAt:e.set_at,updatedAt:e.updated_at,ttlMs:e.ttl_ms??void 0}}}});var rp,dP=w(()=>{rp=class{db;ns;constructor(e,r){this.db=e,this.ns=r,this.db.prepare("INSERT OR IGNORE INTO event_cursors (namespace, cursor) VALUES (?, 0)").run(this.ns)}async publish(e,r,n){let o=new Date().toISOString(),s;return this.db.transaction(()=>{this.db.prepare("UPDATE event_cursors SET cursor = cursor + 1 WHERE namespace = ?").run(this.ns);let c=this.db.prepare("SELECT cursor FROM event_cursors WHERE namespace = ?").get(this.ns).cursor;this.db.prepare("INSERT INTO events (namespace, id, type, data, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?)").run(this.ns,c,e,JSON.stringify(r),n,o),s={id:c,type:e,data:r,publishedBy:n,publishedAt:o}})(),s}async getEvents(e,r){let n="SELECT id, type, data, published_by, published_at FROM events WHERE namespace = ?",o=[this.ns];e!==void 0&&(n+=" AND id > ?",o.push(e)),r&&(n+=" AND type = ?",o.push(r)),n+=" ORDER BY id";let i=this.db.prepare(n).all(...o).map(l=>({id:l.id,type:l.type,data:JSON.parse(l.data),publishedBy:l.published_by,publishedAt:l.published_at})),c=this.db.prepare("SELECT cursor FROM event_cursors WHERE namespace = ?").get(this.ns)?.cursor??0;return{events:i,cursor:c}}async getCursor(){return this.db.prepare("SELECT cursor FROM event_cursors WHERE namespace = ?").get(this.ns)?.cursor??0}async getAll(){return this.db.prepare("SELECT id, type, data, published_by, published_at FROM events WHERE namespace = ? ORDER BY id").all(this.ns).map(r=>({id:r.id,type:r.type,data:JSON.parse(r.data),publishedBy:r.published_by,publishedAt:r.published_at}))}async load(e,r){this.db.transaction(()=>{this.db.prepare("DELETE FROM events WHERE namespace = ?").run(this.ns);let o=this.db.prepare("INSERT INTO events (namespace, id, type, data, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?)");for(let s of e)o.run(this.ns,s.id,s.type,JSON.stringify(s.data),s.publishedBy,s.publishedAt);this.db.prepare("INSERT INTO event_cursors (namespace, cursor) VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET cursor = excluded.cursor").run(this.ns,r)})()}}});var np,fP=w(()=>{Gr();np=class{db;ns;eventStore;constructor(e,r,n){this.db=e,this.ns=r,this.eventStore=n}async claim(e,r,n,o){let s,i=!1;return this.db.transaction(()=>{let c=this.getClaimRow(e);if(c&&c.status==="active"&&!qe(c.claimed_at,c.ttl_ms??void 0)){if(c.owner!==n){s={status:"rejected",claim:this.rowToClaim(c)};return}this.db.prepare("UPDATE claims SET value = ?, ttl_ms = ? WHERE namespace = ? AND resource = ?").run(r,o??null,this.ns,e),s={status:"approved",claim:{...this.rowToClaim(c),value:r,ttlMs:o}};return}let l=new Date().toISOString();this.db.prepare(`
358
+ `).run(this.ns,e,JSON.stringify(r),o??null,n,c,i,s??null),{key:e,value:r,category:o,setBy:n,setAt:c,updatedAt:i,ttlMs:s}}async delete(e){return this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,e).changes>0}async query(e,r){let n="SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ?",o=[this.ns];r&&(n+=" AND category = ?",o.push(r));let s=this.db.prepare(n).all(...o),i=[];for(let a of s){let c=this.rowToEntry(a);if(Ze(c.setAt,c.ttlMs)){this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,c.key);continue}e&&!gr(e,c.key)||i.push(c)}return i}async getAll(){return this.db.prepare("SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ?").all(this.ns).map(r=>this.rowToEntry(r)).filter(r=>!Ze(r.setAt,r.ttlMs))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM state WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO state (namespace, key, value, category, set_by, set_at, updated_at, ttl_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");for(let o of e)Ze(o.setAt,o.ttlMs)||n.run(this.ns,o.key,JSON.stringify(o.value),o.category??null,o.setBy,o.setAt,o.updatedAt,o.ttlMs??null)})()}rowToEntry(e){return{key:e.key,value:JSON.parse(e.value),category:e.category??void 0,setBy:e.set_by,setAt:e.set_at,updatedAt:e.updated_at,ttlMs:e.ttl_ms??void 0}}}});var ip,wP=w(()=>{ip=class{db;ns;constructor(e,r){this.db=e,this.ns=r,this.db.prepare("INSERT OR IGNORE INTO event_cursors (namespace, cursor) VALUES (?, 0)").run(this.ns)}async publish(e,r,n){let o=new Date().toISOString(),s;return this.db.transaction(()=>{this.db.prepare("UPDATE event_cursors SET cursor = cursor + 1 WHERE namespace = ?").run(this.ns);let c=this.db.prepare("SELECT cursor FROM event_cursors WHERE namespace = ?").get(this.ns).cursor;this.db.prepare("INSERT INTO events (namespace, id, type, data, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?)").run(this.ns,c,e,JSON.stringify(r),n,o),s={id:c,type:e,data:r,publishedBy:n,publishedAt:o}})(),s}async getEvents(e,r){let n="SELECT id, type, data, published_by, published_at FROM events WHERE namespace = ?",o=[this.ns];e!==void 0&&(n+=" AND id > ?",o.push(e)),r&&(n+=" AND type = ?",o.push(r)),n+=" ORDER BY id";let i=this.db.prepare(n).all(...o).map(l=>({id:l.id,type:l.type,data:JSON.parse(l.data),publishedBy:l.published_by,publishedAt:l.published_at})),c=this.db.prepare("SELECT cursor FROM event_cursors WHERE namespace = ?").get(this.ns)?.cursor??0;return{events:i,cursor:c}}async getCursor(){return this.db.prepare("SELECT cursor FROM event_cursors WHERE namespace = ?").get(this.ns)?.cursor??0}async getAll(){return this.db.prepare("SELECT id, type, data, published_by, published_at FROM events WHERE namespace = ? ORDER BY id").all(this.ns).map(r=>({id:r.id,type:r.type,data:JSON.parse(r.data),publishedBy:r.published_by,publishedAt:r.published_at}))}async load(e,r){this.db.transaction(()=>{this.db.prepare("DELETE FROM events WHERE namespace = ?").run(this.ns);let o=this.db.prepare("INSERT INTO events (namespace, id, type, data, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?)");for(let s of e)o.run(this.ns,s.id,s.type,JSON.stringify(s.data),s.publishedBy,s.publishedAt);this.db.prepare("INSERT INTO event_cursors (namespace, cursor) VALUES (?, ?) ON CONFLICT(namespace) DO UPDATE SET cursor = excluded.cursor").run(this.ns,r)})()}}});var ap,xP=w(()=>{Vr();ap=class{db;ns;eventStore;constructor(e,r,n){this.db=e,this.ns=r,this.eventStore=n}async claim(e,r,n,o){let s,i=!1;return this.db.transaction(()=>{let c=this.getClaimRow(e);if(c&&c.status==="active"&&!Ze(c.claimed_at,c.ttl_ms??void 0)){if(c.owner!==n){s={status:"rejected",claim:this.rowToClaim(c)};return}this.db.prepare("UPDATE claims SET value = ?, ttl_ms = ? WHERE namespace = ? AND resource = ?").run(r,o??null,this.ns,e),s={status:"approved",claim:{...this.rowToClaim(c),value:r,ttlMs:o}};return}let l=new Date().toISOString();this.db.prepare(`
359
359
  INSERT INTO claims (namespace, resource, value, owner, status, claimed_at, ttl_ms)
360
360
  VALUES (?, ?, ?, ?, 'active', ?, ?)
361
361
  ON CONFLICT(namespace, resource) DO UPDATE SET
@@ -364,7 +364,7 @@ data:
364
364
  status = excluded.status,
365
365
  claimed_at = excluded.claimed_at,
366
366
  ttl_ms = excluded.ttl_ms
367
- `).run(this.ns,e,r,n,l,o??null);let u={resource:e,value:r,owner:n,status:"active",claimedAt:l,ttlMs:o};i=!0,s={status:"approved",claim:u}})(),i&&await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),s}async release(e,r){let n=this.getClaimRow(e);return!n||n.status!=="active"||n.owner!==r?null:(this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("released",this.ns,e),await this.eventStore.publish("claim.released",{resource:e,owner:r},r),{...this.rowToClaim(n),status:"released"})}async check(e){let r=this.getClaimRow(e);return r?r.status==="active"&&qe(r.claimed_at,r.ttl_ms??void 0)?(this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("expired",this.ns,e),{...this.rowToClaim(r),status:"expired"}):this.rowToClaim(r):null}async list(e){let r=this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ? AND status = ?").all(this.ns,"active"),n=[];for(let o of r){if(qe(o.claimed_at,o.ttl_ms??void 0)){this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("expired",this.ns,o.resource);continue}e&&!hr(e,o.resource)||n.push(this.rowToClaim(o))}return n}async getAll(){return this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ?").all(this.ns).map(r=>this.rowToClaim(r))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM claims WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO claims (namespace, resource, value, owner, status, claimed_at, ttl_ms) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let o of e)n.run(this.ns,o.resource,o.value,o.owner,o.status,o.claimedAt,o.ttlMs??null)})()}getClaimRow(e){return this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ? AND resource = ?").get(this.ns,e)}rowToClaim(e){return{resource:e.resource,value:e.value,owner:e.owner,status:e.status,claimedAt:e.claimed_at,ttlMs:e.ttl_ms??void 0}}}});var op,mP=w(()=>{Gr();op=class{db;ns;eventStore;constructor(e,r,n){this.db=e,this.ns=r,this.eventStore=n}async publish(e,r,n,o){let s=Xs(),i=new Date().toISOString();return this.db.prepare("INSERT INTO discoveries (namespace, id, topic, content, category, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(this.ns,s,e,r,o??null,n,i),await this.eventStore.publish("discovery.published",{id:s,topic:e,category:o},n),{id:s,topic:e,content:r,category:o,publishedBy:n,publishedAt:i}}async search(e,r){let n="SELECT id, topic, content, category, published_by, published_at FROM discoveries WHERE namespace = ?",o=[this.ns];r&&(n+=" AND category = ?",o.push(r));let i=this.db.prepare(n).all(...o).map(a=>this.rowToDiscovery(a));if(e){let a=e.toLowerCase();i=i.filter(c=>c.topic.toLowerCase().includes(a)||c.content.toLowerCase().includes(a))}return i}async getAll(){return this.db.prepare("SELECT id, topic, content, category, published_by, published_at FROM discoveries WHERE namespace = ?").all(this.ns).map(r=>this.rowToDiscovery(r))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM discoveries WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO discoveries (namespace, id, topic, content, category, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let o of e)n.run(this.ns,o.id,o.topic,o.content,o.category??null,o.publishedBy,o.publishedAt)})()}rowToDiscovery(e){return{id:e.id,topic:e.topic,content:e.content,category:e.category??void 0,publishedBy:e.published_by,publishedAt:e.published_at}}}});function hP(t,e){let r=lP(t),n=new rp(r,e),o=new tp(r,e),s=new np(r,e,n),i=new op(r,e,n),a=new Bn,c=new Vn(n),l=new Gn,u=new Wn(n),p=new Jn,m=new Kn(n),d=new Yn(n),f=new Xn(n),h=new Qn;return{state:o,events:n,claims:s,discoveries:i,messages:a,help:c,progress:l,conflicts:u,roles:p,proposals:m,reinforcements:d,control:f,runs:h}}var gP=w(()=>{uP();pP();dP();fP();mP();Bu();Vu();Gu();Wu();Ju();Ku();Yu();Xu();Qu()});var sp,yP=w(()=>{Gr();sp=class{client;hashKey;constructor(e,r){this.client=e,this.hashKey=`incubator:${r}:state`}async get(e){let r=await this.client.hget(this.hashKey,e);if(!r)return null;let n=JSON.parse(r);return qe(n.setAt,n.ttlMs)?(await this.client.hdel(this.hashKey,e),null):n}async set(e,r,n,o,s){let i=new Date().toISOString(),c=(await this.get(e))?.setAt??i,l={key:e,value:r,category:o,setBy:n,setAt:c,updatedAt:i,ttlMs:s};return await this.client.hset(this.hashKey,e,JSON.stringify(l)),l}async delete(e){return await this.client.hdel(this.hashKey,e)>0}async query(e,r){let n=await this.client.hgetall(this.hashKey),o=[];for(let[,s]of Object.entries(n)){let i=JSON.parse(s);if(qe(i.setAt,i.ttlMs)){await this.client.hdel(this.hashKey,i.key);continue}e&&!hr(e,i.key)||r&&i.category!==r||o.push(i)}return o}async getAll(){let e=await this.client.hgetall(this.hashKey),r=[];for(let[,n]of Object.entries(e)){let o=JSON.parse(n);qe(o.setAt,o.ttlMs)||r.push(o)}return r}async load(e){if(await this.client.del(this.hashKey),e.length===0)return;let r={};for(let n of e)qe(n.setAt,n.ttlMs)||(r[n.key]=JSON.stringify(n));Object.keys(r).length>0&&await this.client.hset(this.hashKey,r)}}});var ip,vP=w(()=>{ip=class{client;eventsKey;cursorKey;constructor(e,r){this.client=e,this.eventsKey=`incubator:${r}:events`,this.cursorKey=`incubator:${r}:cursor`}async publish(e,r,n){let o=new Date().toISOString(),s=this.client.multi();s.incr(this.cursorKey);let i=await s.exec();if(!i)throw new Error("Redis MULTI/EXEC failed");let a=i[0][1],c={id:a,type:e,data:r,publishedBy:n,publishedAt:o};return await this.client.zadd(this.eventsKey,a,JSON.stringify(c)),c}async getEvents(e,r){let n=e!==void 0?e+1:"-inf",s=(await this.client.zrangebyscore(this.eventsKey,n,"+inf")).map(a=>JSON.parse(a));r&&(s=s.filter(a=>a.type===r));let i=await this.getCursor();return{events:s,cursor:i}}async getCursor(){let e=await this.client.get(this.cursorKey);return e?parseInt(e,10):0}async getAll(){return(await this.client.zrange(this.eventsKey,0,-1)).map(r=>JSON.parse(r))}async load(e,r){let n=this.client.multi();n.del(this.eventsKey);for(let o of e)n.zadd(this.eventsKey,o.id,JSON.stringify(o));n.set(this.cursorKey,String(r)),await n.exec()}}});var ap,_P=w(()=>{Gr();ap=class t{client;hashKey;eventStore;constructor(e,r,n){this.client=e,this.hashKey=`incubator:${r}:claims`,this.eventStore=n}static CLAIM_SCRIPT=`
367
+ `).run(this.ns,e,r,n,l,o??null);let u={resource:e,value:r,owner:n,status:"active",claimedAt:l,ttlMs:o};i=!0,s={status:"approved",claim:u}})(),i&&await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),s}async release(e,r){let n=this.getClaimRow(e);return!n||n.status!=="active"||n.owner!==r?null:(this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("released",this.ns,e),await this.eventStore.publish("claim.released",{resource:e,owner:r},r),{...this.rowToClaim(n),status:"released"})}async check(e){let r=this.getClaimRow(e);return r?r.status==="active"&&Ze(r.claimed_at,r.ttl_ms??void 0)?(this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("expired",this.ns,e),{...this.rowToClaim(r),status:"expired"}):this.rowToClaim(r):null}async list(e){let r=this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ? AND status = ?").all(this.ns,"active"),n=[];for(let o of r){if(Ze(o.claimed_at,o.ttl_ms??void 0)){this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("expired",this.ns,o.resource);continue}e&&!gr(e,o.resource)||n.push(this.rowToClaim(o))}return n}async getAll(){return this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ?").all(this.ns).map(r=>this.rowToClaim(r))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM claims WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO claims (namespace, resource, value, owner, status, claimed_at, ttl_ms) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let o of e)n.run(this.ns,o.resource,o.value,o.owner,o.status,o.claimedAt,o.ttlMs??null)})()}getClaimRow(e){return this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ? AND resource = ?").get(this.ns,e)}rowToClaim(e){return{resource:e.resource,value:e.value,owner:e.owner,status:e.status,claimedAt:e.claimed_at,ttlMs:e.ttl_ms??void 0}}}});var cp,SP=w(()=>{Vr();cp=class{db;ns;eventStore;constructor(e,r,n){this.db=e,this.ns=r,this.eventStore=n}async publish(e,r,n,o){let s=ei(),i=new Date().toISOString();return this.db.prepare("INSERT INTO discoveries (namespace, id, topic, content, category, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(this.ns,s,e,r,o??null,n,i),await this.eventStore.publish("discovery.published",{id:s,topic:e,category:o},n),{id:s,topic:e,content:r,category:o,publishedBy:n,publishedAt:i}}async search(e,r){let n="SELECT id, topic, content, category, published_by, published_at FROM discoveries WHERE namespace = ?",o=[this.ns];r&&(n+=" AND category = ?",o.push(r));let i=this.db.prepare(n).all(...o).map(a=>this.rowToDiscovery(a));if(e){let a=e.toLowerCase();i=i.filter(c=>c.topic.toLowerCase().includes(a)||c.content.toLowerCase().includes(a))}return i}async getAll(){return this.db.prepare("SELECT id, topic, content, category, published_by, published_at FROM discoveries WHERE namespace = ?").all(this.ns).map(r=>this.rowToDiscovery(r))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM discoveries WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO discoveries (namespace, id, topic, content, category, published_by, published_at) VALUES (?, ?, ?, ?, ?, ?, ?)");for(let o of e)n.run(this.ns,o.id,o.topic,o.content,o.category??null,o.publishedBy,o.publishedAt)})()}rowToDiscovery(e){return{id:e.id,topic:e.topic,content:e.content,category:e.category??void 0,publishedBy:e.published_by,publishedAt:e.published_at}}}});function $P(t,e){let r=vP(t),n=new ip(r,e),o=new sp(r,e),s=new ap(r,e,n),i=new cp(r,e,n),a=new Bn,c=new Gn(n),l=new Vn,u=new Wn(n),p=new Jn,f=new Kn(n),d=new Yn(n),m=new Xn(n),h=new Qn;return{state:o,events:n,claims:s,discoveries:i,messages:a,help:c,progress:l,conflicts:u,roles:p,proposals:f,reinforcements:d,control:m,runs:h}}var kP=w(()=>{_P();bP();wP();xP();SP();Ju();Ku();Yu();Xu();Qu();ep();tp();rp();np()});var lp,EP=w(()=>{Vr();lp=class{client;hashKey;constructor(e,r){this.client=e,this.hashKey=`incubator:${r}:state`}async get(e){let r=await this.client.hget(this.hashKey,e);if(!r)return null;let n=JSON.parse(r);return Ze(n.setAt,n.ttlMs)?(await this.client.hdel(this.hashKey,e),null):n}async set(e,r,n,o,s){let i=new Date().toISOString(),c=(await this.get(e))?.setAt??i,l={key:e,value:r,category:o,setBy:n,setAt:c,updatedAt:i,ttlMs:s};return await this.client.hset(this.hashKey,e,JSON.stringify(l)),l}async delete(e){return await this.client.hdel(this.hashKey,e)>0}async query(e,r){let n=await this.client.hgetall(this.hashKey),o=[];for(let[,s]of Object.entries(n)){let i=JSON.parse(s);if(Ze(i.setAt,i.ttlMs)){await this.client.hdel(this.hashKey,i.key);continue}e&&!gr(e,i.key)||r&&i.category!==r||o.push(i)}return o}async getAll(){let e=await this.client.hgetall(this.hashKey),r=[];for(let[,n]of Object.entries(e)){let o=JSON.parse(n);Ze(o.setAt,o.ttlMs)||r.push(o)}return r}async load(e){if(await this.client.del(this.hashKey),e.length===0)return;let r={};for(let n of e)Ze(n.setAt,n.ttlMs)||(r[n.key]=JSON.stringify(n));Object.keys(r).length>0&&await this.client.hset(this.hashKey,r)}}});var up,TP=w(()=>{up=class{client;eventsKey;cursorKey;constructor(e,r){this.client=e,this.eventsKey=`incubator:${r}:events`,this.cursorKey=`incubator:${r}:cursor`}async publish(e,r,n){let o=new Date().toISOString(),s=this.client.multi();s.incr(this.cursorKey);let i=await s.exec();if(!i)throw new Error("Redis MULTI/EXEC failed");let a=i[0][1],c={id:a,type:e,data:r,publishedBy:n,publishedAt:o};return await this.client.zadd(this.eventsKey,a,JSON.stringify(c)),c}async getEvents(e,r){let n=e!==void 0?e+1:"-inf",s=(await this.client.zrangebyscore(this.eventsKey,n,"+inf")).map(a=>JSON.parse(a));r&&(s=s.filter(a=>a.type===r));let i=await this.getCursor();return{events:s,cursor:i}}async getCursor(){let e=await this.client.get(this.cursorKey);return e?parseInt(e,10):0}async getAll(){return(await this.client.zrange(this.eventsKey,0,-1)).map(r=>JSON.parse(r))}async load(e,r){let n=this.client.multi();n.del(this.eventsKey);for(let o of e)n.zadd(this.eventsKey,o.id,JSON.stringify(o));n.set(this.cursorKey,String(r)),await n.exec()}}});var pp,PP=w(()=>{Vr();pp=class t{client;hashKey;eventStore;constructor(e,r,n){this.client=e,this.hashKey=`incubator:${r}:claims`,this.eventStore=n}static CLAIM_SCRIPT=`
368
368
  local raw = redis.call('HGET', KEYS[1], ARGV[1])
369
369
  if raw then
370
370
  local existing = cjson.decode(raw)
@@ -387,28 +387,28 @@ data:
387
387
  end
388
388
  redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
389
389
  return nil
390
- `;async claim(e,r,n,o){let s=new Date,i={resource:e,value:r,owner:n,status:"active",claimedAt:s.toISOString(),ttlMs:o};i.claimedAtMs=s.getTime();let a=JSON.stringify(i),c=await this.client.eval(t.CLAIM_SCRIPT,1,this.hashKey,e,a,n,String(s.getTime()));if(c){let l=JSON.parse(c);return l.owner===n?(l.value=r,l.ttlMs=o,await this.client.hset(this.hashKey,e,JSON.stringify(l)),{status:"approved",claim:l}):{status:"rejected",claim:l}}return await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),{status:"approved",claim:i}}async release(e,r){let n=await this.client.hget(this.hashKey,e);if(!n)return null;let o=JSON.parse(n);return o.status!=="active"||o.owner!==r?null:(o.status="released",await this.client.hset(this.hashKey,e,JSON.stringify(o)),await this.eventStore.publish("claim.released",{resource:e,owner:r},r),o)}async check(e){let r=await this.client.hget(this.hashKey,e);if(!r)return null;let n=JSON.parse(r);return n.status==="active"&&qe(n.claimedAt,n.ttlMs)&&(n.status="expired",await this.client.hset(this.hashKey,e,JSON.stringify(n))),n}async list(e){let r=await this.client.hgetall(this.hashKey),n=[];for(let[,o]of Object.entries(r)){let s=JSON.parse(o);if(s.status==="active"&&qe(s.claimedAt,s.ttlMs)){s.status="expired",await this.client.hset(this.hashKey,s.resource,JSON.stringify(s));continue}s.status==="active"&&(e&&!hr(e,s.resource)||n.push(s))}return n}async getAll(){let e=await this.client.hgetall(this.hashKey);return Object.values(e).map(r=>JSON.parse(r))}async load(e){if(await this.client.del(this.hashKey),e.length===0)return;let r={};for(let n of e)r[n.resource]=JSON.stringify(n);await this.client.hset(this.hashKey,r)}}});var cp,bP=w(()=>{Gr();cp=class{client;listKey;eventStore;constructor(e,r,n){this.client=e,this.listKey=`incubator:${r}:discoveries`,this.eventStore=n}async publish(e,r,n,o){let s={id:Xs(),topic:e,content:r,category:o,publishedBy:n,publishedAt:new Date().toISOString()};return await this.client.rpush(this.listKey,JSON.stringify(s)),await this.eventStore.publish("discovery.published",{id:s.id,topic:e,category:o},n),s}async search(e,r){let o=(await this.client.lrange(this.listKey,0,-1)).map(s=>JSON.parse(s));if(r&&(o=o.filter(s=>s.category===r)),e){let s=e.toLowerCase();o=o.filter(i=>i.topic.toLowerCase().includes(s)||i.content.toLowerCase().includes(s))}return o}async getAll(){return(await this.client.lrange(this.listKey,0,-1)).map(r=>JSON.parse(r))}async load(e){let r=this.client.multi();r.del(this.listKey);for(let n of e)r.rpush(this.listKey,JSON.stringify(n));await r.exec()}}});function wP(t,e){let r=new ip(t,e),n=new sp(t,e),o=new ap(t,e,r),s=new cp(t,e,r),i=new Bn,a=new Vn(r),c=new Gn,l=new Wn(r),u=new Jn,p=new Kn(r),m=new Yn(r),d=new Xn(r),f=new Qn;return{state:n,events:r,claims:o,discoveries:s,messages:i,help:a,progress:c,conflicts:l,roles:u,proposals:p,reinforcements:m,control:d,runs:f}}var xP=w(()=>{yP();vP();_P();bP();Bu();Vu();Gu();Wu();Ju();Ku();Yu();Xu();Qu()});function SP(t){if(t.type==="memory")return rP();if(t.type==="sqlite"){if(!t.dbPath)throw new Error("SQLite backend requires dbPath");return hP(t.dbPath,t.namespace??"default")}if(t.type==="redis"){if(!t.redisClient)throw new Error("Redis backend requires redisClient");return wP(t.redisClient,t.namespace??"default")}throw new Error(`Unknown backend type: ${t.type}`)}var $P=w(()=>{_v();gP();xP()});var bv,lp,kP=w(()=>{bv="honeycomb:",lp=class{getStores;bus;subscribers=new Map;publishers=new Map;subscriptions=new Map;unsubscribers=new Map;transport;hiveName;hivePublishes;transportUnsubs=[];constructor(e,r,n){if(this.getStores=e,this.bus=r,n?.transport&&n.hiveName&&(this.transport=n.transport,this.hiveName=n.hiveName,this.hivePublishes=n.hivePublishes?new Set(n.hivePublishes):void 0,n.hiveSubscribes))for(let o of n.hiveSubscribes){let s=n.transport.subscribe(o,i=>{this.injectRemoteEvent(o,i)});this.transportUnsubs.push(s)}}registerProtocol(e,r){if(this.clearNamespace(e),!!r.topics){if(r.topics.publishes&&r.topics.publishes.length>0&&this.publishers.set(e,new Set(r.topics.publishes)),r.topics.subscribes&&r.topics.subscribes.length>0){let n=new Set(r.topics.subscribes);this.subscriptions.set(e,n);for(let o of n){let s=this.subscribers.get(o);s||(s=new Set,this.subscribers.set(o,s)),s.add(e)}}this.watch(e)}}watch(e){if(this.unsubscribers.has(e))return;let r=this.bus.subscribe(e,n=>{this.route(e,n)});this.unsubscribers.set(e,r)}route(e,r){if(r.publishedBy.startsWith(bv))return;let n=this.publishers.get(e);if(!n||!n.has(r.type))return;let o=this.subscribers.get(r.type);if(o&&o.size>0)for(let s of o){if(s===e)continue;this.getStores(s).events.publish(r.type,{...r.data&&typeof r.data=="object"?r.data:{value:r.data},_source:e},`${bv}${e}`).catch(()=>{})}if(this.transport&&this.hiveName&&(!this.hivePublishes||this.hivePublishes.has(r.type))){let s={sourceHive:this.hiveName,topic:r.type,data:r.data,publishedBy:r.publishedBy,timestamp:r.publishedAt};this.transport.publish(r.type,s).catch(()=>{})}}injectRemoteEvent(e,r){let n=this.subscribers.get(e);if(!n||n.size===0)return;let o=`${bv}${r.sourceHive}`;for(let s of n)this.getStores(s).events.publish(e,{...r.data&&typeof r.data=="object"?r.data:{value:r.data},_source:r.sourceHive},o).catch(()=>{})}clearNamespace(e){this.publishers.delete(e);let r=this.subscriptions.get(e);if(r){for(let o of r){let s=this.subscribers.get(o);s&&(s.delete(e),s.size===0&&this.subscribers.delete(o))}this.subscriptions.delete(e)}let n=this.unsubscribers.get(e);n&&(n(),this.unsubscribers.delete(e))}subscribe(e,r){let n=this.subscriptions.get(e);n||(n=new Set,this.subscriptions.set(e,n)),n.add(r);let o=this.subscribers.get(r);o||(o=new Set,this.subscribers.set(r,o)),o.add(e)}unsubscribe(e,r){let n=this.subscriptions.get(e);n&&(n.delete(r),n.size===0&&this.subscriptions.delete(e));let o=this.subscribers.get(r);o&&(o.delete(e),o.size===0&&this.subscribers.delete(r))}publish(e,r){let n=this.publishers.get(e);n||(n=new Set,this.publishers.set(e,n)),n.add(r),this.watch(e)}unpublish(e,r){let n=this.publishers.get(e);n&&(n.delete(r),n.size===0&&this.publishers.delete(e))}getTopics(e){let r=this.publishers.get(e),n=this.subscriptions.get(e);return{publishes:r?[...r]:[],subscribes:n?[...n]:[]}}getSubscribersForTopic(e){let r=this.subscribers.get(e);return r?[...r]:[]}}});function rH(t,e,r){let n=t.events.publish.bind(t.events);t.events.publish=async(o,s,i)=>{let a=await n(o,s,i);return e.publish(r,a),a}}var tH,up,EP=w(()=>{$P();ep();kP();tH=new Set(["_ns"]);up=class{namespaces=new Map;protocols=new Map;guard;verbose;backendConfig;bus;router;constructor(e){this.backendConfig=e??{type:"memory"}}setGuard(e,r){this.guard=e,this.verbose=r}setBus(e,r){this.bus=e,this.router=new lp(n=>this.get(n),e,r);for(let[n,o]of this.protocols)o.topics&&this.router.registerProtocol(n,o)}getRouter(){return this.router}get(e){if(tH.has(e))throw new Error(`'${e}' is a reserved name and cannot be used as a namespace`);if(!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e))throw new Error("Invalid namespace: must match /^[a-z0-9][a-z0-9_-]{0,63}$/");let r=this.namespaces.get(e);if(r)return r;if(this.namespaces.size>=100)throw new Error("Maximum namespace count (100) reached");return r=SP({...this.backendConfig,namespace:e}),this.bus&&rH(r,this.bus,e),this.guard&&(r=oP(r,this.guard,this.verbose)),this.namespaces.set(e,r),this.router&&this.router.watch(e),r}list(){return[...this.namespaces.keys()]}delete(e){return this.router&&this.router.clearNamespace(e),this.namespaces.delete(e)}has(e){return this.namespaces.has(e)}setProtocol(e,r){this.protocols.set(e,r),this.router&&r.topics&&this.router.registerProtocol(e,r)}getProtocol(e){return this.protocols.get(e)}}});import{readFileSync as nH,writeFileSync as oH,mkdirSync as sH,readdirSync as iH}from"node:fs";import{dirname as TP,basename as aH,join as cH}from"node:path";async function lH(t,e){let r={state:await e.state.getAll(),claims:await e.claims.getAll(),events:await e.events.getAll(),discoveries:await e.discoveries.getAll(),eventCursor:await e.events.getCursor(),savedAt:new Date().toISOString()};sH(TP(t),{recursive:!0}),oH(t,JSON.stringify(r,null,2),{mode:384})}async function uH(t,e,r){try{let n=nH(t,"utf-8"),o=JSON.parse(n);return r&&r(o),await e.events.load(o.events,o.eventCursor),await e.state.load(o.state),await e.claims.load(o.claims),await e.discoveries.load(o.discoveries),!0}catch{return!1}}async function pp(t,e){for(let r of e.list()){let n=`${t}.${r}.json`;await lH(n,e.get(r))}}async function PP(t,e,r){let n=TP(t),o=aH(t)+".",s=".json",i=0;try{let a=iH(n);for(let c of a){if(!c.startsWith(o)||!c.endsWith(s))continue;let l=c.slice(o.length,-s.length);if(!l)continue;let u=e.get(l);await uH(cH(n,c),u,r)&&i++}}catch{}return i}var RP=w(()=>{});import{EventEmitter as pH}from"node:events";var dp,fp,OP=w(()=>{dp=class{emitter=new pH;constructor(){this.emitter.setMaxListeners(0)}publish(e,r){this.emitter.emit(`ns:${e}`,r)}subscribe(e,r){let n=`ns:${e}`;return this.emitter.on(n,r),()=>{this.emitter.removeListener(n,r)}}close(){return this.emitter.removeAllListeners(),Promise.resolve()}},fp=class{pub;sub;listeners=new Map;subscribed=new Set;constructor(e,r){this.pub=e,this.sub=r,this.sub.on("message",(n,o)=>{let s=this.listeners.get(n);if(s)try{let i=JSON.parse(o);for(let a of s)a(i)}catch{}})}publish(e,r){let n=`incubator:${e}:live`;this.pub.publish(n,JSON.stringify(r)).catch(()=>{})}subscribe(e,r){let n=`incubator:${e}:live`,o=this.listeners.get(n);return o||(o=new Set,this.listeners.set(n,o)),o.add(r),this.subscribed.has(n)||(this.subscribed.add(n),this.sub.subscribe(n).catch(()=>{})),()=>{o.delete(r),o.size===0&&(this.listeners.delete(n),this.subscribed.delete(n),this.sub.unsubscribe(n).catch(()=>{}))}}async close(){this.listeners.clear(),this.subscribed.clear(),await this.sub.quit()}}});async function wv(t){let e=await import(t),r=e.default?.default??e.default??e.createIntegration;if(typeof r=="function"){let n=r();if(n&&typeof n.start=="function"&&typeof n.stop=="function")return n}if(e.default&&typeof e.default.start=="function")return e.default;throw new Error(`Package "${t}" does not export a valid IntegrationFactory or IntegrationModule. Expected default export function returning { name, start, stop }.`)}var xv=w(()=>{});var Da,CP=w(()=>{xv();Da=class{integrations=[];bus;namespace;eventStore;verbose;constructor(e){this.namespace=e.namespace??"default",this.bus=e.bus,this.eventStore=e.eventStore,this.verbose=e.verbose??!1}async loadFromConfig(e){let r=Object.entries(e).filter(([,n])=>n.enabled);for(let[n,o]of r)try{await this.load(n,o.package,o.config)}catch(s){console.error(`[integrations] Failed to load "${n}": ${s.message}`)}}async load(e,r,n={}){let o=await wv(r),s=this.createLogger(o.name),i={namespace:this.namespace,config:n,logger:s,publishEvent:async(c,l)=>{this.eventStore&&await this.eventStore.publish(c,l,`integration:${o.name}`)}};await o.start(i),s.info("Started");let a;o.onEvent&&this.bus&&(a=this.bus.subscribe(this.namespace,c=>{let l={type:c.type,data:c.data,agentId:c.publishedBy,namespace:this.namespace,timestamp:Date.now()};o.onEvent(l).catch(u=>{s.error(`onEvent error: ${u.message}`)})})),this.integrations.push({name:e,module:o,unsubscribe:a})}getTools(){let e=[];for(let{module:r}of this.integrations)r.getTools&&e.push(...r.getTools());return e}getLoadedNames(){return this.integrations.map(e=>e.name)}async stopAll(){for(let e of this.integrations)try{e.unsubscribe&&e.unsubscribe(),await e.module.stop(),this.verbose&&console.error(`[integrations] Stopped: ${e.name}`)}catch(r){console.error(`[integrations] Error stopping "${e.name}": ${r.message}`)}this.integrations=[]}createLogger(e){let r=`[int:${e}]`;return{info:(n,...o)=>{this.verbose&&console.error(`${r} ${n}`,...o)},warn:(n,...o)=>{console.error(`${r} WARN: ${n}`,...o)},error:(n,...o)=>{console.error(`${r} ERROR: ${n}`,...o)}}}}});import{readFileSync as dH,writeFileSync as Rte,mkdirSync as Ote,existsSync as fH}from"node:fs";import{join as IP}from"node:path";import{homedir as mH}from"node:os";function hH(){return IP(mH(),".config","honeybee")}function gH(){return IP(hH(),"integrations.json")}function Sv(){let t=gH();if(!fH(t))return{};try{return JSON.parse(dH(t,"utf8"))}catch{return{}}}var AP=w(()=>{});var NP=w(()=>{CP();xv();AP()});var mp,zP=w(()=>{mp=class{bus;runs;namespace;unsubscribe;constructor(e,r,n="default"){this.bus=e,this.runs=r,this.namespace=n}start(){this.unsubscribe=this.bus.subscribe(this.namespace,e=>{this.handleEvent(e).catch(()=>{})})}stop(){this.unsubscribe?.(),this.unsubscribe=void 0}async handleEvent(e){let r=e.data;if(r){if(e.type==="role.transition"){let n=r.agent,o=r.to;n&&o&&await this.runs.start(n,o)}if(e.type==="agent.complete"){let n=r.agent;if(!n)return;let o=r.usage,s=r.summary,i=r.iterations,a=r.elapsed,c="completed";s?.startsWith("Error:")&&(c="error"),s==="Agent halted"&&(c="halted"),await this.runs.complete(n,{status:c,usage:o,summary:s,iterations:i,elapsed:a,...c==="error"?{error:s}:{}})}}}}});var ei={};X(ei,{buildAcpHelper:()=>kv,callDanceTool:()=>Ev,danceToolDefs:()=>$v,loadDances:()=>yH,runInject:()=>Tv});async function yH(t){let e=await import(t),r=new Map,n;for(let[o,s]of Object.entries(e)){if(o==="default")continue;if(o==="inject"){if(typeof s!="function")throw new Error(`Dance file: "inject" must be a function, got ${typeof s}`);n=s;continue}if(!s||typeof s!="object")continue;let i=s;if(typeof i.handler!="function")throw new Error(`Dance file: tool "${o}" must have a handler function`);if(typeof i.description!="string")throw new Error(`Dance file: tool "${o}" must have a description string`);r.set(o,{description:i.description,params:i.params??{},handler:i.handler})}return{inject:n,tools:r}}function $v(t){let e=[];for(let[r,n]of t.tools){let o={},s=[];for(let[i,a]of Object.entries(n.params))o[i]={type:a.type,description:a.description??""},s.push(i);e.push({type:"function",function:{name:r,description:n.description,parameters:{type:"object",properties:o,required:s}}})}return e}function kv(t,e,r){return{async publish(n,o){await t.publishEvent(e,n,o,r)},async claim(n){return t.claimResource(e,n,r)},async release(n){await t.releaseResource(e,n)},async setState(n,o){await t.setState(e,n,o)}}}async function Ev(t,e,r,n,o,s,i){let a=t.tools.get(e);if(!a)return{error:`Unknown dance tool: ${e}`};let c=await s(),l={args:r,state:c,agent:{role:n,agentId:o},acp:i};try{return await a.handler(l)}catch(u){return{error:u instanceof Error?u.message:String(u)}}}function Tv(t,e,r,n){if(!t.inject)return null;try{return t.inject({state:e,agent:{role:r,agentId:n}})}catch(o){return`[inject error: ${o instanceof Error?o.message:String(o)}]`}}var Jo=w(()=>{});import{resolve as jP,relative as vH}from"node:path";function gr(t,e){let r=jP(t,e),n=vH(t,r);if(n.startsWith("..")||jP(n)===n)throw new Error(`Path "${e}" escapes the working directory`);return r}var hp=w(()=>{});function jt(t,e,r){if(!t)return null;let n=e.filter(Boolean).join(`
391
- `);if(!n)return null;let o=t.scan(n);if(r&&o.findings.length>0){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] score=${o.score} action=${o.action} findings=${o.findings.length}`)}if(o.action==="BLOCK")return`Blocked by security policy: ${o.summary}`;if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}return null}var qa=w(()=>{});function pt(t){return{content:[{type:"text",text:typeof t=="string"?t:JSON.stringify(t)}]}}function Ee(t){return pt({error:t})}var Za=w(()=>{});import{readFile as Rv,writeFile as MP,readdir as Ov,mkdir as _H,stat as LP}from"node:fs/promises";import{join as Cv,relative as Iv,dirname as bH}from"node:path";async function DP(t,e,r,n){let o=jt(r,[t.path],n);if(o)return Ee(o);try{let s=gr(e,t.path),i=await LP(s);if(i.size>Pv)return Ee(`File too large (${Math.round(i.size/1024)}KB, max ${Pv/1024}KB)`);let a=await Rv(s,"utf-8");return pt(a)}catch(s){return Ee(s.message)}}async function qP(t,e,r,n){let o=jt(r,[t.path,t.content],n);if(o)return Ee(o);try{let s=gr(e,t.path);return await _H(bH(s),{recursive:!0}),await MP(s,t.content,"utf-8"),pt({success:!0,path:t.path,bytes:Buffer.byteLength(t.content)})}catch(s){return Ee(s.message)}}async function ZP(t,e,r,n){let o=jt(r,[t.path,t.search,t.replace],n);if(o)return Ee(o);try{let s=gr(e,t.path),i=await Rv(s,"utf-8");if(!i.includes(t.search))return Ee(`Search string not found in ${t.path}`);let a=i.replace(t.search,t.replace);return await MP(s,a,"utf-8"),pt({success:!0,path:t.path})}catch(s){return Ee(s.message)}}async function UP(t,e,r,n){let o=jt(r,[t.path],n);if(o)return Ee(o);try{let s=t.path?gr(e,t.path):e,i=[];async function a(c){if(i.length>=Ua)return;let l=await Ov(c,{withFileTypes:!0});for(let u of l){if(i.length>=Ua)return;if(Av.has(u.name))continue;let p=Cv(c,u.name),m=Iv(e,p);i.push(u.isDirectory()?m+"/":m),u.isDirectory()&&t.recursive&&await a(p)}}return await a(s),pt({entries:i,count:i.length,truncated:i.length>=Ua})}catch(s){return Ee(s.message)}}async function FP(t,e,r,n){let o=jt(r,[t.pattern,t.path],n);if(o)return Ee(o);try{let s=t.path?gr(e,t.path):e,i=await wH(s,e,t.pattern);return pt({matches:i,count:i.length})}catch(s){return Ee(s.message)}}async function wH(t,e,r){let n=[],o=HP(r);async function s(i){if(n.length>=Ua)return;let a;try{a=await Ov(i,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Ua)return;if(Av.has(c.name))continue;let l=Cv(i,c.name),u=Iv(e,l);o.test(u)&&n.push(u),c.isDirectory()&&await s(l)}}return await s(t),n}function HP(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):n==="."?(e+="\\.",r++):(e+=n,r++)}return new RegExp(`^${e}$`)}async function BP(t,e,r,n){let o=jt(r,[t.pattern,t.path,t.glob],n);if(o)return Ee(o);try{let s=t.path?gr(e,t.path):e,i=new RegExp(t.pattern),a=t.glob?HP(t.glob):null,c=[],l=200;async function u(p){if(c.length>=l)return;let m;try{m=await Ov(p,{withFileTypes:!0})}catch{return}for(let d of m){if(c.length>=l)return;if(Av.has(d.name))continue;let f=Cv(p,d.name);if(d.isDirectory())await u(f);else if(d.isFile()){let h=Iv(e,f);if(a&&!a.test(h))continue;try{if((await LP(f)).size>Pv)continue;let _=(await Rv(f,"utf-8")).split(`
392
- `);for(let x=0;x<_.length&&!(c.length>=l);x++)i.test(_[x])&&c.push({file:h,line:x+1,text:_[x].slice(0,200)})}catch{}}}}return await u(s),pt({matches:c,count:c.length,truncated:c.length>=l})}catch(s){return Ee(s.message)}}var Pv,Ua,Av,VP=w(()=>{hp();qa();Za();Pv=500*1024,Ua=1e3,Av=new Set([".git","node_modules",".next","__pycache__",".cache","dist","build"])});import{exec as xH}from"node:child_process";async function GP(t,e,r,n){let o=jt(r,[t.command],n);if(o)return Ee(o);let s=t.cwd?gr(e,t.cwd):e,i=t.timeout??SH;return new Promise(a=>{let c=xH(t.command,{cwd:s,timeout:i,maxBuffer:Nv,env:{...process.env,HOME:process.env.HOME}},(l,u,p)=>{let m=u||"";if(p&&(m+=(m?`
390
+ `;async claim(e,r,n,o){let s=new Date,i={resource:e,value:r,owner:n,status:"active",claimedAt:s.toISOString(),ttlMs:o};i.claimedAtMs=s.getTime();let a=JSON.stringify(i),c=await this.client.eval(t.CLAIM_SCRIPT,1,this.hashKey,e,a,n,String(s.getTime()));if(c){let l=JSON.parse(c);return l.owner===n?(l.value=r,l.ttlMs=o,await this.client.hset(this.hashKey,e,JSON.stringify(l)),{status:"approved",claim:l}):{status:"rejected",claim:l}}return await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),{status:"approved",claim:i}}async release(e,r){let n=await this.client.hget(this.hashKey,e);if(!n)return null;let o=JSON.parse(n);return o.status!=="active"||o.owner!==r?null:(o.status="released",await this.client.hset(this.hashKey,e,JSON.stringify(o)),await this.eventStore.publish("claim.released",{resource:e,owner:r},r),o)}async check(e){let r=await this.client.hget(this.hashKey,e);if(!r)return null;let n=JSON.parse(r);return n.status==="active"&&Ze(n.claimedAt,n.ttlMs)&&(n.status="expired",await this.client.hset(this.hashKey,e,JSON.stringify(n))),n}async list(e){let r=await this.client.hgetall(this.hashKey),n=[];for(let[,o]of Object.entries(r)){let s=JSON.parse(o);if(s.status==="active"&&Ze(s.claimedAt,s.ttlMs)){s.status="expired",await this.client.hset(this.hashKey,s.resource,JSON.stringify(s));continue}s.status==="active"&&(e&&!gr(e,s.resource)||n.push(s))}return n}async getAll(){let e=await this.client.hgetall(this.hashKey);return Object.values(e).map(r=>JSON.parse(r))}async load(e){if(await this.client.del(this.hashKey),e.length===0)return;let r={};for(let n of e)r[n.resource]=JSON.stringify(n);await this.client.hset(this.hashKey,r)}}});var dp,RP=w(()=>{Vr();dp=class{client;listKey;eventStore;constructor(e,r,n){this.client=e,this.listKey=`incubator:${r}:discoveries`,this.eventStore=n}async publish(e,r,n,o){let s={id:ei(),topic:e,content:r,category:o,publishedBy:n,publishedAt:new Date().toISOString()};return await this.client.rpush(this.listKey,JSON.stringify(s)),await this.eventStore.publish("discovery.published",{id:s.id,topic:e,category:o},n),s}async search(e,r){let o=(await this.client.lrange(this.listKey,0,-1)).map(s=>JSON.parse(s));if(r&&(o=o.filter(s=>s.category===r)),e){let s=e.toLowerCase();o=o.filter(i=>i.topic.toLowerCase().includes(s)||i.content.toLowerCase().includes(s))}return o}async getAll(){return(await this.client.lrange(this.listKey,0,-1)).map(r=>JSON.parse(r))}async load(e){let r=this.client.multi();r.del(this.listKey);for(let n of e)r.rpush(this.listKey,JSON.stringify(n));await r.exec()}}});function OP(t,e){let r=new up(t,e),n=new lp(t,e),o=new pp(t,e,r),s=new dp(t,e,r),i=new Bn,a=new Gn(r),c=new Vn,l=new Wn(r),u=new Jn,p=new Kn(r),f=new Yn(r),d=new Xn(r),m=new Qn;return{state:n,events:r,claims:o,discoveries:s,messages:i,help:a,progress:c,conflicts:l,roles:u,proposals:p,reinforcements:f,control:d,runs:m}}var CP=w(()=>{EP();TP();PP();RP();Ju();Ku();Yu();Xu();Qu();ep();tp();rp();np()});function IP(t){if(t.type==="memory")return pP();if(t.type==="sqlite"){if(!t.dbPath)throw new Error("SQLite backend requires dbPath");return $P(t.dbPath,t.namespace??"default")}if(t.type==="redis"){if(!t.redisClient)throw new Error("Redis backend requires redisClient");return OP(t.redisClient,t.namespace??"default")}throw new Error(`Unknown backend type: ${t.type}`)}var AP=w(()=>{Ev();kP();CP()});var Tv,fp,NP=w(()=>{Tv="honeycomb:",fp=class{getStores;bus;subscribers=new Map;publishers=new Map;subscriptions=new Map;unsubscribers=new Map;transport;hiveName;hivePublishes;transportUnsubs=[];constructor(e,r,n){if(this.getStores=e,this.bus=r,n?.transport&&n.hiveName&&(this.transport=n.transport,this.hiveName=n.hiveName,this.hivePublishes=n.hivePublishes?new Set(n.hivePublishes):void 0,n.hiveSubscribes))for(let o of n.hiveSubscribes){let s=n.transport.subscribe(o,i=>{this.injectRemoteEvent(o,i)});this.transportUnsubs.push(s)}}registerProtocol(e,r){if(this.clearNamespace(e),!!r.topics){if(r.topics.publishes&&r.topics.publishes.length>0&&this.publishers.set(e,new Set(r.topics.publishes)),r.topics.subscribes&&r.topics.subscribes.length>0){let n=new Set(r.topics.subscribes);this.subscriptions.set(e,n);for(let o of n){let s=this.subscribers.get(o);s||(s=new Set,this.subscribers.set(o,s)),s.add(e)}}this.watch(e)}}watch(e){if(this.unsubscribers.has(e))return;let r=this.bus.subscribe(e,n=>{this.route(e,n)});this.unsubscribers.set(e,r)}route(e,r){if(r.publishedBy.startsWith(Tv))return;let n=this.publishers.get(e);if(!n||!n.has(r.type))return;let o=this.subscribers.get(r.type);if(o&&o.size>0)for(let s of o){if(s===e)continue;this.getStores(s).events.publish(r.type,{...r.data&&typeof r.data=="object"?r.data:{value:r.data},_source:e},`${Tv}${e}`).catch(()=>{})}if(this.transport&&this.hiveName&&(!this.hivePublishes||this.hivePublishes.has(r.type))){let s={sourceHive:this.hiveName,topic:r.type,data:r.data,publishedBy:r.publishedBy,timestamp:r.publishedAt};this.transport.publish(r.type,s).catch(()=>{})}}injectRemoteEvent(e,r){let n=this.subscribers.get(e);if(!n||n.size===0)return;let o=`${Tv}${r.sourceHive}`;for(let s of n)this.getStores(s).events.publish(e,{...r.data&&typeof r.data=="object"?r.data:{value:r.data},_source:r.sourceHive},o).catch(()=>{})}clearNamespace(e){this.publishers.delete(e);let r=this.subscriptions.get(e);if(r){for(let o of r){let s=this.subscribers.get(o);s&&(s.delete(e),s.size===0&&this.subscribers.delete(o))}this.subscriptions.delete(e)}let n=this.unsubscribers.get(e);n&&(n(),this.unsubscribers.delete(e))}subscribe(e,r){let n=this.subscriptions.get(e);n||(n=new Set,this.subscriptions.set(e,n)),n.add(r);let o=this.subscribers.get(r);o||(o=new Set,this.subscribers.set(r,o)),o.add(e)}unsubscribe(e,r){let n=this.subscriptions.get(e);n&&(n.delete(r),n.size===0&&this.subscriptions.delete(e));let o=this.subscribers.get(r);o&&(o.delete(e),o.size===0&&this.subscribers.delete(r))}publish(e,r){let n=this.publishers.get(e);n||(n=new Set,this.publishers.set(e,n)),n.add(r),this.watch(e)}unpublish(e,r){let n=this.publishers.get(e);n&&(n.delete(r),n.size===0&&this.publishers.delete(e))}getTopics(e){let r=this.publishers.get(e),n=this.subscriptions.get(e);return{publishes:r?[...r]:[],subscribes:n?[...n]:[]}}getSubscribersForTopic(e){let r=this.subscribers.get(e);return r?[...r]:[]}}});function S9(t,e,r){let n=t.events.publish.bind(t.events);t.events.publish=async(o,s,i)=>{let a=await n(o,s,i);return e.publish(r,a),a}}var x9,mp,zP=w(()=>{AP();op();NP();x9=new Set(["_ns"]);mp=class{namespaces=new Map;protocols=new Map;guard;verbose;backendConfig;bus;router;constructor(e){this.backendConfig=e??{type:"memory"}}setGuard(e,r){this.guard=e,this.verbose=r}setBus(e,r){this.bus=e,this.router=new fp(n=>this.get(n),e,r);for(let[n,o]of this.protocols)o.topics&&this.router.registerProtocol(n,o)}getRouter(){return this.router}get(e){if(x9.has(e))throw new Error(`'${e}' is a reserved name and cannot be used as a namespace`);if(!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e))throw new Error("Invalid namespace: must match /^[a-z0-9][a-z0-9_-]{0,63}$/");let r=this.namespaces.get(e);if(r)return r;if(this.namespaces.size>=100)throw new Error("Maximum namespace count (100) reached");return r=IP({...this.backendConfig,namespace:e}),this.bus&&S9(r,this.bus,e),this.guard&&(r=fP(r,this.guard,this.verbose)),this.namespaces.set(e,r),this.router&&this.router.watch(e),r}list(){return[...this.namespaces.keys()]}delete(e){return this.router&&this.router.clearNamespace(e),this.namespaces.delete(e)}has(e){return this.namespaces.has(e)}setProtocol(e,r){this.protocols.set(e,r),this.router&&r.topics&&this.router.registerProtocol(e,r)}getProtocol(e){return this.protocols.get(e)}}});import{readFileSync as $9,writeFileSync as k9,mkdirSync as E9,readdirSync as T9}from"node:fs";import{dirname as jP,basename as P9,join as R9}from"node:path";async function O9(t,e){let r={state:await e.state.getAll(),claims:await e.claims.getAll(),events:await e.events.getAll(),discoveries:await e.discoveries.getAll(),eventCursor:await e.events.getCursor(),savedAt:new Date().toISOString()};E9(jP(t),{recursive:!0}),k9(t,JSON.stringify(r,null,2),{mode:384})}async function C9(t,e,r){try{let n=$9(t,"utf-8"),o=JSON.parse(n);return r&&r(o),await e.events.load(o.events,o.eventCursor),await e.state.load(o.state),await e.claims.load(o.claims),await e.discoveries.load(o.discoveries),!0}catch{return!1}}async function hp(t,e){for(let r of e.list()){let n=`${t}.${r}.json`;await O9(n,e.get(r))}}async function MP(t,e,r){let n=jP(t),o=P9(t)+".",s=".json",i=0;try{let a=T9(n);for(let c of a){if(!c.startsWith(o)||!c.endsWith(s))continue;let l=c.slice(o.length,-s.length);if(!l)continue;let u=e.get(l);await C9(R9(n,c),u,r)&&i++}}catch{}return i}var LP=w(()=>{});import{EventEmitter as I9}from"node:events";var gp,yp,DP=w(()=>{gp=class{emitter=new I9;constructor(){this.emitter.setMaxListeners(0)}publish(e,r){this.emitter.emit(`ns:${e}`,r)}subscribe(e,r){let n=`ns:${e}`;return this.emitter.on(n,r),()=>{this.emitter.removeListener(n,r)}}close(){return this.emitter.removeAllListeners(),Promise.resolve()}},yp=class{pub;sub;listeners=new Map;subscribed=new Set;constructor(e,r){this.pub=e,this.sub=r,this.sub.on("message",(n,o)=>{let s=this.listeners.get(n);if(s)try{let i=JSON.parse(o);for(let a of s)a(i)}catch{}})}publish(e,r){let n=`incubator:${e}:live`;this.pub.publish(n,JSON.stringify(r)).catch(()=>{})}subscribe(e,r){let n=`incubator:${e}:live`,o=this.listeners.get(n);return o||(o=new Set,this.listeners.set(n,o)),o.add(r),this.subscribed.has(n)||(this.subscribed.add(n),this.sub.subscribe(n).catch(()=>{})),()=>{o.delete(r),o.size===0&&(this.listeners.delete(n),this.subscribed.delete(n),this.sub.unsubscribe(n).catch(()=>{}))}}async close(){this.listeners.clear(),this.subscribed.clear(),await this.sub.quit()}}});async function Pv(t){let e=await import(t),r=e.default?.default??e.default??e.createIntegration;if(typeof r=="function"){let n=r();if(n&&typeof n.start=="function"&&typeof n.stop=="function")return n}if(e.default&&typeof e.default.start=="function")return e.default;throw new Error(`Package "${t}" does not export a valid IntegrationFactory or IntegrationModule. Expected default export function returning { name, start, stop }.`)}var Rv=w(()=>{});var Ua,qP=w(()=>{Rv();Ua=class{integrations=[];bus;namespace;eventStore;verbose;constructor(e){this.namespace=e.namespace??"default",this.bus=e.bus,this.eventStore=e.eventStore,this.verbose=e.verbose??!1}async loadFromConfig(e){let r=Object.entries(e).filter(([,n])=>n.enabled);for(let[n,o]of r)try{await this.load(n,o.package,o.config)}catch(s){console.error(`[integrations] Failed to load "${n}": ${s.message}`)}}async load(e,r,n={}){let o=await Pv(r),s=this.createLogger(o.name),i={namespace:this.namespace,config:n,logger:s,publishEvent:async(c,l)=>{this.eventStore&&await this.eventStore.publish(c,l,`integration:${o.name}`)}};await o.start(i),s.info("Started");let a;o.onEvent&&this.bus&&(a=this.bus.subscribe(this.namespace,c=>{let l={type:c.type,data:c.data,agentId:c.publishedBy,namespace:this.namespace,timestamp:Date.now()};o.onEvent(l).catch(u=>{s.error(`onEvent error: ${u.message}`)})})),this.integrations.push({name:e,module:o,unsubscribe:a})}getTools(){let e=[];for(let{module:r}of this.integrations)r.getTools&&e.push(...r.getTools());return e}getLoadedNames(){return this.integrations.map(e=>e.name)}async stopAll(){for(let e of this.integrations)try{e.unsubscribe&&e.unsubscribe(),await e.module.stop(),this.verbose&&console.error(`[integrations] Stopped: ${e.name}`)}catch(r){console.error(`[integrations] Error stopping "${e.name}": ${r.message}`)}this.integrations=[]}createLogger(e){let r=`[int:${e}]`;return{info:(n,...o)=>{this.verbose&&console.error(`${r} ${n}`,...o)},warn:(n,...o)=>{console.error(`${r} WARN: ${n}`,...o)},error:(n,...o)=>{console.error(`${r} ERROR: ${n}`,...o)}}}}});import{readFileSync as A9,writeFileSync as dre,mkdirSync as fre,existsSync as N9}from"node:fs";import{join as ZP}from"node:path";import{homedir as z9}from"node:os";function j9(){return ZP(z9(),".config","honeybee")}function M9(){return ZP(j9(),"integrations.json")}function Ov(){let t=M9();if(!N9(t))return{};try{return JSON.parse(A9(t,"utf8"))}catch{return{}}}var UP=w(()=>{});var FP=w(()=>{qP();Rv();UP()});var vp,HP=w(()=>{vp=class{bus;runs;namespace;unsubscribe;constructor(e,r,n="default"){this.bus=e,this.runs=r,this.namespace=n}start(){this.unsubscribe=this.bus.subscribe(this.namespace,e=>{this.handleEvent(e).catch(()=>{})})}stop(){this.unsubscribe?.(),this.unsubscribe=void 0}async handleEvent(e){let r=e.data;if(r){if(e.type==="role.transition"){let n=r.agent,o=r.to;n&&o&&await this.runs.start(n,o)}if(e.type==="agent.complete"){let n=r.agent;if(!n)return;let o=r.usage,s=r.summary,i=r.iterations,a=r.elapsed,c="completed";s?.startsWith("Error:")&&(c="error"),s==="Agent halted"&&(c="halted"),await this.runs.complete(n,{status:c,usage:o,summary:s,iterations:i,elapsed:a,...c==="error"?{error:s}:{}})}}}}});var ri={};K(ri,{buildAcpHelper:()=>Iv,callDanceTool:()=>Av,danceToolDefs:()=>Cv,loadDances:()=>L9,runInject:()=>Nv});async function L9(t){let e=await import(t),r=new Map,n;for(let[o,s]of Object.entries(e)){if(o==="default")continue;if(o==="inject"){if(typeof s!="function")throw new Error(`Dance file: "inject" must be a function, got ${typeof s}`);n=s;continue}if(!s||typeof s!="object")continue;let i=s;if(typeof i.handler!="function")throw new Error(`Dance file: tool "${o}" must have a handler function`);if(typeof i.description!="string")throw new Error(`Dance file: tool "${o}" must have a description string`);r.set(o,{description:i.description,params:i.params??{},handler:i.handler})}return{inject:n,tools:r}}function Cv(t){let e=[];for(let[r,n]of t.tools){let o={},s=[];for(let[i,a]of Object.entries(n.params))o[i]={type:a.type,description:a.description??""},s.push(i);e.push({type:"function",function:{name:r,description:n.description,parameters:{type:"object",properties:o,required:s}}})}return e}function Iv(t,e,r){return{async publish(n,o){await t.publishEvent(e,n,o,r)},async claim(n){return t.claimResource(e,n,r)},async release(n){await t.releaseResource(e,n)},async setState(n,o){await t.setState(e,n,o)}}}async function Av(t,e,r,n,o,s,i){let a=t.tools.get(e);if(!a)return{error:`Unknown dance tool: ${e}`};let c=await s(),l={args:r,state:c,agent:{role:n,agentId:o},acp:i};try{return await a.handler(l)}catch(u){return{error:u instanceof Error?u.message:String(u)}}}function Nv(t,e,r,n){if(!t.inject)return null;try{return t.inject({state:e,agent:{role:r,agentId:n}})}catch(o){return`[inject error: ${o instanceof Error?o.message:String(o)}]`}}var Ko=w(()=>{});import{resolve as BP,relative as D9}from"node:path";function yr(t,e){let r=BP(t,e),n=D9(t,r);if(n.startsWith("..")||BP(n)===n)throw new Error(`Path "${e}" escapes the working directory`);return r}var _p=w(()=>{});function jt(t,e,r){if(!t)return null;let n=e.filter(Boolean).join(`
391
+ `);if(!n)return null;let o=t.scan(n);if(r&&o.findings.length>0){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] score=${o.score} action=${o.action} findings=${o.findings.length}`)}if(o.action==="BLOCK")return`Blocked by security policy: ${o.summary}`;if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}return null}var Fa=w(()=>{});function pt(t){return{content:[{type:"text",text:typeof t=="string"?t:JSON.stringify(t)}]}}function Ee(t){return pt({error:t})}var Ha=w(()=>{});import{readFile as jv,writeFile as GP,readdir as Mv,mkdir as q9,stat as VP}from"node:fs/promises";import{join as Lv,relative as Dv,dirname as Z9}from"node:path";async function WP(t,e,r,n){let o=jt(r,[t.path],n);if(o)return Ee(o);try{let s=yr(e,t.path),i=await VP(s);if(i.size>zv)return Ee(`File too large (${Math.round(i.size/1024)}KB, max ${zv/1024}KB)`);let a=await jv(s,"utf-8");return pt(a)}catch(s){return Ee(s.message)}}async function JP(t,e,r,n){let o=jt(r,[t.path,t.content],n);if(o)return Ee(o);try{let s=yr(e,t.path);return await q9(Z9(s),{recursive:!0}),await GP(s,t.content,"utf-8"),pt({success:!0,path:t.path,bytes:Buffer.byteLength(t.content)})}catch(s){return Ee(s.message)}}async function KP(t,e,r,n){let o=jt(r,[t.path,t.search,t.replace],n);if(o)return Ee(o);try{let s=yr(e,t.path),i=await jv(s,"utf-8");if(!i.includes(t.search))return Ee(`Search string not found in ${t.path}`);let a=i.replace(t.search,t.replace);return await GP(s,a,"utf-8"),pt({success:!0,path:t.path})}catch(s){return Ee(s.message)}}async function YP(t,e,r,n){let o=jt(r,[t.path],n);if(o)return Ee(o);try{let s=t.path?yr(e,t.path):e,i=[];async function a(c){if(i.length>=Ba)return;let l=await Mv(c,{withFileTypes:!0});for(let u of l){if(i.length>=Ba)return;if(qv.has(u.name))continue;let p=Lv(c,u.name),f=Dv(e,p);i.push(u.isDirectory()?f+"/":f),u.isDirectory()&&t.recursive&&await a(p)}}return await a(s),pt({entries:i,count:i.length,truncated:i.length>=Ba})}catch(s){return Ee(s.message)}}async function XP(t,e,r,n){let o=jt(r,[t.pattern,t.path],n);if(o)return Ee(o);try{let s=t.path?yr(e,t.path):e,i=await U9(s,e,t.pattern);return pt({matches:i,count:i.length})}catch(s){return Ee(s.message)}}async function U9(t,e,r){let n=[],o=QP(r);async function s(i){if(n.length>=Ba)return;let a;try{a=await Mv(i,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Ba)return;if(qv.has(c.name))continue;let l=Lv(i,c.name),u=Dv(e,l);o.test(u)&&n.push(u),c.isDirectory()&&await s(l)}}return await s(t),n}function QP(t){let e="",r=0;for(;r<t.length;){let n=t[r];n==="*"&&t[r+1]==="*"?(e+=".*",r+=2,t[r]==="/"&&r++):n==="*"?(e+="[^/]*",r++):n==="?"?(e+="[^/]",r++):n==="."?(e+="\\.",r++):(e+=n,r++)}return new RegExp(`^${e}$`)}async function eR(t,e,r,n){let o=jt(r,[t.pattern,t.path,t.glob],n);if(o)return Ee(o);try{let s=t.path?yr(e,t.path):e,i=new RegExp(t.pattern),a=t.glob?QP(t.glob):null,c=[],l=200;async function u(p){if(c.length>=l)return;let f;try{f=await Mv(p,{withFileTypes:!0})}catch{return}for(let d of f){if(c.length>=l)return;if(qv.has(d.name))continue;let m=Lv(p,d.name);if(d.isDirectory())await u(m);else if(d.isFile()){let h=Dv(e,m);if(a&&!a.test(h))continue;try{if((await VP(m)).size>zv)continue;let b=(await jv(m,"utf-8")).split(`
392
+ `);for(let x=0;x<b.length&&!(c.length>=l);x++)i.test(b[x])&&c.push({file:h,line:x+1,text:b[x].slice(0,200)})}catch{}}}}return await u(s),pt({matches:c,count:c.length,truncated:c.length>=l})}catch(s){return Ee(s.message)}}var zv,Ba,qv,tR=w(()=>{_p();Fa();Ha();zv=500*1024,Ba=1e3,qv=new Set([".git","node_modules",".next","__pycache__",".cache","dist","build"])});import{exec as F9}from"node:child_process";async function rR(t,e,r,n){let o=jt(r,[t.command],n);if(o)return Ee(o);let s=t.cwd?yr(e,t.cwd):e,i=t.timeout??H9;return new Promise(a=>{let c=F9(t.command,{cwd:s,timeout:i,maxBuffer:Zv,env:{...process.env,HOME:process.env.HOME}},(l,u,p)=>{let f=u||"";if(p&&(f+=(f?`
393
393
  --- stderr ---
394
- `:"")+p),m.length>Nv&&(m=m.slice(0,Nv)+`
395
- ... (output truncated)`),l){let d=l.code;a(pt({exitCode:typeof d=="number"?d:1,output:m,error:l.killed?"Command timed out":l.message}));return}a(pt({exitCode:0,output:m}))});setTimeout(()=>{c.kill("SIGKILL")},i+1e3)})}var SH,Nv,WP=w(()=>{hp();qa();Za();SH=6e4,Nv=100*1024});import{exec as JP}from"node:child_process";function Fa(t,e){return new Promise((r,n)=>{JP(t,{cwd:e,timeout:3e4},(o,s,i)=>{if(o){n(new Error(i.trim()||o.message));return}r(s.trim())})})}async function KP(t,e){try{let r=await Fa("git status --porcelain",e);return pt(r||"(clean)")}catch(r){return Ee(r.message)}}async function YP(t,e,r,n){let o=jt(r,[t.path],n);if(o)return Ee(o);try{let s="git diff";if(t.staged&&(s+=" --staged"),t.path){let a=gr(e,t.path);s+=` -- "${a}"`}let i=await Fa(s,e);return pt(i||"(no diff)")}catch(s){return Ee(s.message)}}async function XP(t,e,r,n){let o=jt(r,[t.message,t.files],n);if(o)return Ee(o);try{if(t.files){let i=t.files.split(",").map(a=>a.trim()).filter(Boolean);for(let a of i){let c=gr(e,a);await Fa(`git add "${c}"`,e)}}else await Fa("git add -A",e);let s=await new Promise((i,a)=>{let c=JP("git commit -F -",{cwd:e,timeout:3e4},(l,u,p)=>{if(l){a(new Error(p.trim()||l.message));return}i(u.trim())});c.stdin?.write(t.message),c.stdin?.end()});return pt({success:!0,output:s})}catch(s){return Ee(s.message)}}async function QP(t,e){try{let r=t.count??10,n=await Fa(`git log --oneline -n ${r}`,e);return pt(n||"(no commits)")}catch(r){return Ee(r.message)}}var eR=w(()=>{hp();qa();Za()});function tR(t){try{let e=new URL(t);return kH.test(e.hostname)||$H.test(e.hostname)}catch{return!0}}async function rR(t,e,r,n){let{url:o,method:s="GET",headers:i={},body:a}=t;if(tR(o))return Ee("Blocked: cannot fetch localhost or private IP addresses");let c=jt(r,[o,a],n);if(c)return Ee(c);try{let l=new AbortController,u=setTimeout(()=>l.abort(),gp),p=await fetch(o,{method:s.toUpperCase(),headers:i,body:s.toUpperCase()!=="GET"&&s.toUpperCase()!=="HEAD"?a:void 0,signal:l.signal});clearTimeout(u);let m=[],d=0,f=p.body?.getReader();if(f)for(;;){let{done:v,value:_}=await f.read();if(v)break;if(d+=_.length,d>ti){f.cancel(),m.push(Buffer.from(_.slice(0,ti-(d-_.length))));break}m.push(Buffer.from(_))}let h=Buffer.concat(m).toString("utf-8"),g={};return p.headers.forEach((v,_)=>{g[_]=v}),pt({status:p.status,headers:g,body:h,truncated:d>ti})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("abort")?Ee(`Request timed out after ${gp/1e3}s`):Ee(`Fetch failed: ${u}`)}}async function nR(t,e,r,n){let{url:o}=t;if(tR(o))return Ee("Blocked: cannot scrape localhost or private IP addresses");let s=jt(r,[o],n);if(s)return Ee(s);try{let i=new AbortController,a=setTimeout(()=>i.abort(),gp),c=await fetch(o,{headers:{Accept:"text/html,application/xhtml+xml,*/*"},signal:i.signal});if(clearTimeout(a),!c.ok)return Ee(`HTTP ${c.status}: ${c.statusText}`);let l=[],u=0,p=c.body?.getReader();if(p)for(;;){let{done:f,value:h}=await p.read();if(f)break;if(u+=h.length,u>ti){p.cancel(),l.push(Buffer.from(h.slice(0,ti-(u-h.length))));break}l.push(Buffer.from(h))}let m=Buffer.concat(l).toString("utf-8"),d=EH(m);return pt({url:o,status:c.status,text:d,truncated:u>ti})}catch(i){let a=i instanceof Error?i.message:String(i);return a.includes("abort")?Ee(`Request timed out after ${gp/1e3}s`):Ee(`Scrape failed: ${a}`)}}function EH(t){return t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<\/(p|div|h[1-6]|li|tr|br|hr)[^>]*>/gi,`
394
+ `:"")+p),f.length>Zv&&(f=f.slice(0,Zv)+`
395
+ ... (output truncated)`),l){let d=l.code;a(pt({exitCode:typeof d=="number"?d:1,output:f,error:l.killed?"Command timed out":l.message}));return}a(pt({exitCode:0,output:f}))});setTimeout(()=>{c.kill("SIGKILL")},i+1e3)})}var H9,Zv,nR=w(()=>{_p();Fa();Ha();H9=6e4,Zv=100*1024});import{exec as oR}from"node:child_process";function Ga(t,e){return new Promise((r,n)=>{oR(t,{cwd:e,timeout:3e4},(o,s,i)=>{if(o){n(new Error(i.trim()||o.message));return}r(s.trim())})})}async function sR(t,e){try{let r=await Ga("git status --porcelain",e);return pt(r||"(clean)")}catch(r){return Ee(r.message)}}async function iR(t,e,r,n){let o=jt(r,[t.path],n);if(o)return Ee(o);try{let s="git diff";if(t.staged&&(s+=" --staged"),t.path){let a=yr(e,t.path);s+=` -- "${a}"`}let i=await Ga(s,e);return pt(i||"(no diff)")}catch(s){return Ee(s.message)}}async function aR(t,e,r,n){let o=jt(r,[t.message,t.files],n);if(o)return Ee(o);try{if(t.files){let i=t.files.split(",").map(a=>a.trim()).filter(Boolean);for(let a of i){let c=yr(e,a);await Ga(`git add "${c}"`,e)}}else await Ga("git add -A",e);let s=await new Promise((i,a)=>{let c=oR("git commit -F -",{cwd:e,timeout:3e4},(l,u,p)=>{if(l){a(new Error(p.trim()||l.message));return}i(u.trim())});c.stdin?.write(t.message),c.stdin?.end()});return pt({success:!0,output:s})}catch(s){return Ee(s.message)}}async function cR(t,e){try{let r=t.count??10,n=await Ga(`git log --oneline -n ${r}`,e);return pt(n||"(no commits)")}catch(r){return Ee(r.message)}}var lR=w(()=>{_p();Fa();Ha()});function uR(t){try{let e=new URL(t);return G9.test(e.hostname)||B9.test(e.hostname)}catch{return!0}}async function pR(t,e,r,n){let{url:o,method:s="GET",headers:i={},body:a}=t;if(uR(o))return Ee("Blocked: cannot fetch localhost or private IP addresses");let c=jt(r,[o,a],n);if(c)return Ee(c);try{let l=new AbortController,u=setTimeout(()=>l.abort(),bp),p=await fetch(o,{method:s.toUpperCase(),headers:i,body:s.toUpperCase()!=="GET"&&s.toUpperCase()!=="HEAD"?a:void 0,signal:l.signal});clearTimeout(u);let f=[],d=0,m=p.body?.getReader();if(m)for(;;){let{done:v,value:b}=await m.read();if(v)break;if(d+=b.length,d>ni){m.cancel(),f.push(Buffer.from(b.slice(0,ni-(d-b.length))));break}f.push(Buffer.from(b))}let h=Buffer.concat(f).toString("utf-8"),g={};return p.headers.forEach((v,b)=>{g[b]=v}),pt({status:p.status,headers:g,body:h,truncated:d>ni})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("abort")?Ee(`Request timed out after ${bp/1e3}s`):Ee(`Fetch failed: ${u}`)}}async function dR(t,e,r,n){let{url:o}=t;if(uR(o))return Ee("Blocked: cannot scrape localhost or private IP addresses");let s=jt(r,[o],n);if(s)return Ee(s);try{let i=new AbortController,a=setTimeout(()=>i.abort(),bp),c=await fetch(o,{headers:{Accept:"text/html,application/xhtml+xml,*/*"},signal:i.signal});if(clearTimeout(a),!c.ok)return Ee(`HTTP ${c.status}: ${c.statusText}`);let l=[],u=0,p=c.body?.getReader();if(p)for(;;){let{done:m,value:h}=await p.read();if(m)break;if(u+=h.length,u>ni){p.cancel(),l.push(Buffer.from(h.slice(0,ni-(u-h.length))));break}l.push(Buffer.from(h))}let f=Buffer.concat(l).toString("utf-8"),d=V9(f);return pt({url:o,status:c.status,text:d,truncated:u>ni})}catch(i){let a=i instanceof Error?i.message:String(i);return a.includes("abort")?Ee(`Request timed out after ${bp/1e3}s`):Ee(`Scrape failed: ${a}`)}}function V9(t){return t.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<\/(p|div|h[1-6]|li|tr|br|hr)[^>]*>/gi,`
396
396
  `).replace(/<br\s*\/?>/gi,`
397
397
  `).replace(/<[^>]+>/g,"").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," ").replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
398
398
 
399
- `).trim()}var $H,kH,ti,gp,oR=w(()=>{Za();qa();$H=/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.|169\.254\.|::1|fc|fd|fe80)/i,kH=/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])/i;ti=512*1024,gp=3e4});function zv(t,e,r){return[{def:{type:"function",function:{name:"read_file",description:"Read a file relative to the working directory",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to working directory"}},required:["path"]}}},schema:{path:M.string().describe("File path relative to working directory")},handler:n=>DP(n,t,e,r)},{def:{type:"function",function:{name:"write_file",description:"Write content to a file. Creates parent directories automatically.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to working directory"},content:{type:"string",description:"Content to write"}},required:["path","content"]}}},schema:{path:M.string().describe("File path relative to working directory"),content:M.string().describe("Content to write")},handler:n=>qP(n,t,e,r)},{def:{type:"function",function:{name:"patch_file",description:"Find and replace text in a file. The search string must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to working directory"},search:{type:"string",description:"Exact text to find"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}}},schema:{path:M.string().describe("File path relative to working directory"),search:M.string().describe("Exact text to find"),replace:M.string().describe("Text to replace with")},handler:n=>ZP(n,t,e,r)},{def:{type:"function",function:{name:"list_files",description:"List files in a directory. Skips node_modules, .git, and similar directories.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path relative to working directory (default: root)"},recursive:{type:"string",description:"List recursively (default: false)"}},required:[]}}},schema:{path:M.string().optional().describe("Directory path relative to working directory (default: root)"),recursive:M.boolean().optional().describe("List recursively (default: false)")},handler:n=>UP(n,t,e,r)},{def:{type:"function",function:{name:"glob",description:'Find files matching a glob pattern (e.g. "**/*.ts")',parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern to match"},path:{type:"string",description:"Base directory for the search"}},required:["pattern"]}}},schema:{pattern:M.string().describe("Glob pattern to match"),path:M.string().optional().describe("Base directory for the search")},handler:n=>FP(n,t,e,r)},{def:{type:"function",function:{name:"grep",description:"Search file contents using a regex pattern",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in"},glob:{type:"string",description:'File glob filter (e.g. "*.ts")'}},required:["pattern"]}}},schema:{pattern:M.string().describe("Regex pattern to search for"),path:M.string().optional().describe("Directory to search in"),glob:M.string().optional().describe('File glob filter (e.g. "*.ts")')},handler:n=>BP(n,t,e,r)},{def:{type:"function",function:{name:"run",description:"Execute a shell command. 60s timeout, 100KB output cap.",parameters:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory relative to sandbox root"},timeout:{type:"string",description:"Timeout in milliseconds (default: 60000)"}},required:["command"]}}},schema:{command:M.string().describe("Shell command to execute"),cwd:M.string().optional().describe("Working directory relative to sandbox root"),timeout:M.number().optional().describe("Timeout in milliseconds (default: 60000)")},handler:n=>GP(n,t,e,r)},{def:{type:"function",function:{name:"git_status",description:"Show git status (porcelain format)",parameters:{type:"object",properties:{},required:[]}}},schema:{},handler:()=>KP({},t)},{def:{type:"function",function:{name:"git_diff",description:"Show git diff. Optionally for a specific path or staged changes.",parameters:{type:"object",properties:{path:{type:"string",description:"File path to diff"},staged:{type:"string",description:"Show staged changes"}},required:[]}}},schema:{path:M.string().optional().describe("File path to diff"),staged:M.boolean().optional().describe("Show staged changes")},handler:n=>YP(n,t,e,r)},{def:{type:"function",function:{name:"git_commit",description:"Stage files and create a git commit",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},files:{type:"string",description:"Comma-separated file paths to stage (default: all)"}},required:["message"]}}},schema:{message:M.string().describe("Commit message"),files:M.string().optional().describe("Comma-separated file paths to stage (default: all)")},handler:n=>XP(n,t,e,r)},{def:{type:"function",function:{name:"git_log",description:"Show recent git commits (oneline format)",parameters:{type:"object",properties:{count:{type:"string",description:"Number of commits to show (default: 10)"}},required:[]}}},schema:{count:M.number().optional().describe("Number of commits to show (default: 10)")},handler:n=>QP(n,t)},{def:{type:"function",function:{name:"fetch",description:"Make an HTTP request. Returns status, headers, and body. Blocks localhost/private IPs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},method:{type:"string",description:"HTTP method (default: GET)"},body:{type:"string",description:"Request body (for POST/PUT/PATCH)"}},required:["url"]}}},schema:{url:M.string().describe("URL to fetch"),method:M.string().optional().describe("HTTP method (default: GET)"),body:M.string().optional().describe("Request body (for POST/PUT/PATCH)")},handler:n=>rR(n,t,e,r)},{def:{type:"function",function:{name:"scrape_page",description:"Fetch a web page and extract readable text (strips HTML tags, scripts, styles). Blocks localhost/private IPs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL of the page to scrape"}},required:["url"]}}},schema:{url:M.string().describe("URL of the page to scrape")},handler:n=>nR(n,t,e,r)}]}var jv=w(()=>{Du();VP();WP();eR();oR()});function sR(t){return t===void 0||t===!1||t===null?null:t===!0?{types:null,timeout:0,pureDelay:!1}:typeof t=="string"?{types:[t],timeout:0,pureDelay:!1}:Array.isArray(t)?{types:t.length>0?t:null,timeout:0,pureDelay:!1}:typeof t=="number"?{types:null,timeout:t,pureDelay:!0}:{types:t.types&&t.types.length>0?t.types:null,timeout:t.timeout??0,pureDelay:!1}}var iR=w(()=>{jv()});function Mv(t){let e=new Set,r=[];for(let n of t)if(n.includes("*")){let o=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^.]*");r.push(new RegExp("^"+o+"$"))}else e.add(n);return r.length===0?n=>e.has(n):n=>e.has(n)||r.some(o=>o.test(n))}var aR=w(()=>{});function Lv(t){let e=typeof t.data=="string"?t.data:JSON.stringify(t.data);return`Event from ${t.publishedBy}: [${t.type}] ${e}`}var yp,cR=w(()=>{Jo();iR();aR();yp=class{stores;bus;namespace;agentId;role;maxIterations;verbose;danceModule;protocolData;iterationCount=0;eventBuffer=[];unsubscribe;claimedResources=new Set;cachedInject=null;lastEventCursor=0;constructor(e){this.stores=e.stores,this.bus=e.bus,this.namespace=e.namespace,this.agentId=e.agentId,this.role=e.role,this.maxIterations=e.maxIterations,this.verbose=e.verbose??!1,this.danceModule=e.danceModule,this.protocolData=e.protocolData}async connect(){await this.stores.roles.assign(this.agentId,this.role),await this.stores.runs.start(this.agentId,this.role),this.unsubscribe=this.bus.subscribe(this.namespace,e=>{e.publishedBy!==this.agentId&&this.eventBuffer.push(Lv(e))})}async disconnect(){for(let e of this.claimedResources)try{await this.stores.claims.release(e,this.agentId)}catch{}this.claimedResources.clear(),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}async waitForWake(e){await this.refreshInjectCache(),await this.replayMissedEvents();let r=this.drainMatchingEvents(e.types??null);if(r.length>0)return r;let n=e.timeout&&e.timeout>0?e.timeout:0;return new Promise(o=>{let s,i,a=()=>{s&&clearTimeout(s),i&&i()};i=this.bus.subscribe(this.namespace,c=>{if(c.publishedBy===this.agentId)return;let l=Lv(c);if(e.types&&!Mv(e.types)(c.type)){this.eventBuffer.push(l);return}a(),this.refreshInjectCache().then(()=>o([l]))}),n>0&&(s=setTimeout(()=>{a(),o([])},n))})}getLastInject(){let e=this.cachedInject;return this.cachedInject=null,e}async callDanceTool(e,r){if(!this.danceModule)throw new Error("No dance module loaded");let n=this.buildDanceHelper(),o=async()=>this.getStateMap(),s=await Ev(this.danceModule,e,r,this.role,this.agentId,o,n);if("error"in s||!s.wait)return s;let i=sR(s.wait);if(!i)return s;let{wait:a,...c}=s;try{let{cursor:p}=await this.stores.events.getEvents();this.lastEventCursor=p}catch{}this.eventBuffer=[];let l=[];i.pureDelay?await new Promise(p=>setTimeout(p,i.timeout)):l=await this.waitForWake({types:i.types??void 0,timeout:i.timeout});let u=this.getLastInject();return{...c,wakeEvents:l,...u?{inject:u}:{}}}getDanceTools(){if(!this.danceModule)return null;let e=$v(this.danceModule);return e.length>0?e:null}async beforeIteration(){this.iterationCount++,await this.stores.progress.report(this.agentId,this.agentId,this.iterationCount/this.maxIterations,`Iteration ${this.iterationCount}/${this.maxIterations}`);let e=[...this.eventBuffer];this.eventBuffer=[];let r=await this.stores.messages.getFor(this.agentId);for(let n of r)e.push(`Message from ${n.from}: ${n.content}`);return this.danceModule&&await this.refreshInjectCache(),e}async onFileWrite(e){let r=await this.stores.claims.claim(e,e,this.agentId,3e5);if(r.status==="approved")return this.claimedResources.add(e),null;let n=r.claim?.owner??"another agent";return JSON.stringify({error:`File "${e}" is claimed by ${n}`})}async onComplete(e,r){await this.stores.runs.complete(this.agentId,{status:"completed",summary:e,iterations:this.iterationCount,usage:r});for(let n of this.claimedResources)try{await this.stores.claims.release(n,this.agentId)}catch{}this.claimedResources.clear()}async fetchProtocol(){return this.protocolData??null}async publishEvent(e,r={}){try{return await this.stores.events.publish(e,r,this.agentId),JSON.stringify({published:!0,type:e})}catch(n){return JSON.stringify({error:`publishEvent failed: ${n.message}`})}}async setState(e,r){try{return await this.stores.state.set(e,r,this.agentId),JSON.stringify({ok:!0,key:e})}catch(n){return JSON.stringify({error:`setState failed: ${n.message}`})}}async getState(){try{let e=await this.stores.state.query(),r={};for(let n of e)r[n.key]=n.value;return JSON.stringify(r)}catch(e){return JSON.stringify({error:`getState failed: ${e.message}`})}}async claimResource(e,r){try{let n=await this.stores.claims.claim(e,r??e,this.agentId,3e5);if(n.status==="approved")return this.claimedResources.add(e),JSON.stringify({status:"approved",resource:e});let o=n.claim?.owner??"another agent";return JSON.stringify({status:"rejected",resource:e,owner:o,message:`Already claimed by ${o}`})}catch(n){return JSON.stringify({error:`claimResource failed: ${n.message}`})}}async releaseResource(e){try{return await this.stores.claims.release(e,this.agentId),this.claimedResources.delete(e),JSON.stringify({released:!0,resource:e})}catch(r){return JSON.stringify({error:`releaseResource failed: ${r.message}`})}}async checkControl(){let e=this.stores.control.getStatus(this.agentId);return{halted:e.halted,paused:e.paused,reason:e.haltReason??e.pauseReason}}async waitForResume(e=2e3){for(;;)if(await new Promise(n=>setTimeout(n,e)),!this.stores.control.getStatus(this.agentId).paused)return"resumed"}async replayMissedEvents(){try{let{events:e,cursor:r}=await this.stores.events.getEvents(this.lastEventCursor);this.lastEventCursor=r;for(let n of e){if(n.publishedBy===this.agentId)continue;let o=Lv(n);this.eventBuffer.includes(o)||this.eventBuffer.push(o)}}catch{}}drainMatchingEvents(e){if(this.eventBuffer.length===0)return[];if(!e){let s=[...this.eventBuffer];return this.eventBuffer=[],s}let r=Mv(e),n=[],o=[];for(let s of this.eventBuffer){let i=s.match(/\[([^\]]+)\]/);i&&r(i[1])?n.push(s):o.push(s)}return this.eventBuffer=o,n}async getStateMap(){let e=await this.stores.state.query(),r={};for(let n of e)r[n.key]=typeof n.value=="string"?n.value:JSON.stringify(n.value);return r}buildDanceHelper(){return kv({publishEvent:async(e,r,n,o)=>{await this.stores.events.publish(r,n,o??this.agentId)},claimResource:async(e,r,n,o)=>(await this.stores.claims.claim(r,r,n,o)).status,releaseResource:async(e,r)=>{await this.stores.claims.release(r,this.agentId)},setState:async(e,r,n)=>{await this.stores.state.set(r,n,this.agentId)}},this.namespace,this.agentId)}async refreshInjectCache(){if(!this.danceModule)return;let e=await this.getStateMap();this.cachedInject=Tv(this.danceModule,e,this.role,this.agentId)}}});function uR(t){let e=t.indexOf("/");if(e===-1)throw new Error(`Invalid provider shorthand "${t}". Use format: provider/model (e.g. ollama/qwen3:32b, openai/gpt-4o, anthropic/claude-sonnet-4-5-20250929)`);let r=t.slice(0,e),n=t.slice(e+1);if(!n)throw new Error(`Missing model in provider shorthand "${t}"`);let o=r==="ollama"?"ollama":r==="anthropic"?"anthropic":"openai",s=lR[r]??lR.openai;if(o==="ollama"&&process.env.OLLAMA_HOST){let a=process.env.OLLAMA_HOST;s=a.startsWith("http")?a:`http://${a}`}let i;return r==="cerebras"?i=process.env.CEREBRAS_API_KEY:r==="groq"?i=process.env.GROQ_API_KEY:o==="openai"?i=process.env.OPENAI_API_KEY:o==="anthropic"&&(i=process.env.ANTHROPIC_API_KEY),{type:o,baseUrl:s,apiKey:i,model:n}}async function pR(t,e,r,n,o){let s={temperature:n,...o};for(let i=0;i<=Dv;i++)try{return t.type==="anthropic"?await OH(t,e,r,s.temperature):t.type==="ollama"?await PH(t,e,r,s.temperature):await RH(t,e,r,s.temperature,s.disableReasoning,s)}catch(a){let c=a instanceof Error?a.message:String(a);if(!(c.includes("(429)")||c.toLowerCase().includes("rate limit"))||i===Dv)throw a;let u=TH*Math.pow(2,i)+Math.random()*1e3;console.error(`[hive] Rate limited, retrying in ${(u/1e3).toFixed(1)}s (attempt ${i+1}/${Dv})...`),await new Promise(p=>setTimeout(p,u))}throw new Error("Unreachable")}async function PH(t,e,r,n){let o={model:t.model,messages:e.map(m=>{let d={role:m.role,content:m.content??""};return m.tool_calls&&(d.tool_calls=m.tool_calls),m.tool_call_id&&(d.tool_call_id=m.tool_call_id),d}),stream:!1,options:{}};r.length>0&&(o.tools=r),n!==void 0&&(o.options.temperature=n);let s=await fetch(`${t.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let m=await s.text();throw new Error(`Ollama error (${s.status}): ${m}`)}let i=await s.json(),a=i.message;if(!a)throw new Error("Ollama returned no message");let c={role:"assistant",content:a.content||null};if(a.tool_calls&&a.tool_calls.length>0)c.tool_calls=a.tool_calls.map((m,d)=>({id:`ollama_${Date.now()}_${d}`,type:"function",function:{name:m.function.name,arguments:m.function.arguments}}));else if(c.content){let m=fR(c.content,r);m.length>0&&(c.tool_calls=m,c.content=null)}let l=i.prompt_eval_count??0,u=i.eval_count??0,p={promptTokens:l,completionTokens:u,totalTokens:l+u};return{message:c,usage:p}}async function RH(t,e,r,n,o,s){let i={"Content-Type":"application/json"};t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`);let a={model:t.model,messages:e.map(f=>{let h={role:f.role};return f.content!==void 0&&(h.content=f.content),f.tool_calls&&(h.tool_calls=f.tool_calls.map(g=>({id:g.id,type:"function",function:{name:g.function.name,arguments:typeof g.function.arguments=="string"?g.function.arguments:JSON.stringify(g.function.arguments)}}))),f.tool_call_id&&(h.tool_call_id=f.tool_call_id),h})};r.length>0&&(a.tools=r,a.parallel_tool_calls=!0),n!==void 0&&(a.temperature=n),s?.reasoningEffort&&(a.reasoning_effort=s.reasoningEffort);let c=await fetch(`${t.baseUrl}/v1/chat/completions`,{method:"POST",headers:i,body:JSON.stringify(a)});if(!c.ok){let f=await c.text();throw new Error(`OpenAI error (${c.status}): ${f}`)}let l=await c.json(),u=l.choices?.[0]?.message;if(!u)throw new Error("OpenAI returned no choices");let p=u.content??null;p&&(p=p.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||null);let m={role:"assistant",content:p};if(u.tool_calls&&u.tool_calls.length>0)m.tool_calls=u.tool_calls.map(f=>({id:f.id,type:"function",function:{name:f.function.name,arguments:qv(f.function.arguments)}}));else if(m.content&&r.length>0){let f=fR(m.content,r);f.length>0&&(m.tool_calls=f,m.content=null)}let d={promptTokens:l.usage?.prompt_tokens??0,completionTokens:l.usage?.completion_tokens??0,totalTokens:l.usage?.total_tokens??0};return{message:m,usage:d}}async function OH(t,e,r,n){let o,s=[];for(let g of e){if(g.role==="system"){o=g.content??void 0;continue}if(g.role==="assistant"){let v=[];if(g.content&&v.push({type:"text",text:g.content}),g.tool_calls)for(let _ of g.tool_calls)v.push({type:"tool_use",id:_.id??`call_${Date.now()}`,name:_.function.name,input:typeof _.function.arguments=="string"?qv(_.function.arguments):_.function.arguments});s.push({role:"assistant",content:v});continue}if(g.role==="tool"){let v=s[s.length-1],_={type:"tool_result",tool_use_id:g.tool_call_id??"",content:g.content??""};v?.role==="user"&&Array.isArray(v.content)?v.content.push(_):s.push({role:"user",content:[_]});continue}s.push({role:"user",content:g.content??""})}let i=r.map(g=>({name:g.function.name,description:g.function.description,input_schema:g.function.parameters})),a={model:t.model,max_tokens:4096,messages:s};o&&(a.system=o),i.length>0&&(a.tools=i),n!==void 0&&(a.temperature=n);let c=await fetch(`${t.baseUrl}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t.apiKey??"","anthropic-version":"2023-06-01"},body:JSON.stringify(a)});if(!c.ok){let g=await c.text();throw new Error(`Anthropic error (${c.status}): ${g}`)}let l=await c.json(),u={role:"assistant",content:null},p=[],m=[];for(let g of l.content)g.type==="text"?p.push(g.text):g.type==="tool_use"&&m.push({id:g.id,type:"function",function:{name:g.name,arguments:g.input}});p.length>0&&(u.content=p.join(`
400
- `)),m.length>0&&(u.tool_calls=m);let d=l.usage?.input_tokens??0,f=l.usage?.output_tokens??0,h={promptTokens:d,completionTokens:f,totalTokens:d+f};return{message:u,usage:h}}function qv(t){try{return JSON.parse(t)}catch{return{}}}function dR(t){return typeof t.function.arguments=="string"?qv(t.function.arguments):t.function.arguments}function fR(t,e){let r=new Set(e.map(s=>s.function.name)),n=[],o=CH(t);for(let s of o)try{let i=JSON.parse(s),a=Array.isArray(i)?i:[i];for(let c of a)!c||typeof c!="object"||typeof c.name=="string"&&r.has(c.name)&&n.push({id:`text_${Date.now()}_${n.length}`,type:"function",function:{name:c.name,arguments:c.arguments??c.parameters??{}}})}catch{}return n}function CH(t){let e=[],r=t.matchAll(/```(?:json)?\s*\n?([\s\S]*?)```/g);for(let n of r)e.push(n[1].trim());for(let n=0;n<t.length;n++)if(t[n]==="{"||t[n]==="["){let o=t[n]==="{"?"}":"]",s=1,i=n+1;for(;i<t.length&&s>0;)t[i]===t[n]?s++:t[i]===o&&s--,i++;s===0&&(e.push(t.slice(n,i)),n=i-1)}return e}var lR,Dv,TH,Zv=w(()=>{lR={ollama:"http://localhost:11434",openai:"https://api.openai.com",anthropic:"https://api.anthropic.com",groq:"https://api.groq.com/openai",cerebras:"https://api.cerebras.ai"};Dv=5,TH=2e3});function Ha(t,e,r,n,o){let s=[];if(s.push(`You are agent "${t}" with the role of "${e}".`),s.push(""),n){if(s.push(`## Protocol: ${n.protocol.title}`),s.push(""),s.push(`## Your Role: ${n.role.name}`),s.push(n.role.description),s.push(""),s.push(`## Current Phase: ${n.current_phase}`),n.phases[n.current_phase]&&s.push(n.phases[n.current_phase].description),s.push(""),n.rules){let i=n.rules[n.current_phase];if(i){s.push("## Your Steps (follow in order):"),i.loop&&s.push("*Repeat these steps until no work remains, then say DONE.*"),s.push("");for(let a=0;a<i.steps.length;a++){let c=i.steps[a],l=c.hint??c.description??c.action;s.push(`${a+1}. ${l}`)}s.push("")}}if(n.resources){let i=n.resources;if(i.instances&&Array.isArray(i.instances)){s.push("## Available Resources");for(let a of i.instances)s.push(`- ${a}`);s.push("")}if(i.claim_patterns){s.push("## Claim Patterns");for(let[a,c]of Object.entries(i.claim_patterns))s.push(`- ${a}: \`${c}\``);s.push("")}}s.push("## All Phases");for(let[i,a]of Object.entries(n.phases)){let c=i===n.current_phase?" (CURRENT)":a.terminal?" (TERMINAL)":"";s.push(`- **${i}**${c}: ${a.description}`)}if(s.push(""),n.team&&n.team.length>0){s.push("## Team");let i=new Map;for(let a of n.team){let c=i.get(a.role)??[];c.push(a.agent),i.set(a.role,c)}for(let[a,c]of i){let l=a===e?" (your role)":"";s.push(`- **${a}**${l}: ${c.join(", ")}`)}s.push("")}}s.push("## Available Tools"),s.push("");for(let i of r)s.push(`- **${i.function.name}**: ${i.function.description}`);return s.push(""),s.push("## Instructions"),n?(s.push("- Follow the steps above for your role. Use the available tools to complete each step."),s.push("- Work through the workspace files as described in your role description."),s.push('- When you have completed ALL your work and have no more actions to take, respond with just the word "DONE".')):(s.push("- Use the tools to complete your assigned work."),s.push("- Read files before modifying them to understand existing code."),s.push("- Use grep and glob to explore the codebase before making changes."),s.push('- When you have completed your work and have no more actions to take, say "DONE".')),s.push(""),o?.disableReasoning&&(s.push("/no_think"),s.push("")),s.join(`
401
- `)}function mR(t,e,r){return Ha(t,e,r,null)}var hR=w(()=>{});function jH(t){let e=t.conditions.map(r=>r.count>1?`${r.count}x ${r.event}`:r.event).join(" + ");return t.timeout>0?`${e} (timeout: ${t.timeout}s)`:`${e} (no timeout)`}async function MH(t,e){let{startOn:r}=t;if(!r)return;let n=Q({server:t.serverUrl,agentId:t.agentId,namespace:t.namespace}),o=r.timeout>0?Date.now()+r.timeout*1e3:0,s=2e3;for(;o===0||Date.now()<o;){let i=!0;for(let a of r.conditions){let c=await n.getEvents(0,{type:a.event});if(!c.ok){i=!1;break}let l=c.data,u=Array.isArray(l)?l:l?.events;if(!u||u.length<a.count){i=!1;break}}if(i)return;await new Promise(a=>setTimeout(a,s))}e(`Timeout (${r.timeout}s) \u2014 starting anyway`)}var gR,Ba,Uv,IH,AH,NH,zH,Fv,LH,DH,yR,qH,vp,vR=w(()=>{Zv();hR();Xe();gR=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[91m","\x1B[92m","\x1B[93m","\x1B[94m","\x1B[95m","\x1B[96m"],Ba="\x1B[0m",Uv="\x1B[2m",IH=0,AH=new Set(["write_file","patch_file"]),NH=new Set(["incubator_claim","incubator_releaseClaim","incubator_setState","incubator_publishEvent"]),zH=new Set(["publish_event","set_state","get_state","claim_resource","release_resource"]),Fv=[{type:"function",function:{name:"publish_event",description:"Publish a coordination event to notify other agents of progress or milestones",parameters:{type:"object",properties:{type:{type:"string",description:"Event type (e.g. section.written, review.complete)"},data:{type:"string",description:"JSON object with event payload data (optional)"}},required:["type"]}}},{type:"function",function:{name:"set_state",description:"Set a shared state key visible to all agents in this hive",parameters:{type:"object",properties:{key:{type:"string",description:"State key name"},value:{type:"string",description:"Value to set (string or JSON)"}},required:["key","value"]}}},{type:"function",function:{name:"get_state",description:'Get shared state for this hive. Use key="all" to get everything, or a specific key name.',parameters:{type:"object",properties:{key:{type:"string",description:'State key to retrieve, or "all" for all state'}},required:["key"]}}},{type:"function",function:{name:"claim_resource",description:"Claim exclusive ownership of a resource (e.g. a topic, file, or task). Returns rejected if another agent already holds the claim.",parameters:{type:"object",properties:{resource:{type:"string",description:'Resource identifier to claim (e.g. "topic:quantum-computing")'},reason:{type:"string",description:"Why you need this resource"}},required:["resource"]}}},{type:"function",function:{name:"release_resource",description:"Release a previously claimed resource so other agents can use it",parameters:{type:"object",properties:{resource:{type:"string",description:"Resource identifier to release"}},required:["resource"]}}}];LH={cerebras:128e3,groq:128e3,ollama:8e3,openai:128e3,anthropic:2e5},DH=.8,yR=6,qH=3,vp=class{stopFlag=!1;stop(){this.stopFlag=!0}async run(e,r,n,o,s,i){let a=gR[IH++%gR.length],{agentId:c,role:l,provider:u,maxIterations:p}=e,m=0,d=0,f=Date.now(),h={promptTokens:0,completionTokens:0,totalTokens:0},g=[],v=_=>{if(e.verbose){let x=new Date().toISOString().slice(11,23);console.error(`${a} ${x} [${c}] ${_}${Ba}`)}};try{o&&(await o.connect(),v("ACP runtime connected")),e.startOn&&(v(`Waiting for trigger: ${jH(e.startOn)}`),await MH(e,v),v("Trigger conditions met \u2014 starting agent"));let _=[...r.getToolDefs()];if(e.toolFilter&&e.mode==="drone"){let se=new Set(e.toolFilter);_=_.filter(le=>se.has(le.function.name))}if(n){let se=n.getToolDefs(),le=e.coordination??"full";if(le==="lite")se=se.filter(ct=>NH.has(ct.function.name));else if(le==="none")se=[];else if(Array.isArray(le)){let ct=new Set(le);se=se.filter(Ir=>ct.has(Ir.function.name))}_.push(...se),v(`Tools: ${_.length} (env: ${_.length-se.length}, incubator: ${se.length})`)}else o&&!e.noAcpInject?(_.push(...Fv),v(`Tools: ${_.length} (env: ${_.length-Fv.length}, acp: ${Fv.length})`)):v(`Tools: ${_.length} (env only)`);let x=s??null;!x&&o&&(x=await o.fetchProtocol());let k=null;if(o){let se=o.getDanceTools();se&&se.length>0&&(_=[...se],k=new Set(se.map(le=>le.function.name)),v(`Dance tools: ${se.map(le=>le.function.name).join(", ")} (exclusive \u2014 replaced all env/acp tools)`))}let I=e.wakeOn??null;x&&!I&&x.wait&&(I={types:x.wait.types??null,timeout:x.wait.max_timeout??0,maxWakes:50},v(`Derived wakeOn from spec: types=${x.wait.types?.join(",")??"any"}`));let de=x?.context;de!==void 0&&v(`Context retention: ${de===0?"stateless":`last ${de} exchanges`}`);let Y=x?.temperature??e.temperature,ee=x?.reasoning===!1,ge=x?.reasoning_effort,ne=[{role:"system",content:x?Ha(c,l,_,x,{disableReasoning:ee}):mR(c,l,_)},{role:"user",content:e.prompt??"Begin your work. Explore the codebase, understand the task, and implement the required changes."}];v(`Starting (role=${l}, model=${u.model}, mode=${e.mode})`);let rt=()=>{v("SIGTERM received \u2014 killing agent"),this.stopFlag=!0};process.on("SIGTERM",rt);let Mt=e.contextWindow??LH[u.type]??128e3,te=Math.floor(Mt*DH),fe=e.maxRetries??qH;if(I&&o){v("Sleeping \u2014 waiting for initial wake event");let se=await o.waitForWake(I);if(se.length===0)return v("Initial wake timeout \u2014 no events, exiting"),o&&await o.onComplete("Wake timeout",h),process.removeListener("SIGTERM",rt),{iterations:0,usage:h,agentId:c,role:l,status:"completed"};v(`Woke up with ${se.length} event(s)`);let le=o.getLastInject();le&&(ne.push({role:"user",content:`[SYSTEM] ${le}`}),v("Injected dance state context"));for(let ct of se)ne.push({role:"user",content:`[SYSTEM] ${ct}`})}for(;m<p&&!this.stopFlag;){if(m++,v(`Iteration ${m}/${p}`),e.maxTotalTokens&&e.maxTotalTokens>0&&h.totalTokens>=e.maxTotalTokens){v(`Token budget exhausted (${h.totalTokens.toLocaleString()}/${e.maxTotalTokens.toLocaleString()})`);break}if(e.maxRuntime&&e.maxRuntime>0&&Date.now()-f>=e.maxRuntime){v(`Runtime limit reached (${e.maxRuntime}ms)`);break}if(o){let G=await o.beforeIteration(),F=o.getLastInject();if(de!==void 0&&F){if(de===0)ne.length=1;else if(ne.length>1+de*2){let me=ne.slice(-(de*2));ne.length=1,ne.push(...me)}}for(let me of G)ne.push({role:"user",content:`[SYSTEM] ${me}`});F&&ne.push({role:"user",content:`[SYSTEM] ${F}`})}let se,le,ct=0;for(;;){let G=Date.now();try{let F=await pR(u,ne,_,Y,{...ee?{disableReasoning:!0}:{},...ge?{reasoningEffort:ge}:{}});se=F.message,le=F.usage,i?.record("llm_call",{agentId:c,role:l,provider:u.type,model:u.model,promptTokens:le.promptTokens,completionTokens:le.completionTokens,latency_ms:Date.now()-G});break}catch(F){if(ct++,i?.record("llm_error",{agentId:c,role:l,provider:u.type,model:u.model,error:F.message,retryCount:ct,latency_ms:Date.now()-G}),ct>fe)throw F;let me=1e3*Math.pow(2,ct-1);v(`LLM call failed (attempt ${ct}/${fe}): ${F.message} \u2014 retrying in ${me}ms`),await new Promise(Jr=>setTimeout(Jr,me))}}if(ne.push(se),h.promptTokens+=le.promptTokens,h.completionTokens+=le.completionTokens,h.totalTokens+=le.totalTokens,g.push(le),le.totalTokens>0&&v(`Tokens: +${le.promptTokens}/${le.completionTokens} (total: ${h.totalTokens.toLocaleString()})`),le.promptTokens>te&&ne.length>yR+2){v(`Context compaction triggered (${le.promptTokens.toLocaleString()} > ${te.toLocaleString()} threshold)`);let G=ne.slice(-yR);if(ne.length=1,ne.push(...G),o){let F=await o.fetchProtocol();F&&(ne[0]={role:"system",content:Ha(c,l,_,F)});let me=await o.getState();ne.push({role:"user",content:`[SYSTEM] Context was compacted. Current state: ${me}`})}else ne.push({role:"user",content:"[SYSTEM] Context was compacted. Previous messages were trimmed."});v(`Compacted to ${ne.length} messages`)}if(se.content&&v(`${Uv}${se.content}${Ba}${a}`),se.content&&/\bDONE\b/.test(se.content)){v("Agent said DONE \u2014 finishing");break}if(!se.tool_calls||se.tool_calls.length===0){if(I&&o){let G=I.maxWakes??0;if(G>0&&++d>=G){v(`Max wakes reached (${G}) \u2014 exiting`);break}G===0&&d++,v(`Sleeping \u2014 waiting for wake events (cycle ${d})`);let F=await o.waitForWake(I);if(F.length===0){v("Wake timeout \u2014 no events, exiting");break}v(`Woke up with ${F.length} event(s)`);let me=o.getLastInject();me&&(ne.push({role:"user",content:`[SYSTEM] ${me}`}),v("Injected dance state context"));for(let Jr of F)ne.push({role:"user",content:`[SYSTEM] ${Jr}`});continue}v("No tool calls \u2014 agent finished");break}let Ir=!1;for(let G of se.tool_calls){let F=G.function.name,me=dR(G),Jr=Object.keys(me).length>0?`(${Object.entries(me).map(([Oe,Ar])=>`${Oe}=${JSON.stringify(Ar)}`).join(", ")})`:"()";if(v(`Tool: ${F}${Jr}`),o&&AH.has(F)&&me.path){let Oe=await o.onFileWrite(me.path);if(Oe){ne.push({role:"tool",content:Oe,tool_call_id:G.id??`call_${m}`}),v(`${Uv}\u2192 claim conflict: ${Oe}${Ba}${a}`);continue}}let Be;if(k&&k.has(F)&&o)try{let Oe=await o.callDanceTool(F,me);Be=JSON.stringify(Oe)}catch(Oe){Be=JSON.stringify({error:`Dance tool failed: ${Oe.message}`})}else if(o&&zH.has(F))if(F==="publish_event"){let Oe={};if(me.data)try{Oe=typeof me.data=="string"?JSON.parse(me.data):me.data}catch{}Be=await o.publishEvent(me.type,Oe)}else F==="set_state"?Be=await o.setState(me.key,me.value):F==="get_state"?Be=await o.getState():F==="claim_resource"?Be=await o.claimResource(me.resource,me.reason):F==="release_resource"?Be=await o.releaseResource(me.resource):Be=JSON.stringify({error:`Unknown synthetic tool: ${F}`});else if(n&&n.hasToolName(F))Be=await n.callTool(F,me);else try{Be=await r.callTool(F,me)}catch(Oe){Be=JSON.stringify({error:`Tool call failed: ${Oe.message}`})}if(v(`${Uv}\u2192 ${Be}${Ba}${a}`),ne.push({role:"tool",content:Be,tool_call_id:G.id??`call_${m}`}),o){let Oe=await o.checkControl();if(Oe.halted){v(`HALTED: ${Oe.reason??"no reason"}`),Ir=!0;break}if(Oe.paused){v(`PAUSED: ${Oe.reason??"no reason"} \u2014 waiting...`);let Ar=await o.waitForResume();v(`RESUMED: ${Ar}`),ne.push({role:"user",content:`[SYSTEM] You were paused (reason: ${Oe.reason??"unknown"}). You have been resumed (reason: ${Ar}). Continue your work.`})}}}if(Ir)return v("Agent halted \u2014 exiting loop"),o&&await o.onComplete("Agent halted",h),{agentId:c,role:l,status:"completed",iterations:m,usage:h,iterationUsage:g};if(m%10===0&&o){let G=await o.fetchProtocol();if(G){let F=Ha(c,l,_,G);ne[0]={role:"system",content:F},v("Refreshed system prompt")}}}this.stopFlag?v("Stopped by runner"):m>=p&&v(`Hit max iterations (${p})`),process.off("SIGTERM",rt);let Lt=`Agent ${c} completed after ${m} iterations (${h.totalTokens.toLocaleString()} tokens)`;return o&&await o.onComplete(Lt,h),i?.record("agent_complete",{agentId:c,role:l,status:"completed",iterations:m,promptTokens:h.promptTokens,completionTokens:h.completionTokens,totalTokens:h.totalTokens,duration_ms:Date.now()-f}),v(`Done (${m} iterations, ${h.totalTokens.toLocaleString()} tokens)`),{agentId:c,role:l,status:"completed",iterations:m,usage:h,iterationUsage:g}}catch(_){try{process.off("SIGTERM",()=>{})}catch{}let x=_.message;if(e.verbose&&console.error(`${a} [${c}] ERROR: ${x}${Ba}`),o)try{await o.onComplete(`Error: ${x}`,h)}catch{}return i?.record("agent_complete",{agentId:c,role:l,status:"error",iterations:m,error:x,totalTokens:h.totalTokens,duration_ms:Date.now()-f}),{agentId:c,role:l,status:"error",iterations:m,error:x,usage:h,iterationUsage:g}}}}});var _p,_R=w(()=>{jv();_p=class{entries;entryMap;defs;constructor(e,r,n,o){let s=zv(e,r,n);if(o){let i=new Set(o);s=s.filter(a=>i.has(a.def.function.name))}this.entries=s,this.entryMap=new Map(s.map(i=>[i.def.function.name,i])),this.defs=s.map(i=>i.def)}getToolDefs(){return this.defs}hasToolName(e){return this.entryMap.has(e)}async callTool(e,r){let n=this.entryMap.get(e);if(!n)return JSON.stringify({error:`Unknown tool: ${e}`});let o=await n.handler(r);return o.content&&o.content.length>0?o.content.map(s=>s.text??"").join(`
402
- `):JSON.stringify(o)}async close(){}}});import{randomBytes as ZH}from"node:crypto";function UH(t,e){let r=Object.keys(t.roles),n=r.includes(e)?e:r[0],o=t.roles[n];if(!o)return null;let s={};for(let[f,h]of Object.entries(t.phases))s[f]={description:h.description,...h.terminal?{terminal:!0}:{}};let i=Object.keys(s),a=t.rules?.[n],c={};if(a)for(let[f,h]of Object.entries(a)){let g=h;c[f]=g}let l=o,u=l.wait,p=l.context,m=l.temperature,d=l.reasoning;return{protocol:{name:t.name,title:t.title},role:{name:n,description:o.description},current_phase:i[0]??"default",instructions:`Follow the ${t.title} protocol as the ${n} role.`,phases:s,...t.governance?{governance:t.governance}:{},...Object.keys(c).length>0?{rules:c}:{},...t.resources?{resources:t.resources}:{},...u?{wait:u}:{},...p!==void 0?{context:p}:{},...m!==void 0?{temperature:m}:{},...d!==void 0?{reasoning:d}:{}}}var bp,bR=w(()=>{cR();vR();_R();Zv();bp=class{agents=new Map;async startAgent(e,r){let n=ZH(3).toString("hex"),o=`${e.role}_${n}`,s=(e.modelHint&&r.models?.[e.modelHint])??r.models?.[e.role]??r.provider??"ollama/qwen3:8b",i=uR(s),a=r.protocolData??this.buildProtocolData(r.registry,r.namespace,e.role),c={stores:r.stores,bus:r.bus,namespace:r.namespace,agentId:o,role:e.role,maxIterations:50,verbose:r.verbose,danceModule:r.danceModule,protocolData:a??void 0},l=new yp(c),u=e.tools&&e.tools!=="all"?e.tools:null,p=new _p(r.workDir,r.guard,r.verbose,u),m={agentId:o,role:e.role,provider:i,serverUrl:"direct://localhost",namespace:r.namespace,maxIterations:50,verbose:r.verbose,mode:"worker",workDir:r.workDir,noAcp:!1,toolFilter:u,coordination:e.coordination,startOn:e.startOn??null,wakeOn:e.wakeOn??null,prompt:e.prompt};r.telemetry?.record("agent_spawn",{agentId:o,role:e.role,provider:s,type:"worker",inProcess:!0});let d=new vp,f=d.run(m,p,null,l,a,r.telemetry).finally(()=>{l.disconnect().catch(()=>{}),p.close().catch(()=>{})});return this.agents.set(o,{promise:f,runner:d,runtime:l,agentId:o,role:e.role}),o}async killAgent(e){let r=this.agents.get(e);if(r){r.runner.stop();try{await Promise.race([r.promise,new Promise(n=>setTimeout(n,5e3))])}catch{}this.agents.delete(e)}}async shutdown(){for(let r of this.agents.values())r.runner.stop();let e=[...this.agents.values()].map(r=>r.promise.catch(()=>{}));await Promise.race([Promise.all(e),new Promise(r=>setTimeout(r,1e4))]),this.agents.clear()}getAgents(){return[...this.agents.values()].map(e=>({agentId:e.agentId,role:e.role,type:"worker"}))}async waitForAll(){let e=[];for(let r of this.agents.values())try{e.push(await r.promise)}catch(n){e.push({agentId:r.agentId,role:r.role,status:"error",iterations:0,error:n.message})}return e}get size(){return this.agents.size}buildProtocolData(e,r,n){let o=e.getProtocol(r);return o?UH(o,n):null}}});import{spawn as Hv}from"node:child_process";import{randomBytes as wR}from"node:crypto";import{dirname as FH,join as HH}from"node:path";import{fileURLToPath as BH}from"node:url";function Bv(t){return new Promise(e=>setTimeout(e,t))}var VH,GH,Va,xR=w(()=>{bR();VH=FH(BH(import.meta.url)),GH=HH(VH,"..","plugin"),Va=class{config;incubatorPort;bus;runs;verbose;stores;registry;danceModule;telemetry;children=new Map;childInfo=[];propolisPid;pool;constructor(e,r,n,o,s=!1,i,a,c,l){this.config=e,this.incubatorPort=r,this.bus=n,this.runs=o,this.verbose=s,this.stores=i,this.registry=a,this.danceModule=c,this.telemetry=l}log(e){this.verbose&&console.error(`[orchestrator] ${e}`)}get hiveEntry(){return this.config.hiveEntry??this.config.droneEntry??""}get propolisEntry(){return this.config.propolisEntry?this.config.propolisEntry:this.config.hiveEntry??""}async start(){this.telemetry?.record("protocol_start",{agentCount:this.config.agents.reduce((r,n)=>r+(n.count??1),0),provider:this.config.provider}),this.config.agents.some(r=>r.type==="drone")&&(await this.spawnPropolis(),await Bv(1500)),await this.spawnAgents()}async spawnPropolis(){let e=this.propolisEntry,{propolisPort:r,worktree:n,env:o}=this.config,s=["--http",`--port=${r}`,`--work-dir=${n}`,"--no-guard"],i={...process.env,...o},a=Hv(process.execPath,[e,...s],{env:i,cwd:n,stdio:["ignore","pipe","pipe"]});a.stderr?.on("data",c=>{let l=c.toString().trim();l&&this.log(`[propolis] ${l}`)}),a.on("exit",c=>{this.children.delete("propolis"),c!==null&&c!==0&&this.log(`Propolis exited with code ${c}`)}),a.pid&&(this.children.set("propolis",a),this.propolisPid=a.pid,this.log(`Propolis started on port ${r} (pid ${a.pid})`))}get canRunInProcess(){return!!(this.stores&&this.bus&&this.registry)}async spawnAgents(){let{propolisPort:e,worktree:r}=this.config,n=this.config,o=0,s;this.canRunInProcess&&(this.pool=new bp,s={stores:this.stores,bus:this.bus,registry:this.registry,namespace:"default",workDir:r,guard:null,verbose:this.verbose,danceModule:this.danceModule,provider:n.provider,models:n.models,telemetry:this.telemetry});for(let i of n.agents){let a=i.count??1,c=i.type??"worker";for(let l=0;l<a;l++){let u=n.stagger*1e3;if(o>0&&u>0&&await Bv(u),o++,c==="claude"){let _=wR(3).toString("hex"),x=`${i.role}_${_}`;this.spawnClaude(i,x,n);continue}if(c==="worker"&&this.pool&&s){let _=await this.pool.startAgent(i,s);this.childInfo.push({agentId:_,role:i.role,type:"worker",inProcess:!0});let x=(i.modelHint&&n.models?.[i.modelHint])??n.models?.[i.role]??n.provider??"ollama/qwen3:8b";this.telemetry?.record("agent_spawn",{agentId:_,role:i.role,provider:x,type:"worker",inProcess:!0}),this.log(`Worker ${_} (${i.role}) started in-process \u2192 ${x}`);continue}let p=wR(3).toString("hex"),m=`${i.role}_${p}`,d=(i.modelHint&&n.models?.[i.modelHint])??n.models?.[i.role]??n.provider??"ollama/qwen3:8b",h=[`--server=${n.tls?"https":"http"}://localhost:${this.incubatorPort}`,"--namespace=default",`--agent-id=${m}`,`--role=${i.role}`,`--provider=${d}`,"--verbose"];if(c==="worker"?(h.push("--mode=worker"),h.push(`--work-dir=${r}`)):(h.push("--mode=drone"),h.push(`--propolis=http://localhost:${e}`)),n.protocolPath&&h.push(`--protocol=${n.protocolPath}`),n.noAcp&&h.push("--no-acp"),i.tools&&i.tools!=="all"&&h.push(`--tools=${i.tools.join(",")}`),i.coordination){let _=Array.isArray(i.coordination)?i.coordination.join(","):i.coordination;h.push(`--coordination=${_}`)}i.startOn&&h.push(`--start-on=${JSON.stringify(i.startOn)}`),i.wakeOn&&h.push(`--wake-on=${JSON.stringify(i.wakeOn)}`);let g={...process.env,...n.env,...n.tls?{NODE_TLS_REJECT_UNAUTHORIZED:"0"}:{}};i.prompt&&(g.AGENT_PROMPT=i.prompt);let v=Hv(process.execPath,[this.hiveEntry,...h],{env:g,cwd:r,stdio:["ignore","pipe","pipe"]});v.stderr?.on("data",_=>{let x=_.toString().trim();x&&this.log(`[${m}] ${x}`)}),v.on("exit",_=>{this.children.delete(`${c}:${m}`);let x=_===0?"completed":`exited with code ${_}`;this.log(`[${m}] ${x}`)}),v.pid&&(this.children.set(`${c}:${m}`,v),this.childInfo.push({pid:v.pid,agentId:m,role:i.role,type:c}),this.telemetry?.record("agent_spawn",{agentId:m,role:i.role,provider:d,type:c,pid:v.pid}),this.log(`${c==="worker"?"Worker":"Drone"} ${m} (${i.role}) started \u2192 ${d} (pid ${v.pid})`))}}}spawnClaude(e,r,n){let{worktree:o}=n,s=(e.modelHint&&n.models?.[e.modelHint])??n.models?.[e.role]??e.modelHint??void 0,i=e.prompt??`You are assigned the role "${e.role}" in an ACP coordination protocol. Use the acp MCP tool to coordinate with other agents. Follow the protocol instructions injected at session start.`,a=e.pluginDir??GH,c=["--print","--dangerously-skip-permissions","-p",i,"--plugin-dir",a];s&&c.push("--model",s);let l={...process.env,...n.env,INCUBATOR_URL:`${n.tls?"https":"http"}://localhost:${this.incubatorPort}`,...n.tls?{NODE_TLS_REJECT_UNAUTHORIZED:"0"}:{},ACP_NAMESPACE:"default",ACP_AGENT_ID:r,ACP_ROLE:e.role};e.wakeOn?.types&&(l.ACP_WAKE_ON=e.wakeOn.types.join(","));let u=Hv("claude",c,{env:l,cwd:o,stdio:["ignore","pipe","pipe"]});u.stdout?.on("data",p=>{let m=p.toString().trim();m&&this.log(`[${r}:out] ${m}`)}),u.stderr?.on("data",p=>{let m=p.toString().trim();m&&this.log(`[${r}:err] ${m}`)}),u.on("exit",p=>{this.children.delete(`claude:${r}`);let m=p===0?"completed":`exited with code ${p}`;this.log(`[${r}] ${m}`)}),u.pid&&(this.children.set(`claude:${r}`,u),this.childInfo.push({pid:u.pid,agentId:r,role:e.role,type:"claude"}),this.telemetry?.record("agent_spawn",{agentId:r,role:e.role,type:"claude",pid:u.pid}),this.log(`Claude ${r} (${e.role}) started (pid ${u.pid})`))}getAgents(){return[...this.childInfo]}async killAgent(e){if(this.pool&&this.pool.getAgents().some(o=>o.agentId===e)){await this.pool.killAgent(e),this.log(`Stopped pool agent ${e}`);return}let r=this.children.get(`worker:${e}`)??this.children.get(`drone:${e}`)??this.children.get(`claude:${e}`);r&&(r.kill("SIGTERM"),this.log(`Sent SIGTERM to ${e}`),setTimeout(()=>{r.killed||(r.kill("SIGKILL"),this.log(`Sent SIGKILL to ${e} (did not exit gracefully)`))},5e3))}async shutdown(){this.telemetry?.record("protocol_end",{agentCount:this.childInfo.length,status:"shutdown"}),this.log("Shutting down agents..."),this.pool&&(await this.pool.shutdown(),this.log("Stopped all pool agents"));for(let[r,n]of this.children)(r.startsWith("drone:")||r.startsWith("worker:")||r.startsWith("claude:"))&&(n.kill("SIGTERM"),this.log(`Stopped ${r}`));await Bv(500);let e=this.children.get("propolis");e&&(e.kill("SIGTERM"),this.log("Stopped propolis")),this.children.clear(),this.childInfo=[]}}});import{createHmac as WH}from"node:crypto";var wp,SR=w(()=>{wp=class{unsubscribers=[];verbose;constructor(e=!1){this.verbose=e}register(e,r,n){for(let o of r){let s=o.events?new Set(o.events):null,i=n.subscribe(e,a=>{s&&!s.has(a.type)||this.fire(o,a).catch(c=>{this.verbose&&console.error(`[webhooks] Failed to deliver to ${o.url}: ${c.message}`)})});this.unsubscribers.push(i)}this.verbose&&r.length>0&&console.error(`[webhooks] Registered ${r.length} webhook(s) for namespace "${e}"`)}close(){for(let e of this.unsubscribers)e();this.unsubscribers=[]}async fire(e,r){let n=JSON.stringify({event:r.type,data:r.data,publishedBy:r.publishedBy,publishedAt:r.publishedAt,id:r.id}),o={"Content-Type":"application/json",...e.headers};if(e.secret){let a=WH("sha256",e.secret).update(n).digest("hex");o["X-Webhook-Signature"]=a}let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{await fetch(e.url,{method:"POST",headers:o,body:n,signal:s.signal})}finally{clearTimeout(i)}}}});var Vv={};X(Vv,{getRedisClient:()=>KH,waitForReady:()=>YH});import{createRequire as JH}from"node:module";function KH(t){let e=$R.get(t);if(e)return e;let n=JH(import.meta.url)("ioredis"),o=new n(t);return $R.set(t,o),o}async function YH(t){if(t.status!=="ready")return new Promise((e,r)=>{let n=()=>{s(),e()},o=i=>{s(),r(i)},s=()=>{t.removeListener("ready",n),t.removeListener("error",o)};t.once("ready",n),t.once("error",o)})}var $R,Gv=w(()=>{$R=new Map});var kR={};X(kR,{IPCTransport:()=>Wv});import{connect as XH}from"node:net";var Wv,ER=w(()=>{Wv=class{socket=null;handlers=new Map;buffer="";opts;constructor(e){this.opts=e}async connect(){return new Promise((e,r)=>{let n=XH(this.opts.socketPath,()=>{this.socket=n,this.send({type:"register",hive:this.opts.hiveName,publishes:this.opts.publishes,subscribes:this.opts.subscribes}),e()});n.setEncoding("utf8"),n.on("data",o=>this.onData(o)),n.on("error",o=>{this.socket||r(o)})})}async publish(e,r){this.send({type:"event",hive:this.opts.hiveName,topic:e,event:r})}subscribe(e,r){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(r),()=>{n.delete(r),n.size===0&&this.handlers.delete(e)}}async close(){this.handlers.clear(),this.socket&&(this.socket.end(),this.socket=null)}send(e){this.socket&&this.socket.write(JSON.stringify(e)+`
399
+ `).trim()}var B9,G9,ni,bp,fR=w(()=>{Ha();Fa();B9=/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.|169\.254\.|::1|fc|fd|fe80)/i,G9=/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])/i;ni=512*1024,bp=3e4});function Uv(t,e,r){return[{def:{type:"function",function:{name:"read_file",description:"Read a file relative to the working directory",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to working directory"}},required:["path"]}}},schema:{path:M.string().describe("File path relative to working directory")},handler:n=>WP(n,t,e,r)},{def:{type:"function",function:{name:"write_file",description:"Write content to a file. Creates parent directories automatically.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to working directory"},content:{type:"string",description:"Content to write"}},required:["path","content"]}}},schema:{path:M.string().describe("File path relative to working directory"),content:M.string().describe("Content to write")},handler:n=>JP(n,t,e,r)},{def:{type:"function",function:{name:"patch_file",description:"Find and replace text in a file. The search string must match exactly.",parameters:{type:"object",properties:{path:{type:"string",description:"File path relative to working directory"},search:{type:"string",description:"Exact text to find"},replace:{type:"string",description:"Text to replace with"}},required:["path","search","replace"]}}},schema:{path:M.string().describe("File path relative to working directory"),search:M.string().describe("Exact text to find"),replace:M.string().describe("Text to replace with")},handler:n=>KP(n,t,e,r)},{def:{type:"function",function:{name:"list_files",description:"List files in a directory. Skips node_modules, .git, and similar directories.",parameters:{type:"object",properties:{path:{type:"string",description:"Directory path relative to working directory (default: root)"},recursive:{type:"string",description:"List recursively (default: false)"}},required:[]}}},schema:{path:M.string().optional().describe("Directory path relative to working directory (default: root)"),recursive:M.boolean().optional().describe("List recursively (default: false)")},handler:n=>YP(n,t,e,r)},{def:{type:"function",function:{name:"glob",description:'Find files matching a glob pattern (e.g. "**/*.ts")',parameters:{type:"object",properties:{pattern:{type:"string",description:"Glob pattern to match"},path:{type:"string",description:"Base directory for the search"}},required:["pattern"]}}},schema:{pattern:M.string().describe("Glob pattern to match"),path:M.string().optional().describe("Base directory for the search")},handler:n=>XP(n,t,e,r)},{def:{type:"function",function:{name:"grep",description:"Search file contents using a regex pattern",parameters:{type:"object",properties:{pattern:{type:"string",description:"Regex pattern to search for"},path:{type:"string",description:"Directory to search in"},glob:{type:"string",description:'File glob filter (e.g. "*.ts")'}},required:["pattern"]}}},schema:{pattern:M.string().describe("Regex pattern to search for"),path:M.string().optional().describe("Directory to search in"),glob:M.string().optional().describe('File glob filter (e.g. "*.ts")')},handler:n=>eR(n,t,e,r)},{def:{type:"function",function:{name:"run",description:"Execute a shell command. 60s timeout, 100KB output cap.",parameters:{type:"object",properties:{command:{type:"string",description:"Shell command to execute"},cwd:{type:"string",description:"Working directory relative to sandbox root"},timeout:{type:"string",description:"Timeout in milliseconds (default: 60000)"}},required:["command"]}}},schema:{command:M.string().describe("Shell command to execute"),cwd:M.string().optional().describe("Working directory relative to sandbox root"),timeout:M.number().optional().describe("Timeout in milliseconds (default: 60000)")},handler:n=>rR(n,t,e,r)},{def:{type:"function",function:{name:"git_status",description:"Show git status (porcelain format)",parameters:{type:"object",properties:{},required:[]}}},schema:{},handler:()=>sR({},t)},{def:{type:"function",function:{name:"git_diff",description:"Show git diff. Optionally for a specific path or staged changes.",parameters:{type:"object",properties:{path:{type:"string",description:"File path to diff"},staged:{type:"string",description:"Show staged changes"}},required:[]}}},schema:{path:M.string().optional().describe("File path to diff"),staged:M.boolean().optional().describe("Show staged changes")},handler:n=>iR(n,t,e,r)},{def:{type:"function",function:{name:"git_commit",description:"Stage files and create a git commit",parameters:{type:"object",properties:{message:{type:"string",description:"Commit message"},files:{type:"string",description:"Comma-separated file paths to stage (default: all)"}},required:["message"]}}},schema:{message:M.string().describe("Commit message"),files:M.string().optional().describe("Comma-separated file paths to stage (default: all)")},handler:n=>aR(n,t,e,r)},{def:{type:"function",function:{name:"git_log",description:"Show recent git commits (oneline format)",parameters:{type:"object",properties:{count:{type:"string",description:"Number of commits to show (default: 10)"}},required:[]}}},schema:{count:M.number().optional().describe("Number of commits to show (default: 10)")},handler:n=>cR(n,t)},{def:{type:"function",function:{name:"fetch",description:"Make an HTTP request. Returns status, headers, and body. Blocks localhost/private IPs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL to fetch"},method:{type:"string",description:"HTTP method (default: GET)"},body:{type:"string",description:"Request body (for POST/PUT/PATCH)"}},required:["url"]}}},schema:{url:M.string().describe("URL to fetch"),method:M.string().optional().describe("HTTP method (default: GET)"),body:M.string().optional().describe("Request body (for POST/PUT/PATCH)")},handler:n=>pR(n,t,e,r)},{def:{type:"function",function:{name:"scrape_page",description:"Fetch a web page and extract readable text (strips HTML tags, scripts, styles). Blocks localhost/private IPs.",parameters:{type:"object",properties:{url:{type:"string",description:"URL of the page to scrape"}},required:["url"]}}},schema:{url:M.string().describe("URL of the page to scrape")},handler:n=>dR(n,t,e,r)}]}var Fv=w(()=>{Fu();tR();nR();lR();fR()});function mR(t){return t===void 0||t===!1||t===null?null:t===!0?{types:null,timeout:0,pureDelay:!1}:typeof t=="string"?{types:[t],timeout:0,pureDelay:!1}:Array.isArray(t)?{types:t.length>0?t:null,timeout:0,pureDelay:!1}:typeof t=="number"?{types:null,timeout:t,pureDelay:!0}:{types:t.types&&t.types.length>0?t.types:null,timeout:t.timeout??0,pureDelay:!1}}var hR=w(()=>{Fv()});function Hv(t){let e=new Set,r=[];for(let n of t)if(n.includes("*")){let o=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,"[^.]*");r.push(new RegExp("^"+o+"$"))}else e.add(n);return r.length===0?n=>e.has(n):n=>e.has(n)||r.some(o=>o.test(n))}var gR=w(()=>{});function Bv(t){let e=typeof t.data=="string"?t.data:JSON.stringify(t.data);return`Event from ${t.publishedBy}: [${t.type}] ${e}`}var wp,yR=w(()=>{Ko();hR();gR();wp=class{stores;bus;namespace;agentId;role;maxIterations;verbose;danceModule;protocolData;iterationCount=0;eventBuffer=[];unsubscribe;claimedResources=new Set;cachedInject=null;lastEventCursor=0;constructor(e){this.stores=e.stores,this.bus=e.bus,this.namespace=e.namespace,this.agentId=e.agentId,this.role=e.role,this.maxIterations=e.maxIterations,this.verbose=e.verbose??!1,this.danceModule=e.danceModule,this.protocolData=e.protocolData}async connect(){await this.stores.roles.assign(this.agentId,this.role),await this.stores.runs.start(this.agentId,this.role),this.unsubscribe=this.bus.subscribe(this.namespace,e=>{e.publishedBy!==this.agentId&&this.eventBuffer.push(Bv(e))})}async disconnect(){for(let e of this.claimedResources)try{await this.stores.claims.release(e,this.agentId)}catch{}this.claimedResources.clear(),this.unsubscribe&&(this.unsubscribe(),this.unsubscribe=void 0)}async waitForWake(e){await this.refreshInjectCache(),await this.replayMissedEvents();let r=this.drainMatchingEvents(e.types??null);if(r.length>0)return r;let n=e.timeout&&e.timeout>0?e.timeout:0;return new Promise(o=>{let s,i,a=()=>{s&&clearTimeout(s),i&&i()};i=this.bus.subscribe(this.namespace,c=>{if(c.publishedBy===this.agentId)return;let l=Bv(c);if(e.types&&!Hv(e.types)(c.type)){this.eventBuffer.push(l);return}a(),this.refreshInjectCache().then(()=>o([l]))}),n>0&&(s=setTimeout(()=>{a(),o([])},n))})}getLastInject(){let e=this.cachedInject;return this.cachedInject=null,e}async callDanceTool(e,r){if(!this.danceModule)throw new Error("No dance module loaded");let n=this.buildDanceHelper(),o=async()=>this.getStateMap(),s=await Av(this.danceModule,e,r,this.role,this.agentId,o,n);if("error"in s||!s.wait)return s;let i=mR(s.wait);if(!i)return s;let{wait:a,...c}=s;try{let{cursor:p}=await this.stores.events.getEvents();this.lastEventCursor=p}catch{}this.eventBuffer=[];let l=[];i.pureDelay?await new Promise(p=>setTimeout(p,i.timeout)):l=await this.waitForWake({types:i.types??void 0,timeout:i.timeout});let u=this.getLastInject();return{...c,wakeEvents:l,...u?{inject:u}:{}}}getDanceTools(){if(!this.danceModule)return null;let e=Cv(this.danceModule);return e.length>0?e:null}async beforeIteration(){this.iterationCount++,await this.stores.progress.report(this.agentId,this.agentId,this.iterationCount/this.maxIterations,`Iteration ${this.iterationCount}/${this.maxIterations}`);let e=[...this.eventBuffer];this.eventBuffer=[];let r=await this.stores.messages.getFor(this.agentId);for(let n of r)e.push(`Message from ${n.from}: ${n.content}`);return this.danceModule&&await this.refreshInjectCache(),e}async onFileWrite(e){let r=await this.stores.claims.claim(e,e,this.agentId,3e5);if(r.status==="approved")return this.claimedResources.add(e),null;let n=r.claim?.owner??"another agent";return JSON.stringify({error:`File "${e}" is claimed by ${n}`})}async onComplete(e,r){await this.stores.runs.complete(this.agentId,{status:"completed",summary:e,iterations:this.iterationCount,usage:r});for(let n of this.claimedResources)try{await this.stores.claims.release(n,this.agentId)}catch{}this.claimedResources.clear()}async fetchProtocol(){return this.protocolData??null}async publishEvent(e,r={}){try{return await this.stores.events.publish(e,r,this.agentId),JSON.stringify({published:!0,type:e})}catch(n){return JSON.stringify({error:`publishEvent failed: ${n.message}`})}}async setState(e,r){try{return await this.stores.state.set(e,r,this.agentId),JSON.stringify({ok:!0,key:e})}catch(n){return JSON.stringify({error:`setState failed: ${n.message}`})}}async getState(){try{let e=await this.stores.state.query(),r={};for(let n of e)r[n.key]=n.value;return JSON.stringify(r)}catch(e){return JSON.stringify({error:`getState failed: ${e.message}`})}}async claimResource(e,r){try{let n=await this.stores.claims.claim(e,r??e,this.agentId,3e5);if(n.status==="approved")return this.claimedResources.add(e),JSON.stringify({status:"approved",resource:e});let o=n.claim?.owner??"another agent";return JSON.stringify({status:"rejected",resource:e,owner:o,message:`Already claimed by ${o}`})}catch(n){return JSON.stringify({error:`claimResource failed: ${n.message}`})}}async releaseResource(e){try{return await this.stores.claims.release(e,this.agentId),this.claimedResources.delete(e),JSON.stringify({released:!0,resource:e})}catch(r){return JSON.stringify({error:`releaseResource failed: ${r.message}`})}}async checkControl(){let e=this.stores.control.getStatus(this.agentId);return{halted:e.halted,paused:e.paused,reason:e.haltReason??e.pauseReason}}async waitForResume(e=2e3){for(;;)if(await new Promise(n=>setTimeout(n,e)),!this.stores.control.getStatus(this.agentId).paused)return"resumed"}async replayMissedEvents(){try{let{events:e,cursor:r}=await this.stores.events.getEvents(this.lastEventCursor);this.lastEventCursor=r;for(let n of e){if(n.publishedBy===this.agentId)continue;let o=Bv(n);this.eventBuffer.includes(o)||this.eventBuffer.push(o)}}catch{}}drainMatchingEvents(e){if(this.eventBuffer.length===0)return[];if(!e){let s=[...this.eventBuffer];return this.eventBuffer=[],s}let r=Hv(e),n=[],o=[];for(let s of this.eventBuffer){let i=s.match(/\[([^\]]+)\]/);i&&r(i[1])?n.push(s):o.push(s)}return this.eventBuffer=o,n}async getStateMap(){let e=await this.stores.state.query(),r={};for(let n of e)r[n.key]=typeof n.value=="string"?n.value:JSON.stringify(n.value);return r}buildDanceHelper(){return Iv({publishEvent:async(e,r,n,o)=>{await this.stores.events.publish(r,n,o??this.agentId)},claimResource:async(e,r,n,o)=>(await this.stores.claims.claim(r,r,n,o)).status,releaseResource:async(e,r)=>{await this.stores.claims.release(r,this.agentId)},setState:async(e,r,n)=>{await this.stores.state.set(r,n,this.agentId)}},this.namespace,this.agentId)}async refreshInjectCache(){if(!this.danceModule)return;let e=await this.getStateMap();this.cachedInject=Nv(this.danceModule,e,this.role,this.agentId)}}});function _R(t){let e=t.indexOf("/");if(e===-1)throw new Error(`Invalid provider shorthand "${t}". Use format: provider/model (e.g. ollama/qwen3:32b, openai/gpt-4o, anthropic/claude-sonnet-4-5-20250929)`);let r=t.slice(0,e),n=t.slice(e+1);if(!n)throw new Error(`Missing model in provider shorthand "${t}"`);let o=r==="ollama"?"ollama":r==="anthropic"?"anthropic":"openai",s=vR[r]??vR.openai;if(o==="ollama"&&process.env.OLLAMA_HOST){let a=process.env.OLLAMA_HOST;s=a.startsWith("http")?a:`http://${a}`}let i;return r==="cerebras"?i=process.env.CEREBRAS_API_KEY:r==="groq"?i=process.env.GROQ_API_KEY:o==="openai"?i=process.env.OPENAI_API_KEY:o==="anthropic"&&(i=process.env.ANTHROPIC_API_KEY),{type:o,baseUrl:s,apiKey:i,model:n}}async function bR(t,e,r,n,o){let s={temperature:n,...o};for(let i=0;i<=Gv;i++)try{return t.type==="anthropic"?await Y9(t,e,r,s.temperature):t.type==="ollama"?await J9(t,e,r,s.temperature):await K9(t,e,r,s.temperature,s.disableReasoning,s)}catch(a){let c=a instanceof Error?a.message:String(a);if(!(c.includes("(429)")||c.toLowerCase().includes("rate limit"))||i===Gv)throw a;let u=W9*Math.pow(2,i)+Math.random()*1e3;console.error(`[hive] Rate limited, retrying in ${(u/1e3).toFixed(1)}s (attempt ${i+1}/${Gv})...`),await new Promise(p=>setTimeout(p,u))}throw new Error("Unreachable")}async function J9(t,e,r,n){let o={model:t.model,messages:e.map(f=>{let d={role:f.role,content:f.content??""};return f.tool_calls&&(d.tool_calls=f.tool_calls),f.tool_call_id&&(d.tool_call_id=f.tool_call_id),d}),stream:!1,options:{}};r.length>0&&(o.tools=r),n!==void 0&&(o.options.temperature=n);let s=await fetch(`${t.baseUrl}/api/chat`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let f=await s.text();throw new Error(`Ollama error (${s.status}): ${f}`)}let i=await s.json(),a=i.message;if(!a)throw new Error("Ollama returned no message");let c={role:"assistant",content:a.content||null};if(a.tool_calls&&a.tool_calls.length>0)c.tool_calls=a.tool_calls.map((f,d)=>({id:`ollama_${Date.now()}_${d}`,type:"function",function:{name:f.function.name,arguments:f.function.arguments}}));else if(c.content){let f=xR(c.content,r);f.length>0&&(c.tool_calls=f,c.content=null)}let l=i.prompt_eval_count??0,u=i.eval_count??0,p={promptTokens:l,completionTokens:u,totalTokens:l+u};return{message:c,usage:p}}async function K9(t,e,r,n,o,s){let i={"Content-Type":"application/json"};t.apiKey&&(i.Authorization=`Bearer ${t.apiKey}`);let a={model:t.model,messages:e.map(m=>{let h={role:m.role};return m.content!==void 0&&(h.content=m.content),m.tool_calls&&(h.tool_calls=m.tool_calls.map(g=>({id:g.id,type:"function",function:{name:g.function.name,arguments:typeof g.function.arguments=="string"?g.function.arguments:JSON.stringify(g.function.arguments)}}))),m.tool_call_id&&(h.tool_call_id=m.tool_call_id),h})};r.length>0&&(a.tools=r,a.parallel_tool_calls=!0),n!==void 0&&(a.temperature=n),s?.reasoningEffort&&(a.reasoning_effort=s.reasoningEffort);let c=await fetch(`${t.baseUrl}/v1/chat/completions`,{method:"POST",headers:i,body:JSON.stringify(a)});if(!c.ok){let m=await c.text();throw new Error(`OpenAI error (${c.status}): ${m}`)}let l=await c.json(),u=l.choices?.[0]?.message;if(!u)throw new Error("OpenAI returned no choices");let p=u.content??null;p&&(p=p.replace(/<think>[\s\S]*?<\/think>/g,"").trim()||null);let f={role:"assistant",content:p};if(u.tool_calls&&u.tool_calls.length>0)f.tool_calls=u.tool_calls.map(m=>({id:m.id,type:"function",function:{name:m.function.name,arguments:Vv(m.function.arguments)}}));else if(f.content&&r.length>0){let m=xR(f.content,r);m.length>0&&(f.tool_calls=m,f.content=null)}let d={promptTokens:l.usage?.prompt_tokens??0,completionTokens:l.usage?.completion_tokens??0,totalTokens:l.usage?.total_tokens??0};return{message:f,usage:d}}async function Y9(t,e,r,n){let o,s=[];for(let g of e){if(g.role==="system"){o=g.content??void 0;continue}if(g.role==="assistant"){let v=[];if(g.content&&v.push({type:"text",text:g.content}),g.tool_calls)for(let b of g.tool_calls)v.push({type:"tool_use",id:b.id??`call_${Date.now()}`,name:b.function.name,input:typeof b.function.arguments=="string"?Vv(b.function.arguments):b.function.arguments});s.push({role:"assistant",content:v});continue}if(g.role==="tool"){let v=s[s.length-1],b={type:"tool_result",tool_use_id:g.tool_call_id??"",content:g.content??""};v?.role==="user"&&Array.isArray(v.content)?v.content.push(b):s.push({role:"user",content:[b]});continue}s.push({role:"user",content:g.content??""})}let i=r.map(g=>({name:g.function.name,description:g.function.description,input_schema:g.function.parameters})),a={model:t.model,max_tokens:4096,messages:s};o&&(a.system=o),i.length>0&&(a.tools=i),n!==void 0&&(a.temperature=n);let c=await fetch(`${t.baseUrl}/v1/messages`,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":t.apiKey??"","anthropic-version":"2023-06-01"},body:JSON.stringify(a)});if(!c.ok){let g=await c.text();throw new Error(`Anthropic error (${c.status}): ${g}`)}let l=await c.json(),u={role:"assistant",content:null},p=[],f=[];for(let g of l.content)g.type==="text"?p.push(g.text):g.type==="tool_use"&&f.push({id:g.id,type:"function",function:{name:g.name,arguments:g.input}});p.length>0&&(u.content=p.join(`
400
+ `)),f.length>0&&(u.tool_calls=f);let d=l.usage?.input_tokens??0,m=l.usage?.output_tokens??0,h={promptTokens:d,completionTokens:m,totalTokens:d+m};return{message:u,usage:h}}function Vv(t){try{return JSON.parse(t)}catch{return{}}}function wR(t){return typeof t.function.arguments=="string"?Vv(t.function.arguments):t.function.arguments}function xR(t,e){let r=new Set(e.map(s=>s.function.name)),n=[],o=X9(t);for(let s of o)try{let i=JSON.parse(s),a=Array.isArray(i)?i:[i];for(let c of a)!c||typeof c!="object"||typeof c.name=="string"&&r.has(c.name)&&n.push({id:`text_${Date.now()}_${n.length}`,type:"function",function:{name:c.name,arguments:c.arguments??c.parameters??{}}})}catch{}return n}function X9(t){let e=[],r=t.matchAll(/```(?:json)?\s*\n?([\s\S]*?)```/g);for(let n of r)e.push(n[1].trim());for(let n=0;n<t.length;n++)if(t[n]==="{"||t[n]==="["){let o=t[n]==="{"?"}":"]",s=1,i=n+1;for(;i<t.length&&s>0;)t[i]===t[n]?s++:t[i]===o&&s--,i++;s===0&&(e.push(t.slice(n,i)),n=i-1)}return e}var vR,Gv,W9,Wv=w(()=>{vR={ollama:"http://localhost:11434",openai:"https://api.openai.com",anthropic:"https://api.anthropic.com",groq:"https://api.groq.com/openai",cerebras:"https://api.cerebras.ai"};Gv=5,W9=2e3});function Va(t,e,r,n,o){let s=[];if(s.push(`You are agent "${t}" with the role of "${e}".`),s.push(""),n){if(s.push(`## Protocol: ${n.protocol.title}`),s.push(""),s.push(`## Your Role: ${n.role.name}`),s.push(n.role.description),s.push(""),s.push(`## Current Phase: ${n.current_phase}`),n.phases[n.current_phase]&&s.push(n.phases[n.current_phase].description),s.push(""),n.rules){let i=n.rules[n.current_phase];if(i){s.push("## Your Steps (follow in order):"),i.loop&&s.push("*Repeat these steps until no work remains, then say DONE.*"),s.push("");for(let a=0;a<i.steps.length;a++){let c=i.steps[a],l=c.hint??c.description??c.action;s.push(`${a+1}. ${l}`)}s.push("")}}if(n.resources){let i=n.resources;if(i.instances&&Array.isArray(i.instances)){s.push("## Available Resources");for(let a of i.instances)s.push(`- ${a}`);s.push("")}if(i.claim_patterns){s.push("## Claim Patterns");for(let[a,c]of Object.entries(i.claim_patterns))s.push(`- ${a}: \`${c}\``);s.push("")}}s.push("## All Phases");for(let[i,a]of Object.entries(n.phases)){let c=i===n.current_phase?" (CURRENT)":a.terminal?" (TERMINAL)":"";s.push(`- **${i}**${c}: ${a.description}`)}if(s.push(""),n.team&&n.team.length>0){s.push("## Team");let i=new Map;for(let a of n.team){let c=i.get(a.role)??[];c.push(a.agent),i.set(a.role,c)}for(let[a,c]of i){let l=a===e?" (your role)":"";s.push(`- **${a}**${l}: ${c.join(", ")}`)}s.push("")}}s.push("## Available Tools"),s.push("");for(let i of r)s.push(`- **${i.function.name}**: ${i.function.description}`);return s.push(""),s.push("## Instructions"),n?(s.push("- Follow the steps above for your role. Use the available tools to complete each step."),s.push("- Work through the workspace files as described in your role description."),s.push('- When you have completed ALL your work and have no more actions to take, respond with just the word "DONE".')):(s.push("- Use the tools to complete your assigned work."),s.push("- Read files before modifying them to understand existing code."),s.push("- Use grep and glob to explore the codebase before making changes."),s.push('- When you have completed your work and have no more actions to take, say "DONE".')),s.push(""),o?.disableReasoning&&(s.push("/no_think"),s.push("")),s.join(`
401
+ `)}function SR(t,e,r){return Va(t,e,r,null)}var $R=w(()=>{});function nB(t){let e=t.conditions.map(r=>r.count>1?`${r.count}x ${r.event}`:r.event).join(" + ");return t.timeout>0?`${e} (timeout: ${t.timeout}s)`:`${e} (no timeout)`}async function oB(t,e){let{startOn:r}=t;if(!r)return;let n=Q({server:t.serverUrl,agentId:t.agentId,namespace:t.namespace}),o=r.timeout>0?Date.now()+r.timeout*1e3:0,s=2e3;for(;o===0||Date.now()<o;){let i=!0;for(let a of r.conditions){let c=await n.getEvents(0,{type:a.event});if(!c.ok){i=!1;break}let l=c.data,u=Array.isArray(l)?l:l?.events;if(!u||u.length<a.count){i=!1;break}}if(i)return;await new Promise(a=>setTimeout(a,s))}e(`Timeout (${r.timeout}s) \u2014 starting anyway`)}var kR,Wa,Jv,Q9,eB,tB,rB,Kv,sB,iB,ER,aB,xp,TR=w(()=>{Wv();$R();Qe();kR=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[91m","\x1B[92m","\x1B[93m","\x1B[94m","\x1B[95m","\x1B[96m"],Wa="\x1B[0m",Jv="\x1B[2m",Q9=0,eB=new Set(["write_file","patch_file"]),tB=new Set(["incubator_claim","incubator_releaseClaim","incubator_setState","incubator_publishEvent"]),rB=new Set(["publish_event","set_state","get_state","claim_resource","release_resource"]),Kv=[{type:"function",function:{name:"publish_event",description:"Publish a coordination event to notify other agents of progress or milestones",parameters:{type:"object",properties:{type:{type:"string",description:"Event type (e.g. section.written, review.complete)"},data:{type:"string",description:"JSON object with event payload data (optional)"}},required:["type"]}}},{type:"function",function:{name:"set_state",description:"Set a shared state key visible to all agents in this hive",parameters:{type:"object",properties:{key:{type:"string",description:"State key name"},value:{type:"string",description:"Value to set (string or JSON)"}},required:["key","value"]}}},{type:"function",function:{name:"get_state",description:'Get shared state for this hive. Use key="all" to get everything, or a specific key name.',parameters:{type:"object",properties:{key:{type:"string",description:'State key to retrieve, or "all" for all state'}},required:["key"]}}},{type:"function",function:{name:"claim_resource",description:"Claim exclusive ownership of a resource (e.g. a topic, file, or task). Returns rejected if another agent already holds the claim.",parameters:{type:"object",properties:{resource:{type:"string",description:'Resource identifier to claim (e.g. "topic:quantum-computing")'},reason:{type:"string",description:"Why you need this resource"}},required:["resource"]}}},{type:"function",function:{name:"release_resource",description:"Release a previously claimed resource so other agents can use it",parameters:{type:"object",properties:{resource:{type:"string",description:"Resource identifier to release"}},required:["resource"]}}}];sB={cerebras:128e3,groq:128e3,ollama:8e3,openai:128e3,anthropic:2e5},iB=.8,ER=6,aB=3,xp=class{stopFlag=!1;stop(){this.stopFlag=!0}async run(e,r,n,o,s,i){let a=kR[Q9++%kR.length],{agentId:c,role:l,provider:u,maxIterations:p}=e,f=0,d=0,m=Date.now(),h={promptTokens:0,completionTokens:0,totalTokens:0},g=[],v=b=>{if(e.verbose){let x=new Date().toISOString().slice(11,23);console.error(`${a} ${x} [${c}] ${b}${Wa}`)}};try{o&&(await o.connect(),v("ACP runtime connected")),e.startOn&&(v(`Waiting for trigger: ${nB(e.startOn)}`),await oB(e,v),v("Trigger conditions met \u2014 starting agent"));let b=[...r.getToolDefs()];if(e.toolFilter&&e.mode==="drone"){let se=new Set(e.toolFilter);b=b.filter(ue=>se.has(ue.function.name))}if(n){let se=n.getToolDefs(),ue=e.coordination??"full";if(ue==="lite")se=se.filter(ct=>tB.has(ct.function.name));else if(ue==="none")se=[];else if(Array.isArray(ue)){let ct=new Set(ue);se=se.filter(Ir=>ct.has(Ir.function.name))}b.push(...se),v(`Tools: ${b.length} (env: ${b.length-se.length}, incubator: ${se.length})`)}else o&&!e.noAcpInject?(b.push(...Kv),v(`Tools: ${b.length} (env: ${b.length-Kv.length}, acp: ${Kv.length})`)):v(`Tools: ${b.length} (env only)`);let x=s??null;!x&&o&&(x=await o.fetchProtocol());let $=null;if(o){let se=o.getDanceTools();se&&se.length>0&&(b=[...se],$=new Set(se.map(ue=>ue.function.name)),v(`Dance tools: ${se.map(ue=>ue.function.name).join(", ")} (exclusive \u2014 replaced all env/acp tools)`))}let O=e.wakeOn??null;x&&!O&&x.wait&&(O={types:x.wait.types??null,timeout:x.wait.max_timeout??0,maxWakes:50},v(`Derived wakeOn from spec: types=${x.wait.types?.join(",")??"any"}`));let ce=x?.context;ce!==void 0&&v(`Context retention: ${ce===0?"stateless":`last ${ce} exchanges`}`);let X=x?.temperature??e.temperature,ee=x?.reasoning===!1,ge=x?.reasoning_effort,ne=[{role:"system",content:x?Va(c,l,b,x,{disableReasoning:ee}):SR(c,l,b)},{role:"user",content:e.prompt??"Begin your work. Explore the codebase, understand the task, and implement the required changes."}];v(`Starting (role=${l}, model=${u.model}, mode=${e.mode})`);let rt=()=>{v("SIGTERM received \u2014 killing agent"),this.stopFlag=!0};process.on("SIGTERM",rt);let Mt=e.contextWindow??sB[u.type]??128e3,te=Math.floor(Mt*iB),fe=e.maxRetries??aB;if(O&&o){v("Sleeping \u2014 waiting for initial wake event");let se=await o.waitForWake(O);if(se.length===0)return v("Initial wake timeout \u2014 no events, exiting"),o&&await o.onComplete("Wake timeout",h),process.removeListener("SIGTERM",rt),{iterations:0,usage:h,agentId:c,role:l,status:"completed"};v(`Woke up with ${se.length} event(s)`);let ue=o.getLastInject();ue&&(ne.push({role:"user",content:`[SYSTEM] ${ue}`}),v("Injected dance state context"));for(let ct of se)ne.push({role:"user",content:`[SYSTEM] ${ct}`})}for(;f<p&&!this.stopFlag;){if(f++,v(`Iteration ${f}/${p}`),e.maxTotalTokens&&e.maxTotalTokens>0&&h.totalTokens>=e.maxTotalTokens){v(`Token budget exhausted (${h.totalTokens.toLocaleString()}/${e.maxTotalTokens.toLocaleString()})`);break}if(e.maxRuntime&&e.maxRuntime>0&&Date.now()-m>=e.maxRuntime){v(`Runtime limit reached (${e.maxRuntime}ms)`);break}if(o){let V=await o.beforeIteration(),F=o.getLastInject();if(ce!==void 0&&F){if(ce===0)ne.length=1;else if(ne.length>1+ce*2){let me=ne.slice(-(ce*2));ne.length=1,ne.push(...me)}}for(let me of V)ne.push({role:"user",content:`[SYSTEM] ${me}`});F&&ne.push({role:"user",content:`[SYSTEM] ${F}`})}let se,ue,ct=0;for(;;){let V=Date.now();try{let F=await bR(u,ne,b,X,{...ee?{disableReasoning:!0}:{},...ge?{reasoningEffort:ge}:{}});se=F.message,ue=F.usage,i?.record("llm_call",{agentId:c,role:l,provider:u.type,model:u.model,promptTokens:ue.promptTokens,completionTokens:ue.completionTokens,latency_ms:Date.now()-V});break}catch(F){if(ct++,i?.record("llm_error",{agentId:c,role:l,provider:u.type,model:u.model,error:F.message,retryCount:ct,latency_ms:Date.now()-V}),ct>fe)throw F;let me=1e3*Math.pow(2,ct-1);v(`LLM call failed (attempt ${ct}/${fe}): ${F.message} \u2014 retrying in ${me}ms`),await new Promise(Jr=>setTimeout(Jr,me))}}if(ne.push(se),h.promptTokens+=ue.promptTokens,h.completionTokens+=ue.completionTokens,h.totalTokens+=ue.totalTokens,g.push(ue),ue.totalTokens>0&&v(`Tokens: +${ue.promptTokens}/${ue.completionTokens} (total: ${h.totalTokens.toLocaleString()})`),ue.promptTokens>te&&ne.length>ER+2){v(`Context compaction triggered (${ue.promptTokens.toLocaleString()} > ${te.toLocaleString()} threshold)`);let V=ne.slice(-ER);if(ne.length=1,ne.push(...V),o){let F=await o.fetchProtocol();F&&(ne[0]={role:"system",content:Va(c,l,b,F)});let me=await o.getState();ne.push({role:"user",content:`[SYSTEM] Context was compacted. Current state: ${me}`})}else ne.push({role:"user",content:"[SYSTEM] Context was compacted. Previous messages were trimmed."});v(`Compacted to ${ne.length} messages`)}if(se.content&&v(`${Jv}${se.content}${Wa}${a}`),se.content&&/\bDONE\b/.test(se.content)){v("Agent said DONE \u2014 finishing");break}if(!se.tool_calls||se.tool_calls.length===0){if(O&&o){let V=O.maxWakes??0;if(V>0&&++d>=V){v(`Max wakes reached (${V}) \u2014 exiting`);break}V===0&&d++,v(`Sleeping \u2014 waiting for wake events (cycle ${d})`);let F=await o.waitForWake(O);if(F.length===0){v("Wake timeout \u2014 no events, exiting");break}v(`Woke up with ${F.length} event(s)`);let me=o.getLastInject();me&&(ne.push({role:"user",content:`[SYSTEM] ${me}`}),v("Injected dance state context"));for(let Jr of F)ne.push({role:"user",content:`[SYSTEM] ${Jr}`});continue}v("No tool calls \u2014 agent finished");break}let Ir=!1;for(let V of se.tool_calls){let F=V.function.name,me=wR(V),Jr=Object.keys(me).length>0?`(${Object.entries(me).map(([Oe,Ar])=>`${Oe}=${JSON.stringify(Ar)}`).join(", ")})`:"()";if(v(`Tool: ${F}${Jr}`),o&&eB.has(F)&&me.path){let Oe=await o.onFileWrite(me.path);if(Oe){ne.push({role:"tool",content:Oe,tool_call_id:V.id??`call_${f}`}),v(`${Jv}\u2192 claim conflict: ${Oe}${Wa}${a}`);continue}}let Be;if($&&$.has(F)&&o)try{let Oe=await o.callDanceTool(F,me);Be=JSON.stringify(Oe)}catch(Oe){Be=JSON.stringify({error:`Dance tool failed: ${Oe.message}`})}else if(o&&rB.has(F))if(F==="publish_event"){let Oe={};if(me.data)try{Oe=typeof me.data=="string"?JSON.parse(me.data):me.data}catch{}Be=await o.publishEvent(me.type,Oe)}else F==="set_state"?Be=await o.setState(me.key,me.value):F==="get_state"?Be=await o.getState():F==="claim_resource"?Be=await o.claimResource(me.resource,me.reason):F==="release_resource"?Be=await o.releaseResource(me.resource):Be=JSON.stringify({error:`Unknown synthetic tool: ${F}`});else if(n&&n.hasToolName(F))Be=await n.callTool(F,me);else try{Be=await r.callTool(F,me)}catch(Oe){Be=JSON.stringify({error:`Tool call failed: ${Oe.message}`})}if(v(`${Jv}\u2192 ${Be}${Wa}${a}`),ne.push({role:"tool",content:Be,tool_call_id:V.id??`call_${f}`}),o){let Oe=await o.checkControl();if(Oe.halted){v(`HALTED: ${Oe.reason??"no reason"}`),Ir=!0;break}if(Oe.paused){v(`PAUSED: ${Oe.reason??"no reason"} \u2014 waiting...`);let Ar=await o.waitForResume();v(`RESUMED: ${Ar}`),ne.push({role:"user",content:`[SYSTEM] You were paused (reason: ${Oe.reason??"unknown"}). You have been resumed (reason: ${Ar}). Continue your work.`})}}}if(Ir)return v("Agent halted \u2014 exiting loop"),o&&await o.onComplete("Agent halted",h),{agentId:c,role:l,status:"completed",iterations:f,usage:h,iterationUsage:g};if(f%10===0&&o){let V=await o.fetchProtocol();if(V){let F=Va(c,l,b,V);ne[0]={role:"system",content:F},v("Refreshed system prompt")}}}this.stopFlag?v("Stopped by runner"):f>=p&&v(`Hit max iterations (${p})`),process.off("SIGTERM",rt);let Lt=`Agent ${c} completed after ${f} iterations (${h.totalTokens.toLocaleString()} tokens)`;return o&&await o.onComplete(Lt,h),i?.record("agent_complete",{agentId:c,role:l,status:"completed",iterations:f,promptTokens:h.promptTokens,completionTokens:h.completionTokens,totalTokens:h.totalTokens,duration_ms:Date.now()-m}),v(`Done (${f} iterations, ${h.totalTokens.toLocaleString()} tokens)`),{agentId:c,role:l,status:"completed",iterations:f,usage:h,iterationUsage:g}}catch(b){try{process.off("SIGTERM",()=>{})}catch{}let x=b.message;if(e.verbose&&console.error(`${a} [${c}] ERROR: ${x}${Wa}`),o)try{await o.onComplete(`Error: ${x}`,h)}catch{}return i?.record("agent_complete",{agentId:c,role:l,status:"error",iterations:f,error:x,totalTokens:h.totalTokens,duration_ms:Date.now()-m}),{agentId:c,role:l,status:"error",iterations:f,error:x,usage:h,iterationUsage:g}}}}});var Sp,PR=w(()=>{Fv();Sp=class{entries;entryMap;defs;constructor(e,r,n,o){let s=Uv(e,r,n);if(o){let i=new Set(o);s=s.filter(a=>i.has(a.def.function.name))}this.entries=s,this.entryMap=new Map(s.map(i=>[i.def.function.name,i])),this.defs=s.map(i=>i.def)}getToolDefs(){return this.defs}hasToolName(e){return this.entryMap.has(e)}async callTool(e,r){let n=this.entryMap.get(e);if(!n)return JSON.stringify({error:`Unknown tool: ${e}`});let o=await n.handler(r);return o.content&&o.content.length>0?o.content.map(s=>s.text??"").join(`
402
+ `):JSON.stringify(o)}async close(){}}});import{randomBytes as cB}from"node:crypto";function lB(t,e){let r=Object.keys(t.roles),n=r.includes(e)?e:r[0],o=t.roles[n];if(!o)return null;let s={};for(let[m,h]of Object.entries(t.phases))s[m]={description:h.description,...h.terminal?{terminal:!0}:{}};let i=Object.keys(s),a=t.rules?.[n],c={};if(a)for(let[m,h]of Object.entries(a)){let g=h;c[m]=g}let l=o,u=l.wait,p=l.context,f=l.temperature,d=l.reasoning;return{protocol:{name:t.name,title:t.title},role:{name:n,description:o.description},current_phase:i[0]??"default",instructions:`Follow the ${t.title} protocol as the ${n} role.`,phases:s,...t.governance?{governance:t.governance}:{},...Object.keys(c).length>0?{rules:c}:{},...t.resources?{resources:t.resources}:{},...u?{wait:u}:{},...p!==void 0?{context:p}:{},...f!==void 0?{temperature:f}:{},...d!==void 0?{reasoning:d}:{}}}var $p,RR=w(()=>{yR();TR();PR();Wv();$p=class{agents=new Map;async startAgent(e,r){let n=cB(3).toString("hex"),o=`${e.role}_${n}`,s=(e.modelHint&&r.models?.[e.modelHint])??r.models?.[e.role]??r.provider??"ollama/qwen3:8b",i=_R(s),a=r.protocolData??this.buildProtocolData(r.registry,r.namespace,e.role),c={stores:r.stores,bus:r.bus,namespace:r.namespace,agentId:o,role:e.role,maxIterations:50,verbose:r.verbose,danceModule:r.danceModule,protocolData:a??void 0},l=new wp(c),u=e.tools&&e.tools!=="all"?e.tools:null,p=new Sp(r.workDir,r.guard,r.verbose,u),f={agentId:o,role:e.role,provider:i,serverUrl:"direct://localhost",namespace:r.namespace,maxIterations:50,verbose:r.verbose,mode:"worker",workDir:r.workDir,noAcp:!1,toolFilter:u,coordination:e.coordination,startOn:e.startOn??null,wakeOn:e.wakeOn??null,prompt:e.prompt};r.telemetry?.record("agent_spawn",{agentId:o,role:e.role,provider:s,type:"worker",inProcess:!0});let d=new xp,m=d.run(f,p,null,l,a,r.telemetry).finally(()=>{l.disconnect().catch(()=>{}),p.close().catch(()=>{})});return this.agents.set(o,{promise:m,runner:d,runtime:l,agentId:o,role:e.role}),o}async killAgent(e){let r=this.agents.get(e);if(r){r.runner.stop();try{await Promise.race([r.promise,new Promise(n=>setTimeout(n,5e3))])}catch{}this.agents.delete(e)}}async shutdown(){for(let r of this.agents.values())r.runner.stop();let e=[...this.agents.values()].map(r=>r.promise.catch(()=>{}));await Promise.race([Promise.all(e),new Promise(r=>setTimeout(r,1e4))]),this.agents.clear()}getAgents(){return[...this.agents.values()].map(e=>({agentId:e.agentId,role:e.role,type:"worker"}))}async waitForAll(){let e=[];for(let r of this.agents.values())try{e.push(await r.promise)}catch(n){e.push({agentId:r.agentId,role:r.role,status:"error",iterations:0,error:n.message})}return e}get size(){return this.agents.size}buildProtocolData(e,r,n){let o=e.getProtocol(r);return o?lB(o,n):null}}});import{spawn as Yv}from"node:child_process";import{randomBytes as OR}from"node:crypto";import{dirname as uB,join as pB}from"node:path";import{fileURLToPath as dB}from"node:url";function Xv(t){return new Promise(e=>setTimeout(e,t))}var fB,mB,Ja,CR=w(()=>{RR();fB=uB(dB(import.meta.url)),mB=pB(fB,"..","plugin"),Ja=class{config;incubatorPort;bus;runs;verbose;stores;registry;danceModule;telemetry;children=new Map;childInfo=[];propolisPid;pool;constructor(e,r,n,o,s=!1,i,a,c,l){this.config=e,this.incubatorPort=r,this.bus=n,this.runs=o,this.verbose=s,this.stores=i,this.registry=a,this.danceModule=c,this.telemetry=l}log(e){this.verbose&&console.error(`[orchestrator] ${e}`)}get hiveEntry(){return this.config.hiveEntry??this.config.droneEntry??""}get propolisEntry(){return this.config.propolisEntry?this.config.propolisEntry:this.config.hiveEntry??""}async start(){this.telemetry?.record("protocol_start",{agentCount:this.config.agents.reduce((r,n)=>r+(n.count??1),0),provider:this.config.provider}),this.config.agents.some(r=>r.type==="drone")&&(await this.spawnPropolis(),await Xv(1500)),await this.spawnAgents()}async spawnPropolis(){let e=this.propolisEntry,{propolisPort:r,worktree:n,env:o}=this.config,s=["--http",`--port=${r}`,`--work-dir=${n}`,"--no-guard"],i={...process.env,...o},a=Yv(process.execPath,[e,...s],{env:i,cwd:n,stdio:["ignore","pipe","pipe"]});a.stderr?.on("data",c=>{let l=c.toString().trim();l&&this.log(`[propolis] ${l}`)}),a.on("exit",c=>{this.children.delete("propolis"),c!==null&&c!==0&&this.log(`Propolis exited with code ${c}`)}),a.pid&&(this.children.set("propolis",a),this.propolisPid=a.pid,this.log(`Propolis started on port ${r} (pid ${a.pid})`))}get canRunInProcess(){return!!(this.stores&&this.bus&&this.registry)}async spawnAgents(){let{propolisPort:e,worktree:r}=this.config,n=this.config,o=0,s;this.canRunInProcess&&(this.pool=new $p,s={stores:this.stores,bus:this.bus,registry:this.registry,namespace:"default",workDir:r,guard:null,verbose:this.verbose,danceModule:this.danceModule,provider:n.provider,models:n.models,telemetry:this.telemetry});for(let i of n.agents){let a=i.count??1,c=i.type??"worker";for(let l=0;l<a;l++){let u=n.stagger*1e3;if(o>0&&u>0&&await Xv(u),o++,c==="claude"){let b=OR(3).toString("hex"),x=`${i.role}_${b}`;this.spawnClaude(i,x,n);continue}if(c==="worker"&&this.pool&&s){let b=await this.pool.startAgent(i,s);this.childInfo.push({agentId:b,role:i.role,type:"worker",inProcess:!0});let x=(i.modelHint&&n.models?.[i.modelHint])??n.models?.[i.role]??n.provider??"ollama/qwen3:8b";this.telemetry?.record("agent_spawn",{agentId:b,role:i.role,provider:x,type:"worker",inProcess:!0}),this.log(`Worker ${b} (${i.role}) started in-process \u2192 ${x}`);continue}let p=OR(3).toString("hex"),f=`${i.role}_${p}`,d=(i.modelHint&&n.models?.[i.modelHint])??n.models?.[i.role]??n.provider??"ollama/qwen3:8b",h=[`--server=${n.tls?"https":"http"}://localhost:${this.incubatorPort}`,"--namespace=default",`--agent-id=${f}`,`--role=${i.role}`,`--provider=${d}`,"--verbose"];if(c==="worker"?(h.push("--mode=worker"),h.push(`--work-dir=${r}`)):(h.push("--mode=drone"),h.push(`--propolis=http://localhost:${e}`)),n.protocolPath&&h.push(`--protocol=${n.protocolPath}`),n.noAcp&&h.push("--no-acp"),i.tools&&i.tools!=="all"&&h.push(`--tools=${i.tools.join(",")}`),i.coordination){let b=Array.isArray(i.coordination)?i.coordination.join(","):i.coordination;h.push(`--coordination=${b}`)}i.startOn&&h.push(`--start-on=${JSON.stringify(i.startOn)}`),i.wakeOn&&h.push(`--wake-on=${JSON.stringify(i.wakeOn)}`);let g={...process.env,...n.env,...n.tls?{NODE_TLS_REJECT_UNAUTHORIZED:"0"}:{}};i.prompt&&(g.AGENT_PROMPT=i.prompt);let v=Yv(process.execPath,[this.hiveEntry,...h],{env:g,cwd:r,stdio:["ignore","pipe","pipe"]});v.stderr?.on("data",b=>{let x=b.toString().trim();x&&this.log(`[${f}] ${x}`)}),v.on("exit",b=>{this.children.delete(`${c}:${f}`);let x=b===0?"completed":`exited with code ${b}`;this.log(`[${f}] ${x}`)}),v.pid&&(this.children.set(`${c}:${f}`,v),this.childInfo.push({pid:v.pid,agentId:f,role:i.role,type:c}),this.telemetry?.record("agent_spawn",{agentId:f,role:i.role,provider:d,type:c,pid:v.pid}),this.log(`${c==="worker"?"Worker":"Drone"} ${f} (${i.role}) started \u2192 ${d} (pid ${v.pid})`))}}}spawnClaude(e,r,n){let{worktree:o}=n,s=(e.modelHint&&n.models?.[e.modelHint])??n.models?.[e.role]??e.modelHint??void 0,i=e.prompt??`You are assigned the role "${e.role}" in an ACP coordination protocol. Use the acp MCP tool to coordinate with other agents. Follow the protocol instructions injected at session start.`,a=e.pluginDir??mB,c=["--print","--dangerously-skip-permissions","-p",i,"--plugin-dir",a];s&&c.push("--model",s);let l={...process.env,...n.env,INCUBATOR_URL:`${n.tls?"https":"http"}://localhost:${this.incubatorPort}`,...n.tls?{NODE_TLS_REJECT_UNAUTHORIZED:"0"}:{},ACP_NAMESPACE:"default",ACP_AGENT_ID:r,ACP_ROLE:e.role};e.wakeOn?.types&&(l.ACP_WAKE_ON=e.wakeOn.types.join(","));let u=Yv("claude",c,{env:l,cwd:o,stdio:["ignore","pipe","pipe"]});u.stdout?.on("data",p=>{let f=p.toString().trim();f&&this.log(`[${r}:out] ${f}`)}),u.stderr?.on("data",p=>{let f=p.toString().trim();f&&this.log(`[${r}:err] ${f}`)}),u.on("exit",p=>{this.children.delete(`claude:${r}`);let f=p===0?"completed":`exited with code ${p}`;this.log(`[${r}] ${f}`)}),u.pid&&(this.children.set(`claude:${r}`,u),this.childInfo.push({pid:u.pid,agentId:r,role:e.role,type:"claude"}),this.telemetry?.record("agent_spawn",{agentId:r,role:e.role,type:"claude",pid:u.pid}),this.log(`Claude ${r} (${e.role}) started (pid ${u.pid})`))}getAgents(){return[...this.childInfo]}async killAgent(e){if(this.pool&&this.pool.getAgents().some(o=>o.agentId===e)){await this.pool.killAgent(e),this.log(`Stopped pool agent ${e}`);return}let r=this.children.get(`worker:${e}`)??this.children.get(`drone:${e}`)??this.children.get(`claude:${e}`);r&&(r.kill("SIGTERM"),this.log(`Sent SIGTERM to ${e}`),setTimeout(()=>{r.killed||(r.kill("SIGKILL"),this.log(`Sent SIGKILL to ${e} (did not exit gracefully)`))},5e3))}async shutdown(){this.telemetry?.record("protocol_end",{agentCount:this.childInfo.length,status:"shutdown"}),this.log("Shutting down agents..."),this.pool&&(await this.pool.shutdown(),this.log("Stopped all pool agents"));for(let[r,n]of this.children)(r.startsWith("drone:")||r.startsWith("worker:")||r.startsWith("claude:"))&&(n.kill("SIGTERM"),this.log(`Stopped ${r}`));await Xv(500);let e=this.children.get("propolis");e&&(e.kill("SIGTERM"),this.log("Stopped propolis")),this.children.clear(),this.childInfo=[]}}});import{createHmac as hB}from"node:crypto";var kp,IR=w(()=>{kp=class{unsubscribers=[];verbose;constructor(e=!1){this.verbose=e}register(e,r,n){for(let o of r){let s=o.events?new Set(o.events):null,i=n.subscribe(e,a=>{s&&!s.has(a.type)||this.fire(o,a).catch(c=>{this.verbose&&console.error(`[webhooks] Failed to deliver to ${o.url}: ${c.message}`)})});this.unsubscribers.push(i)}this.verbose&&r.length>0&&console.error(`[webhooks] Registered ${r.length} webhook(s) for namespace "${e}"`)}close(){for(let e of this.unsubscribers)e();this.unsubscribers=[]}async fire(e,r){let n=JSON.stringify({event:r.type,data:r.data,publishedBy:r.publishedBy,publishedAt:r.publishedAt,id:r.id}),o={"Content-Type":"application/json",...e.headers};if(e.secret){let a=hB("sha256",e.secret).update(n).digest("hex");o["X-Webhook-Signature"]=a}let s=new AbortController,i=setTimeout(()=>s.abort(),1e4);try{await fetch(e.url,{method:"POST",headers:o,body:n,signal:s.signal})}finally{clearTimeout(i)}}}});var Qv={};K(Qv,{getRedisClient:()=>yB,waitForReady:()=>vB});import{createRequire as gB}from"node:module";function yB(t){let e=AR.get(t);if(e)return e;let n=gB(import.meta.url)("ioredis"),o=new n(t);return AR.set(t,o),o}async function vB(t){if(t.status!=="ready")return new Promise((e,r)=>{let n=()=>{s(),e()},o=i=>{s(),r(i)},s=()=>{t.removeListener("ready",n),t.removeListener("error",o)};t.once("ready",n),t.once("error",o)})}var AR,e_=w(()=>{AR=new Map});var NR={};K(NR,{IPCTransport:()=>t_});import{connect as _B}from"node:net";var t_,zR=w(()=>{t_=class{socket=null;handlers=new Map;buffer="";opts;constructor(e){this.opts=e}async connect(){return new Promise((e,r)=>{let n=_B(this.opts.socketPath,()=>{this.socket=n,this.send({type:"register",hive:this.opts.hiveName,publishes:this.opts.publishes,subscribes:this.opts.subscribes}),e()});n.setEncoding("utf8"),n.on("data",o=>this.onData(o)),n.on("error",o=>{this.socket||r(o)})})}async publish(e,r){this.send({type:"event",hive:this.opts.hiveName,topic:e,event:r})}subscribe(e,r){let n=this.handlers.get(e);return n||(n=new Set,this.handlers.set(e,n)),n.add(r),()=>{n.delete(r),n.size===0&&this.handlers.delete(e)}}async close(){this.handlers.clear(),this.socket&&(this.socket.end(),this.socket=null)}send(e){this.socket&&this.socket.write(JSON.stringify(e)+`
403
403
  `)}onData(e){this.buffer+=e;let r=this.buffer.split(`
404
- `);this.buffer=r.pop();for(let n of r)if(n)try{let o=JSON.parse(n);if(o.type==="forward"){let s=this.handlers.get(o.topic);if(s)for(let i of s)i(o.event)}}catch{}}}});import{join as Jv,resolve as QH}from"path";import{readdirSync as eB,statSync as tB}from"fs";function Kv(t,e,r=""){t=QH(".",t);let n=eB(t),o=0,s,i;for(;o<n.length;o++)s=Jv(t,n[o]),i=tB(s),i.isDirectory()?Kv(s,e,Jv(r,n[o])):e(Jv(r,n[o]),s,i)}var TR=w(()=>{});import*as PR from"node:querystring";function RR(t){let e=t.url;if(e==null)return;let r=t._parsedUrl;if(r&&r.raw===e)return r;let n=e,o="",s,i;if(e.length>1){let a=e.indexOf("#",1);a!==-1&&(i=e.substring(a),n=e.substring(0,a)),a=n.indexOf("?",1),a!==-1&&(o=n.substring(a),n=n.substring(0,a),o.length>1&&(s=PR.parse(o.substring(1))))}return t._parsedUrl={pathname:n,search:o,query:s,hash:i,raw:e}}var OR=w(()=>{});function CR(t){let e=(""+t).trim().toLowerCase(),r=e.lastIndexOf(".");return rB[~r?e.substring(++r):e]}var rB,IR=w(()=>{rB={"3g2":"video/3gpp2","3gp":"video/3gpp","3gpp":"video/3gpp","3mf":"model/3mf",aac:"audio/aac",ac:"application/pkix-attr-cert",adp:"audio/adpcm",adts:"audio/aac",ai:"application/postscript",aml:"application/automationml-aml+xml",amlx:"application/automationml-amlx+zip",amr:"audio/amr",apng:"image/apng",appcache:"text/cache-manifest",appinstaller:"application/appinstaller",appx:"application/appx",appxbundle:"application/appxbundle",asc:"application/pgp-keys",atom:"application/atom+xml",atomcat:"application/atomcat+xml",atomdeleted:"application/atomdeleted+xml",atomsvc:"application/atomsvc+xml",au:"audio/basic",avci:"image/avci",avcs:"image/avcs",avif:"image/avif",aw:"application/applixware",bdoc:"application/bdoc",bin:"application/octet-stream",bmp:"image/bmp",bpk:"application/octet-stream",btf:"image/prs.btif",btif:"image/prs.btif",buffer:"application/octet-stream",ccxml:"application/ccxml+xml",cdfx:"application/cdfx+xml",cdmia:"application/cdmi-capability",cdmic:"application/cdmi-container",cdmid:"application/cdmi-domain",cdmio:"application/cdmi-object",cdmiq:"application/cdmi-queue",cer:"application/pkix-cert",cgm:"image/cgm",cjs:"application/node",class:"application/java-vm",coffee:"text/coffeescript",conf:"text/plain",cpl:"application/cpl+xml",cpt:"application/mac-compactpro",crl:"application/pkix-crl",css:"text/css",csv:"text/csv",cu:"application/cu-seeme",cwl:"application/cwl",cww:"application/prs.cww",davmount:"application/davmount+xml",dbk:"application/docbook+xml",deb:"application/octet-stream",def:"text/plain",deploy:"application/octet-stream",dib:"image/bmp","disposition-notification":"message/disposition-notification",dist:"application/octet-stream",distz:"application/octet-stream",dll:"application/octet-stream",dmg:"application/octet-stream",dms:"application/octet-stream",doc:"application/msword",dot:"application/msword",dpx:"image/dpx",drle:"image/dicom-rle",dsc:"text/prs.lines.tag",dssc:"application/dssc+der",dtd:"application/xml-dtd",dump:"application/octet-stream",dwd:"application/atsc-dwd+xml",ear:"application/java-archive",ecma:"application/ecmascript",elc:"application/octet-stream",emf:"image/emf",eml:"message/rfc822",emma:"application/emma+xml",emotionml:"application/emotionml+xml",eps:"application/postscript",epub:"application/epub+zip",exe:"application/octet-stream",exi:"application/exi",exp:"application/express",exr:"image/aces",ez:"application/andrew-inset",fdf:"application/fdf",fdt:"application/fdt+xml",fits:"image/fits",g3:"image/g3fax",gbr:"application/rpki-ghostbusters",geojson:"application/geo+json",gif:"image/gif",glb:"model/gltf-binary",gltf:"model/gltf+json",gml:"application/gml+xml",gpx:"application/gpx+xml",gram:"application/srgs",grxml:"application/srgs+xml",gxf:"application/gxf",gz:"application/gzip",h261:"video/h261",h263:"video/h263",h264:"video/h264",heic:"image/heic",heics:"image/heic-sequence",heif:"image/heif",heifs:"image/heif-sequence",hej2:"image/hej2k",held:"application/atsc-held+xml",hjson:"application/hjson",hlp:"application/winhlp",hqx:"application/mac-binhex40",hsj2:"image/hsj2",htm:"text/html",html:"text/html",ics:"text/calendar",ief:"image/ief",ifb:"text/calendar",iges:"model/iges",igs:"model/iges",img:"application/octet-stream",in:"text/plain",ini:"text/plain",ink:"application/inkml+xml",inkml:"application/inkml+xml",ipfix:"application/ipfix",iso:"application/octet-stream",its:"application/its+xml",jade:"text/jade",jar:"application/java-archive",jhc:"image/jphc",jls:"image/jls",jp2:"image/jp2",jpe:"image/jpeg",jpeg:"image/jpeg",jpf:"image/jpx",jpg:"image/jpeg",jpg2:"image/jp2",jpgm:"image/jpm",jpgv:"video/jpeg",jph:"image/jph",jpm:"image/jpm",jpx:"image/jpx",js:"text/javascript",json:"application/json",json5:"application/json5",jsonld:"application/ld+json",jsonml:"application/jsonml+json",jsx:"text/jsx",jt:"model/jt",jxl:"image/jxl",jxr:"image/jxr",jxra:"image/jxra",jxrs:"image/jxrs",jxs:"image/jxs",jxsc:"image/jxsc",jxsi:"image/jxsi",jxss:"image/jxss",kar:"audio/midi",ktx:"image/ktx",ktx2:"image/ktx2",less:"text/less",lgr:"application/lgr+xml",list:"text/plain",litcoffee:"text/coffeescript",log:"text/plain",lostxml:"application/lost+xml",lrf:"application/octet-stream",m1v:"video/mpeg",m21:"application/mp21",m2a:"audio/mpeg",m2t:"video/mp2t",m2ts:"video/mp2t",m2v:"video/mpeg",m3a:"audio/mpeg",m4a:"audio/mp4",m4p:"application/mp4",m4s:"video/iso.segment",ma:"application/mathematica",mads:"application/mads+xml",maei:"application/mmt-aei+xml",man:"text/troff",manifest:"text/cache-manifest",map:"application/json",mar:"application/octet-stream",markdown:"text/markdown",mathml:"application/mathml+xml",mb:"application/mathematica",mbox:"application/mbox",md:"text/markdown",mdx:"text/mdx",me:"text/troff",mesh:"model/mesh",meta4:"application/metalink4+xml",metalink:"application/metalink+xml",mets:"application/mets+xml",mft:"application/rpki-manifest",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mj2:"video/mj2",mjp2:"video/mj2",mjs:"text/javascript",mml:"text/mathml",mods:"application/mods+xml",mov:"video/quicktime",mp2:"audio/mpeg",mp21:"application/mp21",mp2a:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mp4a:"audio/mp4",mp4s:"application/mp4",mp4v:"video/mp4",mpd:"application/dash+xml",mpe:"video/mpeg",mpeg:"video/mpeg",mpf:"application/media-policy-dataset+xml",mpg:"video/mpeg",mpg4:"video/mp4",mpga:"audio/mpeg",mpp:"application/dash-patch+xml",mrc:"application/marc",mrcx:"application/marcxml+xml",ms:"text/troff",mscml:"application/mediaservercontrol+xml",msh:"model/mesh",msi:"application/octet-stream",msix:"application/msix",msixbundle:"application/msixbundle",msm:"application/octet-stream",msp:"application/octet-stream",mtl:"model/mtl",mts:"video/mp2t",musd:"application/mmt-usd+xml",mxf:"application/mxf",mxmf:"audio/mobile-xmf",mxml:"application/xv+xml",n3:"text/n3",nb:"application/mathematica",nq:"application/n-quads",nt:"application/n-triples",obj:"model/obj",oda:"application/oda",oga:"audio/ogg",ogg:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",omdoc:"application/omdoc+xml",onepkg:"application/onenote",onetmp:"application/onenote",onetoc:"application/onenote",onetoc2:"application/onenote",opf:"application/oebps-package+xml",opus:"audio/ogg",otf:"font/otf",owl:"application/rdf+xml",oxps:"application/oxps",p10:"application/pkcs10",p7c:"application/pkcs7-mime",p7m:"application/pkcs7-mime",p7s:"application/pkcs7-signature",p8:"application/pkcs8",pdf:"application/pdf",pfr:"application/font-tdpfr",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pki:"application/pkixcmp",pkipath:"application/pkix-pkipath",pls:"application/pls+xml",png:"image/png",prc:"model/prc",prf:"application/pics-rules",provx:"application/provenance+xml",ps:"application/postscript",pskcxml:"application/pskc+xml",pti:"image/prs.pti",qt:"video/quicktime",raml:"application/raml+yaml",rapd:"application/route-apd+xml",rdf:"application/rdf+xml",relo:"application/p2p-overlay+xml",rif:"application/reginfo+xml",rl:"application/resource-lists+xml",rld:"application/resource-lists-diff+xml",rmi:"audio/midi",rnc:"application/relax-ng-compact-syntax",rng:"application/xml",roa:"application/rpki-roa",roff:"text/troff",rq:"application/sparql-query",rs:"application/rls-services+xml",rsat:"application/atsc-rsat+xml",rsd:"application/rsd+xml",rsheet:"application/urc-ressheet+xml",rss:"application/rss+xml",rtf:"text/rtf",rtx:"text/richtext",rusd:"application/route-usd+xml",s3m:"audio/s3m",sbml:"application/sbml+xml",scq:"application/scvp-cv-request",scs:"application/scvp-cv-response",sdp:"application/sdp",senmlx:"application/senml+xml",sensmlx:"application/sensml+xml",ser:"application/java-serialized-object",setpay:"application/set-payment-initiation",setreg:"application/set-registration-initiation",sgi:"image/sgi",sgm:"text/sgml",sgml:"text/sgml",shex:"text/shex",shf:"application/shf+xml",shtml:"text/html",sieve:"application/sieve",sig:"application/pgp-signature",sil:"audio/silk",silo:"model/mesh",siv:"application/sieve",slim:"text/slim",slm:"text/slim",sls:"application/route-s-tsid+xml",smi:"application/smil+xml",smil:"application/smil+xml",snd:"audio/basic",so:"application/octet-stream",spdx:"text/spdx",spp:"application/scvp-vp-response",spq:"application/scvp-vp-request",spx:"audio/ogg",sql:"application/sql",sru:"application/sru+xml",srx:"application/sparql-results+xml",ssdl:"application/ssdl+xml",ssml:"application/ssml+xml",stk:"application/hyperstudio",stl:"model/stl",stpx:"model/step+xml",stpxz:"model/step-xml+zip",stpz:"model/step+zip",styl:"text/stylus",stylus:"text/stylus",svg:"image/svg+xml",svgz:"image/svg+xml",swidtag:"application/swid+xml",t:"text/troff",t38:"image/t38",td:"application/urc-targetdesc+xml",tei:"application/tei+xml",teicorpus:"application/tei+xml",text:"text/plain",tfi:"application/thraud+xml",tfx:"image/tiff-fx",tif:"image/tiff",tiff:"image/tiff",toml:"application/toml",tr:"text/troff",trig:"application/trig",ts:"video/mp2t",tsd:"application/timestamped-data",tsv:"text/tab-separated-values",ttc:"font/collection",ttf:"font/ttf",ttl:"text/turtle",ttml:"application/ttml+xml",txt:"text/plain",u3d:"model/u3d",u8dsn:"message/global-delivery-status",u8hdr:"message/global-headers",u8mdn:"message/global-disposition-notification",u8msg:"message/global",ubj:"application/ubjson",uri:"text/uri-list",uris:"text/uri-list",urls:"text/uri-list",vcard:"text/vcard",vrml:"model/vrml",vtt:"text/vtt",vxml:"application/voicexml+xml",war:"application/java-archive",wasm:"application/wasm",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webmanifest:"application/manifest+json",webp:"image/webp",wgsl:"text/wgsl",wgt:"application/widget",wif:"application/watcherinfo+xml",wmf:"image/wmf",woff:"font/woff",woff2:"font/woff2",wrl:"model/vrml",wsdl:"application/wsdl+xml",wspolicy:"application/wspolicy+xml",x3d:"model/x3d+xml",x3db:"model/x3d+fastinfoset",x3dbz:"model/x3d+binary",x3dv:"model/x3d-vrml",x3dvz:"model/x3d+vrml",x3dz:"model/x3d+xml",xaml:"application/xaml+xml",xav:"application/xcap-att+xml",xca:"application/xcap-caps+xml",xcs:"application/calendar+xml",xdf:"application/xcap-diff+xml",xdssc:"application/dssc+xml",xel:"application/xcap-el+xml",xenc:"application/xenc+xml",xer:"application/patch-ops-error+xml",xfdf:"application/xfdf",xht:"application/xhtml+xml",xhtml:"application/xhtml+xml",xhvml:"application/xv+xml",xlf:"application/xliff+xml",xm:"audio/xm",xml:"text/xml",xns:"application/xcap-ns+xml",xop:"application/xop+xml",xpl:"application/xproc+xml",xsd:"application/xml",xsf:"application/prs.xsf+xml",xsl:"application/xml",xslt:"application/xml",xspf:"application/xspf+xml",xvm:"application/xv+xml",xvml:"application/xv+xml",yaml:"text/yaml",yang:"application/yang",yin:"application/yin+xml",yml:"text/yaml",zip:"application/zip"}});var zR={};X(zR,{default:()=>mB});import*as ri from"node:fs";import{join as nB,normalize as oB,resolve as sB,sep as iB}from"node:path";function cB(t,e){for(let r=0;r<e.length;r++)if(e[r].test(t))return!0}function AR(t,e){let r=0,n,o=t.length-1;t.charCodeAt(o)===47&&(t=t.substring(0,o));let s=[],i=`${t}/index`;for(;r<e.length;r++)n=e[r]?`.${e[r]}`:"",t&&s.push(t+n),s.push(i+n);return s}function lB(t,e,r){let n=0,o,s=AR(e,r);for(;n<s.length;n++)if(o=t[s[n]])return o}function uB(t,e,r,n){let o=0,s=AR(r,n),i,a,c,l;for(;o<s.length;o++)if(i=oB(nB(t,c=s[o])),i.startsWith(t)&&ri.existsSync(i)){if(a=ri.statSync(i),a.isDirectory())continue;return l=NR(c,a,e),l["Cache-Control"]=e?"no-cache":"no-store",{abs:i,stats:a,headers:l}}}function pB(t,e){return e.statusCode=404,e.end()}function dB(t,e,r,n,o){let s=200,i,a={};o={...o};for(let c in o)i=e.getHeader(c),i&&(o[c]=i);if((i=e.getHeader("content-type"))&&(o["Content-Type"]=i),t.headers.range){s=206;let[c,l]=t.headers.range.replace("bytes=","").split("-"),u=a.end=parseInt(l,10)||n.size-1,p=a.start=parseInt(c,10)||0;if(u>=n.size&&(u=n.size-1),p>=n.size)return e.setHeader("Content-Range",`bytes */${n.size}`),e.statusCode=416,e.end();o["Content-Range"]=`bytes ${p}-${u}/${n.size}`,o["Content-Length"]=u-p+1,o["Accept-Ranges"]="bytes"}e.writeHead(s,o),ri.createReadStream(r,a).pipe(e)}function NR(t,e,r){let n=fB[t.slice(-3)],o=CR(t.slice(0,n&&-3))||"";o==="text/html"&&(o+=";charset=utf-8");let s={"Content-Length":e.size,"Content-Type":o,"Last-Modified":e.mtime.toUTCString()};return n&&(s["Content-Encoding"]=n),r&&(s.ETag=`W/"${e.size}-${e.mtime.getTime()}"`),s}function mB(t,e={}){t=sB(t||".");let r=e.onNoMatch||pB,n=e.setHeaders||aB,o=e.extensions||["html","htm"],s=e.gzip&&o.map(f=>`${f}.gz`).concat("gz"),i=e.brotli&&o.map(f=>`${f}.br`).concat("br"),a={},c="/",l=!!e.etag,u=!!e.single;if(typeof e.single=="string"){let f=e.single.lastIndexOf(".");c+=~f?e.single.substring(0,f):e.single}let p=[];e.ignores!==!1&&(p.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/),e.dotfiles?p.push(/\/\.\w/):p.push(/\/\.well-known/),[].concat(e.ignores||[]).forEach(f=>{p.push(new RegExp(f,"i"))}));let m=e.maxAge!=null&&`public,max-age=${e.maxAge}`;m&&e.immutable?m+=",immutable":m&&e.maxAge===0&&(m+=",must-revalidate"),e.dev||Kv(t,(f,h,g)=>{if(!/\.well-known[\\+\/]/.test(f)){if(!e.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(f))return}let v=NR(f,g,l);m&&(v["Cache-Control"]=m),a["/"+f.normalize().replace(/\\+/g,"/")]={abs:h,stats:g,headers:v}});let d=e.dev?uB.bind(0,t+iB,l):lB.bind(0,a);return function(f,h,g){let v=[""],_=RR(f).pathname,x=f.headers["accept-encoding"]||"";if(s&&x.includes("gzip")&&v.unshift(...s),i&&/(br|brotli)/i.test(x)&&v.unshift(...i),v.push(...o),_.indexOf("%")!==-1)try{_=decodeURI(_)}catch{}let k=d(_,v)||u&&!cB(_,p)&&d(c,v);if(!k)return g?g():r(f,h);if(l&&f.headers["if-none-match"]===k.headers.ETag)return h.writeHead(304),h.end();(s||i)&&h.setHeader("Vary","Accept-Encoding"),n(h,_,k.stats),dB(f,h,k.abs,k.stats,k.headers)}}var aB,fB,jR=w(()=>{TR();OR();IR();aB=()=>{};fB={".br":"br",".gz":"gzip"}});var pn=O((one,DR)=>{"use strict";var MR=["nodebuffer","arraybuffer","fragments"],LR=typeof Blob<"u";LR&&MR.push("blob");DR.exports={BINARY_TYPES:MR,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:LR,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ga=O((sne,xp)=>{"use strict";var{EMPTY_BUFFER:hB}=pn(),Yv=Buffer[Symbol.species];function gB(t,e){if(t.length===0)return hB;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let o=0;o<t.length;o++){let s=t[o];r.set(s,n),n+=s.length}return n<e?new Yv(r.buffer,r.byteOffset,n):r}function qR(t,e,r,n,o){for(let s=0;s<o;s++)r[n+s]=t[s]^e[s&3]}function ZR(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function yB(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function Xv(t){if(Xv.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new Yv(t):ArrayBuffer.isView(t)?e=new Yv(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),Xv.readOnly=!1),e}xp.exports={concat:gB,mask:qR,toArrayBuffer:yB,toBuffer:Xv,unmask:ZR};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=st("bufferutil");xp.exports.mask=function(e,r,n,o,s){s<48?qR(e,r,n,o,s):t.mask(e,r,n,o,s)},xp.exports.unmask=function(e,r){e.length<32?ZR(e,r):t.unmask(e,r)}}catch{}});var HR=O((ine,FR)=>{"use strict";var UR=Symbol("kDone"),Qv=Symbol("kRun"),e_=class{constructor(e){this[UR]=()=>{this.pending--,this[Qv]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[Qv]()}[Qv](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[UR])}}};FR.exports=e_});var Ja=O((ane,WR)=>{"use strict";var Wa=st("zlib"),BR=Ga(),vB=HR(),{kStatusCode:VR}=pn(),_B=Buffer[Symbol.species],bB=Buffer.from([0,0,255,255]),$p=Symbol("permessage-deflate"),dn=Symbol("total-length"),ni=Symbol("callback"),eo=Symbol("buffers"),oi=Symbol("error"),Sp,t_=class{constructor(e,r,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Sp){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Sp=new vB(o)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[ni];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),e}decompress(e,r,n){Sp.add(o=>{this._decompress(e,r,(s,i)=>{o(),n(s,i)})})}compress(e,r,n){Sp.add(o=>{this._compress(e,r,(s,i)=>{o(),n(s,i)})})}_decompress(e,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Wa.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Wa.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[$p]=this,this._inflate[dn]=0,this._inflate[eo]=[],this._inflate.on("error",xB),this._inflate.on("data",GR)}this._inflate[ni]=n,this._inflate.write(e),r&&this._inflate.write(bB),this._inflate.flush(()=>{let s=this._inflate[oi];if(s){this._inflate.close(),this._inflate=null,n(s);return}let i=BR.concat(this._inflate[eo],this._inflate[dn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[dn]=0,this._inflate[eo]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,i)})}_compress(e,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Wa.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Wa.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[dn]=0,this._deflate[eo]=[],this._deflate.on("data",wB)}this._deflate[ni]=n,this._deflate.write(e),this._deflate.flush(Wa.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=BR.concat(this._deflate[eo],this._deflate[dn]);r&&(s=new _B(s.buffer,s.byteOffset,s.length-4)),this._deflate[ni]=null,this._deflate[dn]=0,this._deflate[eo]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};WR.exports=t_;function wB(t){this[eo].push(t),this[dn]+=t.length}function GR(t){if(this[dn]+=t.length,this[$p]._maxPayload<1||this[dn]<=this[$p]._maxPayload){this[eo].push(t);return}this[oi]=new RangeError("Max payload size exceeded"),this[oi].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[oi][VR]=1009,this.removeListener("data",GR),this.reset()}function xB(t){if(this[$p]._inflate=null,this[oi]){this[ni](this[oi]);return}t[VR]=1007,this[ni](t)}});var si=O((cne,kp)=>{"use strict";var{isUtf8:JR}=st("buffer"),{hasBlob:SB}=pn(),$B=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function kB(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function r_(t){let e=t.length,r=0;for(;r<e;)if(!(t[r]&128))r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function EB(t){return SB&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}kp.exports={isBlob:EB,isValidStatusCode:kB,isValidUTF8:r_,tokenChars:$B};if(JR)kp.exports.isValidUTF8=function(t){return t.length<24?r_(t):JR(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=st("utf-8-validate");kp.exports.isValidUTF8=function(e){return e.length<32?r_(e):t(e)}}catch{}});var a_=O((lne,rO)=>{"use strict";var{Writable:TB}=st("stream"),KR=Ja(),{BINARY_TYPES:PB,EMPTY_BUFFER:YR,kStatusCode:RB,kWebSocket:OB}=pn(),{concat:n_,toArrayBuffer:CB,unmask:IB}=Ga(),{isValidStatusCode:AB,isValidUTF8:XR}=si(),Ep=Buffer[Symbol.species],yr=0,QR=1,eO=2,tO=3,o_=4,s_=5,Tp=6,i_=class extends TB{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||PB[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[OB]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=yr}_write(e,r,n){if(this._opcode===8&&this._state==yr)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Ep(n.buffer,n.byteOffset+e,n.length-e),new Ep(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],o=r.length-e;e>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),o),this._buffers[0]=new Ep(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case yr:this.getInfo(e);break;case QR:this.getPayloadLength16(e);break;case eO:this.getPayloadLength64(e);break;case tO:this.getMask();break;case o_:this.getData(e);break;case s_:case Tp:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if(r[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[KR.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=QR:this._payloadLength===127?this._state=eO:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=tO:this._state=o_}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=o_}getData(e){let r=YR;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&IB(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=s_,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[KR.extensionName].decompress(e,this._fin,(o,s)=>{if(o)return r(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===yr&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=yr;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=n_(n,r):this._binaryType==="arraybuffer"?o=CB(n_(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=yr):(this._state=Tp,setImmediate(()=>{this.emit("message",o,!0),this._state=yr,this.startLoop(e)}))}else{let o=n_(n,r);if(!this._skipUTF8Validation&&!XR(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===s_||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=yr):(this._state=Tp,setImmediate(()=>{this.emit("message",o,!1),this._state=yr,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,YR),this.end();else{let n=e.readUInt16BE(0);if(!AB(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new Ep(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!XR(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=yr;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=yr):(this._state=Tp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=yr,this.startLoop(r)}))}createError(e,r,n,o,s){this._loop=!1,this._errored=!0;let i=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[RB]=o,i}};rO.exports=i_});var u_=O((pne,sO)=>{"use strict";var{Duplex:une}=st("stream"),{randomFillSync:NB}=st("crypto"),nO=Ja(),{EMPTY_BUFFER:zB,kWebSocket:jB,NOOP:MB}=pn(),{isBlob:ii,isValidStatusCode:LB}=si(),{mask:oO,toBuffer:Ko}=Ga(),vr=Symbol("kByteLength"),DB=Buffer.alloc(4),Pp=8*1024,Yo,ai=Pp,Cr=0,qB=1,ZB=2,c_=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Cr,this.onerror=MB,this[jB]=void 0}static frame(e,r){let n,o=!1,s=2,i=!1;r.mask&&(n=r.maskBuffer||DB,r.generateMask?r.generateMask(n):(ai===Pp&&(Yo===void 0&&(Yo=Buffer.alloc(Pp)),NB(Yo,0,Pp),ai=0),n[0]=Yo[ai++],n[1]=Yo[ai++],n[2]=Yo[ai++],n[3]=Yo[ai++]),i=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||i)&&r[vr]!==void 0?a=r[vr]:(e=Buffer.from(e),a=e.length):(a=e.length,o=r.mask&&r.readOnly&&!i);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(o?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=n[0],l[s-3]=n[1],l[s-2]=n[2],l[s-1]=n[3],i?[l,e]:o?(oO(e,n,l,s,a),[l]):(oO(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,o){let s;if(e===void 0)s=zB;else{if(typeof e!="number"||!LB(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[vr]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Cr?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(t.frame(s,i),o)}ping(e,r,n){let o,s;if(typeof e=="string"?(o=Buffer.byteLength(e),s=!1):ii(e)?(o=e.size,s=!1):(e=Ko(e),o=e.length,s=Ko.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[vr]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ii(e)?this._state!==Cr?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==Cr?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}pong(e,r,n){let o,s;if(typeof e=="string"?(o=Buffer.byteLength(e),s=!1):ii(e)?(o=e.size,s=!1):(e=Ko(e),o=e.length,s=Ko.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[vr]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ii(e)?this._state!==Cr?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==Cr?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}send(e,r,n){let o=this._extensions[nO.extensionName],s=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):ii(e)?(a=e.size,c=!1):(e=Ko(e),a=e.length,c=Ko.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=o._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[vr]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:i};ii(e)?this._state!==Cr?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Cr?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,o){this._bufferedBytes+=n[vr],this._state=ZB,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(l_,this,a,o);return}this._bufferedBytes-=n[vr];let i=Ko(s);r?this.dispatch(i,r,n,o):(this._state=Cr,this.sendFrame(t.frame(i,n),o),this.dequeue())}).catch(s=>{process.nextTick(UB,this,s,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let s=this._extensions[nO.extensionName];this._bufferedBytes+=n[vr],this._state=qB,s.compress(e,n.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");l_(this,c,o);return}this._bufferedBytes-=n[vr],this._state=Cr,n.readOnly=!1,this.sendFrame(t.frame(a,n),o),this.dequeue()})}dequeue(){for(;this._state===Cr&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][vr],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][vr],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};sO.exports=c_;function l_(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let o=t._queue[n],s=o[o.length-1];typeof s=="function"&&s(e)}}function UB(t,e,r){l_(t,e,r),t.onerror(e)}});var mO=O((dne,fO)=>{"use strict";var{kForOnEventAttribute:Ka,kListener:p_}=pn(),iO=Symbol("kCode"),aO=Symbol("kData"),cO=Symbol("kError"),lO=Symbol("kMessage"),uO=Symbol("kReason"),ci=Symbol("kTarget"),pO=Symbol("kType"),dO=Symbol("kWasClean"),fn=class{constructor(e){this[ci]=null,this[pO]=e}get target(){return this[ci]}get type(){return this[pO]}};Object.defineProperty(fn.prototype,"target",{enumerable:!0});Object.defineProperty(fn.prototype,"type",{enumerable:!0});var Xo=class extends fn{constructor(e,r={}){super(e),this[iO]=r.code===void 0?0:r.code,this[uO]=r.reason===void 0?"":r.reason,this[dO]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[iO]}get reason(){return this[uO]}get wasClean(){return this[dO]}};Object.defineProperty(Xo.prototype,"code",{enumerable:!0});Object.defineProperty(Xo.prototype,"reason",{enumerable:!0});Object.defineProperty(Xo.prototype,"wasClean",{enumerable:!0});var li=class extends fn{constructor(e,r={}){super(e),this[cO]=r.error===void 0?null:r.error,this[lO]=r.message===void 0?"":r.message}get error(){return this[cO]}get message(){return this[lO]}};Object.defineProperty(li.prototype,"error",{enumerable:!0});Object.defineProperty(li.prototype,"message",{enumerable:!0});var Ya=class extends fn{constructor(e,r={}){super(e),this[aO]=r.data===void 0?null:r.data}get data(){return this[aO]}};Object.defineProperty(Ya.prototype,"data",{enumerable:!0});var FB={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Ka]&&o[p_]===e&&!o[Ka])return;let n;if(t==="message")n=function(s,i){let a=new Ya("message",{data:i?s:s.toString()});a[ci]=this,Rp(e,this,a)};else if(t==="close")n=function(s,i){let a=new Xo("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ci]=this,Rp(e,this,a)};else if(t==="error")n=function(s){let i=new li("error",{error:s,message:s.message});i[ci]=this,Rp(e,this,i)};else if(t==="open")n=function(){let s=new fn("open");s[ci]=this,Rp(e,this,s)};else return;n[Ka]=!!r[Ka],n[p_]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[p_]===e&&!r[Ka]){this.removeListener(t,r);break}}};fO.exports={CloseEvent:Xo,ErrorEvent:li,Event:fn,EventTarget:FB,MessageEvent:Ya};function Rp(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var d_=O((fne,hO)=>{"use strict";var{tokenChars:Xa}=si();function Wr(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function HB(t){let e=Object.create(null),r=Object.create(null),n=!1,o=!1,s=!1,i,a,c=-1,l=-1,u=-1,p=0;for(;p<t.length;p++)if(l=t.charCodeAt(p),i===void 0)if(u===-1&&Xa[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let d=t.slice(c,u);l===44?(Wr(e,d,r),r=Object.create(null)):i=d,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(u===-1&&Xa[l]===1)c===-1&&(c=p);else if(l===32||l===9)u===-1&&c!==-1&&(u=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),Wr(r,t.slice(c,u),!0),l===44&&(Wr(e,i,r),r=Object.create(null),i=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,p),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(Xa[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),o=!1}else if(s)if(Xa[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)s=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&t.charCodeAt(p-1)===61)s=!0;else if(u===-1&&Xa[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let d=t.slice(c,u);n&&(d=d.replace(/\\/g,""),n=!1),Wr(r,a,d),l===44&&(Wr(e,i,r),r=Object.create(null),i=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let m=t.slice(c,u);return i===void 0?Wr(e,m,r):(a===void 0?Wr(r,m,!0):n?Wr(r,a,m.replace(/\\/g,"")):Wr(r,a,m),Wr(e,i,r)),e}function BB(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(o=>{let s=n[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}hO.exports={format:BB,parse:HB}});var Ap=O((gne,TO)=>{"use strict";var VB=st("events"),GB=st("https"),WB=st("http"),vO=st("net"),JB=st("tls"),{randomBytes:KB,createHash:YB}=st("crypto"),{Duplex:mne,Readable:hne}=st("stream"),{URL:f_}=st("url"),to=Ja(),XB=a_(),QB=u_(),{isBlob:eV}=si(),{BINARY_TYPES:gO,CLOSE_TIMEOUT:tV,EMPTY_BUFFER:Op,GUID:rV,kForOnEventAttribute:m_,kListener:nV,kStatusCode:oV,kWebSocket:mt,NOOP:_O}=pn(),{EventTarget:{addEventListener:sV,removeEventListener:iV}}=mO(),{format:aV,parse:cV}=d_(),{toBuffer:lV}=Ga(),bO=Symbol("kAborted"),h_=[8,13],mn=["CONNECTING","OPEN","CLOSING","CLOSED"],uV=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ye=class t extends VB{constructor(e,r,n){super(),this._binaryType=gO[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Op,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),wO(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){gO.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let o=new XB({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new QB(e,this._extensions,n.generateMask);this._receiver=o,this._sender=s,this._socket=e,o[mt]=this,s[mt]=this,e[mt]=this,o.on("conclude",fV),o.on("drain",mV),o.on("error",hV),o.on("message",gV),o.on("ping",yV),o.on("pong",vV),s.onerror=_V,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",$O),e.on("data",Ip),e.on("end",kO),e.on("error",EO),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[to.extensionName]&&this._extensions[to.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){rr(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),SO(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){g_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Op,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){g_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Op,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){g_(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[to.extensionName]||(o.compress=!1),this._sender.send(e||Op,o,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){rr(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ye,"CONNECTING",{enumerable:!0,value:mn.indexOf("CONNECTING")});Object.defineProperty(Ye.prototype,"CONNECTING",{enumerable:!0,value:mn.indexOf("CONNECTING")});Object.defineProperty(Ye,"OPEN",{enumerable:!0,value:mn.indexOf("OPEN")});Object.defineProperty(Ye.prototype,"OPEN",{enumerable:!0,value:mn.indexOf("OPEN")});Object.defineProperty(Ye,"CLOSING",{enumerable:!0,value:mn.indexOf("CLOSING")});Object.defineProperty(Ye.prototype,"CLOSING",{enumerable:!0,value:mn.indexOf("CLOSING")});Object.defineProperty(Ye,"CLOSED",{enumerable:!0,value:mn.indexOf("CLOSED")});Object.defineProperty(Ye.prototype,"CLOSED",{enumerable:!0,value:mn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[m_])return e[nV];return null},set(e){for(let r of this.listeners(t))if(r[m_]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[m_]:!0})}})});Ye.prototype.addEventListener=sV;Ye.prototype.removeEventListener=iV;TO.exports=Ye;function wO(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:tV,protocolVersion:h_[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!h_.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${h_.join(", ")})`);let s;if(e instanceof f_)s=e;else try{s=new f_(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!i&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let h=new SyntaxError(c);if(t._redirects===0)throw h;Cp(t,h);return}let l=i?443:80,u=KB(16).toString("base64"),p=i?GB.request:WB.request,m=new Set,d;if(o.createConnection=o.createConnection||(i?dV:pV),o.defaultPort=o.defaultPort||l,o.port=s.port||l,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(d=new to(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=aV({[to.extensionName]:d.offer()})),r.length){for(let h of r){if(typeof h!="string"||!uV.test(h)||m.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");m.add(h)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),a){let h=o.path.split(":");o.socketPath=h[0],o.path=h[1]}let f;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?o.socketPath:s.host;let h=n&&n.headers;if(n={...n,headers:{}},h)for(let[g,v]of Object.entries(h))n.headers[g.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,h||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),f=t._req=p(o),t._redirects&&t.emit("redirect",t.url,f)}else f=t._req=p(o);o.timeout&&f.on("timeout",()=>{rr(t,f,"Opening handshake has timed out")}),f.on("error",h=>{f===null||f[bO]||(f=t._req=null,Cp(t,h))}),f.on("response",h=>{let g=h.headers.location,v=h.statusCode;if(g&&o.followRedirects&&v>=300&&v<400){if(++t._redirects>o.maxRedirects){rr(t,f,"Maximum redirects exceeded");return}f.abort();let _;try{_=new f_(g,e)}catch{let k=new SyntaxError(`Invalid URL: ${g}`);Cp(t,k);return}wO(t,_,r,n)}else t.emit("unexpected-response",f,h)||rr(t,f,`Unexpected server response: ${h.statusCode}`)}),f.on("upgrade",(h,g,v)=>{if(t.emit("upgrade",h),t.readyState!==Ye.CONNECTING)return;f=t._req=null;let _=h.headers.upgrade;if(_===void 0||_.toLowerCase()!=="websocket"){rr(t,g,"Invalid Upgrade header");return}let x=YB("sha1").update(u+rV).digest("base64");if(h.headers["sec-websocket-accept"]!==x){rr(t,g,"Invalid Sec-WebSocket-Accept header");return}let k=h.headers["sec-websocket-protocol"],I;if(k!==void 0?m.size?m.has(k)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":m.size&&(I="Server sent no subprotocol"),I){rr(t,g,I);return}k&&(t._protocol=k);let de=h.headers["sec-websocket-extensions"];if(de!==void 0){if(!d){rr(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let Y;try{Y=cV(de)}catch{rr(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ee=Object.keys(Y);if(ee.length!==1||ee[0]!==to.extensionName){rr(t,g,"Server indicated an extension that was not requested");return}try{d.accept(Y[to.extensionName])}catch{rr(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[to.extensionName]=d}t.setSocket(g,v,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(f,t):f.end()}function Cp(t,e){t._readyState=Ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function pV(t){return t.path=t.socketPath,vO.connect(t)}function dV(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=vO.isIP(t.host)?"":t.host),JB.connect(t)}function rr(t,e,r){t._readyState=Ye.CLOSING;let n=new Error(r);Error.captureStackTrace(n,rr),e.setHeader?(e[bO]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Cp,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function g_(t,e,r){if(e){let n=eV(e)?e.size:lV(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${mn[t.readyState]})`);process.nextTick(r,n)}}function fV(t,e){let r=this[mt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[mt]!==void 0&&(r._socket.removeListener("data",Ip),process.nextTick(xO,r._socket),t===1005?r.close():r.close(t,e))}function mV(){let t=this[mt];t.isPaused||t._socket.resume()}function hV(t){let e=this[mt];e._socket[mt]!==void 0&&(e._socket.removeListener("data",Ip),process.nextTick(xO,e._socket),e.close(t[oV])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function yO(){this[mt].emitClose()}function gV(t,e){this[mt].emit("message",t,e)}function yV(t){let e=this[mt];e._autoPong&&e.pong(t,!this._isServer,_O),e.emit("ping",t)}function vV(t){this[mt].emit("pong",t)}function xO(t){t.resume()}function _V(t){let e=this[mt];e.readyState!==Ye.CLOSED&&(e.readyState===Ye.OPEN&&(e._readyState=Ye.CLOSING,SO(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function SO(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function $O(){let t=this[mt];if(this.removeListener("close",$O),this.removeListener("data",Ip),this.removeListener("end",kO),t._readyState=Ye.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[mt]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",yO),t._receiver.on("finish",yO))}function Ip(t){this[mt]._receiver.write(t)||this.pause()}function kO(){let t=this[mt];t._readyState=Ye.CLOSING,t._receiver.end(),this.end()}function EO(){let t=this[mt];this.removeListener("error",EO),this.on("error",_O),t&&(t._readyState=Ye.CLOSING,this.destroy())}});var CO=O((vne,OO)=>{"use strict";var yne=Ap(),{Duplex:bV}=st("stream");function PO(t){t.emit("close")}function wV(){!this.destroyed&&this._writableState.finished&&this.destroy()}function RO(t){this.removeListener("error",RO),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function xV(t,e){let r=!0,n=new bV({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,i){let a=!i&&n._readableState.objectMode?s.toString():s;n.push(a)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,s){if(t.readyState===t.CLOSED){s(o),process.nextTick(PO,n);return}let i=!1;t.once("error",function(c){i=!0,s(c)}),t.once("close",function(){i||s(o),process.nextTick(PO,n)}),r&&t.terminate()},n._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(o,s,i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(o,s,i)});return}t.send(o,i)},n.on("end",wV),n.on("error",RO),n}OO.exports=xV});var AO=O((_ne,IO)=>{"use strict";var{tokenChars:SV}=si();function $V(t){let e=new Set,r=-1,n=-1,o=0;for(o;o<t.length;o++){let i=t.charCodeAt(o);if(n===-1&&SV[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))n===-1&&r!==-1&&(n=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,o);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}IO.exports={parse:$V}});var qO=O((wne,DO)=>{"use strict";var kV=st("events"),Np=st("http"),{Duplex:bne}=st("stream"),{createHash:EV}=st("crypto"),NO=d_(),Qo=Ja(),TV=AO(),PV=Ap(),{CLOSE_TIMEOUT:RV,GUID:OV,kWebSocket:CV}=pn(),IV=/^[+/0-9A-Za-z]{22}==$/,zO=0,jO=1,LO=2,y_=class extends kV{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:RV,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:PV,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Np.createServer((n,o)=>{let s=Np.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=AV(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,s,i)=>{this.handleUpgrade(o,s,i,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=zO}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===LO){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Qa,this);return}if(e&&this.once("close",e),this._state!==jO)if(this._state=jO,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(Qa,this):process.nextTick(Qa,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{Qa(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,o){r.on("error",MO);let s=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){es(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){es(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!IV.test(s)){es(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){es(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ec(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=TV.parse(c)}catch{es(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let m=new Qo(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let d=NO.parse(u);d[Qo.extensionName]&&(m.accept(d[Qo.extensionName]),p[Qo.extensionName]=m)}catch{es(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let m={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(m,(d,f,h,g)=>{if(!d)return ec(r,f||401,h,g);this.completeUpgrade(p,s,l,e,r,n,o)});return}if(!this.options.verifyClient(m))return ec(r,401)}this.completeUpgrade(p,s,l,e,r,n,o)}completeUpgrade(e,r,n,o,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[CV])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>zO)return ec(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${EV("sha1").update(r+OV).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(e[Qo.extensionName]){let p=e[Qo.extensionName].params,m=NO.format({[Qo.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${m}`),u._extensions=e}this.emit("headers",l,o),s.write(l.concat(`\r
404
+ `);this.buffer=r.pop();for(let n of r)if(n)try{let o=JSON.parse(n);if(o.type==="forward"){let s=this.handlers.get(o.topic);if(s)for(let i of s)i(o.event)}}catch{}}}});import{join as r_,resolve as bB}from"path";import{readdirSync as wB,statSync as xB}from"fs";function n_(t,e,r=""){t=bB(".",t);let n=wB(t),o=0,s,i;for(;o<n.length;o++)s=r_(t,n[o]),i=xB(s),i.isDirectory()?n_(s,e,r_(r,n[o])):e(r_(r,n[o]),s,i)}var jR=w(()=>{});import*as MR from"node:querystring";function LR(t){let e=t.url;if(e==null)return;let r=t._parsedUrl;if(r&&r.raw===e)return r;let n=e,o="",s,i;if(e.length>1){let a=e.indexOf("#",1);a!==-1&&(i=e.substring(a),n=e.substring(0,a)),a=n.indexOf("?",1),a!==-1&&(o=n.substring(a),n=n.substring(0,a),o.length>1&&(s=MR.parse(o.substring(1))))}return t._parsedUrl={pathname:n,search:o,query:s,hash:i,raw:e}}var DR=w(()=>{});function qR(t){let e=(""+t).trim().toLowerCase(),r=e.lastIndexOf(".");return SB[~r?e.substring(++r):e]}var SB,ZR=w(()=>{SB={"3g2":"video/3gpp2","3gp":"video/3gpp","3gpp":"video/3gpp","3mf":"model/3mf",aac:"audio/aac",ac:"application/pkix-attr-cert",adp:"audio/adpcm",adts:"audio/aac",ai:"application/postscript",aml:"application/automationml-aml+xml",amlx:"application/automationml-amlx+zip",amr:"audio/amr",apng:"image/apng",appcache:"text/cache-manifest",appinstaller:"application/appinstaller",appx:"application/appx",appxbundle:"application/appxbundle",asc:"application/pgp-keys",atom:"application/atom+xml",atomcat:"application/atomcat+xml",atomdeleted:"application/atomdeleted+xml",atomsvc:"application/atomsvc+xml",au:"audio/basic",avci:"image/avci",avcs:"image/avcs",avif:"image/avif",aw:"application/applixware",bdoc:"application/bdoc",bin:"application/octet-stream",bmp:"image/bmp",bpk:"application/octet-stream",btf:"image/prs.btif",btif:"image/prs.btif",buffer:"application/octet-stream",ccxml:"application/ccxml+xml",cdfx:"application/cdfx+xml",cdmia:"application/cdmi-capability",cdmic:"application/cdmi-container",cdmid:"application/cdmi-domain",cdmio:"application/cdmi-object",cdmiq:"application/cdmi-queue",cer:"application/pkix-cert",cgm:"image/cgm",cjs:"application/node",class:"application/java-vm",coffee:"text/coffeescript",conf:"text/plain",cpl:"application/cpl+xml",cpt:"application/mac-compactpro",crl:"application/pkix-crl",css:"text/css",csv:"text/csv",cu:"application/cu-seeme",cwl:"application/cwl",cww:"application/prs.cww",davmount:"application/davmount+xml",dbk:"application/docbook+xml",deb:"application/octet-stream",def:"text/plain",deploy:"application/octet-stream",dib:"image/bmp","disposition-notification":"message/disposition-notification",dist:"application/octet-stream",distz:"application/octet-stream",dll:"application/octet-stream",dmg:"application/octet-stream",dms:"application/octet-stream",doc:"application/msword",dot:"application/msword",dpx:"image/dpx",drle:"image/dicom-rle",dsc:"text/prs.lines.tag",dssc:"application/dssc+der",dtd:"application/xml-dtd",dump:"application/octet-stream",dwd:"application/atsc-dwd+xml",ear:"application/java-archive",ecma:"application/ecmascript",elc:"application/octet-stream",emf:"image/emf",eml:"message/rfc822",emma:"application/emma+xml",emotionml:"application/emotionml+xml",eps:"application/postscript",epub:"application/epub+zip",exe:"application/octet-stream",exi:"application/exi",exp:"application/express",exr:"image/aces",ez:"application/andrew-inset",fdf:"application/fdf",fdt:"application/fdt+xml",fits:"image/fits",g3:"image/g3fax",gbr:"application/rpki-ghostbusters",geojson:"application/geo+json",gif:"image/gif",glb:"model/gltf-binary",gltf:"model/gltf+json",gml:"application/gml+xml",gpx:"application/gpx+xml",gram:"application/srgs",grxml:"application/srgs+xml",gxf:"application/gxf",gz:"application/gzip",h261:"video/h261",h263:"video/h263",h264:"video/h264",heic:"image/heic",heics:"image/heic-sequence",heif:"image/heif",heifs:"image/heif-sequence",hej2:"image/hej2k",held:"application/atsc-held+xml",hjson:"application/hjson",hlp:"application/winhlp",hqx:"application/mac-binhex40",hsj2:"image/hsj2",htm:"text/html",html:"text/html",ics:"text/calendar",ief:"image/ief",ifb:"text/calendar",iges:"model/iges",igs:"model/iges",img:"application/octet-stream",in:"text/plain",ini:"text/plain",ink:"application/inkml+xml",inkml:"application/inkml+xml",ipfix:"application/ipfix",iso:"application/octet-stream",its:"application/its+xml",jade:"text/jade",jar:"application/java-archive",jhc:"image/jphc",jls:"image/jls",jp2:"image/jp2",jpe:"image/jpeg",jpeg:"image/jpeg",jpf:"image/jpx",jpg:"image/jpeg",jpg2:"image/jp2",jpgm:"image/jpm",jpgv:"video/jpeg",jph:"image/jph",jpm:"image/jpm",jpx:"image/jpx",js:"text/javascript",json:"application/json",json5:"application/json5",jsonld:"application/ld+json",jsonml:"application/jsonml+json",jsx:"text/jsx",jt:"model/jt",jxl:"image/jxl",jxr:"image/jxr",jxra:"image/jxra",jxrs:"image/jxrs",jxs:"image/jxs",jxsc:"image/jxsc",jxsi:"image/jxsi",jxss:"image/jxss",kar:"audio/midi",ktx:"image/ktx",ktx2:"image/ktx2",less:"text/less",lgr:"application/lgr+xml",list:"text/plain",litcoffee:"text/coffeescript",log:"text/plain",lostxml:"application/lost+xml",lrf:"application/octet-stream",m1v:"video/mpeg",m21:"application/mp21",m2a:"audio/mpeg",m2t:"video/mp2t",m2ts:"video/mp2t",m2v:"video/mpeg",m3a:"audio/mpeg",m4a:"audio/mp4",m4p:"application/mp4",m4s:"video/iso.segment",ma:"application/mathematica",mads:"application/mads+xml",maei:"application/mmt-aei+xml",man:"text/troff",manifest:"text/cache-manifest",map:"application/json",mar:"application/octet-stream",markdown:"text/markdown",mathml:"application/mathml+xml",mb:"application/mathematica",mbox:"application/mbox",md:"text/markdown",mdx:"text/mdx",me:"text/troff",mesh:"model/mesh",meta4:"application/metalink4+xml",metalink:"application/metalink+xml",mets:"application/mets+xml",mft:"application/rpki-manifest",mid:"audio/midi",midi:"audio/midi",mime:"message/rfc822",mj2:"video/mj2",mjp2:"video/mj2",mjs:"text/javascript",mml:"text/mathml",mods:"application/mods+xml",mov:"video/quicktime",mp2:"audio/mpeg",mp21:"application/mp21",mp2a:"audio/mpeg",mp3:"audio/mpeg",mp4:"video/mp4",mp4a:"audio/mp4",mp4s:"application/mp4",mp4v:"video/mp4",mpd:"application/dash+xml",mpe:"video/mpeg",mpeg:"video/mpeg",mpf:"application/media-policy-dataset+xml",mpg:"video/mpeg",mpg4:"video/mp4",mpga:"audio/mpeg",mpp:"application/dash-patch+xml",mrc:"application/marc",mrcx:"application/marcxml+xml",ms:"text/troff",mscml:"application/mediaservercontrol+xml",msh:"model/mesh",msi:"application/octet-stream",msix:"application/msix",msixbundle:"application/msixbundle",msm:"application/octet-stream",msp:"application/octet-stream",mtl:"model/mtl",mts:"video/mp2t",musd:"application/mmt-usd+xml",mxf:"application/mxf",mxmf:"audio/mobile-xmf",mxml:"application/xv+xml",n3:"text/n3",nb:"application/mathematica",nq:"application/n-quads",nt:"application/n-triples",obj:"model/obj",oda:"application/oda",oga:"audio/ogg",ogg:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",omdoc:"application/omdoc+xml",onepkg:"application/onenote",onetmp:"application/onenote",onetoc:"application/onenote",onetoc2:"application/onenote",opf:"application/oebps-package+xml",opus:"audio/ogg",otf:"font/otf",owl:"application/rdf+xml",oxps:"application/oxps",p10:"application/pkcs10",p7c:"application/pkcs7-mime",p7m:"application/pkcs7-mime",p7s:"application/pkcs7-signature",p8:"application/pkcs8",pdf:"application/pdf",pfr:"application/font-tdpfr",pgp:"application/pgp-encrypted",pkg:"application/octet-stream",pki:"application/pkixcmp",pkipath:"application/pkix-pkipath",pls:"application/pls+xml",png:"image/png",prc:"model/prc",prf:"application/pics-rules",provx:"application/provenance+xml",ps:"application/postscript",pskcxml:"application/pskc+xml",pti:"image/prs.pti",qt:"video/quicktime",raml:"application/raml+yaml",rapd:"application/route-apd+xml",rdf:"application/rdf+xml",relo:"application/p2p-overlay+xml",rif:"application/reginfo+xml",rl:"application/resource-lists+xml",rld:"application/resource-lists-diff+xml",rmi:"audio/midi",rnc:"application/relax-ng-compact-syntax",rng:"application/xml",roa:"application/rpki-roa",roff:"text/troff",rq:"application/sparql-query",rs:"application/rls-services+xml",rsat:"application/atsc-rsat+xml",rsd:"application/rsd+xml",rsheet:"application/urc-ressheet+xml",rss:"application/rss+xml",rtf:"text/rtf",rtx:"text/richtext",rusd:"application/route-usd+xml",s3m:"audio/s3m",sbml:"application/sbml+xml",scq:"application/scvp-cv-request",scs:"application/scvp-cv-response",sdp:"application/sdp",senmlx:"application/senml+xml",sensmlx:"application/sensml+xml",ser:"application/java-serialized-object",setpay:"application/set-payment-initiation",setreg:"application/set-registration-initiation",sgi:"image/sgi",sgm:"text/sgml",sgml:"text/sgml",shex:"text/shex",shf:"application/shf+xml",shtml:"text/html",sieve:"application/sieve",sig:"application/pgp-signature",sil:"audio/silk",silo:"model/mesh",siv:"application/sieve",slim:"text/slim",slm:"text/slim",sls:"application/route-s-tsid+xml",smi:"application/smil+xml",smil:"application/smil+xml",snd:"audio/basic",so:"application/octet-stream",spdx:"text/spdx",spp:"application/scvp-vp-response",spq:"application/scvp-vp-request",spx:"audio/ogg",sql:"application/sql",sru:"application/sru+xml",srx:"application/sparql-results+xml",ssdl:"application/ssdl+xml",ssml:"application/ssml+xml",stk:"application/hyperstudio",stl:"model/stl",stpx:"model/step+xml",stpxz:"model/step-xml+zip",stpz:"model/step+zip",styl:"text/stylus",stylus:"text/stylus",svg:"image/svg+xml",svgz:"image/svg+xml",swidtag:"application/swid+xml",t:"text/troff",t38:"image/t38",td:"application/urc-targetdesc+xml",tei:"application/tei+xml",teicorpus:"application/tei+xml",text:"text/plain",tfi:"application/thraud+xml",tfx:"image/tiff-fx",tif:"image/tiff",tiff:"image/tiff",toml:"application/toml",tr:"text/troff",trig:"application/trig",ts:"video/mp2t",tsd:"application/timestamped-data",tsv:"text/tab-separated-values",ttc:"font/collection",ttf:"font/ttf",ttl:"text/turtle",ttml:"application/ttml+xml",txt:"text/plain",u3d:"model/u3d",u8dsn:"message/global-delivery-status",u8hdr:"message/global-headers",u8mdn:"message/global-disposition-notification",u8msg:"message/global",ubj:"application/ubjson",uri:"text/uri-list",uris:"text/uri-list",urls:"text/uri-list",vcard:"text/vcard",vrml:"model/vrml",vtt:"text/vtt",vxml:"application/voicexml+xml",war:"application/java-archive",wasm:"application/wasm",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webmanifest:"application/manifest+json",webp:"image/webp",wgsl:"text/wgsl",wgt:"application/widget",wif:"application/watcherinfo+xml",wmf:"image/wmf",woff:"font/woff",woff2:"font/woff2",wrl:"model/vrml",wsdl:"application/wsdl+xml",wspolicy:"application/wspolicy+xml",x3d:"model/x3d+xml",x3db:"model/x3d+fastinfoset",x3dbz:"model/x3d+binary",x3dv:"model/x3d-vrml",x3dvz:"model/x3d+vrml",x3dz:"model/x3d+xml",xaml:"application/xaml+xml",xav:"application/xcap-att+xml",xca:"application/xcap-caps+xml",xcs:"application/calendar+xml",xdf:"application/xcap-diff+xml",xdssc:"application/dssc+xml",xel:"application/xcap-el+xml",xenc:"application/xenc+xml",xer:"application/patch-ops-error+xml",xfdf:"application/xfdf",xht:"application/xhtml+xml",xhtml:"application/xhtml+xml",xhvml:"application/xv+xml",xlf:"application/xliff+xml",xm:"audio/xm",xml:"text/xml",xns:"application/xcap-ns+xml",xop:"application/xop+xml",xpl:"application/xproc+xml",xsd:"application/xml",xsf:"application/prs.xsf+xml",xsl:"application/xml",xslt:"application/xml",xspf:"application/xspf+xml",xvm:"application/xv+xml",xvml:"application/xv+xml",yaml:"text/yaml",yang:"application/yang",yin:"application/yin+xml",yml:"text/yaml",zip:"application/zip"}});var HR={};K(HR,{default:()=>zB});import*as oi from"node:fs";import{join as $B,normalize as kB,resolve as EB,sep as TB}from"node:path";function RB(t,e){for(let r=0;r<e.length;r++)if(e[r].test(t))return!0}function UR(t,e){let r=0,n,o=t.length-1;t.charCodeAt(o)===47&&(t=t.substring(0,o));let s=[],i=`${t}/index`;for(;r<e.length;r++)n=e[r]?`.${e[r]}`:"",t&&s.push(t+n),s.push(i+n);return s}function OB(t,e,r){let n=0,o,s=UR(e,r);for(;n<s.length;n++)if(o=t[s[n]])return o}function CB(t,e,r,n){let o=0,s=UR(r,n),i,a,c,l;for(;o<s.length;o++)if(i=kB($B(t,c=s[o])),i.startsWith(t)&&oi.existsSync(i)){if(a=oi.statSync(i),a.isDirectory())continue;return l=FR(c,a,e),l["Cache-Control"]=e?"no-cache":"no-store",{abs:i,stats:a,headers:l}}}function IB(t,e){return e.statusCode=404,e.end()}function AB(t,e,r,n,o){let s=200,i,a={};o={...o};for(let c in o)i=e.getHeader(c),i&&(o[c]=i);if((i=e.getHeader("content-type"))&&(o["Content-Type"]=i),t.headers.range){s=206;let[c,l]=t.headers.range.replace("bytes=","").split("-"),u=a.end=parseInt(l,10)||n.size-1,p=a.start=parseInt(c,10)||0;if(u>=n.size&&(u=n.size-1),p>=n.size)return e.setHeader("Content-Range",`bytes */${n.size}`),e.statusCode=416,e.end();o["Content-Range"]=`bytes ${p}-${u}/${n.size}`,o["Content-Length"]=u-p+1,o["Accept-Ranges"]="bytes"}e.writeHead(s,o),oi.createReadStream(r,a).pipe(e)}function FR(t,e,r){let n=NB[t.slice(-3)],o=qR(t.slice(0,n&&-3))||"";o==="text/html"&&(o+=";charset=utf-8");let s={"Content-Length":e.size,"Content-Type":o,"Last-Modified":e.mtime.toUTCString()};return n&&(s["Content-Encoding"]=n),r&&(s.ETag=`W/"${e.size}-${e.mtime.getTime()}"`),s}function zB(t,e={}){t=EB(t||".");let r=e.onNoMatch||IB,n=e.setHeaders||PB,o=e.extensions||["html","htm"],s=e.gzip&&o.map(m=>`${m}.gz`).concat("gz"),i=e.brotli&&o.map(m=>`${m}.br`).concat("br"),a={},c="/",l=!!e.etag,u=!!e.single;if(typeof e.single=="string"){let m=e.single.lastIndexOf(".");c+=~m?e.single.substring(0,m):e.single}let p=[];e.ignores!==!1&&(p.push(/[/]([A-Za-z\s\d~$._-]+\.\w+){1,}$/),e.dotfiles?p.push(/\/\.\w/):p.push(/\/\.well-known/),[].concat(e.ignores||[]).forEach(m=>{p.push(new RegExp(m,"i"))}));let f=e.maxAge!=null&&`public,max-age=${e.maxAge}`;f&&e.immutable?f+=",immutable":f&&e.maxAge===0&&(f+=",must-revalidate"),e.dev||n_(t,(m,h,g)=>{if(!/\.well-known[\\+\/]/.test(m)){if(!e.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(m))return}let v=FR(m,g,l);f&&(v["Cache-Control"]=f),a["/"+m.normalize().replace(/\\+/g,"/")]={abs:h,stats:g,headers:v}});let d=e.dev?CB.bind(0,t+TB,l):OB.bind(0,a);return function(m,h,g){let v=[""],b=LR(m).pathname,x=m.headers["accept-encoding"]||"";if(s&&x.includes("gzip")&&v.unshift(...s),i&&/(br|brotli)/i.test(x)&&v.unshift(...i),v.push(...o),b.indexOf("%")!==-1)try{b=decodeURI(b)}catch{}let $=d(b,v)||u&&!RB(b,p)&&d(c,v);if(!$)return g?g():r(m,h);if(l&&m.headers["if-none-match"]===$.headers.ETag)return h.writeHead(304),h.end();(s||i)&&h.setHeader("Vary","Accept-Encoding"),n(h,b,$.stats),AB(m,h,$.abs,$.stats,$.headers)}}var PB,NB,BR=w(()=>{jR();DR();ZR();PB=()=>{};NB={".br":"br",".gz":"gzip"}});var pn=I((Zne,WR)=>{"use strict";var GR=["nodebuffer","arraybuffer","fragments"],VR=typeof Blob<"u";VR&&GR.push("blob");WR.exports={BINARY_TYPES:GR,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:VR,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Ka=I((Une,Ep)=>{"use strict";var{EMPTY_BUFFER:jB}=pn(),o_=Buffer[Symbol.species];function MB(t,e){if(t.length===0)return jB;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(e),n=0;for(let o=0;o<t.length;o++){let s=t[o];r.set(s,n),n+=s.length}return n<e?new o_(r.buffer,r.byteOffset,n):r}function JR(t,e,r,n,o){for(let s=0;s<o;s++)r[n+s]=t[s]^e[s&3]}function KR(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function LB(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function s_(t){if(s_.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new o_(t):ArrayBuffer.isView(t)?e=new o_(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),s_.readOnly=!1),e}Ep.exports={concat:MB,mask:JR,toArrayBuffer:LB,toBuffer:s_,unmask:KR};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=st("bufferutil");Ep.exports.mask=function(e,r,n,o,s){s<48?JR(e,r,n,o,s):t.mask(e,r,n,o,s)},Ep.exports.unmask=function(e,r){e.length<32?KR(e,r):t.unmask(e,r)}}catch{}});var QR=I((Fne,XR)=>{"use strict";var YR=Symbol("kDone"),i_=Symbol("kRun"),a_=class{constructor(e){this[YR]=()=>{this.pending--,this[i_]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[i_]()}[i_](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[YR])}}};XR.exports=a_});var Xa=I((Hne,nO)=>{"use strict";var Ya=st("zlib"),eO=Ka(),DB=QR(),{kStatusCode:tO}=pn(),qB=Buffer[Symbol.species],ZB=Buffer.from([0,0,255,255]),Pp=Symbol("permessage-deflate"),dn=Symbol("total-length"),si=Symbol("callback"),eo=Symbol("buffers"),ii=Symbol("error"),Tp,c_=class{constructor(e,r,n){if(this._maxPayload=n|0,this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._isServer=!!r,this._deflate=null,this._inflate=null,this.params=null,!Tp){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Tp=new DB(o)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[si];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let r=this._options,n=e.find(o=>!(r.serverNoContextTakeover===!1&&o.server_no_context_takeover||o.server_max_window_bits&&(r.serverMaxWindowBits===!1||typeof r.serverMaxWindowBits=="number"&&r.serverMaxWindowBits>o.server_max_window_bits)||typeof r.clientMaxWindowBits=="number"&&!o.client_max_window_bits));if(!n)throw new Error("None of the extension offers can be accepted");return r.serverNoContextTakeover&&(n.server_no_context_takeover=!0),r.clientNoContextTakeover&&(n.client_no_context_takeover=!0),typeof r.serverMaxWindowBits=="number"&&(n.server_max_window_bits=r.serverMaxWindowBits),typeof r.clientMaxWindowBits=="number"?n.client_max_window_bits=r.clientMaxWindowBits:(n.client_max_window_bits===!0||r.clientMaxWindowBits===!1)&&delete n.client_max_window_bits,n}acceptAsClient(e){let r=e[0];if(this._options.clientNoContextTakeover===!1&&r.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!r.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(r.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&r.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return r}normalizeParams(e){return e.forEach(r=>{Object.keys(r).forEach(n=>{let o=r[n];if(o.length>1)throw new Error(`Parameter "${n}" must have only a single value`);if(o=o[0],n==="client_max_window_bits"){if(o!==!0){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=s}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else if(n==="server_max_window_bits"){let s=+o;if(!Number.isInteger(s)||s<8||s>15)throw new TypeError(`Invalid value for parameter "${n}": ${o}`);o=s}else if(n==="client_no_context_takeover"||n==="server_no_context_takeover"){if(o!==!0)throw new TypeError(`Invalid value for parameter "${n}": ${o}`)}else throw new Error(`Unknown parameter "${n}"`);r[n]=o})}),e}decompress(e,r,n){Tp.add(o=>{this._decompress(e,r,(s,i)=>{o(),n(s,i)})})}compress(e,r,n){Tp.add(o=>{this._compress(e,r,(s,i)=>{o(),n(s,i)})})}_decompress(e,r,n){let o=this._isServer?"client":"server";if(!this._inflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Ya.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=Ya.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Pp]=this,this._inflate[dn]=0,this._inflate[eo]=[],this._inflate.on("error",FB),this._inflate.on("data",rO)}this._inflate[si]=n,this._inflate.write(e),r&&this._inflate.write(ZB),this._inflate.flush(()=>{let s=this._inflate[ii];if(s){this._inflate.close(),this._inflate=null,n(s);return}let i=eO.concat(this._inflate[eo],this._inflate[dn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[dn]=0,this._inflate[eo]=[],r&&this.params[`${o}_no_context_takeover`]&&this._inflate.reset()),n(null,i)})}_compress(e,r,n){let o=this._isServer?"server":"client";if(!this._deflate){let s=`${o}_max_window_bits`,i=typeof this.params[s]!="number"?Ya.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=Ya.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[dn]=0,this._deflate[eo]=[],this._deflate.on("data",UB)}this._deflate[si]=n,this._deflate.write(e),this._deflate.flush(Ya.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=eO.concat(this._deflate[eo],this._deflate[dn]);r&&(s=new qB(s.buffer,s.byteOffset,s.length-4)),this._deflate[si]=null,this._deflate[dn]=0,this._deflate[eo]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};nO.exports=c_;function UB(t){this[eo].push(t),this[dn]+=t.length}function rO(t){if(this[dn]+=t.length,this[Pp]._maxPayload<1||this[dn]<=this[Pp]._maxPayload){this[eo].push(t);return}this[ii]=new RangeError("Max payload size exceeded"),this[ii].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ii][tO]=1009,this.removeListener("data",rO),this.reset()}function FB(t){if(this[Pp]._inflate=null,this[ii]){this[si](this[ii]);return}t[tO]=1007,this[si](t)}});var ai=I((Bne,Rp)=>{"use strict";var{isUtf8:oO}=st("buffer"),{hasBlob:HB}=pn(),BB=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function GB(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function l_(t){let e=t.length,r=0;for(;r<e;)if(!(t[r]&128))r++;else if((t[r]&224)===192){if(r+1===e||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=e||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function VB(t){return HB&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Rp.exports={isBlob:VB,isValidStatusCode:GB,isValidUTF8:l_,tokenChars:BB};if(oO)Rp.exports.isValidUTF8=function(t){return t.length<24?l_(t):oO(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=st("utf-8-validate");Rp.exports.isValidUTF8=function(e){return e.length<32?l_(e):t(e)}}catch{}});var m_=I((Gne,pO)=>{"use strict";var{Writable:WB}=st("stream"),sO=Xa(),{BINARY_TYPES:JB,EMPTY_BUFFER:iO,kStatusCode:KB,kWebSocket:YB}=pn(),{concat:u_,toArrayBuffer:XB,unmask:QB}=Ka(),{isValidStatusCode:eG,isValidUTF8:aO}=ai(),Op=Buffer[Symbol.species],vr=0,cO=1,lO=2,uO=3,p_=4,d_=5,Cp=6,f_=class extends WB{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||JB[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[YB]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=vr}_write(e,r,n){if(this._opcode===8&&this._state==vr)return n();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(n)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let n=this._buffers[0];return this._buffers[0]=new Op(n.buffer,n.byteOffset+e,n.length-e),new Op(n.buffer,n.byteOffset,e)}let r=Buffer.allocUnsafe(e);do{let n=this._buffers[0],o=r.length-e;e>=n.length?r.set(this._buffers.shift(),o):(r.set(new Uint8Array(n.buffer,n.byteOffset,e),o),this._buffers[0]=new Op(n.buffer,n.byteOffset+e,n.length-e)),e-=n.length}while(e>0);return r}startLoop(e){this._loop=!0;do switch(this._state){case vr:this.getInfo(e);break;case cO:this.getPayloadLength16(e);break;case lO:this.getPayloadLength64(e);break;case uO:this.getMask();break;case p_:this.getData(e);break;case d_:case Cp:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let r=this.consume(2);if(r[0]&48){let o=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(o);return}let n=(r[0]&64)===64;if(n&&!this._extensions[sO.extensionName]){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._fin=(r[0]&128)===128,this._opcode=r[0]&15,this._payloadLength=r[1]&127,this._opcode===0){if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(!this._fragmented){let o=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}this._compressed=n}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let o=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(o);return}if(n){let o=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(o);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let o=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(o);return}}else{let o=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(o);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(r[1]&128)===128,this._isServer){if(!this._masked){let o=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(o);return}}else if(this._masked){let o=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(o);return}this._payloadLength===126?this._state=cO:this._payloadLength===127?this._state=lO:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let r=this.consume(8),n=r.readUInt32BE(0);if(n>Math.pow(2,21)-1){let o=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(o);return}this._payloadLength=n*Math.pow(2,32)+r.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let r=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(r);return}this._masked?this._state=uO:this._state=p_}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=p_}getData(e){let r=iO;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}r=this.consume(this._payloadLength),this._masked&&this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3]&&QB(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=d_,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[sO.extensionName].decompress(e,this._fin,(o,s)=>{if(o)return r(o);if(s.length){if(this._messageLength+=s.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let i=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");r(i);return}this._fragments.push(s)}this.dataMessage(r),this._state===vr&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=vr;return}let r=this._messageLength,n=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let o;this._binaryType==="nodebuffer"?o=u_(n,r):this._binaryType==="arraybuffer"?o=XB(u_(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=vr):(this._state=Cp,setImmediate(()=>{this.emit("message",o,!0),this._state=vr,this.startLoop(e)}))}else{let o=u_(n,r);if(!this._skipUTF8Validation&&!aO(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===d_||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=vr):(this._state=Cp,setImmediate(()=>{this.emit("message",o,!1),this._state=vr,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,iO),this.end();else{let n=e.readUInt16BE(0);if(!eG(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new Op(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!aO(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");r(s);return}this._loop=!1,this.emit("conclude",n,o),this.end()}this._state=vr;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=vr):(this._state=Cp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=vr,this.startLoop(r)}))}createError(e,r,n,o,s){this._loop=!1,this._errored=!0;let i=new e(n?`Invalid WebSocket frame: ${r}`:r);return Error.captureStackTrace(i,this.createError),i.code=s,i[KB]=o,i}};pO.exports=f_});var y_=I((Wne,mO)=>{"use strict";var{Duplex:Vne}=st("stream"),{randomFillSync:tG}=st("crypto"),dO=Xa(),{EMPTY_BUFFER:rG,kWebSocket:nG,NOOP:oG}=pn(),{isBlob:ci,isValidStatusCode:sG}=ai(),{mask:fO,toBuffer:Yo}=Ka(),_r=Symbol("kByteLength"),iG=Buffer.alloc(4),Ip=8*1024,Xo,li=Ip,Cr=0,aG=1,cG=2,h_=class t{constructor(e,r,n){this._extensions=r||{},n&&(this._generateMask=n,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=Cr,this.onerror=oG,this[nG]=void 0}static frame(e,r){let n,o=!1,s=2,i=!1;r.mask&&(n=r.maskBuffer||iG,r.generateMask?r.generateMask(n):(li===Ip&&(Xo===void 0&&(Xo=Buffer.alloc(Ip)),tG(Xo,0,Ip),li=0),n[0]=Xo[li++],n[1]=Xo[li++],n[2]=Xo[li++],n[3]=Xo[li++]),i=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||i)&&r[_r]!==void 0?a=r[_r]:(e=Buffer.from(e),a=e.length):(a=e.length,o=r.mask&&r.readOnly&&!i);let c=a;a>=65536?(s+=8,c=127):a>125&&(s+=2,c=126);let l=Buffer.allocUnsafe(o?a+s:s);return l[0]=r.fin?r.opcode|128:r.opcode,r.rsv1&&(l[0]|=64),l[1]=c,c===126?l.writeUInt16BE(a,2):c===127&&(l[2]=l[3]=0,l.writeUIntBE(a,4,6)),r.mask?(l[1]|=128,l[s-4]=n[0],l[s-3]=n[1],l[s-2]=n[2],l[s-1]=n[3],i?[l,e]:o?(fO(e,n,l,s,a),[l]):(fO(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,o){let s;if(e===void 0)s=rG;else{if(typeof e!="number"||!sG(e))throw new TypeError("First argument must be a valid error code number");if(r===void 0||!r.length)s=Buffer.allocUnsafe(2),s.writeUInt16BE(e,0);else{let a=Buffer.byteLength(r);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");s=Buffer.allocUnsafe(2+a),s.writeUInt16BE(e,0),typeof r=="string"?s.write(r,2):s.set(r,2)}}let i={[_r]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Cr?this.enqueue([this.dispatch,s,!1,i,o]):this.sendFrame(t.frame(s,i),o)}ping(e,r,n){let o,s;if(typeof e=="string"?(o=Buffer.byteLength(e),s=!1):ci(e)?(o=e.size,s=!1):(e=Yo(e),o=e.length,s=Yo.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[_r]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};ci(e)?this._state!==Cr?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==Cr?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}pong(e,r,n){let o,s;if(typeof e=="string"?(o=Buffer.byteLength(e),s=!1):ci(e)?(o=e.size,s=!1):(e=Yo(e),o=e.length,s=Yo.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[_r]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};ci(e)?this._state!==Cr?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==Cr?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}send(e,r,n){let o=this._extensions[dO.extensionName],s=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):ci(e)?(a=e.size,c=!1):(e=Yo(e),a=e.length,c=Yo.readOnly),this._firstFragment?(this._firstFragment=!1,i&&o&&o.params[o._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(i=a>=o._threshold),this._compress=i):(i=!1,s=0),r.fin&&(this._firstFragment=!0);let l={[_r]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:i};ci(e)?this._state!==Cr?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Cr?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,o){this._bufferedBytes+=n[_r],this._state=cG,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(g_,this,a,o);return}this._bufferedBytes-=n[_r];let i=Yo(s);r?this.dispatch(i,r,n,o):(this._state=Cr,this.sendFrame(t.frame(i,n),o),this.dequeue())}).catch(s=>{process.nextTick(lG,this,s,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let s=this._extensions[dO.extensionName];this._bufferedBytes+=n[_r],this._state=aG,s.compress(e,n.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");g_(this,c,o);return}this._bufferedBytes-=n[_r],this._state=Cr,n.readOnly=!1,this.sendFrame(t.frame(a,n),o),this.dequeue()})}dequeue(){for(;this._state===Cr&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][_r],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][_r],this._queue.push(e)}sendFrame(e,r){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],r),this._socket.uncork()):this._socket.write(e[0],r)}};mO.exports=h_;function g_(t,e,r){typeof r=="function"&&r(e);for(let n=0;n<t._queue.length;n++){let o=t._queue[n],s=o[o.length-1];typeof s=="function"&&s(e)}}function lG(t,e,r){g_(t,e,r),t.onerror(e)}});var SO=I((Jne,xO)=>{"use strict";var{kForOnEventAttribute:Qa,kListener:v_}=pn(),hO=Symbol("kCode"),gO=Symbol("kData"),yO=Symbol("kError"),vO=Symbol("kMessage"),_O=Symbol("kReason"),ui=Symbol("kTarget"),bO=Symbol("kType"),wO=Symbol("kWasClean"),fn=class{constructor(e){this[ui]=null,this[bO]=e}get target(){return this[ui]}get type(){return this[bO]}};Object.defineProperty(fn.prototype,"target",{enumerable:!0});Object.defineProperty(fn.prototype,"type",{enumerable:!0});var Qo=class extends fn{constructor(e,r={}){super(e),this[hO]=r.code===void 0?0:r.code,this[_O]=r.reason===void 0?"":r.reason,this[wO]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[hO]}get reason(){return this[_O]}get wasClean(){return this[wO]}};Object.defineProperty(Qo.prototype,"code",{enumerable:!0});Object.defineProperty(Qo.prototype,"reason",{enumerable:!0});Object.defineProperty(Qo.prototype,"wasClean",{enumerable:!0});var pi=class extends fn{constructor(e,r={}){super(e),this[yO]=r.error===void 0?null:r.error,this[vO]=r.message===void 0?"":r.message}get error(){return this[yO]}get message(){return this[vO]}};Object.defineProperty(pi.prototype,"error",{enumerable:!0});Object.defineProperty(pi.prototype,"message",{enumerable:!0});var ec=class extends fn{constructor(e,r={}){super(e),this[gO]=r.data===void 0?null:r.data}get data(){return this[gO]}};Object.defineProperty(ec.prototype,"data",{enumerable:!0});var uG={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[Qa]&&o[v_]===e&&!o[Qa])return;let n;if(t==="message")n=function(s,i){let a=new ec("message",{data:i?s:s.toString()});a[ui]=this,Ap(e,this,a)};else if(t==="close")n=function(s,i){let a=new Qo("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[ui]=this,Ap(e,this,a)};else if(t==="error")n=function(s){let i=new pi("error",{error:s,message:s.message});i[ui]=this,Ap(e,this,i)};else if(t==="open")n=function(){let s=new fn("open");s[ui]=this,Ap(e,this,s)};else return;n[Qa]=!!r[Qa],n[v_]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[v_]===e&&!r[Qa]){this.removeListener(t,r);break}}};xO.exports={CloseEvent:Qo,ErrorEvent:pi,Event:fn,EventTarget:uG,MessageEvent:ec};function Ap(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var __=I((Kne,$O)=>{"use strict";var{tokenChars:tc}=ai();function Wr(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function pG(t){let e=Object.create(null),r=Object.create(null),n=!1,o=!1,s=!1,i,a,c=-1,l=-1,u=-1,p=0;for(;p<t.length;p++)if(l=t.charCodeAt(p),i===void 0)if(u===-1&&tc[l]===1)c===-1&&(c=p);else if(p!==0&&(l===32||l===9))u===-1&&c!==-1&&(u=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let d=t.slice(c,u);l===44?(Wr(e,d,r),r=Object.create(null)):i=d,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);else if(a===void 0)if(u===-1&&tc[l]===1)c===-1&&(c=p);else if(l===32||l===9)u===-1&&c!==-1&&(u=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p),Wr(r,t.slice(c,u),!0),l===44&&(Wr(e,i,r),r=Object.create(null),i=void 0),c=u=-1}else if(l===61&&c!==-1&&u===-1)a=t.slice(c,p),c=u=-1;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(o){if(tc[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),o=!1}else if(s)if(tc[l]===1)c===-1&&(c=p);else if(l===34&&c!==-1)s=!1,u=p;else if(l===92)o=!0;else throw new SyntaxError(`Unexpected character at index ${p}`);else if(l===34&&t.charCodeAt(p-1)===61)s=!0;else if(u===-1&&tc[l]===1)c===-1&&(c=p);else if(c!==-1&&(l===32||l===9))u===-1&&(u=p);else if(l===59||l===44){if(c===-1)throw new SyntaxError(`Unexpected character at index ${p}`);u===-1&&(u=p);let d=t.slice(c,u);n&&(d=d.replace(/\\/g,""),n=!1),Wr(r,a,d),l===44&&(Wr(e,i,r),r=Object.create(null),i=void 0),a=void 0,c=u=-1}else throw new SyntaxError(`Unexpected character at index ${p}`);if(c===-1||s||l===32||l===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=p);let f=t.slice(c,u);return i===void 0?Wr(e,f,r):(a===void 0?Wr(r,f,!0):n?Wr(r,a,f.replace(/\\/g,"")):Wr(r,a,f),Wr(e,i,r)),e}function dG(t){return Object.keys(t).map(e=>{let r=t[e];return Array.isArray(r)||(r=[r]),r.map(n=>[e].concat(Object.keys(n).map(o=>{let s=n[o];return Array.isArray(s)||(s=[s]),s.map(i=>i===!0?o:`${o}=${i}`).join("; ")})).join("; ")).join(", ")}).join(", ")}$O.exports={format:dG,parse:pG}});var Mp=I((Qne,jO)=>{"use strict";var fG=st("events"),mG=st("https"),hG=st("http"),TO=st("net"),gG=st("tls"),{randomBytes:yG,createHash:vG}=st("crypto"),{Duplex:Yne,Readable:Xne}=st("stream"),{URL:b_}=st("url"),to=Xa(),_G=m_(),bG=y_(),{isBlob:wG}=ai(),{BINARY_TYPES:kO,CLOSE_TIMEOUT:xG,EMPTY_BUFFER:Np,GUID:SG,kForOnEventAttribute:w_,kListener:$G,kStatusCode:kG,kWebSocket:mt,NOOP:PO}=pn(),{EventTarget:{addEventListener:EG,removeEventListener:TG}}=SO(),{format:PG,parse:RG}=__(),{toBuffer:OG}=Ka(),RO=Symbol("kAborted"),x_=[8,13],mn=["CONNECTING","OPEN","CLOSING","CLOSED"],CG=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Ye=class t extends fG{constructor(e,r,n){super(),this._binaryType=kO[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Np,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=t.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,r===void 0?r=[]:Array.isArray(r)||(typeof r=="object"&&r!==null?(n=r,r=[]):r=[r]),OO(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){kO.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,r,n){let o=new _G({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new bG(e,this._extensions,n.generateMask);this._receiver=o,this._sender=s,this._socket=e,o[mt]=this,s[mt]=this,e[mt]=this,o.on("conclude",NG),o.on("drain",zG),o.on("error",jG),o.on("message",MG),o.on("ping",LG),o.on("pong",DG),s.onerror=qG,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",AO),e.on("data",jp),e.on("end",NO),e.on("error",zO),this._readyState=t.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[to.extensionName]&&this._extensions[to.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=t.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,r){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){rr(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===t.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=t.CLOSING,this._sender.close(e,r,!this._isServer,n=>{n||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),IO(this)}}pause(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){S_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Np,r,n)}pong(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(n=e,e=r=void 0):typeof r=="function"&&(n=r,r=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){S_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Np,r,n)}resume(){this.readyState===t.CONNECTING||this.readyState===t.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,r,n){if(this.readyState===t.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof r=="function"&&(n=r,r={}),typeof e=="number"&&(e=e.toString()),this.readyState!==t.OPEN){S_(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[to.extensionName]||(o.compress=!1),this._sender.send(e||Np,o,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){rr(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Ye,"CONNECTING",{enumerable:!0,value:mn.indexOf("CONNECTING")});Object.defineProperty(Ye.prototype,"CONNECTING",{enumerable:!0,value:mn.indexOf("CONNECTING")});Object.defineProperty(Ye,"OPEN",{enumerable:!0,value:mn.indexOf("OPEN")});Object.defineProperty(Ye.prototype,"OPEN",{enumerable:!0,value:mn.indexOf("OPEN")});Object.defineProperty(Ye,"CLOSING",{enumerable:!0,value:mn.indexOf("CLOSING")});Object.defineProperty(Ye.prototype,"CLOSING",{enumerable:!0,value:mn.indexOf("CLOSING")});Object.defineProperty(Ye,"CLOSED",{enumerable:!0,value:mn.indexOf("CLOSED")});Object.defineProperty(Ye.prototype,"CLOSED",{enumerable:!0,value:mn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Ye.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Ye.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[w_])return e[$G];return null},set(e){for(let r of this.listeners(t))if(r[w_]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[w_]:!0})}})});Ye.prototype.addEventListener=EG;Ye.prototype.removeEventListener=TG;jO.exports=Ye;function OO(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:xG,protocolVersion:x_[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...n,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=o.autoPong,t._closeTimeout=o.closeTimeout,!x_.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${x_.join(", ")})`);let s;if(e instanceof b_)s=e;else try{s=new b_(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}s.protocol==="http:"?s.protocol="ws:":s.protocol==="https:"&&(s.protocol="wss:"),t._url=s.href;let i=s.protocol==="wss:",a=s.protocol==="ws+unix:",c;if(s.protocol!=="ws:"&&!i&&!a?c=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!s.pathname?c="The URL's pathname is empty":s.hash&&(c="The URL contains a fragment identifier"),c){let h=new SyntaxError(c);if(t._redirects===0)throw h;zp(t,h);return}let l=i?443:80,u=yG(16).toString("base64"),p=i?mG.request:hG.request,f=new Set,d;if(o.createConnection=o.createConnection||(i?AG:IG),o.defaultPort=o.defaultPort||l,o.port=s.port||l,o.host=s.hostname.startsWith("[")?s.hostname.slice(1,-1):s.hostname,o.headers={...o.headers,"Sec-WebSocket-Version":o.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},o.path=s.pathname+s.search,o.timeout=o.handshakeTimeout,o.perMessageDeflate&&(d=new to(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=PG({[to.extensionName]:d.offer()})),r.length){for(let h of r){if(typeof h!="string"||!CG.test(h)||f.has(h))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(h)}o.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(o.origin&&(o.protocolVersion<13?o.headers["Sec-WebSocket-Origin"]=o.origin:o.headers.Origin=o.origin),(s.username||s.password)&&(o.auth=`${s.username}:${s.password}`),a){let h=o.path.split(":");o.socketPath=h[0],o.path=h[1]}let m;if(o.followRedirects){if(t._redirects===0){t._originalIpc=a,t._originalSecure=i,t._originalHostOrSocketPath=a?o.socketPath:s.host;let h=n&&n.headers;if(n={...n,headers:{}},h)for(let[g,v]of Object.entries(h))n.headers[g.toLowerCase()]=v}else if(t.listenerCount("redirect")===0){let h=a?t._originalIpc?o.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:s.host===t._originalHostOrSocketPath;(!h||t._originalSecure&&!i)&&(delete o.headers.authorization,delete o.headers.cookie,h||delete o.headers.host,o.auth=void 0)}o.auth&&!n.headers.authorization&&(n.headers.authorization="Basic "+Buffer.from(o.auth).toString("base64")),m=t._req=p(o),t._redirects&&t.emit("redirect",t.url,m)}else m=t._req=p(o);o.timeout&&m.on("timeout",()=>{rr(t,m,"Opening handshake has timed out")}),m.on("error",h=>{m===null||m[RO]||(m=t._req=null,zp(t,h))}),m.on("response",h=>{let g=h.headers.location,v=h.statusCode;if(g&&o.followRedirects&&v>=300&&v<400){if(++t._redirects>o.maxRedirects){rr(t,m,"Maximum redirects exceeded");return}m.abort();let b;try{b=new b_(g,e)}catch{let $=new SyntaxError(`Invalid URL: ${g}`);zp(t,$);return}OO(t,b,r,n)}else t.emit("unexpected-response",m,h)||rr(t,m,`Unexpected server response: ${h.statusCode}`)}),m.on("upgrade",(h,g,v)=>{if(t.emit("upgrade",h),t.readyState!==Ye.CONNECTING)return;m=t._req=null;let b=h.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){rr(t,g,"Invalid Upgrade header");return}let x=vG("sha1").update(u+SG).digest("base64");if(h.headers["sec-websocket-accept"]!==x){rr(t,g,"Invalid Sec-WebSocket-Accept header");return}let $=h.headers["sec-websocket-protocol"],O;if($!==void 0?f.size?f.has($)||(O="Server sent an invalid subprotocol"):O="Server sent a subprotocol but none was requested":f.size&&(O="Server sent no subprotocol"),O){rr(t,g,O);return}$&&(t._protocol=$);let ce=h.headers["sec-websocket-extensions"];if(ce!==void 0){if(!d){rr(t,g,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let X;try{X=RG(ce)}catch{rr(t,g,"Invalid Sec-WebSocket-Extensions header");return}let ee=Object.keys(X);if(ee.length!==1||ee[0]!==to.extensionName){rr(t,g,"Server indicated an extension that was not requested");return}try{d.accept(X[to.extensionName])}catch{rr(t,g,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[to.extensionName]=d}t.setSocket(g,v,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(m,t):m.end()}function zp(t,e){t._readyState=Ye.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function IG(t){return t.path=t.socketPath,TO.connect(t)}function AG(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=TO.isIP(t.host)?"":t.host),gG.connect(t)}function rr(t,e,r){t._readyState=Ye.CLOSING;let n=new Error(r);Error.captureStackTrace(n,rr),e.setHeader?(e[RO]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(zp,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function S_(t,e,r){if(e){let n=wG(e)?e.size:OG(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${mn[t.readyState]})`);process.nextTick(r,n)}}function NG(t,e){let r=this[mt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[mt]!==void 0&&(r._socket.removeListener("data",jp),process.nextTick(CO,r._socket),t===1005?r.close():r.close(t,e))}function zG(){let t=this[mt];t.isPaused||t._socket.resume()}function jG(t){let e=this[mt];e._socket[mt]!==void 0&&(e._socket.removeListener("data",jp),process.nextTick(CO,e._socket),e.close(t[kG])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function EO(){this[mt].emitClose()}function MG(t,e){this[mt].emit("message",t,e)}function LG(t){let e=this[mt];e._autoPong&&e.pong(t,!this._isServer,PO),e.emit("ping",t)}function DG(t){this[mt].emit("pong",t)}function CO(t){t.resume()}function qG(t){let e=this[mt];e.readyState!==Ye.CLOSED&&(e.readyState===Ye.OPEN&&(e._readyState=Ye.CLOSING,IO(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function IO(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function AO(){let t=this[mt];if(this.removeListener("close",AO),this.removeListener("data",jp),this.removeListener("end",NO),t._readyState=Ye.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);t._receiver.write(e)}t._receiver.end(),this[mt]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",EO),t._receiver.on("finish",EO))}function jp(t){this[mt]._receiver.write(t)||this.pause()}function NO(){let t=this[mt];t._readyState=Ye.CLOSING,t._receiver.end(),this.end()}function zO(){let t=this[mt];this.removeListener("error",zO),this.on("error",PO),t&&(t._readyState=Ye.CLOSING,this.destroy())}});var qO=I((toe,DO)=>{"use strict";var eoe=Mp(),{Duplex:ZG}=st("stream");function MO(t){t.emit("close")}function UG(){!this.destroyed&&this._writableState.finished&&this.destroy()}function LO(t){this.removeListener("error",LO),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function FG(t,e){let r=!0,n=new ZG({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(s,i){let a=!i&&n._readableState.objectMode?s.toString():s;n.push(a)||t.pause()}),t.once("error",function(s){n.destroyed||(r=!1,n.destroy(s))}),t.once("close",function(){n.destroyed||n.push(null)}),n._destroy=function(o,s){if(t.readyState===t.CLOSED){s(o),process.nextTick(MO,n);return}let i=!1;t.once("error",function(c){i=!0,s(c)}),t.once("close",function(){i||s(o),process.nextTick(MO,n)}),r&&t.terminate()},n._final=function(o){if(t.readyState===t.CONNECTING){t.once("open",function(){n._final(o)});return}t._socket!==null&&(t._socket._writableState.finished?(o(),n._readableState.endEmitted&&n.destroy()):(t._socket.once("finish",function(){o()}),t.close()))},n._read=function(){t.isPaused&&t.resume()},n._write=function(o,s,i){if(t.readyState===t.CONNECTING){t.once("open",function(){n._write(o,s,i)});return}t.send(o,i)},n.on("end",UG),n.on("error",LO),n}DO.exports=FG});var UO=I((roe,ZO)=>{"use strict";var{tokenChars:HG}=ai();function BG(t){let e=new Set,r=-1,n=-1,o=0;for(o;o<t.length;o++){let i=t.charCodeAt(o);if(n===-1&&HG[i]===1)r===-1&&(r=o);else if(o!==0&&(i===32||i===9))n===-1&&r!==-1&&(n=o);else if(i===44){if(r===-1)throw new SyntaxError(`Unexpected character at index ${o}`);n===-1&&(n=o);let a=t.slice(r,n);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),r=n=-1}else throw new SyntaxError(`Unexpected character at index ${o}`)}if(r===-1||n!==-1)throw new SyntaxError("Unexpected end of input");let s=t.slice(r,o);if(e.has(s))throw new SyntaxError(`The "${s}" subprotocol is duplicated`);return e.add(s),e}ZO.exports={parse:BG}});var JO=I((ooe,WO)=>{"use strict";var GG=st("events"),Lp=st("http"),{Duplex:noe}=st("stream"),{createHash:VG}=st("crypto"),FO=__(),es=Xa(),WG=UO(),JG=Mp(),{CLOSE_TIMEOUT:KG,GUID:YG,kWebSocket:XG}=pn(),QG=/^[+/0-9A-Za-z]{22}==$/,HO=0,BO=1,VO=2,$_=class extends GG{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:KG,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:JG,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=Lp.createServer((n,o)=>{let s=Lp.STATUS_CODES[426];o.writeHead(426,{"Content-Length":s.length,"Content-Type":"text/plain"}),o.end(s)}),this._server.listen(e.port,e.host,e.backlog,r)):e.server&&(this._server=e.server),this._server){let n=this.emit.bind(this,"connection");this._removeListeners=eV(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(o,s,i)=>{this.handleUpgrade(o,s,i,n)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=HO}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===VO){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(rc,this);return}if(e&&this.once("close",e),this._state!==BO)if(this._state=BO,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(rc,this):process.nextTick(rc,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{rc(this)})}}shouldHandle(e){if(this.options.path){let r=e.url.indexOf("?");if((r!==-1?e.url.slice(0,r):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,r,n,o){r.on("error",GO);let s=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ts(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){ts(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!QG.test(s)){ts(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ts(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){nc(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=WG.parse(c)}catch{ts(this,e,r,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],p={};if(this.options.perMessageDeflate&&u!==void 0){let f=new es(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let d=FO.parse(u);d[es.extensionName]&&(f.accept(d[es.extensionName]),p[es.extensionName]=f)}catch{ts(this,e,r,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let f={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(f,(d,m,h,g)=>{if(!d)return nc(r,m||401,h,g);this.completeUpgrade(p,s,l,e,r,n,o)});return}if(!this.options.verifyClient(f))return nc(r,401)}this.completeUpgrade(p,s,l,e,r,n,o)}completeUpgrade(e,r,n,o,s,i,a){if(!s.readable||!s.writable)return s.destroy();if(s[XG])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>HO)return nc(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${VG("sha1").update(r+YG).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(n.size){let p=this.options.handleProtocols?this.options.handleProtocols(n,o):n.values().next().value;p&&(l.push(`Sec-WebSocket-Protocol: ${p}`),u._protocol=p)}if(e[es.extensionName]){let p=e[es.extensionName].params,f=FO.format({[es.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,o),s.write(l.concat(`\r
405
405
  `).join(`\r
406
- `)),s.removeListener("error",MO),u.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(Qa,this)})),a(u,o)}};DO.exports=y_;function AV(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function Qa(t){t._state=LO,t.emit("close")}function MO(){this.destroy()}function ec(t,e,r,n){r=r||Np.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Np.STATUS_CODES[e]}\r
406
+ `)),s.removeListener("error",GO),u.setSocket(s,i,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(u),u.on("close",()=>{this.clients.delete(u),this._shouldEmitClose&&!this.clients.size&&process.nextTick(rc,this)})),a(u,o)}};WO.exports=$_;function eV(t,e){for(let r of Object.keys(e))t.on(r,e[r]);return function(){for(let n of Object.keys(e))t.removeListener(n,e[n])}}function rc(t){t._state=VO,t.emit("close")}function GO(){this.destroy()}function nc(t,e,r,n){r=r||Lp.STATUS_CODES[e],n={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...n},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${e} ${Lp.STATUS_CODES[e]}\r
407
407
  `+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
408
408
  `)+`\r
409
409
  \r
410
- `+r)}function es(t,e,r,n,o,s){if(t.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,es),t.emit("wsClientError",i,r,e)}else ec(r,n,o,s)}});var BO={};X(BO,{Receiver:()=>UO.default,Sender:()=>FO.default,WebSocket:()=>v_.default,WebSocketServer:()=>HO.default,createWebSocketStream:()=>ZO.default,default:()=>NV});var ZO,UO,FO,v_,HO,NV,VO=w(()=>{ZO=oo(CO(),1),UO=oo(a_(),1),FO=oo(u_(),1),v_=oo(Ap(),1),HO=oo(qO(),1),NV=v_.default});var GO={};X(GO,{setupWebSocket:()=>jV});async function zV(){let t=await Promise.resolve().then(()=>(VO(),BO));return(t.default??t).WebSocketServer}async function jV(t,e,r,n,o,s){let i=o??await zV(),a=new i({noServer:!0});return t.on("upgrade",(c,l,u)=>{let p=new URL(c.url??"/","http://localhost");if(p.pathname!=="/ws"){l.destroy();return}a.handleUpgrade(c,l,u,m=>{MV(m,p,e,r,n,s)})}),{close(){a.close()}}}function MV(t,e,r,n,o,s){let i=e.searchParams.get("namespace")??"default",a=e.searchParams.get("since"),c=a!==null?parseInt(a,10):void 0,l=e.searchParams.get("types"),u=l?new Set(l.split(",").filter(Boolean)):null,p=e.searchParams.get("agentId")??void 0,m=e.searchParams.get("role")??void 0,d=[],f=!0,h=c??0;function g(Y){t.readyState===t.OPEN&&t.send(JSON.stringify(Y))}function v(Y){return u?u.has(Y.type):!0}async function _(Y){if(s&&p&&m){let ee=await s.getState(i),{runInject:ge}=await Promise.resolve().then(()=>(Jo(),ei)),U=ge(s.module,ee,m,p);g({type:"event",event:Y,...U?{inject:U}:{}})}else g({type:"event",event:Y})}let x=n.subscribe(i,Y=>{v(Y)&&(f?d.push(Y):_(Y))});r.get(i).events.getEvents(c).then(async({events:Y,cursor:ee})=>{for(let ge of Y)v(ge)&&(await _(ge),h=Math.max(h,ge.id));if(h=Math.max(h,ee),g({type:"replay_done",cursor:h}),s){let{danceToolDefs:ge}=await Promise.resolve().then(()=>(Jo(),ei));g({type:"dance_tools",tools:ge(s.module)})}f=!1;for(let ge of d)ge.id>h&&await _(ge);d.length=0,o&&console.error(`[incubator] WS client connected: ns=${i} since=${c??"start"} replayed=${Y.length}`)}).catch(Y=>{g({type:"error",message:"Replay failed"}),o&&console.error("[incubator] WS replay error:",Y),t.close()}),t.on("message",Y=>{try{let ee=JSON.parse(String(Y));if(ee.type==="subscribe")u=ee.types?new Set(ee.types):null;else if(ee.type==="publish"&&typeof ee.event=="string")r.get(i).events.publish(ee.event,ee.data??{},ee.agentId??"ui").then(U=>{n.publish(i,U),g({type:"publish_ack",eventId:U.id})}).catch(()=>{g({type:"error",message:"Failed to publish event"})});else if(ee.type==="reset"){let ge=r.get(i);ge.state.getAll().then(async U=>{for(let rt of U)await ge.state.delete(rt.key);let ne=await ge.events.publish("reset",{},"ui");n.publish(i,ne),g({type:"reset_ack"}),o&&console.error(`[incubator] WS reset: ns=${i} (cleared ${U.length} keys)`)}).catch(()=>{g({type:"error",message:"Failed to reset state"})})}else if(ee.type==="dance_call"&&s&&typeof ee.tool=="string"){let ge=ee.agentId??p??"unknown",U=ee.role??m??"unknown",ne=ee.callId,rt=()=>s.getState(i),Mt=s.getAcpHelper(i,ge),te=Date.now();Promise.resolve().then(()=>(Jo(),ei)).then(({callDanceTool:fe})=>fe(s.module,ee.tool,ee.args??{},U,ge,rt,Mt)).then(fe=>{let Lt="error"in fe?{error:fe.error}:fe.result;s?.telemetry?.record("dance_call",{tool:ee.tool,role:U,agentId:ge,success:!("error"in fe),latency_ms:Date.now()-te}),g({type:"dance_result",callId:ne,result:Lt})}).catch(fe=>{s?.telemetry?.record("dance_call",{tool:ee.tool,role:U,agentId:ge,success:!1,error:fe.message,latency_ms:Date.now()-te}),g({type:"dance_result",callId:ne,result:{error:fe.message}})})}}catch{}});let I=setInterval(()=>{g({type:"ping",ts:Date.now()})},3e4),de=()=>{clearInterval(I),x(),o&&console.error(`[incubator] WS client disconnected: ns=${i}`)};t.on("close",de),t.on("error",de)}var WO=w(()=>{});var b_={};X(b_,{main:()=>ZV});import{createServer as LV}from"node:http";import{createServer as DV}from"node:https";import{randomUUID as JO}from"node:crypto";import{fileURLToPath as KO}from"node:url";import{dirname as zp,join as YO,resolve as tc}from"node:path";import{existsSync as __,readFileSync as jp}from"node:fs";function qV(t){let e={};for(let r of t.slice(2))if(r.startsWith("--")){let[n,...o]=r.slice(2).split("=");e[n]=o.length>0?o.join("="):!0}return e}async function ZV(){let t=qV(process.argv),e=typeof t.mode=="string"?t.mode:(t.http===!0,"http");e!=="http"&&e!=="mcp"&&(console.error(`[incubator] Unknown mode: ${e}. Use 'http' (default) or 'mcp'.`),process.exit(1));let r=e==="http",n=typeof t.port=="string"?parseInt(t.port,10):3100,o=typeof t["agent-id"]=="string"?t["agent-id"]:void 0,s=typeof t.persist=="string"?t.persist:void 0,i=t.verbose===!0,a=t["no-guard"]===!0,c=typeof t["tls-cert"]=="string"?t["tls-cert"]:void 0,l=typeof t["tls-key"]=="string"?t["tls-key"]:void 0,u=!!(c&&l),p=typeof t.static=="string"?t.static:void 0,m=typeof t.brood=="string"?t.brood:void 0,d=typeof t.backend=="string"?t.backend:"memory";d!=="memory"&&d!=="sqlite"&&d!=="redis"&&(console.error(`[incubator] Unknown backend: ${d}. Use 'memory', 'sqlite', or 'redis'.`),process.exit(1));let f=typeof t.db=="string"?t.db:void 0,h=typeof t["redis-url"]=="string"?t["redis-url"]:"redis://localhost:6379",g=d==="sqlite",v=d==="redis";g&&!f&&(console.error("[incubator] SQLite backend requires --db=<path>"),process.exit(1)),(g||v)&&s&&console.error(`[incubator] WARNING: --persist is ignored with ${d} backend (data is already persistent)`);let _;if(v){let{getRedisClient:te,waitForReady:fe}=await Promise.resolve().then(()=>(Gv(),Vv));_=te(h),await fe(_)}let x={type:d,dbPath:f,redisClient:_},k=g||v,I=typeof t.protocol=="string"?t.protocol:void 0,de=typeof t.dances=="string"?t.dances:void 0,Y;if(typeof t.agents=="string")try{Y=JSON.parse(t.agents)}catch(te){console.error(`[incubator] Failed to parse --agents JSON: ${te.message}`),process.exit(1)}let ee=[];for(let te of process.argv.slice(2))te.startsWith("--integration=")&&ee.push(te.slice(14));let ge=ee.length>0||t.integrations===!0,U=new up(x),ne;if(a)console.error("[incubator] WARNING: Carapace disabled \u2014 no prompt injection scanning");else{let te=nP(i);U.setGuard(te,i),ne=fe=>sP(fe,te,i),console.error("[incubator] Carapace active \u2014 scanning writes, reads, and snapshots")}if(s&&!k){let te=await PP(s,U,ne);te>0&&console.error(`[incubator] Restored ${te} namespace(s) from ${s}`)}if(I)try{let te=await wc(I);U.setProtocol("default",te),r&&te.name!=="default"&&U.setProtocol(te.name,te),console.error(`[incubator] Protocol loaded: "${te.title}" (${te.name})`)}catch(te){console.error(`[incubator] Failed to load protocol: ${te.message}`),process.exit(1)}let rt,Mt=de;if(!Mt&&m)try{let te=jp(tc(m),"utf-8"),fe=m.endsWith(".json")?JSON.parse(te):Xr.load(te),Lt=fe.hives??{},se=Object.values(Lt)[0],le=se?.dances??se?.logic??fe.dances??fe.logic;typeof le=="string"&&(Mt=tc(zp(m),le))}catch{}if(Mt){let{loadDances:te}=await Promise.resolve().then(()=>(Jo(),ei)),fe=tc(Mt),Lt=new URL(`file://${fe}`).href;rt=await te(Lt);let se=[...rt.tools.keys()];console.error(`[incubator] Dances loaded: ${se.join(", ")}${rt.inject?" + inject":""}`)}if(console.error(g?`[incubator] Backend: sqlite (${f})`:v?`[incubator] Backend: redis (${h})`:"[incubator] Backend: memory"),r){let te=new Map,fe;if(v&&_){let ie=_.duplicate(),{waitForReady:oe}=await Promise.resolve().then(()=>(Gv(),Vv));await oe(ie),fe=new fp(_,ie)}else fe=new dp;let Lt,se=process.env.HONEYCOMB_BROKER_SOCKET,le=process.env.HONEYCOMB_HIVE_NAME;if(se&&le){let ie=process.env.HONEYCOMB_PUBLISHES?.split(",").filter(Boolean)??[],oe=process.env.HONEYCOMB_SUBSCRIBES?.split(",").filter(Boolean)??[],{IPCTransport:je}=await Promise.resolve().then(()=>(ER(),kR)),ye=new je({socketPath:se,hiveName:le,publishes:ie,subscribes:oe});await ye.connect(),console.error(`[incubator] Honeycomb: connected to broker as "${le}"`),Lt={transport:ye,hiveName:le,hivePublishes:ie,hiveSubscribes:oe}}U.setBus(fe,Lt);let ct=U.get("default"),Ir=new mp(fe,ct.runs);Ir.start();let G=[],F=new wp(i);if(I){let ie=U.getProtocol("default");ie?.governance?.webhooks?.length&&F.register("default",ie.governance.webhooks,fe)}let me=u?"https":"http",Jr=u?"wss":"ws",Be,Oe;try{let ie=await Promise.resolve().then(()=>(jR(),zR)),oe=ie.default??ie,je=zp(KO(import.meta.url)),ye=YO(je,"..","dashboard","dist");__(ye)&&(Be=oe(ye,{single:!0,dev:!0}),console.error(`[incubator] Dashboard: ${me}://localhost:${n}/dashboard`)),p&&__(p)&&(Oe=oe(p,{single:!0,dev:!0}),console.error(`[incubator] Static: ${me}://localhost:${n}/`))}catch{}let Ar=async(ie,oe)=>{if(ie.url?.startsWith("/api/")){await iP(ie,oe,U,i);return}let je=new URL(ie.url??"/",`${me}://localhost:${n}`);if(je.pathname==="/dashboard"||je.pathname.startsWith("/dashboard/")){if(Be){let _r=ie.url;ie.url=je.pathname.replace(/^\/dashboard/,"")||"/",je.search&&(ie.url+=je.search),Be(ie,oe,()=>{ie.url=_r,oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Not found."}))});return}oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Dashboard not available."}));return}if(je.pathname!=="/mcp"){if(je.pathname==="/"&&!Oe&&Be){oe.writeHead(302,{Location:"/dashboard"}),oe.end();return}Oe?Oe(ie,oe,()=>{oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."}))}):(oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."})));return}let ye=ie.headers["x-namespace"]||"default",Ze=U.get(ye),V=ie.headers["mcp-session-id"];if(V&&te.has(V)){await te.get(V).transport.handleRequest(ie,oe);return}let $t=`agent_${JO().slice(0,8)}`,or=new Ol({sessionIdGenerator:()=>JO(),onsessioninitialized:_r=>{let fi=ye==="default"?"":`@${ye}`;console.error(`[incubator] Session ${_r} started (${$t}${fi})`),te.set(_r,{server:oc,transport:or})}});or.onclose=()=>{let _r=or.sessionId;_r&&(te.delete(_r),console.error(`[incubator] Session ${_r} closed`))};let oc=vv(Ze,{agentId:$t,namespace:ye,persistPath:k?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!k?()=>{pp(s,U)}:void 0,getProtocol:()=>U.getProtocol(ye)});await oc.connect(or),await or.handleRequest(ie,oe)},Kr=u?DV({key:jp(l),cert:jp(c)},Ar):LV(Ar),hn;if(rt){let{buildAcpHelper:ie}=await Promise.resolve().then(()=>(Jo(),ei));hn={module:rt,getState:async oe=>{let ye=await U.get(oe).state.query(),Ze={};for(let V of ye)Ze[V.key]=typeof V.value=="string"?V.value:JSON.stringify(V.value);return Ze},getAcpHelper:(oe,je)=>{let ye=U.get(oe);return ie({publishEvent:async(Ze,V,$t,or)=>{let di=await ye.events.publish(V,$t??{},or??je);fe.publish(oe,di)},claimResource:async(Ze,V,$t,or)=>(await ye.claims.claim(V,V,$t,or)).claim.resource,releaseResource:async(Ze,V)=>{await ye.claims.release(V,je)},setState:async(Ze,V,$t)=>{await ye.state.set(V,$t,je)}},oe,je)}}}let nr;try{let{setupWebSocket:ie}=await Promise.resolve().then(()=>(WO(),GO));nr=await ie(Kr,U,fe,i,void 0,hn)}catch{}if(m){let ie=jp(tc(m),"utf-8"),oe=m.endsWith(".json")?JSON.parse(ie):Xr.load(ie),je=oe.hives??{},ye=Object.values(je)[0],Ze=(ye?.agents??ye?.workers??[]).map(Kt=>({role:String(Kt.role??""),type:Kt.type??"worker",prompt:typeof Kt.prompt=="string"?Kt.prompt:void 0,wakeOn:Kt.wake_on?{types:Kt.wake_on.types,maxWakes:Kt.wake_on.max_wakes}:void 0})),V=ye?.acp??ye?.spec??ye?.protocol;if(typeof V=="string"&&I===void 0){let Kt=tc(zp(m),V);if(__(Kt)){let no=await wc(Kt);if(U.setProtocol("default",no),console.error(`[incubator] Protocol loaded from brood: ${V}`),Ze.length===0&&no.roles){for(let[sc,ic]of Object.entries(no.roles)){let HC=typeof ic.agents=="number"?ic.agents:1;for(let I_=0;I_<HC;I_++)Ze.push({role:sc,type:"worker",prompt:void 0,wakeOn:void 0})}console.error(`[incubator] Derived ${Ze.length} agents from spec roles`)}}}let $t=typeof oe.stagger=="number"?oe.stagger:0,or=typeof oe.provider=="string"?oe.provider:"ollama/qwen3:8b",di=oe.env??{},oc=zp(KO(import.meta.url)),_r=YO(oc,"agent","cli.js");console.error(`[incubator] Brood loaded: ${Ze.length} agents (${or}), waiting for "start" event`);let fi=!1;fe.subscribe("default",Kt=>{if(Kt.type==="start"&&!fi){fi=!0,console.error("[orchestrator] Start event received, spawning agents...");let no={provider:or,stagger:$t,noAcp:!1,propolisPort:0,worktree:process.cwd(),hiveEntry:_r,tls:u,env:di,agents:Ze},sc=new Va(no,n,fe,ct.runs,i,ct,U,hn?.module);sc.start().catch(ic=>{console.error(`[orchestrator] Spawn failed: ${ic.message}`)}),G.push(sc)}if(Kt.type==="reset"){fi=!1;for(let no of G)no.shutdown().catch(()=>{});G.length=0,console.error("[orchestrator] Reset \u2014 agents stopped, ready for new game")}})}let ot;if(ge){let ie=U.get("default");ot=new Da({namespace:"default",bus:fe,eventStore:ie.events,verbose:i});let oe=Sv();if(ee.length>0)for(let ye of ee){let Ze=oe[ye];if(Ze)try{await ot.load(ye,Ze.package,Ze.config)}catch(V){console.error(`[integrations] Failed to load "${ye}": ${V.message}`)}else try{await ot.load(ye,ye)}catch(V){console.error(`[integrations] Failed to load "${ye}": ${V.message}`)}}else await ot.loadFromConfig(oe);let je=ot.getLoadedNames();if(je.length>0){console.error(`[incubator] Integrations: ${je.join(", ")}`);let ye=ot.getTools();ye.length>0&&console.error(`[incubator] Integration tools: ${ye.map(Ze=>Ze.name).join(", ")}`)}}Kr.listen(n,()=>{console.error(`[incubator] ${u?"HTTPS":"HTTP"} server listening on port ${n}`),console.error(`[incubator] MCP endpoint: ${me}://localhost:${n}/mcp`),console.error(`[incubator] REST API: ${me}://localhost:${n}/api/`),console.error(nr?`[incubator] WebSocket: ${Jr}://localhost:${n}/ws`:'[incubator] WebSocket: disabled (install "ws" to enable)'),s&&!k&&console.error(`[incubator] Persistence: ${s}`),Y&&(Jt=new Va(Y,n,fe,ct.runs,i,ct,U,hn?.module),Jt.start().catch(ie=>{console.error(`[orchestrator] Fatal: ${ie.message}`),process.exit(1)}))});let Jt;process.on("SIGINT",async()=>{console.error(`
411
- [incubator] Shutting down...`),Jt&&await Jt.shutdown();for(let ie of G)await ie.shutdown();Ir.stop(),F.close(),ot&&await ot.stopAll(),nr&&nr.close(),await fe.close(),s&&!k&&(await pp(s,U),console.error("[incubator] Snapshots saved")),_&&(await _.quit(),console.error("[incubator] Redis disconnected"));for(let[,ie]of te)ie.server.close();Kr.close(),process.exit(0)})}else{let te=U.get("default"),Lt=vv(te,{agentId:o??"agent_stdio",persistPath:k?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!k?()=>{pp(s,U)}:void 0,getProtocol:()=>U.getProtocol("default")}),se=new kl;await Lt.connect(se),console.error(`[incubator] Running on stdio (agent: ${o??"agent_stdio"})`),s&&!k&&console.error(`[incubator] Persistence: ${s}`)}}var w_=w(()=>{PS();qS();_v();aP();ep();EP();RP();OP();wi();Ti();NP();zP();xR();SR()});var XO={};X(XO,{serve:()=>UV});async function UV(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
410
+ `+r)}function ts(t,e,r,n,o,s){if(t.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,ts),t.emit("wsClientError",i,r,e)}else nc(r,n,o,s)}});var eC={};K(eC,{Receiver:()=>YO.default,Sender:()=>XO.default,WebSocket:()=>k_.default,WebSocketServer:()=>QO.default,createWebSocketStream:()=>KO.default,default:()=>tV});var KO,YO,XO,k_,QO,tV,tC=w(()=>{KO=oo(qO(),1),YO=oo(m_(),1),XO=oo(y_(),1),k_=oo(Mp(),1),QO=oo(JO(),1),tV=k_.default});var rC={};K(rC,{setupWebSocket:()=>nV});async function rV(){let t=await Promise.resolve().then(()=>(tC(),eC));return(t.default??t).WebSocketServer}async function nV(t,e,r,n,o,s){let i=o??await rV(),a=new i({noServer:!0});return t.on("upgrade",(c,l,u)=>{let p=new URL(c.url??"/","http://localhost");if(p.pathname!=="/ws"){l.destroy();return}a.handleUpgrade(c,l,u,f=>{oV(f,p,e,r,n,s)})}),{close(){a.close()}}}function oV(t,e,r,n,o,s){let i=e.searchParams.get("namespace")??"default",a=e.searchParams.get("since"),c=a!==null?parseInt(a,10):void 0,l=e.searchParams.get("types"),u=l?new Set(l.split(",").filter(Boolean)):null,p=e.searchParams.get("agentId")??void 0,f=e.searchParams.get("role")??void 0,d=[],m=!0,h=c??0;function g(X){t.readyState===t.OPEN&&t.send(JSON.stringify(X))}function v(X){return u?u.has(X.type):!0}async function b(X){if(s&&p&&f){let ee=await s.getState(i),{runInject:ge}=await Promise.resolve().then(()=>(Ko(),ri)),U=ge(s.module,ee,f,p);g({type:"event",event:X,...U?{inject:U}:{}})}else g({type:"event",event:X})}let x=n.subscribe(i,X=>{v(X)&&(m?d.push(X):b(X))});r.get(i).events.getEvents(c).then(async({events:X,cursor:ee})=>{for(let ge of X)v(ge)&&(await b(ge),h=Math.max(h,ge.id));if(h=Math.max(h,ee),g({type:"replay_done",cursor:h}),s){let{danceToolDefs:ge}=await Promise.resolve().then(()=>(Ko(),ri));g({type:"dance_tools",tools:ge(s.module)})}m=!1;for(let ge of d)ge.id>h&&await b(ge);d.length=0,o&&console.error(`[incubator] WS client connected: ns=${i} since=${c??"start"} replayed=${X.length}`)}).catch(X=>{g({type:"error",message:"Replay failed"}),o&&console.error("[incubator] WS replay error:",X),t.close()}),t.on("message",X=>{try{let ee=JSON.parse(String(X));if(ee.type==="subscribe")u=ee.types?new Set(ee.types):null;else if(ee.type==="publish"&&typeof ee.event=="string")r.get(i).events.publish(ee.event,ee.data??{},ee.agentId??"ui").then(U=>{n.publish(i,U),g({type:"publish_ack",eventId:U.id})}).catch(()=>{g({type:"error",message:"Failed to publish event"})});else if(ee.type==="reset"){let ge=r.get(i);ge.state.getAll().then(async U=>{for(let rt of U)await ge.state.delete(rt.key);let ne=await ge.events.publish("reset",{},"ui");n.publish(i,ne),g({type:"reset_ack"}),o&&console.error(`[incubator] WS reset: ns=${i} (cleared ${U.length} keys)`)}).catch(()=>{g({type:"error",message:"Failed to reset state"})})}else if(ee.type==="dance_call"&&s&&typeof ee.tool=="string"){let ge=ee.agentId??p??"unknown",U=ee.role??f??"unknown",ne=ee.callId,rt=()=>s.getState(i),Mt=s.getAcpHelper(i,ge),te=Date.now();Promise.resolve().then(()=>(Ko(),ri)).then(({callDanceTool:fe})=>fe(s.module,ee.tool,ee.args??{},U,ge,rt,Mt)).then(fe=>{let Lt="error"in fe?{error:fe.error}:fe.result;s?.telemetry?.record("dance_call",{tool:ee.tool,role:U,agentId:ge,success:!("error"in fe),latency_ms:Date.now()-te}),g({type:"dance_result",callId:ne,result:Lt})}).catch(fe=>{s?.telemetry?.record("dance_call",{tool:ee.tool,role:U,agentId:ge,success:!1,error:fe.message,latency_ms:Date.now()-te}),g({type:"dance_result",callId:ne,result:{error:fe.message}})})}}catch{}});let O=setInterval(()=>{g({type:"ping",ts:Date.now()})},3e4),ce=()=>{clearInterval(O),x(),o&&console.error(`[incubator] WS client disconnected: ns=${i}`)};t.on("close",ce),t.on("error",ce)}var nC=w(()=>{});var T_={};K(T_,{main:()=>cV});import{createServer as sV}from"node:http";import{createServer as iV}from"node:https";import{randomUUID as oC}from"node:crypto";import{fileURLToPath as sC}from"node:url";import{dirname as Dp,join as iC,resolve as oc}from"node:path";import{existsSync as E_,readFileSync as qp}from"node:fs";function aV(t){let e={};for(let r of t.slice(2))if(r.startsWith("--")){let[n,...o]=r.slice(2).split("=");e[n]=o.length>0?o.join("="):!0}return e}async function cV(){let t=aV(process.argv),e=typeof t.mode=="string"?t.mode:(t.http===!0,"http");e!=="http"&&e!=="mcp"&&(console.error(`[incubator] Unknown mode: ${e}. Use 'http' (default) or 'mcp'.`),process.exit(1));let r=e==="http",n=typeof t.port=="string"?parseInt(t.port,10):3100,o=typeof t["agent-id"]=="string"?t["agent-id"]:void 0,s=typeof t.persist=="string"?t.persist:void 0,i=t.verbose===!0,a=t["no-guard"]===!0,c=typeof t["tls-cert"]=="string"?t["tls-cert"]:void 0,l=typeof t["tls-key"]=="string"?t["tls-key"]:void 0,u=!!(c&&l),p=typeof t.static=="string"?t.static:void 0,f=typeof t.brood=="string"?t.brood:void 0,d=typeof t.backend=="string"?t.backend:"memory";d!=="memory"&&d!=="sqlite"&&d!=="redis"&&(console.error(`[incubator] Unknown backend: ${d}. Use 'memory', 'sqlite', or 'redis'.`),process.exit(1));let m=typeof t.db=="string"?t.db:void 0,h=typeof t["redis-url"]=="string"?t["redis-url"]:"redis://localhost:6379",g=d==="sqlite",v=d==="redis";g&&!m&&(console.error("[incubator] SQLite backend requires --db=<path>"),process.exit(1)),(g||v)&&s&&console.error(`[incubator] WARNING: --persist is ignored with ${d} backend (data is already persistent)`);let b;if(v){let{getRedisClient:te,waitForReady:fe}=await Promise.resolve().then(()=>(e_(),Qv));b=te(h),await fe(b)}let x={type:d,dbPath:m,redisClient:b},$=g||v,O=typeof t.protocol=="string"?t.protocol:void 0,ce=typeof t.dances=="string"?t.dances:void 0,X;if(typeof t.agents=="string")try{X=JSON.parse(t.agents)}catch(te){console.error(`[incubator] Failed to parse --agents JSON: ${te.message}`),process.exit(1)}let ee=[];for(let te of process.argv.slice(2))te.startsWith("--integration=")&&ee.push(te.slice(14));let ge=ee.length>0||t.integrations===!0,U=new mp(x),ne;if(a)console.error("[incubator] WARNING: Carapace disabled \u2014 no prompt injection scanning");else{let te=dP(i);U.setGuard(te,i),ne=fe=>mP(fe,te,i),console.error("[incubator] Carapace active \u2014 scanning writes, reads, and snapshots")}if(s&&!$){let te=await MP(s,U,ne);te>0&&console.error(`[incubator] Restored ${te} namespace(s) from ${s}`)}if(O)try{let te=await kc(O);U.setProtocol("default",te),r&&te.name!=="default"&&U.setProtocol(te.name,te),console.error(`[incubator] Protocol loaded: "${te.title}" (${te.name})`)}catch(te){console.error(`[incubator] Failed to load protocol: ${te.message}`),process.exit(1)}let rt,Mt=ce;if(!Mt&&f)try{let te=qp(oc(f),"utf-8"),fe=f.endsWith(".json")?JSON.parse(te):Xr.load(te),Lt=fe.hives??{},se=Object.values(Lt)[0],ue=se?.dances??se?.logic??fe.dances??fe.logic;typeof ue=="string"&&(Mt=oc(Dp(f),ue))}catch{}if(Mt){let{loadDances:te}=await Promise.resolve().then(()=>(Ko(),ri)),fe=oc(Mt),Lt=new URL(`file://${fe}`).href;rt=await te(Lt);let se=[...rt.tools.keys()];console.error(`[incubator] Dances loaded: ${se.join(", ")}${rt.inject?" + inject":""}`)}if(console.error(g?`[incubator] Backend: sqlite (${m})`:v?`[incubator] Backend: redis (${h})`:"[incubator] Backend: memory"),r){let te=new Map,fe;if(v&&b){let ie=b.duplicate(),{waitForReady:oe}=await Promise.resolve().then(()=>(e_(),Qv));await oe(ie),fe=new yp(b,ie)}else fe=new gp;let Lt,se=process.env.HONEYCOMB_BROKER_SOCKET,ue=process.env.HONEYCOMB_HIVE_NAME;if(se&&ue){let ie=process.env.HONEYCOMB_PUBLISHES?.split(",").filter(Boolean)??[],oe=process.env.HONEYCOMB_SUBSCRIBES?.split(",").filter(Boolean)??[],{IPCTransport:Me}=await Promise.resolve().then(()=>(zR(),NR)),ye=new Me({socketPath:se,hiveName:ue,publishes:ie,subscribes:oe});await ye.connect(),console.error(`[incubator] Honeycomb: connected to broker as "${ue}"`),Lt={transport:ye,hiveName:ue,hivePublishes:ie,hiveSubscribes:oe}}U.setBus(fe,Lt);let ct=U.get("default"),Ir=new vp(fe,ct.runs);Ir.start();let V=[],F=new kp(i);if(O){let ie=U.getProtocol("default");ie?.governance?.webhooks?.length&&F.register("default",ie.governance.webhooks,fe)}let me=u?"https":"http",Jr=u?"wss":"ws",Be,Oe;try{let ie=await Promise.resolve().then(()=>(BR(),HR)),oe=ie.default??ie,Me=Dp(sC(import.meta.url)),ye=iC(Me,"..","dashboard","dist");E_(ye)&&(Be=oe(ye,{single:!0,dev:!0}),console.error(`[incubator] Dashboard: ${me}://localhost:${n}/dashboard`)),p&&E_(p)&&(Oe=oe(p,{single:!0,dev:!0}),console.error(`[incubator] Static: ${me}://localhost:${n}/`))}catch{}let Ar=async(ie,oe)=>{if(ie.url?.startsWith("/api/")){await hP(ie,oe,U,i);return}let Me=new URL(ie.url??"/",`${me}://localhost:${n}`);if(Me.pathname==="/dashboard"||Me.pathname.startsWith("/dashboard/")){if(Be){let br=ie.url;ie.url=Me.pathname.replace(/^\/dashboard/,"")||"/",Me.search&&(ie.url+=Me.search),Be(ie,oe,()=>{ie.url=br,oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Not found."}))});return}oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Dashboard not available."}));return}if(Me.pathname!=="/mcp"){if(Me.pathname==="/"&&!Oe&&Be){oe.writeHead(302,{Location:"/dashboard"}),oe.end();return}Oe?Oe(ie,oe,()=>{oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."}))}):(oe.writeHead(404,{"Content-Type":"application/json"}),oe.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."})));return}let ye=ie.headers["x-namespace"]||"default",Ue=U.get(ye),G=ie.headers["mcp-session-id"];if(G&&te.has(G)){await te.get(G).transport.handleRequest(ie,oe);return}let $t=`agent_${oC().slice(0,8)}`,or=new Nl({sessionIdGenerator:()=>oC(),onsessioninitialized:br=>{let gi=ye==="default"?"":`@${ye}`;console.error(`[incubator] Session ${br} started (${$t}${gi})`),te.set(br,{server:ac,transport:or})}});or.onclose=()=>{let br=or.sessionId;br&&(te.delete(br),console.error(`[incubator] Session ${br} closed`))};let ac=kv(Ue,{agentId:$t,namespace:ye,persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!$?()=>{hp(s,U)}:void 0,getProtocol:()=>U.getProtocol(ye)});await ac.connect(or),await or.handleRequest(ie,oe)},Kr=u?iV({key:qp(l),cert:qp(c)},Ar):sV(Ar),hn;if(rt){let{buildAcpHelper:ie}=await Promise.resolve().then(()=>(Ko(),ri));hn={module:rt,getState:async oe=>{let ye=await U.get(oe).state.query(),Ue={};for(let G of ye)Ue[G.key]=typeof G.value=="string"?G.value:JSON.stringify(G.value);return Ue},getAcpHelper:(oe,Me)=>{let ye=U.get(oe);return ie({publishEvent:async(Ue,G,$t,or)=>{let hi=await ye.events.publish(G,$t??{},or??Me);fe.publish(oe,hi)},claimResource:async(Ue,G,$t,or)=>(await ye.claims.claim(G,G,$t,or)).claim.resource,releaseResource:async(Ue,G)=>{await ye.claims.release(G,Me)},setState:async(Ue,G,$t)=>{await ye.state.set(G,$t,Me)}},oe,Me)}}}let nr;try{let{setupWebSocket:ie}=await Promise.resolve().then(()=>(nC(),rC));nr=await ie(Kr,U,fe,i,void 0,hn)}catch{}if(f){let ie=qp(oc(f),"utf-8"),oe=f.endsWith(".json")?JSON.parse(ie):Xr.load(ie),Me=oe.hives??{},ye=Object.values(Me)[0],Ue=(ye?.agents??ye?.workers??[]).map(Kt=>({role:String(Kt.role??""),type:Kt.type??"worker",prompt:typeof Kt.prompt=="string"?Kt.prompt:void 0,wakeOn:Kt.wake_on?{types:Kt.wake_on.types,maxWakes:Kt.wake_on.max_wakes}:void 0})),G=ye?.acp??ye?.spec??ye?.protocol;if(typeof G=="string"&&O===void 0){let Kt=oc(Dp(f),G);if(E_(Kt)){let no=await kc(Kt);if(U.setProtocol("default",no),console.error(`[incubator] Protocol loaded from brood: ${G}`),Ue.length===0&&no.roles){for(let[cc,lc]of Object.entries(no.roles)){let pI=typeof lc.agents=="number"?lc.agents:1;for(let F_=0;F_<pI;F_++)Ue.push({role:cc,type:"worker",prompt:void 0,wakeOn:void 0})}console.error(`[incubator] Derived ${Ue.length} agents from spec roles`)}}}let $t=typeof oe.stagger=="number"?oe.stagger:0,or=typeof oe.provider=="string"?oe.provider:"ollama/qwen3:8b",hi=oe.env??{},ac=Dp(sC(import.meta.url)),br=iC(ac,"agent","cli.js");console.error(`[incubator] Brood loaded: ${Ue.length} agents (${or}), waiting for "start" event`);let gi=!1;fe.subscribe("default",Kt=>{if(Kt.type==="start"&&!gi){gi=!0,console.error("[orchestrator] Start event received, spawning agents...");let no={provider:or,stagger:$t,noAcp:!1,propolisPort:0,worktree:process.cwd(),hiveEntry:br,tls:u,env:hi,agents:Ue},cc=new Ja(no,n,fe,ct.runs,i,ct,U,hn?.module);cc.start().catch(lc=>{console.error(`[orchestrator] Spawn failed: ${lc.message}`)}),V.push(cc)}if(Kt.type==="reset"){gi=!1;for(let no of V)no.shutdown().catch(()=>{});V.length=0,console.error("[orchestrator] Reset \u2014 agents stopped, ready for new game")}})}let ot;if(ge){let ie=U.get("default");ot=new Ua({namespace:"default",bus:fe,eventStore:ie.events,verbose:i});let oe=Ov();if(ee.length>0)for(let ye of ee){let Ue=oe[ye];if(Ue)try{await ot.load(ye,Ue.package,Ue.config)}catch(G){console.error(`[integrations] Failed to load "${ye}": ${G.message}`)}else try{await ot.load(ye,ye)}catch(G){console.error(`[integrations] Failed to load "${ye}": ${G.message}`)}}else await ot.loadFromConfig(oe);let Me=ot.getLoadedNames();if(Me.length>0){console.error(`[incubator] Integrations: ${Me.join(", ")}`);let ye=ot.getTools();ye.length>0&&console.error(`[incubator] Integration tools: ${ye.map(Ue=>Ue.name).join(", ")}`)}}Kr.listen(n,()=>{console.error(`[incubator] ${u?"HTTPS":"HTTP"} server listening on port ${n}`),console.error(`[incubator] MCP endpoint: ${me}://localhost:${n}/mcp`),console.error(`[incubator] REST API: ${me}://localhost:${n}/api/`),console.error(nr?`[incubator] WebSocket: ${Jr}://localhost:${n}/ws`:'[incubator] WebSocket: disabled (install "ws" to enable)'),s&&!$&&console.error(`[incubator] Persistence: ${s}`),X&&(Jt=new Ja(X,n,fe,ct.runs,i,ct,U,hn?.module),Jt.start().catch(ie=>{console.error(`[orchestrator] Fatal: ${ie.message}`),process.exit(1)}))});let Jt;process.on("SIGINT",async()=>{console.error(`
411
+ [incubator] Shutting down...`),Jt&&await Jt.shutdown();for(let ie of V)await ie.shutdown();Ir.stop(),F.close(),ot&&await ot.stopAll(),nr&&nr.close(),await fe.close(),s&&!$&&(await hp(s,U),console.error("[incubator] Snapshots saved")),b&&(await b.quit(),console.error("[incubator] Redis disconnected"));for(let[,ie]of te)ie.server.close();Kr.close(),process.exit(0)})}else{let te=U.get("default"),Lt=kv(te,{agentId:o??"agent_stdio",persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!$?()=>{hp(s,U)}:void 0,getProtocol:()=>U.getProtocol("default")}),se=new Rl;await Lt.connect(se),console.error(`[incubator] Running on stdio (agent: ${o??"agent_stdio"})`),s&&!$&&console.error(`[incubator] Persistence: ${s}`)}}var P_=w(()=>{MS();JS();Ev();gP();op();zP();LP();DP();$i();Oi();FP();HP();CR();IR()});var aC={};K(aC,{serve:()=>lV});async function lV(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
412
412
  ${y("bold","wgl serve")} \u2014 start a local incubator server
413
413
 
414
414
  ${y("cyan","USAGE:")}
@@ -424,9 +424,9 @@ ${y("cyan","EXAMPLES:")}
424
424
  wgl serve --port 4000
425
425
  wgl serve --protocol workflow.acp
426
426
  wgl serve --persist ./data.db
427
- `);return}let e=t.indexOf("--port"),r=e!==-1?parseInt(t[e+1],10):3100,n=t.indexOf("--protocol"),o=n!==-1?t[n+1]:void 0,s=t.indexOf("--persist"),i=s!==-1?t[s+1]:void 0;console.log(C("Starting Incubator")),console.log(S("Port",String(r))),o&&console.log(S("Protocol",o)),i&&console.log(S("Persist",i)),console.log();let{main:a}=await Promise.resolve().then(()=>(w_(),b_)),c=process.argv;process.argv=["node","incubator","--http",`--port=${r}`],o&&process.argv.push(`--protocol=${o}`),i&&process.argv.push("--backend=sqlite",`--db=${i}`);try{await a()}finally{process.argv=c}}var QO=w(()=>{"use strict";Re()});import{readFileSync as FV,writeFileSync as HV,existsSync as BV}from"node:fs";import{join as VV}from"node:path";import{homedir as GV}from"node:os";function He(){let t=Nr();return{...eC,defaultPlatform:t.platform,defaultRole:t.role??eC.defaultRole,editor:t.cli.editor,activeProfile:t.activeProfile}}function rC(t){let r=Nr(),n=tC[t];if(n){let s=dc(r,n);return s!==void 0?String(s):void 0}let o=dc(r,t);return o!==void 0&&typeof o!="object"?String(o):void 0}function Mp(t,e){let r=VV(GV(),".wglrc.json"),n=BV(r)?WV(FV(r,"utf8")):{},o=tC[t]||t;gi(n,o,JV(e)),HV(r,JSON.stringify(n,null,2)+`
428
- `)}function WV(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return{}}}function JV(t){if(t==="true")return!0;if(t==="false")return!1;let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}var eC,tC,ts=w(()=>{"use strict";bn();eC={defaultPlatform:"https://hivemind.honeyb.dev",defaultRole:"developer",editor:"nano",activeProfile:"personal"},tC={defaultPlatform:"platform",defaultRole:"role",editor:"cli.editor",activeProfile:"activeProfile"}});import{request as KV}from"node:http";import{request as YV}from"node:https";function ro(t,e,r,n={}){return new Promise((o,s)=>{let i=new URL(e),c=i.protocol==="https:"?YV:KV,l={...n},u;r!==void 0&&(u=JSON.stringify(r),l["Content-Type"]="application/json",l["Content-Length"]=Buffer.byteLength(u).toString());let p=c(i,{method:t,headers:l,timeout:XV},m=>{let d="";m.on("data",f=>d+=f),m.on("end",()=>{try{let f=d?JSON.parse(d):{};o({ok:m.statusCode>=200&&m.statusCode<300,status:m.statusCode,data:f})}catch{o({ok:!1,status:m.statusCode,data:{}})}})});p.on("error",m=>s(m)),p.on("timeout",()=>{p.destroy(),s(new Error("timeout"))}),u&&p.write(u),p.end()})}var XV,x_=w(()=>{XV=1e4});function rs(t){return pd(t)}function ui(t,e){dd(t,e)}function S_(t){return fd(t)}function Lp(){return md()}function rc(t){return Date.now()/1e3>t.expiresAt-60}async function $_(){let t=await ro("POST","https://github.com/login/device/code",{client_id:nC,scope:"read:user user:email"},{Accept:"application/json"});if(!t.ok)throw new Error("Failed to start device flow");return t.data}async function k_(t,e,r){let n=Date.now()+r*1e3;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,e*1e3));let o=await ro("POST","https://github.com/login/oauth/access_token",{client_id:nC,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"},{Accept:"application/json"});if(o.ok&&o.data.access_token)return o.data.access_token;if(o.data.error!=="authorization_pending"){if(o.data.error==="slow_down"){e+=5;continue}if(o.data.error&&o.data.error!=="authorization_pending")throw new Error(o.data.error_description||o.data.error)}}throw new Error("Device flow expired")}async function E_(t,e){let r=await ro("POST",`${t}/api/auth/device/exchange`,{github_access_token:e});if(!r.ok)throw new Error("Token exchange failed");return r.data}async function T_(t,e){let r=await ro("GET",`${t}/api/auth/me`,void 0,{Authorization:`Bearer ${e}`});if(!r.ok)throw new Error("Invalid PAT or network error");let n=r.data.user;return{email:n.email||n.username,org:"personal"}}async function P_(t,e){let r=await ro("POST",`${t}/api/auth/token`,{client_id:"wgl-cli",refresh_token:e,grant_type:"refresh_token"});if(!r.ok)throw new Error("Token refresh failed");return r.data}var nC,R_=w(()=>{x_();bn();nC="Ov23liy8H1qGZdVAk1Vr"});function tt(t){let e=t?.profileName||"personal",r=rs(e);if(!r)throw new Error("Not logged in. Run `wgl auth login` first.");let n=r,o=t?.platform||n.platform,s=new URL(o),i=`${s.protocol}//api.${s.host}/rest/v1`,a=n.accessToken,c=null;async function l(){try{let d=await P_(n.platform,n.refreshToken);a=d.access_token,ui(e,{platform:n.platform,email:n.email,org:n.org,accessToken:d.access_token,refreshToken:d.refresh_token,expiresAt:Math.floor(Date.now()/1e3)+d.expires_in})}catch{throw new Error("Session expired. Run `wgl auth login` to re-authenticate.")}finally{c=null}}async function u(){if(rc(n))return c||(c=l()),c}function p(d,f,h,g=!1){let v=`${i}${f}`,_={};return g||(_.Authorization=`Bearer ${a}`),ro(d,v,h,_)}async function m(d,f,h){await u();let g=await p(d,f,h);return g.status===401?(c||(c=l()),await c,p(d,f,h)):g}return{searchSpecs:(d,f)=>{let h=new URLSearchParams;d&&h.set("q",d),f?.tag&&h.set("tag",f.tag),f?.sort&&h.set("sort",f.sort),f?.page&&h.set("page",String(f.page));let g=h.toString();return p("GET",`/marketplace/specs${g?"?"+g:""}`)},getSpec:d=>p("GET",`/marketplace/specs/${encodeURIComponent(d)}`),downloadSpec:d=>p("GET",`/marketplace/specs/${encodeURIComponent(d)}/download`),publishSpec:d=>m("POST","/marketplace/specs",d),updateSpec:(d,f)=>m("PUT",`/marketplace/specs/${encodeURIComponent(d)}`,f),forkSpec:(d,f)=>m("POST",`/marketplace/specs/${encodeURIComponent(d)}/fork`,f?{fork_name:f}:void 0),listMySpecs:()=>m("GET","/marketplace/specs/mine"),deleteSpec:d=>m("DELETE",`/marketplace/specs/${encodeURIComponent(d)}`),listReviews:d=>p("GET",`/marketplace/specs/${encodeURIComponent(d)}/reviews`),createReview:(d,f,h)=>m("POST",`/marketplace/specs/${encodeURIComponent(d)}/reviews`,{rating:f,comment:h}),deleteReview:(d,f)=>m("DELETE",`/marketplace/specs/${encodeURIComponent(d)}/reviews/${encodeURIComponent(f)}`),searchIntegrations:(d,f)=>{let h=new URLSearchParams;d&&h.set("q",d),f?.category&&h.set("category",f.category),f?.sort&&h.set("sort",f.sort),f?.page&&h.set("page",String(f.page));let g=h.toString();return p("GET",`/marketplace/integrations${g?"?"+g:""}`)},getIntegration:d=>p("GET",`/marketplace/integrations/${encodeURIComponent(d)}`),downloadIntegration:d=>p("GET",`/marketplace/integrations/${encodeURIComponent(d)}/download`),publishIntegration:d=>m("POST","/marketplace/integrations",d),updateIntegration:(d,f)=>m("PUT",`/marketplace/integrations/${encodeURIComponent(d)}`,f),deleteIntegration:d=>m("DELETE",`/marketplace/integrations/${encodeURIComponent(d)}`),listIntegrationReviews:(d,f)=>{let h=new URLSearchParams;f?.page&&h.set("page",String(f.page));let g=h.toString();return p("GET",`/marketplace/integrations/${encodeURIComponent(d)}/reviews${g?"?"+g:""}`)},createIntegrationReview:(d,f,h)=>m("POST",`/marketplace/integrations/${encodeURIComponent(d)}/reviews`,{rating:f,comment:h}),deleteIntegrationReview:(d,f)=>m("DELETE",`/marketplace/integrations/${encodeURIComponent(d)}/reviews/${encodeURIComponent(f)}`),listSwarms:()=>m("GET","/colony/swarms"),createSwarm:d=>m("POST","/colony/swarms",d),getSwarm:d=>m("GET",`/colony/swarms/${encodeURIComponent(d)}`),deleteSwarm:d=>m("DELETE",`/colony/swarms/${encodeURIComponent(d)}`),pauseSwarm:d=>m("POST",`/colony/swarms/${encodeURIComponent(d)}/pause`),resumeSwarm:d=>m("POST",`/colony/swarms/${encodeURIComponent(d)}/resume`),getSwarmEvents:(d,f)=>m("GET",`/colony/swarms/${encodeURIComponent(d)}/events${f?"?since="+f:""}`),listKeys:()=>m("GET","/colony/keys"),createKey:d=>m("POST","/colony/keys",d),revokeKey:d=>m("DELETE",`/colony/keys/${encodeURIComponent(d)}`),scan:d=>m("POST","/carapace/v1/scan",d),carapaceDashboard:()=>m("GET","/carapace/dashboard/overview"),carapaceUsage:d=>m("GET",`/carapace/dashboard/usage${d?"?hours="+d:""}`),carapaceBlocked:d=>{let f=new URLSearchParams;d?.limit&&f.set("limit",String(d.limit)),d?.offset&&f.set("offset",String(d.offset));let h=f.toString();return m("GET",`/carapace/dashboard/blocked${h?"?"+h:""}`)},listCarapaceKeys:()=>m("GET","/carapace/dashboard/keys"),createCarapaceKey:(d,f)=>m("POST","/carapace/dashboard/keys",{name:d,mode:f}),deleteCarapaceKey:d=>m("DELETE",`/carapace/dashboard/keys/${encodeURIComponent(d)}`),telemetryOverview:d=>m("GET",`/carapace/api/telemetry/overview${d?"?days="+d:""}`),telemetryTimeline:d=>m("GET",`/carapace/api/telemetry/timeline${d?"?days="+d:""}`),telemetryEvents:d=>{let f=new URLSearchParams;d?.limit&&f.set("limit",String(d.limit)),d?.offset&&f.set("offset",String(d.offset));let h=f.toString();return m("GET",`/carapace/api/telemetry/events${h?"?"+h:""}`)},getMe:()=>m("GET","/auth/me")}}var oC=w(()=>{x_();R_()});var pi=w(()=>{oC();R_()});var sC={};X(sC,{auth:()=>QV});async function QV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
429
- ${y("bold","wgl auth")} \u2014 platform authentication
427
+ `);return}let e=t.indexOf("--port"),r=e!==-1?parseInt(t[e+1],10):3100,n=t.indexOf("--protocol"),o=n!==-1?t[n+1]:void 0,s=t.indexOf("--persist"),i=s!==-1?t[s+1]:void 0;console.log(C("Starting Incubator")),console.log(S("Port",String(r))),o&&console.log(S("Protocol",o)),i&&console.log(S("Persist",i)),console.log();let{main:a}=await Promise.resolve().then(()=>(P_(),T_)),c=process.argv;process.argv=["node","incubator","--http",`--port=${r}`],o&&process.argv.push(`--protocol=${o}`),i&&process.argv.push("--backend=sqlite",`--db=${i}`);try{await a()}finally{process.argv=c}}var cC=w(()=>{"use strict";Re()});import{readFileSync as uV,writeFileSync as pV,existsSync as dV}from"node:fs";import{join as fV}from"node:path";import{homedir as mV}from"node:os";function je(){let t=Nr();return{...lC,defaultPlatform:t.platform,defaultRole:t.role??lC.defaultRole,editor:t.cli.editor,activeProfile:t.activeProfile}}function pC(t){let r=Nr(),n=uC[t];if(n){let s=hc(r,n);return s!==void 0?String(s):void 0}let o=hc(r,t);return o!==void 0&&typeof o!="object"?String(o):void 0}function Zp(t,e){let r=fV(mV(),".wglrc.json"),n=dV(r)?hV(uV(r,"utf8")):{},o=uC[t]||t;_i(n,o,gV(e)),pV(r,JSON.stringify(n,null,2)+`
428
+ `)}function hV(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return{}}}function gV(t){if(t==="true")return!0;if(t==="false")return!1;let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}var lC,uC,rs=w(()=>{"use strict";bn();lC={defaultPlatform:"https://hivemind.honeyb.dev",defaultRole:"developer",editor:"nano",activeProfile:"personal"},uC={defaultPlatform:"platform",defaultRole:"role",editor:"cli.editor",activeProfile:"activeProfile"}});import{request as yV}from"node:http";import{request as vV}from"node:https";function ro(t,e,r,n={}){return new Promise((o,s)=>{let i=new URL(e),c=i.protocol==="https:"?vV:yV,l={...n},u;r!==void 0&&(u=JSON.stringify(r),l["Content-Type"]="application/json",l["Content-Length"]=Buffer.byteLength(u).toString());let p=c(i,{method:t,headers:l,timeout:_V},f=>{let d="";f.on("data",m=>d+=m),f.on("end",()=>{try{let m=d?JSON.parse(d):{};o({ok:f.statusCode>=200&&f.statusCode<300,status:f.statusCode,data:m})}catch{o({ok:!1,status:f.statusCode,data:{}})}})});p.on("error",f=>s(f)),p.on("timeout",()=>{p.destroy(),s(new Error("timeout"))}),u&&p.write(u),p.end()})}var _V,R_=w(()=>{_V=1e4});function ns(t){return vd(t)}function di(t,e){_d(t,e)}function O_(t){return bd(t)}function Up(){return wd()}function sc(t){return Date.now()/1e3>t.expiresAt-60}async function C_(){let t=await ro("POST","https://github.com/login/device/code",{client_id:dC,scope:"read:user user:email"},{Accept:"application/json"});if(!t.ok)throw new Error("Failed to start device flow");return t.data}async function I_(t,e,r){let n=Date.now()+r*1e3;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,e*1e3));let o=await ro("POST","https://github.com/login/oauth/access_token",{client_id:dC,device_code:t,grant_type:"urn:ietf:params:oauth:grant-type:device_code"},{Accept:"application/json"});if(o.ok&&o.data.access_token)return o.data.access_token;if(o.data.error!=="authorization_pending"){if(o.data.error==="slow_down"){e+=5;continue}if(o.data.error&&o.data.error!=="authorization_pending")throw new Error(o.data.error_description||o.data.error)}}throw new Error("Device flow expired")}async function A_(t,e){let r=await ro("POST",`${t}/api/auth/device/exchange`,{github_access_token:e});if(!r.ok)throw new Error("Token exchange failed");return r.data}async function N_(t,e){let r=await ro("GET",`${t}/api/auth/me`,void 0,{Authorization:`Bearer ${e}`});if(!r.ok)throw new Error("Invalid PAT or network error");let n=r.data.user;return{email:n.email||n.username,org:"personal"}}async function z_(t,e){let r=await ro("POST",`${t}/api/auth/token`,{client_id:"wgl-cli",refresh_token:e,grant_type:"refresh_token"});if(!r.ok)throw new Error("Token refresh failed");return r.data}var dC,j_=w(()=>{R_();bn();dC="Ov23liy8H1qGZdVAk1Vr"});function Xe(t){let e=t?.profileName||"personal",r=ns(e);if(!r)throw new Error("Not logged in. Run `wgl auth login` first.");let n=r,o=t?.platform||n.platform,s=new URL(o),i=`${s.protocol}//api.${s.host}/rest/v1`,a=n.accessToken,c=null;async function l(){try{let d=await z_(n.platform,n.refreshToken);a=d.access_token,di(e,{platform:n.platform,email:n.email,org:n.org,accessToken:d.access_token,refreshToken:d.refresh_token,expiresAt:Math.floor(Date.now()/1e3)+d.expires_in})}catch{throw new Error("Session expired. Run `wgl auth login` to re-authenticate.")}finally{c=null}}async function u(){if(sc(n))return c||(c=l()),c}function p(d,m,h,g=!1){let v=`${i}${m}`,b={};return g||(b.Authorization=`Bearer ${a}`),ro(d,v,h,b)}async function f(d,m,h){await u();let g=await p(d,m,h);return g.status===401?(c||(c=l()),await c,p(d,m,h)):g}return{searchSpecs:(d,m)=>{let h=new URLSearchParams;d&&h.set("q",d),m?.tag&&h.set("tag",m.tag),m?.sort&&h.set("sort",m.sort),m?.page&&h.set("page",String(m.page));let g=h.toString();return p("GET",`/marketplace/specs${g?"?"+g:""}`)},getSpec:d=>p("GET",`/marketplace/specs/${encodeURIComponent(d)}`),downloadSpec:d=>p("GET",`/marketplace/specs/${encodeURIComponent(d)}/download`),publishSpec:d=>f("POST","/marketplace/specs",d),updateSpec:(d,m)=>f("PUT",`/marketplace/specs/${encodeURIComponent(d)}`,m),forkSpec:(d,m)=>f("POST",`/marketplace/specs/${encodeURIComponent(d)}/fork`,m?{fork_name:m}:void 0),listMySpecs:()=>f("GET","/marketplace/specs/mine"),deleteSpec:d=>f("DELETE",`/marketplace/specs/${encodeURIComponent(d)}`),listReviews:d=>p("GET",`/marketplace/specs/${encodeURIComponent(d)}/reviews`),createReview:(d,m,h)=>f("POST",`/marketplace/specs/${encodeURIComponent(d)}/reviews`,{rating:m,comment:h}),deleteReview:(d,m)=>f("DELETE",`/marketplace/specs/${encodeURIComponent(d)}/reviews/${encodeURIComponent(m)}`),searchIntegrations:(d,m)=>{let h=new URLSearchParams;d&&h.set("q",d),m?.category&&h.set("category",m.category),m?.sort&&h.set("sort",m.sort),m?.page&&h.set("page",String(m.page));let g=h.toString();return p("GET",`/marketplace/integrations${g?"?"+g:""}`)},getIntegration:d=>p("GET",`/marketplace/integrations/${encodeURIComponent(d)}`),downloadIntegration:d=>p("GET",`/marketplace/integrations/${encodeURIComponent(d)}/download`),publishIntegration:d=>f("POST","/marketplace/integrations",d),updateIntegration:(d,m)=>f("PUT",`/marketplace/integrations/${encodeURIComponent(d)}`,m),deleteIntegration:d=>f("DELETE",`/marketplace/integrations/${encodeURIComponent(d)}`),listIntegrationReviews:(d,m)=>{let h=new URLSearchParams;m?.page&&h.set("page",String(m.page));let g=h.toString();return p("GET",`/marketplace/integrations/${encodeURIComponent(d)}/reviews${g?"?"+g:""}`)},createIntegrationReview:(d,m,h)=>f("POST",`/marketplace/integrations/${encodeURIComponent(d)}/reviews`,{rating:m,comment:h}),deleteIntegrationReview:(d,m)=>f("DELETE",`/marketplace/integrations/${encodeURIComponent(d)}/reviews/${encodeURIComponent(m)}`),listHives:()=>f("GET","/colony/hives"),createHive:d=>f("POST","/colony/hives",d),getHive:d=>f("GET",`/colony/hives/${encodeURIComponent(d)}`),deleteHive:d=>f("DELETE",`/colony/hives/${encodeURIComponent(d)}`),pauseHive:d=>f("POST",`/colony/hives/${encodeURIComponent(d)}/pause`),resumeHive:d=>f("POST",`/colony/hives/${encodeURIComponent(d)}/resume`),getHiveEvents:(d,m,h)=>{let g=new URLSearchParams;m!==void 0&&g.set("since",String(m)),h&&g.set("type",h);let v=g.toString();return f("GET",`/colony/hives/${encodeURIComponent(d)}/events${v?"?"+v:""}`)},startHive:d=>f("POST",`/colony/hives/${encodeURIComponent(d)}/start`),getHiveAgents:d=>f("GET",`/colony/hives/${encodeURIComponent(d)}/agents`),setProviderKey:(d,m,h)=>f("POST",`/colony/hives/${encodeURIComponent(d)}/provider-keys`,{provider:m,key:h}),listKeys:()=>f("GET","/colony/keys"),createKey:d=>f("POST","/colony/keys",d),revokeKey:d=>f("DELETE",`/colony/keys/${encodeURIComponent(d)}`),scan:d=>f("POST","/carapace/v1/scan",d),carapaceDashboard:()=>f("GET","/carapace/dashboard/overview"),carapaceUsage:d=>f("GET",`/carapace/dashboard/usage${d?"?hours="+d:""}`),carapaceBlocked:d=>{let m=new URLSearchParams;d?.limit&&m.set("limit",String(d.limit)),d?.offset&&m.set("offset",String(d.offset));let h=m.toString();return f("GET",`/carapace/dashboard/blocked${h?"?"+h:""}`)},listCarapaceKeys:()=>f("GET","/carapace/dashboard/keys"),createCarapaceKey:(d,m)=>f("POST","/carapace/dashboard/keys",{name:d,mode:m}),deleteCarapaceKey:d=>f("DELETE",`/carapace/dashboard/keys/${encodeURIComponent(d)}`),telemetryOverview:d=>f("GET",`/carapace/api/telemetry/overview${d?"?days="+d:""}`),telemetryTimeline:d=>f("GET",`/carapace/api/telemetry/timeline${d?"?days="+d:""}`),telemetryEvents:d=>{let m=new URLSearchParams;d?.limit&&m.set("limit",String(d.limit)),d?.offset&&m.set("offset",String(d.offset));let h=m.toString();return f("GET",`/carapace/api/telemetry/events${h?"?"+h:""}`)},getMe:()=>f("GET","/auth/me")}}var fC=w(()=>{R_();j_()});var fi=w(()=>{fC();j_()});var mC={};K(mC,{auth:()=>bV});async function bV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
429
+ ${y("bold","wgl auth")} \u2014 Hivemind authentication
430
430
 
431
431
  ${y("cyan","USAGE:")}
432
432
  wgl auth login [--platform URL] Log in via device flow
@@ -434,11 +434,11 @@ ${y("cyan","USAGE:")}
434
434
  wgl auth logout Clear stored credentials
435
435
  wgl auth status Show current auth state
436
436
  wgl auth switch <profile> Switch between saved profiles
437
- `);return}switch(e){case"login":{let r=t.indexOf("--platform"),n=t.indexOf("--token"),o=He(),s=r!==-1?t[r+1]:o.defaultPlatform,i=o.activeProfile||"personal";if(n!==-1){let a=t[n+1];if(!a){console.log(b("Usage: wgl auth login --token <PAT>")),process.exit(2);return}console.log(y("dim",`Authenticating with PAT on ${s}...
438
- `));try{let c=await T_(s,a);ui(i,{platform:s,accessToken:a,refreshToken:"",expiresAt:Math.floor(Date.now()/1e3)+365*24*60*60,email:c.email,org:c.org||"personal"}),console.log(z(`Logged in as ${c.email} (PAT)`)),console.log(S("Profile",i))}catch(c){console.log(b(`PAT login failed: ${c.message}`)),process.exit(1)}break}console.log(y("dim",`Authenticating via GitHub...
439
- `));try{let a=await $_();console.log(` Visit: ${y("cyan",a.verification_uri)}`),console.log(` Enter code: ${y("bold",a.user_code)}
440
- `),console.log(y("dim","Waiting for authorization..."));let c=await k_(a.device_code,a.interval||5,a.expires_in||300);console.log(y("dim","Exchanging token with platform..."));let l=await E_(s,c);ui(i,{platform:s,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:Math.floor(Date.now()/1e3)+l.expires_in,email:l.email,org:l.org}),console.log(z(`Logged in as ${l.email} (${l.org})`)),console.log(S("Profile",i))}catch(a){console.log(b(`Login failed: ${a.message}`)),process.exit(1)}break}case"logout":{let n=He().activeProfile||"personal";S_(n)?console.log(z(`Logged out (profile: ${n})`)):console.log(y("dim","Not logged in"));break}case"status":{let n=He().activeProfile||"personal",o=rs(n);if(console.log(C("Auth Status")),console.log(S("Profile",n)),!o)console.log(` ${y("dim","Not logged in")}`),console.log(`
441
- Run ${y("cyan","wgl auth login")} to authenticate`);else if(console.log(S("Platform",o.platform)),console.log(S("Email",o.email)),console.log(S("Org",o.org)),rc(o))console.log(` ${gn("Token expired \u2014 run `wgl auth login` to refresh")}`);else{let i=o.expiresAt-Math.floor(Date.now()/1e3),a=Math.floor(i/3600),c=Math.floor(i%3600/60);console.log(S("Token",y("green",`valid (${a}h ${c}m remaining)`)))}let s=Lp();if(s.length>1){console.log(C("Available Profiles"));for(let i of s){let a=i===n?y("green"," (active)"):"",c=rs(i);console.log(` ${y("bold",i)}${a} \u2014 ${c.email} (${c.org})`)}}console.log();break}case"switch":{let r=t[1];if(!r){console.log(b("Usage: wgl auth switch <profile>")),process.exit(2);return}let n=rs(r);if(!n){console.log(b(`Profile not found: ${r}`));let o=Lp();o.length>0&&console.log(y("dim",` Available: ${o.join(", ")}`)),process.exit(1);return}Mp("activeProfile",r),console.log(z(`Switched to profile: ${r} (${n.email})`));break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl auth --help` for usage"),process.exit(2)}}var iC=w(()=>{"use strict";Re();ts();pi()});var cC={};X(cC,{configCmd:()=>eG});async function eG(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
437
+ `);return}switch(e){case"login":{let r=t.indexOf("--platform"),n=t.indexOf("--token"),o=je(),s=r!==-1?t[r+1]:o.defaultPlatform,i=o.activeProfile||"personal";if(n!==-1){let a=t[n+1];if(!a){console.log(_("Usage: wgl auth login --token <PAT>")),process.exit(2);return}console.log(y("dim",`Authenticating with PAT on ${s}...
438
+ `));try{let c=await N_(s,a);di(i,{platform:s,accessToken:a,refreshToken:"",expiresAt:Math.floor(Date.now()/1e3)+365*24*60*60,email:c.email,org:c.org||"personal"}),console.log(N(`Logged in as ${c.email} (PAT)`)),console.log(S("Profile",i))}catch(c){console.log(_(`PAT login failed: ${c.message}`)),process.exit(1)}break}console.log(y("dim",`Authenticating via GitHub...
439
+ `));try{let a=await C_();console.log(` Visit: ${y("cyan",a.verification_uri)}`),console.log(` Enter code: ${y("bold",a.user_code)}
440
+ `),console.log(y("dim","Waiting for authorization..."));let c=await I_(a.device_code,a.interval||5,a.expires_in||300);console.log(y("dim","Exchanging token with Hivemind..."));let l=await A_(s,c);di(i,{platform:s,accessToken:l.access_token,refreshToken:l.refresh_token,expiresAt:Math.floor(Date.now()/1e3)+l.expires_in,email:l.email,org:l.org}),console.log(N(`Logged in as ${l.email} (${l.org})`)),console.log(S("Profile",i))}catch(a){console.log(_(`Login failed: ${a.message}`)),process.exit(1)}break}case"logout":{let n=je().activeProfile||"personal";O_(n)?console.log(N(`Logged out (profile: ${n})`)):console.log(y("dim","Not logged in"));break}case"status":{let n=je().activeProfile||"personal",o=ns(n);if(console.log(C("Auth Status")),console.log(S("Profile",n)),!o)console.log(` ${y("dim","Not logged in")}`),console.log(`
441
+ Run ${y("cyan","wgl auth login")} to authenticate`);else if(console.log(S("Hivemind",o.platform)),console.log(S("Email",o.email)),console.log(S("Org",o.org)),sc(o))console.log(` ${gn("Token expired \u2014 run `wgl auth login` to refresh")}`);else{let i=o.expiresAt-Math.floor(Date.now()/1e3),a=Math.floor(i/3600),c=Math.floor(i%3600/60);console.log(S("Token",y("green",`valid (${a}h ${c}m remaining)`)))}let s=Up();if(s.length>1){console.log(C("Available Profiles"));for(let i of s){let a=i===n?y("green"," (active)"):"",c=ns(i);console.log(` ${y("bold",i)}${a} \u2014 ${c.email} (${c.org})`)}}console.log();break}case"switch":{let r=t[1];if(!r){console.log(_("Usage: wgl auth switch <profile>")),process.exit(2);return}let n=ns(r);if(!n){console.log(_(`Profile not found: ${r}`));let o=Up();o.length>0&&console.log(y("dim",` Available: ${o.join(", ")}`)),process.exit(1);return}Zp("activeProfile",r),console.log(N(`Switched to profile: ${r} (${n.email})`));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl auth --help` for usage"),process.exit(2)}}var hC=w(()=>{"use strict";Re();rs();fi()});var yC={};K(yC,{configCmd:()=>wV});async function wV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
442
442
  ${y("bold","wgl config")} \u2014 global preferences
443
443
 
444
444
  ${y("cyan","USAGE:")}
@@ -458,7 +458,7 @@ ${y("cyan","KEYS (dotted paths supported):")}
458
458
  carapace.threshold Block threshold (0-100)
459
459
  telemetry.endpoint Telemetry endpoint URL
460
460
  telemetry.apiKey Telemetry API key
461
- `);return}switch(e){case"set":{let r=t[1],n=t.slice(2).join(" ");if(!r||!n){console.log(b("Usage: wgl config set <key> <value>")),process.exit(2);return}Mp(r,n),console.log(z(`Set ${r} = ${n}`));break}case"get":{let r=t[1];if(!r){console.log(b("Usage: wgl config get <key>")),process.exit(2);return}let n=rC(r);n!==void 0?console.log(n):(console.log(b(`Key not found: ${r}`)),process.exit(1));break}case"list":{let r=Nr(),n=aC(r);console.log(C("Global Config"));for(let[o,s]of n)console.log(S(o,String(s)));console.log();break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl config --help` for usage"),process.exit(2)}}function aC(t,e=""){let r=[];for(let[n,o]of Object.entries(t)){let s=e?`${e}.${n}`:n;o!==null&&typeof o=="object"&&!Array.isArray(o)?r.push(...aC(o,s)):o!==void 0&&o!==""&&r.push([s,String(o)])}return r}var lC=w(()=>{"use strict";Re();ts();bn()});var uC={};X(uC,{marketplace:()=>oG});import{readFileSync as tG,writeFileSync as rG}from"node:fs";import{basename as nG}from"node:path";async function oG(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
461
+ `);return}switch(e){case"set":{let r=t[1],n=t.slice(2).join(" ");if(!r||!n){console.log(_("Usage: wgl config set <key> <value>")),process.exit(2);return}Zp(r,n),console.log(N(`Set ${r} = ${n}`));break}case"get":{let r=t[1];if(!r){console.log(_("Usage: wgl config get <key>")),process.exit(2);return}let n=pC(r);n!==void 0?console.log(n):(console.log(_(`Key not found: ${r}`)),process.exit(1));break}case"list":{let r=Nr(),n=gC(r);console.log(C("Global Config"));for(let[o,s]of n)console.log(S(o,String(s)));console.log();break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl config --help` for usage"),process.exit(2)}}function gC(t,e=""){let r=[];for(let[n,o]of Object.entries(t)){let s=e?`${e}.${n}`:n;o!==null&&typeof o=="object"&&!Array.isArray(o)?r.push(...gC(o,s)):o!==void 0&&o!==""&&r.push([s,String(o)])}return r}var vC=w(()=>{"use strict";Re();rs();bn()});var _C={};K(_C,{marketplace:()=>kV});import{readFileSync as xV,writeFileSync as SV}from"node:fs";import{basename as $V}from"node:path";async function kV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
462
462
  ${y("bold","wgl marketplace")} \u2014 protocol marketplace
463
463
 
464
464
  ${y("cyan","USAGE:")}
@@ -467,10 +467,10 @@ ${y("cyan","USAGE:")}
467
467
  wgl marketplace install <name> Download + load into local server
468
468
  wgl marketplace publish <file> [--name N] [--title T] [--tags t1,t2]
469
469
  wgl marketplace list Your published specs (auth required)
470
- `);return}switch(e){case"search":{await sG(t.slice(1));break}case"info":{await iG(t.slice(1));break}case"install":{await aG(t.slice(1));break}case"publish":{await cG(t.slice(1));break}case"list":{await lG();break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl marketplace --help` for usage"),process.exit(2)}}async function sG(t){let e=t.indexOf("--tag"),r=e!==-1?t[e+1]:void 0,n=t.indexOf("--sort"),o=n!==-1?t[n+1]:void 0,s=[];for(let a=0;a<t.length;a++){if(t[a]==="--tag"||t[a]==="--sort"){a++;continue}s.push(t[a])}let i=s.join(" ")||void 0;try{let c=await tt({profileName:He().activeProfile||"personal"}).searchSpecs(i,{tag:r,sort:o});c.ok||(console.log(b(`Server returned ${c.status}`)),process.exit(1));let{data:l,total:u}=c.data;if(l.length===0){console.log(` ${y("dim","No protocols found")}`);return}console.log(C("Marketplace")),console.log(y("dim",` ${u} protocol${u===1?"":"s"} found
471
- `));let p=l.map(m=>{let d=m.avg_rating>0?` ${y("yellow",`\u2605${m.avg_rating.toFixed(1)}`)}`:"",f=y("dim",`\u2193${m.downloads}`);return[m.name,`${m.title} ${f}${d}`]});console.log(br(p)),console.log()}catch(a){console.log(b(a.message)),process.exit(1)}}async function iG(t){let e=t[0];e||(console.log(b("Usage: wgl marketplace info <name>")),process.exit(2));try{let n=await tt({profileName:He().activeProfile||"personal"}).getSpec(e);n.ok||(n.status===404?console.log(b(`Protocol not found: ${e}`)):console.log(b(`Server returned ${n.status}`)),process.exit(1));let o=n.data;if(console.log(C("Protocol")),console.log(S("Name",o.name)),console.log(S("Title",o.title)),console.log(S("Description",o.description)),console.log(S("Author",o.author.username)),console.log(S("Version",String(o.version))),console.log(S("Downloads",String(o.downloads))),o.avg_rating>0&&console.log(S("Rating",`${o.avg_rating.toFixed(1)} (${o.rating_count} ratings)`)),o.tags.length&&console.log(S("Tags",o.tags.join(", "))),o.forked_from&&console.log(S("Forked from",o.forked_from)),console.log(S("Created",o.created_at)),console.log(S("Updated",o.updated_at)),o.spec_content&&typeof o.spec_content=="object"){let s=o.spec_content;if(s.roles?.length){console.log(C("Roles"));for(let i of s.roles)console.log(` ${y("bold",i.name)}${i.description?` \u2014 ${i.description}`:""}`)}if(s.phases?.length){console.log(C("Phases"));for(let i=0;i<s.phases.length;i++){let a=s.phases[i];console.log(` ${y("cyan",`${i+1}.`)} ${y("bold",a.name)}${a.description?` \u2014 ${a.description}`:""}`)}}}console.log()}catch(r){console.log(b(r.message)),process.exit(1)}}async function aG(t){let e=t[0];e||(console.log(b("Usage: wgl marketplace install <name>")),process.exit(2));try{let n=await tt({profileName:He().activeProfile||"personal"}).downloadSpec(e);n.ok||(n.status===404?console.log(b(`Protocol not found: ${e}`)):console.log(b(`Server returned ${n.status}`)),process.exit(1));let o=n.data,s=be();if(s)try{if((await Q(s).loadProtocol(o)).ok){console.log(z(`Installed and loaded: ${e}`));return}}catch{}let a=`${nG(e).replace(/[/\\]/g,"_")}.acp.json`;rG(a,JSON.stringify(o,null,2)+`
472
- `),console.log(z(`Downloaded: ${a}`)),console.log(y("dim"," No local server \u2014 saved to file. Load with: wgl protocol load "+a))}catch(r){console.log(b(r.message)),process.exit(1)}}async function cG(t){let e=t.indexOf("--name"),r=t.indexOf("--title"),n=t.indexOf("--tags"),o;for(let p=0;p<t.length;p++){if(t[p]==="--name"||t[p]==="--title"||t[p]==="--tags"){p++;continue}o=t[p];break}if(!o){console.log(b("Usage: wgl marketplace publish <file> [--name N] [--title T] [--tags t1,t2]")),process.exit(2);return}let s;try{s=tG(o,"utf8")}catch{console.log(b(`Cannot read file: ${o}`)),process.exit(1);return}let i;try{i=JSON.parse(s)}catch{console.log(b("File must be valid JSON (parse YAML locally first with `wgl protocol validate`)")),process.exit(1);return}let a=i,c=e!==-1?t[e+1]:a.name,l=r!==-1?t[r+1]:a.title||a.name,u=n!==-1?t[n+1].split(","):a.tags||[];if(!c){console.log(b('Protocol name is required (use --name or include "name" in spec)')),process.exit(2);return}try{let m=await tt({profileName:He().activeProfile||"personal"}).publishSpec({name:c,title:l,tags:u,spec_content:i});m.ok||(console.log(b(`Server returned ${m.status}`)),process.exit(1)),console.log(z(`Published: ${m.data.name} (v${m.data.version})`))}catch(p){console.log(b(p.message)),process.exit(1)}}async function lG(){try{let e=await tt({profileName:He().activeProfile||"personal"}).listMySpecs();e.ok||(console.log(b(`Server returned ${e.status}`)),process.exit(1));let{data:r}=e.data;if(r.length===0){console.log(` ${y("dim","No published protocols")}`);return}console.log(C("Your Protocols"));let n=r.map(o=>{let s=y("dim",`\u2193${o.downloads}`);return[o.name,`v${o.version} ${s}`]});console.log(br(n)),console.log()}catch(t){console.log(b(t.message)),process.exit(1)}}var pC=w(()=>{"use strict";Re();pi();dt();ts();Xe()});var hC={};X(hC,{integrations:()=>fG});import{readFileSync as O_,writeFileSync as uG,mkdirSync as pG,existsSync as dC}from"node:fs";import{join as C_}from"node:path";import{homedir as dG}from"node:os";function fC(){return C_(dG(),".config","honeybee")}function mC(){return C_(fC(),"integrations.json")}function nc(){let t=mC();if(!dC(t))return{};try{return JSON.parse(O_(t,"utf8"))}catch{return{}}}function Dp(t){let e=fC();dC(e)||pG(e,{recursive:!0}),uG(mC(),JSON.stringify(t,null,2)+`
473
- `,{mode:384})}async function fG(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
470
+ `);return}switch(e){case"search":{await EV(t.slice(1));break}case"info":{await TV(t.slice(1));break}case"install":{await PV(t.slice(1));break}case"publish":{await RV(t.slice(1));break}case"list":{await OV();break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl marketplace --help` for usage"),process.exit(2)}}async function EV(t){let e=t.indexOf("--tag"),r=e!==-1?t[e+1]:void 0,n=t.indexOf("--sort"),o=n!==-1?t[n+1]:void 0,s=[];for(let a=0;a<t.length;a++){if(t[a]==="--tag"||t[a]==="--sort"){a++;continue}s.push(t[a])}let i=s.join(" ")||void 0;try{let c=await Xe({profileName:je().activeProfile||"personal"}).searchSpecs(i,{tag:r,sort:o});c.ok||(console.log(_(`Server returned ${c.status}`)),process.exit(1));let{data:l,total:u}=c.data;if(l.length===0){console.log(` ${y("dim","No protocols found")}`);return}console.log(C("Marketplace")),console.log(y("dim",` ${u} protocol${u===1?"":"s"} found
471
+ `));let p=l.map(f=>{let d=f.avg_rating>0?` ${y("yellow",`\u2605${f.avg_rating.toFixed(1)}`)}`:"",m=y("dim",`\u2193${f.downloads}`);return[f.name,`${f.title} ${m}${d}`]});console.log(sr(p)),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}}async function TV(t){let e=t[0];e||(console.log(_("Usage: wgl marketplace info <name>")),process.exit(2));try{let n=await Xe({profileName:je().activeProfile||"personal"}).getSpec(e);n.ok||(n.status===404?console.log(_(`Protocol not found: ${e}`)):console.log(_(`Server returned ${n.status}`)),process.exit(1));let o=n.data;if(console.log(C("Protocol")),console.log(S("Name",o.name)),console.log(S("Title",o.title)),console.log(S("Description",o.description)),console.log(S("Author",o.author.username)),console.log(S("Version",String(o.version))),console.log(S("Downloads",String(o.downloads))),o.avg_rating>0&&console.log(S("Rating",`${o.avg_rating.toFixed(1)} (${o.rating_count} ratings)`)),o.tags.length&&console.log(S("Tags",o.tags.join(", "))),o.forked_from&&console.log(S("Forked from",o.forked_from)),console.log(S("Created",o.created_at)),console.log(S("Updated",o.updated_at)),o.spec_content&&typeof o.spec_content=="object"){let s=o.spec_content;if(s.roles?.length){console.log(C("Roles"));for(let i of s.roles)console.log(` ${y("bold",i.name)}${i.description?` \u2014 ${i.description}`:""}`)}if(s.phases?.length){console.log(C("Phases"));for(let i=0;i<s.phases.length;i++){let a=s.phases[i];console.log(` ${y("cyan",`${i+1}.`)} ${y("bold",a.name)}${a.description?` \u2014 ${a.description}`:""}`)}}}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function PV(t){let e=t[0];e||(console.log(_("Usage: wgl marketplace install <name>")),process.exit(2));try{let n=await Xe({profileName:je().activeProfile||"personal"}).downloadSpec(e);n.ok||(n.status===404?console.log(_(`Protocol not found: ${e}`)):console.log(_(`Server returned ${n.status}`)),process.exit(1));let o=n.data,s=be();if(s)try{if((await Q(s).loadProtocol(o)).ok){console.log(N(`Installed and loaded: ${e}`));return}}catch{}let a=`${$V(e).replace(/[/\\]/g,"_")}.acp.json`;SV(a,JSON.stringify(o,null,2)+`
472
+ `),console.log(N(`Downloaded: ${a}`)),console.log(y("dim"," No local server \u2014 saved to file. Load with: wgl protocol load "+a))}catch(r){console.log(_(r.message)),process.exit(1)}}async function RV(t){let e=t.indexOf("--name"),r=t.indexOf("--title"),n=t.indexOf("--tags"),o;for(let p=0;p<t.length;p++){if(t[p]==="--name"||t[p]==="--title"||t[p]==="--tags"){p++;continue}o=t[p];break}if(!o){console.log(_("Usage: wgl marketplace publish <file> [--name N] [--title T] [--tags t1,t2]")),process.exit(2);return}let s;try{s=xV(o,"utf8")}catch{console.log(_(`Cannot read file: ${o}`)),process.exit(1);return}let i;try{i=JSON.parse(s)}catch{console.log(_("File must be valid JSON (parse YAML locally first with `wgl protocol validate`)")),process.exit(1);return}let a=i,c=e!==-1?t[e+1]:a.name,l=r!==-1?t[r+1]:a.title||a.name,u=n!==-1?t[n+1].split(","):a.tags||[];if(!c){console.log(_('Protocol name is required (use --name or include "name" in spec)')),process.exit(2);return}try{let f=await Xe({profileName:je().activeProfile||"personal"}).publishSpec({name:c,title:l,tags:u,spec_content:i});f.ok||(console.log(_(`Server returned ${f.status}`)),process.exit(1)),console.log(N(`Published: ${f.data.name} (v${f.data.version})`))}catch(p){console.log(_(p.message)),process.exit(1)}}async function OV(){try{let e=await Xe({profileName:je().activeProfile||"personal"}).listMySpecs();e.ok||(console.log(_(`Server returned ${e.status}`)),process.exit(1));let{data:r}=e.data;if(r.length===0){console.log(` ${y("dim","No published protocols")}`);return}console.log(C("Your Protocols"));let n=r.map(o=>{let s=y("dim",`\u2193${o.downloads}`);return[o.name,`v${o.version} ${s}`]});console.log(sr(n)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}var bC=w(()=>{"use strict";Re();fi();dt();rs();Qe()});var $C={};K($C,{integrations:()=>NV});import{readFileSync as M_,writeFileSync as CV,mkdirSync as IV,existsSync as wC}from"node:fs";import{join as L_}from"node:path";import{homedir as AV}from"node:os";function xC(){return L_(AV(),".config","honeybee")}function SC(){return L_(xC(),"integrations.json")}function ic(){let t=SC();if(!wC(t))return{};try{return JSON.parse(M_(t,"utf8"))}catch{return{}}}function Fp(t){let e=xC();wC(e)||IV(e,{recursive:!0}),CV(SC(),JSON.stringify(t,null,2)+`
473
+ `,{mode:384})}async function NV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
474
474
  ${y("bold","wgl integrations")} \u2014 integration marketplace
475
475
 
476
476
  ${y("cyan","USAGE:")}
@@ -482,36 +482,48 @@ ${y("cyan","USAGE:")}
482
482
  wgl integrations enable <name> Enable an installed integration
483
483
  wgl integrations disable <name> Disable an integration
484
484
  wgl integrations publish <dir> Publish an integration (auth required)
485
- `);return}switch(e){case"search":{await mG(t.slice(1));break}case"info":{await hG(t.slice(1));break}case"install":{await gG(t.slice(1));break}case"remove":{await yG(t.slice(1));break}case"list":{await vG();break}case"enable":{await _G(t.slice(1));break}case"disable":{await bG(t.slice(1));break}case"publish":{await wG(t.slice(1));break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl integrations --help` for usage"),process.exit(2)}}function qp(){return tt({profileName:He().activeProfile||"personal"})}async function mG(t){let e=t.indexOf("--category"),r=e!==-1?t[e+1]:void 0,n=t.indexOf("--sort"),o=n!==-1?t[n+1]:void 0,s=[];for(let a=0;a<t.length;a++){if(t[a]==="--category"||t[a]==="--sort"){a++;continue}s.push(t[a])}let i=s.join(" ")||void 0;try{let c=await qp().searchIntegrations(i,{category:r,sort:o});c.ok||(console.log(b(`Server returned ${c.status}`)),process.exit(1));let{data:l,total:u}=c.data;if(l.length===0){console.log(` ${y("dim","No integrations found")}`);return}console.log(C("Integrations")),console.log(y("dim",` ${u} integration${u===1?"":"s"} found
486
- `));let p=l.map(m=>{let d=y("cyan",`[${m.category}]`),f=m.avg_rating>0?` ${y("yellow",`\u2605${m.avg_rating.toFixed(1)}`)}`:"",h=y("dim",`\u2193${m.downloads}`);return[m.name,`${m.title} ${d} ${h}${f}`]});console.log(br(p)),console.log()}catch(a){console.log(b(a.message)),process.exit(1)}}async function hG(t){let e=t[0];e||(console.log(b("Usage: wgl integrations info <name>")),process.exit(2));try{let n=await qp().getIntegration(e);n.ok||(n.status===404?console.log(b(`Integration not found: ${e}`)):console.log(b(`Server returned ${n.status}`)),process.exit(1));let o=n.data.data;console.log(C("Integration")),console.log(S("Name",o.name)),console.log(S("Title",o.title)),console.log(S("Description",o.description)),console.log(S("Category",o.category)),console.log(S("Author",o.author.username)),console.log(S("Version",String(o.version))),console.log(S("npm Package",o.npm_package)),console.log(S("Downloads",String(o.downloads))),o.avg_rating>0&&console.log(S("Rating",`${o.avg_rating.toFixed(1)} (${o.rating_count} ratings)`)),o.tags.length&&console.log(S("Tags",o.tags.join(", ")));let s=o.manifest;if(s?.config_keys&&Array.isArray(s.config_keys)){console.log(C("Config Keys"));for(let i of s.config_keys){let a=i,c=a.required?y("red"," (required)"):"";console.log(` ${y("bold",a.key)}${c} \u2014 ${a.description}`)}}console.log(S("Created",o.created_at)),console.log(S("Updated",o.updated_at)),console.log()}catch(r){console.log(b(r.message)),process.exit(1)}}async function gG(t){let e=t[0];e||(console.log(b("Usage: wgl integrations install <name>")),process.exit(2));try{let n=await qp().downloadIntegration(e);n.ok||(n.status===404?console.log(b(`Integration not found: ${e}`)):console.log(b(`Server returned ${n.status}`)),process.exit(1));let s=n.data.npm_package||e;/^(@[a-z0-9-~][a-z0-9._-~]*\/)?[a-z0-9-~][a-z0-9._-~]*(@[^;|&`$\s]+)?$/.test(s)||(console.log(b(`Invalid npm package name: ${s}`)),process.exit(1));let{execFileSync:i}=await import("node:child_process");console.log(y("dim",` Installing ${s}...`)),i("npm",["install","-g",s],{stdio:"inherit"});let a=nc();a[e]={package:s,enabled:!0,config:{}},Dp(a),console.log(z(`Installed and enabled: ${e}`)),console.log(y("dim",` npm package: ${s}`)),console.log(y("dim"," Run incubator with --integrations or --integration="+e+" to activate"))}catch(r){console.log(b(r.message)),process.exit(1)}}async function yG(t){let e=t[0];e||(console.log(b("Usage: wgl integrations remove <name>")),process.exit(2));let r=nc();r[e]||(console.log(b(`Integration not installed: ${e}`)),process.exit(1)),delete r[e],Dp(r),console.log(z(`Removed: ${e}`))}async function vG(){let t=nc(),e=Object.entries(t);if(e.length===0){console.log(` ${y("dim","No integrations installed")}`),console.log(y("dim"," Search marketplace: wgl integrations search"));return}console.log(C("Installed Integrations"));let r=e.map(([n,o])=>{let s=o.enabled?y("green","enabled"):y("dim","disabled");return[n,`${o.package} [${s}]`]});console.log(br(r)),console.log()}async function _G(t){let e=t[0];e||(console.log(b("Usage: wgl integrations enable <name>")),process.exit(2));let r=nc();r[e]||(console.log(b(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!0,Dp(r),console.log(z(`Enabled: ${e}`))}async function bG(t){let e=t[0];e||(console.log(b("Usage: wgl integrations disable <name>")),process.exit(2));let r=nc();r[e]||(console.log(b(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!1,Dp(r),console.log(z(`Disabled: ${e}`))}async function wG(t){let e=t.indexOf("--name"),r=t.indexOf("--title"),n=t.indexOf("--tags"),o;for(let u=0;u<t.length;u++){if(t[u]==="--name"||t[u]==="--title"||t[u]==="--tags"){u++;continue}o=t[u];break}if(!o){console.log(b("Usage: wgl integrations publish <manifest.json|dir> [--name N] [--title T] [--tags t1,t2]")),process.exit(2);return}let s;try{s=O_(o,"utf8")}catch{try{s=O_(C_(o,"manifest.json"),"utf8")}catch{console.log(b(`Cannot read manifest: ${o}`)),process.exit(1);return}}let i;try{i=JSON.parse(s)}catch{console.log(b("Manifest must be valid JSON")),process.exit(1);return}let a=e!==-1?t[e+1]:i.name,c=r!==-1?t[r+1]:i.title||i.name,l=n!==-1?t[n+1].split(","):i.tags||[];if(!a){console.log(b('Integration name is required (use --name or include "name" in manifest)')),process.exit(2);return}if(!i.npm_package){console.log(b('Manifest must include "npm_package" field')),process.exit(2);return}if(!i.category){console.log(b('Manifest must include "category" field (bridge, notification, backend, tool)')),process.exit(2);return}try{let p=await qp().publishIntegration({name:a,title:c,description:i.description||"",tags:l,npm_package:i.npm_package,category:i.category,manifest:i});p.ok||(console.log(b(`Server returned ${p.status}`)),process.exit(1)),console.log(z(`Published: ${p.data.data.name} (v${p.data.data.version})`))}catch(u){console.log(b(u.message)),process.exit(1)}}var gC=w(()=>{"use strict";Re();pi();ts()});var yC={};X(yC,{swarm:()=>SG});import{readFileSync as xG}from"node:fs";async function SG(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
487
- ${y("bold","wgl swarm")} \u2014 managed swarm coordination (Colony)
485
+ `);return}switch(e){case"search":{await zV(t.slice(1));break}case"info":{await jV(t.slice(1));break}case"install":{await MV(t.slice(1));break}case"remove":{await LV(t.slice(1));break}case"list":{await DV();break}case"enable":{await qV(t.slice(1));break}case"disable":{await ZV(t.slice(1));break}case"publish":{await UV(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl integrations --help` for usage"),process.exit(2)}}function Hp(){return Xe({profileName:je().activeProfile||"personal"})}async function zV(t){let e=t.indexOf("--category"),r=e!==-1?t[e+1]:void 0,n=t.indexOf("--sort"),o=n!==-1?t[n+1]:void 0,s=[];for(let a=0;a<t.length;a++){if(t[a]==="--category"||t[a]==="--sort"){a++;continue}s.push(t[a])}let i=s.join(" ")||void 0;try{let c=await Hp().searchIntegrations(i,{category:r,sort:o});c.ok||(console.log(_(`Server returned ${c.status}`)),process.exit(1));let{data:l,total:u}=c.data;if(l.length===0){console.log(` ${y("dim","No integrations found")}`);return}console.log(C("Integrations")),console.log(y("dim",` ${u} integration${u===1?"":"s"} found
486
+ `));let p=l.map(f=>{let d=y("cyan",`[${f.category}]`),m=f.avg_rating>0?` ${y("yellow",`\u2605${f.avg_rating.toFixed(1)}`)}`:"",h=y("dim",`\u2193${f.downloads}`);return[f.name,`${f.title} ${d} ${h}${m}`]});console.log(sr(p)),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}}async function jV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations info <name>")),process.exit(2));try{let n=await Hp().getIntegration(e);n.ok||(n.status===404?console.log(_(`Integration not found: ${e}`)):console.log(_(`Server returned ${n.status}`)),process.exit(1));let o=n.data.data;console.log(C("Integration")),console.log(S("Name",o.name)),console.log(S("Title",o.title)),console.log(S("Description",o.description)),console.log(S("Category",o.category)),console.log(S("Author",o.author.username)),console.log(S("Version",String(o.version))),console.log(S("npm Package",o.npm_package)),console.log(S("Downloads",String(o.downloads))),o.avg_rating>0&&console.log(S("Rating",`${o.avg_rating.toFixed(1)} (${o.rating_count} ratings)`)),o.tags.length&&console.log(S("Tags",o.tags.join(", ")));let s=o.manifest;if(s?.config_keys&&Array.isArray(s.config_keys)){console.log(C("Config Keys"));for(let i of s.config_keys){let a=i,c=a.required?y("red"," (required)"):"";console.log(` ${y("bold",a.key)}${c} \u2014 ${a.description}`)}}console.log(S("Created",o.created_at)),console.log(S("Updated",o.updated_at)),console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function MV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations install <name>")),process.exit(2));try{let n=await Hp().downloadIntegration(e);n.ok||(n.status===404?console.log(_(`Integration not found: ${e}`)):console.log(_(`Server returned ${n.status}`)),process.exit(1));let s=n.data.npm_package||e;/^(@[a-z0-9-~][a-z0-9._-~]*\/)?[a-z0-9-~][a-z0-9._-~]*(@[^;|&`$\s]+)?$/.test(s)||(console.log(_(`Invalid npm package name: ${s}`)),process.exit(1));let{execFileSync:i}=await import("node:child_process");console.log(y("dim",` Installing ${s}...`)),i("npm",["install","-g",s],{stdio:"inherit"});let a=ic();a[e]={package:s,enabled:!0,config:{}},Fp(a),console.log(N(`Installed and enabled: ${e}`)),console.log(y("dim",` npm package: ${s}`)),console.log(y("dim"," Run incubator with --integrations or --integration="+e+" to activate"))}catch(r){console.log(_(r.message)),process.exit(1)}}async function LV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations remove <name>")),process.exit(2));let r=ic();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),delete r[e],Fp(r),console.log(N(`Removed: ${e}`))}async function DV(){let t=ic(),e=Object.entries(t);if(e.length===0){console.log(` ${y("dim","No integrations installed")}`),console.log(y("dim"," Search marketplace: wgl integrations search"));return}console.log(C("Installed Integrations"));let r=e.map(([n,o])=>{let s=o.enabled?y("green","enabled"):y("dim","disabled");return[n,`${o.package} [${s}]`]});console.log(sr(r)),console.log()}async function qV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations enable <name>")),process.exit(2));let r=ic();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!0,Fp(r),console.log(N(`Enabled: ${e}`))}async function ZV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations disable <name>")),process.exit(2));let r=ic();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!1,Fp(r),console.log(N(`Disabled: ${e}`))}async function UV(t){let e=t.indexOf("--name"),r=t.indexOf("--title"),n=t.indexOf("--tags"),o;for(let u=0;u<t.length;u++){if(t[u]==="--name"||t[u]==="--title"||t[u]==="--tags"){u++;continue}o=t[u];break}if(!o){console.log(_("Usage: wgl integrations publish <manifest.json|dir> [--name N] [--title T] [--tags t1,t2]")),process.exit(2);return}let s;try{s=M_(o,"utf8")}catch{try{s=M_(L_(o,"manifest.json"),"utf8")}catch{console.log(_(`Cannot read manifest: ${o}`)),process.exit(1);return}}let i;try{i=JSON.parse(s)}catch{console.log(_("Manifest must be valid JSON")),process.exit(1);return}let a=e!==-1?t[e+1]:i.name,c=r!==-1?t[r+1]:i.title||i.name,l=n!==-1?t[n+1].split(","):i.tags||[];if(!a){console.log(_('Integration name is required (use --name or include "name" in manifest)')),process.exit(2);return}if(!i.npm_package){console.log(_('Manifest must include "npm_package" field')),process.exit(2);return}if(!i.category){console.log(_('Manifest must include "category" field (bridge, notification, backend, tool)')),process.exit(2);return}try{let p=await Hp().publishIntegration({name:a,title:c,description:i.description||"",tags:l,npm_package:i.npm_package,category:i.category,manifest:i});p.ok||(console.log(_(`Server returned ${p.status}`)),process.exit(1)),console.log(N(`Published: ${p.data.data.name} (v${p.data.data.version})`))}catch(u){console.log(_(u.message)),process.exit(1)}}var kC=w(()=>{"use strict";Re();fi();rs()});var TC={};K(TC,{hive:()=>BV});import{readFileSync as D_,existsSync as FV}from"node:fs";import{resolve as EC,dirname as HV}from"node:path";async function BV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
487
+ ${y("bold","wgl hive")} \u2014 managed hive coordination (Colony)
488
488
 
489
489
  ${y("cyan","USAGE:")}
490
- wgl swarm create <name> [--description D] [--max-agents N] [--protocol F]
491
- wgl swarm list List your swarms
492
- wgl swarm info <id> Show swarm details
493
- wgl swarm delete <id> Delete a swarm
494
- wgl swarm pause <id> Pause a swarm
495
- wgl swarm resume <id> Resume a swarm
496
- wgl swarm keys create <swarm-id> --name N [--permissions all|read|write]
497
- wgl swarm keys list List API keys
498
- wgl swarm keys revoke <id> Revoke an API key
499
- wgl swarm logs <id> Tail swarm events
500
- `);return}if(e==="keys"){await CG(t.slice(1));return}switch(e){case"create":{await $G(t.slice(1));break}case"list":{await kG();break}case"info":{await EG(t.slice(1));break}case"delete":{await TG(t.slice(1));break}case"pause":{await PG(t.slice(1));break}case"resume":{await RG(t.slice(1));break}case"logs":{await OG(t.slice(1));break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl swarm --help` for usage"),process.exit(2)}}async function $G(t){let e=t.find(i=>!i.startsWith("--"));if(!e){console.log(b("Usage: wgl swarm create <name> [options]")),process.exit(2);return}let r=t.indexOf("--description"),n=t.indexOf("--max-agents"),o=t.indexOf("--protocol"),s={name:e};if(r!==-1&&t[r+1]&&(s.description=t[r+1]),n!==-1){let i=parseInt(t[n+1],10);if(isNaN(i)||i<1){console.log(b("--max-agents must be a positive integer")),process.exit(2);return}s.max_agents=i}if(o!==-1){let i=t[o+1];try{let a=xG(i,"utf8"),c=JSON.parse(a);s.protocol_name=c.name||i,s.protocol_content=a}catch{console.log(b(`Cannot read protocol file: ${i}`)),process.exit(1);return}}try{let a=await tt({profileName:He().activeProfile||"personal"}).createSwarm(s);a.ok||(console.log(b(`Server returned ${a.status}`)),process.exit(1));let c=a.data;console.log(z(`Created swarm: ${c.name}`)),console.log(S("ID",c.id)),console.log(S("Max Agents",String(c.max_agents))),console.log(S("Status",c.status)),c.protocol_name&&console.log(S("Protocol",c.protocol_name)),console.log()}catch(i){console.log(b(i.message)),process.exit(1)}}async function kG(){try{let e=await tt({profileName:He().activeProfile||"personal"}).listSwarms();e.ok||(console.log(b(`Server returned ${e.status}`)),process.exit(1));let{swarms:r}=e.data;if(r.length===0){console.log(` ${y("dim","No swarms")}`);return}console.log(C("Swarms"));let n=r.map(o=>{let s=o.status==="active"?y("green",o.status):o.status==="paused"?y("yellow",o.status):y("dim",o.status);return[o.id.slice(0,8),`${y("bold",o.name)} ${s} (max: ${o.max_agents})`]});console.log(br(n)),console.log()}catch(t){console.log(b(t.message)),process.exit(1)}}async function EG(t){let e=t[0];if(!e){console.log(b("Usage: wgl swarm info <id>")),process.exit(2);return}try{let n=await tt({profileName:He().activeProfile||"personal"}).getSwarm(e);n.ok||(n.status===404?console.log(b(`Swarm not found: ${e}`)):console.log(b(`Server returned ${n.status}`)),process.exit(1));let o=n.data;console.log(C("Swarm")),console.log(S("ID",o.id)),console.log(S("Name",o.name)),console.log(S("Status",o.status)),console.log(S("Max Agents",String(o.max_agents))),o.description&&console.log(S("Description",o.description)),o.protocol_name&&console.log(S("Protocol",o.protocol_name)),console.log(S("Carapace",o.carapace_enabled?y("green","enabled"):y("dim","disabled"))),console.log(S("Scan",o.scan_enabled?`${y("green","enabled")} (threshold: ${o.scan_threshold})`:y("dim","disabled"))),console.log(S("Created",o.created_at)),console.log(S("Updated",o.updated_at)),console.log()}catch(r){console.log(b(r.message)),process.exit(1)}}async function TG(t){let e=t[0];if(!e){console.log(b("Usage: wgl swarm delete <id>")),process.exit(2);return}if(!t.includes("--yes")&&!t.includes("-y")){console.log(gn(`This will permanently delete swarm ${e}`)),console.log(y("dim"," Pass --yes to confirm")),process.exit(1);return}try{let n=await tt({profileName:He().activeProfile||"personal"}).deleteSwarm(e);n.ok||(console.log(b(`Server returned ${n.status}`)),process.exit(1)),console.log(z(`Deleted swarm: ${e}`))}catch(r){console.log(b(r.message)),process.exit(1)}}async function PG(t){let e=t[0];if(!e){console.log(b("Usage: wgl swarm pause <id>")),process.exit(2);return}try{let n=await tt({profileName:He().activeProfile||"personal"}).pauseSwarm(e);n.ok||(console.log(b(`Server returned ${n.status}`)),process.exit(1)),console.log(z(`Paused swarm: ${e}`))}catch(r){console.log(b(r.message)),process.exit(1)}}async function RG(t){let e=t[0];if(!e){console.log(b("Usage: wgl swarm resume <id>")),process.exit(2);return}try{let n=await tt({profileName:He().activeProfile||"personal"}).resumeSwarm(e);n.ok||(console.log(b(`Server returned ${n.status}`)),process.exit(1)),console.log(z(`Resumed swarm: ${e}`))}catch(r){console.log(b(r.message)),process.exit(1)}}async function OG(t){let e=t[0];if(!e){console.log(b("Usage: wgl swarm logs <id>")),process.exit(2);return}console.log(y("dim",`Tailing swarm ${e} events... Ctrl+C to stop
501
- `));let r=0,n=async()=>{try{let i=await tt({profileName:He().activeProfile||"personal"}).getSwarmEvents(e,r||void 0);if(i.ok&&Array.isArray(i.data))for(let a of i.data){let c=new Date(a.publishedAt||a.created_at).toLocaleTimeString();console.log(` ${y("dim",`#${a.id}`)} ${y("bold",a.type)} by ${a.publishedBy||a.agent_id} ${y("dim",c)}`),a.id>r&&(r=a.id)}}catch{}};await n();let o=setInterval(n,2e3);process.on("SIGINT",()=>{clearInterval(o),console.log(y("dim",`
502
- Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{})}async function CG(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
503
- ${y("bold","wgl swarm keys")} \u2014 API key management
490
+ wgl hive create <name> [--description D] [--max-agents N] [--protocol F] [--brood F]
491
+ wgl hive list List your hives
492
+ wgl hive info <id> Show hive details + live agents
493
+ wgl hive start <id> Start agent execution
494
+ wgl hive delete <id> Delete a hive
495
+ wgl hive pause <id> Pause a hive
496
+ wgl hive resume <id> Resume a hive
497
+ wgl hive config set-key <id> <provider> Set provider API key (reads from stdin)
498
+ wgl hive keys create <hive-id> --name N [--permissions all|read|write]
499
+ wgl hive keys list List API keys
500
+ wgl hive keys revoke <id> Revoke an API key
501
+ wgl hive logs <id> Tail hive events
502
+ `);return}if(e==="keys"){await o3(t.slice(1));return}if(e==="config"){await QV(t.slice(1));return}switch(e){case"create":{await GV(t.slice(1));break}case"list":{await VV();break}case"info":{await WV(t.slice(1));break}case"start":{await XV(t.slice(1));break}case"delete":{await JV(t.slice(1));break}case"pause":{await KV(t.slice(1));break}case"resume":{await YV(t.slice(1));break}case"logs":{await n3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl hive --help` for usage"),process.exit(2)}}async function GV(t){let e=t.indexOf("--description"),r=t.indexOf("--max-agents"),n=t.indexOf("--protocol"),o=t.indexOf("--brood"),s=new Set;for(let c of[e,r,n,o])c!==-1&&(s.add(c),s.add(c+1));let i=t.find((c,l)=>!c.startsWith("--")&&!s.has(l)),a={};if(e!==-1&&t[e+1]&&(a.description=t[e+1]),r!==-1){let c=parseInt(t[r+1],10);if(isNaN(c)||c<1){console.log(_("--max-agents must be a positive integer")),process.exit(2);return}a.max_agents=c}if(n!==-1){let c=t[n+1];try{let l=D_(c,"utf8"),u=JSON.parse(l);a.protocol_name=u.name||c,a.protocol_content=l}catch{console.log(_(`Cannot read protocol file: ${c}`)),process.exit(1);return}}if(o!==-1){let c=t[o+1];if(!c){console.log(_("--brood requires a file path")),process.exit(2);return}let l;try{l=D_(c,"utf8")}catch{console.log(_(`Cannot read brood file: ${c}`)),process.exit(1);return}let u=r3(l);if(a.brood_config=l,!i&&u.name&&(a.name=u.name),u.provider&&(a.provider=u.provider),u.agents&&u.agents.length>0&&(a.agents=u.agents,!a.max_agents)){let p=u.agents.reduce((f,d)=>f+(d.count||1),0);a.max_agents=Math.max(p,1)}if(u.env&&Object.keys(u.env).length>0&&(a.env=u.env),u.acpFile&&!a.protocol_content){let p=HV(EC(c)),f=EC(p,u.acpFile);if(FV(f))try{let d=D_(f,"utf8");a.protocol_content=d;let m=d.match(/^name:\s*(.+)$/m);m&&(a.protocol_name=m[1].trim().replace(/^["']|["']$/g,""))}catch{}}}if(a.name)i&&(a.name=i);else if(i)a.name=i;else{console.log(_("Usage: wgl hive create <name> [options]")),console.log(y("dim"," Or use --brood <file> with a name: field in the brood YAML")),process.exit(2);return}try{let l=await Xe({profileName:je().activeProfile||"personal"}).createHive(a);l.ok||(console.log(_(`Server returned ${l.status}`)),process.exit(1));let u=l.data;console.log(N(`Created hive: ${u.name}`)),console.log(S("ID",u.id)),console.log(S("Max Agents",String(u.max_agents))),console.log(S("Status",u.status)),u.protocol_name&&console.log(S("Protocol",u.protocol_name)),a.agents&&console.log(S("Agents",`${a.agents.length} spec(s)`)),a.provider&&console.log(S("Provider",a.provider)),console.log()}catch(c){console.log(_(c.message)),process.exit(1)}}async function VV(){try{let e=await Xe({profileName:je().activeProfile||"personal"}).listHives();e.ok||(console.log(_(`Server returned ${e.status}`)),process.exit(1));let{hives:r}=e.data;if(r.length===0){console.log(` ${y("dim","No hives")}`);return}console.log(C("Hives"));let n=r.map(o=>{let s=o.status==="active"?y("green",o.status):o.status==="paused"?y("yellow",o.status):y("dim",o.status);return[o.id.slice(0,8),`${y("bold",o.name)} ${s} (max: ${o.max_agents})`]});console.log(sr(n)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}async function WV(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive info <id>")),process.exit(2);return}try{let r=Xe({profileName:je().activeProfile||"personal"}),n=await r.getHive(e);n.ok||(n.status===404?console.log(_(`Hive not found: ${e}`)):console.log(_(`Server returned ${n.status}`)),process.exit(1));let o=n.data;console.log(C("Hive")),console.log(S("ID",o.id)),console.log(S("Name",o.name)),console.log(S("Status",o.status)),console.log(S("Max Agents",String(o.max_agents))),o.description&&console.log(S("Description",o.description)),o.protocol_name&&console.log(S("Protocol",o.protocol_name)),console.log(S("Carapace",o.carapace_enabled?y("green","enabled"):y("dim","disabled"))),console.log(S("Scan",o.scan_enabled?`${y("green","enabled")} (threshold: ${o.scan_threshold})`:y("dim","disabled"))),console.log(S("Created",o.created_at)),console.log(S("Updated",o.updated_at));try{let s=await r.getHiveAgents(e);if(s.ok&&s.data?.agents?.length>0){let i=s.data.agents;console.log(C("Agents"));for(let a of i){let c=a.status==="running"?"green":a.status==="sleeping"?"yellow":a.status==="error"?"red":a.status==="stopped"?"dim":"cyan",l=(a.totalTokens?.prompt||0)+(a.totalTokens?.completion||0),u=typeof a.totalCost=="number"?`$${a.totalCost.toFixed(2)}`:"$0.00";console.log(` ${y("bold",a.agentId)} ${y("dim",a.role)} ${y(c,a.status)} iter:${a.iteration} tokens:${t3(l)} ${u}`),a.error&&console.log(` ${y("red",a.error)}`)}}}catch{}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function JV(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive delete <id>")),process.exit(2);return}if(!t.includes("--yes")&&!t.includes("-y")){console.log(gn(`This will permanently delete hive ${e}`)),console.log(y("dim"," Pass --yes to confirm")),process.exit(1);return}try{let n=await Xe({profileName:je().activeProfile||"personal"}).deleteHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(N(`Deleted hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function KV(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive pause <id>")),process.exit(2);return}try{let n=await Xe({profileName:je().activeProfile||"personal"}).pauseHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(N(`Paused hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function YV(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive resume <id>")),process.exit(2);return}try{let n=await Xe({profileName:je().activeProfile||"personal"}).resumeHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(N(`Resumed hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function XV(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive start <id>")),process.exit(2);return}try{let n=await Xe({profileName:je().activeProfile||"personal"}).startHive(e);n.ok||(n.status===404?console.log(_(`Hive not found: ${e}`)):console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(N(`Started hive: ${e}`)),console.log(y("dim"," Agents will begin executing on the next alarm cycle."))}catch(r){console.log(_(r.message)),process.exit(1)}}async function QV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
503
+ ${y("bold","wgl hive config")} \u2014 hive configuration
504
504
 
505
505
  ${y("cyan","USAGE:")}
506
- wgl swarm keys create <swarm-id> --name N [--permissions all|read|write]
507
- wgl swarm keys list
508
- wgl swarm keys revoke <id>
509
- `);return}switch(e){case"create":{let r=t[1],n=t.indexOf("--name"),o=t.indexOf("--permissions");if(!r||n===-1){console.log(b("Usage: wgl swarm keys create <swarm-id> --name N")),process.exit(2);return}let s=t[n+1],i=o!==-1?t[o+1]:"all";try{let c=await tt({profileName:He().activeProfile||"personal"}).createKey({swarm_id:r,name:s,permissions:i});c.ok||(console.log(b(`Server returned ${c.status}`)),process.exit(1));let l=c.data;console.log(z(`Created API key: ${l.name}`)),console.log(S("ID",l.id)),console.log(S("Permissions",l.permissions)),console.log(),console.log(` ${y("yellow","KEY:")} ${y("bold",l.key)}`),console.log(` ${gn("Save this key \u2014 it will not be shown again")}`),console.log()}catch(a){console.log(b(a.message)),process.exit(1)}break}case"list":{try{let n=await tt({profileName:He().activeProfile||"personal"}).listKeys();n.ok||(console.log(b(`Server returned ${n.status}`)),process.exit(1));let{keys:o}=n.data;if(o.length===0){console.log(` ${y("dim","No API keys")}`);return}console.log(C("API Keys"));let s=o.map(i=>[i.id.slice(0,8),`${y("bold",i.name)} (${i.swarm_name}) ${y("dim",i.permissions)}`]);console.log(br(s)),console.log()}catch(r){console.log(b(r.message)),process.exit(1)}break}case"revoke":{let r=t[1];if(!r){console.log(b("Usage: wgl swarm keys revoke <id>")),process.exit(2);return}try{let o=await tt({profileName:He().activeProfile||"personal"}).revokeKey(r);o.ok||(console.log(b(`Server returned ${o.status}`)),process.exit(1)),console.log(z(`Revoked key: ${r}`))}catch(n){console.log(b(n.message)),process.exit(1)}break}default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl swarm keys --help` for usage"),process.exit(2)}}var vC=w(()=>{"use strict";Re();pi();ts()});var _C={};X(_C,{runCarapace:()=>zG});import{createRequire as IG}from"node:module";import{dirname as AG,join as NG}from"node:path";async function zG(t){let e=IG(import.meta.url),r=e.resolve("@honeybee-ai/carapace"),n=AG(r),o=NG(n,"cli.js"),s=process.argv;process.argv=["node","carapace",...t];try{e(o)}finally{process.argv=s}}var bC=w(()=>{"use strict"});var wC={};X(wC,{handleSessionStart:()=>MG});import{appendFileSync as jG}from"node:fs";async function MG(t,e,r){let n=process.env.CLAUDE_ENV_FILE;if(n){let i=a=>a.replace(/["\\`$!]/g,"\\$&");jG(n,[`export WGL_SERVER="${i(t.server)}"`,`export WGL_AGENT_ID="${i(t.agentId)}"`,`export WGL_NAMESPACE="${i(t.namespace)}"`,`export WGL_ROLE="${i(t.role)}"`,`export WGL_CONFIG="${i(e)}"`].join(`
506
+ wgl hive config set-key <hive-id> <provider> Set provider API key (reads from stdin)
507
+
508
+ ${y("cyan","EXAMPLES:")}
509
+ echo "sk-..." | wgl hive config set-key abc123 openai
510
+ cat ~/.secrets/cerebras.key | wgl hive config set-key abc123 cerebras
511
+ `);return}if(e==="set-key"){let r=t[1],n=t[2];if(!r||!n){console.log(_("Usage: wgl hive config set-key <hive-id> <provider>")),console.log(y("dim",' Pipe the key via stdin: echo "sk-..." | wgl hive config set-key <id> <provider>')),process.exit(2);return}if(!/^[a-zA-Z0-9-]+$/.test(n)){console.log(_("Invalid provider name (use alphanumeric + hyphens)")),process.exit(2);return}let o=await e3();if(!o.trim()){console.log(_("No key provided on stdin.")),console.log(y("dim",' Usage: echo "sk-..." | wgl hive config set-key <id> <provider>')),process.exit(1);return}try{let i=await Xe({profileName:je().activeProfile||"personal"}).setProviderKey(r,n,o.trim());i.ok||(i.status===404?console.log(_(`Hive not found: ${r}`)):console.log(_(`Server returned ${i.status}`)),process.exit(1)),console.log(N(`Set ${n} key for hive ${r}`))}catch(s){console.log(_(s.message)),process.exit(1)}return}console.log(_(`Unknown config subcommand: ${e}`)),console.log("Run `wgl hive config --help` for usage"),process.exit(2)}async function e3(){if(process.stdin.isTTY)return"";let t=[];for await(let e of process.stdin)t.push(Buffer.from(e));return Buffer.concat(t).toString("utf8")}function t3(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function r3(t){let e={agents:[],env:{}},r=t.split(`
512
+ `);try{let p=JSON.parse(t);if(typeof p=="object"&&p!==null){if(e.name=p.name,e.provider=p.provider,p.env&&(e.env=p.env),p.hives){let f=Object.values(p.hives)[0];f&&(e.acpFile=f.acp||f.spec||f.protocol,(f.agents||f.workers)&&(e.agents=f.agents||f.workers))}return e}}catch{}for(let p of r){let f=p.match(/^name:\s*(.+)$/);f&&(e.name=f[1].trim().replace(/^["']|["']$/g,""));let d=p.match(/^provider:\s*(.+)$/);d&&(e.provider=d[1].trim().replace(/^["']|["']$/g,""))}let n=!1,o=!1,s="",i=!1,a=!1,c=null,l=!1,u=[];for(let p=0;p<r.length;p++){let f=r[p],d=f.trimEnd(),m=f.length-f.trimStart().length;if(/^env:\s*$/.test(d)||/^env:$/.test(d)){a=!0,n=!1,i=!1;continue}if(/^hives:\s*$/.test(d)||/^hives:$/.test(d)){n=!0,a=!1;continue}if(!(m===0&&d.includes(":")&&!d.startsWith("#")&&!d.startsWith("hives")&&!d.startsWith("env")&&(a=!1,!n))){if(a&&m===2){let h=d.trim().match(/^([A-Za-z_][A-Za-z0-9_]*):\s*(.+)$/);h&&(e.env[h[1]]=h[2].trim().replace(/^["']|["']$/g,""));continue}if(n&&m===2&&d.trim().endsWith(":")&&!d.trim().startsWith("-")){if(!s)s=d.trim().replace(/:$/,""),o=!0;else break;continue}if(o&&m>=4){let h=d.trim(),g=h.match(/^(?:acp|spec|protocol):\s*(.+)$/);if(g&&!i){let v=g[1].trim().replace(/^["']|["']$/g,"");(v.includes(".")||v.includes("/"))&&(e.acpFile=v);continue}if(/^(?:agents|workers):\s*$/.test(h)){i=!0;continue}if(m===4&&!h.startsWith("-")&&h.includes(":")&&!l){i=!1;continue}if(i){if(h.startsWith("- role:")){c&&(u.length>0&&(c.wake_on||(c.wake_on={}),c.wake_on.types=u,u=[]),e.agents.push(c)),c={},l=!1;let v=h.match(/^- role:\s*(.+)$/);v&&(c.role=v[1].trim().replace(/^["']|["']$/g,""));continue}if(c&&!h.startsWith("-")){let v=h.match(/^type:\s*(.+)$/);if(v){c.type=v[1].trim().replace(/^["']|["']$/g,"");continue}let b=h.match(/^count:\s*(\d+)$/);if(b){c.count=parseInt(b[1],10);continue}let x=h.match(/^provider:\s*(.+)$/);if(x){c.provider=x[1].trim().replace(/^["']|["']$/g,"");continue}if(/^wake_on:/.test(h)){l=!0;let $=h.match(/wake_on:\s*\{(.+)\}/);if($){let O=$[1].match(/types:\s*\[([^\]]*)\]/);O&&(u=O[1].split(",").map(ce=>ce.trim().replace(/^["']|["']$/g,"")).filter(Boolean)),l=!1}continue}if(l){let $=h.match(/^types:\s*\[([^\]]*)\]$/);if($){u=$[1].split(",").map(O=>O.trim().replace(/^["']|["']$/g,"")).filter(Boolean),l=!1;continue}if(h.startsWith("- ")){u.push(h.slice(2).trim().replace(/^["']|["']$/g,""));continue}}}}}o&&m<2&&d.length>0&&!d.startsWith("#")&&(o=!1)}}return c&&(u.length>0&&(c.wake_on||(c.wake_on={}),c.wake_on.types=u),e.agents.push(c)),e}async function n3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive logs <id>")),process.exit(2);return}console.log(y("dim",`Tailing hive ${e} events... Ctrl+C to stop
513
+ `));let r=0,n=async()=>{try{let i=await Xe({profileName:je().activeProfile||"personal"}).getHiveEvents(e,r||void 0);if(i.ok&&Array.isArray(i.data))for(let a of i.data){let c=new Date(a.publishedAt||a.created_at).toLocaleTimeString();console.log(` ${y("dim",`#${a.id}`)} ${y("bold",a.type)} by ${a.publishedBy||a.agent_id} ${y("dim",c)}`),a.id>r&&(r=a.id)}}catch{}};await n();let o=setInterval(n,2e3);process.on("SIGINT",()=>{clearInterval(o),console.log(y("dim",`
514
+ Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{})}async function o3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
515
+ ${y("bold","wgl hive keys")} \u2014 API key management
516
+
517
+ ${y("cyan","USAGE:")}
518
+ wgl hive keys create <hive-id> --name N [--permissions all|read|write]
519
+ wgl hive keys list
520
+ wgl hive keys revoke <id>
521
+ `);return}switch(e){case"create":{let r=t[1],n=t.indexOf("--name"),o=t.indexOf("--permissions");if(!r||n===-1){console.log(_("Usage: wgl hive keys create <hive-id> --name N")),process.exit(2);return}let s=t[n+1],i=o!==-1?t[o+1]:"all";try{let c=await Xe({profileName:je().activeProfile||"personal"}).createKey({hive_id:r,name:s,permissions:i});c.ok||(console.log(_(`Server returned ${c.status}`)),process.exit(1));let l=c.data;console.log(N(`Created API key: ${l.name}`)),console.log(S("ID",l.id)),console.log(S("Permissions",l.permissions)),console.log(),console.log(` ${y("yellow","KEY:")} ${y("bold",l.key)}`),console.log(` ${gn("Save this key \u2014 it will not be shown again")}`),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}break}case"list":{try{let n=await Xe({profileName:je().activeProfile||"personal"}).listKeys();n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1));let{keys:o}=n.data;if(o.length===0){console.log(` ${y("dim","No API keys")}`);return}console.log(C("API Keys"));let s=o.map(i=>[i.id.slice(0,8),`${y("bold",i.name)} (${i.hive_name}) ${y("dim",i.permissions)}`]);console.log(sr(s)),console.log()}catch(r){console.log(_(r.message)),process.exit(1)}break}case"revoke":{let r=t[1];if(!r){console.log(_("Usage: wgl hive keys revoke <id>")),process.exit(2);return}try{let o=await Xe({profileName:je().activeProfile||"personal"}).revokeKey(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1)),console.log(N(`Revoked key: ${r}`))}catch(n){console.log(_(n.message)),process.exit(1)}break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl hive keys --help` for usage"),process.exit(2)}}var PC=w(()=>{"use strict";Re();fi();rs()});var RC={};K(RC,{runCarapace:()=>c3});import{createRequire as s3}from"node:module";import{dirname as i3,join as a3}from"node:path";async function c3(t){let e=s3(import.meta.url),r=e.resolve("@honeybee-ai/carapace"),n=i3(r),o=a3(n,"cli.js"),s=process.argv;process.argv=["node","carapace",...t];try{e(o)}finally{process.argv=s}}var OC=w(()=>{"use strict"});var CC={};K(CC,{handleSessionStart:()=>u3});import{appendFileSync as l3}from"node:fs";async function u3(t,e,r){let n=process.env.CLAUDE_ENV_FILE;if(n){let i=a=>a.replace(/["\\`$!]/g,"\\$&");l3(n,[`export WGL_SERVER="${i(t.server)}"`,`export WGL_AGENT_ID="${i(t.agentId)}"`,`export WGL_NAMESPACE="${i(t.namespace)}"`,`export WGL_ROLE="${i(t.role)}"`,`export WGL_CONFIG="${i(e)}"`].join(`
510
522
  `)+`
511
- `)}let o=Q(t),s=[];try{let[i,a,c,l,u]=await Promise.all([o.getControlStatus().catch(()=>null),o.getProtocol().catch(()=>null),o.getRoles().catch(()=>null),o.getClaims().catch(()=>null),o.getMessages().catch(()=>null)]);if(i?.ok){let p=i.data;p.halted?s.push(`COORDINATION HALTED${p.reason?`: ${p.reason}`:""}. Do not proceed with any coordinated work.`):p.paused&&s.push(`Coordination paused${p.reason?`: ${p.reason}`:""}. Proceed cautiously.`)}try{await o.requestRole(t.role)}catch{}if(a?.ok){let p=a.data;p.name&&(s.push(`Protocol: ${p.name}${p.description?` \u2014 ${p.description}`:""}`),p.phases?.length&&s.push(`Phases: ${p.phases.map(m=>m.name).join(" \u2192 ")}`),p.rules?.length&&s.push(`Rules:
512
- ${p.rules.map(m=>` - ${m}`).join(`
513
- `)}`))}if(c?.ok&&Array.isArray(c.data)){let p=c.data;p.length>0&&s.push(`Team: ${p.map(m=>`${m.agent} (${m.role})`).join(", ")}`)}if(l?.ok&&Array.isArray(l.data)){let p=l.data.filter(m=>m.status==="active");if(p.length>0){let m=p.filter(f=>f.owner===t.agentId),d=p.filter(f=>f.owner!==t.agentId);m.length>0&&s.push(`Your claims: ${m.map(f=>f.resource).join(", ")}`),d.length>0&&s.push(`Locked by others: ${d.map(f=>`${f.resource} (${f.owner})`).join(", ")}`)}}if(u?.ok&&Array.isArray(u.data)){let p=u.data.filter(m=>m.to===t.agentId||m.to==="*");p.length>0&&s.push(`Messages:
514
- ${p.map(m=>` [${m.from}]: ${m.content}`).join(`
523
+ `)}let o=Q(t),s=[];try{let[i,a,c,l,u]=await Promise.all([o.getControlStatus().catch(()=>null),o.getProtocol().catch(()=>null),o.getRoles().catch(()=>null),o.getClaims().catch(()=>null),o.getMessages().catch(()=>null)]);if(i?.ok){let p=i.data;p.halted?s.push(`COORDINATION HALTED${p.reason?`: ${p.reason}`:""}. Do not proceed with any coordinated work.`):p.paused&&s.push(`Coordination paused${p.reason?`: ${p.reason}`:""}. Proceed cautiously.`)}try{await o.requestRole(t.role)}catch{}if(a?.ok){let p=a.data;p.name&&(s.push(`Protocol: ${p.name}${p.description?` \u2014 ${p.description}`:""}`),p.phases?.length&&s.push(`Phases: ${p.phases.map(f=>f.name).join(" \u2192 ")}`),p.rules?.length&&s.push(`Rules:
524
+ ${p.rules.map(f=>` - ${f}`).join(`
525
+ `)}`))}if(c?.ok&&Array.isArray(c.data)){let p=c.data;p.length>0&&s.push(`Team: ${p.map(f=>`${f.agent} (${f.role})`).join(", ")}`)}if(l?.ok&&Array.isArray(l.data)){let p=l.data.filter(f=>f.status==="active");if(p.length>0){let f=p.filter(m=>m.owner===t.agentId),d=p.filter(m=>m.owner!==t.agentId);f.length>0&&s.push(`Your claims: ${f.map(m=>m.resource).join(", ")}`),d.length>0&&s.push(`Locked by others: ${d.map(m=>`${m.resource} (${m.owner})`).join(", ")}`)}}if(u?.ok&&Array.isArray(u.data)){let p=u.data.filter(f=>f.to===t.agentId||f.to==="*");p.length>0&&s.push(`Messages:
526
+ ${p.map(f=>` [${f.from}]: ${f.content}`).join(`
515
527
  `)}`)}}catch{}if(o.publishEvent("agent.session_start",{agentId:t.agentId,role:t.role}).catch(()=>{}),s.length>0){let i={additionalContext:`[waggle-cli] You are agent ${t.agentId} (role: ${t.role}) coordinating via ACP.
516
528
  Server: ${t.server} | Namespace: ${t.namespace}
517
529
 
@@ -519,11 +531,11 @@ ${s.join(`
519
531
 
520
532
  `)}
521
533
 
522
- File edits are auto-claimed. Use wgl commands for manual coordination.`};console.log(JSON.stringify(i))}}var xC=w(()=>{"use strict";Xe()});var SC={};X(SC,{handlePreToolUse:()=>LG});async function LG(t,e){let r=Q(t);try{let s=await r.getControlStatus();if(s.ok){let i=s.data;if(i.halted){let a={decision:"block",reason:`Coordination HALTED${i.reason?`: ${i.reason}`:""}. File edits blocked.`};console.log(JSON.stringify(a));return}}}catch{}if(!t.autoClaimFiles)return;let n=e.tool_input?.file_path;if(!n)return;let o=`file:${n}`;try{let s=await r.claim(o,n);if(s.ok){let i=s.data;if(i.status==="rejected"){let c={decision:"block",reason:`File locked by ${i.claim?.owner||"another agent"}: ${n}`};console.log(JSON.stringify(c));return}}}catch{}}var $C=w(()=>{"use strict";Xe()});var kC={};X(kC,{handlePostToolUse:()=>DG});async function DG(t,e){let r=Q(t),n=e.tool_input?.file_path;if(!n)return;let o=`file:${n}`;if(t.autoPublishDiscoveries){let s=e.tool_name||"unknown";r.publishDiscovery(`file-change:${n}`,`${t.agentId} ${s==="Write"?"created":"edited"} ${n}`,"file-change").catch(()=>{})}r.reportProgress(o,0,`${e.tool_name||"edit"} completed`).catch(()=>{})}var EC=w(()=>{"use strict";Xe()});var TC={};X(TC,{handleStop:()=>qG});async function qG(t,e){let r=Q(t);try{let[n,o,s]=await Promise.all([r.getMessages().catch(()=>null),r.getHelp().catch(()=>null),r.getClaims().catch(()=>null)]),i=[];if(n?.ok&&Array.isArray(n.data)){let a=n.data.filter(c=>c.to===t.agentId||c.to==="*");a.length>0&&i.push(`${a.length} unread message(s) \u2014 check with \`wgl status\``)}if(o?.ok&&Array.isArray(o.data)){let a=o.data.filter(c=>c.status==="open");a.length>0&&i.push(`${a.length} open help request(s) need attention`)}if(s?.ok&&Array.isArray(s.data)){let a=s.data.filter(c=>c.owner===t.agentId&&c.status==="active");for(let c of a)r.releaseClaim(c.resource).catch(()=>{})}if(i.length>0){let a={decision:"block",reason:`Cannot stop \u2014 coordination items pending:
534
+ File edits are auto-claimed. Use wgl commands for manual coordination.`};console.log(JSON.stringify(i))}}var IC=w(()=>{"use strict";Qe()});var AC={};K(AC,{handlePreToolUse:()=>p3});async function p3(t,e){let r=Q(t);try{let s=await r.getControlStatus();if(s.ok){let i=s.data;if(i.halted){let a={decision:"block",reason:`Coordination HALTED${i.reason?`: ${i.reason}`:""}. File edits blocked.`};console.log(JSON.stringify(a));return}}}catch{}if(!t.autoClaimFiles)return;let n=e.tool_input?.file_path;if(!n)return;let o=`file:${n}`;try{let s=await r.claim(o,n);if(s.ok){let i=s.data;if(i.status==="rejected"){let c={decision:"block",reason:`File locked by ${i.claim?.owner||"another agent"}: ${n}`};console.log(JSON.stringify(c));return}}}catch{}}var NC=w(()=>{"use strict";Qe()});var zC={};K(zC,{handlePostToolUse:()=>d3});async function d3(t,e){let r=Q(t),n=e.tool_input?.file_path;if(!n)return;let o=`file:${n}`;if(t.autoPublishDiscoveries){let s=e.tool_name||"unknown";r.publishDiscovery(`file-change:${n}`,`${t.agentId} ${s==="Write"?"created":"edited"} ${n}`,"file-change").catch(()=>{})}r.reportProgress(o,0,`${e.tool_name||"edit"} completed`).catch(()=>{})}var jC=w(()=>{"use strict";Qe()});var MC={};K(MC,{handleStop:()=>f3});async function f3(t,e){let r=Q(t);try{let[n,o,s]=await Promise.all([r.getMessages().catch(()=>null),r.getHelp().catch(()=>null),r.getClaims().catch(()=>null)]),i=[];if(n?.ok&&Array.isArray(n.data)){let a=n.data.filter(c=>c.to===t.agentId||c.to==="*");a.length>0&&i.push(`${a.length} unread message(s) \u2014 check with \`wgl status\``)}if(o?.ok&&Array.isArray(o.data)){let a=o.data.filter(c=>c.status==="open");a.length>0&&i.push(`${a.length} open help request(s) need attention`)}if(s?.ok&&Array.isArray(s.data)){let a=s.data.filter(c=>c.owner===t.agentId&&c.status==="active");for(let c of a)r.releaseClaim(c.resource).catch(()=>{})}if(i.length>0){let a={decision:"block",reason:`Cannot stop \u2014 coordination items pending:
523
535
  ${i.map(c=>` \u2022 ${c}`).join(`
524
- `)}`};console.log(JSON.stringify(a));return}}catch{}r.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role}).catch(()=>{})}var PC=w(()=>{"use strict";Xe()});var RC={};X(RC,{handlePromptSubmit:()=>UG});import{writeFileSync as ZG}from"node:fs";async function UG(t,e,r){let n=Q(t),o=[];try{let[s,i]=await Promise.all([n.getControlStatus().catch(()=>null),n.getEvents(t.lastEventCursor).catch(()=>null)]);if(s?.ok){let a=s.data;a.halted?o.push(`COORDINATION HALTED${a.reason?`: ${a.reason}`:""}. Do not proceed with coordinated work.`):a.paused&&o.push(`Coordination paused${a.reason?`: ${a.reason}`:""}.`)}if(i?.ok&&Array.isArray(i.data)){let a=i.data;if(a.length>0){let c=Math.max(...a.map(m=>m.id));t.lastEventCursor=c;try{ZG(e,JSON.stringify(t,null,2)+`
525
- `)}catch{}let l={};for(let m of a)l[m.type]=(l[m.type]||0)+1;let u=Object.entries(l).map(([m,d])=>`${m} (${d})`).join(", ");o.push(`New events since last prompt: ${u}`);let p=a.filter(m=>m.type.startsWith("agent.")||m.type.startsWith("control.")||m.type.startsWith("conflict."));if(p.length>0)for(let m of p.slice(-5))o.push(` [${m.type}] ${JSON.stringify(m.data)}`)}}}catch{}o.length>0&&console.log(`[waggle-cli] ${o.join(`
526
- `)}`)}var OC=w(()=>{"use strict";Xe()});var IC={};X(IC,{runHook:()=>BG});import{readFileSync as CC,existsSync as FG}from"node:fs";import{join as HG}from"node:path";async function BG(t){let e=t[0],r=t[1]??HG(process.cwd(),".wgl.json");e||process.exit(0),FG(r)||process.exit(0);let n;try{n=JSON.parse(CC(r,"utf8"))}catch{process.exit(0)}let o;try{let s=CC(0,"utf8");o=s?JSON.parse(s):{}}catch{o={}}switch(e){case"session-start":{let{handleSessionStart:s}=await Promise.resolve().then(()=>(xC(),wC));await s(n,r,o);break}case"pre-tool-use":{let{handlePreToolUse:s}=await Promise.resolve().then(()=>($C(),SC));await s(n,o);break}case"post-tool-use":{let{handlePostToolUse:s}=await Promise.resolve().then(()=>(EC(),kC));await s(n,o);break}case"stop":{let{handleStop:s}=await Promise.resolve().then(()=>(PC(),TC));await s(n,o);break}case"prompt-submit":{let{handlePromptSubmit:s}=await Promise.resolve().then(()=>(OC(),RC));await s(n,r,o);break}default:process.exit(0)}}var AC=w(()=>{"use strict"});var zC={};X(zC,{scan:()=>WG});import{readFileSync as VG}from"node:fs";import{createRequire as GG}from"node:module";async function WG(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
536
+ `)}`};console.log(JSON.stringify(a));return}}catch{}r.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role}).catch(()=>{})}var LC=w(()=>{"use strict";Qe()});var DC={};K(DC,{handlePromptSubmit:()=>h3});import{writeFileSync as m3}from"node:fs";async function h3(t,e,r){let n=Q(t),o=[];try{let[s,i]=await Promise.all([n.getControlStatus().catch(()=>null),n.getEvents(t.lastEventCursor).catch(()=>null)]);if(s?.ok){let a=s.data;a.halted?o.push(`COORDINATION HALTED${a.reason?`: ${a.reason}`:""}. Do not proceed with coordinated work.`):a.paused&&o.push(`Coordination paused${a.reason?`: ${a.reason}`:""}.`)}if(i?.ok&&Array.isArray(i.data)){let a=i.data;if(a.length>0){let c=Math.max(...a.map(f=>f.id));t.lastEventCursor=c;try{m3(e,JSON.stringify(t,null,2)+`
537
+ `)}catch{}let l={};for(let f of a)l[f.type]=(l[f.type]||0)+1;let u=Object.entries(l).map(([f,d])=>`${f} (${d})`).join(", ");o.push(`New events since last prompt: ${u}`);let p=a.filter(f=>f.type.startsWith("agent.")||f.type.startsWith("control.")||f.type.startsWith("conflict."));if(p.length>0)for(let f of p.slice(-5))o.push(` [${f.type}] ${JSON.stringify(f.data)}`)}}}catch{}o.length>0&&console.log(`[waggle-cli] ${o.join(`
538
+ `)}`)}var qC=w(()=>{"use strict";Qe()});var UC={};K(UC,{runHook:()=>v3});import{readFileSync as ZC,existsSync as g3}from"node:fs";import{join as y3}from"node:path";async function v3(t){let e=t[0],r=t[1]??y3(process.cwd(),".wgl.json");e||process.exit(0),g3(r)||process.exit(0);let n;try{n=JSON.parse(ZC(r,"utf8"))}catch{process.exit(0)}let o;try{let s=ZC(0,"utf8");o=s?JSON.parse(s):{}}catch{o={}}switch(e){case"session-start":{let{handleSessionStart:s}=await Promise.resolve().then(()=>(IC(),CC));await s(n,r,o);break}case"pre-tool-use":{let{handlePreToolUse:s}=await Promise.resolve().then(()=>(NC(),AC));await s(n,o);break}case"post-tool-use":{let{handlePostToolUse:s}=await Promise.resolve().then(()=>(jC(),zC));await s(n,o);break}case"stop":{let{handleStop:s}=await Promise.resolve().then(()=>(LC(),MC));await s(n,o);break}case"prompt-submit":{let{handlePromptSubmit:s}=await Promise.resolve().then(()=>(qC(),DC));await s(n,r,o);break}default:process.exit(0)}}var FC=w(()=>{"use strict"});var BC={};K(BC,{scan:()=>w3});import{readFileSync as _3}from"node:fs";import{createRequire as b3}from"node:module";async function w3(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
527
539
  ${y("bold","wgl scan")} \u2014 scan text for prompt injection
528
540
 
529
541
  ${y("cyan","USAGE:")}
@@ -543,8 +555,10 @@ ${y("cyan","EXAMPLES:")}
543
555
  wgl scan --file user-input.txt
544
556
  wgl scan --json "hello world" | jq .score
545
557
  wgl scan --strict --file untrusted.txt
546
- `);return}let e=t.indexOf("--file"),r=t.includes("--json"),n=t.includes("--strict"),o=t.indexOf("--threshold"),s;if(o!==-1&&(s=parseInt(t[o+1],10),isNaN(s)||s<0||s>100)){console.log(b("--threshold must be an integer between 0 and 100")),process.exit(2);return}let i;if(e!==-1){let d=t[e+1];if(!d){console.log(b("Usage: wgl scan --file <path>")),process.exit(2);return}try{i=VG(d,"utf8")}catch{console.log(b(`Cannot read file: ${d}`)),process.exit(1);return}}else{let d=[];for(let f=0;f<t.length;f++)if(!(t[f]==="--json"||t[f]==="--strict")){if(t[f]==="--threshold"||t[f]==="--file"){f++;continue}d.push(t[f])}i=d.join(" ")}if(!i){console.log(b("No text to scan. Provide inline text or use --file.")),process.exit(2);return}let l=GG(import.meta.url)("@honeybee-ai/carapace").scan;if(!l){console.log(b("Carapace module does not export a scan function")),process.exit(1);return}let u={};s!==void 0&&(u.thresholds={block:s});let p=l(i,u);if(r){console.log(JSON.stringify(p,null,2)),NC(p,n);return}let m=p.action==="BLOCK"?"red":p.action==="WARN"||p.action==="LOG"?"yellow":"green";if(console.log(C("Scan Result")),console.log(S("Score",String(p.score))),console.log(S("Action",y(m,p.action))),console.log(S("Pass",p.pass?y("green","yes"):y("red","no"))),p.findings.length>0){console.log(C("Findings"));let d={};for(let f of p.findings)(d[f.severity]||=[]).push(f);for(let f of["critical","high","medium","low"]){let h=d[f];if(!h)continue;let g=f==="critical"||f==="high"?"red":f==="medium"?"yellow":"dim";for(let v of h)if(console.log(` ${y(g,`[${f.toUpperCase()}]`)} ${v.description}`),console.log(` ${y("dim",`Category: ${v.category} | Pattern: ${v.pattern} | Score: ${v.score}`)}`),v.matches.length>0){let _=v.matches[0].slice(0,80);console.log(` ${y("dim",`Match: "${_}"${v.matches[0].length>80?"...":""}`)}`)}}}else console.log(`
547
- ${y("green","No findings \u2014 text appears clean")}`);console.log(),NC(p,n)}function NC(t,e){t.action==="BLOCK"&&process.exit(2),e&&t.findings.length>0&&process.exit(1)}var jC=w(()=>{"use strict";Re()});var MC={};X(MC,{telemetry:()=>JG});async function JG(t){let e=t[0];if(e==="--help"||e==="-h"||!e){console.log(`
558
+ `);return}let e=t.indexOf("--file"),r=t.includes("--json"),n=t.includes("--strict"),o=t.indexOf("--threshold"),s;if(o!==-1&&(s=parseInt(t[o+1],10),isNaN(s)||s<0||s>100)){console.log(_("--threshold must be an integer between 0 and 100")),process.exit(2);return}let i;if(e!==-1){let d=t[e+1];if(!d){console.log(_("Usage: wgl scan --file <path>")),process.exit(2);return}try{i=_3(d,"utf8")}catch{console.log(_(`Cannot read file: ${d}`)),process.exit(1);return}}else{let d=[];for(let m=0;m<t.length;m++)if(!(t[m]==="--json"||t[m]==="--strict")){if(t[m]==="--threshold"||t[m]==="--file"){m++;continue}d.push(t[m])}i=d.join(" ")}if(!i){console.log(_("No text to scan. Provide inline text or use --file.")),process.exit(2);return}let l=b3(import.meta.url)("@honeybee-ai/carapace").scan;if(!l){console.log(_("Carapace module does not export a scan function")),process.exit(1);return}let u={};s!==void 0&&(u.thresholds={block:s});let p=l(i,u);if(r){console.log(JSON.stringify(p,null,2)),HC(p,n);return}let f=p.action==="BLOCK"?"red":p.action==="WARN"||p.action==="LOG"?"yellow":"green";if(console.log(C("Scan Result")),console.log(S("Score",String(p.score))),console.log(S("Action",y(f,p.action))),console.log(S("Pass",p.pass?y("green","yes"):y("red","no"))),p.findings.length>0){console.log(C("Findings"));let d={};for(let m of p.findings)(d[m.severity]||=[]).push(m);for(let m of["critical","high","medium","low"]){let h=d[m];if(!h)continue;let g=m==="critical"||m==="high"?"red":m==="medium"?"yellow":"dim";for(let v of h)if(console.log(` ${y(g,`[${m.toUpperCase()}]`)} ${v.description}`),console.log(` ${y("dim",`Category: ${v.category} | Pattern: ${v.pattern} | Score: ${v.score}`)}`),v.matches.length>0){let b=v.matches[0].slice(0,80);console.log(` ${y("dim",`Match: "${b}"${v.matches[0].length>80?"...":""}`)}`)}}}else console.log(`
559
+ ${y("green","No findings \u2014 text appears clean")}`);console.log(),HC(p,n)}function HC(t,e){t.action==="BLOCK"&&process.exit(2),e&&t.findings.length>0&&process.exit(1)}var GC=w(()=>{"use strict";Re()});import{mkdirSync as x3,appendFileSync as S3,readdirSync as $3,unlinkSync as k3}from"node:fs";import{join as q_}from"node:path";function Z_(t){let e=t.getTime(),r=e-e%ed;return new Date(r).toISOString()}function T3(){return new Date().toISOString().slice(0,10)}function VC(t){return new mi({endpoint:process.env.TELEMETRY_ENDPOINT,apiKey:process.env.TELEMETRY_API_KEY,projectRoot:t??process.cwd()})}var E3,mi,WC,JC=w(()=>{io();gc();E3=new Set(["latency_ms","total_tokens","prompt_tokens","completion_tokens","score"]);mi=class{endpoint;apiKey;syncInterval;localDir;windows=new Map;syncTimer=null;currentLogFd=null;localEnabled;cloudEnabled;constructor(e={}){if(this.endpoint=e.endpoint??null,this.apiKey=e.apiKey??null,this.syncInterval=e.syncInterval??Qp,e.localDir)this.localDir=e.localDir;else if(e.projectRoot)try{this.localDir=q_(cs(e.projectRoot),yi)}catch{this.localDir=null}else this.localDir=null;this.localEnabled=!!this.localDir,this.cloudEnabled=!!(this.endpoint&&this.apiKey)}start(){!this.localEnabled&&!this.cloudEnabled||(this.localDir&&(x3(this.localDir,{recursive:!0}),this.rotateFiles()),this.cloudEnabled&&(this.syncTimer=setInterval(()=>this.syncToCloud(),this.syncInterval),this.syncTimer.unref()))}record(e,r={}){if(!this.localEnabled&&!this.cloudEnabled)return;let n={event_type:e,metadata:r,timestamp:new Date().toISOString()};this.localEnabled&&this.appendLocal(n),this.aggregate(n)}async stop(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.cloudEnabled&&await this.syncToCloud()}get windowCount(){return this.windows.size}getSnapshot(){if(!this.localEnabled&&!this.cloudEnabled)return null;let e=Z_(new Date),r=this.windows.get(e);return r?{counts:Object.fromEntries(r.counts),numerics:Object.fromEntries([...r.numericRollups].map(([n,o])=>[n,{avg:o.sum/o.count,count:o.count}]))}:null}appendLocal(e){if(!this.localDir)return;let r=T3(),n=q_(this.localDir,`${r}.jsonl`);try{S3(n,JSON.stringify(e)+`
560
+ `)}catch{}}rotateFiles(){if(this.localDir)try{let e=$3(this.localDir).filter(r=>r.endsWith(".jsonl")).sort().reverse();for(let r=Xp;r<e.length;r++)k3(q_(this.localDir,e[r]))}catch{}}aggregate(e){let r=Z_(new Date(e.timestamp)),n=this.windows.get(r);if(n||(n={windowStart:r,counts:new Map,numericRollups:new Map},this.windows.set(r,n)),n.counts.set(e.event_type,(n.counts.get(e.event_type)??0)+1),e.metadata)for(let o of E3){let s=e.metadata[o];if(typeof s=="number"&&Number.isFinite(s)){let i=`${e.event_type}.${o}`,a=n.numericRollups.get(i);a?(a.sum+=s,a.count+=1):n.numericRollups.set(i,{sum:s,count:1})}}}closedWindows(){let e=Z_(new Date),r=[];for(let[n,o]of this.windows)n<e&&r.push(o);return r}async syncToCloud(){if(!this.cloudEnabled)return;let e=this.closedWindows();if(e.length===0)return;let r=e.map(n=>({window_start:n.windowStart,counts:Object.fromEntries(n.counts),averages:Object.fromEntries([...n.numericRollups].map(([o,s])=>[o,{avg:s.sum/s.count,sum:s.sum,count:s.count}]))}));try{await fetch(this.endpoint+"/summary",{method:"POST",headers:{"Content-Type":"application/json","X-Carapace-Key":this.apiKey},body:JSON.stringify({summaries:r})});for(let n of e)this.windows.delete(n.windowStart)}catch{}}};WC=new mi});import{readFileSync as P3,readdirSync as R3,existsSync as O3}from"node:fs";import{join as KC}from"node:path";function YC(t){return KC(cs(t),yi)}function U_(t,e){if(!O3(t))return[];let r=new Date;r.setDate(r.getDate()-e);let n=r.toISOString().slice(0,10),o=R3(t).filter(i=>i.endsWith(".jsonl")&&i.slice(0,10)>=n).sort(),s=[];for(let i of o)try{let a=P3(KC(t,i),"utf8");for(let c of a.split(`
561
+ `))if(c.trim())try{s.push(JSON.parse(c))}catch{}}catch{}return s}function XC(t,e=30){let r=U_(t,e),n=0,o=0,s=0,i=0,a=0,c=0,l=0,u=0,p=0,f=0,d=0,m=0,h=0,g=0,v=0,b=0;for(let x of r){switch(x.event_type){case"scan":n++;break;case"threat_detected":o++;break;case"llm_proxy":s++;break;case"mcp_proxy":i++;break;case"llm_call":l++;break;case"llm_error":u++;break;case"tool_call":p++;break;case"dance_call":f++;break;case"agent_spawn":d++;break;case"agent_complete":m++;break;case"guard_scan":h++;break;case"context_compaction":v++;break}x.event_type==="guard_scan"&&x.metadata?.action==="BLOCK"&&g++;let $=x.metadata?.totalTokens??x.metadata?.total_tokens;typeof $=="number"&&(b+=$);let O=x.metadata?.latency_ms;typeof O=="number"&&Number.isFinite(O)&&(a+=O,c++)}return{days:e,totalScans:n,threatsBlocked:o,avgLatencyMs:c>0?Math.round(a/c*100)/100:0,totalProxyRequests:s,totalMcpRequests:i,totalLlmCalls:l,totalLlmErrors:u,totalToolCalls:p,totalDanceCalls:f,totalAgentSpawns:d,totalAgentCompletes:m,totalGuardScans:h,totalGuardBlocks:g,totalCompactions:v,totalTokens:b}}function QC(t,e=30){let r=U_(t,e),n=new Map;for(let s of r){let a=`${s.timestamp.slice(0,10)}|${s.event_type}`;n.set(a,(n.get(a)??0)+1)}let o=[];for(let[s,i]of n){let[a,c]=s.split("|");o.push({date:a,eventType:c,count:i})}return o.sort((s,i)=>s.date.localeCompare(i.date)||s.eventType.localeCompare(i.eventType))}function eI(t,e={}){let{limit:r=20,offset:n=0,eventType:o,days:s=30}=e,i=U_(t,s);o&&(i=i.filter(l=>l.event_type===o)),i.sort((l,u)=>u.timestamp.localeCompare(l.timestamp));let a=i.length;return{events:i.slice(n,n+r).map((l,u)=>({id:`local-${n+u}`,userId:"local",eventType:l.event_type,hiveId:null,metadata:l.metadata??null,createdAt:l.timestamp})),total:a}}var tI=w(()=>{io();gc()});var rI={};K(rI,{NO_OP_TELEMETRY:()=>WC,TelemetryReporter:()=>mi,createTelemetryFromEnv:()=>VC,getTelemetryDir:()=>YC,localEvents:()=>eI,localOverview:()=>XC,localTimeline:()=>QC});var nI=w(()=>{JC();tI()});var oI={};K(oI,{telemetry:()=>C3});async function C3(t){let e=t[0];if(e==="--help"||e==="-h"||!e){console.log(`
548
562
  ${y("bold","wgl telemetry")} \u2014 view telemetry data from Carapace
549
563
 
550
564
  ${y("cyan","USAGE:")}
@@ -553,16 +567,18 @@ ${y("cyan","USAGE:")}
553
567
  wgl telemetry timeline Daily breakdown by event type
554
568
 
555
569
  ${y("cyan","OPTIONS:")}
570
+ --local Read from local JSONL (no login required)
556
571
  --days N Time window in days (default: 30, max: 90)
557
572
  --limit N Number of events to show (default: 20, max: 100)
573
+ --type TYPE Filter events by type (--local events only)
558
574
  --json JSON output (pipe-friendly)
559
575
 
560
576
  ${y("cyan","EXAMPLES:")}
561
- wgl telemetry overview
577
+ wgl telemetry overview --local
562
578
  wgl telemetry overview --days 7
563
- wgl telemetry events --limit 10
579
+ wgl telemetry events --local --type scan
564
580
  wgl telemetry timeline --json
565
- `);return}let r;try{r=tt({profileName:He().activeProfile||"personal"})}catch{console.log(b("Not logged in. Run `wgl auth login` first.")),process.exit(1);return}let n=t.includes("--json"),o=t.indexOf("--days"),s=o!==-1?parseInt(t[o+1],10)||30:void 0,i=t.indexOf("--limit"),a=i!==-1?parseInt(t[i+1],10)||20:void 0;switch(e){case"overview":await KG(r,s,n);break;case"events":await YG(r,a,n);break;case"timeline":await XG(r,s,n);break;default:console.log(b(`Unknown subcommand: ${e}`)),console.log("Run `wgl telemetry --help` for usage"),process.exit(2)}}async function KG(t,e,r){let n=await t.telemetryOverview(e);if(!n.ok){console.log(b(`Failed to fetch overview (${n.status})`)),process.exit(1);return}let o=n.data;if(r){console.log(JSON.stringify(o,null,2));return}console.log(C(`Telemetry Overview (${o.days} days)`)),console.log(br([["Scans",String(o.totalScans)],["Threats Blocked",o.threatsBlocked>0?y("red",String(o.threatsBlocked)):"0"],["MCP Proxy Requests",String(o.totalMcpRequests)],["LLM Proxy Requests",String(o.totalProxyRequests)],["Avg Latency",`${o.avgLatencyMs}ms`]])),console.log()}async function YG(t,e,r){let n=await t.telemetryEvents({limit:e??20});if(!n.ok){console.log(b(`Failed to fetch events (${n.status})`)),process.exit(1);return}let o=n.data;if(r){console.log(JSON.stringify(o,null,2));return}if(console.log(C(`Recent Events (${o.events.length} of ${o.total})`)),o.events.length===0){console.log(` ${y("dim","No telemetry events yet.")}`),console.log();return}for(let s of o.events){let i=s.eventType==="threat_detected"?"red":s.eventType.startsWith("agent_")?"cyan":s.eventType.startsWith("llm_")?"yellow":"dim",a=new Date(s.createdAt).toLocaleString();if(console.log(` ${y("dim",a)} ${y(i,s.eventType.padEnd(18))}`),s.metadata){let c=Object.entries(s.metadata).slice(0,4).map(([l,u])=>`${l}=${typeof u=="object"?JSON.stringify(u):u}`).join(" ");c&&console.log(` ${y("dim",c)}`)}}console.log()}async function XG(t,e,r){let n=await t.telemetryTimeline(e);if(!n.ok){console.log(b(`Failed to fetch timeline (${n.status})`)),process.exit(1);return}let o=n.data;if(r){console.log(JSON.stringify(o,null,2));return}if(console.log(C(`Telemetry Timeline (${o.days} days)`)),o.timeline.length===0){console.log(` ${y("dim","No data for this period.")}`),console.log();return}let s=new Map;for(let i of o.timeline){let a=i.date;s.has(a)||s.set(a,[]),s.get(a).push({type:i.eventType,count:i.count})}for(let[i,a]of s){let c=a.reduce((l,u)=>l+u.count,0);console.log(` ${y("bold",i)} ${y("dim",`(${c} events)`)}`);for(let l of a){let u="|".repeat(Math.min(l.count,40));console.log(` ${l.type.padEnd(18)} ${y("cyan",u)} ${l.count}`)}}console.log()}var LC=w(()=>{"use strict";pi();Re();ts()});var DC={};X(DC,{completion:()=>e3});async function e3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
581
+ `);return}let r=t.includes("--json"),n=t.includes("--local"),o=t.indexOf("--days"),s=o!==-1?parseInt(t[o+1],10)||30:void 0,i=t.indexOf("--limit"),a=i!==-1?parseInt(t[i+1],10)||20:void 0,c=t.indexOf("--type"),l=c!==-1?t[c+1]:void 0;if(n){await I3(e,{days:s,limit:a,eventType:l,json:r});return}let u;try{u=Xe({profileName:je().activeProfile||"personal"})}catch{console.log(_("Not logged in. Run `wgl auth login` first, or use --local for local data.")),process.exit(1);return}switch(e){case"overview":await A3(u,s,r);break;case"events":await N3(u,a,r);break;case"timeline":await z3(u,s,r);break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl telemetry --help` for usage"),process.exit(2)}}async function I3(t,e){let{localOverview:r,localTimeline:n,localEvents:o,getTelemetryDir:s}=await Promise.resolve().then(()=>(nI(),rI)),i=s(),a=e.days??30;switch(t){case"overview":{let c=r(i,a);if(e.json){console.log(JSON.stringify(c,null,2));return}console.log(C(`Telemetry Overview \u2014 local (${c.days} days)`));let l=[["Scans",String(c.totalScans)],["Threats Blocked",c.threatsBlocked>0?y("red",String(c.threatsBlocked)):"0"]];c.totalLlmCalls!=null&&l.push(["LLM Calls",String(c.totalLlmCalls)],["LLM Errors",c.totalLlmErrors?y("red",String(c.totalLlmErrors)):"0"],["Tool Calls",String(c.totalToolCalls)],["Dance Calls",String(c.totalDanceCalls??0)],["Agent Spawns",String(c.totalAgentSpawns)],["Agent Completes",String(c.totalAgentCompletes)],["Guard Scans",String(c.totalGuardScans)],["Guard Blocks",c.totalGuardBlocks?y("red",String(c.totalGuardBlocks)):"0"],["Context Compactions",String(c.totalCompactions)],["Total Tokens",c.totalTokens?.toLocaleString()??"0"]),l.push(["Avg Latency",`${c.avgLatencyMs}ms`],["MCP Proxy Requests",String(c.totalMcpRequests)],["LLM Proxy Requests",String(c.totalProxyRequests)]),console.log(sr(l)),console.log();break}case"events":{let c=o(i,{limit:e.limit??20,eventType:e.eventType,days:a});if(e.json){console.log(JSON.stringify(c,null,2));return}if(console.log(C(`Recent Events \u2014 local (${c.events.length} of ${c.total})`)),c.events.length===0){console.log(` ${y("dim","No telemetry events yet.")}`),console.log();return}for(let l of c.events){let u=l.eventType==="threat_detected"?"red":l.eventType.startsWith("agent_")?"cyan":l.eventType.startsWith("llm_")?"yellow":"dim",p=new Date(l.createdAt).toLocaleString();if(console.log(` ${y("dim",p)} ${y(u,l.eventType.padEnd(18))}`),l.metadata){let f=Object.entries(l.metadata).slice(0,4).map(([d,m])=>`${d}=${typeof m=="object"?JSON.stringify(m):m}`).join(" ");f&&console.log(` ${y("dim",f)}`)}}console.log();break}case"timeline":{let c=n(i,a);if(e.json){console.log(JSON.stringify({days:a,timeline:c},null,2));return}if(console.log(C(`Telemetry Timeline \u2014 local (${a} days)`)),c.length===0){console.log(` ${y("dim","No data for this period.")}`),console.log();return}let l=new Map;for(let u of c)l.has(u.date)||l.set(u.date,[]),l.get(u.date).push({type:u.eventType,count:u.count});for(let[u,p]of l){let f=p.reduce((d,m)=>d+m.count,0);console.log(` ${y("bold",u)} ${y("dim",`(${f} events)`)}`);for(let d of p){let m="|".repeat(Math.min(d.count,40));console.log(` ${d.type.padEnd(18)} ${y("cyan",m)} ${d.count}`)}}console.log();break}default:console.log(_(`Unknown subcommand: ${t}`)),console.log("Run `wgl telemetry --help` for usage"),process.exit(2)}}async function A3(t,e,r){let n=await t.telemetryOverview(e);if(!n.ok){console.log(_(`Failed to fetch overview (${n.status})`)),process.exit(1);return}let o=n.data;if(r){console.log(JSON.stringify(o,null,2));return}console.log(C(`Telemetry Overview (${o.days} days)`)),console.log(sr([["Scans",String(o.totalScans)],["Threats Blocked",o.threatsBlocked>0?y("red",String(o.threatsBlocked)):"0"],["MCP Proxy Requests",String(o.totalMcpRequests)],["LLM Proxy Requests",String(o.totalProxyRequests)],["Avg Latency",`${o.avgLatencyMs}ms`]])),console.log()}async function N3(t,e,r){let n=await t.telemetryEvents({limit:e??20});if(!n.ok){console.log(_(`Failed to fetch events (${n.status})`)),process.exit(1);return}let o=n.data;if(r){console.log(JSON.stringify(o,null,2));return}if(console.log(C(`Recent Events (${o.events.length} of ${o.total})`)),o.events.length===0){console.log(` ${y("dim","No telemetry events yet.")}`),console.log();return}for(let s of o.events){let i=s.eventType==="threat_detected"?"red":s.eventType.startsWith("agent_")?"cyan":s.eventType.startsWith("llm_")?"yellow":"dim",a=new Date(s.createdAt).toLocaleString();if(console.log(` ${y("dim",a)} ${y(i,s.eventType.padEnd(18))}`),s.metadata){let c=Object.entries(s.metadata).slice(0,4).map(([l,u])=>`${l}=${typeof u=="object"?JSON.stringify(u):u}`).join(" ");c&&console.log(` ${y("dim",c)}`)}}console.log()}async function z3(t,e,r){let n=await t.telemetryTimeline(e);if(!n.ok){console.log(_(`Failed to fetch timeline (${n.status})`)),process.exit(1);return}let o=n.data;if(r){console.log(JSON.stringify(o,null,2));return}if(console.log(C(`Telemetry Timeline (${o.days} days)`)),o.timeline.length===0){console.log(` ${y("dim","No data for this period.")}`),console.log();return}let s=new Map;for(let i of o.timeline){let a=i.date;s.has(a)||s.set(a,[]),s.get(a).push({type:i.eventType,count:i.count})}for(let[i,a]of s){let c=a.reduce((l,u)=>l+u.count,0);console.log(` ${y("bold",i)} ${y("dim",`(${c} events)`)}`);for(let l of a){let u="|".repeat(Math.min(l.count,40));console.log(` ${l.type.padEnd(18)} ${y("cyan",u)} ${l.count}`)}}console.log()}var sI=w(()=>{"use strict";fi();Re();rs()});var iI={};K(iI,{completion:()=>M3});async function M3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
566
582
  ${y("bold","wgl completion")} \u2014 generate shell completion scripts
567
583
 
568
584
  ${y("cyan","USAGE:")}
@@ -574,7 +590,7 @@ ${y("cyan","SETUP:")}
574
590
  eval "$(wgl completion bash)" # add to .bashrc
575
591
  eval "$(wgl completion zsh)" # add to .zshrc
576
592
  wgl completion fish | source # add to config.fish
577
- `);return}switch(e){case"bash":console.log(t3());break;case"zsh":console.log(r3());break;case"fish":console.log(n3());break;default:console.log(b(`Unknown shell: ${e}. Supported: bash, zsh, fish`)),process.exit(2)}}function t3(){let t=Object.entries(Zp).filter(([,e])=>e.length>0).map(([e,r])=>` ${e}) COMPREPLY=( $(compgen -W "${r.join(" ")}" -- "$cur") ) ;;`).join(`
593
+ `);return}switch(e){case"bash":console.log(L3());break;case"zsh":console.log(D3());break;case"fish":console.log(q3());break;default:console.log(_(`Unknown shell: ${e}. Supported: bash, zsh, fish`)),process.exit(2)}}function L3(){let t=Object.entries(Bp).filter(([,e])=>e.length>0).map(([e,r])=>` ${e}) COMPREPLY=( $(compgen -W "${r.join(" ")}" -- "$cur") ) ;;`).join(`
578
594
  `);return`# wgl bash completion \u2014 generated by wgl completion bash
579
595
  _wgl_completions() {
580
596
  local cur prev
@@ -583,7 +599,7 @@ _wgl_completions() {
583
599
  prev="\${COMP_WORDS[COMP_CWORD-1]}"
584
600
 
585
601
  if [ "$COMP_CWORD" -eq 1 ]; then
586
- COMPREPLY=( $(compgen -W "${QG} --help --version" -- "$cur") )
602
+ COMPREPLY=( $(compgen -W "${j3} --help --version" -- "$cur") )
587
603
  return
588
604
  fi
589
605
 
@@ -592,7 +608,7 @@ ${t}
592
608
  keys) COMPREPLY=( $(compgen -W "create list revoke" -- "$cur") ) ;;
593
609
  esac
594
610
  }
595
- complete -F _wgl_completions wgl`}function r3(){return`#compdef wgl
611
+ complete -F _wgl_completions wgl`}function D3(){return`#compdef wgl
596
612
  # wgl zsh completion \u2014 generated by wgl completion zsh
597
613
  _wgl() {
598
614
  local -a commands
@@ -619,7 +635,7 @@ _wgl() {
619
635
  'config:Global configuration'
620
636
  'marketplace:Protocol marketplace'
621
637
  'integrations:Integration marketplace'
622
- 'swarm:Managed swarms'
638
+ 'hive:Managed hives'
623
639
  'scan:Security scanning'
624
640
  'completion:Shell completions'
625
641
  'upgrade:Self-update'
@@ -631,22 +647,22 @@ _wgl() {
631
647
  fi
632
648
 
633
649
  case "\${words[2]}" in
634
- ${Object.entries(Zp).filter(([,e])=>e.length>0).map(([e,r])=>{let n=r.map(o=>`'${o}[${o}]'`).join(" ");return` ${e}) _arguments '1:subcommand:(${r.join(" ")})' ;;`}).join(`
650
+ ${Object.entries(Bp).filter(([,e])=>e.length>0).map(([e,r])=>{let n=r.map(o=>`'${o}[${o}]'`).join(" ");return` ${e}) _arguments '1:subcommand:(${r.join(" ")})' ;;`}).join(`
635
651
  `)}
636
652
  esac
637
653
  }
638
- _wgl "$@"`}function n3(){let t=["# wgl fish completion \u2014 generated by wgl completion fish"];t.push("# Disable file completion by default"),t.push("complete -c wgl -f"),t.push("");let e={init:"Interactive setup",join:"Quick join a server",status:"Show current status",leave:"Leave coordination",protocol:"Protocol management",team:"Show agents",claim:"Claim a resource",release:"Release a resource",halt:"Emergency stop",pause:"Pause coordination",resume:"Resume coordination",events:"Event management",state:"Shared state",msg:"Messaging",help:"Help requests",namespace:"Namespace management",hooks:"Hook management",serve:"Start local server",auth:"Authentication",config:"Global configuration",marketplace:"Protocol marketplace",integrations:"Integration marketplace",swarm:"Managed swarms",scan:"Security scanning",completion:"Shell completions",upgrade:"Self-update"};for(let[r,n]of Object.entries(e))t.push(`complete -c wgl -n '__fish_use_subcommand' -a '${r}' -d '${n}'`);t.push("");for(let[r,n]of Object.entries(Zp))if(n.length!==0)for(let o of n)t.push(`complete -c wgl -n '__fish_seen_subcommand_from ${r}' -a '${o}'`);return t.push("complete -c wgl -n '__fish_seen_subcommand_from keys' -a 'create list revoke'"),t.join(`
639
- `)}var Zp,QG,qC=w(()=>{"use strict";Re();Zp={init:[],join:[],status:[],leave:[],protocol:["show","validate","load","init"],team:[],claim:[],release:[],halt:[],pause:[],resume:[],events:["list","tail","publish"],state:["get","set","delete"],msg:["send","list","broadcast"],help:["ask","list","claim","resolve"],namespace:["list","create","delete"],hooks:["install","uninstall","list"],serve:[],auth:["login","logout","status","switch"],config:["set","get","list"],marketplace:["search","info","install","publish","list"],integrations:["search","info","install","remove","list","enable","disable","publish"],swarm:["create","list","info","delete","pause","resume","keys","logs"],scan:[],completion:["bash","zsh","fish"],upgrade:[]},QG=Object.keys(Zp).join(" ")});var ZC={};X(ZC,{upgrade:()=>d3});import{readFileSync as o3}from"node:fs";import{join as s3,dirname as i3}from"node:path";import{request as a3}from"node:https";import{execSync as c3}from"node:child_process";function u3(){return"1.0.6";try{let t=s3(i3(new URL(import.meta.url).pathname),"..","package.json");return JSON.parse(o3(t,"utf8")).version}catch{return"0.0.0-dev"}}function p3(){return new Promise((t,e)=>{let r=a3(l3,{timeout:1e4},n=>{let o="";n.on("data",s=>o+=s),n.on("end",()=>{try{let s=JSON.parse(o);t(s.version)}catch{e(new Error("Failed to parse registry response"))}})});r.on("error",n=>e(n)),r.on("timeout",()=>{r.destroy(),e(new Error("timeout"))}),r.end()})}async function d3(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
654
+ _wgl "$@"`}function q3(){let t=["# wgl fish completion \u2014 generated by wgl completion fish"];t.push("# Disable file completion by default"),t.push("complete -c wgl -f"),t.push("");let e={init:"Interactive setup",join:"Quick join a server",status:"Show current status",leave:"Leave coordination",protocol:"Protocol management",team:"Show agents",claim:"Claim a resource",release:"Release a resource",halt:"Emergency stop",pause:"Pause coordination",resume:"Resume coordination",events:"Event management",state:"Shared state",msg:"Messaging",help:"Help requests",namespace:"Namespace management",hooks:"Hook management",serve:"Start local server",auth:"Authentication",config:"Global configuration",marketplace:"Protocol marketplace",integrations:"Integration marketplace",hive:"Managed hives",scan:"Security scanning",completion:"Shell completions",upgrade:"Self-update"};for(let[r,n]of Object.entries(e))t.push(`complete -c wgl -n '__fish_use_subcommand' -a '${r}' -d '${n}'`);t.push("");for(let[r,n]of Object.entries(Bp))if(n.length!==0)for(let o of n)t.push(`complete -c wgl -n '__fish_seen_subcommand_from ${r}' -a '${o}'`);return t.push("complete -c wgl -n '__fish_seen_subcommand_from keys' -a 'create list revoke'"),t.join(`
655
+ `)}var Bp,j3,aI=w(()=>{"use strict";Re();Bp={init:[],join:[],status:[],leave:[],protocol:["show","validate","load","init"],team:[],claim:[],release:[],halt:[],pause:[],resume:[],events:["list","tail","publish"],state:["get","set","delete"],msg:["send","list","broadcast"],help:["ask","list","claim","resolve"],namespace:["list","create","delete"],hooks:["install","uninstall","list"],serve:[],auth:["login","logout","status","switch"],config:["set","get","list"],marketplace:["search","info","install","publish","list"],integrations:["search","info","install","remove","list","enable","disable","publish"],hive:["create","list","info","delete","pause","resume","keys","logs"],scan:[],completion:["bash","zsh","fish"],upgrade:[]},j3=Object.keys(Bp).join(" ")});var cI={};K(cI,{upgrade:()=>J3});import{readFileSync as Z3}from"node:fs";import{join as U3,dirname as F3}from"node:path";import{request as H3}from"node:https";import{execSync as B3}from"node:child_process";function V3(){return"1.0.8";try{let t=U3(F3(new URL(import.meta.url).pathname),"..","package.json");return JSON.parse(Z3(t,"utf8")).version}catch{return"0.0.0-dev"}}function W3(){return new Promise((t,e)=>{let r=H3(G3,{timeout:1e4},n=>{let o="";n.on("data",s=>o+=s),n.on("end",()=>{try{let s=JSON.parse(o);t(s.version)}catch{e(new Error("Failed to parse registry response"))}})});r.on("error",n=>e(n)),r.on("timeout",()=>{r.destroy(),e(new Error("timeout"))}),r.end()})}async function J3(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
640
656
  ${y("bold","wgl upgrade")} \u2014 update waggle-cli to the latest version
641
657
 
642
658
  ${y("cyan","USAGE:")}
643
659
  wgl upgrade Update to latest version
644
660
  wgl upgrade --check Just check, don't install
645
- `);return}let e=t.includes("--check"),r=u3();console.log(S("Current",r));let n;try{n=await p3()}catch{console.log(b("Cannot reach npm registry")),process.exit(1);return}if(console.log(S("Latest",n)),r===n){console.log(`
661
+ `);return}let e=t.includes("--check"),r=V3();console.log(S("Current",r));let n;try{n=await W3()}catch{console.log(_("Cannot reach npm registry")),process.exit(1);return}if(console.log(S("Latest",n)),r===n){console.log(`
646
662
  ${y("green","Already up to date")}`);return}let o=r.split(".").map(Number),s=n.split(".").map(Number),i=!1;for(let a=0;a<3;a++){if(s[a]>o[a]){i=!0;break}if(s[a]<o[a])break}if(!i){console.log(`
647
663
  ${y("green","Already up to date (or ahead)")}`);return}if(e){console.log(`
648
664
  ${y("yellow",`Update available: ${r} \u2192 ${n}`)}`),console.log(y("dim"," Run `wgl upgrade` to install"));return}console.log(`
649
- Upgrading ${r} \u2192 ${n}...`);try{c3("npm install -g @honeybee-ai/waggle-cli@latest",{stdio:"inherit"}),console.log(z(`Updated to ${n}`))}catch{console.log(b("Upgrade failed. Try manually: npm install -g @honeybee-ai/waggle-cli@latest")),process.exit(1)}}var l3,UC=w(()=>{"use strict";Re();l3="https://registry.npmjs.org/@honeybee-ai/waggle-cli/latest"});Re();var FC=process.argv.slice(2),ns=FC[0],Ce=FC.slice(1);function f3(){console.log(`
665
+ Upgrading ${r} \u2192 ${n}...`);try{B3("npm install -g @honeybee-ai/waggle-cli@latest",{stdio:"inherit"}),console.log(N(`Updated to ${n}`))}catch{console.log(_("Upgrade failed. Try manually: npm install -g @honeybee-ai/waggle-cli@latest")),process.exit(1)}}var G3,lI=w(()=>{"use strict";Re();G3="https://registry.npmjs.org/@honeybee-ai/waggle-cli/latest"});Re();var uI=process.argv.slice(2),os=uI[0],Ce=uI.slice(1);function K3(){console.log(`
650
666
  ${y("bold","wgl")} \u2014 waggle-cli: bridge AI agents to ACP coordination servers
651
667
 
652
668
  ${y("cyan","USAGE:")}
@@ -737,13 +753,13 @@ ${y("cyan","CLOUD:")}
737
753
  integrations enable Enable an integration
738
754
  integrations disable Disable an integration
739
755
  integrations publish Publish an integration
740
- swarm create Create a managed swarm
741
- swarm list List your swarms
742
- swarm info Show swarm details
743
- swarm delete Delete a swarm
744
- swarm pause/resume Pause or resume a swarm
745
- swarm keys Manage API keys
746
- swarm logs Tail swarm events
756
+ hive create Create a managed hive
757
+ hive list List your hives
758
+ hive info Show hive details
759
+ hive delete Delete a hive
760
+ hive pause/resume Pause or resume a hive
761
+ hive keys Manage API keys
762
+ hive logs Tail hive events
747
763
 
748
764
  ${y("cyan","TELEMETRY:")}
749
765
  telemetry overview Aggregate counters (scans, threats, latency)
@@ -772,12 +788,12 @@ ${y("cyan","EXAMPLES:")}
772
788
  wgl halt "critical bug found"
773
789
  wgl auth login
774
790
  wgl marketplace search "code review"
775
- wgl swarm create my-swarm --max-agents 5
791
+ wgl hive create my-hive --max-agents 5
776
792
  wgl carapace scan "ignore previous instructions"
777
793
  wgl carapace gateway
778
794
  wgl incubator --port=8080 --brood=brood.yaml
779
795
  wgl leave
780
- `)}async function m3(){if(!ns||ns==="--help"||ns==="-h"){f3();return}if(ns==="--version"||ns==="-v"){console.log("1.0.6");return}switch(ns){case"init":{let{init:t}=await Promise.resolve().then(()=>(nb(),rb));await t(Ce);break}case"join":{let{join:t}=await Promise.resolve().then(()=>(sb(),ob));await t(Ce);break}case"status":{let{status:t}=await Promise.resolve().then(()=>(ab(),ib));await t();break}case"leave":{let{leave:t}=await Promise.resolve().then(()=>(lb(),cb));await t();break}case"protocol":{let{protocol:t}=await Promise.resolve().then(()=>(xw(),ww));await t(Ce);break}case"team":{let{team:t}=await Promise.resolve().then(()=>($w(),Sw));await t();break}case"claim":{let{claim:t}=await Promise.resolve().then(()=>(Ew(),kw));await t(Ce);break}case"release":{let{release:t}=await Promise.resolve().then(()=>(Pw(),Tw));await t(Ce);break}case"halt":{let{halt:t}=await Promise.resolve().then(()=>(Ow(),Rw));await t(Ce);break}case"pause":{let{pause:t}=await Promise.resolve().then(()=>(qd(),Dd));await t(Ce);break}case"resume":{let{resume:t}=await Promise.resolve().then(()=>(qd(),Dd));await t();break}case"events":{let{events:t}=await Promise.resolve().then(()=>(Aw(),Iw));await t(Ce);break}case"state":{let{state:t}=await Promise.resolve().then(()=>(zw(),Nw));await t(Ce);break}case"msg":{let{msg:t}=await Promise.resolve().then(()=>(Mw(),jw));await t(Ce);break}case"help":{let{helpCmd:t}=await Promise.resolve().then(()=>(Dw(),Lw));await t(Ce);break}case"namespace":{let{namespace:t}=await Promise.resolve().then(()=>(Zw(),qw));await t(Ce);break}case"hooks":{let{hooksCmd:t}=await Promise.resolve().then(()=>(Fw(),Uw));await t(Ce);break}case"up":{let{up:t}=await Promise.resolve().then(()=>(ix(),sx));await t(Ce);break}case"down":{let{down:t}=await Promise.resolve().then(()=>(ux(),lx));await t(Ce);break}case"logs":{let{logs:t}=await Promise.resolve().then(()=>(dx(),px));await t(Ce);break}case"inspect":{let{inspect:t}=await Promise.resolve().then(()=>(hx(),mx));await t(Ce);break}case"serve":{let{serve:t}=await Promise.resolve().then(()=>(QO(),XO));await t(Ce);break}case"auth":{let{auth:t}=await Promise.resolve().then(()=>(iC(),sC));await t(Ce);break}case"config":{let{configCmd:t}=await Promise.resolve().then(()=>(lC(),cC));await t(Ce);break}case"marketplace":{let{marketplace:t}=await Promise.resolve().then(()=>(pC(),uC));await t(Ce);break}case"integrations":{let{integrations:t}=await Promise.resolve().then(()=>(gC(),hC));await t(Ce);break}case"swarm":{let{swarm:t}=await Promise.resolve().then(()=>(vC(),yC));await t(Ce);break}case"carapace":{let{runCarapace:t}=await Promise.resolve().then(()=>(bC(),_C));await t(Ce);break}case"incubator":{let{main:t}=await Promise.resolve().then(()=>(w_(),b_)),e=process.argv;process.argv=["node","incubator",...Ce];try{await t()}finally{process.argv=e}break}case"hook":{let{runHook:t}=await Promise.resolve().then(()=>(AC(),IC));await t(Ce);break}case"scan":{let{scan:t}=await Promise.resolve().then(()=>(jC(),zC));await t(Ce);break}case"telemetry":{let{telemetry:t}=await Promise.resolve().then(()=>(LC(),MC));await t(Ce);break}case"completion":{let{completion:t}=await Promise.resolve().then(()=>(qC(),DC));await t(Ce);break}case"upgrade":{let{upgrade:t}=await Promise.resolve().then(()=>(UC(),ZC));await t(Ce);break}default:console.error(y("red",`Unknown command: ${ns}`)),console.log("Run `wgl --help` for usage"),process.exit(2)}}m3().catch(t=>{console.error(y("red",`Error: ${t.message}`)),process.exit(2)});
796
+ `)}async function Y3(){if(!os||os==="--help"||os==="-h"){K3();return}if(os==="--version"||os==="-v"){console.log("1.0.8");return}switch(os){case"init":{let{init:t}=await Promise.resolve().then(()=>(db(),pb));await t(Ce);break}case"join":{let{join:t}=await Promise.resolve().then(()=>(mb(),fb));await t(Ce);break}case"status":{let{status:t}=await Promise.resolve().then(()=>(gb(),hb));await t();break}case"leave":{let{leave:t}=await Promise.resolve().then(()=>(vb(),yb));await t();break}case"protocol":{let{protocol:t}=await Promise.resolve().then(()=>(Cw(),Ow));await t(Ce);break}case"team":{let{team:t}=await Promise.resolve().then(()=>(Aw(),Iw));await t();break}case"claim":{let{claim:t}=await Promise.resolve().then(()=>(zw(),Nw));await t(Ce);break}case"release":{let{release:t}=await Promise.resolve().then(()=>(Mw(),jw));await t(Ce);break}case"halt":{let{halt:t}=await Promise.resolve().then(()=>(Dw(),Lw));await t(Ce);break}case"pause":{let{pause:t}=await Promise.resolve().then(()=>(Vd(),Gd));await t(Ce);break}case"resume":{let{resume:t}=await Promise.resolve().then(()=>(Vd(),Gd));await t();break}case"events":{let{events:t}=await Promise.resolve().then(()=>(Uw(),Zw));await t(Ce);break}case"state":{let{state:t}=await Promise.resolve().then(()=>(Hw(),Fw));await t(Ce);break}case"msg":{let{msg:t}=await Promise.resolve().then(()=>(Gw(),Bw));await t(Ce);break}case"help":{let{helpCmd:t}=await Promise.resolve().then(()=>(Ww(),Vw));await t(Ce);break}case"namespace":{let{namespace:t}=await Promise.resolve().then(()=>(Kw(),Jw));await t(Ce);break}case"hooks":{let{hooksCmd:t}=await Promise.resolve().then(()=>(Xw(),Yw));await t(Ce);break}case"up":{let{up:t}=await Promise.resolve().then(()=>(hx(),mx));await t(Ce);break}case"down":{let{down:t}=await Promise.resolve().then(()=>(_x(),vx));await t(Ce);break}case"logs":{let{logs:t}=await Promise.resolve().then(()=>(wx(),bx));await t(Ce);break}case"inspect":{let{inspect:t}=await Promise.resolve().then(()=>($x(),Sx));await t(Ce);break}case"serve":{let{serve:t}=await Promise.resolve().then(()=>(cC(),aC));await t(Ce);break}case"auth":{let{auth:t}=await Promise.resolve().then(()=>(hC(),mC));await t(Ce);break}case"config":{let{configCmd:t}=await Promise.resolve().then(()=>(vC(),yC));await t(Ce);break}case"marketplace":{let{marketplace:t}=await Promise.resolve().then(()=>(bC(),_C));await t(Ce);break}case"integrations":{let{integrations:t}=await Promise.resolve().then(()=>(kC(),$C));await t(Ce);break}case"hive":{let{hive:t}=await Promise.resolve().then(()=>(PC(),TC));await t(Ce);break}case"carapace":{let{runCarapace:t}=await Promise.resolve().then(()=>(OC(),RC));await t(Ce);break}case"incubator":{let{main:t}=await Promise.resolve().then(()=>(P_(),T_)),e=process.argv;process.argv=["node","incubator",...Ce];try{await t()}finally{process.argv=e}break}case"hook":{let{runHook:t}=await Promise.resolve().then(()=>(FC(),UC));await t(Ce);break}case"scan":{let{scan:t}=await Promise.resolve().then(()=>(GC(),BC));await t(Ce);break}case"telemetry":{let{telemetry:t}=await Promise.resolve().then(()=>(sI(),oI));await t(Ce);break}case"completion":{let{completion:t}=await Promise.resolve().then(()=>(aI(),iI));await t(Ce);break}case"upgrade":{let{upgrade:t}=await Promise.resolve().then(()=>(lI(),cI));await t(Ce);break}default:console.error(y("red",`Unknown command: ${os}`)),console.log("Run `wgl --help` for usage"),process.exit(2)}}Y3().catch(t=>{console.error(y("red",`Error: ${t.message}`)),process.exit(2)});
781
797
  /*! Bundled license information:
782
798
 
783
799
  js-yaml/dist/js-yaml.mjs: