@honeybee-ai/waggle-cli 1.0.10 → 1.0.11

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,50 +1,50 @@
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 qI=Object.create;var rd=Object.defineProperty;var ZI=Object.getOwnPropertyDescriptor;var UI=Object.getOwnPropertyNames;var FI=Object.getPrototypeOf,HI=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),V=(t,e)=>{for(var r in e)rd(t,r,{get:e[r],enumerable:!0})},BI=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of UI(e))!HI.call(t,o)&&o!==r&&rd(t,o,{get:()=>e[o],enumerable:!(n=ZI(e,o))||n.enumerable});return t};var io=(t,e,r)=>(r=t!=null?qI(FI(t)):{},BI(e||!t||!t.__esModule?rd(r,"default",{value:t,enumerable:!0}):r,t));function g(t,e){return`${ab[t]}${e}${ab.reset}`}function C(t){return`
4
- ${g("bold",g("cyan",t))}`}function A(t){return g("green",`\u2713 ${t}`)}function sr(t){return g("yellow",`\u26A0 ${t}`)}function _(t){return g("red",`\u2717 ${t}`)}function S(t,e){return` ${g("bold",t+":")} ${e}`}function ir(t){let e=Math.max(...t.map(([r])=>r.length));return t.map(([r,n])=>` ${g("bold",r.padEnd(e))} ${n}`).join(`
5
- `)}var ab,Ee=w(()=>{"use strict";ab={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 GI}from"node:crypto";function hc(){return`wgl_${GI(4).toString("hex")}`}var nd=w(()=>{"use strict"});import{join as cb}from"node:path";import{homedir as lb}from"node:os";var gt,zr,us,od,ps,sd,gc,ao,ds,yc,id,ad,bi,cd,ld,ud,pd,dd,co=w(()=>{gt=cb(lb(),".honeyb"),zr=cb(lb(),".wgl"),us="auth.json",od="integrations.json",ps=".honeyb",sd=".honeybee",gc=[".wglrc.yaml",".wglrc.json",".wglrc"],ao=".wgl.json",ds="session.json",yc="brood.state.json",id="logs",ad=10,bi="telemetry",cd=30,ld=3e5,ud=3e5,pd={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"},dd={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 fb,writeFileSync as fd,existsSync as Zt,mkdirSync as vc,copyFileSync as md,chmodSync as VI}from"node:fs";import{join as Qt,resolve as WI}from"node:path";import{homedir as ub}from"node:os";function hd(){if(pb)return;pb=!0;let t=Qt(zr,"auth.json"),e=Qt(gt,us);Zt(t)&&!Zt(e)&&(Zt(gt)||vc(gt,{recursive:!0}),md(t,e),VI(e,384),console.error("[honeyb] Migrated auth store: ~/.wgl/auth.json \u2192 ~/.honeyb/auth.json"));let r=Qt(zr,"config.json"),n=ub(),o=Qt(n,".wglrc.json");if(Zt(r)&&!Zt(o))try{let a=JSON.parse(fb(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&&(fd(o,JSON.stringify(c,null,2)+`
6
- `),console.error("[honeyb] Migrated global config: ~/.wgl/config.json \u2192 ~/.wglrc.json"))}catch{}let s=Qt(ub(),".config","honeybee","integrations.json"),i=Qt(gt,od);Zt(s)&&!Zt(i)&&(Zt(gt)||vc(gt,{recursive:!0}),md(s,i),console.error("[honeyb] Migrated integrations: ~/.config/honeybee/integrations.json \u2192 ~/.honeyb/integrations.json"))}function gd(t){let e=WI(t||process.cwd());if(db.has(e))return;db.add(e);let r=Qt(e,ao),n=Qt(e,".wglrc.json"),o=Qt(e,ps),s=Qt(o,ds);if(Zt(r)&&!Zt(n))try{let l=JSON.parse(fb(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&&fd(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&&(Zt(o)||vc(o,{recursive:!0}),fd(s,JSON.stringify(p,null,2)+`
8
- `)),console.error("[honeyb] Migrated project config: .wgl.json \u2192 .wglrc.json + .honeyb/session.json")}catch{}let i=Qt(e,sd),a=Qt(i,"brood.state.json"),c=Qt(o,yc);Zt(a)&&!Zt(c)&&(Zt(o)||vc(o,{recursive:!0}),md(a,c),console.error("[honeyb] Migrated brood state: .honeybee/brood.state.json \u2192 .honeyb/brood.state.json"))}var pb,db,yd=w(()=>{co();pb=!1,db=new Set});import{readFileSync as _d,writeFileSync as YI,existsSync as vn,mkdirSync as _c,readdirSync as XI,unlinkSync as QI}from"node:fs";import{join as Sr,dirname as mb,resolve as wi,sep as e1}from"node:path";import{homedir as t1}from"node:os";function bd(t){let e=wi(t||process.cwd()),r=e1==="/"?"/":e.slice(0,3);for(;;){for(let o of gc){let s=Sr(e,o);if(vn(s))return s}let n=mb(e);if(n===e||e===r)return null;e=n}}function hb(){let t=t1();for(let e of gc){let r=Sr(t,e);if(vn(r))return r}return null}function vd(t){let e=_d(t,"utf8").trim();return e?t.endsWith(".yaml")?r1(e):t.endsWith(".json")?gb(e):o1(e):{}}function gb(t){try{let e=JSON.parse(t);return typeof e!="object"||e===null||Array.isArray(e)?{}:e}catch{return{}}}function r1(t){try{return n1(t)}catch{return gb(t)}}function n1(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]=wd(l)}return e}function o1(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();xi(e,s,wd(i))}return e}function wd(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 xi(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 bc(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 yn(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]=yn(s,o):r[n]=o}return r}function s1(){let t={};for(let[e,r]of Object.entries(pd)){let n=process.env[e];n!==void 0&&n!==""&&xi(t,r,wd(n))}return t}function jr(t){hd(),gd(t);let e=structuredClone(dd),r=hb();r&&(e=yn(e,vd(r)));let n=bd(t);if(n&&(e=yn(e,vd(n))),!n){let o=i1(t);if(o){let s=a1(o);s&&(e=yn(e,s))}}return e=yn(e,s1()),Object.freeze(e)}function wc(){return vn(gt)||_c(gt,{recursive:!0}),gt}function yb(t){return wi(t||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}function fs(t){let e=yb(t),r=Sr(wc(),"projects",e);return vn(r)||_c(r,{recursive:!0}),r}function vb(t){let e=wi(t||process.cwd()),r=Sr(e,ps);return vn(r)||_c(r,{recursive:!0}),r}function xd(t){let e=Sr(wi(t||process.cwd()),ps),r=Sr(e,ds);if(!vn(r))return{};try{return JSON.parse(_d(r,"utf8"))}catch{return{}}}function Sd(t,e){let r=vb(e),n=Sr(r,ds);YI(n,JSON.stringify(t,null,2)+`
11
- `)}function _n(t){let e=Sr(fs(t),id);return vn(e)||_c(e,{recursive:!0}),e}function $d(t){let e=_n(t),r=new Date().toISOString().replace(/[:.]/g,"-");return Sr(e,`${r}.jsonl`)}function kd(t){let e=_n(t);try{let r=XI(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();for(let n=ad;n<r.length;n++)QI(Sr(e,r[n]))}catch{}}function i1(t){let e=wi(t||process.cwd()),r="/";for(;;){let n=Sr(e,ao);if(vn(n))return n;let o=mb(e);if(o===e||e===r)return null;e=o}}function a1(t){try{let e=JSON.parse(_d(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 xc=w(()=>{co();yd()});import{readFileSync as c1,writeFileSync as l1,existsSync as Sc,mkdirSync as u1,chmodSync as p1}from"node:fs";import{join as Ed}from"node:path";function d1(){let t=Ed(gt,us);if(Sc(t))return t;let e=Ed(zr,"auth.json");return Sc(e)?e:t}function lo(){let t=d1();if(!Sc(t))return{profiles:{}};try{return JSON.parse(c1(t,"utf8"))}catch{return{profiles:{}}}}function Si(t){Sc(gt)||u1(gt,{recursive:!0});let e=Ed(gt,us);l1(e,JSON.stringify(t,null,2)+`
12
- `,{mode:384}),p1(e,384)}function Td(t){return lo().profiles[t]||null}function Pd(t,e){let r=lo();r.profiles[t]=e,Si(r)}function Rd(t){let e=lo();return t in e.profiles?(delete e.profiles[t],Si(e),!0):!1}function Od(){let t=lo();return Object.keys(t.profiles)}var _b=w(()=>{co()});var bn=w(()=>{co();xc();_b();yd()});import{writeFileSync as f1,existsSync as bb,unlinkSync as wb}from"node:fs";import{join as Cd}from"node:path";function _e(t){let e=jr(t),r=xd(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=Cd(r,".wglrc.json");f1(o,JSON.stringify(n,null,2)+`
13
- `);let s={agentId:t.agentId,lastEventCursor:t.lastEventCursor,autoPublishDiscoveries:t.autoPublishDiscoveries};return Sd(s,r),o}function xb(t){let e=t||process.cwd(),r=!1;for(let o of[".wglrc.json",".wglrc.yaml",".wglrc"]){let s=Cd(e,o);bb(s)&&(wb(s),r=!0)}let n=Cd(e,ao);return bb(n)&&(wb(n),r=!0),r}function kc(t,e,r,n){return{server:t,namespace:n||"default",agentId:e,role:r,autoClaimFiles:!0,autoPublishDiscoveries:!0,hookTimeout:10,lastEventCursor:0}}var ft=w(()=>{"use strict";bn()});import{readFileSync as m1,writeFileSync as h1,existsSync as Sb,mkdirSync as g1}from"node:fs";import{join as y1,dirname as v1}from"node:path";function $b(){return y1(process.cwd(),".claude","settings.local.json")}function kb(){let t=$b();if(!Sb(t))return{};try{return JSON.parse(m1(t,"utf8"))}catch{return{}}}function Eb(t){let e=$b(),r=v1(e);Sb(r)||g1(r,{recursive:!0}),h1(e,JSON.stringify(t,null,2)+`
14
- `)}function Ec(t){return t.includes("waggle-cli")||t.includes("/cli/hooks/")||t.includes(" hook ")}function ms(t=10){let e=process.argv[1],r=kb();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=>Ec(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 Tc(){let t=kb();if(t.hooks){for(let e of Object.keys(t.hooks))t.hooks[e]=t.hooks[e].filter(r=>!Ec(r.command)),t.hooks[e].length===0&&delete t.hooks[e];Object.keys(t.hooks).length===0&&delete t.hooks,Eb(t)}}var $i=w(()=>{"use strict"});import{request as _1}from"node:http";import{request as b1}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:"?b1:_1,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:w1},h=>{let y="";h.on("data",v=>y+=v),h.on("end",()=>{try{let v=y?JSON.parse(y):{};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 w1,Tb=w(()=>{w1=3e3});var et=w(()=>{Tb()});var Pb={};V(Pb,{init:()=>S1});import{createInterface as x1}from"node:readline";function Id(t,e,r){let n=r?` ${g("dim",`[${r}]`)}`:"";return new Promise(o=>{t.question(` ${e}${n}: `,s=>{o(s.trim()||r||"")})})}async function S1(t){_e()&&(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=x1({input:process.stdin,output:process.stdout});console.log(C("waggle-cli setup")),console.log(),n=await Id(d,"Server URL","http://localhost:3100"),o=await Id(d,"Namespace","default"),s=await Id(d,"Role","developer"),d.close(),console.log()}let l=hc(),u=kc(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);ms(u.hookTimeout),console.log(A("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 ${g("dim",".claude/settings.local.json")}`),console.log(" Start a Claude Code session to begin coordinating.")}var Rb=w(()=>{"use strict";nd();ft();$i();et();Ee()});var Ob={};V(Ob,{join:()=>$1});async function $1(t){_e()&&(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=hc(),c=kc(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),ms(c.hookTimeout),console.log(A("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?g("green"," (you)"):"";console.log(` ${g("bold",f.role)}: ${f.agent}${d}`)}}}catch{}console.log()}var Cb=w(()=>{"use strict";nd();ft();$i();et();Ee()});var Ib={};V(Ib,{status:()=>k1});async function k1(){let t=_e();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(` ${g("red","HALTED")}${s.reason?` \u2014 ${s.reason}`:""}`):s.paused?console.log(` ${g("yellow","PAUSED")}${s.reason?` \u2014 ${s.reason}`:""}`):console.log(` ${g("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(` ${g("dim","No active claims")}`);else{for(let c of i)console.log(` ${g("green","\u25CF")} ${c.resource} ${g("dim","(yours)")}`);for(let c of a)console.log(` ${g("yellow","\u25CF")} ${c.resource} ${g("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(` ${g("dim","No new events")}`);else{let i=s.slice(-10);for(let a of i)console.log(` ${g("dim",`#${a.id}`)} ${g("bold",a.type)} ${g("dim",`by ${a.publishedBy}`)}`);s.length>10&&console.log(` ${g("dim",`... and ${s.length-10} more`)}`)}}}catch{console.log(`
15
- ${g("yellow","Server unreachable")}`)}console.log()}var Ab=w(()=>{"use strict";ft();et();Ee()});var Nb={};V(Nb,{leave:()=>E1});async function E1(){let t=_e();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{}Tc(),xb(),console.log(A("Left coordination server. Hooks removed, config deleted."))}var zb=w(()=>{"use strict";ft();$i();et();Ee()});var Pc,Ad=w(()=>{Pc="1.0"});var jb={};V(jb,{SpecValidationError:()=>uo,normalizeAgents:()=>zd,normalizeRules:()=>ki,validateSpec:()=>Nd});function Nd(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]=Pc.split(".").map(Number);n!==o&&e.push(`Unsupported ACP version ${r.acp} (this parser supports ${Pc})`)}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 ki(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 zd(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 uo,Rc=w(()=>{Ad();uo=class extends Error{errors;constructor(e){super(`Invalid ACP spec:
3
+ var PI=Object.create;var ed=Object.defineProperty;var RI=Object.getOwnPropertyDescriptor;var OI=Object.getOwnPropertyNames;var CI=Object.getPrototypeOf,II=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),V=(t,e)=>{for(var r in e)ed(t,r,{get:e[r],enumerable:!0})},AI=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of OI(e))!II.call(t,o)&&o!==r&&ed(t,o,{get:()=>e[o],enumerable:!(n=RI(e,o))||n.enumerable});return t};var ao=(t,e,r)=>(r=t!=null?PI(CI(t)):{},AI(e||!t||!t.__esModule?ed(r,"default",{value:t,enumerable:!0}):r,t));function g(t,e){return`${eb[t]}${e}${eb.reset}`}function C(t){return`
4
+ ${g("bold",g("cyan",t))}`}function A(t){return g("green",`\u2713 ${t}`)}function ar(t){return g("yellow",`\u26A0 ${t}`)}function _(t){return g("red",`\u2717 ${t}`)}function S(t,e){return` ${g("bold",t+":")} ${e}`}function cr(t){let e=Math.max(...t.map(([r])=>r.length));return t.map(([r,n])=>` ${g("bold",r.padEnd(e))} ${n}`).join(`
5
+ `)}var eb,Te=w(()=>{"use strict";eb={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 NI}from"node:crypto";function mc(){return`wgl_${NI(4).toString("hex")}`}var td=w(()=>{"use strict"});import{join as tb}from"node:path";import{homedir as rb}from"node:os";var yt,Mr,ls,rd,us,nd,hc,co,ps,gc,od,sd,_i,id,ad,cd,ld,ud,lo=w(()=>{yt=tb(rb(),".honeyb"),Mr=tb(rb(),".wgl"),ls="auth.json",rd="integrations.json",us=".honeyb",nd=".honeybee",hc=[".wglrc.yaml",".wglrc.json",".wglrc"],co=".wgl.json",ps="session.json",gc="brood.state.json",od="logs",sd=10,_i="telemetry",id=30,ad=3e5,cd=3e5,ld={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"},ud={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 ib,writeFileSync as pd,existsSync as Ft,mkdirSync as yc,copyFileSync as dd,chmodSync as zI}from"node:fs";import{join as tr,resolve as jI}from"node:path";import{homedir as nb}from"node:os";function fd(){if(ob)return;ob=!0;let t=tr(Mr,"auth.json"),e=tr(yt,ls);Ft(t)&&!Ft(e)&&(Ft(yt)||yc(yt,{recursive:!0}),dd(t,e),zI(e,384),console.error("[honeyb] Migrated auth store: ~/.wgl/auth.json \u2192 ~/.honeyb/auth.json"));let r=tr(Mr,"config.json"),n=nb(),o=tr(n,".wglrc.json");if(Ft(r)&&!Ft(o))try{let a=JSON.parse(ib(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&&(pd(o,JSON.stringify(c,null,2)+`
6
+ `),console.error("[honeyb] Migrated global config: ~/.wgl/config.json \u2192 ~/.wglrc.json"))}catch{}let s=tr(nb(),".config","honeybee","integrations.json"),i=tr(yt,rd);Ft(s)&&!Ft(i)&&(Ft(yt)||yc(yt,{recursive:!0}),dd(s,i),console.error("[honeyb] Migrated integrations: ~/.config/honeybee/integrations.json \u2192 ~/.honeyb/integrations.json"))}function md(t){let e=jI(t||process.cwd());if(sb.has(e))return;sb.add(e);let r=tr(e,co),n=tr(e,".wglrc.json"),o=tr(e,us),s=tr(o,ps);if(Ft(r)&&!Ft(n))try{let l=JSON.parse(ib(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&&pd(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&&(Ft(o)||yc(o,{recursive:!0}),pd(s,JSON.stringify(p,null,2)+`
8
+ `)),console.error("[honeyb] Migrated project config: .wgl.json \u2192 .wglrc.json + .honeyb/session.json")}catch{}let i=tr(e,nd),a=tr(i,"brood.state.json"),c=tr(o,gc);Ft(a)&&!Ft(c)&&(Ft(o)||yc(o,{recursive:!0}),dd(a,c),console.error("[honeyb] Migrated brood state: .honeybee/brood.state.json \u2192 .honeyb/brood.state.json"))}var ob,sb,hd=w(()=>{lo();ob=!1,sb=new Set});import{readFileSync as yd,writeFileSync as DI,existsSync as bn,mkdirSync as vc,readdirSync as qI,unlinkSync as ZI}from"node:fs";import{join as kr,dirname as ab,resolve as bi,sep as UI}from"node:path";import{homedir as FI}from"node:os";function vd(t){let e=bi(t||process.cwd()),r=UI==="/"?"/":e.slice(0,3);for(;;){for(let o of hc){let s=kr(e,o);if(bn(s))return s}let n=ab(e);if(n===e||e===r)return null;e=n}}function cb(){let t=FI();for(let e of hc){let r=kr(t,e);if(bn(r))return r}return null}function gd(t){let e=yd(t,"utf8").trim();return e?t.endsWith(".yaml")?HI(e):t.endsWith(".json")?lb(e):GI(e):{}}function lb(t){try{let e=JSON.parse(t);return typeof e!="object"||e===null||Array.isArray(e)?{}:e}catch{return{}}}function HI(t){try{return BI(t)}catch{return lb(t)}}function BI(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]=_d(l)}return e}function GI(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();wi(e,s,_d(i))}return e}function _d(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 wi(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 _c(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 _n(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]=_n(s,o):r[n]=o}return r}function VI(){let t={};for(let[e,r]of Object.entries(ld)){let n=process.env[e];n!==void 0&&n!==""&&wi(t,r,_d(n))}return t}function Lr(t){fd(),md(t);let e=structuredClone(ud),r=cb();r&&(e=_n(e,gd(r)));let n=vd(t);if(n&&(e=_n(e,gd(n))),!n){let o=WI(t);if(o){let s=JI(o);s&&(e=_n(e,s))}}return e=_n(e,VI()),Object.freeze(e)}function bc(){return bn(yt)||vc(yt,{recursive:!0}),yt}function ub(t){return bi(t||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}function ds(t){let e=ub(t),r=kr(bc(),"projects",e);return bn(r)||vc(r,{recursive:!0}),r}function pb(t){let e=bi(t||process.cwd()),r=kr(e,us);return bn(r)||vc(r,{recursive:!0}),r}function bd(t){let e=kr(bi(t||process.cwd()),us),r=kr(e,ps);if(!bn(r))return{};try{return JSON.parse(yd(r,"utf8"))}catch{return{}}}function wd(t,e){let r=pb(e),n=kr(r,ps);DI(n,JSON.stringify(t,null,2)+`
11
+ `)}function wn(t){let e=kr(ds(t),od);return bn(e)||vc(e,{recursive:!0}),e}function xd(t){let e=wn(t),r=new Date().toISOString().replace(/[:.]/g,"-");return kr(e,`${r}.jsonl`)}function Sd(t){let e=wn(t);try{let r=qI(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();for(let n=sd;n<r.length;n++)ZI(kr(e,r[n]))}catch{}}function WI(t){let e=bi(t||process.cwd()),r="/";for(;;){let n=kr(e,co);if(bn(n))return n;let o=ab(e);if(o===e||e===r)return null;e=o}}function JI(t){try{let e=JSON.parse(yd(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 wc=w(()=>{lo();hd()});import{readFileSync as KI,writeFileSync as YI,existsSync as xc,mkdirSync as XI,chmodSync as QI}from"node:fs";import{join as $d}from"node:path";function e1(){let t=$d(yt,ls);if(xc(t))return t;let e=$d(Mr,"auth.json");return xc(e)?e:t}function uo(){let t=e1();if(!xc(t))return{profiles:{}};try{return JSON.parse(KI(t,"utf8"))}catch{return{profiles:{}}}}function xi(t){xc(yt)||XI(yt,{recursive:!0});let e=$d(yt,ls);YI(e,JSON.stringify(t,null,2)+`
12
+ `,{mode:384}),QI(e,384)}function kd(t){return uo().profiles[t]||null}function Ed(t,e){let r=uo();r.profiles[t]=e,xi(r)}function Td(t){let e=uo();return t in e.profiles?(delete e.profiles[t],xi(e),!0):!1}function Pd(){let t=uo();return Object.keys(t.profiles)}var db=w(()=>{lo()});var xn=w(()=>{lo();wc();db();hd()});import{writeFileSync as t1,existsSync as fb,unlinkSync as mb}from"node:fs";import{join as Rd}from"node:path";function _e(t){let e=Lr(t),r=bd(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 Sc(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=Rd(r,".wglrc.json");t1(o,JSON.stringify(n,null,2)+`
13
+ `);let s={agentId:t.agentId,lastEventCursor:t.lastEventCursor,autoPublishDiscoveries:t.autoPublishDiscoveries};return wd(s,r),o}function hb(t){let e=t||process.cwd(),r=!1;for(let o of[".wglrc.json",".wglrc.yaml",".wglrc"]){let s=Rd(e,o);fb(s)&&(mb(s),r=!0)}let n=Rd(e,co);return fb(n)&&(mb(n),r=!0),r}function $c(t,e,r,n){return{server:t,namespace:n||"default",agentId:e,role:r,autoClaimFiles:!0,autoPublishDiscoveries:!0,hookTimeout:10,lastEventCursor:0}}var mt=w(()=>{"use strict";xn()});import{readFileSync as r1,writeFileSync as n1,existsSync as gb,mkdirSync as o1}from"node:fs";import{join as s1,dirname as i1}from"node:path";function yb(){return s1(process.cwd(),".claude","settings.local.json")}function vb(){let t=yb();if(!gb(t))return{};try{return JSON.parse(r1(t,"utf8"))}catch{return{}}}function _b(t){let e=yb(),r=i1(e);gb(r)||o1(r,{recursive:!0}),n1(e,JSON.stringify(t,null,2)+`
14
+ `)}function kc(t){return t.includes("waggle-cli")||t.includes("/cli/hooks/")||t.includes(" hook ")}function fs(t=10){let e=process.argv[1],r=vb();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=>kc(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)}}_b(r)}function Ec(){let t=vb();if(t.hooks){for(let e of Object.keys(t.hooks))t.hooks[e]=t.hooks[e].filter(r=>!kc(r.command)),t.hooks[e].length===0&&delete t.hooks[e];Object.keys(t.hooks).length===0&&delete t.hooks,_b(t)}}var Si=w(()=>{"use strict"});import{request as a1}from"node:http";import{request as c1}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:"?c1:a1,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:l1},h=>{let y="";h.on("data",v=>y+=v),h.on("end",()=>{try{let v=y?JSON.parse(y):{};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 l1,bb=w(()=>{l1=3e3});var et=w(()=>{bb()});var wb={};V(wb,{init:()=>p1});import{createInterface as u1}from"node:readline";function Od(t,e,r){let n=r?` ${g("dim",`[${r}]`)}`:"";return new Promise(o=>{t.question(` ${e}${n}: `,s=>{o(s.trim()||r||"")})})}async function p1(t){_e()&&(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=u1({input:process.stdin,output:process.stdout});console.log(C("waggle-cli setup")),console.log(),n=await Od(d,"Server URL","http://localhost:3100"),o=await Od(d,"Namespace","default"),s=await Od(d,"Role","developer"),d.close(),console.log()}let l=mc(),u=$c(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=Sc(u);fs(u.hookTimeout),console.log(A("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 ${g("dim",".claude/settings.local.json")}`),console.log(" Start a Claude Code session to begin coordinating.")}var xb=w(()=>{"use strict";td();mt();Si();et();Te()});var Sb={};V(Sb,{join:()=>d1});async function d1(t){_e()&&(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=mc(),c=$c(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{}Sc(c),fs(c.hookTimeout),console.log(A("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?g("green"," (you)"):"";console.log(` ${g("bold",f.role)}: ${f.agent}${d}`)}}}catch{}console.log()}var $b=w(()=>{"use strict";td();mt();Si();et();Te()});var kb={};V(kb,{status:()=>f1});async function f1(){let t=_e();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(` ${g("red","HALTED")}${s.reason?` \u2014 ${s.reason}`:""}`):s.paused?console.log(` ${g("yellow","PAUSED")}${s.reason?` \u2014 ${s.reason}`:""}`):console.log(` ${g("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(` ${g("dim","No active claims")}`);else{for(let c of i)console.log(` ${g("green","\u25CF")} ${c.resource} ${g("dim","(yours)")}`);for(let c of a)console.log(` ${g("yellow","\u25CF")} ${c.resource} ${g("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(` ${g("dim","No new events")}`);else{let i=s.slice(-10);for(let a of i)console.log(` ${g("dim",`#${a.id}`)} ${g("bold",a.type)} ${g("dim",`by ${a.publishedBy}`)}`);s.length>10&&console.log(` ${g("dim",`... and ${s.length-10} more`)}`)}}}catch{console.log(`
15
+ ${g("yellow","Server unreachable")}`)}console.log()}var Eb=w(()=>{"use strict";mt();et();Te()});var Tb={};V(Tb,{leave:()=>m1});async function m1(){let t=_e();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{}Ec(),hb(),console.log(A("Left coordination server. Hooks removed, config deleted."))}var Pb=w(()=>{"use strict";mt();Si();et();Te()});var Tc,Cd=w(()=>{Tc="1.0"});var Rb={};V(Rb,{SpecValidationError:()=>po,normalizeAgents:()=>Ad,normalizeRules:()=>$i,validateSpec:()=>Id});function Id(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]=Tc.split(".").map(Number);n!==o&&e.push(`Unsupported ACP version ${r.acp} (this parser supports ${Tc})`)}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 $i(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 Ad(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 po,Pc=w(()=>{Cd();po=class extends Error{errors;constructor(e){super(`Invalid ACP spec:
16
16
  - ${e.join(`
17
- - `)}`),this.errors=e,this.name="SpecValidationError"}}});import{readFile as T1}from"node:fs/promises";async function P1(){if(!Ei)try{let{createRequire:t}=await import("node:module");Ei=t(import.meta.url)("js-yaml")}catch{}}function R1(t){if(Ei)return Ei.load(t,{schema:Ei.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 po(t,e){let{validateSpec:r,SpecValidationError:n}=await Promise.resolve().then(()=>(Rc(),jb));await P1();let o=R1(t);(e?.variables||o&&typeof o=="object"&&o.variables)&&(o=Mb(o,e?.variables??{}));let s=r(o);if(s.length>0)throw new n(s);return o}async function Oc(t,e){let r=await T1(t,"utf-8");return po(r,e)}function Mb(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 jd(t,o)}function jd(t,e){if(typeof t=="string"){let r=t.match(O1);if(r){let n=r[1];if(n in e)return e[n]}return t}if(Array.isArray(t))return t.map(r=>jd(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=jd(o,e);return r}return t}var Ei,O1,Md=w(()=>{Rc();O1=/^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$/});async function Ld(t,e,r,n){let o=await e.events.getCursor(),i=(await e.claims.list()).map(y=>y.resource),a=await e.discoveries.search(),c=new Set(a.map(y=>y.topic)),l=null;if(t.resources?.instances){let y=new Set(i);for(let v of t.resources.instances)if(!y.has(v)&&!c.has(v)){l=v;break}}let u=e.roles?await e.roles.getAssignments():[],p=u.find(y=>y.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(y=>y.topic),...l!==null?{$next_unclaimed:l}:{},...n}}function Ti(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 Dd=w(()=>{});function Cc(t,e,r){return ki(t.rules)[e]?.[r]??{steps:[]}}function C1(t,e,r,n){let o=e+1,s=n(t.action),i=t.description?` \u2014 ${Ti(t.description,r)}`:"",a=t.hint?`
19
- Hint: ${Ti(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"?Ti(p,r):p;c+=`
17
+ - `)}`),this.errors=e,this.name="SpecValidationError"}}});import{readFile as h1}from"node:fs/promises";async function g1(){if(!ki)try{let{createRequire:t}=await import("node:module");ki=t(import.meta.url)("js-yaml")}catch{}}function y1(t){if(ki)return ki.load(t,{schema:ki.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 fo(t,e){let{validateSpec:r,SpecValidationError:n}=await Promise.resolve().then(()=>(Pc(),Rb));await g1();let o=y1(t);(e?.variables||o&&typeof o=="object"&&o.variables)&&(o=Ob(o,e?.variables??{}));let s=r(o);if(s.length>0)throw new n(s);return o}async function Rc(t,e){let r=await h1(t,"utf-8");return fo(r,e)}function Ob(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 Nd(t,o)}function Nd(t,e){if(typeof t=="string"){let r=t.match(v1);if(r){let n=r[1];if(n in e)return e[n]}return t}if(Array.isArray(t))return t.map(r=>Nd(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=Nd(o,e);return r}return t}var ki,v1,zd=w(()=>{Pc();v1=/^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$/});async function jd(t,e,r,n){let o=await e.events.getCursor(),i=(await e.claims.list()).map(y=>y.resource),a=await e.discoveries.search(),c=new Set(a.map(y=>y.topic)),l=null;if(t.resources?.instances){let y=new Set(i);for(let v of t.resources.instances)if(!y.has(v)&&!c.has(v)){l=v;break}}let u=e.roles?await e.roles.getAssignments():[],p=u.find(y=>y.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(y=>y.topic),...l!==null?{$next_unclaimed:l}:{},...n}}function Ei(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 Md=w(()=>{});function Oc(t,e,r){return $i(t.rules)[e]?.[r]??{steps:[]}}function _1(t,e,r,n){let o=e+1,s=n(t.action),i=t.description?` \u2014 ${Ei(t.description,r)}`:"",a=t.hint?`
19
+ Hint: ${Ei(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"?Ei(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 I1(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 b1(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 A1(t){if(!t)return"";let e=[`
30
+ `):""}function w1(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 N1(t){if(!t)return"";let e=[`
34
+ `)}function x1(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 z1(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 S1(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 j1(t){if(!t||t.length===0)return"";let e=[`
43
+ `):""}function $1(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 qd(t,e,r,n,o){let s=o?.toolMapping??Lb,i=d=>s[d]??d,a=t.roles[e],c=t.phases[r],l=Cc(t,e,r),u=[];u.push(`# ${t.title}`),t.description&&u.push(`
47
+ `)}function Ld(t,e,r,n,o){let s=o?.toolMapping??Cb,i=d=>s[d]??d,a=t.roles[e],c=t.phases[r],l=Oc(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(`
@@ -52,53 +52,53 @@ ${t.description}`),u.push(`
52
52
  `);let p=Object.keys(t.phases);for(let d of p){let m=t.phases[d],h=d===r?" **(current)**":"",y=m.terminal?" (terminal)":"";u.push(`- **${d}**${h}: ${m.description}${y}`)}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(C1(l.steps[d],d,n,i))}else c.terminal?u.push(`
55
+ `);for(let d=0;d<l.steps.length;d++)u.push(_1(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(I1(t.resources)),u.push(A1(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(b1(t.resources)),u.push(w1(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(j1(n.$team)),u.push(N1(t.governance)),u.push(z1(t.topics));let f=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($1(n.$team)),u.push(x1(t.governance)),u.push(S1(t.topics));let f=i("getProtocol");return u.push(`
64
64
 
65
65
  ## Phase Transitions
66
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 Lb,Db=w(()=>{Md();Dd();Lb={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 Pi=w(()=>{Ad();Rc();Md();Dd();Db()});function tw(t){return typeof t>"u"||t===null}function M1(t){return typeof t=="object"&&t!==null}function L1(t){return Array.isArray(t)?t:tw(t)?[]:[t]}function D1(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 q1(t,e){var r="",n;for(n=0;n<e;n+=1)r+=t;return r}function Z1(t){return t===0&&Number.NEGATIVE_INFINITY===1/t}function rw(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
-
72
- `+t.mark.snippet),n+" "+r):n}function Oi(t,e){Error.call(this),this.name="YAMLException",this.reason=t,this.mark=e,this.message=rw(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}function Zd(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 Ud(t,e){return lt.repeat(" ",e-t.length)+t}function W1(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=Zd(t.buffer,n[i-c],o[i-c],t.position-(n[i]-n[i-c]),p),a=lt.repeat(" ",e.indent)+Ud((t.line-c+1).toString(),u)+" | "+l.str+`
73
- `+a;for(l=Zd(t.buffer,n[i],o[i],t.position,p),a+=lt.repeat(" ",e.indent)+Ud((t.line+1).toString(),u)+" | "+l.str+`
74
- `,a+=lt.repeat("-",e.indent+u+3+l.pos)+`^
75
- `,c=1;c<=e.linesAfter&&!(i+c>=o.length);c++)l=Zd(t.buffer,n[i+c],o[i+c],t.position-(n[i]-n[i+c]),p),a+=lt.repeat(" ",e.indent)+Ud((t.line+c+1).toString(),u)+" | "+l.str+`
76
- `;return a.replace(/\n$/,"")}function X1(t){var e={};return t!==null&&Object.keys(t).forEach(function(r){t[r].forEach(function(n){e[String(n)]=r})}),e}function Q1(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(K1.indexOf(r)===-1)throw new Nt('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=X1(e.styleAliases||null),Y1.indexOf(this.kind)===-1)throw new Nt('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}function qb(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 eA(){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 Hd(t){return this.extend(t)}function tA(t){if(t===null)return!0;var e=t.length;return e===1&&t==="~"||e===4&&(t==="null"||t==="Null"||t==="NULL")}function rA(){return null}function nA(t){return t===null}function oA(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 sA(t){return t==="true"||t==="True"||t==="TRUE"}function iA(t){return Object.prototype.toString.call(t)==="[object Boolean]"}function aA(t){return 48<=t&&t<=57||65<=t&&t<=70||97<=t&&t<=102}function cA(t){return 48<=t&&t<=55}function lA(t){return 48<=t&&t<=57}function uA(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(!aA(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}if(o==="o"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!cA(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}}if(o==="_")return!1;for(;r<e;r++)if(o=t[r],o!=="_"){if(!lA(t.charCodeAt(r)))return!1;n=!0}return!(!n||o==="_")}function pA(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 dA(t){return Object.prototype.toString.call(t)==="[object Number]"&&t%1===0&&!lt.isNegativeZero(t)}function mA(t){return!(t===null||!fA.test(t)||t[t.length-1]==="_")}function hA(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 yA(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),gA.test(r)?r.replace("e",".e"):r}function vA(t){return Object.prototype.toString.call(t)==="[object Number]"&&(t%1!==0||lt.isNegativeZero(t))}function _A(t){return t===null?!1:mw.exec(t)!==null||hw.exec(t)!==null}function bA(t){var e,r,n,o,s,i,a,c=0,l=null,u,p,f;if(e=mw.exec(t),e===null&&(e=hw.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 wA(t){return t.toISOString()}function xA(t){return t==="<<"||t===null}function SA(t){if(t===null)return!1;var e,r,n=0,o=t.length,s=Jd;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 $A(t){var e,r,n=t.replace(/[\r\n=]/g,""),o=n.length,s=Jd,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 kA(t){var e="",r=0,n,o,s=t.length,i=Jd;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 EA(t){return Object.prototype.toString.call(t)==="[object Uint8Array]"}function RA(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,PA.call(o)!=="[object Object]")return!1;for(s in o)if(TA.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 OA(t){return t!==null?t:[]}function IA(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],CA.call(n)!=="[object Object]"||(o=Object.keys(n),o.length!==1))return!1;s[e]=[o[0],n[o[0]]]}return!0}function AA(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 zA(t){if(t===null)return!0;var e,r=t;for(e in r)if(NA.call(r,e)&&r[e]!==null)return!1;return!0}function jA(t){return t!==null?t:{}}function Ub(t){return Object.prototype.toString.call(t)}function Mr(t){return t===10||t===13}function mo(t){return t===9||t===32}function Ut(t){return t===9||t===32||t===10||t===13}function gs(t){return t===44||t===91||t===93||t===123||t===125}function ZA(t){var e;return 48<=t&&t<=57?t-48:(e=t|32,97<=e&&e<=102?e-97+10:-1)}function UA(t){return t===120?2:t===117?4:t===85?8:0}function FA(t){return 48<=t&&t<=57?t-48:-1}function Fb(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 HA(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 BA(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||Kd,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 Rw(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=J1(r),new Nt(e,r)}function H(t,e){throw Rw(t,e)}function Nc(t,e){t.onWarning&&t.onWarning.call(null,Rw(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 LA.test(a)&&H(t,"the stream contains non-printable characters");t.result+=a}}function Bb(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 ys(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"&&Ub(o[l])==="[object Object]"&&(o[l]="[object Object]");if(typeof o=="object"&&Ub(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)Bb(t,e,s[l],r);else Bb(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 Yd(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(;mo(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(Mr(o))for(Yd(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&&Nc(t,"deficient indentation"),n}function Mc(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||Ut(r)))}function Xd(t,e){e===1?t.result+=" ":e>1&&(t.result+=lt.repeat(`
78
- `,e-1))}function GA(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),Ut(d)||gs(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),Ut(o)||r&&gs(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),Ut(o)||r&&gs(o))break}else if(d===35){if(n=t.input.charCodeAt(t.position-1),Ut(n))break}else{if(t.position===t.lineStart&&Mc(t)||r&&gs(d))break;if(Mr(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),Xd(t,t.line-c),s=i=t.position,a=!1),mo(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 VA(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 Mr(r)?(wn(t,n,o,!0),Xd(t,it(t,!1,e)),n=o=t.position):t.position===t.lineStart&&Mc(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 WA(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),Mr(a))it(t,!1,e);else if(a<256&&Tw[a])t.result+=Pw[a],t.position++;else if((i=UA(a))>0){for(o=i,s=0;o>0;o--)a=t.input.charCodeAt(++t.position),(i=ZA(a))>=0?s=(s<<4)+i:H(t,"expected hexadecimal character");t.result+=HA(s),t.position++}else H(t,"unknown escape sequence");r=n=t.position}else Mr(a)?(wn(t,r,n,!0),Xd(t,it(t,!1,e)),r=n=t.position):t.position===t.lineStart&&Mc(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 JA(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,y,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"),y=h=v=null,p=f=!1,b===63&&(l=t.input.charCodeAt(t.position+1),Ut(l)&&(p=f=!0,t.position++,it(t,!0,e))),n=t.line,o=t.lineStart,s=t.position,vs(t,e,Ic,!1,!0),y=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),vs(t,e,Ic,!1,!0),v=t.result),d?ys(t,a,m,y,h,v,n,o,s):p?a.push(ys(t,null,m,y,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 KA(t,e){var r,n,o=Fd,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)Fd===o?o=p===43?Zb:MA:H(t,"repeat of a chomping mode identifier");else if((u=FA(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(mo(p)){do p=t.input.charCodeAt(++t.position);while(mo(p));if(p===35)do p=t.input.charCodeAt(++t.position);while(!Mr(p)&&p!==0)}for(;p!==0;){for(Yd(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),Mr(p)){c++;continue}if(t.lineIndent<a){o===Zb?t.result+=lt.repeat(`
79
- `,s?1+c:c):o===Fd&&s&&(t.result+=`
80
- `);break}for(n?mo(p)?(l=!0,t.result+=lt.repeat(`
81
- `,s?1+c:c)):l?(l=!1,t.result+=lt.repeat(`
82
- `,c+1)):c===0?s&&(t.result+=" "):t.result+=lt.repeat(`
83
- `,c):t.result+=lt.repeat(`
84
- `,s?1+c:c),s=!0,i=!0,c=0,r=t.position;!Mr(p)&&p!==0;)p=t.input.charCodeAt(++t.position);wn(t,r,t.position,!1)}return!0}function Gb(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),!Ut(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,vs(t,e,Sw,!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 YA(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,y=!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(!y&&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)&&Ut(n))b===63?(y&&(ys(t,p,f,d,m,null,i,a,c),d=m=h=null),v=!0,y=!0,o=!0):y?(y=!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,!vs(t,r,xw,!1,!0))break;if(t.line===s){for(b=t.input.charCodeAt(t.position);mo(b);)b=t.input.charCodeAt(++t.position);if(b===58)b=t.input.charCodeAt(++t.position),Ut(b)||H(t,"a whitespace character is expected after the key-value separator within a block mapping"),y&&(ys(t,p,f,d,m,null,i,a,c),d=m=h=null),v=!0,y=!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)&&(y&&(i=t.line,a=t.lineStart,c=t.position),vs(t,e,Ac,!0,o)&&(y?m=t.result:h=t.result),y||(ys(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 y&&ys(t,p,f,d,m,null,i,a,c),v&&(t.tag=l,t.anchor=u,t.kind="mapping",t.result=p),v}function XA(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&&!Ut(i);)i===33&&(n?H(t,"tag suffix cannot contain exclamation marks"):(o=t.input.slice(e-1,t.position+1),$w.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),qA.test(s)&&H(t,"tag suffix cannot contain flow indicator characters")}s&&!kw.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 QA(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&&!Ut(r)&&!gs(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 eN(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&&!Ut(n)&&!gs(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 vs(t,e,r,n,o){var s,i,a,c=1,l=!1,u=!1,p,f,d,m,h,y;if(t.listener!==null&&t.listener("open",t),t.tag=null,t.anchor=null,t.kind=null,t.result=null,s=i=a=Ac===r||Sw===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(;XA(t)||QA(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||Ac===r)&&(Ic===r||xw===r?h=e:h=e+1,y=t.position-t.lineStart,c===1?a&&(Gb(t,y)||YA(t,y,h))||JA(t,h)?u=!0:(i&&KA(t,h)||VA(t,h)||WA(t,h)?u=!0:eN(t)?(u=!0,(t.tag!==null||t.anchor!==null)&&H(t,"alias node should not have any properties")):GA(t,h,Ic===r)&&(u=!0,t.tag===null&&(t.tag="?")),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):c===0&&(u=a&&Gb(t,y))),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 tN(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&&!Ut(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(;mo(i);)i=t.input.charCodeAt(++t.position);if(i===35){do i=t.input.charCodeAt(++t.position);while(i!==0&&!Mr(i));break}if(Mr(i))break;for(r=t.position;i!==0&&!Ut(i);)i=t.input.charCodeAt(++t.position);o.push(t.input.slice(r,t.position))}i!==0&&Yd(t),xn.call(Hb,n)?Hb[n](t,n,o):Nc(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"),vs(t,t.lineIndent-1,Ac,!1,!0),it(t,!0,-1),t.checkLineBreaks&&DA.test(t.input.slice(e,t.position))&&Nc(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&Mc(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 BA(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;)tN(r);return r.documents}function rN(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 nN(t,e){var r=Ow(t,e);if(r.length!==0){if(r.length===1)return r[0];throw new Nt("expected a single document in the stream, but found more")}}function $N(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 kN(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 Nt("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+r+lt.repeat("0",n-e.length)+e}function TN(t){this.schema=t.schema||Kd,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=$N(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==='"'?Ii:EN,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 Vb(t,e){for(var r=lt.repeat(" ",e),n=0,o=-1,s="",i,a=t.length;n<a;)o=t.indexOf(`
70
+ `)}var Cb,Ib=w(()=>{zd();Md();Cb={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 Ti=w(()=>{Cd();Pc();zd();Md();Ib()});function Wb(t){return typeof t>"u"||t===null}function k1(t){return typeof t=="object"&&t!==null}function E1(t){return Array.isArray(t)?t:Wb(t)?[]:[t]}function T1(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 P1(t,e){var r="",n;for(n=0;n<e;n+=1)r+=t;return r}function R1(t){return t===0&&Number.NEGATIVE_INFINITY===1/t}function Jb(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
+
72
+ `+t.mark.snippet),n+" "+r):n}function Ri(t,e){Error.call(this),this.name="YAMLException",this.reason=t,this.mark=e,this.message=Jb(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}function Dd(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 qd(t,e){return ut.repeat(" ",e-t.length)+t}function j1(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=Dd(t.buffer,n[i-c],o[i-c],t.position-(n[i]-n[i-c]),p),a=ut.repeat(" ",e.indent)+qd((t.line-c+1).toString(),u)+" | "+l.str+`
73
+ `+a;for(l=Dd(t.buffer,n[i],o[i],t.position,p),a+=ut.repeat(" ",e.indent)+qd((t.line+1).toString(),u)+" | "+l.str+`
74
+ `,a+=ut.repeat("-",e.indent+u+3+l.pos)+`^
75
+ `,c=1;c<=e.linesAfter&&!(i+c>=o.length);c++)l=Dd(t.buffer,n[i+c],o[i+c],t.position-(n[i]-n[i+c]),p),a+=ut.repeat(" ",e.indent)+qd((t.line+c+1).toString(),u)+" | "+l.str+`
76
+ `;return a.replace(/\n$/,"")}function q1(t){var e={};return t!==null&&Object.keys(t).forEach(function(r){t[r].forEach(function(n){e[String(n)]=r})}),e}function Z1(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(L1.indexOf(r)===-1)throw new jt('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=q1(e.styleAliases||null),D1.indexOf(this.kind)===-1)throw new jt('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}function Ab(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 U1(){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 Ud(t){return this.extend(t)}function F1(t){if(t===null)return!0;var e=t.length;return e===1&&t==="~"||e===4&&(t==="null"||t==="Null"||t==="NULL")}function H1(){return null}function B1(t){return t===null}function G1(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 V1(t){return t==="true"||t==="True"||t==="TRUE"}function W1(t){return Object.prototype.toString.call(t)==="[object Boolean]"}function J1(t){return 48<=t&&t<=57||65<=t&&t<=70||97<=t&&t<=102}function K1(t){return 48<=t&&t<=55}function Y1(t){return 48<=t&&t<=57}function X1(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(!J1(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}if(o==="o"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!K1(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}}if(o==="_")return!1;for(;r<e;r++)if(o=t[r],o!=="_"){if(!Y1(t.charCodeAt(r)))return!1;n=!0}return!(!n||o==="_")}function Q1(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 eA(t){return Object.prototype.toString.call(t)==="[object Number]"&&t%1===0&&!ut.isNegativeZero(t)}function rA(t){return!(t===null||!tA.test(t)||t[t.length-1]==="_")}function nA(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 sA(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(ut.isNegativeZero(t))return"-0.0";return r=t.toString(10),oA.test(r)?r.replace("e",".e"):r}function iA(t){return Object.prototype.toString.call(t)==="[object Number]"&&(t%1!==0||ut.isNegativeZero(t))}function aA(t){return t===null?!1:aw.exec(t)!==null||cw.exec(t)!==null}function cA(t){var e,r,n,o,s,i,a,c=0,l=null,u,p,f;if(e=aw.exec(t),e===null&&(e=cw.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 lA(t){return t.toISOString()}function uA(t){return t==="<<"||t===null}function pA(t){if(t===null)return!1;var e,r,n=0,o=t.length,s=Vd;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 dA(t){var e,r,n=t.replace(/[\r\n=]/g,""),o=n.length,s=Vd,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 fA(t){var e="",r=0,n,o,s=t.length,i=Vd;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 mA(t){return Object.prototype.toString.call(t)==="[object Uint8Array]"}function yA(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,gA.call(o)!=="[object Object]")return!1;for(s in o)if(hA.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 vA(t){return t!==null?t:[]}function bA(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],_A.call(n)!=="[object Object]"||(o=Object.keys(n),o.length!==1))return!1;s[e]=[o[0],n[o[0]]]}return!0}function wA(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 SA(t){if(t===null)return!0;var e,r=t;for(e in r)if(xA.call(r,e)&&r[e]!==null)return!1;return!0}function $A(t){return t!==null?t:{}}function zb(t){return Object.prototype.toString.call(t)}function Dr(t){return t===10||t===13}function ho(t){return t===9||t===32}function Ht(t){return t===9||t===32||t===10||t===13}function hs(t){return t===44||t===91||t===93||t===123||t===125}function RA(t){var e;return 48<=t&&t<=57?t-48:(e=t|32,97<=e&&e<=102?e-97+10:-1)}function OA(t){return t===120?2:t===117?4:t===85?8:0}function CA(t){return 48<=t&&t<=57?t-48:-1}function jb(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 IA(t){return t<=65535?String.fromCharCode(t):String.fromCharCode((t-65536>>10)+55296,(t-65536&1023)+56320)}function _w(t,e,r){e==="__proto__"?Object.defineProperty(t,e,{configurable:!0,enumerable:!0,writable:!0,value:r}):t[e]=r}function AA(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||Wd,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 xw(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=M1(r),new jt(e,r)}function B(t,e){throw xw(t,e)}function Ac(t,e){t.onWarning&&t.onWarning.call(null,xw(t,e))}function Sn(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||B(t,"expected valid JSON character");else EA.test(a)&&B(t,"the stream contains non-printable characters");t.result+=a}}function Lb(t,e,r,n){var o,s,i,a;for(ut.isObject(r)||B(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],$n.call(e,s)||(_w(e,s,r[s]),n[s]=!0)}function gs(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])&&B(t,"nested arrays are not supported inside keys"),typeof o=="object"&&zb(o[l])==="[object Object]"&&(o[l]="[object Object]");if(typeof o=="object"&&zb(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)Lb(t,e,s[l],r);else Lb(t,e,s,r);else!t.json&&!$n.call(r,o)&&$n.call(e,o)&&(t.line=i||t.line,t.lineStart=a||t.lineStart,t.position=c||t.position,B(t,"duplicated mapping key")),_w(e,o,s),delete r[o];return e}function Jd(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++):B(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(;ho(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(Dr(o))for(Jd(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&&Ac(t,"deficient indentation"),n}function jc(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||Ht(r)))}function Kd(t,e){e===1?t.result+=" ":e>1&&(t.result+=ut.repeat(`
78
+ `,e-1))}function NA(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),Ht(d)||hs(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),Ht(o)||r&&hs(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),Ht(o)||r&&hs(o))break}else if(d===35){if(n=t.input.charCodeAt(t.position-1),Ht(n))break}else{if(t.position===t.lineStart&&jc(t)||r&&hs(d))break;if(Dr(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&&(Sn(t,s,i,!1),Kd(t,t.line-c),s=i=t.position,a=!1),ho(d)||(i=t.position+1),d=t.input.charCodeAt(++t.position)}return Sn(t,s,i,!1),t.result?!0:(t.kind=p,t.result=f,!1)}function zA(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(Sn(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 Dr(r)?(Sn(t,n,o,!0),Kd(t,it(t,!1,e)),n=o=t.position):t.position===t.lineStart&&jc(t)?B(t,"unexpected end of the document within a single quoted scalar"):(t.position++,o=t.position);B(t,"unexpected end of the stream within a single quoted scalar")}function jA(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 Sn(t,r,t.position,!0),t.position++,!0;if(a===92){if(Sn(t,r,t.position,!0),a=t.input.charCodeAt(++t.position),Dr(a))it(t,!1,e);else if(a<256&&bw[a])t.result+=ww[a],t.position++;else if((i=OA(a))>0){for(o=i,s=0;o>0;o--)a=t.input.charCodeAt(++t.position),(i=RA(a))>=0?s=(s<<4)+i:B(t,"expected hexadecimal character");t.result+=IA(s),t.position++}else B(t,"unknown escape sequence");r=n=t.position}else Dr(a)?(Sn(t,r,n,!0),Kd(t,it(t,!1,e)),r=n=t.position):t.position===t.lineStart&&jc(t)?B(t,"unexpected end of the document within a double quoted scalar"):(t.position++,n=t.position)}B(t,"unexpected end of the stream within a double quoted scalar")}function MA(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,y,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&&B(t,"expected the node content, but found ','"):B(t,"missed comma between flow collection entries"),y=h=v=null,p=f=!1,b===63&&(l=t.input.charCodeAt(t.position+1),Ht(l)&&(p=f=!0,t.position++,it(t,!0,e))),n=t.line,o=t.lineStart,s=t.position,ys(t,e,Cc,!1,!0),y=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),ys(t,e,Cc,!1,!0),v=t.result),d?gs(t,a,m,y,h,v,n,o,s):p?a.push(gs(t,null,m,y,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}B(t,"unexpected end of the stream within a flow collection")}function LA(t,e){var r,n,o=Zd,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)Zd===o?o=p===43?Nb:kA:B(t,"repeat of a chomping mode identifier");else if((u=CA(p))>=0)u===0?B(t,"bad explicit indentation width of a block scalar; it cannot be less than one"):i?B(t,"repeat of an indentation width identifier"):(a=e+u-1,i=!0);else break;if(ho(p)){do p=t.input.charCodeAt(++t.position);while(ho(p));if(p===35)do p=t.input.charCodeAt(++t.position);while(!Dr(p)&&p!==0)}for(;p!==0;){for(Jd(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),Dr(p)){c++;continue}if(t.lineIndent<a){o===Nb?t.result+=ut.repeat(`
79
+ `,s?1+c:c):o===Zd&&s&&(t.result+=`
80
+ `);break}for(n?ho(p)?(l=!0,t.result+=ut.repeat(`
81
+ `,s?1+c:c)):l?(l=!1,t.result+=ut.repeat(`
82
+ `,c+1)):c===0?s&&(t.result+=" "):t.result+=ut.repeat(`
83
+ `,c):t.result+=ut.repeat(`
84
+ `,s?1+c:c),s=!0,i=!0,c=0,r=t.position;!Dr(p)&&p!==0;)p=t.input.charCodeAt(++t.position);Sn(t,r,t.position,!1)}return!0}function Db(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,B(t,"tab characters must not be used in indentation")),!(c!==45||(i=t.input.charCodeAt(t.position+1),!Ht(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,ys(t,e,gw,!1,!0),s.push(t.result),it(t,!0,-1),c=t.input.charCodeAt(t.position),(t.line===r||t.lineIndent>e)&&c!==0)B(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 DA(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,y=!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(!y&&t.firstTabInLine!==-1&&(t.position=t.firstTabInLine,B(t,"tab characters must not be used in indentation")),n=t.input.charCodeAt(t.position+1),s=t.line,(b===63||b===58)&&Ht(n))b===63?(y&&(gs(t,p,f,d,m,null,i,a,c),d=m=h=null),v=!0,y=!0,o=!0):y?(y=!1,o=!0):B(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,!ys(t,r,hw,!1,!0))break;if(t.line===s){for(b=t.input.charCodeAt(t.position);ho(b);)b=t.input.charCodeAt(++t.position);if(b===58)b=t.input.charCodeAt(++t.position),Ht(b)||B(t,"a whitespace character is expected after the key-value separator within a block mapping"),y&&(gs(t,p,f,d,m,null,i,a,c),d=m=h=null),v=!0,y=!1,o=!1,d=t.tag,m=t.result;else if(v)B(t,"can not read an implicit mapping pair; a colon is missed");else return t.tag=l,t.anchor=u,!0}else if(v)B(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)&&(y&&(i=t.line,a=t.lineStart,c=t.position),ys(t,e,Ic,!0,o)&&(y?m=t.result:h=t.result),y||(gs(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)B(t,"bad indentation of a mapping entry");else if(t.lineIndent<e)break}return y&&gs(t,p,f,d,m,null,i,a,c),v&&(t.tag=l,t.anchor=u,t.kind="mapping",t.result=p),v}function qA(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&&B(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)):B(t,"unexpected end of the stream within a verbatim tag")}else{for(;i!==0&&!Ht(i);)i===33&&(n?B(t,"tag suffix cannot contain exclamation marks"):(o=t.input.slice(e-1,t.position+1),yw.test(o)||B(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),PA.test(s)&&B(t,"tag suffix cannot contain flow indicator characters")}s&&!vw.test(s)&&B(t,"tag name cannot contain such characters: "+s);try{s=decodeURIComponent(s)}catch{B(t,"tag name is malformed: "+s)}return r?t.tag=s:$n.call(t.tagMap,o)?t.tag=t.tagMap[o]+s:o==="!"?t.tag="!"+s:o==="!!"?t.tag="tag:yaml.org,2002:"+s:B(t,'undeclared tag handle "'+o+'"'),!0}function ZA(t){var e,r;if(r=t.input.charCodeAt(t.position),r!==38)return!1;for(t.anchor!==null&&B(t,"duplication of an anchor property"),r=t.input.charCodeAt(++t.position),e=t.position;r!==0&&!Ht(r)&&!hs(r);)r=t.input.charCodeAt(++t.position);return t.position===e&&B(t,"name of an anchor node must contain at least one character"),t.anchor=t.input.slice(e,t.position),!0}function UA(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&&!Ht(n)&&!hs(n);)n=t.input.charCodeAt(++t.position);return t.position===e&&B(t,"name of an alias node must contain at least one character"),r=t.input.slice(e,t.position),$n.call(t.anchorMap,r)||B(t,'unidentified alias "'+r+'"'),t.result=t.anchorMap[r],it(t,!0,-1),!0}function ys(t,e,r,n,o){var s,i,a,c=1,l=!1,u=!1,p,f,d,m,h,y;if(t.listener!==null&&t.listener("open",t),t.tag=null,t.anchor=null,t.kind=null,t.result=null,s=i=a=Ic===r||gw===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(;qA(t)||ZA(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||Ic===r)&&(Cc===r||hw===r?h=e:h=e+1,y=t.position-t.lineStart,c===1?a&&(Db(t,y)||DA(t,y,h))||MA(t,h)?u=!0:(i&&LA(t,h)||zA(t,h)||jA(t,h)?u=!0:UA(t)?(u=!0,(t.tag!==null||t.anchor!==null)&&B(t,"alias node should not have any properties")):NA(t,h,Cc===r)&&(u=!0,t.tag===null&&(t.tag="?")),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):c===0&&(u=a&&Db(t,y))),t.tag===null)t.anchor!==null&&(t.anchorMap[t.anchor]=t.result);else if(t.tag==="?"){for(t.result!==null&&t.kind!=="scalar"&&B(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($n.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||B(t,"unknown tag !<"+t.tag+">"),t.result!==null&&m.kind!==t.kind&&B(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)):B(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 FA(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&&!Ht(i);)i=t.input.charCodeAt(++t.position);for(n=t.input.slice(r,t.position),o=[],n.length<1&&B(t,"directive name must not be less than one character in length");i!==0;){for(;ho(i);)i=t.input.charCodeAt(++t.position);if(i===35){do i=t.input.charCodeAt(++t.position);while(i!==0&&!Dr(i));break}if(Dr(i))break;for(r=t.position;i!==0&&!Ht(i);)i=t.input.charCodeAt(++t.position);o.push(t.input.slice(r,t.position))}i!==0&&Jd(t),$n.call(Mb,n)?Mb[n](t,n,o):Ac(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&&B(t,"directives end mark is expected"),ys(t,t.lineIndent-1,Ic,!1,!0),it(t,!0,-1),t.checkLineBreaks&&TA.test(t.input.slice(e,t.position))&&Ac(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&jc(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,it(t,!0,-1));return}if(t.position<t.length-1)B(t,"end of the stream or a document separator is expected");else return}function Sw(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 AA(t,e),n=t.indexOf("\0");for(n!==-1&&(r.position=n,B(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;)FA(r);return r.documents}function HA(t,e,r){e!==null&&typeof e=="object"&&typeof r>"u"&&(r=e,e=null);var n=Sw(t,r);if(typeof e!="function")return n;for(var o=0,s=n.length;o<s;o+=1)e(n[o])}function BA(t,e){var r=Sw(t,e);if(r.length!==0){if(r.length===1)return r[0];throw new jt("expected a single document in the stream, but found more")}}function dN(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&&Ew.call(c.styleAliases,a)&&(a=c.styleAliases[a]),r[i]=a;return r}function fN(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 jt("code point within a string may not be greater than 0xFFFFFFFF");return"\\"+r+ut.repeat("0",n-e.length)+e}function hN(t){this.schema=t.schema||Wd,this.indent=Math.max(1,t.indent||2),this.noArrayIndent=t.noArrayIndent||!1,this.skipInvalid=t.skipInvalid||!1,this.flowLevel=ut.isNothing(t.flowLevel)?-1:t.flowLevel,this.styleMap=dN(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==='"'?Ci:mN,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 qb(t,e){for(var r=ut.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 Gd(t,e){return`
88
- `+lt.repeat(" ",t.indent*e)}function PN(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 jc(t){return t===cN||t===iN}function Ai(t){return 32<=t&&t<=126||161<=t&&t<=55295&&t!==8232&&t!==8233||57344<=t&&t<=65533&&t!==Qd||65536<=t&&t<=1114111}function Wb(t){return Ai(t)&&t!==Qd&&t!==aN&&t!==Ci}function Jb(t,e,r){var n=Wb(t),o=n&&!jc(t);return(r?n:n&&t!==Nw&&t!==zw&&t!==jw&&t!==Mw&&t!==Lw)&&t!==Bd&&!(e===zc&&!o)||Wb(e)&&!jc(e)&&t===Bd||e===zc&&o}function RN(t){return Ai(t)&&t!==Qd&&!jc(t)&&t!==hN&&t!==vN&&t!==zc&&t!==Nw&&t!==zw&&t!==jw&&t!==Mw&&t!==Lw&&t!==Bd&&t!==dN&&t!==mN&&t!==lN&&t!==wN&&t!==gN&&t!==yN&&t!==fN&&t!==uN&&t!==pN&&t!==_N&&t!==bN}function ON(t){return!jc(t)&&t!==zc}function Ri(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 Dw(t){var e=/^\n* /;return e.test(t)}function CN(t,e,r,n,o,s,i,a){var c,l=0,u=null,p=!1,f=!1,d=n!==-1,m=-1,h=RN(Ri(t,0))&&ON(Ri(t,t.length-1));if(e||i)for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=Ri(t,c),!Ai(l))return hs;h=h&&Jb(l,u,a),u=l}else{for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=Ri(t,c),l===Ci)p=!0,d&&(f=f||c-m-1>n&&t[m+1]!==" ",m=c);else if(!Ai(l))return hs;h=h&&Jb(l,u,a),u=l}f=f||d&&c-m-1>n&&t[m+1]!==" "}return!p&&!f?h&&!i&&!o(t)?qw:s===Ii?hs:Vd:r>9&&Dw(t)?hs:i?s===Ii?hs:Vd:f?Uw:Zw}function IN(t,e,r,n,o){t.dump=function(){if(e.length===0)return t.quotingType===Ii?'""':"''";if(!t.noCompatMode&&(xN.indexOf(e)!==-1||SN.test(e)))return t.quotingType===Ii?'"'+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 PN(t,l)}switch(CN(e,a,t.indent,i,c,t.quotingType,t.forceQuotes&&!n,o)){case qw:return e;case Vd:return"'"+e.replace(/'/g,"''")+"'";case Zw:return"|"+Kb(e,t.indent)+Yb(Vb(e,s));case Uw:return">"+Kb(e,t.indent)+Yb(Vb(AN(e,i),s));case hs:return'"'+NN(e)+'"';default:throw new Nt("impossible error: invalid scalar style")}}()}function Kb(t,e){var r=Dw(t)?String(e):"",n=t[t.length-1]===`
87
+ `&&(s+=r),s+=i;return s}function Hd(t,e){return`
88
+ `+ut.repeat(" ",t.indent*e)}function gN(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 zc(t){return t===KA||t===WA}function Ii(t){return 32<=t&&t<=126||161<=t&&t<=55295&&t!==8232&&t!==8233||57344<=t&&t<=65533&&t!==Yd||65536<=t&&t<=1114111}function Zb(t){return Ii(t)&&t!==Yd&&t!==JA&&t!==Oi}function Ub(t,e,r){var n=Zb(t),o=n&&!zc(t);return(r?n:n&&t!==Tw&&t!==Pw&&t!==Rw&&t!==Ow&&t!==Cw)&&t!==Fd&&!(e===Nc&&!o)||Zb(e)&&!zc(e)&&t===Fd||e===Nc&&o}function yN(t){return Ii(t)&&t!==Yd&&!zc(t)&&t!==nN&&t!==iN&&t!==Nc&&t!==Tw&&t!==Pw&&t!==Rw&&t!==Ow&&t!==Cw&&t!==Fd&&t!==eN&&t!==rN&&t!==YA&&t!==lN&&t!==oN&&t!==sN&&t!==tN&&t!==XA&&t!==QA&&t!==aN&&t!==cN}function vN(t){return!zc(t)&&t!==Nc}function Pi(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 Iw(t){var e=/^\n* /;return e.test(t)}function _N(t,e,r,n,o,s,i,a){var c,l=0,u=null,p=!1,f=!1,d=n!==-1,m=-1,h=yN(Pi(t,0))&&vN(Pi(t,t.length-1));if(e||i)for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=Pi(t,c),!Ii(l))return ms;h=h&&Ub(l,u,a),u=l}else{for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=Pi(t,c),l===Oi)p=!0,d&&(f=f||c-m-1>n&&t[m+1]!==" ",m=c);else if(!Ii(l))return ms;h=h&&Ub(l,u,a),u=l}f=f||d&&c-m-1>n&&t[m+1]!==" "}return!p&&!f?h&&!i&&!o(t)?Aw:s===Ci?ms:Bd:r>9&&Iw(t)?ms:i?s===Ci?ms:Bd:f?zw:Nw}function bN(t,e,r,n,o){t.dump=function(){if(e.length===0)return t.quotingType===Ci?'""':"''";if(!t.noCompatMode&&(uN.indexOf(e)!==-1||pN.test(e)))return t.quotingType===Ci?'"'+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 gN(t,l)}switch(_N(e,a,t.indent,i,c,t.quotingType,t.forceQuotes&&!n,o)){case Aw:return e;case Bd:return"'"+e.replace(/'/g,"''")+"'";case Nw:return"|"+Fb(e,t.indent)+Hb(qb(e,s));case zw:return">"+Fb(e,t.indent)+Hb(qb(wN(e,i),s));case ms:return'"'+xN(e)+'"';default:throw new jt("impossible error: invalid scalar style")}}()}function Fb(t,e){var r=Iw(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 Yb(t){return t[t.length-1]===`
93
- `?t.slice(0,-1):t}function AN(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,Xb(t.slice(0,l),e)}(),o=t[0]===`
92
+ `}function Hb(t){return t[t.length-1]===`
93
+ `?t.slice(0,-1):t}function wN(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,Bb(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
- `:"")+Xb(c,e),o=s}return n}function Xb(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
+ `:"")+Bb(c,e),o=s}return n}function Bb(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 NN(t){for(var e="",r=0,n,o=0;o<t.length;r>=65536?o+=2:o++)r=Ri(t,o),n=Pt[r],!n&&Ai(r)?(e+=t[o],r>=65536&&(e+=t[o+1])):e+=n||kN(r);return e}function zN(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)),(Xr(t,e,a,!1,!1)||typeof a>"u"&&Xr(t,e,null,!1,!1))&&(n!==""&&(n+=","+(t.condenseFlow?"":" ")),n+=t.dump);t.tag=o,t.dump="["+n+"]"}function Qb(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)),(Xr(t,e+1,c,!0,!0,!1,!0)||typeof c>"u"&&Xr(t,e+1,null,!0,!0,!1,!0))&&((!n||o!=="")&&(o+=Gd(t,e)),t.dump&&Ci===t.dump.charCodeAt(0)?o+="-":o+="- ",o+=t.dump);t.tag=s,t.dump=o||"[]"}function jN(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)),Xr(t,e,c,!1,!1)&&(t.dump.length>1024&&(u+="? "),u+=t.dump+(t.condenseFlow?'"':"")+":"+(t.condenseFlow?"":" "),Xr(t,e,l,!1,!1)&&(u+=t.dump,n+=u));t.tag=o,t.dump="{"+n+"}"}function MN(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 Nt("sortKeys must be a boolean or a function");for(a=0,c=i.length;a<c;a+=1)f="",(!n||o!=="")&&(f+=Gd(t,e)),l=i[a],u=r[l],t.replacer&&(u=t.replacer.call(r,l,u)),Xr(t,e+1,l,!0,!0,!0)&&(p=t.tag!==null&&t.tag!=="?"||t.dump&&t.dump.length>1024,p&&(t.dump&&Ci===t.dump.charCodeAt(0)?f+="?":f+="? "),f+=t.dump,p&&(f+=Gd(t,e)),Xr(t,e+1,u,!0,p)&&(t.dump&&Ci===t.dump.charCodeAt(0)?f+=":":f+=": ",f+=t.dump,o+=f));t.tag=s,t.dump=o||"{}"}function ew(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 Nt("!<"+a.tag+'> tag resolver accepts not "'+c+'" style');t.dump=n}return!0}return!1}function Xr(t,e,r,n,o,s,i){t.tag=null,t.dump=r,ew(t,r,!1)||ew(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,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?(MN(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):(jN(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?Qb(t,e-1,t.dump,o):Qb(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):(zN(t,e,t.dump),f&&(t.dump="&ref_"+p+" "+t.dump));else if(a==="[object String]")t.tag!=="?"&&IN(t,t.dump,e,s,c);else{if(a==="[object Undefined]")return!1;if(t.skipInvalid)return!1;throw new Nt("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 LN(t,e){var r=[],n=[],o,s;for(Wd(t,r,n),o=0,s=n.length;o<s;o+=1)e.duplicates.push(r[n[o]]);e.usedDuplicates=new Array(s)}function Wd(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)Wd(t[o],e,r);else for(n=Object.keys(t),o=0,s=n.length;o<s;o+=1)Wd(t[n[o]],e,r)}function DN(t,e){e=e||{};var r=new TN(e);r.noRefs||LN(t,r);var n=t;return r.replacer&&(n=r.replacer.call({"":n},"",n)),Xr(r,0,n,!0,!0)?r.dump+`
100
- `:""}function ef(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 U1,F1,H1,B1,G1,V1,lt,Nt,J1,K1,Y1,yt,nw,ow,sw,iw,aw,cw,lw,uw,fA,gA,pw,dw,fw,mw,hw,gw,yw,Jd,vw,TA,PA,_w,CA,bw,NA,ww,Kd,xn,Ic,xw,Sw,Ac,Fd,MA,Zb,LA,DA,qA,$w,kw,Tw,Pw,fo,Hb,oN,sN,Cw,Iw,Aw,Qd,iN,Ci,aN,cN,lN,uN,Bd,pN,dN,fN,mN,Nw,hN,zc,gN,yN,vN,_N,zw,jw,bN,Mw,wN,Lw,Pt,xN,SN,EN,Ii,qw,Vd,Zw,Uw,hs,qN,ZN,UN,FN,HN,BN,GN,VN,WN,JN,KN,YN,XN,QN,ez,tz,Qr,Ni=w(()=>{U1=tw,F1=M1,H1=L1,B1=q1,G1=Z1,V1=D1,lt={isNothing:U1,isObject:F1,toArray:H1,repeat:B1,isNegativeZero:G1,extend:V1};Oi.prototype=Object.create(Error.prototype);Oi.prototype.constructor=Oi;Oi.prototype.toString=function(e){return this.name+": "+rw(this,e)};Nt=Oi;J1=W1,K1=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],Y1=["scalar","sequence","mapping"];yt=Q1;Hd.prototype.extend=function(e){var r=[],n=[];if(e instanceof yt)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 Nt("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");r.forEach(function(s){if(!(s instanceof yt))throw new Nt("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(s.loadKind&&s.loadKind!=="scalar")throw new Nt("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 Nt("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 yt))throw new Nt("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var o=Object.create(Hd.prototype);return o.implicit=(this.implicit||[]).concat(r),o.explicit=(this.explicit||[]).concat(n),o.compiledImplicit=qb(o,"implicit"),o.compiledExplicit=qb(o,"explicit"),o.compiledTypeMap=eA(o.compiledImplicit,o.compiledExplicit),o};nw=Hd,ow=new yt("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),sw=new yt("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),iw=new yt("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),aw=new nw({explicit:[ow,sw,iw]});cw=new yt("tag:yaml.org,2002:null",{kind:"scalar",resolve:tA,construct:rA,predicate:nA,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});lw=new yt("tag:yaml.org,2002:bool",{kind:"scalar",resolve:oA,construct:sA,predicate:iA,represent:{lowercase:function(t){return t?"true":"false"},uppercase:function(t){return t?"TRUE":"FALSE"},camelcase:function(t){return t?"True":"False"}},defaultStyle:"lowercase"});uw=new yt("tag:yaml.org,2002:int",{kind:"scalar",resolve:uA,construct:pA,predicate:dA,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"]}}),fA=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");gA=/^[-+]?[0-9]+e/;pw=new yt("tag:yaml.org,2002:float",{kind:"scalar",resolve:mA,construct:hA,predicate:vA,represent:yA,defaultStyle:"lowercase"}),dw=aw.extend({implicit:[cw,lw,uw,pw]}),fw=dw,mw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),hw=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]))?))?$");gw=new yt("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:_A,construct:bA,instanceOf:Date,represent:wA});yw=new yt("tag:yaml.org,2002:merge",{kind:"scalar",resolve:xA}),Jd=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
101
- \r`;vw=new yt("tag:yaml.org,2002:binary",{kind:"scalar",resolve:SA,construct:$A,predicate:EA,represent:kA}),TA=Object.prototype.hasOwnProperty,PA=Object.prototype.toString;_w=new yt("tag:yaml.org,2002:omap",{kind:"sequence",resolve:RA,construct:OA}),CA=Object.prototype.toString;bw=new yt("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:IA,construct:AA}),NA=Object.prototype.hasOwnProperty;ww=new yt("tag:yaml.org,2002:set",{kind:"mapping",resolve:zA,construct:jA}),Kd=fw.extend({implicit:[gw,yw],explicit:[vw,_w,bw,ww]}),xn=Object.prototype.hasOwnProperty,Ic=1,xw=2,Sw=3,Ac=4,Fd=1,MA=2,Zb=3,LA=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,DA=/[\x85\u2028\u2029]/,qA=/[,\[\]\{\}]/,$w=/^(?:!|!!|![a-z\-]+!)$/i,kw=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;Tw=new Array(256),Pw=new Array(256);for(fo=0;fo<256;fo++)Tw[fo]=Fb(fo)?1:0,Pw[fo]=Fb(fo);Hb={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&&Nc(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],$w.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'),kw.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}};oN=rN,sN=nN,Cw={loadAll:oN,load:sN},Iw=Object.prototype.toString,Aw=Object.prototype.hasOwnProperty,Qd=65279,iN=9,Ci=10,aN=13,cN=32,lN=33,uN=34,Bd=35,pN=37,dN=38,fN=39,mN=42,Nw=44,hN=45,zc=58,gN=61,yN=62,vN=63,_N=64,zw=91,jw=93,bN=96,Mw=123,wN=124,Lw=125,Pt={};Pt[0]="\\0";Pt[7]="\\a";Pt[8]="\\b";Pt[9]="\\t";Pt[10]="\\n";Pt[11]="\\v";Pt[12]="\\f";Pt[13]="\\r";Pt[27]="\\e";Pt[34]='\\"';Pt[92]="\\\\";Pt[133]="\\N";Pt[160]="\\_";Pt[8232]="\\L";Pt[8233]="\\P";xN=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],SN=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;EN=1,Ii=2;qw=1,Vd=2,Zw=3,Uw=4,hs=5;qN=DN,ZN={dump:qN};UN=yt,FN=nw,HN=aw,BN=dw,GN=fw,VN=Kd,WN=Cw.load,JN=Cw.loadAll,KN=ZN.dump,YN=Nt,XN={binary:vw,float:pw,map:iw,null:cw,pairs:bw,set:ww,timestamp:gw,bool:lw,int:uw,merge:yw,omap:_w,seq:sw,str:ow},QN=ef("safeLoad","load"),ez=ef("safeLoadAll","loadAll"),tz=ef("safeDump","dump"),Qr={Type:UN,Schema:FN,FAILSAFE_SCHEMA:HN,JSON_SCHEMA:BN,CORE_SCHEMA:GN,DEFAULT_SCHEMA:VN,load:WN,loadAll:JN,dump:KN,YAMLException:YN,types:XN,safeLoad:QN,safeLoadAll:ez,safeDump:tz}});var Vw={};V(Vw,{protocol:()=>sz});import{readFileSync as Hw,writeFileSync as rz,existsSync as nz}from"node:fs";import{basename as oz}from"node:path";function Bw(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(` ${g("bold",e.name)}${e.description?` \u2014 ${e.description}`:""}`),e.capabilities?.length&&console.log(` ${g("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(` ${g("cyan",`${e+1}.`)} ${g("bold",r.name)}${r.description?` \u2014 ${r.description}`:""}`),r.resources?.length&&console.log(` Resources: ${g("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 Gw(t){try{return await po(t)}catch{}try{return JSON.parse(t)}catch{}try{return Qr.load(t)}catch{}return null}async function sz(t=[]){let e=t[0];if(e==="validate"){await az(t.slice(1));return}if(e==="load"){await cz(t.slice(1));return}if(e==="init"){await lz(t.slice(1));return}if(e==="--help"||e==="-h"){console.log(`
99
+ `+t.slice(i+1):c+=t.slice(o),c.slice(1)}function xN(t){for(var e="",r=0,n,o=0;o<t.length;r>=65536?o+=2:o++)r=Pi(t,o),n=Rt[r],!n&&Ii(r)?(e+=t[o],r>=65536&&(e+=t[o+1])):e+=n||fN(r);return e}function SN(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)),(tn(t,e,a,!1,!1)||typeof a>"u"&&tn(t,e,null,!1,!1))&&(n!==""&&(n+=","+(t.condenseFlow?"":" ")),n+=t.dump);t.tag=o,t.dump="["+n+"]"}function Gb(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)),(tn(t,e+1,c,!0,!0,!1,!0)||typeof c>"u"&&tn(t,e+1,null,!0,!0,!1,!0))&&((!n||o!=="")&&(o+=Hd(t,e)),t.dump&&Oi===t.dump.charCodeAt(0)?o+="-":o+="- ",o+=t.dump);t.tag=s,t.dump=o||"[]"}function $N(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)),tn(t,e,c,!1,!1)&&(t.dump.length>1024&&(u+="? "),u+=t.dump+(t.condenseFlow?'"':"")+":"+(t.condenseFlow?"":" "),tn(t,e,l,!1,!1)&&(u+=t.dump,n+=u));t.tag=o,t.dump="{"+n+"}"}function kN(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 jt("sortKeys must be a boolean or a function");for(a=0,c=i.length;a<c;a+=1)f="",(!n||o!=="")&&(f+=Hd(t,e)),l=i[a],u=r[l],t.replacer&&(u=t.replacer.call(r,l,u)),tn(t,e+1,l,!0,!0,!0)&&(p=t.tag!==null&&t.tag!=="?"||t.dump&&t.dump.length>1024,p&&(t.dump&&Oi===t.dump.charCodeAt(0)?f+="?":f+="? "),f+=t.dump,p&&(f+=Hd(t,e)),tn(t,e+1,u,!0,p)&&(t.dump&&Oi===t.dump.charCodeAt(0)?f+=":":f+=": ",f+=t.dump,o+=f));t.tag=s,t.dump=o||"{}"}function Vb(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,kw.call(a.represent)==="[object Function]")n=a.represent(e,c);else if(Ew.call(a.represent,c))n=a.represent[c](e,c);else throw new jt("!<"+a.tag+'> tag resolver accepts not "'+c+'" style');t.dump=n}return!0}return!1}function tn(t,e,r,n,o,s,i){t.tag=null,t.dump=r,Vb(t,r,!1)||Vb(t,r,!0);var a=kw.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?(kN(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):($N(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?Gb(t,e-1,t.dump,o):Gb(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):(SN(t,e,t.dump),f&&(t.dump="&ref_"+p+" "+t.dump));else if(a==="[object String]")t.tag!=="?"&&bN(t,t.dump,e,s,c);else{if(a==="[object Undefined]")return!1;if(t.skipInvalid)return!1;throw new jt("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 EN(t,e){var r=[],n=[],o,s;for(Gd(t,r,n),o=0,s=n.length;o<s;o+=1)e.duplicates.push(r[n[o]]);e.usedDuplicates=new Array(s)}function Gd(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)Gd(t[o],e,r);else for(n=Object.keys(t),o=0,s=n.length;o<s;o+=1)Gd(t[n[o]],e,r)}function TN(t,e){e=e||{};var r=new hN(e);r.noRefs||EN(t,r);var n=t;return r.replacer&&(n=r.replacer.call({"":n},"",n)),tn(r,0,n,!0,!0)?r.dump+`
100
+ `:""}function Xd(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 O1,C1,I1,A1,N1,z1,ut,jt,M1,L1,D1,vt,Kb,Yb,Xb,Qb,ew,tw,rw,nw,tA,oA,ow,sw,iw,aw,cw,lw,uw,Vd,pw,hA,gA,dw,_A,fw,xA,mw,Wd,$n,Cc,hw,gw,Ic,Zd,kA,Nb,EA,TA,PA,yw,vw,bw,ww,mo,Mb,GA,VA,$w,kw,Ew,Yd,WA,Oi,JA,KA,YA,XA,Fd,QA,eN,tN,rN,Tw,nN,Nc,oN,sN,iN,aN,Pw,Rw,cN,Ow,lN,Cw,Rt,uN,pN,mN,Ci,Aw,Bd,Nw,zw,ms,PN,RN,ON,CN,IN,AN,NN,zN,jN,MN,LN,DN,qN,ZN,UN,FN,rn,Ai=w(()=>{O1=Wb,C1=k1,I1=E1,A1=P1,N1=R1,z1=T1,ut={isNothing:O1,isObject:C1,toArray:I1,repeat:A1,isNegativeZero:N1,extend:z1};Ri.prototype=Object.create(Error.prototype);Ri.prototype.constructor=Ri;Ri.prototype.toString=function(e){return this.name+": "+Jb(this,e)};jt=Ri;M1=j1,L1=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],D1=["scalar","sequence","mapping"];vt=Z1;Ud.prototype.extend=function(e){var r=[],n=[];if(e instanceof vt)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 jt("Schema.extend argument should be a Type, [ Type ], or a schema definition ({ implicit: [...], explicit: [...] })");r.forEach(function(s){if(!(s instanceof vt))throw new jt("Specified list of YAML types (or a single Type object) contains a non-Type object.");if(s.loadKind&&s.loadKind!=="scalar")throw new jt("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 jt("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 vt))throw new jt("Specified list of YAML types (or a single Type object) contains a non-Type object.")});var o=Object.create(Ud.prototype);return o.implicit=(this.implicit||[]).concat(r),o.explicit=(this.explicit||[]).concat(n),o.compiledImplicit=Ab(o,"implicit"),o.compiledExplicit=Ab(o,"explicit"),o.compiledTypeMap=U1(o.compiledImplicit,o.compiledExplicit),o};Kb=Ud,Yb=new vt("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),Xb=new vt("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),Qb=new vt("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),ew=new Kb({explicit:[Yb,Xb,Qb]});tw=new vt("tag:yaml.org,2002:null",{kind:"scalar",resolve:F1,construct:H1,predicate:B1,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});rw=new vt("tag:yaml.org,2002:bool",{kind:"scalar",resolve:G1,construct:V1,predicate:W1,represent:{lowercase:function(t){return t?"true":"false"},uppercase:function(t){return t?"TRUE":"FALSE"},camelcase:function(t){return t?"True":"False"}},defaultStyle:"lowercase"});nw=new vt("tag:yaml.org,2002:int",{kind:"scalar",resolve:X1,construct:Q1,predicate:eA,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"]}}),tA=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");oA=/^[-+]?[0-9]+e/;ow=new vt("tag:yaml.org,2002:float",{kind:"scalar",resolve:rA,construct:nA,predicate:iA,represent:sA,defaultStyle:"lowercase"}),sw=ew.extend({implicit:[tw,rw,nw,ow]}),iw=sw,aw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),cw=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]))?))?$");lw=new vt("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:aA,construct:cA,instanceOf:Date,represent:lA});uw=new vt("tag:yaml.org,2002:merge",{kind:"scalar",resolve:uA}),Vd=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
101
+ \r`;pw=new vt("tag:yaml.org,2002:binary",{kind:"scalar",resolve:pA,construct:dA,predicate:mA,represent:fA}),hA=Object.prototype.hasOwnProperty,gA=Object.prototype.toString;dw=new vt("tag:yaml.org,2002:omap",{kind:"sequence",resolve:yA,construct:vA}),_A=Object.prototype.toString;fw=new vt("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:bA,construct:wA}),xA=Object.prototype.hasOwnProperty;mw=new vt("tag:yaml.org,2002:set",{kind:"mapping",resolve:SA,construct:$A}),Wd=iw.extend({implicit:[lw,uw],explicit:[pw,dw,fw,mw]}),$n=Object.prototype.hasOwnProperty,Cc=1,hw=2,gw=3,Ic=4,Zd=1,kA=2,Nb=3,EA=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,TA=/[\x85\u2028\u2029]/,PA=/[,\[\]\{\}]/,yw=/^(?:!|!!|![a-z\-]+!)$/i,vw=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;bw=new Array(256),ww=new Array(256);for(mo=0;mo<256;mo++)bw[mo]=jb(mo)?1:0,ww[mo]=jb(mo);Mb={YAML:function(e,r,n){var o,s,i;e.version!==null&&B(e,"duplication of %YAML directive"),n.length!==1&&B(e,"YAML directive accepts exactly one argument"),o=/^([0-9]+)\.([0-9]+)$/.exec(n[0]),o===null&&B(e,"ill-formed argument of the YAML directive"),s=parseInt(o[1],10),i=parseInt(o[2],10),s!==1&&B(e,"unacceptable YAML version of the document"),e.version=n[0],e.checkLineBreaks=i<2,i!==1&&i!==2&&Ac(e,"unsupported YAML version of the document")},TAG:function(e,r,n){var o,s;n.length!==2&&B(e,"TAG directive accepts exactly two arguments"),o=n[0],s=n[1],yw.test(o)||B(e,"ill-formed tag handle (first argument) of the TAG directive"),$n.call(e.tagMap,o)&&B(e,'there is a previously declared suffix for "'+o+'" tag handle'),vw.test(s)||B(e,"ill-formed tag prefix (second argument) of the TAG directive");try{s=decodeURIComponent(s)}catch{B(e,"tag prefix is malformed: "+s)}e.tagMap[o]=s}};GA=HA,VA=BA,$w={loadAll:GA,load:VA},kw=Object.prototype.toString,Ew=Object.prototype.hasOwnProperty,Yd=65279,WA=9,Oi=10,JA=13,KA=32,YA=33,XA=34,Fd=35,QA=37,eN=38,tN=39,rN=42,Tw=44,nN=45,Nc=58,oN=61,sN=62,iN=63,aN=64,Pw=91,Rw=93,cN=96,Ow=123,lN=124,Cw=125,Rt={};Rt[0]="\\0";Rt[7]="\\a";Rt[8]="\\b";Rt[9]="\\t";Rt[10]="\\n";Rt[11]="\\v";Rt[12]="\\f";Rt[13]="\\r";Rt[27]="\\e";Rt[34]='\\"';Rt[92]="\\\\";Rt[133]="\\N";Rt[160]="\\_";Rt[8232]="\\L";Rt[8233]="\\P";uN=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],pN=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;mN=1,Ci=2;Aw=1,Bd=2,Nw=3,zw=4,ms=5;PN=TN,RN={dump:PN};ON=vt,CN=Kb,IN=ew,AN=sw,NN=iw,zN=Wd,jN=$w.load,MN=$w.loadAll,LN=RN.dump,DN=jt,qN={binary:pw,float:ow,map:Qb,null:tw,pairs:fw,set:mw,timestamp:lw,bool:rw,int:nw,merge:uw,omap:dw,seq:Xb,str:Yb},ZN=Xd("safeLoad","load"),UN=Xd("safeLoadAll","loadAll"),FN=Xd("safeDump","dump"),rn={Type:ON,Schema:CN,FAILSAFE_SCHEMA:IN,JSON_SCHEMA:AN,CORE_SCHEMA:NN,DEFAULT_SCHEMA:zN,load:jN,loadAll:MN,dump:LN,YAMLException:DN,types:qN,safeLoad:ZN,safeLoadAll:UN,safeDump:FN}});var qw={};V(qw,{protocol:()=>VN});import{readFileSync as Mw,writeFileSync as HN,existsSync as BN}from"node:fs";import{basename as GN}from"node:path";function Lw(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(` ${g("bold",e.name)}${e.description?` \u2014 ${e.description}`:""}`),e.capabilities?.length&&console.log(` ${g("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(` ${g("cyan",`${e+1}.`)} ${g("bold",r.name)}${r.description?` \u2014 ${r.description}`:""}`),r.resources?.length&&console.log(` Resources: ${g("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 Dw(t){try{return await fo(t)}catch{}try{return JSON.parse(t)}catch{}try{return rn.load(t)}catch{}return null}async function VN(t=[]){let e=t[0];if(e==="validate"){await JN(t.slice(1));return}if(e==="load"){await KN(t.slice(1));return}if(e==="init"){await YN(t.slice(1));return}if(e==="--help"||e==="-h"){console.log(`
102
102
  ${g("bold","wgl protocol")} \u2014 protocol management
103
103
 
104
104
  ${g("cyan","USAGE:")}
@@ -113,32 +113,32 @@ ${g("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 iz();return}console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl protocol --help` for usage"),process.exit(2)}async function iz(){let t=_e();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(` ${g("dim","No protocol loaded on server")}`);return}Bw(n)}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function az(t){let e=t[0];e||(console.log(_("Usage: wgl protocol validate <file>")),process.exit(2));let r;try{r=Hw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let n=await Gw(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(A(`Valid protocol: ${o.name}`)),Bw(o)}async function cz(t){let e=t[0];e||(console.log(_("Usage: wgl protocol load <file>")),process.exit(2));let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n;try{n=Hw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let o=await Gw(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(A(`Loaded protocol: ${o.name||"unknown"}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function lz(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=Fw[n];if(!s){console.log(_(`Unknown template: ${n}`)),console.log(g("dim",` Available: ${Object.keys(Fw).join(", ")}`)),process.exit(2);return}let i={...s};o&&(i.name=o);let c=`${oz(i.name).replace(/[/\\]/g,"_")}.acp.json`;if(nz(c)){console.log(_(`File already exists: ${c}`)),process.exit(1);return}rz(c,JSON.stringify(i,null,2)+`
117
- `),console.log(A(`Created protocol: ${c}`)),console.log(g("dim",` Template: ${n}`)),console.log(g("dim",` Load it: wgl protocol load ${c}`)),console.log()}var Fw,Ww=w(()=>{"use strict";ft();et();Ee();Pi();Ni();Fw={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 Jw={};V(Jw,{team:()=>uz});async function uz(){let t=_e();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(` ${g("dim","No agents connected")}`);else for(let o of n){let s=o.agent===t.agentId?g("green"," (you)"):"";console.log(` ${g("bold",o.role.padEnd(15))} ${o.agent}${s}`)}}catch{console.log(_("Cannot reach server")),process.exit(1)}console.log()}var Kw=w(()=>{"use strict";ft();et();Ee()});var Yw={};V(Yw,{claim:()=>pz});async function pz(t){let e=_e();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(A(`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 Xw=w(()=>{"use strict";ft();et();Ee()});var Qw={};V(Qw,{release:()=>dz});async function dz(t){let e=_e();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(A(`Released: ${r}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var ex=w(()=>{"use strict";ft();et();Ee()});var tx={};V(tx,{halt:()=>fz});async function fz(t){let e=_e();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(A(`Halted${r?`: ${r}`:""}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var rx=w(()=>{"use strict";ft();et();Ee()});var tf={};V(tf,{pause:()=>mz,resume:()=>hz});async function mz(t){let e=_e();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(A(`Paused${r?`: ${r}`:""}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function hz(){let t=_e();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(A("Resumed"))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var rf=w(()=>{"use strict";ft();et();Ee()});var ox={};V(ox,{events:()=>gz});function nx(t){let e=new Date(t.publishedAt).toLocaleTimeString();return` ${g("dim",`#${t.id}`)} ${g("bold",t.type)} by ${t.publishedBy} ${g("dim",e)}`}async function gz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
116
+ `);return}if(e==="show"||!e){await WN();return}console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl protocol --help` for usage"),process.exit(2)}async function WN(){let t=_e();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(` ${g("dim","No protocol loaded on server")}`);return}Lw(n)}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function JN(t){let e=t[0];e||(console.log(_("Usage: wgl protocol validate <file>")),process.exit(2));let r;try{r=Mw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let n=await Dw(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(A(`Valid protocol: ${o.name}`)),Lw(o)}async function KN(t){let e=t[0];e||(console.log(_("Usage: wgl protocol load <file>")),process.exit(2));let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n;try{n=Mw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let o=await Dw(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(A(`Loaded protocol: ${o.name||"unknown"}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function YN(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=jw[n];if(!s){console.log(_(`Unknown template: ${n}`)),console.log(g("dim",` Available: ${Object.keys(jw).join(", ")}`)),process.exit(2);return}let i={...s};o&&(i.name=o);let c=`${GN(i.name).replace(/[/\\]/g,"_")}.acp.json`;if(BN(c)){console.log(_(`File already exists: ${c}`)),process.exit(1);return}HN(c,JSON.stringify(i,null,2)+`
117
+ `),console.log(A(`Created protocol: ${c}`)),console.log(g("dim",` Template: ${n}`)),console.log(g("dim",` Load it: wgl protocol load ${c}`)),console.log()}var jw,Zw=w(()=>{"use strict";mt();et();Te();Ti();Ai();jw={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 Uw={};V(Uw,{team:()=>XN});async function XN(){let t=_e();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(` ${g("dim","No agents connected")}`);else for(let o of n){let s=o.agent===t.agentId?g("green"," (you)"):"";console.log(` ${g("bold",o.role.padEnd(15))} ${o.agent}${s}`)}}catch{console.log(_("Cannot reach server")),process.exit(1)}console.log()}var Fw=w(()=>{"use strict";mt();et();Te()});var Hw={};V(Hw,{claim:()=>QN});async function QN(t){let e=_e();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(A(`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 Bw=w(()=>{"use strict";mt();et();Te()});var Gw={};V(Gw,{release:()=>ez});async function ez(t){let e=_e();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(A(`Released: ${r}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var Vw=w(()=>{"use strict";mt();et();Te()});var Ww={};V(Ww,{halt:()=>tz});async function tz(t){let e=_e();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(A(`Halted${r?`: ${r}`:""}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var Jw=w(()=>{"use strict";mt();et();Te()});var Qd={};V(Qd,{pause:()=>rz,resume:()=>nz});async function rz(t){let e=_e();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(A(`Paused${r?`: ${r}`:""}`))}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function nz(){let t=_e();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(A("Resumed"))}catch{console.log(_("Cannot reach server")),process.exit(1)}}var ef=w(()=>{"use strict";mt();et();Te()});var Yw={};V(Yw,{events:()=>oz});function Kw(t){let e=new Date(t.publishedAt).toLocaleTimeString();return` ${g("dim",`#${t.id}`)} ${g("bold",t.type)} by ${t.publishedBy} ${g("dim",e)}`}async function oz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
118
118
  ${g("bold","wgl events")} \u2014 event management
119
119
 
120
120
  ${g("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=_e();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(` ${g("dim","No events")}`);return}console.log(C("Events"));for(let u of l)console.log(nx(u));console.log()}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"tail":{let o=r.lastEventCursor||0;console.log(g("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(nx(l)),l.id>o&&(o=l.id)}}catch{}};await s();let i=setInterval(s,2e3);process.on("SIGINT",()=>{clearInterval(i),console.log(g("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(A(`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 sx=w(()=>{"use strict";ft();et();Ee()});var ix={};V(ix,{state:()=>yz});async function yz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
124
+ `);return}let r=_e();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(` ${g("dim","No events")}`);return}console.log(C("Events"));for(let u of l)console.log(Kw(u));console.log()}catch{console.log(_("Cannot reach server")),process.exit(1)}break}case"tail":{let o=r.lastEventCursor||0;console.log(g("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(Kw(l)),l.id>o&&(o=l.id)}}catch{}};await s();let i=setInterval(s,2e3);process.on("SIGINT",()=>{clearInterval(i),console.log(g("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(A(`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 Xw=w(()=>{"use strict";mt();et();Te()});var Qw={};V(Qw,{state:()=>sz});async function sz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
127
127
  ${g("bold","wgl state")} \u2014 shared state management
128
128
 
129
129
  ${g("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=_e();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(` ${g("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(A(`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(A(`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 ax=w(()=>{"use strict";ft();et();Ee()});var cx={};V(cx,{msg:()=>_z});function vz(t,e){let r=new Date(t.sentAt).toLocaleTimeString(),n=t.from===e?g("green",t.from+" (you)"):g("bold",t.from),o=t.to==="*"?g("yellow","broadcast"):t.to===e?g("green","you"):t.to;return` ${g("dim",`#${t.id}`)} ${n} ${g("dim","->")} ${o}: ${t.content} ${g("dim",r)}`}async function _z(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
133
+ `);return}let r=_e();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(` ${g("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(A(`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(A(`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 ex=w(()=>{"use strict";mt();et();Te()});var tx={};V(tx,{msg:()=>az});function iz(t,e){let r=new Date(t.sentAt).toLocaleTimeString(),n=t.from===e?g("green",t.from+" (you)"):g("bold",t.from),o=t.to==="*"?g("yellow","broadcast"):t.to===e?g("green","you"):t.to;return` ${g("dim",`#${t.id}`)} ${n} ${g("dim","->")} ${o}: ${t.content} ${g("dim",r)}`}async function az(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
134
134
  ${g("bold","wgl msg")} \u2014 agent messaging
135
135
 
136
136
  ${g("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=_e();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(A(`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(` ${g("dim","No messages")}`);return}console.log(C("Messages"));for(let a of i)console.log(vz(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(A(`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 lx=w(()=>{"use strict";ft();et();Ee()});var ux={};V(ux,{helpCmd:()=>xz});function wz(t,e){let r=bz[t.urgency||"normal"],n=t.status==="open"?g("yellow","open"):t.status==="claimed"?g("cyan",`claimed by ${t.claimedBy}`):g("green","resolved"),o=t.from===e?g("green"," (you)"):"";return` ${g("dim",`#${t.id}`)} ${g(r,`[${t.urgency||"normal"}]`)} ${t.problem}${o}
141
- ${n} \u2014 ${t.from} ${g("dim",new Date(t.createdAt).toLocaleTimeString())}`}async function xz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
140
+ `);return}let r=_e();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(A(`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(` ${g("dim","No messages")}`);return}console.log(C("Messages"));for(let a of i)console.log(iz(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(A(`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 rx=w(()=>{"use strict";mt();et();Te()});var nx={};V(nx,{helpCmd:()=>uz});function lz(t,e){let r=cz[t.urgency||"normal"],n=t.status==="open"?g("yellow","open"):t.status==="claimed"?g("cyan",`claimed by ${t.claimedBy}`):g("green","resolved"),o=t.from===e?g("green"," (you)"):"";return` ${g("dim",`#${t.id}`)} ${g(r,`[${t.urgency||"normal"}]`)} ${t.problem}${o}
141
+ ${n} \u2014 ${t.from} ${g("dim",new Date(t.createdAt).toLocaleTimeString())}`}async function uz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
142
142
  ${g("bold","wgl help")} \u2014 help request management
143
143
 
144
144
  ${g("cyan","USAGE:")}
@@ -146,26 +146,26 @@ ${g("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=_e();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(A(`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(` ${g("dim","No help requests")}`);return}console.log(C("Help Requests"));for(let i of s)console.log(wz(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(A(`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(A(`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 bz,px=w(()=>{"use strict";ft();et();Ee();bz={low:"dim",normal:"cyan",high:"red"}});var dx={};V(dx,{namespace:()=>Sz});async function Sz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
149
+ `);return}let r=_e();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(A(`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(` ${g("dim","No help requests")}`);return}console.log(C("Help Requests"));for(let i of s)console.log(lz(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(A(`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(A(`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 cz,ox=w(()=>{"use strict";mt();et();Te();cz={low:"dim",normal:"cyan",high:"red"}});var sx={};V(sx,{namespace:()=>pz});async function pz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
150
150
  ${g("bold","wgl namespace")} \u2014 namespace management
151
151
 
152
152
  ${g("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=_e();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(` ${g("dim","No namespaces")}`);return}console.log(C("Namespaces"));for(let i of s){let a=i===r.namespace?g("green"," (active)"):"";console.log(` ${g("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(A(`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(A(`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 fx=w(()=>{"use strict";ft();et();Ee()});var mx={};V(mx,{hooksCmd:()=>Tz});import{readFileSync as $z,existsSync as kz}from"node:fs";import{join as Ez}from"node:path";async function Tz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
156
+ `);return}let r=_e();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(` ${g("dim","No namespaces")}`);return}console.log(C("Namespaces"));for(let i of s){let a=i===r.namespace?g("green"," (active)"):"";console.log(` ${g("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(A(`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(A(`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 ix=w(()=>{"use strict";mt();et();Te()});var ax={};V(ax,{hooksCmd:()=>hz});import{readFileSync as dz,existsSync as fz}from"node:fs";import{join as mz}from"node:path";async function hz(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
157
157
  ${g("bold","wgl hooks")} \u2014 Claude Code hook management
158
158
 
159
159
  ${g("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=_e()?.hookTimeout||10;try{ms(n),console.log(A("Hooks installed"))}catch(o){console.log(_(`Failed to install hooks: ${o.message}`)),process.exit(1)}break}case"uninstall":{try{Tc(),console.log(A("Hooks uninstalled"))}catch(r){console.log(_(`Failed to uninstall hooks: ${r.message}`)),process.exit(1)}break}case"list":{let r=Ez(process.cwd(),".claude","settings.local.json");if(!kz(r)){console.log(` ${g("dim","No hooks installed (no settings.local.json)")}`);return}let n;try{n=JSON.parse($z(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(` ${g("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=Ec(i.command)?g("green"," [wgl]"):"";console.log(` ${g("bold",o)}${i.matcher?g("dim",` (${i.matcher})`):""}${c}`),console.log(` ${g("dim",i.command)}`),i.timeout&&console.log(` ${g("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 hx=w(()=>{"use strict";ft();$i();Ee()});import{readFileSync as Pz,existsSync as gx}from"node:fs";import{join as Rz,resolve as Oz}from"node:path";function vx(t){if(typeof t=="string")return{conditions:[{event:t,count:1}],timeout:yx};let e=typeof t.timeout=="number"?t.timeout:yx;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 _x(t){if(t){let e=Oz(t);return gx(e)?e:null}for(let e of Cz){let r=Rz(process.cwd(),e);if(gx(r))return r}return null}async function bx(t){let e=Pz(t,"utf8"),r=t.endsWith(".json")?JSON.parse(e):Iz(e);return Az(r)}function Iz(t){return Qr.load(t)}function Az(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(F=>typeof F=="string"))O=$.tools;else throw new Error(`hive "${u}".agents[${x}].tools must be 'all' or an array of strings`);let ie;if($.coordination!==void 0)if(typeof $.coordination=="string"&&["lite","full","none"].includes($.coordination))ie=$.coordination;else if(Array.isArray($.coordination)&&$.coordination.every(F=>typeof F=="string"))ie=$.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,de;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 F=$.wake_on;de={types:Array.isArray(F.types)?F.types.filter(ne=>typeof ne=="string"):void 0,timeout:typeof F.timeout=="number"?F.timeout:void 0,max_wakes:typeof F.max_wakes=="number"?F.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:ie,startOn:ee,wake_on:de}})}let y=f.honeycomb??f.comb;if(y!==void 0){if(!y||typeof y!="object")throw new Error(`hive "${u}".honeycomb must be an object`);let b=y;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 yx,Cz,wx=w(()=>{"use strict";Ni();yx=0;Cz=["brood.yaml","brood.yml","brood.json"]});import{createServer as Nz}from"node:net";var Lc,xx=w(()=>{"use strict";Lc=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=Nz(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=_e()?.hookTimeout||10;try{fs(n),console.log(A("Hooks installed"))}catch(o){console.log(_(`Failed to install hooks: ${o.message}`)),process.exit(1)}break}case"uninstall":{try{Ec(),console.log(A("Hooks uninstalled"))}catch(r){console.log(_(`Failed to uninstall hooks: ${r.message}`)),process.exit(1)}break}case"list":{let r=mz(process.cwd(),".claude","settings.local.json");if(!fz(r)){console.log(` ${g("dim","No hooks installed (no settings.local.json)")}`);return}let n;try{n=JSON.parse(dz(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(` ${g("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=kc(i.command)?g("green"," [wgl]"):"";console.log(` ${g("bold",o)}${i.matcher?g("dim",` (${i.matcher})`):""}${c}`),console.log(` ${g("dim",i.command)}`),i.timeout&&console.log(` ${g("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 cx=w(()=>{"use strict";mt();Si();Te()});import{readFileSync as gz,existsSync as lx}from"node:fs";import{join as yz,resolve as vz}from"node:path";function px(t){if(typeof t=="string")return{conditions:[{event:t,count:1}],timeout:ux};let e=typeof t.timeout=="number"?t.timeout:ux;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 dx(t){if(t){let e=vz(t);return lx(e)?e:null}for(let e of _z){let r=yz(process.cwd(),e);if(lx(r))return r}return null}async function fx(t){let e=gz(t,"utf8"),r=t.endsWith(".json")?JSON.parse(e):bz(e);return wz(r)}function bz(t){return rn.load(t)}function wz(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(F=>typeof F=="string"))O=$.tools;else throw new Error(`hive "${u}".agents[${x}].tools must be 'all' or an array of strings`);let ie;if($.coordination!==void 0)if(typeof $.coordination=="string"&&["lite","full","none"].includes($.coordination))ie=$.coordination;else if(Array.isArray($.coordination)&&$.coordination.every(F=>typeof F=="string"))ie=$.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,de;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 F=$.wake_on;de={types:Array.isArray(F.types)?F.types.filter(ne=>typeof ne=="string"):void 0,timeout:typeof F.timeout=="number"?F.timeout:void 0,max_wakes:typeof F.max_wakes=="number"?F.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:ie,startOn:ee,wake_on:de}})}let y=f.honeycomb??f.comb;if(y!==void 0){if(!y||typeof y!="object")throw new Error(`hive "${u}".honeycomb must be an object`);let b=y;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 ux,_z,mx=w(()=>{"use strict";Ai();ux=0;_z=["brood.yaml","brood.yml","brood.json"]});import{createServer as xz}from"node:net";var Mc,hx=w(()=>{"use strict";Mc=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=xz(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 zz}from"node:fs";import{readdirSync as jz,readFileSync as Mz,existsSync as Sx}from"node:fs";import{join as Lz}from"node:path";function $x(t){if(!Sx(t))return[];let e=Mz(t,"utf8").split(`
166
- `).filter(Boolean),r=[];for(let n of e)try{r.push(JSON.parse(n))}catch{}return r}function nf(t){let e=_n(t);return Sx(e)?jz(e).filter(r=>r.endsWith(".jsonl")).sort().reverse().map(r=>Lz(e,r)):[]}function kx(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 Dz,Dc,of=w(()=>{"use strict";bn();Dz=/\x1b\[[0-9;]*m/g,Dc=class{stream;path;constructor(e){kd(e),this.path=$d(e),this.stream=zz(this.path,{flags:"a"})}write(e){this.stream.write(JSON.stringify(e)+`
165
+ `;s.socket.write(i)}}}});import{createWriteStream as Sz}from"node:fs";import{readdirSync as $z,readFileSync as kz,existsSync as gx}from"node:fs";import{join as Ez}from"node:path";function yx(t){if(!gx(t))return[];let e=kz(t,"utf8").split(`
166
+ `).filter(Boolean),r=[];for(let n of e)try{r.push(JSON.parse(n))}catch{}return r}function tf(t){let e=wn(t);return gx(e)?$z(e).filter(r=>r.endsWith(".jsonl")).sort().reverse().map(r=>Ez(e,r)):[]}function vx(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 Tz,Lc,rf=w(()=>{"use strict";xn();Tz=/\x1b\[[0-9;]*m/g,Lc=class{stream;path;constructor(e){Sd(e),this.path=xd(e),this.stream=Sz(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(Dz,"")})}}close(){this.stream.end()}}});var Cx={};V(Cx,{deleteSecret:()=>cf,getSecret:()=>Bz,getSecretsAsEnv:()=>Gz,isKnownProvider:()=>uf,listSecrets:()=>lf,loadSecrets:()=>ho,saveSecrets:()=>qc,setHiveSecret:()=>af,setProviderSecret:()=>sf});import{readFileSync as qz,writeFileSync as Zz,mkdirSync as Uz,chmodSync as Fz,existsSync as Ex}from"node:fs";import{join as Tx}from"node:path";import{homedir as Px}from"node:os";function Ox(){return Tx(Px(),".honeyb","secrets.json")}function ho(){let t=Ox();if(!Ex(t))return{providers:{},hives:{}};try{let e=qz(t,"utf8"),r=JSON.parse(e);return{providers:r.providers??{},hives:r.hives??{}}}catch{return{providers:{},hives:{}}}}function qc(t){let e=Ox(),r=Tx(Px(),".honeyb");Ex(r)||Uz(r,{recursive:!0}),Zz(e,JSON.stringify(t,null,2),{mode:384});try{Fz(e,384)}catch{}}function sf(t,e){let r=ho();r.providers[t]=e,qc(r)}function af(t,e,r){let n=ho();n.hives[t]||(n.hives[t]={}),n.hives[t][e]=r,qc(n)}function cf(t,e){let r=ho();if(e){if(!r.hives[e]?.[t])return!1;delete r.hives[e][t],Object.keys(r.hives[e]).length===0&&delete r.hives[e]}else{if(!r.providers[t])return!1;delete r.providers[t]}return qc(r),!0}function Bz(t,e){let r=ho();if(e&&r.hives[e]?.[t])return r.hives[e][t];if(r.providers[t])return r.providers[t];let n=Rx[t];if(n&&process.env[n])return process.env[n]}function lf(){let t=ho();return{providers:Object.keys(t.providers),hives:Object.fromEntries(Object.entries(t.hives).map(([e,r])=>[e,Object.keys(r)]))}}function uf(t){return Hz.has(t)}function Gz(){let t=ho(),e={};for(let[r,n]of Object.entries(t.providers)){let o=Rx[r];o&&(e[o]=n)}return e}var Hz,Rx,pf=w(()=>{"use strict";Hz=new Set(["cerebras","groq","openai","anthropic","ollama"]),Rx={cerebras:"CEREBRAS_API_KEY",groq:"GROQ_API_KEY",openai:"OPENAI_API_KEY",anthropic:"ANTHROPIC_API_KEY",ollama:"OLLAMA_HOST"}});var Mx={};V(Mx,{up:()=>Qz});import{spawn as Vz}from"node:child_process";import{mkdirSync as ff,writeFileSync as Ax,existsSync as Wz,unlinkSync as Ix,readFileSync as Jz}from"node:fs";import{join as Sn,dirname as _s,resolve as zi}from"node:path";import{tmpdir as Nx}from"node:os";import{randomBytes as zx}from"node:crypto";import{createRequire as Kz}from"node:module";function Xz(t,e){let r=[Sn(e,"__placeholder.js"),import.meta.url];for(let n of r)try{return Kz(n).resolve(t)}catch{}return null}function jx(){return Sn(process.cwd(),".honeyb")}function df(){return Sn(jx(),"brood.state.json")}async function Qz(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(Tz,"")})}}close(){this.stream.end()}}});var kx={};V(kx,{up:()=>zz});import{spawn as Pz}from"node:child_process";import{mkdirSync as of,writeFileSync as bx,existsSync as Rz,unlinkSync as _x,readFileSync as wx,readdirSync as Oz}from"node:fs";import{join as qr,dirname as vs,resolve as Ni}from"node:path";import{tmpdir as xx,homedir as Cz}from"node:os";import{randomBytes as Sx}from"node:crypto";import{createRequire as Iz}from"node:module";function Nz(t,e){let r=[qr(e,"__placeholder.js"),import.meta.url];for(let n of r)try{return Iz(n).resolve(t)}catch{}return null}function $x(){return qr(process.cwd(),".honeyb")}function nf(){return qr($x(),"brood.state.json")}async function zz(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
169
169
  ${g("bold","wgl up")} \u2014 start a local brood (multi-hive incubator cluster)
170
170
 
171
171
  ${g("cyan","USAGE:")}
@@ -193,12 +193,13 @@ ${g("cyan","EXAMPLES:")}
193
193
  wgl up
194
194
  wgl up --file ./my-project/brood.yaml
195
195
  wgl up --base-port 4000
196
- `);return}Wz(df())&&(console.log(_("A brood is already running")),console.log(g("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,y=d??process.env.WAGGLE_DANCES??void 0,v=_x(o??r),b;if(v)try{b=await bx(v)}catch(M){console.log(_(`Invalid brood file: ${M.message}`)),process.exit(1);return}else if(h){let M=h.replace(/\.(acp|yaml|yml|json)$/i,"").split("/").pop()??"default";b={name:M,provider:m??"ollama/qwen3:8b",dances:y,hives:{[M]:{acp:h,dances:y}}},v=Sn(process.cwd(),"brood.yaml")}else{console.log(_("No brood.yaml found and no --spec provided")),console.log(g("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(M=>(b.hives[M].agents?.length??0)>0),O=$.some(M=>b.hives[M].agents?.some(B=>!B.type||B.type==="worker"||B.type==="drone")),ie=process.cwd(),X=process.argv[1],ee=null;if(O&&(ee=Xz(Yz,ie),!ee)){console.log(_("Hive not installed (required for worker/drone agents)")),console.log(`
196
+ `);return}Rz(nf())&&(console.log(_("A brood is already running")),console.log(g("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,y=d??process.env.WAGGLE_DANCES??void 0,v=dx(o??r),b;if(v)try{b=await fx(v)}catch(M){console.log(_(`Invalid brood file: ${M.message}`)),process.exit(1);return}else if(h){let M=h.replace(/\.(acp|yaml|yml|json)$/i,"").split("/").pop()??"default";b={name:M,provider:m??"ollama/qwen3:8b",dances:y,hives:{[M]:{acp:h,dances:y}}},v=qr(process.cwd(),"brood.yaml")}else{console.log(_("No brood.yaml found and no --spec provided")),console.log(g("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(M=>(b.hives[M].agents?.length??0)>0),O=$.some(M=>b.hives[M].agents?.some(H=>!H.type||H.type==="worker"||H.type==="drone")),ie=process.cwd(),X=process.argv[1],ee=null;if(O&&(ee=Nz(Az,ie),!ee)){console.log(_("Hive not installed (required for worker/drone agents)")),console.log(`
197
197
  Install it with:
198
198
  ${g("cyan","npm install @honeybee-ai/hive")}
199
- `),process.exit(1);return}let de={};try{let{getSecretsAsEnv:M}=await Promise.resolve().then(()=>(pf(),Cx));de=M()}catch{}let F={...process.env,...de,...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 ne=zx(4).toString("hex"),ct=Sn(Nx(),`honeybee-brood-${ne}`);ff(ct,{recursive:!0});let kt=Sn(ct,"broker.sock"),re=new Lc({onHiveConnect:M=>console.log(A(`Hive "${M}" connected to broker`)),onHiveDisconnect:M=>console.log(sr(`Hive "${M}" disconnected`))});await re.listen(kt),console.log(A("IPC broker started"));let le=new Map,At={},oe=i,ve=i+100,Qe=null;try{Qe=new Dc,console.log(g("dim",` Logging to ${Qe.path}`))}catch{}for(let[M,B]of Object.entries(b.hives)){let wr=B.port??oe++,ot=B.worktree?zi(_s(v),B.worktree):_s(v),Re=tj(B,v,M),Yt=["--http",`--port=${wr}`,"--log-format=json"];Re&&Yt.push(`--protocol=${Re}`);let ls=y??B.dances??b.dances;if(ls){let Tt=zi(_s(v),ls);Yt.push(`--dances=${Tt}`)}let Nr=B.agents?.length?B.agents:ej(Re);if(Nr.length){let Tt=ve++,K=B.worktree?zi(_s(v),B.worktree):zi(_s(v)),ae={provider:b.provider??"ollama/qwen3:8b",stagger:b.stagger??2,noAcp:a,propolisPort:Tt,worktree:K,hiveEntry:ee??"",...Re?{protocolPath:Re}:{},agents:Nr.map(ge=>({role:ge.role,count:ge.count,type:ge.type,tools:ge.tools,coordination:ge.coordination,modelHint:ge.model_hint??null,prompt:ge.prompt??null,startOn:ge.startOn?vx(ge.startOn):null,wakeOn:ge.wake_on?{types:ge.wake_on.types??null,timeout:ge.wake_on.timeout??0,maxWakes:ge.wake_on.max_wakes??0}:null})),models:b.models,env:b.env};Yt.push(`--agents=${JSON.stringify(ae)}`),Yt.push("--verbose");let Le=Nr.filter(ge=>!ge.type||ge.type==="worker").reduce((ge,dt)=>ge+(dt.count??1),0),me=Nr.filter(ge=>ge.type==="drone").reduce((ge,dt)=>ge+(dt.count??1),0),Ge=Nr.filter(ge=>ge.type==="claude").reduce((ge,dt)=>ge+(dt.count??1),0),Ce=[];Le>0&&Ce.push(`${Le} worker${Le!==1?"s":""}`),me>0&&Ce.push(`${me} drone${me!==1?"s":""}`),Ge>0&&Ce.push(`${Ge} claude${Ge!==1?"s":""}`),console.log(S(`${M}/agents`,`${Ce.join(" + ")} (delegated to incubator)`))}let gn={...F,HONEYCOMB_BROKER_SOCKET:kt,HONEYCOMB_HIVE_NAME:M};B.honeycomb?.publishes?.length&&(gn.HONEYCOMB_PUBLISHES=B.honeycomb.publishes.join(",")),B.honeycomb?.subscribes?.length&&(gn.HONEYCOMB_SUBSCRIBES=B.honeycomb.subscribes.join(","));let Et=Vz(process.execPath,[X,"incubator",...Yt],{env:gn,cwd:ot,stdio:["ignore","pipe","pipe"]});Et.stdout?.on("data",Tt=>{for(let K of Tt.toString().split(`
200
- `))K.trim()&&Qe?.writeLine(K,M,"info")}),Et.stderr?.on("data",Tt=>{let K=Tt.toString().trim();K&&(console.log(g("dim",`[${M}] ${K}`)),Qe?.writeLine(K,M,"info"))}),Et.on("exit",Tt=>{le.delete(`incubator:${M}`),Tt!==null&&Tt!==0&&console.log(sr(`Hive "${M}" incubator exited with code ${Tt}`))}),Et.pid&&(le.set(`incubator:${M}`,Et),At[M]={pid:Et.pid,port:wr},console.log(S(M,`incubator port ${wr} (pid ${Et.pid})`)))}ff(jx(),{recursive:!0});let Yr={name:b.name,socketPath:kt,hives:At,startedAt:new Date().toISOString()};Ax(df(),JSON.stringify(Yr,null,2)),console.log(),console.log(A(`Brood "${b.name}" running (${x.length} hive${x.length!==1?"s":""})`)),console.log(g("dim"," Press Ctrl+C or run `wgl down` to stop"));let je=async()=>{console.log(`
201
- `+g("dim","Shutting down..."));for(let[M,B]of le)B.kill("SIGTERM"),console.log(g("dim",` Stopped ${M}`));await re.close(),Qe?.close();try{Ix(kt)}catch{}try{Ix(df())}catch{}console.log(A("Brood stopped")),process.exit(0)};process.on("SIGINT",je),process.on("SIGTERM",je),await new Promise(()=>{})}function ej(t){if(!t||t.startsWith("http://")||t.startsWith("https://"))return[];try{let e=Jz(t,"utf-8"),n=(t.endsWith(".json")?JSON.parse(e):Qr.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 tj(t,e,r){let n=t.acp??t.protocol;if(!n)return;if(typeof n=="string")return n.startsWith("http://")||n.startsWith("https://")?n:zi(_s(e),n);let o=Sn(Nx(),`honeybee-protocol-${zx(4).toString("hex")}`);ff(o,{recursive:!0});let s=Sn(o,`${r}.acp.json`);return Ax(s,JSON.stringify(n,null,2)),s}var Yz,Lx=w(()=>{"use strict";Ee();wx();xx();of();Ni();Yz="@honeybee-ai/hive"});var Zx={};V(Zx,{down:()=>sj});import{readFileSync as rj,existsSync as mf,unlinkSync as Dx,rmSync as nj}from"node:fs";import{join as qx}from"node:path";function oj(){let t=qx(process.cwd(),".honeyb","brood.state.json");if(mf(t))return t;let e=qx(process.cwd(),".honeybee","brood.state.json");return mf(e)?e:t}async function sj(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
199
+ `),process.exit(1);return}let de={};try{let M=qr(Cz(),".secrets"),H=Oz(M).filter(zt=>zt.endsWith(".env"));for(let zt of H){let nt=wx(qr(M,zt),"utf8");for(let Ee of nt.split(`
200
+ `)){let lt=Ee.trim();if(!lt||lt.startsWith("#"))continue;let jr=lt.indexOf("=");if(jr===-1)continue;let Qt=lt.slice(0,jr).trim(),Sr=lt.slice(jr+1).trim();Qt&&Sr&&(de[Qt]=Sr)}}}catch{}let F={...process.env,...de,...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 ne=Sx(4).toString("hex"),ct=qr(xx(),`honeybee-brood-${ne}`);of(ct,{recursive:!0});let Et=qr(ct,"broker.sock"),re=new Mc({onHiveConnect:M=>console.log(A(`Hive "${M}" connected to broker`)),onHiveDisconnect:M=>console.log(ar(`Hive "${M}" disconnected`))});await re.listen(Et),console.log(A("IPC broker started"));let le=new Map,Nt={},oe=i,ve=i+100,Qe=null;try{Qe=new Lc,console.log(g("dim",` Logging to ${Qe.path}`))}catch{}for(let[M,H]of Object.entries(b.hives)){let zt=H.port??oe++,nt=H.worktree?Ni(vs(v),H.worktree):vs(v),Ee=Mz(H,v,M),lt=["--http",`--port=${zt}`,"--log-format=json"];Ee&&lt.push(`--protocol=${Ee}`);let jr=y??H.dances??b.dances;if(jr){let Pt=Ni(vs(v),jr);lt.push(`--dances=${Pt}`)}let Qt=H.agents?.length?H.agents:jz(Ee);if(Qt.length){let Pt=ve++,K=H.worktree?Ni(vs(v),H.worktree):Ni(vs(v)),ae={provider:b.provider??"ollama/qwen3:8b",stagger:b.stagger??2,noAcp:a,propolisPort:Pt,worktree:K,hiveEntry:ee??"",...Ee?{protocolPath:Ee}:{},agents:Qt.map(ge=>({role:ge.role,count:ge.count,type:ge.type,tools:ge.tools,coordination:ge.coordination,modelHint:ge.model_hint??null,prompt:ge.prompt??null,startOn:ge.startOn?px(ge.startOn):null,wakeOn:ge.wake_on?{types:ge.wake_on.types??null,timeout:ge.wake_on.timeout??0,maxWakes:ge.wake_on.max_wakes??0}:null})),models:b.models,env:b.env};lt.push(`--agents=${JSON.stringify(ae)}`),lt.push("--verbose");let Le=Qt.filter(ge=>!ge.type||ge.type==="worker").reduce((ge,ft)=>ge+(ft.count??1),0),me=Qt.filter(ge=>ge.type==="drone").reduce((ge,ft)=>ge+(ft.count??1),0),Ge=Qt.filter(ge=>ge.type==="claude").reduce((ge,ft)=>ge+(ft.count??1),0),Ce=[];Le>0&&Ce.push(`${Le} worker${Le!==1?"s":""}`),me>0&&Ce.push(`${me} drone${me!==1?"s":""}`),Ge>0&&Ce.push(`${Ge} claude${Ge!==1?"s":""}`),console.log(S(`${M}/agents`,`${Ce.join(" + ")} (delegated to incubator)`))}let Sr={...F,HONEYCOMB_BROKER_SOCKET:Et,HONEYCOMB_HIVE_NAME:M};H.honeycomb?.publishes?.length&&(Sr.HONEYCOMB_PUBLISHES=H.honeycomb.publishes.join(",")),H.honeycomb?.subscribes?.length&&(Sr.HONEYCOMB_SUBSCRIBES=H.honeycomb.subscribes.join(","));let Tt=Pz(process.execPath,[X,"incubator",...lt],{env:Sr,cwd:nt,stdio:["ignore","pipe","pipe"]});Tt.stdout?.on("data",Pt=>{for(let K of Pt.toString().split(`
201
+ `))K.trim()&&Qe?.writeLine(K,M,"info")}),Tt.stderr?.on("data",Pt=>{let K=Pt.toString().trim();K&&(console.log(g("dim",`[${M}] ${K}`)),Qe?.writeLine(K,M,"info"))}),Tt.on("exit",Pt=>{le.delete(`incubator:${M}`),Pt!==null&&Pt!==0&&console.log(ar(`Hive "${M}" incubator exited with code ${Pt}`))}),Tt.pid&&(le.set(`incubator:${M}`,Tt),Nt[M]={pid:Tt.pid,port:zt},console.log(S(M,`incubator port ${zt} (pid ${Tt.pid})`)))}of($x(),{recursive:!0});let en={name:b.name,socketPath:Et,hives:Nt,startedAt:new Date().toISOString()};bx(nf(),JSON.stringify(en,null,2)),console.log(),console.log(A(`Brood "${b.name}" running (${x.length} hive${x.length!==1?"s":""})`)),console.log(g("dim"," Press Ctrl+C or run `wgl down` to stop"));let je=async()=>{console.log(`
202
+ `+g("dim","Shutting down..."));for(let[M,H]of le)H.kill("SIGTERM"),console.log(g("dim",` Stopped ${M}`));await re.close(),Qe?.close();try{_x(Et)}catch{}try{_x(nf())}catch{}console.log(A("Brood stopped")),process.exit(0)};process.on("SIGINT",je),process.on("SIGTERM",je),await new Promise(()=>{})}function jz(t){if(!t||t.startsWith("http://")||t.startsWith("https://"))return[];try{let e=wx(t,"utf-8"),n=(t.endsWith(".json")?JSON.parse(e):rn.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 Mz(t,e,r){let n=t.acp??t.protocol;if(!n)return;if(typeof n=="string")return n.startsWith("http://")||n.startsWith("https://")?n:Ni(vs(e),n);let o=qr(xx(),`honeybee-protocol-${Sx(4).toString("hex")}`);of(o,{recursive:!0});let s=qr(o,`${r}.acp.json`);return bx(s,JSON.stringify(n,null,2)),s}var Az,Ex=w(()=>{"use strict";Te();mx();hx();rf();Ai();Az="@honeybee-ai/hive"});var Rx={};V(Rx,{down:()=>Zz});import{readFileSync as Lz,existsSync as sf,unlinkSync as Tx,rmSync as Dz}from"node:fs";import{join as Px}from"node:path";function qz(){let t=Px(process.cwd(),".honeyb","brood.state.json");if(sf(t))return t;let e=Px(process.cwd(),".honeybee","brood.state.json");return sf(e)?e:t}async function Zz(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
202
203
  ${g("bold","wgl down")} \u2014 stop a running brood
203
204
 
204
205
  ${g("cyan","USAGE:")}
@@ -211,7 +212,7 @@ ${g("cyan","DESCRIPTION:")}
211
212
 
212
213
  ${g("cyan","EXAMPLES:")}
213
214
  wgl down
214
- `);return}let e=oj();if(!mf(e)){console.log(_("No running brood found")),console.log(g("dim"," No .honeyb/brood.state.json in current directory")),process.exit(1);return}let r;try{r=JSON.parse(rj(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,g("dim",`not running (pid ${i.pid})`)))}if(r.socketPath){try{Dx(r.socketPath)}catch{}let{dirname:s}=await import("node:path");try{nj(s(r.socketPath),{recursive:!0,force:!0})}catch{}}try{Dx(e)}catch{}let o=Object.keys(r.hives).length;console.log(),console.log(A(`Brood stopped (${o} hive${o!==1?"s":""} terminated)`))}var Ux=w(()=>{"use strict";Ee()});var Fx={};V(Fx,{logs:()=>pj});import{existsSync as ij,readdirSync as aj,unlinkSync as cj,statSync as lj}from"node:fs";import{join as uj}from"node:path";async function pj(t){let e=t[0];if(e==="--help"||e==="-h"){console.log(`
215
+ `);return}let e=qz();if(!sf(e)){console.log(_("No running brood found")),console.log(g("dim"," No .honeyb/brood.state.json in current directory")),process.exit(1);return}let r;try{r=JSON.parse(Lz(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,g("dim",`not running (pid ${i.pid})`)))}if(r.socketPath){try{Tx(r.socketPath)}catch{}let{dirname:s}=await import("node:path");try{Dz(s(r.socketPath),{recursive:!0,force:!0})}catch{}}try{Tx(e)}catch{}let o=Object.keys(r.hives).length;console.log(),console.log(A(`Brood stopped (${o} hive${o!==1?"s":""} terminated)`))}var Ox=w(()=>{"use strict";Te()});var Cx={};V(Cx,{logs:()=>Vz});import{existsSync as Uz,readdirSync as Fz,unlinkSync as Hz,statSync as Bz}from"node:fs";import{join as Gz}from"node:path";async function Vz(t){let e=t[0];if(e==="--help"||e==="-h"){console.log(`
215
216
  ${g("bold","wgl logs")} \u2014 view brood run logs
216
217
 
217
218
  ${g("cyan","USAGE:")}
@@ -225,7 +226,7 @@ ${g("cyan","USAGE:")}
225
226
  wgl logs --json Raw JSONL output (default for pipe)
226
227
  wgl logs --clean Delete old log files
227
228
  wgl logs --list List available log files
228
- `);return}let r=dj(t);if(r.clean){await mj();return}if(r.list){await hj();return}let n=nf();if(n.length===0){console.log(_("No log files found")),console.log(g("dim",` Log directory: ${_n()}`)),console.log(g("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=$x(s),a=i;if(r.level){let l=fj(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(g("dim",` ${a.length} entries (of ${i.length} total)`)),console.log());for(let l of a)console.log(c?kx(l):JSON.stringify(l))}function dj(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 fj(t){let e=["debug","info","warn","error"],r=e.indexOf(t);return r<0?new Set(e):new Set(e.slice(r))}async function mj(){let t=_n();if(!ij(t)){console.log("No log directory found");return}let e=aj(t).filter(r=>r.endsWith(".jsonl"));for(let r of e)cj(uj(t,r));console.log(`Deleted ${e.length} log file(s)`)}async function hj(){let t=nf();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=lj(t[e]),o=n.size<1024?`${n.size}B`:`${(n.size/1024).toFixed(1)}KB`,s=e===0?" (latest)":"";console.log(S(`${e}`,`${r} ${g("dim",o)}${s}`))}}var Hx=w(()=>{"use strict";Ee();of();bn()});var Gx={};V(Gx,{inspect:()=>gj});async function gj(t){let e=t[0]||"overview";if(e==="--help"||e==="-h"){console.log(`
229
+ `);return}let r=Wz(t);if(r.clean){await Kz();return}if(r.list){await Yz();return}let n=tf();if(n.length===0){console.log(_("No log files found")),console.log(g("dim",` Log directory: ${wn()}`)),console.log(g("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=yx(s),a=i;if(r.level){let l=Jz(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(g("dim",` ${a.length} entries (of ${i.length} total)`)),console.log());for(let l of a)console.log(c?vx(l):JSON.stringify(l))}function Wz(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 Jz(t){let e=["debug","info","warn","error"],r=e.indexOf(t);return r<0?new Set(e):new Set(e.slice(r))}async function Kz(){let t=wn();if(!Uz(t)){console.log("No log directory found");return}let e=Fz(t).filter(r=>r.endsWith(".jsonl"));for(let r of e)Hz(Gz(t,r));console.log(`Deleted ${e.length} log file(s)`)}async function Yz(){let t=tf();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=Bz(t[e]),o=n.size<1024?`${n.size}B`:`${(n.size/1024).toFixed(1)}KB`,s=e===0?" (latest)":"";console.log(S(`${e}`,`${r} ${g("dim",o)}${s}`))}}var Ix=w(()=>{"use strict";Te();rf();xn()});var Nx={};V(Nx,{inspect:()=>Xz});async function Xz(t){let e=t[0]||"overview";if(e==="--help"||e==="-h"){console.log(`
229
230
  ${g("bold","wgl inspect")} \u2014 runtime introspection
230
231
 
231
232
  ${g("cyan","USAGE:")}
@@ -241,9 +242,9 @@ ${g("cyan","USAGE:")}
241
242
 
242
243
  ${g("cyan","OPTIONS:")}
243
244
  --server=URL Override incubator URL (default: from .wglrc or localhost:3100)
244
- `);return}let r=t.find(s=>s.startsWith("--server=")),n=jr(),o=r?r.slice(9):n.server||`http://localhost:${n.incubator.port}`;switch(e){case"overview":return yj(o);case"agents":return vj(o);case"agent":return _j(o,t[1]);case"events":return bj(o,t);case"protocol":return wj(o);case"tokens":return xj(o,n);case"health":return Sj(o);case"governance":return $j(o);default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl inspect --help` for usage"),process.exit(2)}}async function er(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 yj(t){try{let[e,r,n]=await Promise.all([er(t,"/api/health"),er(t,"/api/runs/summary"),er(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(g("dim",` ${e.message}`)),process.exit(1)}}async function vj(t){try{let r=(await er(t,"/api/runs")).runs||[];if(r.length===0){console.log("No agents registered");return}console.log(C("Agents")),console.log();let n=Bx("Agent ID","Role","Status","Iters","Tokens","Elapsed");console.log(g("dim",n)),console.log(g("dim","\u2500".repeat(n.length)));for(let o of r){let s=o.status==="running"?"green":o.status==="error"?"red":"dim";console.log(Bx(o.agentId,o.role,g(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(g("dim",` ${e.message}`)),process.exit(1)}}async function _j(t,e){if(!e){console.log(_("Usage: wgl inspect agent <id>")),process.exit(2);return}try{let r=await er(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",g("red",n.error)));try{let o=await er(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(g("dim",` ${r.message}`)),process.exit(1)}}async function bj(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 er(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(`${g("dim",u)} ${g("cyan",l.type)} ${g("dim",`by ${l.agentId||"system"}`)}`)}}catch(s){console.log(_(`Cannot connect to ${t}`)),console.log(g("dim",` ${s.message}`)),process.exit(1)}}async function wj(t){try{let e=await er(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 er(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(g("dim",` ${e.message}`)),process.exit(1)}}async function xj(t,e){try{let n=(await er(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(g("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(g("dim",` ${r.message}`)),process.exit(1)}}async function Sj(t){try{let e=await er(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(g("dim",` ${e.message}`)),process.exit(1)}}async function $j(t){try{let[e,r]=await Promise.all([er(t,"/api/governance/proposals").catch(()=>({proposals:[]})),er(t,"/api/control/status").catch(()=>({}))]);console.log(C("Governance")),r.halted?(console.log(S("Status",g("red","HALTED"))),r.reason&&console.log(S("Reason",r.reason))):r.paused?console.log(S("Status",g("yellow","PAUSED"))):console.log(S("Status",g("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(g("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 Bx(...t){let e=[20,14,12,6,12,10];return t.map((r,n)=>r.padEnd(e[n]||10)).join(" ")}var Vx=w(()=>{"use strict";Ee();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 tr(t){return t&&Object.assign(Uc,t),Uc}var kj,Ej,en,Uc,bs=w(()=>{kj=Object.freeze({status:"aborted"});Ej=Symbol("zod_brand"),en=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Uc={}});var be={};V(be,{BIGINT_FORMAT_RANGES:()=>Jx,Class:()=>gf,NUMBER_FORMAT_RANGES:()=>Sf,aborted:()=>yo,allowsEval:()=>bf,assert:()=>Cj,assertEqual:()=>Tj,assertIs:()=>Rj,assertNever:()=>Oj,assertNotEqual:()=>Pj,assignProp:()=>_f,cached:()=>Li,captureStackTrace:()=>Hc,cleanEnum:()=>Hj,cleanRegex:()=>qi,clone:()=>rr,createTransparentProxy:()=>Mj,defineLazy:()=>De,esc:()=>go,escapeRegex:()=>$n,extend:()=>qj,finalizeIssue:()=>$r,floatSafeRemainder:()=>vf,getElementAtPath:()=>Ij,getEnumValues:()=>Mi,getLengthableOrigin:()=>Zi,getParsedType:()=>jj,getSizableOrigin:()=>Kx,isObject:()=>ws,isPlainObject:()=>xs,issue:()=>$f,joinValues:()=>Fc,jsonStringifyReplacer:()=>yf,merge:()=>Zj,normalizeParams:()=>W,nullish:()=>Di,numKeys:()=>zj,omit:()=>Dj,optionalKeys:()=>xf,partial:()=>Uj,pick:()=>Lj,prefixIssues:()=>Lr,primitiveTypes:()=>Wx,promiseAllObject:()=>Aj,propertyKeyTypes:()=>wf,randomString:()=>Nj,required:()=>Fj,stringifyPrimitive:()=>Bc,unwrapMessage:()=>ji});function Tj(t){return t}function Pj(t){return t}function Rj(t){}function Oj(t){throw new Error}function Cj(t){}function Mi(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 Fc(t,e="|"){return t.map(r=>Bc(r)).join(e)}function yf(t,e){return typeof e=="bigint"?e.toString():e}function Li(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Di(t){return t==null}function qi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function vf(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 De(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 _f(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Ij(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Aj(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 Nj(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function go(t){return JSON.stringify(t)}function ws(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xs(t){if(ws(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ws(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function zj(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 rr(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 Mj(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 Bc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function xf(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Lj(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 rr(t,{...t._zod.def,shape:r,checks:[]})}function Dj(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 rr(t,{...t._zod.def,shape:r,checks:[]})}function qj(t,e){if(!xs(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 _f(this,"shape",n),n},checks:[]};return rr(t,r)}function Zj(t,e){return rr(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return _f(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Uj(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 rr(e,{...e._zod.def,shape:o,checks:[]})}function Fj(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 rr(e,{...e._zod.def,shape:o,checks:[]})}function yo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Lr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ji(t){return typeof t=="string"?t:t?.message}function $r(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=ji(t.inst?._zod.def?.error?.(t))??ji(e?.error?.(t))??ji(r.customError?.(t))??ji(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Kx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Zi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function $f(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Hj(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Hc,bf,jj,wf,Wx,Sf,Jx,gf,Dr=w(()=>{Hc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};bf=Li(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});jj=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}`)}},wf=new Set(["string","number","symbol"]),Wx=new Set(["string","number","bigint","boolean","symbol","undefined"]);Sf={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]},Jx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};gf=class{constructor(...e){}}});function kf(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 Ef(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 Yx,Gc,Ui,Tf=w(()=>{bs();Dr();Yx=(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,yf,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Gc=E("$ZodError",Yx),Ui=E("$ZodError",Yx,{Parent:Error})});var Pf,Rf,Of,Cf,If,vo,Af,_o,Nf=w(()=>{bs();Tf();Dr();Pf=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 en;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>$r(c,s,tr())));throw Hc(a,o?.callee),a}return i.value},Rf=Pf(Ui),Of=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=>$r(c,s,tr())));throw Hc(a,o?.callee),a}return i.value},Cf=Of(Ui),If=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 en;return s.issues.length?{success:!1,error:new(t??Gc)(s.issues.map(i=>$r(i,o,tr())))}:{success:!0,data:s.value}},vo=If(Ui),Af=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=>$r(i,o,tr())))}:{success:!0,data:s.value}},_o=Af(Ui)});function a0(){return new RegExp(Gj,"u")}function y0(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 v0(t){return new RegExp(`^${y0(t)}$`)}function _0(t){let e=y0({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(`^${h0}T(?:${n})$`)}var Xx,Qx,e0,t0,r0,n0,o0,s0,zf,i0,Gj,c0,l0,u0,p0,d0,jf,f0,m0,h0,g0,b0,w0,x0,S0,$0,k0,E0,Wc=w(()=>{Xx=/^[cC][^\s-]{8,}$/,Qx=/^[0-9a-z]+$/,e0=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,t0=/^[0-9a-vA-V]{20}$/,r0=/^[A-Za-z0-9]{27}$/,n0=/^[a-zA-Z0-9_-]{21}$/,o0=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,s0=/^([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})$/,zf=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)$/,i0=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Gj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";c0=/^(?:(?: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])$/,l0=/^(([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})$/,u0=/^((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])$/,p0=/^(([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])$/,d0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,jf=/^[A-Za-z0-9_-]*$/,f0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,m0=/^\+(?:[0-9]){6,14}[0-9]$/,h0="(?:(?:\\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])))",g0=new RegExp(`^${h0}$`);b0=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},w0=/^\d+$/,x0=/^-?\d+(?:\.\d+)?/i,S0=/true|false/i,$0=/null/i,k0=/^[^A-Z]*$/,E0=/^[^a-z]*$/});var vt,T0,Mf,Lf,P0,R0,O0,C0,I0,Fi,A0,N0,z0,j0,M0,L0,D0,Jc=w(()=>{bs();Wc();Dr();vt=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),T0={number:"number",bigint:"bigint",object:"date"},Mf=E("$ZodCheckLessThan",(t,e)=>{vt.init(t,e);let r=T0[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})}}),Lf=E("$ZodCheckGreaterThan",(t,e)=>{vt.init(t,e);let r=T0[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})}}),P0=E("$ZodCheckMultipleOf",(t,e)=>{vt.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):vf(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})}}),R0=E("$ZodCheckNumberFormat",(t,e)=>{vt.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Sf[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=w0)}),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})}}),O0=E("$ZodCheckMaxLength",(t,e)=>{var r;vt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Di(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=Zi(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;vt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Di(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=Zi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),I0=E("$ZodCheckLengthEquals",(t,e)=>{var r;vt.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Di(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=Zi(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})}}),Fi=E("$ZodCheckStringFormat",(t,e)=>{var r,n;vt.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=()=>{})}),A0=E("$ZodCheckRegex",(t,e)=>{Fi.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})}}),N0=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=k0),Fi.init(t,e)}),z0=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=E0),Fi.init(t,e)}),j0=E("$ZodCheckIncludes",(t,e)=>{vt.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)=>{vt.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})}}),L0=E("$ZodCheckEndsWith",(t,e)=>{vt.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})}}),D0=E("$ZodCheckOverwrite",(t,e)=>{vt.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Kc,Df=w(()=>{Kc=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
+ `);return}let r=t.find(s=>s.startsWith("--server=")),n=Lr(),o=r?r.slice(9):n.server||`http://localhost:${n.incubator.port}`;switch(e){case"overview":return Qz(o);case"agents":return ej(o);case"agent":return tj(o,t[1]);case"events":return rj(o,t);case"protocol":return nj(o);case"tokens":return oj(o,n);case"health":return sj(o);case"governance":return ij(o);default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl inspect --help` for usage"),process.exit(2)}}async function rr(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 Qz(t){try{let[e,r,n]=await Promise.all([rr(t,"/api/health"),rr(t,"/api/runs/summary"),rr(t,"/api/protocol").catch(()=>null)]);console.log(C("Incubator Overview")),console.log(S("Server",t)),console.log(S("Uptime",Dc(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(g("dim",` ${e.message}`)),process.exit(1)}}async function ej(t){try{let r=(await rr(t,"/api/runs")).runs||[];if(r.length===0){console.log("No agents registered");return}console.log(C("Agents")),console.log();let n=Ax("Agent ID","Role","Status","Iters","Tokens","Elapsed");console.log(g("dim",n)),console.log(g("dim","\u2500".repeat(n.length)));for(let o of r){let s=o.status==="running"?"green":o.status==="error"?"red":"dim";console.log(Ax(o.agentId,o.role,g(s,o.status),String(o.iterations||0),(o.usage?.totalTokens||0).toLocaleString(),o.elapsed?Dc(o.elapsed):"-"))}}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(g("dim",` ${e.message}`)),process.exit(1)}}async function tj(t,e){if(!e){console.log(_("Usage: wgl inspect agent <id>")),process.exit(2);return}try{let r=await rr(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",Dc(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",g("red",n.error)));try{let o=await rr(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(g("dim",` ${r.message}`)),process.exit(1)}}async function rj(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 rr(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(`${g("dim",u)} ${g("cyan",l.type)} ${g("dim",`by ${l.agentId||"system"}`)}`)}}catch(s){console.log(_(`Cannot connect to ${t}`)),console.log(g("dim",` ${s.message}`)),process.exit(1)}}async function nj(t){try{let e=await rr(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 rr(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(g("dim",` ${e.message}`)),process.exit(1)}}async function oj(t,e){try{let n=(await rr(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(g("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(g("dim",` ${r.message}`)),process.exit(1)}}async function sj(t){try{let e=await rr(t,"/api/health");console.log(C("Server Health")),console.log(S("Server",t)),console.log(S("Uptime",Dc(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(g("dim",` ${e.message}`)),process.exit(1)}}async function ij(t){try{let[e,r]=await Promise.all([rr(t,"/api/governance/proposals").catch(()=>({proposals:[]})),rr(t,"/api/control/status").catch(()=>({}))]);console.log(C("Governance")),r.halted?(console.log(S("Status",g("red","HALTED"))),r.reason&&console.log(S("Reason",r.reason))):r.paused?console.log(S("Status",g("yellow","PAUSED"))):console.log(S("Status",g("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(g("dim",` ${e.message}`)),process.exit(1)}}function Dc(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 Ax(...t){let e=[20,14,12,6,12,10];return t.map((r,n)=>r.padEnd(e[n]||10)).join(" ")}var zx=w(()=>{"use strict";Te();xn()});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 nr(t){return t&&Object.assign(qc,t),qc}var aj,cj,nn,qc,_s=w(()=>{aj=Object.freeze({status:"aborted"});cj=Symbol("zod_brand"),nn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},qc={}});var be={};V(be,{BIGINT_FORMAT_RANGES:()=>Mx,Class:()=>cf,NUMBER_FORMAT_RANGES:()=>hf,aborted:()=>yo,allowsEval:()=>df,assert:()=>fj,assertEqual:()=>lj,assertIs:()=>pj,assertNever:()=>dj,assertNotEqual:()=>uj,assignProp:()=>pf,cached:()=>Mi,captureStackTrace:()=>Uc,cleanEnum:()=>Ej,cleanRegex:()=>Di,clone:()=>or,createTransparentProxy:()=>_j,defineLazy:()=>De,esc:()=>go,escapeRegex:()=>kn,extend:()=>xj,finalizeIssue:()=>Er,floatSafeRemainder:()=>uf,getElementAtPath:()=>mj,getEnumValues:()=>ji,getLengthableOrigin:()=>qi,getParsedType:()=>vj,getSizableOrigin:()=>Lx,isObject:()=>bs,isPlainObject:()=>ws,issue:()=>gf,joinValues:()=>Zc,jsonStringifyReplacer:()=>lf,merge:()=>Sj,normalizeParams:()=>W,nullish:()=>Li,numKeys:()=>yj,omit:()=>wj,optionalKeys:()=>mf,partial:()=>$j,pick:()=>bj,prefixIssues:()=>Zr,primitiveTypes:()=>jx,promiseAllObject:()=>hj,propertyKeyTypes:()=>ff,randomString:()=>gj,required:()=>kj,stringifyPrimitive:()=>Fc,unwrapMessage:()=>zi});function lj(t){return t}function uj(t){return t}function pj(t){}function dj(t){throw new Error}function fj(t){}function ji(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 Zc(t,e="|"){return t.map(r=>Fc(r)).join(e)}function lf(t,e){return typeof e=="bigint"?e.toString():e}function Mi(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Li(t){return t==null}function Di(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function uf(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 De(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 pf(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function mj(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function hj(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 gj(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function go(t){return JSON.stringify(t)}function bs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ws(t){if(bs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(bs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function yj(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function kn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function or(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 _j(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 Fc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function mf(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function bj(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 or(t,{...t._zod.def,shape:r,checks:[]})}function wj(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 or(t,{...t._zod.def,shape:r,checks:[]})}function xj(t,e){if(!ws(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 pf(this,"shape",n),n},checks:[]};return or(t,r)}function Sj(t,e){return or(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return pf(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function $j(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 or(e,{...e._zod.def,shape:o,checks:[]})}function kj(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 or(e,{...e._zod.def,shape:o,checks:[]})}function yo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Zr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function zi(t){return typeof t=="string"?t:t?.message}function Er(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=zi(t.inst?._zod.def?.error?.(t))??zi(e?.error?.(t))??zi(r.customError?.(t))??zi(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Lx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function qi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function gf(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Ej(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Uc,df,vj,ff,jx,hf,Mx,cf,Ur=w(()=>{Uc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};df=Mi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});vj=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}`)}},ff=new Set(["string","number","symbol"]),jx=new Set(["string","number","bigint","boolean","symbol","undefined"]);hf={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]},Mx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};cf=class{constructor(...e){}}});function yf(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 vf(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 Dx,Hc,Zi,_f=w(()=>{_s();Ur();Dx=(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,lf,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Hc=E("$ZodError",Dx),Zi=E("$ZodError",Dx,{Parent:Error})});var bf,wf,xf,Sf,$f,vo,kf,_o,Ef=w(()=>{_s();_f();Ur();bf=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 nn;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Er(c,s,nr())));throw Uc(a,o?.callee),a}return i.value},wf=bf(Zi),xf=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=>Er(c,s,nr())));throw Uc(a,o?.callee),a}return i.value},Sf=xf(Zi),$f=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 nn;return s.issues.length?{success:!1,error:new(t??Hc)(s.issues.map(i=>Er(i,o,nr())))}:{success:!0,data:s.value}},vo=$f(Zi),kf=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=>Er(i,o,nr())))}:{success:!0,data:s.value}},_o=kf(Zi)});function Jx(){return new RegExp(Pj,"u")}function s0(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 i0(t){return new RegExp(`^${s0(t)}$`)}function a0(t){let e=s0({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(`^${n0}T(?:${n})$`)}var qx,Zx,Ux,Fx,Hx,Bx,Gx,Vx,Tf,Wx,Pj,Kx,Yx,Xx,Qx,e0,Pf,t0,r0,n0,o0,c0,l0,u0,p0,d0,f0,m0,Gc=w(()=>{qx=/^[cC][^\s-]{8,}$/,Zx=/^[0-9a-z]+$/,Ux=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Fx=/^[0-9a-vA-V]{20}$/,Hx=/^[A-Za-z0-9]{27}$/,Bx=/^[a-zA-Z0-9_-]{21}$/,Gx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Vx=/^([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})$/,Tf=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)$/,Wx=/^(?!\.)(?!.*\.\.)([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})+$";Kx=/^(?:(?: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])$/,Yx=/^(([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})$/,Xx=/^((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])$/,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})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,e0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Pf=/^[A-Za-z0-9_-]*$/,t0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,r0=/^\+(?:[0-9]){6,14}[0-9]$/,n0="(?:(?:\\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])))",o0=new RegExp(`^${n0}$`);c0=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},l0=/^\d+$/,u0=/^-?\d+(?:\.\d+)?/i,p0=/true|false/i,d0=/null/i,f0=/^[^A-Z]*$/,m0=/^[^a-z]*$/});var _t,h0,Rf,Of,g0,y0,v0,_0,b0,Ui,w0,x0,S0,$0,k0,E0,T0,Vc=w(()=>{_s();Gc();Ur();_t=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),h0={number:"number",bigint:"bigint",object:"date"},Rf=E("$ZodCheckLessThan",(t,e)=>{_t.init(t,e);let r=h0[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})}}),Of=E("$ZodCheckGreaterThan",(t,e)=>{_t.init(t,e);let r=h0[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})}}),g0=E("$ZodCheckMultipleOf",(t,e)=>{_t.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):uf(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})}}),y0=E("$ZodCheckNumberFormat",(t,e)=>{_t.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=hf[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=l0)}),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})}}),v0=E("$ZodCheckMaxLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Li(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=qi(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),_0=E("$ZodCheckMinLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Li(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=qi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),b0=E("$ZodCheckLengthEquals",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Li(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=qi(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})}}),Ui=E("$ZodCheckStringFormat",(t,e)=>{var r,n;_t.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=()=>{})}),w0=E("$ZodCheckRegex",(t,e)=>{Ui.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})}}),x0=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=f0),Ui.init(t,e)}),S0=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=m0),Ui.init(t,e)}),$0=E("$ZodCheckIncludes",(t,e)=>{_t.init(t,e);let r=kn(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})}}),k0=E("$ZodCheckStartsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`^${kn(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})}}),E0=E("$ZodCheckEndsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`.*${kn(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})}}),T0=E("$ZodCheckOverwrite",(t,e)=>{_t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Wc,Cf=w(()=>{Wc=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
246
  `).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 Z0,qf=w(()=>{Z0={major:4,minor:0,patch:0}});function tS(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Vj(t){if(!jf.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return tS(r)}function Wj(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(...Lr(r,t.issues)),e.value[r]=t.value}function Yc(t,e,r){t.issues.length&&e.issues.push(...Lr(r,t.issues)),e.value[r]=t.value}function F0(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(...Lr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function H0(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=>$r(s,n,tr())))}),e}function Zf(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(xs(t)&&xs(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=Zf(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=Zf(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 B0(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),yo(t))return t;let n=Zf(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 G0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function V0(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 W0(t,e,r){return yo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function J0(t){return t.value=Object.freeze(t.value),t}function K0(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($f(o))}}var Ae,Hi,qe,Uf,Ff,Hf,Bf,Gf,Vf,Wf,Jf,Kf,Yf,Xf,Y0,X0,Q0,eS,Qf,em,tm,rm,nm,om,sm,im,Xc,am,cm,lm,um,pm,dm,Qc,el,fm,mm,hm,gm,ym,vm,_m,bm,wm,xm,Sm,$m,km,Em,Tm,rS=w(()=>{Jc();bs();Df();Nf();Wc();Dr();qf();Dr();Ae=E("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=Z0;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=yo(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 en;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=yo(s,p)))});else{if(s.issues.length===p)continue;c||(c=yo(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 en;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=vo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return _o(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Hi=E("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??b0(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}}),qe=E("$ZodStringFormat",(t,e)=>{Fi.init(t,e),Hi.init(t,e)}),Uf=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=s0),qe.init(t,e)}),Ff=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=zf(n))}else e.pattern??(e.pattern=zf());qe.init(t,e)}),Hf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=i0),qe.init(t,e)}),Bf=E("$ZodURL",(t,e)=>{qe.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:f0.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})}}}),Gf=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=a0()),qe.init(t,e)}),Vf=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=n0),qe.init(t,e)}),Wf=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Xx),qe.init(t,e)}),Jf=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Qx),qe.init(t,e)}),Kf=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=e0),qe.init(t,e)}),Yf=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=t0),qe.init(t,e)}),Xf=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=r0),qe.init(t,e)}),Y0=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=_0(e)),qe.init(t,e)}),X0=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=g0),qe.init(t,e)}),Q0=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=v0(e)),qe.init(t,e)}),eS=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=o0),qe.init(t,e)}),Qf=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=c0),qe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),em=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=l0),qe.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})}}}),tm=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=u0),qe.init(t,e)}),rm=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=p0),qe.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})}}});nm=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=d0),qe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{tS(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});om=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=jf),qe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Vj(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),sm=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=m0),qe.init(t,e)});im=E("$ZodJWT",(t,e)=>{qe.init(t,e),t._zod.check=r=>{Wj(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Xc=E("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??x0,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}}),am=E("$ZodNumber",(t,e)=>{R0.init(t,e),Xc.init(t,e)}),cm=E("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=S0,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}}),lm=E("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=$0,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}}),um=E("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),pm=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)});dm=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}});Qc=E("$ZodObject",(t,e)=>{Ae.init(t,e);let r=Li(()=>{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=xf(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(f)}});De(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 Kc(["shape","payload","ctx"]),d=r.value,m=b=>{let x=go(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),y=0;for(let b of d.keys)h[b]=`key_${y++}`;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 $=go(b);f.write(`
247
+ `))}}});var R0,If=w(()=>{R0={major:4,minor:0,patch:0}});function F0(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Rj(t){if(!Pf.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return F0(r)}function Oj(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 O0(t,e,r){t.issues.length&&e.issues.push(...Zr(r,t.issues)),e.value[r]=t.value}function Jc(t,e,r){t.issues.length&&e.issues.push(...Zr(r,t.issues)),e.value[r]=t.value}function C0(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(...Zr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function I0(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=>Er(s,n,nr())))}),e}function Af(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(ws(t)&&ws(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=Af(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=Af(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 A0(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),yo(t))return t;let n=Af(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 N0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function z0(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 j0(t,e,r){return yo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function M0(t){return t.value=Object.freeze(t.value),t}function L0(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(gf(o))}}var Ae,Fi,qe,Nf,zf,jf,Mf,Lf,Df,qf,Zf,Uf,Ff,Hf,D0,q0,Z0,U0,Bf,Gf,Vf,Wf,Jf,Kf,Yf,Xf,Kc,Qf,em,tm,rm,nm,om,Yc,Xc,sm,im,am,cm,lm,um,pm,dm,fm,mm,hm,gm,ym,vm,_m,H0=w(()=>{Vc();_s();Cf();Ef();Gc();Ur();If();Ur();Ae=E("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=R0;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=yo(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 nn;if(l||f instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await f,s.issues.length!==p&&(c||(c=yo(s,p)))});else{if(s.issues.length===p)continue;c||(c=yo(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 nn;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=vo(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return _o(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Fi=E("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??c0(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}}),qe=E("$ZodStringFormat",(t,e)=>{Ui.init(t,e),Fi.init(t,e)}),Nf=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Vx),qe.init(t,e)}),zf=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=Tf(n))}else e.pattern??(e.pattern=Tf());qe.init(t,e)}),jf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Wx),qe.init(t,e)}),Mf=E("$ZodURL",(t,e)=>{qe.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:t0.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})}}}),Lf=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Jx()),qe.init(t,e)}),Df=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Bx),qe.init(t,e)}),qf=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=qx),qe.init(t,e)}),Zf=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Zx),qe.init(t,e)}),Uf=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ux),qe.init(t,e)}),Ff=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Fx),qe.init(t,e)}),Hf=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Hx),qe.init(t,e)}),D0=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=a0(e)),qe.init(t,e)}),q0=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=o0),qe.init(t,e)}),Z0=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=i0(e)),qe.init(t,e)}),U0=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Gx),qe.init(t,e)}),Bf=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Kx),qe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Gf=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Yx),qe.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})}}}),Vf=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Xx),qe.init(t,e)}),Wf=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Qx),qe.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})}}});Jf=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=e0),qe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{F0(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Kf=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Pf),qe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Rj(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Yf=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=r0),qe.init(t,e)});Xf=E("$ZodJWT",(t,e)=>{qe.init(t,e),t._zod.check=r=>{Oj(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Kc=E("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??u0,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}}),Qf=E("$ZodNumber",(t,e)=>{y0.init(t,e),Kc.init(t,e)}),em=E("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=p0,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}}),tm=E("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=d0,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}}),rm=E("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),nm=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)});om=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=>O0(l,r,i))):O0(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Yc=E("$ZodObject",(t,e)=>{Ae.init(t,e);let r=Mi(()=>{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=mf(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(f)}});De(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 Wc(["shape","payload","ctx"]),d=r.value,m=b=>{let x=go(b);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};f.write("const input = payload.value;");let h=Object.create(null),y=0;for(let b of d.keys)h[b]=`key_${y++}`;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 $=go(b);f.write(`
247
248
  if (${x}.issues.length) {
248
249
  if (input[${$}] === undefined) {
249
250
  if (${$} in input) {
@@ -266,11 +267,11 @@ ${g("cyan","OPTIONS:")}
266
267
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
267
268
  ...iss,
268
269
  path: iss.path ? [${go(b)}, ...iss.path] : [${go(b)}]
269
- })));`),f.write(`newResult[${go(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=ws,i=!Uc.jitless,c=i&&bf.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[$],ie=O._zod.run({value:d[$],issues:[]},f),X=O._zod.optin==="optional"&&O._zod.optout==="optional";ie instanceof Promise?m.push(ie.then(ee=>X?F0(ee,p,$,d):Yc(ee,p,$))):X?F0(ie,p,$,d):Yc(ie,p,$)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let h=[],y=u.keySet,v=l._zod,b=v.def.type;for(let x of Object.keys(d)){if(y.has(x))continue;if(b==="never"){h.push(x);continue}let $=v.run({value:d[x],issues:[]},f);$ instanceof Promise?m.push($.then(O=>Yc(O,p,x))):Yc($,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}});el=E("$ZodUnion",(t,e)=>{Ae.init(t,e),De(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),De(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),De(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),De(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=>qi(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=>H0(i,r,t,n)):H0(s,r,t,n)}}),fm=E("$ZodDiscriminatedUnion",(t,e)=>{el.init(t,e);let r=t._zod.parse;De(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=Li(()=>{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(!ws(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)}}),mm=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])=>B0(r,c,l)):B0(r,s,i)}});hm=E("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!xs(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(...Lr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Lr(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=>$r(l,n,tr())),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(...Lr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Lr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),gm=E("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Mi(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>wf.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}}),ym=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}}),vm=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 en;return r.value=o,r}}),_m=E("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",De(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),De(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${qi(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)}),bm=E("$ZodNullable",(t,e)=>{Ae.init(t,e),De(t._zod,"optin",()=>e.innerType._zod.optin),De(t._zod,"optout",()=>e.innerType._zod.optout),De(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${qi(r.source)}|null)$`):void 0}),De(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)}),wm=E("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",De(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=>G0(s,e)):G0(o,e)}});xm=E("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",De(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))}),Sm=E("$ZodNonOptional",(t,e)=>{Ae.init(t,e),De(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=>V0(s,t)):V0(o,t)}});$m=E("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",De(t._zod,"optout",()=>e.innerType._zod.optout),De(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=>$r(i,n,tr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>$r(s,n,tr()))},input:r.value}),r.issues=[]),r)}}),km=E("$ZodPipe",(t,e)=>{Ae.init(t,e),De(t._zod,"values",()=>e.in._zod.values),De(t._zod,"optin",()=>e.in._zod.optin),De(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=>W0(s,e,n)):W0(o,e,n)}});Em=E("$ZodReadonly",(t,e)=>{Ae.init(t,e),De(t._zod,"propValues",()=>e.innerType._zod.propValues),De(t._zod,"values",()=>e.innerType._zod.values),De(t._zod,"optin",()=>e.innerType._zod.optin),De(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(J0):J0(o)}});Tm=E("$ZodCustom",(t,e)=>{vt.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=>K0(s,r,n,t));K0(o,r,n,t)}})});function nS(){return{localeError:Kj()}}var Jj,Kj,oS=w(()=>{Dr();Jj=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},Kj=()=>{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 ${Jj(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Bc(n.values[0])}`:`Invalid option: expected one of ${Fc(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":""}: ${Fc(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 tl=w(()=>{});function sS(){return new Bi}var Yj,Xj,Bi,kn,Rm=w(()=>{Yj=Symbol("ZodOutput"),Xj=Symbol("ZodInput"),Bi=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=sS()});function Om(t,e){return new t({type:"string",...W(e)})}function Cm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...W(e)})}function rl(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...W(e)})}function Im(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...W(e)})}function Am(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(e)})}function Nm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(e)})}function zm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(e)})}function jm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...W(e)})}function Mm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...W(e)})}function Lm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(e)})}function Dm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...W(e)})}function qm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(e)})}function Zm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...W(e)})}function Um(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...W(e)})}function Fm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(e)})}function Hm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(e)})}function Bm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(e)})}function Gm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(e)})}function Vm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(e)})}function Wm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...W(e)})}function Jm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...W(e)})}function Km(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...W(e)})}function Ym(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...W(e)})}function iS(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(e)})}function aS(t,e){return new t({type:"string",format:"date",check:"string_format",...W(e)})}function cS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...W(e)})}function lS(t,e){return new t({type:"string",format:"duration",check:"string_format",...W(e)})}function Xm(t,e){return new t({type:"number",checks:[],...W(e)})}function Qm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...W(e)})}function eh(t,e){return new t({type:"boolean",...W(e)})}function th(t,e){return new t({type:"null",...W(e)})}function rh(t){return new t({type:"unknown"})}function nh(t,e){return new t({type:"never",...W(e)})}function nl(t,e){return new Mf({check:"less_than",...W(e),value:t,inclusive:!1})}function Gi(t,e){return new Mf({check:"less_than",...W(e),value:t,inclusive:!0})}function ol(t,e){return new Lf({check:"greater_than",...W(e),value:t,inclusive:!1})}function Vi(t,e){return new Lf({check:"greater_than",...W(e),value:t,inclusive:!0})}function sl(t,e){return new P0({check:"multiple_of",...W(e),value:t})}function il(t,e){return new O0({check:"max_length",...W(e),maximum:t})}function Ss(t,e){return new C0({check:"min_length",...W(e),minimum:t})}function al(t,e){return new I0({check:"length_equals",...W(e),length:t})}function oh(t,e){return new A0({check:"string_format",format:"regex",...W(e),pattern:t})}function sh(t){return new N0({check:"string_format",format:"lowercase",...W(t)})}function ih(t){return new z0({check:"string_format",format:"uppercase",...W(t)})}function ah(t,e){return new j0({check:"string_format",format:"includes",...W(e),includes:t})}function ch(t,e){return new M0({check:"string_format",format:"starts_with",...W(e),prefix:t})}function lh(t,e){return new L0({check:"string_format",format:"ends_with",...W(e),suffix:t})}function bo(t){return new D0({check:"overwrite",tx:t})}function uh(t){return bo(e=>e.normalize(t))}function ph(){return bo(t=>t.trim())}function dh(){return bo(t=>t.toLowerCase())}function fh(){return bo(t=>t.toUpperCase())}function uS(t,e,r){return new t({type:"array",element:e,...W(r)})}function mh(t,e,r){let n=W(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function hh(t,e,r){return new t({type:"custom",check:"custom",fn:e,...W(r)})}var pS=w(()=>{Jc();Dr()});var dS=w(()=>{});function gh(t,e){if(t instanceof Bi){let n=new cl(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 cl(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 cl,fS=w(()=>{Rm();Dr();cl=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:y,format:v,patterns:b,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof y=="number"&&(m.maxLength=y),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:y,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 y=="number"&&(m.maximum=y,typeof x=="number"&&(x<=y?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:y}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof y=="number"&&(m.maxItems=y),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 y=new Set(Object.keys(h)),v=new Set([...y].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,y)=>this.process(h,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{let m=d,h=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),y=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(y)?y.allOf:[y]];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:y,maximum:v}=e._zod.bag;typeof y=="number"&&(m.minItems=y),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=Mi(o.entries);h.every(y=>typeof y=="number")&&(m.type="number"),h.every(y=>typeof y=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=d,h=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(y))}else h.push(y);if(h.length!==0)if(h.length===1){let y=h[0];m.type=y===null?"null":typeof y,m.const=y}else h.every(y=>typeof y=="number")&&(m.type="number"),h.every(y=>typeof y=="string")&&(m.type="string"),h.every(y=>typeof y=="boolean")&&(m.type="string"),h.every(y=>y===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=d,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:v,mime:b}=e._zod.bag;y!==void 0&&(h.minLength=y),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,y=n.external.uri??(b=>b);if(h)return{ref:y(h)};let v=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=v,{defId:v,ref:`${y("__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
+ })));`),f.write(`newResult[${go(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=bs,i=!qc.jitless,c=i&&df.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[$],ie=O._zod.run({value:d[$],issues:[]},f),X=O._zod.optin==="optional"&&O._zod.optout==="optional";ie instanceof Promise?m.push(ie.then(ee=>X?C0(ee,p,$,d):Jc(ee,p,$))):X?C0(ie,p,$,d):Jc(ie,p,$)}}if(!l)return m.length?Promise.all(m).then(()=>p):p;let h=[],y=u.keySet,v=l._zod,b=v.def.type;for(let x of Object.keys(d)){if(y.has(x))continue;if(b==="never"){h.push(x);continue}let $=v.run({value:d[x],issues:[]},f);$ instanceof Promise?m.push($.then(O=>Jc(O,p,x))):Jc($,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}});Xc=E("$ZodUnion",(t,e)=>{Ae.init(t,e),De(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),De(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),De(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),De(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=>Di(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=>I0(i,r,t,n)):I0(s,r,t,n)}}),sm=E("$ZodDiscriminatedUnion",(t,e)=>{Xc.init(t,e);let r=t._zod.parse;De(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=Mi(()=>{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(!bs(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)}}),im=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])=>A0(r,c,l)):A0(r,s,i)}});am=E("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!ws(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(...Zr(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Zr(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=>Er(l,n,nr())),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(...Zr(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Zr(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),cm=E("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=ji(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>ff.has(typeof n)).map(n=>typeof n=="string"?kn(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}}),lm=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"?kn(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}}),um=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 nn;return r.value=o,r}}),pm=E("$ZodOptional",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",t._zod.optout="optional",De(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),De(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Di(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)}),dm=E("$ZodNullable",(t,e)=>{Ae.init(t,e),De(t._zod,"optin",()=>e.innerType._zod.optin),De(t._zod,"optout",()=>e.innerType._zod.optout),De(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Di(r.source)}|null)$`):void 0}),De(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)}),fm=E("$ZodDefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",De(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=>N0(s,e)):N0(o,e)}});mm=E("$ZodPrefault",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",De(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))}),hm=E("$ZodNonOptional",(t,e)=>{Ae.init(t,e),De(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=>z0(s,t)):z0(o,t)}});gm=E("$ZodCatch",(t,e)=>{Ae.init(t,e),t._zod.optin="optional",De(t._zod,"optout",()=>e.innerType._zod.optout),De(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=>Er(i,n,nr()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Er(s,n,nr()))},input:r.value}),r.issues=[]),r)}}),ym=E("$ZodPipe",(t,e)=>{Ae.init(t,e),De(t._zod,"values",()=>e.in._zod.values),De(t._zod,"optin",()=>e.in._zod.optin),De(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=>j0(s,e,n)):j0(o,e,n)}});vm=E("$ZodReadonly",(t,e)=>{Ae.init(t,e),De(t._zod,"propValues",()=>e.innerType._zod.propValues),De(t._zod,"values",()=>e.innerType._zod.values),De(t._zod,"optin",()=>e.innerType._zod.optin),De(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(M0):M0(o)}});_m=E("$ZodCustom",(t,e)=>{_t.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=>L0(s,r,n,t));L0(o,r,n,t)}})});function B0(){return{localeError:Ij()}}var Cj,Ij,G0=w(()=>{Ur();Cj=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},Ij=()=>{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 ${Cj(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Fc(n.values[0])}`:`Invalid option: expected one of ${Zc(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":""}: ${Zc(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 Qc=w(()=>{});function V0(){return new Hi}var Aj,Nj,Hi,En,wm=w(()=>{Aj=Symbol("ZodOutput"),Nj=Symbol("ZodInput"),Hi=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)}};En=V0()});function xm(t,e){return new t({type:"string",...W(e)})}function Sm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...W(e)})}function el(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...W(e)})}function $m(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...W(e)})}function km(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(e)})}function Em(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(e)})}function Tm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(e)})}function Pm(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...W(e)})}function Rm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...W(e)})}function Om(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(e)})}function Cm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...W(e)})}function Im(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(e)})}function Am(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...W(e)})}function Nm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...W(e)})}function zm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(e)})}function jm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(e)})}function Mm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(e)})}function Lm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(e)})}function Dm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(e)})}function qm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...W(e)})}function Zm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...W(e)})}function Um(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...W(e)})}function Fm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...W(e)})}function W0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(e)})}function J0(t,e){return new t({type:"string",format:"date",check:"string_format",...W(e)})}function K0(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...W(e)})}function Y0(t,e){return new t({type:"string",format:"duration",check:"string_format",...W(e)})}function Hm(t,e){return new t({type:"number",checks:[],...W(e)})}function Bm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...W(e)})}function Gm(t,e){return new t({type:"boolean",...W(e)})}function Vm(t,e){return new t({type:"null",...W(e)})}function Wm(t){return new t({type:"unknown"})}function Jm(t,e){return new t({type:"never",...W(e)})}function tl(t,e){return new Rf({check:"less_than",...W(e),value:t,inclusive:!1})}function Bi(t,e){return new Rf({check:"less_than",...W(e),value:t,inclusive:!0})}function rl(t,e){return new Of({check:"greater_than",...W(e),value:t,inclusive:!1})}function Gi(t,e){return new Of({check:"greater_than",...W(e),value:t,inclusive:!0})}function nl(t,e){return new g0({check:"multiple_of",...W(e),value:t})}function ol(t,e){return new v0({check:"max_length",...W(e),maximum:t})}function xs(t,e){return new _0({check:"min_length",...W(e),minimum:t})}function sl(t,e){return new b0({check:"length_equals",...W(e),length:t})}function Km(t,e){return new w0({check:"string_format",format:"regex",...W(e),pattern:t})}function Ym(t){return new x0({check:"string_format",format:"lowercase",...W(t)})}function Xm(t){return new S0({check:"string_format",format:"uppercase",...W(t)})}function Qm(t,e){return new $0({check:"string_format",format:"includes",...W(e),includes:t})}function eh(t,e){return new k0({check:"string_format",format:"starts_with",...W(e),prefix:t})}function th(t,e){return new E0({check:"string_format",format:"ends_with",...W(e),suffix:t})}function bo(t){return new T0({check:"overwrite",tx:t})}function rh(t){return bo(e=>e.normalize(t))}function nh(){return bo(t=>t.trim())}function oh(){return bo(t=>t.toLowerCase())}function sh(){return bo(t=>t.toUpperCase())}function X0(t,e,r){return new t({type:"array",element:e,...W(r)})}function ih(t,e,r){let n=W(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ah(t,e,r){return new t({type:"custom",check:"custom",fn:e,...W(r)})}var Q0=w(()=>{Vc();Ur()});var eS=w(()=>{});function ch(t,e){if(t instanceof Hi){let n=new il(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 il(e);return r.process(t),r.emit(t,e)}function pt(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 pt(o.element,r);case"object":{for(let s in o.shape)if(pt(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(pt(s,r))return!0;return!1}case"intersection":return pt(o.left,r)||pt(o.right,r);case"tuple":{for(let s of o.items)if(pt(s,r))return!0;return!!(o.rest&&pt(o.rest,r))}case"record":return pt(o.keyType,r)||pt(o.valueType,r);case"map":return pt(o.keyType,r)||pt(o.valueType,r);case"set":return pt(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return pt(o.innerType,r);case"lazy":return pt(o.getter(),r);case"default":return pt(o.innerType,r);case"prefault":return pt(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return pt(o.in,r)||pt(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var il,tS=w(()=>{wm();Ur();il=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??En,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:y,format:v,patterns:b,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof y=="number"&&(m.maxLength=y),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:y,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 y=="number"&&(m.maximum=y,typeof x=="number"&&(x<=y?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:y}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof y=="number"&&(m.maxItems=y),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 y=new Set(Object.keys(h)),v=new Set([...y].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,y)=>this.process(h,{...p,path:[...p.path,"anyOf",y]}));break}case"intersection":{let m=d,h=this.process(o.left,{...p,path:[...p.path,"allOf",0]}),y=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(y)?y.allOf:[y]];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:y,maximum:v}=e._zod.bag;typeof y=="number"&&(m.minItems=y),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=ji(o.entries);h.every(y=>typeof y=="number")&&(m.type="number"),h.every(y=>typeof y=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=d,h=[];for(let y of o.values)if(y===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof y=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(y))}else h.push(y);if(h.length!==0)if(h.length===1){let y=h[0];m.type=y===null?"null":typeof y,m.const=y}else h.every(y=>typeof y=="number")&&(m.type="number"),h.every(y=>typeof y=="string")&&(m.type="string"),h.every(y=>typeof y=="boolean")&&(m.type="string"),h.every(y=>y===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=d,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:y,maximum:v,mime:b}=e._zod.bag;y!==void 0&&(h.minLength=y),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"&&pt(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,y=n.external.uri??(b=>b);if(h)return{ref:y(h)};let v=u[1].defId??u[1].schema.id??`schema${this.counter++}`;return u[1].defId=v,{defId:v,ref:`${y("__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
271
 
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 y=this.seen.get(h).schema;y.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(y)):(Object.assign(d,y),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 mS=w(()=>{});var zt=w(()=>{bs();Nf();Tf();rS();Jc();qf();Dr();Wc();tl();Rm();Df();dS();pS();fS();mS()});var yh=w(()=>{zt()});var Wi={};V(Wi,{ZodISODate:()=>gS,ZodISODateTime:()=>hS,ZodISODuration:()=>vS,ZodISOTime:()=>yS,date:()=>_h,datetime:()=>vh,duration:()=>wh,time:()=>bh});function vh(t){return iS(hS,t)}function _h(t){return aS(gS,t)}function bh(t){return cS(yS,t)}function wh(t){return lS(vS,t)}var hS,gS,yS,vS,xh=w(()=>{zt();Sh();hS=E("ZodISODateTime",(t,e)=>{Y0.init(t,e),Ve.init(t,e)});gS=E("ZodISODate",(t,e)=>{X0.init(t,e),Ve.init(t,e)});yS=E("ZodISOTime",(t,e)=>{Q0.init(t,e),Ve.init(t,e)});vS=E("ZodISODuration",(t,e)=>{eS.init(t,e),Ve.init(t,e)})});var _S,C5,Ji,$h=w(()=>{zt();zt();_S=(t,e)=>{Gc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Ef(t,r)},flatten:{value:r=>kf(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",_S),Ji=E("ZodError",_S,{Parent:Error})});var bS,wS,xS,SS,kh=w(()=>{zt();$h();bS=Pf(Ji),wS=Of(Ji),xS=If(Ji),SS=Af(Ji)});function k(t){return Om(DM,t)}function Ie(t){return Xm(PS,t)}function kS(t){return Qm(nL,t)}function mt(t){return eh(oL,t)}function Ph(t){return th(sL,t)}function We(){return rh(iL)}function cL(t){return nh(aL,t)}function we(t,e){return uS(lL,t,e)}function j(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new RS(r)}function jt(t,e){return new RS({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:We(),...be.normalizeParams(e)})}function Ze(t,e){return new OS({type:"union",options:t,...be.normalizeParams(e)})}function Rh(t,e,r){return new uL({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function ul(t,e){return new pL({type:"intersection",left:t,right:e})}function Je(t,e,r){return new dL({type:"record",keyType:t,valueType:e,...be.normalizeParams(r)})}function Ft(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Eh({type:"enum",entries:r,...be.normalizeParams(e)})}function Z(t,e){return new fL({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function CS(t){return new mL({type:"transform",transform:t})}function tt(t){return new IS({type:"optional",innerType:t})}function ES(t){return new hL({type:"nullable",innerType:t})}function yL(t,e){return new gL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function _L(t,e){return new vL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function bL(t,e){return new AS({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function xL(t,e){return new wL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Th(t,e){return new SL({type:"pipe",in:t,out:e})}function kL(t){return new $L({type:"readonly",innerType:t})}function EL(t){let e=new vt({check:"custom"});return e._zod.check=t,e}function zS(t,e){return mh(NS,t??(()=>!0),e)}function TL(t,e={}){return hh(NS,t,e)}function PL(t){let e=EL(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(be.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(be.issue(o))}},t(r.value,r)));return e}function Oh(t,e){return Th(CS(t),e)}var rt,TS,DM,Ve,qM,$S,ll,ZM,UM,FM,HM,BM,GM,VM,WM,JM,KM,YM,XM,QM,eL,tL,rL,PS,nL,oL,sL,iL,aL,lL,RS,OS,uL,pL,dL,Eh,fL,mL,IS,hL,gL,vL,AS,wL,SL,$L,NS,Sh=w(()=>{zt();zt();yh();xh();kh();rt=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)=>rr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>bS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>xS(t,r,n),t.parseAsync=async(r,n)=>wS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>SS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(TL(r,n)),t.superRefine=r=>t.check(PL(r)),t.overwrite=r=>t.check(bo(r)),t.optional=()=>tt(t),t.nullable=()=>ES(t),t.nullish=()=>tt(ES(t)),t.nonoptional=r=>bL(t,r),t.array=()=>we(t),t.or=r=>Ze([t,r]),t.and=r=>ul(t,r),t.transform=r=>Th(t,CS(r)),t.default=r=>yL(t,r),t.prefault=r=>_L(t,r),t.catch=r=>xL(t,r),t.pipe=r=>Th(t,r),t.readonly=()=>kL(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)),TS=E("_ZodString",(t,e)=>{Hi.init(t,e),rt.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(oh(...n)),t.includes=(...n)=>t.check(ah(...n)),t.startsWith=(...n)=>t.check(ch(...n)),t.endsWith=(...n)=>t.check(lh(...n)),t.min=(...n)=>t.check(Ss(...n)),t.max=(...n)=>t.check(il(...n)),t.length=(...n)=>t.check(al(...n)),t.nonempty=(...n)=>t.check(Ss(1,...n)),t.lowercase=n=>t.check(sh(n)),t.uppercase=n=>t.check(ih(n)),t.trim=()=>t.check(ph()),t.normalize=(...n)=>t.check(uh(...n)),t.toLowerCase=()=>t.check(dh()),t.toUpperCase=()=>t.check(fh())}),DM=E("ZodString",(t,e)=>{Hi.init(t,e),TS.init(t,e),t.email=r=>t.check(Cm(qM,r)),t.url=r=>t.check(jm(ZM,r)),t.jwt=r=>t.check(Ym(rL,r)),t.emoji=r=>t.check(Mm(UM,r)),t.guid=r=>t.check(rl($S,r)),t.uuid=r=>t.check(Im(ll,r)),t.uuidv4=r=>t.check(Am(ll,r)),t.uuidv6=r=>t.check(Nm(ll,r)),t.uuidv7=r=>t.check(zm(ll,r)),t.nanoid=r=>t.check(Lm(FM,r)),t.guid=r=>t.check(rl($S,r)),t.cuid=r=>t.check(Dm(HM,r)),t.cuid2=r=>t.check(qm(BM,r)),t.ulid=r=>t.check(Zm(GM,r)),t.base64=r=>t.check(Wm(QM,r)),t.base64url=r=>t.check(Jm(eL,r)),t.xid=r=>t.check(Um(VM,r)),t.ksuid=r=>t.check(Fm(WM,r)),t.ipv4=r=>t.check(Hm(JM,r)),t.ipv6=r=>t.check(Bm(KM,r)),t.cidrv4=r=>t.check(Gm(YM,r)),t.cidrv6=r=>t.check(Vm(XM,r)),t.e164=r=>t.check(Km(tL,r)),t.datetime=r=>t.check(vh(r)),t.date=r=>t.check(_h(r)),t.time=r=>t.check(bh(r)),t.duration=r=>t.check(wh(r))});Ve=E("ZodStringFormat",(t,e)=>{qe.init(t,e),TS.init(t,e)}),qM=E("ZodEmail",(t,e)=>{Hf.init(t,e),Ve.init(t,e)}),$S=E("ZodGUID",(t,e)=>{Uf.init(t,e),Ve.init(t,e)}),ll=E("ZodUUID",(t,e)=>{Ff.init(t,e),Ve.init(t,e)}),ZM=E("ZodURL",(t,e)=>{Bf.init(t,e),Ve.init(t,e)}),UM=E("ZodEmoji",(t,e)=>{Gf.init(t,e),Ve.init(t,e)}),FM=E("ZodNanoID",(t,e)=>{Vf.init(t,e),Ve.init(t,e)}),HM=E("ZodCUID",(t,e)=>{Wf.init(t,e),Ve.init(t,e)}),BM=E("ZodCUID2",(t,e)=>{Jf.init(t,e),Ve.init(t,e)}),GM=E("ZodULID",(t,e)=>{Kf.init(t,e),Ve.init(t,e)}),VM=E("ZodXID",(t,e)=>{Yf.init(t,e),Ve.init(t,e)}),WM=E("ZodKSUID",(t,e)=>{Xf.init(t,e),Ve.init(t,e)}),JM=E("ZodIPv4",(t,e)=>{Qf.init(t,e),Ve.init(t,e)}),KM=E("ZodIPv6",(t,e)=>{em.init(t,e),Ve.init(t,e)}),YM=E("ZodCIDRv4",(t,e)=>{tm.init(t,e),Ve.init(t,e)}),XM=E("ZodCIDRv6",(t,e)=>{rm.init(t,e),Ve.init(t,e)}),QM=E("ZodBase64",(t,e)=>{nm.init(t,e),Ve.init(t,e)}),eL=E("ZodBase64URL",(t,e)=>{om.init(t,e),Ve.init(t,e)}),tL=E("ZodE164",(t,e)=>{sm.init(t,e),Ve.init(t,e)}),rL=E("ZodJWT",(t,e)=>{im.init(t,e),Ve.init(t,e)}),PS=E("ZodNumber",(t,e)=>{Xc.init(t,e),rt.init(t,e),t.gt=(n,o)=>t.check(ol(n,o)),t.gte=(n,o)=>t.check(Vi(n,o)),t.min=(n,o)=>t.check(Vi(n,o)),t.lt=(n,o)=>t.check(nl(n,o)),t.lte=(n,o)=>t.check(Gi(n,o)),t.max=(n,o)=>t.check(Gi(n,o)),t.int=n=>t.check(kS(n)),t.safe=n=>t.check(kS(n)),t.positive=n=>t.check(ol(0,n)),t.nonnegative=n=>t.check(Vi(0,n)),t.negative=n=>t.check(nl(0,n)),t.nonpositive=n=>t.check(Gi(0,n)),t.multipleOf=(n,o)=>t.check(sl(n,o)),t.step=(n,o)=>t.check(sl(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});nL=E("ZodNumberFormat",(t,e)=>{am.init(t,e),PS.init(t,e)});oL=E("ZodBoolean",(t,e)=>{cm.init(t,e),rt.init(t,e)});sL=E("ZodNull",(t,e)=>{lm.init(t,e),rt.init(t,e)});iL=E("ZodUnknown",(t,e)=>{um.init(t,e),rt.init(t,e)});aL=E("ZodNever",(t,e)=>{pm.init(t,e),rt.init(t,e)});lL=E("ZodArray",(t,e)=>{dm.init(t,e),rt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Ss(r,n)),t.nonempty=r=>t.check(Ss(1,r)),t.max=(r,n)=>t.check(il(r,n)),t.length=(r,n)=>t.check(al(r,n)),t.unwrap=()=>t.element});RS=E("ZodObject",(t,e)=>{Qc.init(t,e),rt.init(t,e),be.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Ft(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:We()}),t.loose=()=>t.clone({...t._zod.def,catchall:We()}),t.strict=()=>t.clone({...t._zod.def,catchall:cL()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>be.extend(t,r),t.merge=r=>be.merge(t,r),t.pick=r=>be.pick(t,r),t.omit=r=>be.omit(t,r),t.partial=(...r)=>be.partial(IS,t,r[0]),t.required=(...r)=>be.required(AS,t,r[0])});OS=E("ZodUnion",(t,e)=>{el.init(t,e),rt.init(t,e),t.options=e.options});uL=E("ZodDiscriminatedUnion",(t,e)=>{OS.init(t,e),fm.init(t,e)});pL=E("ZodIntersection",(t,e)=>{mm.init(t,e),rt.init(t,e)});dL=E("ZodRecord",(t,e)=>{hm.init(t,e),rt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Eh=E("ZodEnum",(t,e)=>{gm.init(t,e),rt.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 Eh({...e,checks:[],...be.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 Eh({...e,checks:[],...be.normalizeParams(o),entries:s})}});fL=E("ZodLiteral",(t,e)=>{ym.init(t,e),rt.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]}})});mL=E("ZodTransform",(t,e)=>{vm.init(t,e),rt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(be.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(be.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});IS=E("ZodOptional",(t,e)=>{_m.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});hL=E("ZodNullable",(t,e)=>{bm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});gL=E("ZodDefault",(t,e)=>{wm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});vL=E("ZodPrefault",(t,e)=>{xm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});AS=E("ZodNonOptional",(t,e)=>{Sm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});wL=E("ZodCatch",(t,e)=>{$m.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});SL=E("ZodPipe",(t,e)=>{km.init(t,e),rt.init(t,e),t.in=e.in,t.out=e.out});$L=E("ZodReadonly",(t,e)=>{Em.init(t,e),rt.init(t,e)});NS=E("ZodCustom",(t,e)=>{Tm.init(t,e),rt.init(t,e)})});var jS=w(()=>{});var MS=w(()=>{});var LS=w(()=>{zt();Sh();yh();$h();kh();jS();zt();oS();tl();xh();MS();tr(nS())});var DS=w(()=>{LS()});var qS=w(()=>{DS()});function t$(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function r$(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ih,ZS,Ki,En,dl,_t,US,FS,V5,CL,IL,Ah,nr,Yi,HS,bt,ar,cr,wt,fl,BS,Tn,GS,VS,Nh,tn,G,zh,ks,Xi,W5,ml,AL,hl,NL,Qi,$s,WS,zL,jL,ML,LL,DL,qL,gl,jh,ZL,UL,Mh,yl,FL,HL,vl,BL,ea,ta,GL,ra,Es,VL,na,_l,bl,wl,J5,xl,Sl,$l,JS,KS,YS,Lh,XS,oa,Ts,QS,WL,kl,JL,El,KL,Dh,YL,Tl,XL,QL,eD,tD,rD,nD,oD,sD,iD,aD,Pl,cD,lD,Rl,qh,Zh,Uh,uD,pD,dD,Fh,fD,mD,hD,gD,yD,e$,Ol,vD,Cl,K5,_D,Ps,bD,Y5,sa,wD,Hh,xD,SD,$D,kD,ED,TD,PD,pl,RD,OD,CD,Bh,Gh,ID,AD,ND,zD,jD,MD,LD,DD,qD,ZD,UD,FD,HD,BD,GD,VD,WD,JD,Il,KD,YD,XD,Al,QD,e2,t2,Vh,r2,X5,Q5,e8,t8,r8,n8,q,Ch,Rs=w(()=>{qS();Ih="2025-11-25",ZS="2025-03-26",Ki=[Ih,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],En="io.modelcontextprotocol/related-task",dl="2.0",_t=zS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),US=Ze([k(),Ie().int()]),FS=k(),V5=jt({ttl:Ze([Ie(),Ph()]).optional(),pollInterval:Ie().optional()}),CL=j({ttl:Ie().optional()}),IL=j({taskId:k()}),Ah=jt({progressToken:US.optional(),[En]:IL.optional()}),nr=j({_meta:Ah.optional()}),Yi=nr.extend({task:CL.optional()}),HS=t=>Yi.safeParse(t).success,bt=j({method:k(),params:nr.loose().optional()}),ar=j({_meta:Ah.optional()}),cr=j({method:k(),params:ar.loose().optional()}),wt=jt({_meta:Ah.optional()}),fl=Ze([k(),Ie().int()]),BS=j({jsonrpc:Z(dl),id:fl,...bt.shape}).strict(),Tn=t=>BS.safeParse(t).success,GS=j({jsonrpc:Z(dl),...cr.shape}).strict(),VS=t=>GS.safeParse(t).success,Nh=j({jsonrpc:Z(dl),id:fl,result:wt}).strict(),tn=t=>Nh.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"})(G||(G={}));zh=j({jsonrpc:Z(dl),id:fl.optional(),error:j({code:Ie().int(),message:k(),data:We().optional()})}).strict(),ks=t=>zh.safeParse(t).success,Xi=Ze([BS,GS,Nh,zh]),W5=Ze([Nh,zh]),ml=wt.strict(),AL=ar.extend({requestId:fl.optional(),reason:k().optional()}),hl=cr.extend({method:Z("notifications/cancelled"),params:AL}),NL=j({src:k(),mimeType:k().optional(),sizes:we(k()).optional(),theme:Ft(["light","dark"]).optional()}),Qi=j({icons:we(NL).optional()}),$s=j({name:k(),title:k().optional()}),WS=$s.extend({...$s.shape,...Qi.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),zL=ul(j({applyDefaults:mt().optional()}),Je(k(),We())),jL=Oh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,ul(j({form:zL.optional(),url:_t.optional()}),Je(k(),We()).optional())),ML=jt({list:_t.optional(),cancel:_t.optional(),requests:jt({sampling:jt({createMessage:_t.optional()}).optional(),elicitation:jt({create:_t.optional()}).optional()}).optional()}),LL=jt({list:_t.optional(),cancel:_t.optional(),requests:jt({tools:jt({call:_t.optional()}).optional()}).optional()}),DL=j({experimental:Je(k(),_t).optional(),sampling:j({context:_t.optional(),tools:_t.optional()}).optional(),elicitation:jL.optional(),roots:j({listChanged:mt().optional()}).optional(),tasks:ML.optional()}),qL=nr.extend({protocolVersion:k(),capabilities:DL,clientInfo:WS}),gl=bt.extend({method:Z("initialize"),params:qL}),jh=t=>gl.safeParse(t).success,ZL=j({experimental:Je(k(),_t).optional(),logging:_t.optional(),completions:_t.optional(),prompts:j({listChanged:mt().optional()}).optional(),resources:j({subscribe:mt().optional(),listChanged:mt().optional()}).optional(),tools:j({listChanged:mt().optional()}).optional(),tasks:LL.optional()}),UL=wt.extend({protocolVersion:k(),capabilities:ZL,serverInfo:WS,instructions:k().optional()}),Mh=cr.extend({method:Z("notifications/initialized"),params:ar.optional()}),yl=bt.extend({method:Z("ping"),params:nr.optional()}),FL=j({progress:Ie(),total:tt(Ie()),message:tt(k())}),HL=j({...ar.shape,...FL.shape,progressToken:US}),vl=cr.extend({method:Z("notifications/progress"),params:HL}),BL=nr.extend({cursor:FS.optional()}),ea=bt.extend({params:BL.optional()}),ta=wt.extend({nextCursor:FS.optional()}),GL=Ft(["working","input_required","completed","failed","cancelled"]),ra=j({taskId:k(),status:GL,ttl:Ze([Ie(),Ph()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:tt(Ie()),statusMessage:tt(k())}),Es=wt.extend({task:ra}),VL=ar.merge(ra),na=cr.extend({method:Z("notifications/tasks/status"),params:VL}),_l=bt.extend({method:Z("tasks/get"),params:nr.extend({taskId:k()})}),bl=wt.merge(ra),wl=bt.extend({method:Z("tasks/result"),params:nr.extend({taskId:k()})}),J5=wt.loose(),xl=ea.extend({method:Z("tasks/list")}),Sl=ta.extend({tasks:we(ra)}),$l=bt.extend({method:Z("tasks/cancel"),params:nr.extend({taskId:k()})}),JS=wt.merge(ra),KS=j({uri:k(),mimeType:tt(k()),_meta:Je(k(),We()).optional()}),YS=KS.extend({text:k()}),Lh=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),XS=KS.extend({blob:Lh}),oa=Ft(["user","assistant"]),Ts=j({audience:we(oa).optional(),priority:Ie().min(0).max(1).optional(),lastModified:Wi.datetime({offset:!0}).optional()}),QS=j({...$s.shape,...Qi.shape,uri:k(),description:tt(k()),mimeType:tt(k()),annotations:Ts.optional(),_meta:tt(jt({}))}),WL=j({...$s.shape,...Qi.shape,uriTemplate:k(),description:tt(k()),mimeType:tt(k()),annotations:Ts.optional(),_meta:tt(jt({}))}),kl=ea.extend({method:Z("resources/list")}),JL=ta.extend({resources:we(QS)}),El=ea.extend({method:Z("resources/templates/list")}),KL=ta.extend({resourceTemplates:we(WL)}),Dh=nr.extend({uri:k()}),YL=Dh,Tl=bt.extend({method:Z("resources/read"),params:YL}),XL=wt.extend({contents:we(Ze([YS,XS]))}),QL=cr.extend({method:Z("notifications/resources/list_changed"),params:ar.optional()}),eD=Dh,tD=bt.extend({method:Z("resources/subscribe"),params:eD}),rD=Dh,nD=bt.extend({method:Z("resources/unsubscribe"),params:rD}),oD=ar.extend({uri:k()}),sD=cr.extend({method:Z("notifications/resources/updated"),params:oD}),iD=j({name:k(),description:tt(k()),required:tt(mt())}),aD=j({...$s.shape,...Qi.shape,description:tt(k()),arguments:tt(we(iD)),_meta:tt(jt({}))}),Pl=ea.extend({method:Z("prompts/list")}),cD=ta.extend({prompts:we(aD)}),lD=nr.extend({name:k(),arguments:Je(k(),k()).optional()}),Rl=bt.extend({method:Z("prompts/get"),params:lD}),qh=j({type:Z("text"),text:k(),annotations:Ts.optional(),_meta:Je(k(),We()).optional()}),Zh=j({type:Z("image"),data:Lh,mimeType:k(),annotations:Ts.optional(),_meta:Je(k(),We()).optional()}),Uh=j({type:Z("audio"),data:Lh,mimeType:k(),annotations:Ts.optional(),_meta:Je(k(),We()).optional()}),uD=j({type:Z("tool_use"),name:k(),id:k(),input:Je(k(),We()),_meta:Je(k(),We()).optional()}),pD=j({type:Z("resource"),resource:Ze([YS,XS]),annotations:Ts.optional(),_meta:Je(k(),We()).optional()}),dD=QS.extend({type:Z("resource_link")}),Fh=Ze([qh,Zh,Uh,dD,pD]),fD=j({role:oa,content:Fh}),mD=wt.extend({description:k().optional(),messages:we(fD)}),hD=cr.extend({method:Z("notifications/prompts/list_changed"),params:ar.optional()}),gD=j({title:k().optional(),readOnlyHint:mt().optional(),destructiveHint:mt().optional(),idempotentHint:mt().optional(),openWorldHint:mt().optional()}),yD=j({taskSupport:Ft(["required","optional","forbidden"]).optional()}),e$=j({...$s.shape,...Qi.shape,description:k().optional(),inputSchema:j({type:Z("object"),properties:Je(k(),_t).optional(),required:we(k()).optional()}).catchall(We()),outputSchema:j({type:Z("object"),properties:Je(k(),_t).optional(),required:we(k()).optional()}).catchall(We()).optional(),annotations:gD.optional(),execution:yD.optional(),_meta:Je(k(),We()).optional()}),Ol=ea.extend({method:Z("tools/list")}),vD=ta.extend({tools:we(e$)}),Cl=wt.extend({content:we(Fh).default([]),structuredContent:Je(k(),We()).optional(),isError:mt().optional()}),K5=Cl.or(wt.extend({toolResult:We()})),_D=Yi.extend({name:k(),arguments:Je(k(),We()).optional()}),Ps=bt.extend({method:Z("tools/call"),params:_D}),bD=cr.extend({method:Z("notifications/tools/list_changed"),params:ar.optional()}),Y5=j({autoRefresh:mt().default(!0),debounceMs:Ie().int().nonnegative().default(300)}),sa=Ft(["debug","info","notice","warning","error","critical","alert","emergency"]),wD=nr.extend({level:sa}),Hh=bt.extend({method:Z("logging/setLevel"),params:wD}),xD=ar.extend({level:sa,logger:k().optional(),data:We()}),SD=cr.extend({method:Z("notifications/message"),params:xD}),$D=j({name:k().optional()}),kD=j({hints:we($D).optional(),costPriority:Ie().min(0).max(1).optional(),speedPriority:Ie().min(0).max(1).optional(),intelligencePriority:Ie().min(0).max(1).optional()}),ED=j({mode:Ft(["auto","required","none"]).optional()}),TD=j({type:Z("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:we(Fh).default([]),structuredContent:j({}).loose().optional(),isError:mt().optional(),_meta:Je(k(),We()).optional()}),PD=Rh("type",[qh,Zh,Uh]),pl=Rh("type",[qh,Zh,Uh,uD,TD]),RD=j({role:oa,content:Ze([pl,we(pl)]),_meta:Je(k(),We()).optional()}),OD=Yi.extend({messages:we(RD),modelPreferences:kD.optional(),systemPrompt:k().optional(),includeContext:Ft(["none","thisServer","allServers"]).optional(),temperature:Ie().optional(),maxTokens:Ie().int(),stopSequences:we(k()).optional(),metadata:_t.optional(),tools:we(e$).optional(),toolChoice:ED.optional()}),CD=bt.extend({method:Z("sampling/createMessage"),params:OD}),Bh=wt.extend({model:k(),stopReason:tt(Ft(["endTurn","stopSequence","maxTokens"]).or(k())),role:oa,content:PD}),Gh=wt.extend({model:k(),stopReason:tt(Ft(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:oa,content:Ze([pl,we(pl)])}),ID=j({type:Z("boolean"),title:k().optional(),description:k().optional(),default:mt().optional()}),AD=j({type:Z("string"),title:k().optional(),description:k().optional(),minLength:Ie().optional(),maxLength:Ie().optional(),format:Ft(["email","uri","date","date-time"]).optional(),default:k().optional()}),ND=j({type:Ft(["number","integer"]),title:k().optional(),description:k().optional(),minimum:Ie().optional(),maximum:Ie().optional(),default:Ie().optional()}),zD=j({type:Z("string"),title:k().optional(),description:k().optional(),enum:we(k()),default:k().optional()}),jD=j({type:Z("string"),title:k().optional(),description:k().optional(),oneOf:we(j({const:k(),title:k()})),default:k().optional()}),MD=j({type:Z("string"),title:k().optional(),description:k().optional(),enum:we(k()),enumNames:we(k()).optional(),default:k().optional()}),LD=Ze([zD,jD]),DD=j({type:Z("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({type:Z("string"),enum:we(k())}),default:we(k()).optional()}),qD=j({type:Z("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({anyOf:we(j({const:k(),title:k()}))}),default:we(k()).optional()}),ZD=Ze([DD,qD]),UD=Ze([MD,LD,ZD]),FD=Ze([UD,ID,AD,ND]),HD=Yi.extend({mode:Z("form").optional(),message:k(),requestedSchema:j({type:Z("object"),properties:Je(k(),FD),required:we(k()).optional()})}),BD=Yi.extend({mode:Z("url"),message:k(),elicitationId:k(),url:k().url()}),GD=Ze([HD,BD]),VD=bt.extend({method:Z("elicitation/create"),params:GD}),WD=ar.extend({elicitationId:k()}),JD=cr.extend({method:Z("notifications/elicitation/complete"),params:WD}),Il=wt.extend({action:Ft(["accept","decline","cancel"]),content:Oh(t=>t===null?void 0:t,Je(k(),Ze([k(),Ie(),mt(),we(k())])).optional())}),KD=j({type:Z("ref/resource"),uri:k()}),YD=j({type:Z("ref/prompt"),name:k()}),XD=nr.extend({ref:Ze([YD,KD]),argument:j({name:k(),value:k()}),context:j({arguments:Je(k(),k()).optional()}).optional()}),Al=bt.extend({method:Z("completion/complete"),params:XD});QD=wt.extend({completion:jt({values:we(k()).max(100),total:tt(Ie().int()),hasMore:tt(mt())})}),e2=j({uri:k().startsWith("file://"),name:k().optional(),_meta:Je(k(),We()).optional()}),t2=bt.extend({method:Z("roots/list"),params:nr.optional()}),Vh=wt.extend({roots:we(e2)}),r2=cr.extend({method:Z("notifications/roots/list_changed"),params:ar.optional()}),X5=Ze([yl,gl,Al,Hh,Rl,Pl,kl,El,Tl,tD,nD,Ps,Ol,_l,wl,xl,$l]),Q5=Ze([hl,vl,Mh,r2,na]),e8=Ze([ml,Bh,Gh,Il,Vh,bl,Sl,Es]),t8=Ze([yl,CD,VD,t2,_l,wl,xl,$l]),r8=Ze([hl,vl,SD,sD,QL,bD,hD,na,JD]),n8=Ze([ml,UL,QD,mD,cD,JL,KL,XL,Cl,vD,bl,Sl,Es]),q=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===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Ch(o.elicitations,r)}return new t(e,r,n)}},Ch=class extends q{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function n2(t){return Xi.parse(JSON.parse(t))}function n$(t){return JSON.stringify(t)+`
272
- `}var Nl,o$=w(()=>{Rs();Nl=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),n2(r)}clear(){this._buffer=void 0}}});import s$ from"node:process";var zl,i$=w(()=>{o$();zl=class{constructor(e=s$.stdin,r=s$.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Nl,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=n$(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});import{Http2ServerRequest as o2}from"http2";import{Http2ServerRequest as Wh}from"http2";import{Readable as a$}from"stream";import g2 from"crypto";async function f2(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function p$(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 m2(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:p$(t.getReader(),e)}var xo,s2,i2,ia,a2,l$,c2,Is,l2,jl,Ml,u2,Cs,p2,Ll,d2,c$,Os,So,Kh,aa,d$,h2,Yh,y2,f$,Jh,m$,h$,v2,_2,Xh,g$=w(()=>{xo=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},s2=t=>t instanceof xo?t:new xo(t.message,{cause:t}),i2=global.Request,ia=class extends i2{constructor(t,e){typeof t=="object"&&Is in t&&(t=t[Is]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},a2=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)},l$=Symbol("wrapBodyStream"),c2=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ia(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[l$]){let i;s.body=new ReadableStream({async pull(a){try{i||=a$.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=a$.toWeb(n);return new ia(e,s)},Is=Symbol("getRequestCache"),l2=Symbol("requestCache"),jl=Symbol("incomingKey"),Ml=Symbol("urlKey"),u2=Symbol("headersKey"),Cs=Symbol("abortControllerKey"),p2=Symbol("getAbortController"),Ll={get method(){return this[jl].method||"GET"},get url(){return this[Ml]},get headers(){return this[u2]||=a2(this[jl])},[p2](){return this[Is](),this[Cs]},[Is](){return this[Cs]||=new AbortController,this[l2]||=c2(this.method,this[Ml],this.headers,this[jl],this[Cs])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(Ll,t,{get(){return this[Is]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(Ll,t,{value:function(){return this[Is]()[t]()}})});Object.setPrototypeOf(Ll,ia.prototype);d2=(t,e)=>{let r=Object.create(Ll);r[jl]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Wh)throw new xo("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Ml]=a.href}catch(a){throw new xo("Invalid absolute URL",{cause:a})}return r}let o=(t instanceof Wh?t.authority:t.headers.host)||e;if(!o)throw new xo("Missing host header");let s;if(t instanceof Wh){if(s=t.scheme,!(s==="http"||s==="https"))throw new xo("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 xo("Invalid host header");return r[Ml]=i.href,r},c$=Symbol("responseCache"),Os=Symbol("getResponseCache"),So=Symbol("cache"),Kh=global.Response,aa=class u${#t;#e;[Os](){return delete this[So],this[c$]||=new Kh(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof u$){let o=r[c$];if(o){this.#e=o,this[Os]();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[So]=[r?.status||200,e,n])}get headers(){let e=this[So];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[Os]().headers}get status(){return this[So]?.[0]??this[Os]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(aa.prototype,t,{get(){return this[Os]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(aa.prototype,t,{value:function(){return this[Os]()[t]()}})});Object.setPrototypeOf(aa,Kh);Object.setPrototypeOf(aa.prototype,Kh.prototype);d$=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},h2="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=g2);Yh=Symbol("outgoingEnded"),y2=()=>new Response(null,{status:400}),f$=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Jh=(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))},m$=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},h$=async(t,e)=>{let[r,n,o]=t[So];o instanceof Headers&&(o=d$(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())):(m$(e),await m2(n,e)?.catch(s=>Jh(s,e))),e[Yh]?.()},v2=t=>typeof t.then=="function",_2=async(t,e,r={})=>{if(v2(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(f$);if(So in t)return h$(t,e);let n=d$(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 f2(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&&m$(e),await p$(o,e,a))}else n[h2]||(e.writeHead(t.status,n),e.end());e[Yh]?.()},Xh=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ia&&(Object.defineProperty(global,"Request",{value:ia}),Object.defineProperty(global,"Response",{value:aa})),async(n,o)=>{let s,i;try{i=d2(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[l$]=!0,n.on("end",()=>{a=!0}),n instanceof o2&&(o[Yh]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{i[Cs]&&(n.errored?i[Cs].abort(n.errored.toString()):o.writableFinished||i[Cs].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(i,{incoming:n,outgoing:o}),So in s)return h$(s,o)}catch(a){if(s)return Jh(a,o);if(e.errorHandler){if(s=await e.errorHandler(i?a:s2(a)),!s)return}else i?s=f$(a):s=y2()}try{return await _2(s,o,e)}catch(a){return Jh(a,o)}}}});var Dl,y$=w(()=>{Rs();Dl=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}
272
+ 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 y=this.seen.get(h).schema;y.$ref&&p.target==="draft-7"?(d.allOf=d.allOf??[],d.allOf.push(y)):(Object.assign(d,y),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 rS=w(()=>{});var Mt=w(()=>{_s();Ef();_f();H0();Vc();If();Ur();Gc();Qc();wm();Cf();eS();Q0();tS();rS()});var lh=w(()=>{Mt()});var Vi={};V(Vi,{ZodISODate:()=>oS,ZodISODateTime:()=>nS,ZodISODuration:()=>iS,ZodISOTime:()=>sS,date:()=>ph,datetime:()=>uh,duration:()=>fh,time:()=>dh});function uh(t){return W0(nS,t)}function ph(t){return J0(oS,t)}function dh(t){return K0(sS,t)}function fh(t){return Y0(iS,t)}var nS,oS,sS,iS,mh=w(()=>{Mt();hh();nS=E("ZodISODateTime",(t,e)=>{D0.init(t,e),Ve.init(t,e)});oS=E("ZodISODate",(t,e)=>{q0.init(t,e),Ve.init(t,e)});sS=E("ZodISOTime",(t,e)=>{Z0.init(t,e),Ve.init(t,e)});iS=E("ZodISODuration",(t,e)=>{U0.init(t,e),Ve.init(t,e)})});var aS,p5,Wi,gh=w(()=>{Mt();Mt();aS=(t,e)=>{Hc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>vf(t,r)},flatten:{value:r=>yf(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},p5=E("ZodError",aS),Wi=E("ZodError",aS,{Parent:Error})});var cS,lS,uS,pS,yh=w(()=>{Mt();gh();cS=bf(Wi),lS=xf(Wi),uS=$f(Wi),pS=kf(Wi)});function k(t){return xm(wM,t)}function Ie(t){return Hm(gS,t)}function fS(t){return Bm(DM,t)}function ht(t){return Gm(qM,t)}function bh(t){return Vm(ZM,t)}function We(){return Wm(UM)}function HM(t){return Jm(FM,t)}function we(t,e){return X0(BM,t,e)}function j(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new yS(r)}function Lt(t,e){return new yS({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:We(),...be.normalizeParams(e)})}function Ze(t,e){return new vS({type:"union",options:t,...be.normalizeParams(e)})}function wh(t,e,r){return new GM({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function cl(t,e){return new VM({type:"intersection",left:t,right:e})}function Je(t,e,r){return new WM({type:"record",keyType:t,valueType:e,...be.normalizeParams(r)})}function Bt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new vh({type:"enum",entries:r,...be.normalizeParams(e)})}function Z(t,e){return new JM({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function _S(t){return new KM({type:"transform",transform:t})}function tt(t){return new bS({type:"optional",innerType:t})}function mS(t){return new YM({type:"nullable",innerType:t})}function QM(t,e){return new XM({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function tL(t,e){return new eL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function rL(t,e){return new wS({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function oL(t,e){return new nL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function _h(t,e){return new sL({type:"pipe",in:t,out:e})}function aL(t){return new iL({type:"readonly",innerType:t})}function cL(t){let e=new _t({check:"custom"});return e._zod.check=t,e}function SS(t,e){return ih(xS,t??(()=>!0),e)}function lL(t,e={}){return ah(xS,t,e)}function uL(t){let e=cL(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(be.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(be.issue(o))}},t(r.value,r)));return e}function xh(t,e){return _h(_S(t),e)}var rt,hS,wM,Ve,xM,dS,al,SM,$M,kM,EM,TM,PM,RM,OM,CM,IM,AM,NM,zM,jM,MM,LM,gS,DM,qM,ZM,UM,FM,BM,yS,vS,GM,VM,WM,vh,JM,KM,bS,YM,XM,eL,wS,nL,sL,iL,xS,hh=w(()=>{Mt();Mt();lh();mh();yh();rt=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)=>or(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t),t.parse=(r,n)=>cS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>uS(t,r,n),t.parseAsync=async(r,n)=>lS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>pS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(lL(r,n)),t.superRefine=r=>t.check(uL(r)),t.overwrite=r=>t.check(bo(r)),t.optional=()=>tt(t),t.nullable=()=>mS(t),t.nullish=()=>tt(mS(t)),t.nonoptional=r=>rL(t,r),t.array=()=>we(t),t.or=r=>Ze([t,r]),t.and=r=>cl(t,r),t.transform=r=>_h(t,_S(r)),t.default=r=>QM(t,r),t.prefault=r=>tL(t,r),t.catch=r=>oL(t,r),t.pipe=r=>_h(t,r),t.readonly=()=>aL(t),t.describe=r=>{let n=t.clone();return En.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return En.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return En.get(t);let n=t.clone();return En.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),hS=E("_ZodString",(t,e)=>{Fi.init(t,e),rt.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(Km(...n)),t.includes=(...n)=>t.check(Qm(...n)),t.startsWith=(...n)=>t.check(eh(...n)),t.endsWith=(...n)=>t.check(th(...n)),t.min=(...n)=>t.check(xs(...n)),t.max=(...n)=>t.check(ol(...n)),t.length=(...n)=>t.check(sl(...n)),t.nonempty=(...n)=>t.check(xs(1,...n)),t.lowercase=n=>t.check(Ym(n)),t.uppercase=n=>t.check(Xm(n)),t.trim=()=>t.check(nh()),t.normalize=(...n)=>t.check(rh(...n)),t.toLowerCase=()=>t.check(oh()),t.toUpperCase=()=>t.check(sh())}),wM=E("ZodString",(t,e)=>{Fi.init(t,e),hS.init(t,e),t.email=r=>t.check(Sm(xM,r)),t.url=r=>t.check(Pm(SM,r)),t.jwt=r=>t.check(Fm(LM,r)),t.emoji=r=>t.check(Rm($M,r)),t.guid=r=>t.check(el(dS,r)),t.uuid=r=>t.check($m(al,r)),t.uuidv4=r=>t.check(km(al,r)),t.uuidv6=r=>t.check(Em(al,r)),t.uuidv7=r=>t.check(Tm(al,r)),t.nanoid=r=>t.check(Om(kM,r)),t.guid=r=>t.check(el(dS,r)),t.cuid=r=>t.check(Cm(EM,r)),t.cuid2=r=>t.check(Im(TM,r)),t.ulid=r=>t.check(Am(PM,r)),t.base64=r=>t.check(qm(zM,r)),t.base64url=r=>t.check(Zm(jM,r)),t.xid=r=>t.check(Nm(RM,r)),t.ksuid=r=>t.check(zm(OM,r)),t.ipv4=r=>t.check(jm(CM,r)),t.ipv6=r=>t.check(Mm(IM,r)),t.cidrv4=r=>t.check(Lm(AM,r)),t.cidrv6=r=>t.check(Dm(NM,r)),t.e164=r=>t.check(Um(MM,r)),t.datetime=r=>t.check(uh(r)),t.date=r=>t.check(ph(r)),t.time=r=>t.check(dh(r)),t.duration=r=>t.check(fh(r))});Ve=E("ZodStringFormat",(t,e)=>{qe.init(t,e),hS.init(t,e)}),xM=E("ZodEmail",(t,e)=>{jf.init(t,e),Ve.init(t,e)}),dS=E("ZodGUID",(t,e)=>{Nf.init(t,e),Ve.init(t,e)}),al=E("ZodUUID",(t,e)=>{zf.init(t,e),Ve.init(t,e)}),SM=E("ZodURL",(t,e)=>{Mf.init(t,e),Ve.init(t,e)}),$M=E("ZodEmoji",(t,e)=>{Lf.init(t,e),Ve.init(t,e)}),kM=E("ZodNanoID",(t,e)=>{Df.init(t,e),Ve.init(t,e)}),EM=E("ZodCUID",(t,e)=>{qf.init(t,e),Ve.init(t,e)}),TM=E("ZodCUID2",(t,e)=>{Zf.init(t,e),Ve.init(t,e)}),PM=E("ZodULID",(t,e)=>{Uf.init(t,e),Ve.init(t,e)}),RM=E("ZodXID",(t,e)=>{Ff.init(t,e),Ve.init(t,e)}),OM=E("ZodKSUID",(t,e)=>{Hf.init(t,e),Ve.init(t,e)}),CM=E("ZodIPv4",(t,e)=>{Bf.init(t,e),Ve.init(t,e)}),IM=E("ZodIPv6",(t,e)=>{Gf.init(t,e),Ve.init(t,e)}),AM=E("ZodCIDRv4",(t,e)=>{Vf.init(t,e),Ve.init(t,e)}),NM=E("ZodCIDRv6",(t,e)=>{Wf.init(t,e),Ve.init(t,e)}),zM=E("ZodBase64",(t,e)=>{Jf.init(t,e),Ve.init(t,e)}),jM=E("ZodBase64URL",(t,e)=>{Kf.init(t,e),Ve.init(t,e)}),MM=E("ZodE164",(t,e)=>{Yf.init(t,e),Ve.init(t,e)}),LM=E("ZodJWT",(t,e)=>{Xf.init(t,e),Ve.init(t,e)}),gS=E("ZodNumber",(t,e)=>{Kc.init(t,e),rt.init(t,e),t.gt=(n,o)=>t.check(rl(n,o)),t.gte=(n,o)=>t.check(Gi(n,o)),t.min=(n,o)=>t.check(Gi(n,o)),t.lt=(n,o)=>t.check(tl(n,o)),t.lte=(n,o)=>t.check(Bi(n,o)),t.max=(n,o)=>t.check(Bi(n,o)),t.int=n=>t.check(fS(n)),t.safe=n=>t.check(fS(n)),t.positive=n=>t.check(rl(0,n)),t.nonnegative=n=>t.check(Gi(0,n)),t.negative=n=>t.check(tl(0,n)),t.nonpositive=n=>t.check(Bi(0,n)),t.multipleOf=(n,o)=>t.check(nl(n,o)),t.step=(n,o)=>t.check(nl(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});DM=E("ZodNumberFormat",(t,e)=>{Qf.init(t,e),gS.init(t,e)});qM=E("ZodBoolean",(t,e)=>{em.init(t,e),rt.init(t,e)});ZM=E("ZodNull",(t,e)=>{tm.init(t,e),rt.init(t,e)});UM=E("ZodUnknown",(t,e)=>{rm.init(t,e),rt.init(t,e)});FM=E("ZodNever",(t,e)=>{nm.init(t,e),rt.init(t,e)});BM=E("ZodArray",(t,e)=>{om.init(t,e),rt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(xs(r,n)),t.nonempty=r=>t.check(xs(1,r)),t.max=(r,n)=>t.check(ol(r,n)),t.length=(r,n)=>t.check(sl(r,n)),t.unwrap=()=>t.element});yS=E("ZodObject",(t,e)=>{Yc.init(t,e),rt.init(t,e),be.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>Bt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:We()}),t.loose=()=>t.clone({...t._zod.def,catchall:We()}),t.strict=()=>t.clone({...t._zod.def,catchall:HM()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>be.extend(t,r),t.merge=r=>be.merge(t,r),t.pick=r=>be.pick(t,r),t.omit=r=>be.omit(t,r),t.partial=(...r)=>be.partial(bS,t,r[0]),t.required=(...r)=>be.required(wS,t,r[0])});vS=E("ZodUnion",(t,e)=>{Xc.init(t,e),rt.init(t,e),t.options=e.options});GM=E("ZodDiscriminatedUnion",(t,e)=>{vS.init(t,e),sm.init(t,e)});VM=E("ZodIntersection",(t,e)=>{im.init(t,e),rt.init(t,e)});WM=E("ZodRecord",(t,e)=>{am.init(t,e),rt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});vh=E("ZodEnum",(t,e)=>{cm.init(t,e),rt.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 vh({...e,checks:[],...be.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 vh({...e,checks:[],...be.normalizeParams(o),entries:s})}});JM=E("ZodLiteral",(t,e)=>{lm.init(t,e),rt.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]}})});KM=E("ZodTransform",(t,e)=>{um.init(t,e),rt.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(be.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(be.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});bS=E("ZodOptional",(t,e)=>{pm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});YM=E("ZodNullable",(t,e)=>{dm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});XM=E("ZodDefault",(t,e)=>{fm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});eL=E("ZodPrefault",(t,e)=>{mm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});wS=E("ZodNonOptional",(t,e)=>{hm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});nL=E("ZodCatch",(t,e)=>{gm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});sL=E("ZodPipe",(t,e)=>{ym.init(t,e),rt.init(t,e),t.in=e.in,t.out=e.out});iL=E("ZodReadonly",(t,e)=>{vm.init(t,e),rt.init(t,e)});xS=E("ZodCustom",(t,e)=>{_m.init(t,e),rt.init(t,e)})});var $S=w(()=>{});var kS=w(()=>{});var ES=w(()=>{Mt();hh();lh();gh();yh();$S();Mt();G0();Qc();mh();kS();nr(B0())});var TS=w(()=>{ES()});var PS=w(()=>{TS()});function FS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function HS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var $h,RS,Ji,Tn,ul,bt,OS,CS,T5,fL,mL,kh,sr,Ki,IS,wt,lr,ur,xt,pl,AS,Pn,NS,zS,Eh,on,G,Th,$s,Yi,P5,dl,hL,fl,gL,Xi,Ss,jS,yL,vL,_L,bL,wL,xL,ml,Ph,SL,$L,Rh,hl,kL,EL,gl,TL,Qi,ea,PL,ta,ks,RL,ra,yl,vl,_l,R5,bl,wl,xl,MS,LS,DS,Oh,qS,na,Es,ZS,OL,Sl,CL,$l,IL,Ch,AL,kl,NL,zL,jL,ML,LL,DL,qL,ZL,UL,FL,El,HL,BL,Tl,Ih,Ah,Nh,GL,VL,WL,zh,JL,KL,YL,XL,QL,US,Pl,eD,Rl,O5,tD,Ts,rD,C5,oa,nD,jh,oD,sD,iD,aD,cD,lD,uD,ll,pD,dD,fD,Mh,Lh,mD,hD,gD,yD,vD,_D,bD,wD,xD,SD,$D,kD,ED,TD,PD,RD,OD,CD,Ol,ID,AD,ND,Cl,zD,jD,MD,Dh,LD,I5,A5,N5,z5,j5,M5,q,Sh,Ps=w(()=>{PS();$h="2025-11-25",RS="2025-03-26",Ji=[$h,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Tn="io.modelcontextprotocol/related-task",ul="2.0",bt=SS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),OS=Ze([k(),Ie().int()]),CS=k(),T5=Lt({ttl:Ze([Ie(),bh()]).optional(),pollInterval:Ie().optional()}),fL=j({ttl:Ie().optional()}),mL=j({taskId:k()}),kh=Lt({progressToken:OS.optional(),[Tn]:mL.optional()}),sr=j({_meta:kh.optional()}),Ki=sr.extend({task:fL.optional()}),IS=t=>Ki.safeParse(t).success,wt=j({method:k(),params:sr.loose().optional()}),lr=j({_meta:kh.optional()}),ur=j({method:k(),params:lr.loose().optional()}),xt=Lt({_meta:kh.optional()}),pl=Ze([k(),Ie().int()]),AS=j({jsonrpc:Z(ul),id:pl,...wt.shape}).strict(),Pn=t=>AS.safeParse(t).success,NS=j({jsonrpc:Z(ul),...ur.shape}).strict(),zS=t=>NS.safeParse(t).success,Eh=j({jsonrpc:Z(ul),id:pl,result:xt}).strict(),on=t=>Eh.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"})(G||(G={}));Th=j({jsonrpc:Z(ul),id:pl.optional(),error:j({code:Ie().int(),message:k(),data:We().optional()})}).strict(),$s=t=>Th.safeParse(t).success,Yi=Ze([AS,NS,Eh,Th]),P5=Ze([Eh,Th]),dl=xt.strict(),hL=lr.extend({requestId:pl.optional(),reason:k().optional()}),fl=ur.extend({method:Z("notifications/cancelled"),params:hL}),gL=j({src:k(),mimeType:k().optional(),sizes:we(k()).optional(),theme:Bt(["light","dark"]).optional()}),Xi=j({icons:we(gL).optional()}),Ss=j({name:k(),title:k().optional()}),jS=Ss.extend({...Ss.shape,...Xi.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),yL=cl(j({applyDefaults:ht().optional()}),Je(k(),We())),vL=xh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,cl(j({form:yL.optional(),url:bt.optional()}),Je(k(),We()).optional())),_L=Lt({list:bt.optional(),cancel:bt.optional(),requests:Lt({sampling:Lt({createMessage:bt.optional()}).optional(),elicitation:Lt({create:bt.optional()}).optional()}).optional()}),bL=Lt({list:bt.optional(),cancel:bt.optional(),requests:Lt({tools:Lt({call:bt.optional()}).optional()}).optional()}),wL=j({experimental:Je(k(),bt).optional(),sampling:j({context:bt.optional(),tools:bt.optional()}).optional(),elicitation:vL.optional(),roots:j({listChanged:ht().optional()}).optional(),tasks:_L.optional()}),xL=sr.extend({protocolVersion:k(),capabilities:wL,clientInfo:jS}),ml=wt.extend({method:Z("initialize"),params:xL}),Ph=t=>ml.safeParse(t).success,SL=j({experimental:Je(k(),bt).optional(),logging:bt.optional(),completions:bt.optional(),prompts:j({listChanged:ht().optional()}).optional(),resources:j({subscribe:ht().optional(),listChanged:ht().optional()}).optional(),tools:j({listChanged:ht().optional()}).optional(),tasks:bL.optional()}),$L=xt.extend({protocolVersion:k(),capabilities:SL,serverInfo:jS,instructions:k().optional()}),Rh=ur.extend({method:Z("notifications/initialized"),params:lr.optional()}),hl=wt.extend({method:Z("ping"),params:sr.optional()}),kL=j({progress:Ie(),total:tt(Ie()),message:tt(k())}),EL=j({...lr.shape,...kL.shape,progressToken:OS}),gl=ur.extend({method:Z("notifications/progress"),params:EL}),TL=sr.extend({cursor:CS.optional()}),Qi=wt.extend({params:TL.optional()}),ea=xt.extend({nextCursor:CS.optional()}),PL=Bt(["working","input_required","completed","failed","cancelled"]),ta=j({taskId:k(),status:PL,ttl:Ze([Ie(),bh()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:tt(Ie()),statusMessage:tt(k())}),ks=xt.extend({task:ta}),RL=lr.merge(ta),ra=ur.extend({method:Z("notifications/tasks/status"),params:RL}),yl=wt.extend({method:Z("tasks/get"),params:sr.extend({taskId:k()})}),vl=xt.merge(ta),_l=wt.extend({method:Z("tasks/result"),params:sr.extend({taskId:k()})}),R5=xt.loose(),bl=Qi.extend({method:Z("tasks/list")}),wl=ea.extend({tasks:we(ta)}),xl=wt.extend({method:Z("tasks/cancel"),params:sr.extend({taskId:k()})}),MS=xt.merge(ta),LS=j({uri:k(),mimeType:tt(k()),_meta:Je(k(),We()).optional()}),DS=LS.extend({text:k()}),Oh=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),qS=LS.extend({blob:Oh}),na=Bt(["user","assistant"]),Es=j({audience:we(na).optional(),priority:Ie().min(0).max(1).optional(),lastModified:Vi.datetime({offset:!0}).optional()}),ZS=j({...Ss.shape,...Xi.shape,uri:k(),description:tt(k()),mimeType:tt(k()),annotations:Es.optional(),_meta:tt(Lt({}))}),OL=j({...Ss.shape,...Xi.shape,uriTemplate:k(),description:tt(k()),mimeType:tt(k()),annotations:Es.optional(),_meta:tt(Lt({}))}),Sl=Qi.extend({method:Z("resources/list")}),CL=ea.extend({resources:we(ZS)}),$l=Qi.extend({method:Z("resources/templates/list")}),IL=ea.extend({resourceTemplates:we(OL)}),Ch=sr.extend({uri:k()}),AL=Ch,kl=wt.extend({method:Z("resources/read"),params:AL}),NL=xt.extend({contents:we(Ze([DS,qS]))}),zL=ur.extend({method:Z("notifications/resources/list_changed"),params:lr.optional()}),jL=Ch,ML=wt.extend({method:Z("resources/subscribe"),params:jL}),LL=Ch,DL=wt.extend({method:Z("resources/unsubscribe"),params:LL}),qL=lr.extend({uri:k()}),ZL=ur.extend({method:Z("notifications/resources/updated"),params:qL}),UL=j({name:k(),description:tt(k()),required:tt(ht())}),FL=j({...Ss.shape,...Xi.shape,description:tt(k()),arguments:tt(we(UL)),_meta:tt(Lt({}))}),El=Qi.extend({method:Z("prompts/list")}),HL=ea.extend({prompts:we(FL)}),BL=sr.extend({name:k(),arguments:Je(k(),k()).optional()}),Tl=wt.extend({method:Z("prompts/get"),params:BL}),Ih=j({type:Z("text"),text:k(),annotations:Es.optional(),_meta:Je(k(),We()).optional()}),Ah=j({type:Z("image"),data:Oh,mimeType:k(),annotations:Es.optional(),_meta:Je(k(),We()).optional()}),Nh=j({type:Z("audio"),data:Oh,mimeType:k(),annotations:Es.optional(),_meta:Je(k(),We()).optional()}),GL=j({type:Z("tool_use"),name:k(),id:k(),input:Je(k(),We()),_meta:Je(k(),We()).optional()}),VL=j({type:Z("resource"),resource:Ze([DS,qS]),annotations:Es.optional(),_meta:Je(k(),We()).optional()}),WL=ZS.extend({type:Z("resource_link")}),zh=Ze([Ih,Ah,Nh,WL,VL]),JL=j({role:na,content:zh}),KL=xt.extend({description:k().optional(),messages:we(JL)}),YL=ur.extend({method:Z("notifications/prompts/list_changed"),params:lr.optional()}),XL=j({title:k().optional(),readOnlyHint:ht().optional(),destructiveHint:ht().optional(),idempotentHint:ht().optional(),openWorldHint:ht().optional()}),QL=j({taskSupport:Bt(["required","optional","forbidden"]).optional()}),US=j({...Ss.shape,...Xi.shape,description:k().optional(),inputSchema:j({type:Z("object"),properties:Je(k(),bt).optional(),required:we(k()).optional()}).catchall(We()),outputSchema:j({type:Z("object"),properties:Je(k(),bt).optional(),required:we(k()).optional()}).catchall(We()).optional(),annotations:XL.optional(),execution:QL.optional(),_meta:Je(k(),We()).optional()}),Pl=Qi.extend({method:Z("tools/list")}),eD=ea.extend({tools:we(US)}),Rl=xt.extend({content:we(zh).default([]),structuredContent:Je(k(),We()).optional(),isError:ht().optional()}),O5=Rl.or(xt.extend({toolResult:We()})),tD=Ki.extend({name:k(),arguments:Je(k(),We()).optional()}),Ts=wt.extend({method:Z("tools/call"),params:tD}),rD=ur.extend({method:Z("notifications/tools/list_changed"),params:lr.optional()}),C5=j({autoRefresh:ht().default(!0),debounceMs:Ie().int().nonnegative().default(300)}),oa=Bt(["debug","info","notice","warning","error","critical","alert","emergency"]),nD=sr.extend({level:oa}),jh=wt.extend({method:Z("logging/setLevel"),params:nD}),oD=lr.extend({level:oa,logger:k().optional(),data:We()}),sD=ur.extend({method:Z("notifications/message"),params:oD}),iD=j({name:k().optional()}),aD=j({hints:we(iD).optional(),costPriority:Ie().min(0).max(1).optional(),speedPriority:Ie().min(0).max(1).optional(),intelligencePriority:Ie().min(0).max(1).optional()}),cD=j({mode:Bt(["auto","required","none"]).optional()}),lD=j({type:Z("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:we(zh).default([]),structuredContent:j({}).loose().optional(),isError:ht().optional(),_meta:Je(k(),We()).optional()}),uD=wh("type",[Ih,Ah,Nh]),ll=wh("type",[Ih,Ah,Nh,GL,lD]),pD=j({role:na,content:Ze([ll,we(ll)]),_meta:Je(k(),We()).optional()}),dD=Ki.extend({messages:we(pD),modelPreferences:aD.optional(),systemPrompt:k().optional(),includeContext:Bt(["none","thisServer","allServers"]).optional(),temperature:Ie().optional(),maxTokens:Ie().int(),stopSequences:we(k()).optional(),metadata:bt.optional(),tools:we(US).optional(),toolChoice:cD.optional()}),fD=wt.extend({method:Z("sampling/createMessage"),params:dD}),Mh=xt.extend({model:k(),stopReason:tt(Bt(["endTurn","stopSequence","maxTokens"]).or(k())),role:na,content:uD}),Lh=xt.extend({model:k(),stopReason:tt(Bt(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:na,content:Ze([ll,we(ll)])}),mD=j({type:Z("boolean"),title:k().optional(),description:k().optional(),default:ht().optional()}),hD=j({type:Z("string"),title:k().optional(),description:k().optional(),minLength:Ie().optional(),maxLength:Ie().optional(),format:Bt(["email","uri","date","date-time"]).optional(),default:k().optional()}),gD=j({type:Bt(["number","integer"]),title:k().optional(),description:k().optional(),minimum:Ie().optional(),maximum:Ie().optional(),default:Ie().optional()}),yD=j({type:Z("string"),title:k().optional(),description:k().optional(),enum:we(k()),default:k().optional()}),vD=j({type:Z("string"),title:k().optional(),description:k().optional(),oneOf:we(j({const:k(),title:k()})),default:k().optional()}),_D=j({type:Z("string"),title:k().optional(),description:k().optional(),enum:we(k()),enumNames:we(k()).optional(),default:k().optional()}),bD=Ze([yD,vD]),wD=j({type:Z("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({type:Z("string"),enum:we(k())}),default:we(k()).optional()}),xD=j({type:Z("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({anyOf:we(j({const:k(),title:k()}))}),default:we(k()).optional()}),SD=Ze([wD,xD]),$D=Ze([_D,bD,SD]),kD=Ze([$D,mD,hD,gD]),ED=Ki.extend({mode:Z("form").optional(),message:k(),requestedSchema:j({type:Z("object"),properties:Je(k(),kD),required:we(k()).optional()})}),TD=Ki.extend({mode:Z("url"),message:k(),elicitationId:k(),url:k().url()}),PD=Ze([ED,TD]),RD=wt.extend({method:Z("elicitation/create"),params:PD}),OD=lr.extend({elicitationId:k()}),CD=ur.extend({method:Z("notifications/elicitation/complete"),params:OD}),Ol=xt.extend({action:Bt(["accept","decline","cancel"]),content:xh(t=>t===null?void 0:t,Je(k(),Ze([k(),Ie(),ht(),we(k())])).optional())}),ID=j({type:Z("ref/resource"),uri:k()}),AD=j({type:Z("ref/prompt"),name:k()}),ND=sr.extend({ref:Ze([AD,ID]),argument:j({name:k(),value:k()}),context:j({arguments:Je(k(),k()).optional()}).optional()}),Cl=wt.extend({method:Z("completion/complete"),params:ND});zD=xt.extend({completion:Lt({values:we(k()).max(100),total:tt(Ie().int()),hasMore:tt(ht())})}),jD=j({uri:k().startsWith("file://"),name:k().optional(),_meta:Je(k(),We()).optional()}),MD=wt.extend({method:Z("roots/list"),params:sr.optional()}),Dh=xt.extend({roots:we(jD)}),LD=ur.extend({method:Z("notifications/roots/list_changed"),params:lr.optional()}),I5=Ze([hl,ml,Cl,jh,Tl,El,Sl,$l,kl,ML,DL,Ts,Pl,yl,_l,bl,xl]),A5=Ze([fl,gl,Rh,LD,ra]),N5=Ze([dl,Mh,Lh,Ol,Dh,vl,wl,ks]),z5=Ze([hl,fD,RD,MD,yl,_l,bl,xl]),j5=Ze([fl,gl,sD,ZL,zL,rD,YL,ra,CD]),M5=Ze([dl,$L,zD,KL,HL,CL,IL,NL,Rl,eD,vl,wl,ks]),q=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===G.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Sh(o.elicitations,r)}return new t(e,r,n)}},Sh=class extends q{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(G.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function DD(t){return Yi.parse(JSON.parse(t))}function BS(t){return JSON.stringify(t)+`
273
+ `}var Il,GS=w(()=>{Ps();Il=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
274
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),DD(r)}clear(){this._buffer=void 0}}});import VS from"node:process";var Al,WS=w(()=>{GS();Al=class{constructor(e=VS.stdin,r=VS.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Il,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=BS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});import{Http2ServerRequest as qD}from"http2";import{Http2ServerRequest as qh}from"http2";import{Readable as JS}from"stream";import XD from"crypto";async function JD(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function QS(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 KD(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:QS(t.getReader(),e)}var xo,ZD,UD,sa,FD,YS,HD,Cs,BD,Nl,zl,GD,Os,VD,jl,WD,KS,Rs,So,Uh,ia,e$,YD,Fh,QD,t$,Zh,r$,n$,e2,t2,Hh,o$=w(()=>{xo=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},ZD=t=>t instanceof xo?t:new xo(t.message,{cause:t}),UD=global.Request,sa=class extends UD{constructor(t,e){typeof t=="object"&&Cs in t&&(t=t[Cs]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},FD=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)},YS=Symbol("wrapBodyStream"),HD=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new sa(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[YS]){let i;s.body=new ReadableStream({async pull(a){try{i||=JS.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=JS.toWeb(n);return new sa(e,s)},Cs=Symbol("getRequestCache"),BD=Symbol("requestCache"),Nl=Symbol("incomingKey"),zl=Symbol("urlKey"),GD=Symbol("headersKey"),Os=Symbol("abortControllerKey"),VD=Symbol("getAbortController"),jl={get method(){return this[Nl].method||"GET"},get url(){return this[zl]},get headers(){return this[GD]||=FD(this[Nl])},[VD](){return this[Cs](),this[Os]},[Cs](){return this[Os]||=new AbortController,this[BD]||=HD(this.method,this[zl],this.headers,this[Nl],this[Os])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(jl,t,{get(){return this[Cs]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(jl,t,{value:function(){return this[Cs]()[t]()}})});Object.setPrototypeOf(jl,sa.prototype);WD=(t,e)=>{let r=Object.create(jl);r[Nl]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof qh)throw new xo("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[zl]=a.href}catch(a){throw new xo("Invalid absolute URL",{cause:a})}return r}let o=(t instanceof qh?t.authority:t.headers.host)||e;if(!o)throw new xo("Missing host header");let s;if(t instanceof qh){if(s=t.scheme,!(s==="http"||s==="https"))throw new xo("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 xo("Invalid host header");return r[zl]=i.href,r},KS=Symbol("responseCache"),Rs=Symbol("getResponseCache"),So=Symbol("cache"),Uh=global.Response,ia=class XS{#t;#e;[Rs](){return delete this[So],this[KS]||=new Uh(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof XS){let o=r[KS];if(o){this.#e=o,this[Rs]();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[So]=[r?.status||200,e,n])}get headers(){let e=this[So];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[Rs]().headers}get status(){return this[So]?.[0]??this[Rs]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(ia.prototype,t,{get(){return this[Rs]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(ia.prototype,t,{value:function(){return this[Rs]()[t]()}})});Object.setPrototypeOf(ia,Uh);Object.setPrototypeOf(ia.prototype,Uh.prototype);e$=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},YD="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=XD);Fh=Symbol("outgoingEnded"),QD=()=>new Response(null,{status:400}),t$=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Zh=(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))},r$=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},n$=async(t,e)=>{let[r,n,o]=t[So];o instanceof Headers&&(o=e$(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())):(r$(e),await KD(n,e)?.catch(s=>Zh(s,e))),e[Fh]?.()},e2=t=>typeof t.then=="function",t2=async(t,e,r={})=>{if(e2(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(t$);if(So in t)return n$(t,e);let n=e$(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 JD(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&&r$(e),await QS(o,e,a))}else n[YD]||(e.writeHead(t.status,n),e.end());e[Fh]?.()},Hh=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==sa&&(Object.defineProperty(global,"Request",{value:sa}),Object.defineProperty(global,"Response",{value:ia})),async(n,o)=>{let s,i;try{i=WD(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[YS]=!0,n.on("end",()=>{a=!0}),n instanceof qD&&(o[Fh]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{i[Os]&&(n.errored?i[Os].abort(n.errored.toString()):o.writableFinished||i[Os].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(i,{incoming:n,outgoing:o}),So in s)return n$(s,o)}catch(a){if(s)return Zh(a,o);if(e.errorHandler){if(s=await e.errorHandler(i?a:ZD(a)),!s)return}else i?s=t$(a):s=QD()}try{return await t2(s,o,e)}catch(a){return Zh(a,o)}}}});var Ml,s$=w(()=>{Ps();Ml=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
275
  data:
275
276
 
276
277
  `;this._retryInterval!==void 0&&(i=`id: ${s}
@@ -281,18 +282,18 @@ data:
281
282
  `;return o&&(s+=`id: ${o}
282
283
  `),s+=`data: ${JSON.stringify(n)}
283
284
 
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=>Xi.parse(v)):a=[Xi.parse(i)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=a.some(jh);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=>jh(v)),f=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??ZS;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)}}),y={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(y["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:y})}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&&!Ki.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Ki.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((tn(e)||ks(e))&&(n=e.id),n===void 0){if(tn(e)||ks(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(tn(e)||ks(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 ql,v$=w(()=>{g$();y$();ql=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Dl(e),this._requestListener=Xh(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 Xh(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 ye,Qh,z,qr,ca=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})(ye||(ye={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Qh||(Qh={}));z=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),qr=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,b2,Ht,Zl=w(()=>{ca();T=ye.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"]),b2=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Ht=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,ye.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()}};Ht.create=t=>new Ht(t)});var w2,rn,eg=w(()=>{Zl();ca();w2=(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,ye.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case T.invalid_union:r="Invalid input";break;case T.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case T.invalid_enum_value:r=`Invalid enum value. Expected ${ye.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}"`:ye.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,ye.assertNever(t)}return{message:r}},rn=w2});function x2(t){_$=t}function As(){return _$}var _$,Ul=w(()=>{eg();_$=rn});function N(t,e){let r=As(),n=la({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===rn?void 0:rn].filter(o=>!!o)});t.common.issues.push(n)}var la,S2,xt,J,$o,Rt,Fl,Hl,Pn,Ns,tg=w(()=>{Ul();eg();la=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}},S2=[];xt=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"}),$o=t=>({status:"dirty",value:t}),Rt=t=>({status:"valid",value:t}),Fl=t=>t.status==="aborted",Hl=t=>t.status==="dirty",Pn=t=>t.status==="valid",Ns=t=>typeof Promise<"u"&&t instanceof Promise});var b$=w(()=>{});var D,w$=w(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(D||(D={}))});function se(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 k$(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 q2(t){return new RegExp(`^${k$(t)}$`)}function E$(t){let e=`${$$}T${k$(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 Z2(t,e){return!!((e==="v4"||!e)&&A2.test(t)||(e==="v6"||!e)&&z2.test(t))}function U2(t,e){if(!R2.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 F2(t,e){return!!((e==="v4"||!e)&&N2.test(t)||(e==="v6"||!e)&&j2.test(t))}function H2(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 zs(t){if(t instanceof Gt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Bt.create(zs(n))}return new Gt({...t._def,shape:()=>e})}else return t instanceof sn?new sn({...t._def,type:zs(t.element)}):t instanceof Bt?Bt.create(zs(t.unwrap())):t instanceof Ur?Ur.create(zs(t.unwrap())):t instanceof Zr?Zr.create(t.items.map(e=>zs(e))):t}function ng(t,e){let r=qr(t),n=qr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=ng(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=ng(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 T$(t,e){return new zo({values:t,typeName:P.ZodEnum,...se(e)})}function S$(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function P$(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=S$(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=S$(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):On.create()}var lr,x$,ue,$2,k2,E2,T2,P2,R2,O2,C2,I2,rg,A2,N2,z2,j2,M2,L2,$$,D2,Rn,ko,Eo,To,Po,js,Ro,Oo,On,on,kr,Ms,sn,Gt,Co,nn,Bl,Io,Zr,Gl,Ls,Ds,Vl,Ao,No,zo,jo,Cn,ur,Bt,Ur,Mo,Lo,qs,B2,ua,pa,Do,G2,P,V2,R$,O$,W2,J2,C$,K2,Y2,X2,Q2,eq,tq,rq,nq,oq,og,sq,iq,aq,cq,lq,uq,pq,dq,fq,mq,hq,gq,yq,vq,_q,bq,wq,xq,Sq,$q,kq,Eq,Tq,Pq,I$=w(()=>{Zl();Ul();w$();tg();ca();lr=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}},x$=(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 Ht(t.common.issues);return this._error=r,this._error}}};ue=class{get description(){return this._def.description}_getType(e){return qr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:qr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new xt,ctx:{common:e.parent.common,data:e.data,parsedType:qr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ns(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:qr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return x$(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qr(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:qr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(Ns(o)?o:Promise.resolve(o));return x$(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 ur({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 Bt.create(this,this._def)}nullable(){return Ur.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return sn.create(this)}promise(){return Cn.create(this,this._def)}or(e){return Co.create([this,e],this._def)}and(e){return Io.create(this,e,this._def)}transform(e){return new ur({...se(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Mo({...se(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new ua({typeName:P.ZodBranded,type:this,...se(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Lo({...se(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 pa.create(this,e)}readonly(){return Do.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},$2=/^c[^\s-]{8,}$/i,k2=/^[0-9a-z]+$/,E2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,T2=/^[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,P2=/^[a-z0-9_-]{21}$/i,R2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,O2=/^[-+]?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)?)??$/,C2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,I2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",A2=/^(?:(?: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])$/,N2=/^(?:(?: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])$/,z2=/^(([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]))$/,j2=/^(([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])$/,M2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,L2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,$$="((\\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])))",D2=new RegExp(`^${$$}$`);Rn=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new xt,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),N(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),N(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?N(o,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&N(o,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")C2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"email",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")rg||(rg=new RegExp(I2,"u")),rg.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"emoji",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")T2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"uuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")P2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"nanoid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")$2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")k2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid2",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")E2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(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),N(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),N(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),N(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),N(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),N(o,{code:T.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?E$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?D2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?q2(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?O2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"duration",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?Z2(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"ip",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?U2(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"jwt",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?F2(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cidr",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?M2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?L2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64url",code:T.invalid_string,message:s.message}),n.dirty()):ye.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,...D.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...D.errToObj(e)})}url(e){return this._addCheck({kind:"url",...D.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...D.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...D.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...D.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...D.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...D.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...D.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...D.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...D.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...D.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...D.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...D.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,...D.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,...D.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...D.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...D.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...D.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...D.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...D.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...D.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...D.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...D.errToObj(r)})}nonempty(e){return this.min(1,D.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,...se(t)});ko=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)!==z.number){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new xt;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(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),N(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),N(n,{code:T.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?H2(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),N(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),N(n,{code:T.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,D.toString(r))}gt(e,r){return this.setLimit("min",e,!1,D.toString(r))}lte(e,r){return this.setLimit("max",e,!0,D.toString(r))}lt(e,r){return this.setLimit("max",e,!1,D.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:D.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:D.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:D.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:D.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.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"&&ye.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)}};ko.create=t=>new ko({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...se(t)});Eo=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)!==z.bigint)return this._getInvalidInput(e);let n,o=new xt;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),N(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),N(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),N(n,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:T.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,D.toString(r))}gt(e,r){return this.setLimit("min",e,!1,D.toString(r))}lte(e,r){return this.setLimit("max",e,!0,D.toString(r))}lt(e,r){return this.setLimit("max",e,!1,D.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:D.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:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:D.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}};Eo.create=t=>new Eo({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...se(t)});To=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.boolean,received:n.parsedType}),J}return Rt(e.data)}};To.create=t=>new To({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...se(t)});Po=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_date}),J}let n=new xt,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),N(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),N(o,{code:T.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.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:D.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:D.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}};Po.create=t=>new Po({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...se(t)});js=class extends ue{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.symbol,received:n.parsedType}),J}return Rt(e.data)}};js.create=t=>new js({typeName:P.ZodSymbol,...se(t)});Ro=class extends ue{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.undefined,received:n.parsedType}),J}return Rt(e.data)}};Ro.create=t=>new Ro({typeName:P.ZodUndefined,...se(t)});Oo=class extends ue{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.null,received:n.parsedType}),J}return Rt(e.data)}};Oo.create=t=>new Oo({typeName:P.ZodNull,...se(t)});On=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return Rt(e.data)}};On.create=t=>new On({typeName:P.ZodAny,...se(t)});on=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Rt(e.data)}};on.create=t=>new on({typeName:P.ZodUnknown,...se(t)});kr=class extends ue{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:T.invalid_type,expected:z.never,received:r.parsedType}),J}};kr.create=t=>new kr({typeName:P.ZodNever,...se(t)});Ms=class extends ue{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.void,received:n.parsedType}),J}return Rt(e.data)}};Ms.create=t=>new Ms({typeName:P.ZodVoid,...se(t)});sn=class t extends ue{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return N(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)&&(N(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&&(N(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&&(N(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 lr(r,i,r.path,a)))).then(i=>xt.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new lr(r,i,r.path,a)));return xt.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:D.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:D.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:D.toString(r)}})}nonempty(e){return this.min(1,e)}};sn.create=(t,e)=>new sn({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...se(e)});Gt=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=ye.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 N(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 kr&&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 lr(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof kr){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&&(N(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 lr(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=>xt.mergeObjectSync(n,l)):xt.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return D.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:D.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 ye.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 ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return zs(this)}partial(e){let r={};for(let n of ye.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 ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Bt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return T$(ye.objectKeys(this.shape))}};Gt.create=(t,e)=>new Gt({shape:()=>t,unknownKeys:"strip",catchall:kr.create(),typeName:P.ZodObject,...se(e)});Gt.strictCreate=(t,e)=>new Gt({shape:()=>t,unknownKeys:"strict",catchall:kr.create(),typeName:P.ZodObject,...se(e)});Gt.lazycreate=(t,e)=>new Gt({shape:t,unknownKeys:"strip",catchall:kr.create(),typeName:P.ZodObject,...se(e)});Co=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 Ht(a.ctx.common.issues));return N(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 Ht(c));return N(r,{code:T.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};Co.create=(t,e)=>new Co({options:t,typeName:P.ZodUnion,...se(e)});nn=t=>t instanceof Ao?nn(t.schema):t instanceof ur?nn(t.innerType()):t instanceof No?[t.value]:t instanceof zo?t.options:t instanceof jo?ye.objectValues(t.enum):t instanceof Mo?nn(t._def.innerType):t instanceof Ro?[void 0]:t instanceof Oo?[null]:t instanceof Bt?[void 0,...nn(t.unwrap())]:t instanceof Ur?[null,...nn(t.unwrap())]:t instanceof ua||t instanceof Do?nn(t.unwrap()):t instanceof Lo?nn(t._def.innerType):[],Bl=class t extends ue{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return N(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}):(N(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=nn(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,...se(n)})}};Io=class extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Fl(s)||Fl(i))return J;let a=ng(s.value,i.value);return a.valid?((Hl(s)||Hl(i))&&r.dirty(),{status:r.value,value:a.data}):(N(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}))}};Io.create=(t,e,r)=>new Io({left:t,right:e,typeName:P.ZodIntersection,...se(r)});Zr=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return N(n,{code:T.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return N(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&&(N(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 lr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>xt.mergeArray(r,i)):xt.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Zr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Zr({items:t,typeName:P.ZodTuple,rest:null,...se(e)})};Gl=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!==z.object)return N(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 lr(n,a,n.path,a)),value:i._parse(new lr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?xt.mergeObjectAsync(r,o):xt.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,...se(n)}):new t({keyType:Rn.create(),valueType:e,typeName:P.ZodRecord,...se(r)})}},Ls=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!==z.map)return N(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 lr(n,a,n.path,[l,"key"])),value:s._parse(new lr(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}}}};Ls.create=(t,e,r)=>new Ls({valueType:e,keyType:t,typeName:P.ZodMap,...se(r)});Ds=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return N(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&&(N(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&&(N(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 lr(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:D.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:D.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Ds.create=(t,e)=>new Ds({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...se(e)});Vl=class t extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return N(r,{code:T.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return la({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,As(),rn].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function o(a,c){return la({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,As(),rn].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 Rt(async function(...c){let l=new Ht([]),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 Rt(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Ht([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new Ht([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:Zr.create(e).rest(on.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||Zr.create([]).rest(on.create()),returns:r||on.create(),typeName:P.ZodFunction,...se(n)})}},Ao=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})}};Ao.create=(t,e)=>new Ao({getter:t,typeName:P.ZodLazy,...se(e)});No=class extends ue{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(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}};No.create=(t,e)=>new No({value:t,typeName:P.ZodLiteral,...se(e)});zo=class t extends ue{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ye.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 N(r,{received:r.data,code:T.invalid_enum_value,options:n}),J}return Rt(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})}};zo.create=T$;jo=class extends ue{_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=ye.objectValues(r);return N(n,{expected:ye.joinValues(o),received:n.parsedType,code:T.invalid_type}),J}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ye.objectValues(r);return N(n,{received:n.data,code:T.invalid_enum_value,options:o}),J}return Rt(e.data)}get enum(){return this._def.values}};jo.create=(t,e)=>new jo({values:t,typeName:P.ZodNativeEnum,...se(e)});Cn=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return N(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 Rt(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,...se(e)});ur=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=>{N(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"?$o(c.value):r.value==="dirty"?$o(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"?$o(a.value):r.value==="dirty"?$o(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);ye.assertNever(o)}};ur.create=(t,e,r)=>new ur({schema:t,typeName:P.ZodEffects,effect:e,...se(r)});ur.createWithPreprocess=(t,e,r)=>new ur({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...se(r)});Bt=class extends ue{_parse(e){return this._getType(e)===z.undefined?Rt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Bt.create=(t,e)=>new Bt({innerType:t,typeName:P.ZodOptional,...se(e)});Ur=class extends ue{_parse(e){return this._getType(e)===z.null?Rt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ur.create=(t,e)=>new Ur({innerType:t,typeName:P.ZodNullable,...se(e)});Mo=class extends ue{_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}};Mo.create=(t,e)=>new Mo({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});Lo=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 Ns(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Ht(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ht(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Lo.create=(t,e)=>new Lo({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});qs=class extends ue{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};qs.create=t=>new qs({typeName:P.ZodNaN,...se(t)});B2=Symbol("zod_brand"),ua=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}},pa=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(),$o(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})}},Do=class extends ue{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Pn(o)&&(o.value=Object.freeze(o.value)),o);return Ns(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Do.create=(t,e)=>new Do({innerType:t,typeName:P.ZodReadonly,...se(e)});G2={object:Gt.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={}));V2=(t,e={message:`Input not instance of ${t.name}`})=>P$(r=>r instanceof t,e),R$=Rn.create,O$=ko.create,W2=qs.create,J2=Eo.create,C$=To.create,K2=Po.create,Y2=js.create,X2=Ro.create,Q2=Oo.create,eq=On.create,tq=on.create,rq=kr.create,nq=Ms.create,oq=sn.create,og=Gt.create,sq=Gt.strictCreate,iq=Co.create,aq=Bl.create,cq=Io.create,lq=Zr.create,uq=Gl.create,pq=Ls.create,dq=Ds.create,fq=Vl.create,mq=Ao.create,hq=No.create,gq=zo.create,yq=jo.create,vq=Cn.create,_q=ur.create,bq=Bt.create,wq=Ur.create,xq=ur.createWithPreprocess,Sq=pa.create,$q=()=>R$().optional(),kq=()=>O$().optional(),Eq=()=>C$().optional(),Tq={string:t=>Rn.create({...t,coerce:!0}),number:t=>ko.create({...t,coerce:!0}),boolean:t=>To.create({...t,coerce:!0}),bigint:t=>Eo.create({...t,coerce:!0}),date:t=>Po.create({...t,coerce:!0})},Pq=J});var L={};V(L,{BRAND:()=>B2,DIRTY:()=>$o,EMPTY_PATH:()=>S2,INVALID:()=>J,NEVER:()=>Pq,OK:()=>Rt,ParseStatus:()=>xt,Schema:()=>ue,ZodAny:()=>On,ZodArray:()=>sn,ZodBigInt:()=>Eo,ZodBoolean:()=>To,ZodBranded:()=>ua,ZodCatch:()=>Lo,ZodDate:()=>Po,ZodDefault:()=>Mo,ZodDiscriminatedUnion:()=>Bl,ZodEffects:()=>ur,ZodEnum:()=>zo,ZodError:()=>Ht,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Vl,ZodIntersection:()=>Io,ZodIssueCode:()=>T,ZodLazy:()=>Ao,ZodLiteral:()=>No,ZodMap:()=>Ls,ZodNaN:()=>qs,ZodNativeEnum:()=>jo,ZodNever:()=>kr,ZodNull:()=>Oo,ZodNullable:()=>Ur,ZodNumber:()=>ko,ZodObject:()=>Gt,ZodOptional:()=>Bt,ZodParsedType:()=>z,ZodPipeline:()=>pa,ZodPromise:()=>Cn,ZodReadonly:()=>Do,ZodRecord:()=>Gl,ZodSchema:()=>ue,ZodSet:()=>Ds,ZodString:()=>Rn,ZodSymbol:()=>js,ZodTransformer:()=>ur,ZodTuple:()=>Zr,ZodType:()=>ue,ZodUndefined:()=>Ro,ZodUnion:()=>Co,ZodUnknown:()=>on,ZodVoid:()=>Ms,addIssueToContext:()=>N,any:()=>eq,array:()=>oq,bigint:()=>J2,boolean:()=>C$,coerce:()=>Tq,custom:()=>P$,date:()=>K2,datetimeRegex:()=>E$,defaultErrorMap:()=>rn,discriminatedUnion:()=>aq,effect:()=>_q,enum:()=>gq,function:()=>fq,getErrorMap:()=>As,getParsedType:()=>qr,instanceof:()=>V2,intersection:()=>cq,isAborted:()=>Fl,isAsync:()=>Ns,isDirty:()=>Hl,isValid:()=>Pn,late:()=>G2,lazy:()=>mq,literal:()=>hq,makeIssue:()=>la,map:()=>pq,nan:()=>W2,nativeEnum:()=>yq,never:()=>rq,null:()=>Q2,nullable:()=>wq,number:()=>O$,object:()=>og,objectUtil:()=>Qh,oboolean:()=>Eq,onumber:()=>kq,optional:()=>bq,ostring:()=>$q,pipeline:()=>Sq,preprocess:()=>xq,promise:()=>vq,quotelessJson:()=>b2,record:()=>uq,set:()=>dq,setErrorMap:()=>x2,strictObject:()=>sq,string:()=>R$,symbol:()=>Y2,transformer:()=>_q,tuple:()=>lq,undefined:()=>X2,union:()=>iq,unknown:()=>tq,util:()=>ye,void:()=>nq});var Wl=w(()=>{Ul();tg();b$();ca();I$();Zl()});var da=w(()=>{Wl()});var sg=w(()=>{zt()});function ig(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new Iq(r)}var Cq,Iq,A$=w(()=>{zt();zt();sg();Cq=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)=>Rf(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>vo(t,r,n),t.parseAsync=async(r,n)=>Cf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>_o(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)=>rr(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)}),Iq=E("ZodMiniObject",(t,e)=>{Qc.init(t,e),Cq.init(t,e),be.defineLazy(t,"shape",()=>e.shape)})});var N$=w(()=>{});var z$=w(()=>{});var j$=w(()=>{});var M$=w(()=>{zt();sg();A$();N$();zt();tl();z$();j$()});var L$=w(()=>{M$()});var ag=w(()=>{L$()});function pr(t){return!!t._zod}function qo(t){let e=Object.values(t);if(e.length===0)return ig({});let r=e.every(pr),n=e.every(o=>!pr(o));if(r)return ig(t);if(n)return og(t);throw new Error("Mixed Zod versions detected in object shape.")}function In(t,e){return pr(t)?vo(t,e):t.safeParse(e)}async function Jl(t,e){return pr(t)?await _o(t,e):await t.safeParseAsync(e)}function An(t){if(!t)return;let e;if(pr(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 qo(t)}}if(pr(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 Kl(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 q$(t){return t.description}function Z$(t){if(pr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Yl(t){if(pr(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 fa=w(()=>{da();ag()});function Nn(t){return t==="completed"||t==="failed"||t==="cancelled"}var U$=w(()=>{});var H$,F$,B$,Xl=w(()=>{H$=Symbol("Let zodToJsonSchema decide on which parser to use"),F$={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"},B$=t=>typeof t=="string"?{...F$,name:t}:{...F$,...t}});var G$,cg=w(()=>{Xl();G$=t=>{let e=B$(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 lg(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,lg(t,e,n,o)}var zn=w(()=>{});var Ql,eu=w(()=>{Ql=(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 Ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Ql(e,t.currentPath):e.join("/")}}var dr=w(()=>{eu()});function V$(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&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var ug=w(()=>{da();zn();at()});function W$(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?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var pg=w(()=>{zn()});function J$(){return{type:"boolean"}}var dg=w(()=>{});function tu(t,e){return Y(t.type._def,e)}var ru=w(()=>{at()});var K$,fg=w(()=>{at();K$=(t,e)=>Y(t.innerType._def,e)});function mg(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>mg(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 zq(t,e)}}var zq,hg=w(()=>{zn();zq=(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":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function Y$(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var gg=w(()=>{at()});function X$(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Ke(e)}var yg=w(()=>{at();dr()});function Q$(t){return{type:"string",enum:Array.from(t.values)}}var vg=w(()=>{});function ek(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(jq(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 jq,_g=w(()=>{at();jq=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function tk(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 bg=w(()=>{});function nu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(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":Tr(r,"email",n.message,e);break;case"format:idn-email":Tr(r,"idn-email",n.message,e);break;case"pattern:zod":Mt(r,Er.email,n.message,e);break}break;case"url":Tr(r,"uri",n.message,e);break;case"uuid":Tr(r,"uuid",n.message,e);break;case"regex":Mt(r,n.regex,n.message,e);break;case"cuid":Mt(r,Er.cuid,n.message,e);break;case"cuid2":Mt(r,Er.cuid2,n.message,e);break;case"startsWith":Mt(r,RegExp(`^${xg(n.value,e)}`),n.message,e);break;case"endsWith":Mt(r,RegExp(`${xg(n.value,e)}$`),n.message,e);break;case"datetime":Tr(r,"date-time",n.message,e);break;case"date":Tr(r,"date",n.message,e);break;case"time":Tr(r,"time",n.message,e);break;case"duration":Tr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Mt(r,RegExp(xg(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Tr(r,"ipv4",n.message,e),n.version!=="v4"&&Tr(r,"ipv6",n.message,e);break}case"base64url":Mt(r,Er.base64url,n.message,e);break;case"jwt":Mt(r,Er.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Mt(r,Er.ipv4Cidr,n.message,e),n.version!=="v4"&&Mt(r,Er.ipv6Cidr,n.message,e);break}case"emoji":Mt(r,Er.emoji(),n.message,e);break;case"ulid":{Mt(r,Er.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Tr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Mt(r,Er.base64,n.message,e);break}}break}case"nanoid":Mt(r,Er.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function xg(t,e){return e.patternStrategy==="escape"?Lq(t):t}function Lq(t){let e="";for(let r=0;r<t.length;r++)Mq.has(t[r])||(e+="\\"),e+=t[r];return e}function Tr(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}}})):xe(t,"format",e,r,n)}function Mt(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:rk(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",rk(e,n),r,n)}function rk(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
+ `,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=>Yi.parse(v)):a=[Yi.parse(i)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=a.some(Ph);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(Pn)){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=>Ph(v)),f=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??RS;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(u,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(u)}});for(let b of a)Pn(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)}}),y={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};this.sessionId!==void 0&&(y["mcp-session-id"]=this.sessionId);for(let v of a)Pn(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;Pn(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:y})}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&&!Ji.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Ji.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((on(e)||$s(e))&&(n=e.id),n===void 0){if(on(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(on(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 Ll,i$=w(()=>{o$();s$();Ll=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Ml(e),this._requestListener=Hh(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 Hh(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 ye,Bh,z,Fr,aa=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})(ye||(ye={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Bh||(Bh={}));z=ye.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Fr=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,r2,Gt,Dl=w(()=>{aa();T=ye.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"]),r2=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),Gt=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,ye.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()}};Gt.create=t=>new Gt(t)});var n2,sn,Gh=w(()=>{Dl();aa();n2=(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,ye.jsonStringifyReplacer)}`;break;case T.unrecognized_keys:r=`Unrecognized key(s) in object: ${ye.joinValues(t.keys,", ")}`;break;case T.invalid_union:r="Invalid input";break;case T.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ye.joinValues(t.options)}`;break;case T.invalid_enum_value:r=`Invalid enum value. Expected ${ye.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}"`:ye.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,ye.assertNever(t)}return{message:r}},sn=n2});function o2(t){a$=t}function Is(){return a$}var a$,ql=w(()=>{Gh();a$=sn});function N(t,e){let r=Is(),n=ca({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===sn?void 0:sn].filter(o=>!!o)});t.common.issues.push(n)}var ca,s2,St,J,$o,Ot,Zl,Ul,Rn,As,Vh=w(()=>{ql();Gh();ca=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}},s2=[];St=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"}),$o=t=>({status:"dirty",value:t}),Ot=t=>({status:"valid",value:t}),Zl=t=>t.status==="aborted",Ul=t=>t.status==="dirty",Rn=t=>t.status==="valid",As=t=>typeof Promise<"u"&&t instanceof Promise});var c$=w(()=>{});var D,l$=w(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(D||(D={}))});function se(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 f$(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 x2(t){return new RegExp(`^${f$(t)}$`)}function m$(t){let e=`${d$}T${f$(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 S2(t,e){return!!((e==="v4"||!e)&&h2.test(t)||(e==="v6"||!e)&&y2.test(t))}function $2(t,e){if(!p2.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 k2(t,e){return!!((e==="v4"||!e)&&g2.test(t)||(e==="v6"||!e)&&v2.test(t))}function E2(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 Ns(t){if(t instanceof Wt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Vt.create(Ns(n))}return new Wt({...t._def,shape:()=>e})}else return t instanceof ln?new ln({...t._def,type:Ns(t.element)}):t instanceof Vt?Vt.create(Ns(t.unwrap())):t instanceof Br?Br.create(Ns(t.unwrap())):t instanceof Hr?Hr.create(t.items.map(e=>Ns(e))):t}function Jh(t,e){let r=Fr(t),n=Fr(e);if(t===e)return{valid:!0,data:t};if(r===z.object&&n===z.object){let o=ye.objectKeys(e),s=ye.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Jh(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=Jh(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 h$(t,e){return new zo({values:t,typeName:P.ZodEnum,...se(e)})}function p$(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function g$(t,e={},r){return t?Cn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=p$(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=p$(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Cn.create()}var pr,u$,ue,i2,a2,c2,l2,u2,p2,d2,f2,m2,Wh,h2,g2,y2,v2,_2,b2,d$,w2,On,ko,Eo,To,Po,zs,Ro,Oo,Cn,cn,Tr,js,ln,Wt,Co,an,Fl,Io,Hr,Hl,Ms,Ls,Bl,Ao,No,zo,jo,In,dr,Vt,Br,Mo,Lo,Ds,T2,la,ua,Do,P2,P,R2,y$,v$,O2,C2,_$,I2,A2,N2,z2,j2,M2,L2,D2,q2,Kh,Z2,U2,F2,H2,B2,G2,V2,W2,J2,K2,Y2,X2,Q2,eq,tq,rq,nq,oq,sq,iq,aq,cq,lq,uq,b$=w(()=>{Dl();ql();l$();Vh();aa();pr=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}},u$=(t,e)=>{if(Rn(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 Gt(t.common.issues);return this._error=r,this._error}}};ue=class{get description(){return this._def.description}_getType(e){return Fr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:Fr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new St,ctx:{common:e.parent.common,data:e.data,parsedType:Fr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(As(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:Fr(e)},o=this._parseSync({data:e,path:n.path,parent:n});return u$(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Fr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Rn(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=>Rn(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:Fr(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(As(o)?o:Promise.resolve(o));return u$(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 dr({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 Vt.create(this,this._def)}nullable(){return Br.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ln.create(this)}promise(){return In.create(this,this._def)}or(e){return Co.create([this,e],this._def)}and(e){return Io.create(this,e,this._def)}transform(e){return new dr({...se(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Mo({...se(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new la({typeName:P.ZodBranded,type:this,...se(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Lo({...se(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 ua.create(this,e)}readonly(){return Do.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},i2=/^c[^\s-]{8,}$/i,a2=/^[0-9a-z]+$/,c2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,l2=/^[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,u2=/^[a-z0-9_-]{21}$/i,p2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,d2=/^[-+]?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)?)??$/,f2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,m2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",h2=/^(?:(?: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])$/,g2=/^(?:(?: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])$/,y2=/^(([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]))$/,v2=/^(([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])$/,_2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,b2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,d$="((\\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])))",w2=new RegExp(`^${d$}$`);On=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_type,expected:z.string,received:s.parsedType}),J}let n=new St,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),N(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),N(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?N(o,{code:T.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&N(o,{code:T.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")f2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"email",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Wh||(Wh=new RegExp(m2,"u")),Wh.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"emoji",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")l2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"uuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")u2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"nanoid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")i2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")a2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cuid2",code:T.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")c2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(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),N(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),N(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),N(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),N(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),N(o,{code:T.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?m$(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?w2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?x2(s).test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?d2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"duration",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?S2(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"ip",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?$2(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"jwt",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?k2(e.data,s.version)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"cidr",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?_2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?b2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64url",code:T.invalid_string,message:s.message}),n.dirty()):ye.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,...D.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...D.errToObj(e)})}url(e){return this._addCheck({kind:"url",...D.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...D.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...D.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...D.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...D.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...D.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...D.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...D.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...D.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...D.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...D.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...D.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,...D.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,...D.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...D.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...D.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...D.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...D.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...D.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...D.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...D.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...D.errToObj(r)})}nonempty(e){return this.min(1,D.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}};On.create=t=>new On({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...se(t)});ko=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)!==z.number){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_type,expected:z.number,received:s.parsedType}),J}let n,o=new St;for(let s of this._def.checks)s.kind==="int"?ye.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),N(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),N(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),N(n,{code:T.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?E2(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),N(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),N(n,{code:T.not_finite,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,D.toString(r))}gt(e,r){return this.setLimit("min",e,!1,D.toString(r))}lte(e,r){return this.setLimit("max",e,!0,D.toString(r))}lt(e,r){return this.setLimit("max",e,!1,D.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:D.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:D.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:D.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:D.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:D.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:D.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:D.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"&&ye.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)}};ko.create=t=>new ko({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...se(t)});Eo=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)!==z.bigint)return this._getInvalidInput(e);let n,o=new St;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),N(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),N(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),N(n,{code:T.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ye.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:T.invalid_type,expected:z.bigint,received:r.parsedType}),J}gte(e,r){return this.setLimit("min",e,!0,D.toString(r))}gt(e,r){return this.setLimit("min",e,!1,D.toString(r))}lte(e,r){return this.setLimit("max",e,!0,D.toString(r))}lt(e,r){return this.setLimit("max",e,!1,D.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:D.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:D.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:D.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:D.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:D.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:D.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}};Eo.create=t=>new Eo({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...se(t)});To=class extends ue{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.boolean,received:n.parsedType}),J}return Ot(e.data)}};To.create=t=>new To({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...se(t)});Po=class t extends ue{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_type,expected:z.date,received:s.parsedType}),J}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return N(s,{code:T.invalid_date}),J}let n=new St,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),N(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),N(o,{code:T.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ye.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:D.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:D.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}};Po.create=t=>new Po({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...se(t)});zs=class extends ue{_parse(e){if(this._getType(e)!==z.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.symbol,received:n.parsedType}),J}return Ot(e.data)}};zs.create=t=>new zs({typeName:P.ZodSymbol,...se(t)});Ro=class extends ue{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.undefined,received:n.parsedType}),J}return Ot(e.data)}};Ro.create=t=>new Ro({typeName:P.ZodUndefined,...se(t)});Oo=class extends ue{_parse(e){if(this._getType(e)!==z.null){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.null,received:n.parsedType}),J}return Ot(e.data)}};Oo.create=t=>new Oo({typeName:P.ZodNull,...se(t)});Cn=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return Ot(e.data)}};Cn.create=t=>new Cn({typeName:P.ZodAny,...se(t)});cn=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ot(e.data)}};cn.create=t=>new cn({typeName:P.ZodUnknown,...se(t)});Tr=class extends ue{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:T.invalid_type,expected:z.never,received:r.parsedType}),J}};Tr.create=t=>new Tr({typeName:P.ZodNever,...se(t)});js=class extends ue{_parse(e){if(this._getType(e)!==z.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.void,received:n.parsedType}),J}return Ot(e.data)}};js.create=t=>new js({typeName:P.ZodVoid,...se(t)});ln=class t extends ue{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==z.array)return N(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)&&(N(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&&(N(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&&(N(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 pr(r,i,r.path,a)))).then(i=>St.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new pr(r,i,r.path,a)));return St.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:D.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:D.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:D.toString(r)}})}nonempty(e){return this.min(1,e)}};ln.create=(t,e)=>new ln({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...se(e)});Wt=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=ye.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 N(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 Tr&&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 pr(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Tr){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&&(N(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 pr(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=>St.mergeObjectSync(n,l)):St.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return D.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:D.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 ye.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 ye.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Ns(this)}partial(e){let r={};for(let n of ye.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 ye.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof Vt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return h$(ye.objectKeys(this.shape))}};Wt.create=(t,e)=>new Wt({shape:()=>t,unknownKeys:"strip",catchall:Tr.create(),typeName:P.ZodObject,...se(e)});Wt.strictCreate=(t,e)=>new Wt({shape:()=>t,unknownKeys:"strict",catchall:Tr.create(),typeName:P.ZodObject,...se(e)});Wt.lazycreate=(t,e)=>new Wt({shape:t,unknownKeys:"strip",catchall:Tr.create(),typeName:P.ZodObject,...se(e)});Co=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 Gt(a.ctx.common.issues));return N(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 Gt(c));return N(r,{code:T.invalid_union,unionErrors:a}),J}}get options(){return this._def.options}};Co.create=(t,e)=>new Co({options:t,typeName:P.ZodUnion,...se(e)});an=t=>t instanceof Ao?an(t.schema):t instanceof dr?an(t.innerType()):t instanceof No?[t.value]:t instanceof zo?t.options:t instanceof jo?ye.objectValues(t.enum):t instanceof Mo?an(t._def.innerType):t instanceof Ro?[void 0]:t instanceof Oo?[null]:t instanceof Vt?[void 0,...an(t.unwrap())]:t instanceof Br?[null,...an(t.unwrap())]:t instanceof la||t instanceof Do?an(t.unwrap()):t instanceof Lo?an(t._def.innerType):[],Fl=class t extends ue{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return N(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}):(N(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=an(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,...se(n)})}};Io=class extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Zl(s)||Zl(i))return J;let a=Jh(s.value,i.value);return a.valid?((Ul(s)||Ul(i))&&r.dirty(),{status:r.value,value:a.data}):(N(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}))}};Io.create=(t,e,r)=>new Io({left:t,right:e,typeName:P.ZodIntersection,...se(r)});Hr=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.array)return N(n,{code:T.invalid_type,expected:z.array,received:n.parsedType}),J;if(n.data.length<this._def.items.length)return N(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&&(N(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 pr(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>St.mergeArray(r,i)):St.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Hr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Hr({items:t,typeName:P.ZodTuple,rest:null,...se(e)})};Hl=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!==z.object)return N(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 pr(n,a,n.path,a)),value:i._parse(new pr(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?St.mergeObjectAsync(r,o):St.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,...se(n)}):new t({keyType:On.create(),valueType:e,typeName:P.ZodRecord,...se(r)})}},Ms=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!==z.map)return N(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 pr(n,a,n.path,[l,"key"])),value:s._parse(new pr(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}}}};Ms.create=(t,e,r)=>new Ms({valueType:e,keyType:t,typeName:P.ZodMap,...se(r)});Ls=class t extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==z.set)return N(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&&(N(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&&(N(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 pr(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:D.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:D.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Ls.create=(t,e)=>new Ls({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...se(e)});Bl=class t extends ue{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.function)return N(r,{code:T.invalid_type,expected:z.function,received:r.parsedType}),J;function n(a,c){return ca({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Is(),sn].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function o(a,c){return ca({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Is(),sn].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 In){let a=this;return Ot(async function(...c){let l=new Gt([]),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 Ot(function(...c){let l=a._def.args.safeParse(c,s);if(!l.success)throw new Gt([n(c,l.error)]);let u=Reflect.apply(i,this,l.data),p=a._def.returns.safeParse(u,s);if(!p.success)throw new Gt([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:Hr.create(e).rest(cn.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||Hr.create([]).rest(cn.create()),returns:r||cn.create(),typeName:P.ZodFunction,...se(n)})}},Ao=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})}};Ao.create=(t,e)=>new Ao({getter:t,typeName:P.ZodLazy,...se(e)});No=class extends ue{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return N(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}};No.create=(t,e)=>new No({value:t,typeName:P.ZodLiteral,...se(e)});zo=class t extends ue{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ye.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 N(r,{received:r.data,code:T.invalid_enum_value,options:n}),J}return Ot(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})}};zo.create=h$;jo=class extends ue{_parse(e){let r=ye.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==z.string&&n.parsedType!==z.number){let o=ye.objectValues(r);return N(n,{expected:ye.joinValues(o),received:n.parsedType,code:T.invalid_type}),J}if(this._cache||(this._cache=new Set(ye.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ye.objectValues(r);return N(n,{received:n.data,code:T.invalid_enum_value,options:o}),J}return Ot(e.data)}get enum(){return this._def.values}};jo.create=(t,e)=>new jo({values:t,typeName:P.ZodNativeEnum,...se(e)});In=class extends ue{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==z.promise&&r.common.async===!1)return N(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 Ot(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};In.create=(t,e)=>new In({type:t,typeName:P.ZodPromise,...se(e)});dr=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=>{N(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"?$o(c.value):r.value==="dirty"?$o(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"?$o(a.value):r.value==="dirty"?$o(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(!Rn(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=>Rn(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):J);ye.assertNever(o)}};dr.create=(t,e,r)=>new dr({schema:t,typeName:P.ZodEffects,effect:e,...se(r)});dr.createWithPreprocess=(t,e,r)=>new dr({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...se(r)});Vt=class extends ue{_parse(e){return this._getType(e)===z.undefined?Ot(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vt.create=(t,e)=>new Vt({innerType:t,typeName:P.ZodOptional,...se(e)});Br=class extends ue{_parse(e){return this._getType(e)===z.null?Ot(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:P.ZodNullable,...se(e)});Mo=class extends ue{_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}};Mo.create=(t,e)=>new Mo({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});Lo=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 As(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Gt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Gt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Lo.create=(t,e)=>new Lo({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});Ds=class extends ue{_parse(e){if(this._getType(e)!==z.nan){let n=this._getOrReturnCtx(e);return N(n,{code:T.invalid_type,expected:z.nan,received:n.parsedType}),J}return{status:"valid",value:e.data}}};Ds.create=t=>new Ds({typeName:P.ZodNaN,...se(t)});T2=Symbol("zod_brand"),la=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}},ua=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(),$o(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})}},Do=class extends ue{_parse(e){let r=this._def.innerType._parse(e),n=o=>(Rn(o)&&(o.value=Object.freeze(o.value)),o);return As(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Do.create=(t,e)=>new Do({innerType:t,typeName:P.ZodReadonly,...se(e)});P2={object:Wt.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={}));R2=(t,e={message:`Input not instance of ${t.name}`})=>g$(r=>r instanceof t,e),y$=On.create,v$=ko.create,O2=Ds.create,C2=Eo.create,_$=To.create,I2=Po.create,A2=zs.create,N2=Ro.create,z2=Oo.create,j2=Cn.create,M2=cn.create,L2=Tr.create,D2=js.create,q2=ln.create,Kh=Wt.create,Z2=Wt.strictCreate,U2=Co.create,F2=Fl.create,H2=Io.create,B2=Hr.create,G2=Hl.create,V2=Ms.create,W2=Ls.create,J2=Bl.create,K2=Ao.create,Y2=No.create,X2=zo.create,Q2=jo.create,eq=In.create,tq=dr.create,rq=Vt.create,nq=Br.create,oq=dr.createWithPreprocess,sq=ua.create,iq=()=>y$().optional(),aq=()=>v$().optional(),cq=()=>_$().optional(),lq={string:t=>On.create({...t,coerce:!0}),number:t=>ko.create({...t,coerce:!0}),boolean:t=>To.create({...t,coerce:!0}),bigint:t=>Eo.create({...t,coerce:!0}),date:t=>Po.create({...t,coerce:!0})},uq=J});var L={};V(L,{BRAND:()=>T2,DIRTY:()=>$o,EMPTY_PATH:()=>s2,INVALID:()=>J,NEVER:()=>uq,OK:()=>Ot,ParseStatus:()=>St,Schema:()=>ue,ZodAny:()=>Cn,ZodArray:()=>ln,ZodBigInt:()=>Eo,ZodBoolean:()=>To,ZodBranded:()=>la,ZodCatch:()=>Lo,ZodDate:()=>Po,ZodDefault:()=>Mo,ZodDiscriminatedUnion:()=>Fl,ZodEffects:()=>dr,ZodEnum:()=>zo,ZodError:()=>Gt,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Bl,ZodIntersection:()=>Io,ZodIssueCode:()=>T,ZodLazy:()=>Ao,ZodLiteral:()=>No,ZodMap:()=>Ms,ZodNaN:()=>Ds,ZodNativeEnum:()=>jo,ZodNever:()=>Tr,ZodNull:()=>Oo,ZodNullable:()=>Br,ZodNumber:()=>ko,ZodObject:()=>Wt,ZodOptional:()=>Vt,ZodParsedType:()=>z,ZodPipeline:()=>ua,ZodPromise:()=>In,ZodReadonly:()=>Do,ZodRecord:()=>Hl,ZodSchema:()=>ue,ZodSet:()=>Ls,ZodString:()=>On,ZodSymbol:()=>zs,ZodTransformer:()=>dr,ZodTuple:()=>Hr,ZodType:()=>ue,ZodUndefined:()=>Ro,ZodUnion:()=>Co,ZodUnknown:()=>cn,ZodVoid:()=>js,addIssueToContext:()=>N,any:()=>j2,array:()=>q2,bigint:()=>C2,boolean:()=>_$,coerce:()=>lq,custom:()=>g$,date:()=>I2,datetimeRegex:()=>m$,defaultErrorMap:()=>sn,discriminatedUnion:()=>F2,effect:()=>tq,enum:()=>X2,function:()=>J2,getErrorMap:()=>Is,getParsedType:()=>Fr,instanceof:()=>R2,intersection:()=>H2,isAborted:()=>Zl,isAsync:()=>As,isDirty:()=>Ul,isValid:()=>Rn,late:()=>P2,lazy:()=>K2,literal:()=>Y2,makeIssue:()=>ca,map:()=>V2,nan:()=>O2,nativeEnum:()=>Q2,never:()=>L2,null:()=>z2,nullable:()=>nq,number:()=>v$,object:()=>Kh,objectUtil:()=>Bh,oboolean:()=>cq,onumber:()=>aq,optional:()=>rq,ostring:()=>iq,pipeline:()=>sq,preprocess:()=>oq,promise:()=>eq,quotelessJson:()=>r2,record:()=>G2,set:()=>W2,setErrorMap:()=>o2,strictObject:()=>Z2,string:()=>y$,symbol:()=>A2,transformer:()=>tq,tuple:()=>B2,undefined:()=>N2,union:()=>U2,unknown:()=>M2,util:()=>ye,void:()=>D2});var Gl=w(()=>{ql();Vh();c$();aa();b$();Dl()});var pa=w(()=>{Gl()});var Yh=w(()=>{Mt()});function Xh(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new mq(r)}var fq,mq,w$=w(()=>{Mt();Mt();Yh();fq=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)=>wf(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>vo(t,r,n),t.parseAsync=async(r,n)=>Sf(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>_o(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)=>or(t,r,n),t.brand=()=>t,t.register=(r,n)=>(r.add(t,n),t)}),mq=E("ZodMiniObject",(t,e)=>{Yc.init(t,e),fq.init(t,e),be.defineLazy(t,"shape",()=>e.shape)})});var x$=w(()=>{});var S$=w(()=>{});var $$=w(()=>{});var k$=w(()=>{Mt();Yh();w$();x$();Mt();Qc();S$();$$()});var E$=w(()=>{k$()});var Qh=w(()=>{E$()});function fr(t){return!!t._zod}function qo(t){let e=Object.values(t);if(e.length===0)return Xh({});let r=e.every(fr),n=e.every(o=>!fr(o));if(r)return Xh(t);if(n)return Kh(t);throw new Error("Mixed Zod versions detected in object shape.")}function An(t,e){return fr(t)?vo(t,e):t.safeParse(e)}async function Vl(t,e){return fr(t)?await _o(t,e):await t.safeParseAsync(e)}function Nn(t){if(!t)return;let e;if(fr(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function qs(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 qo(t)}}if(fr(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 Wl(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 P$(t){return t.description}function R$(t){if(fr(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Jl(t){if(fr(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 da=w(()=>{pa();Qh()});function zn(t){return t==="completed"||t==="failed"||t==="cancelled"}var O$=w(()=>{});var I$,C$,A$,Kl=w(()=>{I$=Symbol("Let zodToJsonSchema decide on which parser to use"),C$={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"},A$=t=>typeof t=="string"?{...C$,name:t}:{...C$,...t}});var N$,eg=w(()=>{Kl();N$=t=>{let e=A$(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 tg(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,tg(t,e,n,o)}var jn=w(()=>{});var Yl,Xl=w(()=>{Yl=(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 Ke(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Yl(e,t.currentPath):e.join("/")}}var mr=w(()=>{Xl()});function z$(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&&xe(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&xe(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(xe(r,"minItems",t.exactLength.value,t.exactLength.message,e),xe(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var rg=w(()=>{pa();jn();at()});function j$(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?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var ng=w(()=>{jn()});function M$(){return{type:"boolean"}}var og=w(()=>{});function Ql(t,e){return Y(t.type._def,e)}var eu=w(()=>{at()});var L$,sg=w(()=>{at();L$=(t,e)=>Y(t.innerType._def,e)});function ig(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ig(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 yq(t,e)}}var yq,ag=w(()=>{jn();yq=(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":xe(r,"minimum",n.value,n.message,e);break;case"max":xe(r,"maximum",n.value,n.message,e);break}return r}});function D$(t,e){return{...Y(t.innerType._def,e),default:t.defaultValue()}}var cg=w(()=>{at()});function q$(t,e){return e.effectStrategy==="input"?Y(t.schema._def,e):Ke(e)}var lg=w(()=>{at();mr()});function Z$(t){return{type:"string",enum:Array.from(t.values)}}var ug=w(()=>{});function U$(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(vq(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 vq,pg=w(()=>{at();vq=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function F$(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 dg=w(()=>{});function tu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":xe(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":Rr(r,"email",n.message,e);break;case"format:idn-email":Rr(r,"idn-email",n.message,e);break;case"pattern:zod":Dt(r,Pr.email,n.message,e);break}break;case"url":Rr(r,"uri",n.message,e);break;case"uuid":Rr(r,"uuid",n.message,e);break;case"regex":Dt(r,n.regex,n.message,e);break;case"cuid":Dt(r,Pr.cuid,n.message,e);break;case"cuid2":Dt(r,Pr.cuid2,n.message,e);break;case"startsWith":Dt(r,RegExp(`^${mg(n.value,e)}`),n.message,e);break;case"endsWith":Dt(r,RegExp(`${mg(n.value,e)}$`),n.message,e);break;case"datetime":Rr(r,"date-time",n.message,e);break;case"date":Rr(r,"date",n.message,e);break;case"time":Rr(r,"time",n.message,e);break;case"duration":Rr(r,"duration",n.message,e);break;case"length":xe(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),xe(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{Dt(r,RegExp(mg(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Rr(r,"ipv4",n.message,e),n.version!=="v4"&&Rr(r,"ipv6",n.message,e);break}case"base64url":Dt(r,Pr.base64url,n.message,e);break;case"jwt":Dt(r,Pr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&Dt(r,Pr.ipv4Cidr,n.message,e),n.version!=="v4"&&Dt(r,Pr.ipv6Cidr,n.message,e);break}case"emoji":Dt(r,Pr.emoji(),n.message,e);break;case"ulid":{Dt(r,Pr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Rr(r,"binary",n.message,e);break}case"contentEncoding:base64":{xe(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{Dt(r,Pr.base64,n.message,e);break}}break}case"nanoid":Dt(r,Pr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function mg(t,e){return e.patternStrategy==="escape"?bq(t):t}function bq(t){let e="";for(let r=0;r<t.length;r++)_q.has(t[r])||(e+="\\"),e+=t[r];return e}function Rr(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}}})):xe(t,"format",e,r,n)}function Dt(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:H$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",H$(e,n),r,n)}function H$(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
286
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
286
287
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
287
288
  `:`[${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 wg,Er,Mq,ou=w(()=>{zn();Er={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:()=>(wg===void 0&&(wg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),wg),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-_]*$/};Mq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function su(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]})??Ke(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}=nu(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}=tu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var iu=w(()=>{da();at();ou();ru();dr()});function nk(t,e){if(e.mapStrategy==="record")return su(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ke(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Sg=w(()=>{at();iu();dr()});function ok(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 $g=w(()=>{});function sk(t){return t.target==="openAi"?void 0:{not:Ke({...t,currentPath:[...t.currentPath,"not"]})}}var kg=w(()=>{dr()});function ik(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Eg=w(()=>{});function ck(t,e){if(e.target==="openApi3")return ak(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ma&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ma[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 ak(t,e)}var ma,ak,au=w(()=>{at();ma={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};ak=(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 lk(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:ma[t.innerType._def.typeName],nullable:!0}:{type:[ma[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 Tg=w(()=>{at();au()});function uk(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",lg(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var Pg=w(()=>{zn()});function pk(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=qq(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=Dq(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Dq(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 qq(t){try{return t.isOptional()}catch{return!0}}var Rg=w(()=>{at()});var dk,Og=w(()=>{at();dr();dk=(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:Ke(e)},r]}:Ke(e)}});var fk,Cg=w(()=>{at();fk=(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 mk(t,e){return Y(t.type._def,e)}var Ig=w(()=>{at()});function hk(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Ag=w(()=>{zn();at()});function gk(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 Ng=w(()=>{at()});function yk(t){return{not:Ke(t)}}var zg=w(()=>{dr()});function vk(t){return Ke(t)}var jg=w(()=>{dr()});var _k,Mg=w(()=>{at();_k=(t,e)=>Y(t.innerType._def,e)});var bk,Lg=w(()=>{da();dr();ug();pg();dg();ru();fg();hg();gg();yg();vg();_g();bg();Sg();$g();kg();Eg();Tg();Pg();Rg();Og();Cg();Ig();iu();Ag();ou();Ng();zg();au();jg();Mg();bk=(t,e,r)=>{switch(e){case P.ZodString:return nu(t,r);case P.ZodNumber:return uk(t,r);case P.ZodObject:return pk(t,r);case P.ZodBigInt:return W$(t,r);case P.ZodBoolean:return J$();case P.ZodDate:return mg(t,r);case P.ZodUndefined:return yk(r);case P.ZodNull:return ik(r);case P.ZodArray:return V$(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return ck(t,r);case P.ZodIntersection:return ek(t,r);case P.ZodTuple:return gk(t,r);case P.ZodRecord:return su(t,r);case P.ZodLiteral:return tk(t,r);case P.ZodEnum:return Q$(t);case P.ZodNativeEnum:return ok(t);case P.ZodNullable:return lk(t,r);case P.ZodOptional:return dk(t,r);case P.ZodMap:return nk(t,r);case P.ZodSet:return hk(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return mk(t,r);case P.ZodNaN:case P.ZodNever:return sk(r);case P.ZodEffects:return X$(t,r);case P.ZodAny:return Ke(r);case P.ZodUnknown:return vk(r);case P.ZodDefault:return Y$(t,r);case P.ZodBranded:return tu(t,r);case P.ZodReadonly:return _k(t,r);case P.ZodCatch:return K$(t,r);case P.ZodPipeline:return fk(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!==H$)return a}if(n&&!r){let a=Zq(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=bk(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&Uq(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Zq,Uq,at=w(()=>{Xl();Lg();eu();dr();Zq=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Ql(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`),Ke(e)):e.$refStrategy==="seen"?Ke(e):void 0}},Uq=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var wk=w(()=>{});var Dg,qg=w(()=>{at();cg();dr();Dg=(t,e)=>{let r=G$(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)??Ke(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)??Ke(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 xk=w(()=>{Xl();cg();zn();eu();at();wk();dr();ug();pg();dg();ru();fg();hg();gg();yg();vg();_g();bg();Sg();$g();kg();Eg();Tg();Pg();Rg();Og();Cg();Ig();Mg();iu();Ag();ou();Ng();zg();au();jg();Lg();qg();qg()});function Fq(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Zg(t,e){return pr(t)?gh(t,{target:Fq(e?.target),io:e?.pipeStrategy??"input"}):Dg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ug(t){let r=An(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Yl(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Fg(t,e){let r=In(t,e);if(!r.success)throw r.error;return r.data}var Hg=w(()=>{ag();fa();xk()});function Sk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function $k(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];Sk(i)&&Sk(s)?r[o]={...i,...s}:r[o]=s}return r}var Hq,cu,kk=w(()=>{fa();Rs();U$();Hg();Hq=6e4,cu=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(hl,r=>{this._oncancel(r)}),this.setNotificationHandler(vl,r=>{this._onprogress(r)}),this.setRequestHandler(yl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(_l,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(wl,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 q(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 q(G.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(xl,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 q(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler($l,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(Nn(o.status))throw new q(G.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 q(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof q?o:new q(G.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),q.fromError(G.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),tn(s)||ks(s)?this._onresponse(s):Tn(s)?this._onrequest(s,i):VS(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=q.fromError(G.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:G.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=HS(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 q(G.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:G.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),tn(e))n(e);else{let i=new q(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(tn(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),tn(e))o(e);else{let i=q.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 q?i:new q(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Es,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(G.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 q(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(G.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 q?i:new q(G.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 q?b:new q(G.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??Hq,y=()=>m(q.fromError(G.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,y,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},bl,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},Sl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},JS,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=Ug(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Fg(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=Ug(e);this._notificationHandlers.set(n,o=>{let s=Fg(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 q(G.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 q(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new q(G.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 q(G.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=na.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 q(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Nn(a.status))throw new q(G.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=na.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Nn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ya=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 ha=class{};Te._CodeOrName=ha;Te.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Zo=class extends ha{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=Zo;var fr=class extends ha{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 Zo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Te._Code=fr;Te.nil=new fr("");function Ek(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Gg(r,e[n]),r.push(t[++n]);return new fr(r)}Te._=Ek;var Bg=new fr("+");function Tk(t,...e){let r=[ga(t[0])],n=0;for(;n<e.length;)r.push(Bg),Gg(r,e[n]),r.push(Bg,ga(t[++n]));return Bq(r),new fr(r)}Te.str=Tk;function Gg(t,e){e instanceof fr?t.push(...e._items):e instanceof Zo?t.push(e):t.push(Wq(e))}Te.addCodeArg=Gg;function Bq(t){let e=1;for(;e<t.length-1;){if(t[e]===Bg){let r=Gq(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Gq(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Zo||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 Zo))return`"${t}${e.slice(1)}`}function Vq(t,e){return e.emptyStr()?t:t.emptyStr()?e:Tk`${t}${e}`}Te.strConcat=Vq;function Wq(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ga(Array.isArray(t)?t.join(","):t)}function Jq(t){return new fr(ga(t))}Te.stringify=Jq;function ga(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Te.safeStringify=ga;function Kq(t){return typeof t=="string"&&Te.IDENTIFIER.test(t)?new fr(`.${t}`):Ek`[${t}]`}Te.getProperty=Kq;function Yq(t){if(typeof t=="string"&&Te.IDENTIFIER.test(t))return new fr(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Te.getEsmExportName=Yq;function Xq(t){return new fr(t.toString())}Te.regexpCode=Xq});var Jg=I(Wt=>{"use strict";Object.defineProperty(Wt,"__esModule",{value:!0});Wt.ValueScope=Wt.ValueScopeName=Wt.Scope=Wt.varKinds=Wt.UsedValueState=void 0;var Vt=ya(),Vg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},lu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(lu||(Wt.UsedValueState=lu={}));Wt.varKinds={const:new Vt.Name("const"),let:new Vt.Name("let"),var:new Vt.Name("var")};var uu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Vt.Name?e:this.name(e)}name(e){return new Vt.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}}};Wt.Scope=uu;var pu=class extends Vt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Vt._)`.${new Vt.Name(r)}[${n}]`}};Wt.ValueScopeName=pu;var Qq=(0,Vt._)`\n`,Wg=class extends uu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Qq:Vt.nil}}get(){return this._scope}name(e){return new pu(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,Vt._)`${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=Vt.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,lu.Started);let u=r(l);if(u){let p=this.opts.es5?Wt.varKinds.var:Wt.varKinds.const;s=(0,Vt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Vt._)`${s}${u}${this.opts._n}`;else throw new Vg(l);c.set(l,lu.Completed)})}return s}};Wt.ValueScope=Wg});var pe=I(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var Se=ya(),Pr=Jg(),jn=ya();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return jn._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return jn.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return jn.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return jn.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return jn.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return jn.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return jn.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return jn.Name}});var hu=Jg();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return hu.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return hu.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return hu.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return hu.varKinds}});fe.operators={GT:new Se._Code(">"),GTE:new Se._Code(">="),LT:new Se._Code("<"),LTE:new Se._Code("<="),EQ:new Se._Code("==="),NEQ:new Se._Code("!=="),NOT:new Se._Code("!"),OR:new Se._Code("||"),AND:new Se._Code("&&"),ADD:new Se._Code("+")};var an=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Kg=class extends an{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Pr.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=Fs(this.rhs,e,r)),this}get names(){return this.rhs instanceof Se._CodeOrName?this.rhs.names:{}}},du=class extends an{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 Se.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Fs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Se.Name?{}:{...this.lhs.names};return mu(e,this.rhs)}},Yg=class extends du{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Xg=class extends an{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Qg=class extends an{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},ey=class extends an{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},ty=class extends an{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=Fs(this.code,e,r),this}get names(){return this.code instanceof Se._CodeOrName?this.code.names:{}}},va=class extends an{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)||(eZ(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ho(e,r.names),{})}},cn=class extends va{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},ry=class extends va{},Us=class extends cn{};Us.kind="else";var Uo=class t extends cn{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 Us(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Pk(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=Fs(this.condition,e,r),this}get names(){let e=super.names;return mu(e,this.condition),this.else&&Ho(e,this.else.names),e}};Uo.kind="if";var Fo=class extends cn{};Fo.kind="for";var ny=class extends Fo{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=Fs(this.iteration,e,r),this}get names(){return Ho(super.names,this.iteration.names)}},oy=class extends Fo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Pr.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=mu(super.names,this.from);return mu(e,this.to)}},fu=class extends Fo{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=Fs(this.iterable,e,r),this}get names(){return Ho(super.names,this.iterable.names)}},_a=class extends cn{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)}};_a.kind="func";var ba=class extends va{render(e){return"return "+super.render(e)}};ba.kind="return";var sy=class extends cn{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&&Ho(e,this.catch.names),this.finally&&Ho(e,this.finally.names),e}},wa=class extends cn{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};wa.kind="catch";var xa=class extends cn{render(e){return"finally"+super.render(e)}};xa.kind="finally";var iy=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
289
- `:""},this._extScope=e,this._scope=new Pr.Scope({parent:e}),this._nodes=[new ry]}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 Kg(e,s,n)),s}const(e,r,n){return this._def(Pr.varKinds.const,e,r,n)}let(e,r,n){return this._def(Pr.varKinds.let,e,r,n)}var(e,r,n){return this._def(Pr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new du(e,r,n))}add(e,r){return this._leafNode(new Yg(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Se.nil&&this._leafNode(new ty(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,Se.addCodeArg)(r,o));return r.push("}"),new Se._Code(r)}if(e,r,n){if(this._blockNode(new Uo(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 Uo(e))}else(){return this._elseNode(new Us)}endIf(){return this._endBlockNode(Uo,Us)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new ny(e),r)}forRange(e,r,n,o,s=this.opts.es5?Pr.varKinds.var:Pr.varKinds.let){let i=this._scope.toName(e);return this._for(new oy(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Pr.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Se.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Se._)`${i}.length`,a=>{this.var(s,(0,Se._)`${i}[${a}]`),n(s)})}return this._for(new fu("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Pr.varKinds.var:Pr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Se._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new fu("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fo)}label(e){return this._leafNode(new Xg(e))}break(e){return this._leafNode(new Qg(e))}return(e){let r=new ba;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ba)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new sy;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new wa(s),r(s)}return n&&(this._currNode=o.finally=new xa,this.code(n)),this._endBlockNode(wa,xa)}throw(e){return this._leafNode(new ey(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=Se.nil,n,o){return this._blockNode(new _a(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(_a)}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 Uo))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}};fe.CodeGen=iy;function Ho(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function mu(t,e){return e instanceof Se._CodeOrName?Ho(t,e.names):t}function Fs(t,e,r){if(t instanceof Se.Name)return n(t);if(!o(t))return t;return new Se._Code(t._items.reduce((s,i)=>(i instanceof Se.Name&&(i=n(i)),i instanceof Se._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 Se._Code&&s._items.some(i=>i instanceof Se.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function eZ(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Pk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Se._)`!${ay(t)}`}fe.not=Pk;var tZ=Rk(fe.operators.AND);function rZ(...t){return t.reduce(tZ)}fe.and=rZ;var nZ=Rk(fe.operators.OR);function oZ(...t){return t.reduce(nZ)}fe.or=oZ;function Rk(t){return(e,r)=>e===Se.nil?r:r===Se.nil?e:(0,Se._)`${ay(e)} ${t} ${ay(r)}`}function ay(t){return t instanceof Se.Name?t:(0,Se._)`(${t})`}});var Pe=I(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.checkStrictMode=he.getErrorPath=he.Type=he.useFunc=he.setEvaluated=he.evaluatedPropsToName=he.mergeEvaluated=he.eachItem=he.unescapeJsonPointer=he.escapeJsonPointer=he.escapeFragment=he.unescapeFragment=he.schemaRefOrVal=he.schemaHasRulesButRef=he.schemaHasRules=he.checkUnknownRules=he.alwaysValidSchema=he.toHash=void 0;var Me=pe(),sZ=ya();function iZ(t){let e={};for(let r of t)e[r]=!0;return e}he.toHash=iZ;function aZ(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ik(t,e),!Ak(e,t.self.RULES.all))}he.alwaysValidSchema=aZ;function Ik(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]||jk(t,`unknown keyword: "${s}"`)}he.checkUnknownRules=Ik;function Ak(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}he.schemaHasRules=Ak;function cZ(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}he.schemaHasRulesButRef=cZ;function lZ({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Me._)`${r}`}return(0,Me._)`${t}${e}${(0,Me.getProperty)(n)}`}he.schemaRefOrVal=lZ;function uZ(t){return Nk(decodeURIComponent(t))}he.unescapeFragment=uZ;function pZ(t){return encodeURIComponent(ly(t))}he.escapeFragment=pZ;function ly(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}he.escapeJsonPointer=ly;function Nk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}he.unescapeJsonPointer=Nk;function dZ(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}he.eachItem=dZ;function Ok({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Me.Name?(s instanceof Me.Name?t(o,s,i):e(o,s,i),i):s instanceof Me.Name?(e(o,i,s),s):r(s,i);return a===Me.Name&&!(c instanceof Me.Name)?n(o,c):c}}he.mergeEvaluated={props:Ok({mergeNames:(t,e,r)=>t.if((0,Me._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Me._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Me._)`${r} || {}`).code((0,Me._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Me._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Me._)`${r} || {}`),uy(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:zk}),items:Ok({mergeNames:(t,e,r)=>t.if((0,Me._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Me._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Me._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Me._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function zk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Me._)`{}`);return e!==void 0&&uy(t,r,e),r}he.evaluatedPropsToName=zk;function uy(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Me._)`${e}${(0,Me.getProperty)(n)}`,!0))}he.setEvaluated=uy;var Ck={};function fZ(t,e){return t.scopeValue("func",{ref:e,code:Ck[e.code]||(Ck[e.code]=new sZ._Code(e.code))})}he.useFunc=fZ;var cy;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(cy||(he.Type=cy={}));function mZ(t,e,r){if(t instanceof Me.Name){let n=e===cy.Num;return r?n?(0,Me._)`"[" + ${t} + "]"`:(0,Me._)`"['" + ${t} + "']"`:n?(0,Me._)`"/" + ${t}`:(0,Me._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Me.getProperty)(t).toString():"/"+ly(t)}he.getErrorPath=mZ;function jk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}he.checkStrictMode=jk});var ln=I(py=>{"use strict";Object.defineProperty(py,"__esModule",{value:!0});var Ot=pe(),hZ={data:new Ot.Name("data"),valCxt:new Ot.Name("valCxt"),instancePath:new Ot.Name("instancePath"),parentData:new Ot.Name("parentData"),parentDataProperty:new Ot.Name("parentDataProperty"),rootData:new Ot.Name("rootData"),dynamicAnchors:new Ot.Name("dynamicAnchors"),vErrors:new Ot.Name("vErrors"),errors:new Ot.Name("errors"),this:new Ot.Name("this"),self:new Ot.Name("self"),scope:new Ot.Name("scope"),json:new Ot.Name("json"),jsonPos:new Ot.Name("jsonPos"),jsonLen:new Ot.Name("jsonLen"),jsonPart:new Ot.Name("jsonPart")};py.default=hZ});var Sa=I(Ct=>{"use strict";Object.defineProperty(Ct,"__esModule",{value:!0});Ct.extendErrors=Ct.resetErrorsCount=Ct.reportExtraError=Ct.reportError=Ct.keyword$DataError=Ct.keywordError=void 0;var $e=pe(),gu=Pe(),Lt=ln();Ct.keywordError={message:({keyword:t})=>(0,$e.str)`must pass "${t}" keyword validation`};Ct.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,$e.str)`"${t}" keyword must be ${e} ($data)`:(0,$e.str)`"${t}" keyword is invalid ($data)`};function gZ(t,e=Ct.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Dk(t,e,r);n??(i||a)?Mk(s,c):Lk(o,(0,$e._)`[${c}]`)}Ct.reportError=gZ;function yZ(t,e=Ct.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Dk(t,e,r);Mk(o,a),s||i||Lk(n,Lt.default.vErrors)}Ct.reportExtraError=yZ;function vZ(t,e){t.assign(Lt.default.errors,e),t.if((0,$e._)`${Lt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,$e._)`${Lt.default.vErrors}.length`,e),()=>t.assign(Lt.default.vErrors,null)))}Ct.resetErrorsCount=vZ;function _Z({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,Lt.default.errors,a=>{t.const(i,(0,$e._)`${Lt.default.vErrors}[${a}]`),t.if((0,$e._)`${i}.instancePath === undefined`,()=>t.assign((0,$e._)`${i}.instancePath`,(0,$e.strConcat)(Lt.default.instancePath,s.errorPath))),t.assign((0,$e._)`${i}.schemaPath`,(0,$e.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,$e._)`${i}.schema`,r),t.assign((0,$e._)`${i}.data`,n))})}Ct.extendErrors=_Z;function Mk(t,e){let r=t.const("err",e);t.if((0,$e._)`${Lt.default.vErrors} === null`,()=>t.assign(Lt.default.vErrors,(0,$e._)`[${r}]`),(0,$e._)`${Lt.default.vErrors}.push(${r})`),t.code((0,$e._)`${Lt.default.errors}++`)}function Lk(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,$e._)`new ${t.ValidationError}(${e})`):(r.assign((0,$e._)`${n}.errors`,e),r.return(!1))}var Bo={keyword:new $e.Name("keyword"),schemaPath:new $e.Name("schemaPath"),params:new $e.Name("params"),propertyName:new $e.Name("propertyName"),message:new $e.Name("message"),schema:new $e.Name("schema"),parentSchema:new $e.Name("parentSchema")};function Dk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,$e._)`{}`:bZ(t,e,r)}function bZ(t,e,r={}){let{gen:n,it:o}=t,s=[wZ(o,r),xZ(t,r)];return SZ(t,e,s),n.object(...s)}function wZ({errorPath:t},{instancePath:e}){let r=e?(0,$e.str)`${t}${(0,gu.getErrorPath)(e,gu.Type.Str)}`:t;return[Lt.default.instancePath,(0,$e.strConcat)(Lt.default.instancePath,r)]}function xZ({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,$e.str)`${e}/${t}`;return r&&(o=(0,$e.str)`${o}${(0,gu.getErrorPath)(r,gu.Type.Str)}`),[Bo.schemaPath,o]}function SZ(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([Bo.keyword,o],[Bo.params,typeof e=="function"?e(t):e||(0,$e._)`{}`]),c.messages&&n.push([Bo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Bo.schema,i],[Bo.parentSchema,(0,$e._)`${u}${p}`],[Lt.default.data,s]),l&&n.push([Bo.propertyName,l])}});var Zk=I(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.boolOrEmptySchema=Hs.topBoolOrEmptySchema=void 0;var $Z=Sa(),kZ=pe(),EZ=ln(),TZ={message:"boolean schema is false"};function PZ(t){let{gen:e,schema:r,validateName:n}=t;r===!1?qk(t,!1):typeof r=="object"&&r.$async===!0?e.return(EZ.default.data):(e.assign((0,kZ._)`${n}.errors`,null),e.return(!0))}Hs.topBoolOrEmptySchema=PZ;function RZ(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),qk(t)):r.var(e,!0)}Hs.boolOrEmptySchema=RZ;function qk(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,$Z.reportError)(o,TZ,void 0,e)}});var dy=I(Bs=>{"use strict";Object.defineProperty(Bs,"__esModule",{value:!0});Bs.getRules=Bs.isJSONType=void 0;var OZ=["string","number","integer","boolean","null","object","array"],CZ=new Set(OZ);function IZ(t){return typeof t=="string"&&CZ.has(t)}Bs.isJSONType=IZ;function AZ(){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:{}}}Bs.getRules=AZ});var fy=I(Mn=>{"use strict";Object.defineProperty(Mn,"__esModule",{value:!0});Mn.shouldUseRule=Mn.shouldUseGroup=Mn.schemaHasRulesForType=void 0;function NZ({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Uk(t,n)}Mn.schemaHasRulesForType=NZ;function Uk(t,e){return e.rules.some(r=>Fk(t,r))}Mn.shouldUseGroup=Uk;function Fk(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=Fk});var $a=I(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.reportTypeError=It.checkDataTypes=It.checkDataType=It.coerceAndCheckDataType=It.getJSONTypes=It.getSchemaTypes=It.DataType=void 0;var zZ=dy(),jZ=fy(),MZ=Sa(),ce=pe(),Hk=Pe(),Gs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Gs||(It.DataType=Gs={}));function LZ(t){let e=Bk(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}It.getSchemaTypes=LZ;function Bk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(zZ.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}It.getJSONTypes=Bk;function DZ(t,e){let{gen:r,data:n,opts:o}=t,s=qZ(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,jZ.schemaHasRulesForType)(t,e[0]));if(i){let a=hy(e,n,o.strictNumbers,Gs.Wrong);r.if(a,()=>{s.length?ZZ(t,e,s):gy(t)})}return i}It.coerceAndCheckDataType=DZ;var Gk=new Set(["string","number","integer","boolean","null"]);function qZ(t,e){return e?t.filter(r=>Gk.has(r)||e==="array"&&r==="array"):[]}function ZZ(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(hy(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ce._)`${a} !== undefined`);for(let l of r)(Gk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),gy(t),n.endIf(),n.if((0,ce._)`${a} !== undefined`,()=>{n.assign(o,a),UZ(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
289
+ ]`;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 fg,Pr,_q,ru=w(()=>{jn();Pr={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:()=>(fg===void 0&&(fg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),fg),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-_]*$/};_q=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function nu(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]})??Ke(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}=tu(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}=Ql(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var ou=w(()=>{pa();at();ru();eu();mr()});function B$(t,e){if(e.mapStrategy==="record")return nu(t,e);let r=Y(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ke(e),n=Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ke(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var hg=w(()=>{at();ou();mr()});function G$(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 gg=w(()=>{});function V$(t){return t.target==="openAi"?void 0:{not:Ke({...t,currentPath:[...t.currentPath,"not"]})}}var yg=w(()=>{mr()});function W$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var vg=w(()=>{});function K$(t,e){if(e.target==="openApi3")return J$(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in fa&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=fa[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 J$(t,e)}var fa,J$,su=w(()=>{at();fa={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};J$=(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 Y$(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:fa[t.innerType._def.typeName],nullable:!0}:{type:[fa[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 _g=w(()=>{at();su()});function X$(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",tg(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?xe(r,"minimum",n.value,n.message,e):xe(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),xe(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?xe(r,"maximum",n.value,n.message,e):xe(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),xe(r,"maximum",n.value,n.message,e));break;case"multipleOf":xe(r,"multipleOf",n.value,n.message,e);break}return r}var bg=w(()=>{jn()});function Q$(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=xq(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=wq(t,e);return i!==void 0&&(n.additionalProperties=i),n}function wq(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 xq(t){try{return t.isOptional()}catch{return!0}}var wg=w(()=>{at()});var ek,xg=w(()=>{at();mr();ek=(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:Ke(e)},r]}:Ke(e)}});var tk,Sg=w(()=>{at();tk=(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 rk(t,e){return Y(t.type._def,e)}var $g=w(()=>{at()});function nk(t,e){let n={type:"array",uniqueItems:!0,items:Y(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&xe(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&xe(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var kg=w(()=>{jn();at()});function ok(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 Eg=w(()=>{at()});function sk(t){return{not:Ke(t)}}var Tg=w(()=>{mr()});function ik(t){return Ke(t)}var Pg=w(()=>{mr()});var ak,Rg=w(()=>{at();ak=(t,e)=>Y(t.innerType._def,e)});var ck,Og=w(()=>{pa();mr();rg();ng();og();eu();sg();ag();cg();lg();ug();pg();dg();hg();gg();yg();vg();_g();bg();wg();xg();Sg();$g();ou();kg();ru();Eg();Tg();su();Pg();Rg();ck=(t,e,r)=>{switch(e){case P.ZodString:return tu(t,r);case P.ZodNumber:return X$(t,r);case P.ZodObject:return Q$(t,r);case P.ZodBigInt:return j$(t,r);case P.ZodBoolean:return M$();case P.ZodDate:return ig(t,r);case P.ZodUndefined:return sk(r);case P.ZodNull:return W$(r);case P.ZodArray:return z$(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return K$(t,r);case P.ZodIntersection:return U$(t,r);case P.ZodTuple:return ok(t,r);case P.ZodRecord:return nu(t,r);case P.ZodLiteral:return F$(t,r);case P.ZodEnum:return Z$(t);case P.ZodNativeEnum:return G$(t);case P.ZodNullable:return Y$(t,r);case P.ZodOptional:return ek(t,r);case P.ZodMap:return B$(t,r);case P.ZodSet:return nk(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return rk(t,r);case P.ZodNaN:case P.ZodNever:return V$(r);case P.ZodEffects:return q$(t,r);case P.ZodAny:return Ke(r);case P.ZodUnknown:return ik(r);case P.ZodDefault:return D$(t,r);case P.ZodBranded:return Ql(t,r);case P.ZodReadonly:return ak(t,r);case P.ZodCatch:return L$(t,r);case P.ZodPipeline:return tk(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!==I$)return a}if(n&&!r){let a=Sq(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=ck(t,t.typeName,e),i=typeof s=="function"?Y(s(),e):s;if(i&&$q(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var Sq,$q,at=w(()=>{Kl();Og();Xl();mr();Sq=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Yl(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`),Ke(e)):e.$refStrategy==="seen"?Ke(e):void 0}},$q=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var lk=w(()=>{});var Cg,Ig=w(()=>{at();eg();mr();Cg=(t,e)=>{let r=N$(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)??Ke(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)??Ke(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 uk=w(()=>{Kl();eg();jn();Xl();at();lk();mr();rg();ng();og();eu();sg();ag();cg();lg();ug();pg();dg();hg();gg();yg();vg();_g();bg();wg();xg();Sg();$g();Rg();ou();kg();ru();Eg();Tg();su();Pg();Og();Ig();Ig()});function kq(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Ag(t,e){return fr(t)?ch(t,{target:kq(e?.target),io:e?.pipeStrategy??"input"}):Cg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Ng(t){let r=Nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Jl(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zg(t,e){let r=An(t,e);if(!r.success)throw r.error;return r.data}var jg=w(()=>{Qh();da();uk()});function pk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function dk(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];pk(i)&&pk(s)?r[o]={...i,...s}:r[o]=s}return r}var Eq,iu,fk=w(()=>{da();Ps();O$();jg();Eq=6e4,iu=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(fl,r=>{this._oncancel(r)}),this.setNotificationHandler(gl,r=>{this._onprogress(r)}),this.setRequestHandler(hl,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(yl,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(G.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(_l,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 q(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 q(G.InvalidParams,`Task not found: ${s}`);if(!zn(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(zn(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Tn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(bl,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 q(G.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(xl,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(G.InvalidParams,`Task not found: ${r.params.taskId}`);if(zn(o.status))throw new q(G.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 q(G.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof q?o:new q(G.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),q.fromError(G.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),on(s)||$s(s)?this._onresponse(s):Pn(s)?this._onrequest(s,i):zS(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=q.fromError(G.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?.[Tn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:G.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=IS(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 q(G.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:G.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),on(e))n(e);else{let i=new q(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(on(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),on(e))o(e);else{let i=q.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 q?i:new q(G.InternalError,String(i))}}return}let s;try{let i=await this.request(e,ks,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(G.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},zn(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new q(G.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(G.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 q?i:new q(G.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||{},[Tn]: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 q?b:new q(G.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=An(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??Eq,y=()=>m(q.fromError(G.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(f,h,n?.maxTotalTimeout,y,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},vl,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},wl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},MS,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||{},[Tn]: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||{},[Tn]: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||{},[Tn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Ng(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=zg(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=Ng(e);this._notificationHandlers.set(n,o=>{let s=zg(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"&&Pn(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new q(G.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 q(G.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new q(G.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 q(G.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=ra.parse({method:"notifications/tasks/status",params:a});await this.notification(c),zn(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 q(G.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(zn(a.status))throw new q(G.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=ra.parse({method:"notifications/tasks/status",params:c});await this.notification(l),zn(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ga=I(Pe=>{"use strict";Object.defineProperty(Pe,"__esModule",{value:!0});Pe.regexpCode=Pe.getEsmExportName=Pe.getProperty=Pe.safeStringify=Pe.stringify=Pe.strConcat=Pe.addCodeArg=Pe.str=Pe._=Pe.nil=Pe._Code=Pe.Name=Pe.IDENTIFIER=Pe._CodeOrName=void 0;var ma=class{};Pe._CodeOrName=ma;Pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Zo=class extends ma{constructor(e){if(super(),!Pe.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}}};Pe.Name=Zo;var hr=class extends ma{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 Zo&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Pe._Code=hr;Pe.nil=new hr("");function mk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Lg(r,e[n]),r.push(t[++n]);return new hr(r)}Pe._=mk;var Mg=new hr("+");function hk(t,...e){let r=[ha(t[0])],n=0;for(;n<e.length;)r.push(Mg),Lg(r,e[n]),r.push(Mg,ha(t[++n]));return Tq(r),new hr(r)}Pe.str=hk;function Lg(t,e){e instanceof hr?t.push(...e._items):e instanceof Zo?t.push(e):t.push(Oq(e))}Pe.addCodeArg=Lg;function Tq(t){let e=1;for(;e<t.length-1;){if(t[e]===Mg){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 Zo||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 Zo))return`"${t}${e.slice(1)}`}function Rq(t,e){return e.emptyStr()?t:t.emptyStr()?e:hk`${t}${e}`}Pe.strConcat=Rq;function Oq(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ha(Array.isArray(t)?t.join(","):t)}function Cq(t){return new hr(ha(t))}Pe.stringify=Cq;function ha(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Pe.safeStringify=ha;function Iq(t){return typeof t=="string"&&Pe.IDENTIFIER.test(t)?new hr(`.${t}`):mk`[${t}]`}Pe.getProperty=Iq;function Aq(t){if(typeof t=="string"&&Pe.IDENTIFIER.test(t))return new hr(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}Pe.getEsmExportName=Aq;function Nq(t){return new hr(t.toString())}Pe.regexpCode=Nq});var Zg=I(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.ValueScope=Kt.ValueScopeName=Kt.Scope=Kt.varKinds=Kt.UsedValueState=void 0;var Jt=ga(),Dg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},au;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(au||(Kt.UsedValueState=au={}));Kt.varKinds={const:new Jt.Name("const"),let:new Jt.Name("let"),var:new Jt.Name("var")};var cu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Jt.Name?e:this.name(e)}name(e){return new Jt.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}}};Kt.Scope=cu;var lu=class extends Jt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Jt._)`.${new Jt.Name(r)}[${n}]`}};Kt.ValueScopeName=lu;var zq=(0,Jt._)`\n`,qg=class extends cu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?zq:Jt.nil}}get(){return this._scope}name(e){return new lu(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,Jt._)`${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=Jt.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,au.Started);let u=r(l);if(u){let p=this.opts.es5?Kt.varKinds.var:Kt.varKinds.const;s=(0,Jt._)`${s}${p} ${l} = ${u};${this.opts._n}`}else if(u=o?.(l))s=(0,Jt._)`${s}${u}${this.opts._n}`;else throw new Dg(l);c.set(l,au.Completed)})}return s}};Kt.ValueScope=qg});var pe=I(fe=>{"use strict";Object.defineProperty(fe,"__esModule",{value:!0});fe.or=fe.and=fe.not=fe.CodeGen=fe.operators=fe.varKinds=fe.ValueScopeName=fe.ValueScope=fe.Scope=fe.Name=fe.regexpCode=fe.stringify=fe.getProperty=fe.nil=fe.strConcat=fe.str=fe._=void 0;var Se=ga(),Or=Zg(),Mn=ga();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return Mn._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return Mn.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return Mn.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return Mn.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return Mn.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return Mn.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return Mn.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return Mn.Name}});var fu=Zg();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return fu.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return fu.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return fu.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return fu.varKinds}});fe.operators={GT:new Se._Code(">"),GTE:new Se._Code(">="),LT:new Se._Code("<"),LTE:new Se._Code("<="),EQ:new Se._Code("==="),NEQ:new Se._Code("!=="),NOT:new Se._Code("!"),OR:new Se._Code("||"),AND:new Se._Code("&&"),ADD:new Se._Code("+")};var un=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ug=class extends un{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Or.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=Us(this.rhs,e,r)),this}get names(){return this.rhs instanceof Se._CodeOrName?this.rhs.names:{}}},uu=class extends un{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 Se.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Us(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Se.Name?{}:{...this.lhs.names};return du(e,this.rhs)}},Fg=class extends uu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Hg=class extends un{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Bg=class extends un{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Gg=class extends un{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Vg=class extends un{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=Us(this.code,e,r),this}get names(){return this.code instanceof Se._CodeOrName?this.code.names:{}}},ya=class extends un{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)||(jq(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Ho(e,r.names),{})}},pn=class extends ya{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Wg=class extends ya{},Zs=class extends pn{};Zs.kind="else";var Uo=class t extends pn{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 Zs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(gk(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=Us(this.condition,e,r),this}get names(){let e=super.names;return du(e,this.condition),this.else&&Ho(e,this.else.names),e}};Uo.kind="if";var Fo=class extends pn{};Fo.kind="for";var Jg=class extends Fo{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=Us(this.iteration,e,r),this}get names(){return Ho(super.names,this.iteration.names)}},Kg=class extends Fo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Or.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=du(super.names,this.from);return du(e,this.to)}},pu=class extends Fo{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=Us(this.iterable,e,r),this}get names(){return Ho(super.names,this.iterable.names)}},va=class extends pn{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)}};va.kind="func";var _a=class extends ya{render(e){return"return "+super.render(e)}};_a.kind="return";var Yg=class extends pn{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&&Ho(e,this.catch.names),this.finally&&Ho(e,this.finally.names),e}},ba=class extends pn{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};ba.kind="catch";var wa=class extends pn{render(e){return"finally"+super.render(e)}};wa.kind="finally";var Xg=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
290
+ `:""},this._extScope=e,this._scope=new Or.Scope({parent:e}),this._nodes=[new Wg]}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 Ug(e,s,n)),s}const(e,r,n){return this._def(Or.varKinds.const,e,r,n)}let(e,r,n){return this._def(Or.varKinds.let,e,r,n)}var(e,r,n){return this._def(Or.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new uu(e,r,n))}add(e,r){return this._leafNode(new Fg(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Se.nil&&this._leafNode(new Vg(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,Se.addCodeArg)(r,o));return r.push("}"),new Se._Code(r)}if(e,r,n){if(this._blockNode(new Uo(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 Uo(e))}else(){return this._elseNode(new Zs)}endIf(){return this._endBlockNode(Uo,Zs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Jg(e),r)}forRange(e,r,n,o,s=this.opts.es5?Or.varKinds.var:Or.varKinds.let){let i=this._scope.toName(e);return this._for(new Kg(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Or.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof Se.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Se._)`${i}.length`,a=>{this.var(s,(0,Se._)`${i}[${a}]`),n(s)})}return this._for(new pu("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Or.varKinds.var:Or.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,Se._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new pu("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Fo)}label(e){return this._leafNode(new Hg(e))}break(e){return this._leafNode(new Bg(e))}return(e){let r=new _a;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(_a)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new Yg;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new ba(s),r(s)}return n&&(this._currNode=o.finally=new wa,this.code(n)),this._endBlockNode(ba,wa)}throw(e){return this._leafNode(new Gg(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=Se.nil,n,o){return this._blockNode(new va(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(va)}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 Uo))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}};fe.CodeGen=Xg;function Ho(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function du(t,e){return e instanceof Se._CodeOrName?Ho(t,e.names):t}function Us(t,e,r){if(t instanceof Se.Name)return n(t);if(!o(t))return t;return new Se._Code(t._items.reduce((s,i)=>(i instanceof Se.Name&&(i=n(i)),i instanceof Se._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 Se._Code&&s._items.some(i=>i instanceof Se.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function jq(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function gk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Se._)`!${Qg(t)}`}fe.not=gk;var Mq=yk(fe.operators.AND);function Lq(...t){return t.reduce(Mq)}fe.and=Lq;var Dq=yk(fe.operators.OR);function qq(...t){return t.reduce(Dq)}fe.or=qq;function yk(t){return(e,r)=>e===Se.nil?r:r===Se.nil?e:(0,Se._)`${Qg(e)} ${t} ${Qg(r)}`}function Qg(t){return t instanceof Se.Name?t:(0,Se._)`(${t})`}});var Re=I(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.checkStrictMode=he.getErrorPath=he.Type=he.useFunc=he.setEvaluated=he.evaluatedPropsToName=he.mergeEvaluated=he.eachItem=he.unescapeJsonPointer=he.escapeJsonPointer=he.escapeFragment=he.unescapeFragment=he.schemaRefOrVal=he.schemaHasRulesButRef=he.schemaHasRules=he.checkUnknownRules=he.alwaysValidSchema=he.toHash=void 0;var Me=pe(),Zq=ga();function Uq(t){let e={};for(let r of t)e[r]=!0;return e}he.toHash=Uq;function Fq(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(bk(t,e),!wk(e,t.self.RULES.all))}he.alwaysValidSchema=Fq;function bk(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]||$k(t,`unknown keyword: "${s}"`)}he.checkUnknownRules=bk;function wk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}he.schemaHasRules=wk;function Hq(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}he.schemaHasRulesButRef=Hq;function Bq({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Me._)`${r}`}return(0,Me._)`${t}${e}${(0,Me.getProperty)(n)}`}he.schemaRefOrVal=Bq;function Gq(t){return xk(decodeURIComponent(t))}he.unescapeFragment=Gq;function Vq(t){return encodeURIComponent(ty(t))}he.escapeFragment=Vq;function ty(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}he.escapeJsonPointer=ty;function xk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}he.unescapeJsonPointer=xk;function Wq(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}he.eachItem=Wq;function vk({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof Me.Name?(s instanceof Me.Name?t(o,s,i):e(o,s,i),i):s instanceof Me.Name?(e(o,i,s),s):r(s,i);return a===Me.Name&&!(c instanceof Me.Name)?n(o,c):c}}he.mergeEvaluated={props:vk({mergeNames:(t,e,r)=>t.if((0,Me._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Me._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Me._)`${r} || {}`).code((0,Me._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Me._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Me._)`${r} || {}`),ry(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Sk}),items:vk({mergeNames:(t,e,r)=>t.if((0,Me._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Me._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Me._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Me._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Sk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Me._)`{}`);return e!==void 0&&ry(t,r,e),r}he.evaluatedPropsToName=Sk;function ry(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Me._)`${e}${(0,Me.getProperty)(n)}`,!0))}he.setEvaluated=ry;var _k={};function Jq(t,e){return t.scopeValue("func",{ref:e,code:_k[e.code]||(_k[e.code]=new Zq._Code(e.code))})}he.useFunc=Jq;var ey;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ey||(he.Type=ey={}));function Kq(t,e,r){if(t instanceof Me.Name){let n=e===ey.Num;return r?n?(0,Me._)`"[" + ${t} + "]"`:(0,Me._)`"['" + ${t} + "']"`:n?(0,Me._)`"/" + ${t}`:(0,Me._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Me.getProperty)(t).toString():"/"+ty(t)}he.getErrorPath=Kq;function $k(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}he.checkStrictMode=$k});var dn=I(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});var Ct=pe(),Yq={data:new Ct.Name("data"),valCxt:new Ct.Name("valCxt"),instancePath:new Ct.Name("instancePath"),parentData:new Ct.Name("parentData"),parentDataProperty:new Ct.Name("parentDataProperty"),rootData:new Ct.Name("rootData"),dynamicAnchors:new Ct.Name("dynamicAnchors"),vErrors:new Ct.Name("vErrors"),errors:new Ct.Name("errors"),this:new Ct.Name("this"),self:new Ct.Name("self"),scope:new Ct.Name("scope"),json:new Ct.Name("json"),jsonPos:new Ct.Name("jsonPos"),jsonLen:new Ct.Name("jsonLen"),jsonPart:new Ct.Name("jsonPart")};ny.default=Yq});var xa=I(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.extendErrors=It.resetErrorsCount=It.reportExtraError=It.reportError=It.keyword$DataError=It.keywordError=void 0;var $e=pe(),mu=Re(),qt=dn();It.keywordError={message:({keyword:t})=>(0,$e.str)`must pass "${t}" keyword validation`};It.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,$e.str)`"${t}" keyword must be ${e} ($data)`:(0,$e.str)`"${t}" keyword is invalid ($data)`};function Xq(t,e=It.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Tk(t,e,r);n??(i||a)?kk(s,c):Ek(o,(0,$e._)`[${c}]`)}It.reportError=Xq;function Qq(t,e=It.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Tk(t,e,r);kk(o,a),s||i||Ek(n,qt.default.vErrors)}It.reportExtraError=Qq;function eZ(t,e){t.assign(qt.default.errors,e),t.if((0,$e._)`${qt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,$e._)`${qt.default.vErrors}.length`,e),()=>t.assign(qt.default.vErrors,null)))}It.resetErrorsCount=eZ;function tZ({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,qt.default.errors,a=>{t.const(i,(0,$e._)`${qt.default.vErrors}[${a}]`),t.if((0,$e._)`${i}.instancePath === undefined`,()=>t.assign((0,$e._)`${i}.instancePath`,(0,$e.strConcat)(qt.default.instancePath,s.errorPath))),t.assign((0,$e._)`${i}.schemaPath`,(0,$e.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,$e._)`${i}.schema`,r),t.assign((0,$e._)`${i}.data`,n))})}It.extendErrors=tZ;function kk(t,e){let r=t.const("err",e);t.if((0,$e._)`${qt.default.vErrors} === null`,()=>t.assign(qt.default.vErrors,(0,$e._)`[${r}]`),(0,$e._)`${qt.default.vErrors}.push(${r})`),t.code((0,$e._)`${qt.default.errors}++`)}function Ek(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,$e._)`new ${t.ValidationError}(${e})`):(r.assign((0,$e._)`${n}.errors`,e),r.return(!1))}var Bo={keyword:new $e.Name("keyword"),schemaPath:new $e.Name("schemaPath"),params:new $e.Name("params"),propertyName:new $e.Name("propertyName"),message:new $e.Name("message"),schema:new $e.Name("schema"),parentSchema:new $e.Name("parentSchema")};function Tk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,$e._)`{}`:rZ(t,e,r)}function rZ(t,e,r={}){let{gen:n,it:o}=t,s=[nZ(o,r),oZ(t,r)];return sZ(t,e,s),n.object(...s)}function nZ({errorPath:t},{instancePath:e}){let r=e?(0,$e.str)`${t}${(0,mu.getErrorPath)(e,mu.Type.Str)}`:t;return[qt.default.instancePath,(0,$e.strConcat)(qt.default.instancePath,r)]}function oZ({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,$e.str)`${e}/${t}`;return r&&(o=(0,$e.str)`${o}${(0,mu.getErrorPath)(r,mu.Type.Str)}`),[Bo.schemaPath,o]}function sZ(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([Bo.keyword,o],[Bo.params,typeof e=="function"?e(t):e||(0,$e._)`{}`]),c.messages&&n.push([Bo.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Bo.schema,i],[Bo.parentSchema,(0,$e._)`${u}${p}`],[qt.default.data,s]),l&&n.push([Bo.propertyName,l])}});var Rk=I(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});Fs.boolOrEmptySchema=Fs.topBoolOrEmptySchema=void 0;var iZ=xa(),aZ=pe(),cZ=dn(),lZ={message:"boolean schema is false"};function uZ(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Pk(t,!1):typeof r=="object"&&r.$async===!0?e.return(cZ.default.data):(e.assign((0,aZ._)`${n}.errors`,null),e.return(!0))}Fs.topBoolOrEmptySchema=uZ;function pZ(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Pk(t)):r.var(e,!0)}Fs.boolOrEmptySchema=pZ;function Pk(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,iZ.reportError)(o,lZ,void 0,e)}});var oy=I(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.getRules=Hs.isJSONType=void 0;var dZ=["string","number","integer","boolean","null","object","array"],fZ=new Set(dZ);function mZ(t){return typeof t=="string"&&fZ.has(t)}Hs.isJSONType=mZ;function hZ(){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:{}}}Hs.getRules=hZ});var sy=I(Ln=>{"use strict";Object.defineProperty(Ln,"__esModule",{value:!0});Ln.shouldUseRule=Ln.shouldUseGroup=Ln.schemaHasRulesForType=void 0;function gZ({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ok(t,n)}Ln.schemaHasRulesForType=gZ;function Ok(t,e){return e.rules.some(r=>Ck(t,r))}Ln.shouldUseGroup=Ok;function Ck(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))}Ln.shouldUseRule=Ck});var Sa=I(At=>{"use strict";Object.defineProperty(At,"__esModule",{value:!0});At.reportTypeError=At.checkDataTypes=At.checkDataType=At.coerceAndCheckDataType=At.getJSONTypes=At.getSchemaTypes=At.DataType=void 0;var yZ=oy(),vZ=sy(),_Z=xa(),ce=pe(),Ik=Re(),Bs;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Bs||(At.DataType=Bs={}));function bZ(t){let e=Ak(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}At.getSchemaTypes=bZ;function Ak(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(yZ.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}At.getJSONTypes=Ak;function wZ(t,e){let{gen:r,data:n,opts:o}=t,s=xZ(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,vZ.schemaHasRulesForType)(t,e[0]));if(i){let a=ay(e,n,o.strictNumbers,Bs.Wrong);r.if(a,()=>{s.length?SZ(t,e,s):cy(t)})}return i}At.coerceAndCheckDataType=wZ;var Nk=new Set(["string","number","integer","boolean","null"]);function xZ(t,e){return e?t.filter(r=>Nk.has(r)||e==="array"&&r==="array"):[]}function SZ(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(ay(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ce._)`${a} !== undefined`);for(let l of r)(Nk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),cy(t),n.endIf(),n.if((0,ce._)`${a} !== undefined`,()=>{n.assign(o,a),$Z(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
291
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ce._)`+${o}`);return;case"integer":n.elseIf((0,ce._)`${i} === "boolean" || ${o} === null
291
292
  || (${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 UZ({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ce._)`${e} !== undefined`,()=>t.assign((0,ce._)`${e}[${r}]`,n))}function my(t,e,r,n=Gs.Correct){let o=n===Gs.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===Gs.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)}}It.checkDataType=my;function hy(t,e,r,n){if(t.length===1)return my(t[0],e,r,n);let o,s=(0,Hk.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,my(i,e,r,n));return o}It.checkDataTypes=hy;var FZ={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ce._)`{type: ${t}}`:(0,ce._)`{type: ${e}}`};function gy(t){let e=HZ(t);(0,MZ.reportError)(e,FZ)}It.reportTypeError=gy;function HZ(t){let{gen:e,data:r,schema:n}=t,o=(0,Hk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Wk=I(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.assignDefaults=void 0;var Vs=pe(),BZ=Pe();function GZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Vk(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Vk(t,s,o.default))}yu.assignDefaults=GZ;function Vk(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Vs._)`${s}${(0,Vs.getProperty)(e)}`;if(o){(0,BZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Vs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Vs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Vs._)`${a} = ${(0,Vs.stringify)(r)}`)}});var mr=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 He=pe(),yy=Pe(),Ln=ln(),VZ=Pe();function WZ(t,e){let{gen:r,data:n,it:o}=t;r.if(_y(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,He._)`${e}`},!0),t.error()})}Ne.checkReportMissingProp=WZ;function JZ({gen:t,data:e,it:{opts:r}},n,o){return(0,He.or)(...n.map(s=>(0,He.and)(_y(t,e,s,r.ownProperties),(0,He._)`${o} = ${s}`)))}Ne.checkMissingProp=JZ;function KZ(t,e){t.setParams({missingProperty:e},!0),t.error()}Ne.reportMissingProp=KZ;function Jk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,He._)`Object.prototype.hasOwnProperty`})}Ne.hasPropFunc=Jk;function vy(t,e,r){return(0,He._)`${Jk(t)}.call(${e}, ${r})`}Ne.isOwnProperty=vy;function YZ(t,e,r,n){let o=(0,He._)`${e}${(0,He.getProperty)(r)} !== undefined`;return n?(0,He._)`${o} && ${vy(t,e,r)}`:o}Ne.propertyInData=YZ;function _y(t,e,r,n){let o=(0,He._)`${e}${(0,He.getProperty)(r)} === undefined`;return n?(0,He.or)(o,(0,He.not)(vy(t,e,r))):o}Ne.noPropertyInData=_y;function Kk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ne.allSchemaProperties=Kk;function XZ(t,e){return Kk(e).filter(r=>!(0,yy.alwaysValidSchema)(t,e[r]))}Ne.schemaProperties=XZ;function QZ({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,He._)`${t}, ${e}, ${n}${o}`:e,p=[[Ln.default.instancePath,(0,He.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,He._)`${u}, ${r.object(...p)}`;return c!==He.nil?(0,He._)`${a}.call(${c}, ${f})`:(0,He._)`${a}(${f})`}Ne.callValidateCode=QZ;var eU=(0,He._)`new RegExp`;function tU({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,He._)`${o.code==="new RegExp"?eU:(0,VZ.useFunc)(t,o)}(${r}, ${n})`})}Ne.usePattern=tU;function rU(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,He._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:yy.Type.Num},s),e.if((0,He.not)(s),a)})}}Ne.validateArray=rU;function nU(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,yy.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,He._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,He.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ne.validateUnion=nU});var Qk=I(Fr=>{"use strict";Object.defineProperty(Fr,"__esModule",{value:!0});Fr.validateKeywordUsage=Fr.validSchemaType=Fr.funcKeywordCode=Fr.macroKeywordCode=void 0;var Dt=pe(),Go=ln(),oU=mr(),sU=Sa();function iU(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Xk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:Dt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Fr.macroKeywordCode=iU;function aU(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;lU(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Xk(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&&Yk(t),y(()=>t.error());else{let v=e.async?d():m();e.modifying&&Yk(t),y(()=>cU(t,v))}}function d(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,Dt._)`await `),b=>n.assign(p,!1).if((0,Dt._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Dt._)`${b}.errors`),()=>n.throw(b))),v}function m(){let v=(0,Dt._)`${u}.errors`;return n.assign(v,null),h(Dt.nil),v}function h(v=e.async?(0,Dt._)`await `:Dt.nil){let b=c.opts.passContext?Go.default.this:Go.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,Dt._)`${v}${(0,oU.callValidateCode)(t,u,b,x)}`,e.modifying)}function y(v){var b;n.if((0,Dt.not)((b=e.valid)!==null&&b!==void 0?b:p),v)}}Fr.funcKeywordCode=aU;function Yk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Dt._)`${n.parentData}[${n.parentDataProperty}]`))}function cU(t,e){let{gen:r}=t;r.if((0,Dt._)`Array.isArray(${e})`,()=>{r.assign(Go.default.vErrors,(0,Dt._)`${Go.default.vErrors} === null ? ${e} : ${Go.default.vErrors}.concat(${e})`).assign(Go.default.errors,(0,Dt._)`${Go.default.vErrors}.length`),(0,sU.extendErrors)(t)},()=>t.error())}function lU({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Xk(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,Dt.stringify)(r)})}function uU(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")}Fr.validSchemaType=uU;function pU({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)}}Fr.validateKeywordUsage=pU});var tE=I(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.extendSubschemaMode=Dn.extendSubschemaData=Dn.getSubschema=void 0;var Hr=pe(),eE=Pe();function dU(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,Hr._)`${t.schemaPath}${(0,Hr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Hr._)`${t.schemaPath}${(0,Hr.getProperty)(e)}${(0,Hr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,eE.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=dU;function fU(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,Hr._)`${e.data}${(0,Hr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Hr.str)`${l}${(0,eE.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,Hr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Hr.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=fU;function mU(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=mU});var by=I(($Q,rE)=>{"use strict";rE.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 oE=I((kQ,nE)=>{"use strict";var qn=nE.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(){};vu(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 vu(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++)vu(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)vu(t,e,r,p[d],o+"/"+u+"/"+hU(d),s,o,u,n,d)}else(u in qn.keywords||t.allKeys&&!(u in qn.skipKeywords))&&vu(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function hU(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ka=I(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.getSchemaRefs=Jt.resolveUrl=Jt.normalizeId=Jt._getFullPath=Jt.getFullPath=Jt.inlineRef=void 0;var gU=Pe(),yU=by(),vU=oE(),_U=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function bU(t,e=!0){return typeof t=="boolean"?!0:e===!0?!wy(t):e?sE(t)<=e:!1}Jt.inlineRef=bU;var wU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function wy(t){for(let e in t){if(wU.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(wy)||typeof r=="object"&&wy(r))return!0}return!1}function sE(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!_U.has(r)&&(typeof t[r]=="object"&&(0,gU.eachItem)(t[r],n=>e+=sE(n)),e===1/0))return 1/0}return e}function iE(t,e="",r){r!==!1&&(e=Ws(e));let n=t.parse(e);return aE(t,n)}Jt.getFullPath=iE;function aE(t,e){return t.serialize(e).split("#")[0]+"#"}Jt._getFullPath=aE;var xU=/#\/?$/;function Ws(t){return t?t.replace(xU,""):""}Jt.normalizeId=Ws;function SU(t,e,r){return r=Ws(r),t.resolve(e,r)}Jt.resolveUrl=SU;var $U=/^[a-z_][-a-z0-9._]*$/i;function kU(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Ws(t[r]||e),s={"":o},i=iE(n,o,!1),a={},c=new Set;return vU(t,{allKeys:!0},(p,f,d,m)=>{if(m===void 0)return;let h=i+f,y=s[m];typeof p[r]=="string"&&(y=v.call(this,p[r])),b.call(this,p.$anchor),b.call(this,p.$dynamicAnchor),s[f]=y;function v(x){let $=this.opts.uriResolver.resolve;if(x=Ws(y?$(y,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!==Ws(h)&&(x[0]==="#"?(l(p,a[x],x),a[x]=p):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!$U.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`)}}}),a;function l(p,f,d){if(f!==void 0&&!yU(p,f))throw u(d)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Jt.getSchemaRefs=kU});var Pa=I(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.getData=Zn.KeywordCxt=Zn.validateFunctionCode=void 0;var dE=Zk(),cE=$a(),Sy=fy(),_u=$a(),EU=Wk(),Ta=Qk(),xy=tE(),U=pe(),te=ln(),TU=ka(),un=Pe(),Ea=Sa();function PU(t){if(hE(t)&&(gE(t),mE(t))){CU(t);return}fE(t,()=>(0,dE.topBoolOrEmptySchema)(t))}Zn.validateFunctionCode=PU;function fE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,U._)`${te.default.data}, ${te.default.valCxt}`,n.$async,()=>{t.code((0,U._)`"use strict"; ${lE(r,o)}`),OU(t,o),t.code(s)}):t.func(e,(0,U._)`${te.default.data}, ${RU(o)}`,n.$async,()=>t.code(lE(r,o)).code(s))}function RU(t){return(0,U._)`{${te.default.instancePath}="", ${te.default.parentData}, ${te.default.parentDataProperty}, ${te.default.rootData}=${te.default.data}${t.dynamicRef?(0,U._)`, ${te.default.dynamicAnchors}={}`:U.nil}}={}`}function OU(t,e){t.if(te.default.valCxt,()=>{t.var(te.default.instancePath,(0,U._)`${te.default.valCxt}.${te.default.instancePath}`),t.var(te.default.parentData,(0,U._)`${te.default.valCxt}.${te.default.parentData}`),t.var(te.default.parentDataProperty,(0,U._)`${te.default.valCxt}.${te.default.parentDataProperty}`),t.var(te.default.rootData,(0,U._)`${te.default.valCxt}.${te.default.rootData}`),e.dynamicRef&&t.var(te.default.dynamicAnchors,(0,U._)`${te.default.valCxt}.${te.default.dynamicAnchors}`)},()=>{t.var(te.default.instancePath,(0,U._)`""`),t.var(te.default.parentData,(0,U._)`undefined`),t.var(te.default.parentDataProperty,(0,U._)`undefined`),t.var(te.default.rootData,te.default.data),e.dynamicRef&&t.var(te.default.dynamicAnchors,(0,U._)`{}`)})}function CU(t){let{schema:e,opts:r,gen:n}=t;fE(t,()=>{r.$comment&&e.$comment&&vE(t),jU(t),n.let(te.default.vErrors,null),n.let(te.default.errors,0),r.unevaluated&&IU(t),yE(t),DU(t)})}function IU(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,U._)`${r}.evaluated`),e.if((0,U._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,U._)`${t.evaluated}.props`,(0,U._)`undefined`)),e.if((0,U._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,U._)`${t.evaluated}.items`,(0,U._)`undefined`))}function lE(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,U._)`/*# sourceURL=${r} */`:U.nil}function AU(t,e){if(hE(t)&&(gE(t),mE(t))){NU(t,e);return}(0,dE.boolOrEmptySchema)(t,e)}function mE({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 hE(t){return typeof t.schema!="boolean"}function NU(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&vE(t),MU(t),LU(t);let s=n.const("_errs",te.default.errors);yE(t,s),n.var(e,(0,U._)`${s} === ${te.default.errors}`)}function gE(t){(0,un.checkUnknownRules)(t),zU(t)}function yE(t,e){if(t.opts.jtd)return uE(t,[],!1,e);let r=(0,cE.getSchemaTypes)(t.schema),n=(0,cE.coerceAndCheckDataType)(t,r);uE(t,r,!n,e)}function zU(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,un.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function jU(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,un.checkStrictMode)(t,"default is ignored in the schema root")}function MU(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,TU.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function LU(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function vE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,U._)`${te.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,U.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,U._)`${te.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function DU(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,U._)`${te.default.errors} === 0`,()=>e.return(te.default.data),()=>e.throw((0,U._)`new ${o}(${te.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,te.default.vErrors),s.unevaluated&&qU(t),e.return((0,U._)`${te.default.errors} === 0`))}function qU({gen:t,evaluated:e,props:r,items:n}){r instanceof U.Name&&t.assign((0,U._)`${e}.props`,r),n instanceof U.Name&&t.assign((0,U._)`${e}.items`,n)}function uE(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,un.schemaHasRulesButRef)(s,u))){o.block(()=>bE(t,"$ref",u.all.$ref.definition));return}c.jtd||ZU(t,e),o.block(()=>{for(let f of u.rules)p(f);p(u.post)});function p(f){(0,Sy.shouldUseGroup)(s,f)&&(f.type?(o.if((0,_u.checkDataType)(f.type,i,c.strictNumbers)),pE(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,_u.reportTypeError)(t)),o.endIf()):pE(t,f),a||o.if((0,U._)`${te.default.errors} === ${n||0}`))}}function pE(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,EU.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Sy.shouldUseRule)(n,s)&&bE(t,s.keyword,s.definition,e.type)})}function ZU(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(UU(t,e),t.opts.allowUnionTypes||FU(t,e),HU(t,t.dataTypes))}function UU(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{_E(t.dataTypes,r)||$y(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),GU(t,e)}}function FU(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&$y(t,"use allowUnionTypes to allow union type keyword")}function HU(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Sy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>BU(e,i))&&$y(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function BU(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function _E(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function GU(t,e){let r=[];for(let n of t.dataTypes)_E(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function $y(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,un.checkStrictMode)(t,e,t.opts.strictTypes)}var bu=class{constructor(e,r,n){if((0,Ta.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,un.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",wE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ta.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",te.default.errors))}result(e,r,n){this.failResult((0,U.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,U.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,U._)`${r} !== undefined && (${(0,U.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?Ea.reportExtraError:Ea.reportError)(this,this.def.error,r)}$dataError(){(0,Ea.reportError)(this,this.def.$dataError||Ea.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ea.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=U.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=U.nil,r=U.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,U.or)((0,U._)`${o} === undefined`,r)),e!==U.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==U.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,U.or)(i(),a());function i(){if(n.length){if(!(r instanceof U.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,U._)`${(0,_u.checkDataTypes)(c,r,s.opts.strictNumbers,_u.DataType.Wrong)}`}return U.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,U._)`!${c}(${r})`}return U.nil}}subschema(e,r){let n=(0,xy.getSubschema)(this.it,e);(0,xy.extendSubschemaData)(n,this.it,e),(0,xy.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return AU(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=un.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=un.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,U.Name)),!0}};Zn.KeywordCxt=bu;function bE(t,e,r,n){let o=new bu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ta.funcKeywordCode)(o,r):"macro"in r?(0,Ta.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ta.funcKeywordCode)(o,r)}var VU=/^\/(?:[^~]|~0|~1)*$/,WU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function wE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return te.default.rootData;if(t[0]==="/"){if(!VU.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=te.default.rootData}else{let l=WU.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,U._)`${s}${(0,U.getProperty)((0,un.unescapeJsonPointer)(l))}`,i=(0,U._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Zn.getData=wE});var wu=I(Ey=>{"use strict";Object.defineProperty(Ey,"__esModule",{value:!0});var ky=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Ey.default=ky});var Ra=I(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});var Ty=ka(),Py=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Ty.resolveUrl)(e,r,n),this.missingSchema=(0,Ty.normalizeId)((0,Ty.getFullPath)(e,this.missingRef))}};Ry.default=Py});var Su=I(hr=>{"use strict";Object.defineProperty(hr,"__esModule",{value:!0});hr.resolveSchema=hr.getCompilingSchema=hr.resolveRef=hr.compileSchema=hr.SchemaEnv=void 0;var Rr=pe(),JU=wu(),Vo=ln(),Or=ka(),xE=Pe(),KU=Pa(),Js=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,Or.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};hr.SchemaEnv=Js;function Cy(t){let e=SE.call(this,t);if(e)return e;let r=(0,Or.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Rr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:JU.default,code:(0,Rr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Vo.default.data,parentData:Vo.default.parentData,parentDataProperty:Vo.default.parentDataProperty,dataNames:[Vo.default.data],dataPathArr:[Rr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Rr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Rr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Rr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,KU.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Vo.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let d=new Function(`${Vo.default.self}`,`${Vo.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 Rr.Name?void 0:m,items:h instanceof Rr.Name?void 0:h,dynamicProps:m instanceof Rr.Name,dynamicItems:h instanceof Rr.Name},d.source&&(d.source.evaluated=(0,Rr.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)}}hr.compileSchema=Cy;function YU(t,e,r){var n;r=(0,Or.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=eF.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 Js({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=XU.call(this,s)}hr.resolveRef=YU;function XU(t){return(0,Or.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Cy.call(this,t)}function SE(t){for(let e of this._compilations)if(QU(e,t))return e}hr.getCompilingSchema=SE;function QU(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function eF(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||xu.call(this,t,e)}function xu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Or._getFullPath)(this.opts.uriResolver,r),o=(0,Or.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return Oy.call(this,r,t);let s=(0,Or.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=xu.call(this,t,i);return typeof a?.schema!="object"?void 0:Oy.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Cy.call(this,i),s===(0,Or.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Or.resolveUrl)(this.opts.uriResolver,o,l)),new Js({schema:a,schemaId:c,root:t,baseId:o})}return Oy.call(this,r,i)}}hr.resolveSchema=xu;var tF=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Oy(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,xE.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!tF.has(a)&&l&&(e=(0,Or.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,xE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Or.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=xu.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Js({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var $E=I((CQ,rF)=>{rF.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 Ay=I((IQ,PE)=>{"use strict";var nF=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),EE=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 Iy(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 oF=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function kE(t){return t.length=0,!0}function sF(t,e,r){if(t.length){let n=Iy(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function iF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=sF;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=kE}else{o.push(l);continue}}return o.length&&(a===kE?r.zone=o.join(""):i?n.push(o.join("")):n.push(Iy(o))),r.address=n.join(""),r}function TE(t){if(aF(t,":")<2)return{host:t,isIPV6:!1};let e=iF(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 aF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function cF(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 lF(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 uF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!EE(r)){let n=TE(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}PE.exports={nonSimpleDomain:oF,recomposeAuthority:uF,normalizeComponentEncoding:lF,removeDotSegments:cF,isIPv4:EE,isUUID:nF,normalizeIPv6:TE,stringArrayToHexStripped:Iy}});var AE=I((AQ,IE)=>{"use strict";var{isUUID:pF}=Ay(),dF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,fF=["http","https","ws","wss","urn","urn:uuid"];function mF(t){return fF.indexOf(t)!==-1}function Ny(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 RE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function OE(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 hF(t){return t.secure=Ny(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function gF(t){if((t.port===(Ny(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 yF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(dF);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=zy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function vF(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=zy(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 _F(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!pF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function bF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var CE={scheme:"http",domainHost:!0,parse:RE,serialize:OE},wF={scheme:"https",domainHost:CE.domainHost,parse:RE,serialize:OE},$u={scheme:"ws",domainHost:!0,parse:hF,serialize:gF},xF={scheme:"wss",domainHost:$u.domainHost,parse:$u.parse,serialize:$u.serialize},SF={scheme:"urn",parse:yF,serialize:vF,skipNormalize:!0},$F={scheme:"urn:uuid",parse:_F,serialize:bF,skipNormalize:!0},ku={http:CE,https:wF,ws:$u,wss:xF,urn:SF,"urn:uuid":$F};Object.setPrototypeOf(ku,null);function zy(t){return t&&(ku[t]||ku[t.toLowerCase()])||void 0}IE.exports={wsIsSecure:Ny,SCHEMES:ku,isValidSchemeName:mF,getSchemeHandler:zy}});var jE=I((NQ,Tu)=>{"use strict";var{normalizeIPv6:kF,removeDotSegments:Oa,recomposeAuthority:EF,normalizeComponentEncoding:Eu,isIPv4:TF,nonSimpleDomain:PF}=Ay(),{SCHEMES:RF,getSchemeHandler:NE}=AE();function OF(t,e){return typeof t=="string"?t=Br(pn(t,e),e):typeof t=="object"&&(t=pn(Br(t,e),e)),t}function CF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=zE(pn(t,n),pn(e,n),n,!0);return n.skipEscape=!0,Br(o,n)}function zE(t,e,r,n){let o={};return n||(t=pn(Br(t,r),r),e=pn(Br(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=Oa(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=Oa(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Oa(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=Oa(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 IF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Br(Eu(pn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Br(Eu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Br(Eu(pn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Br(Eu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Br(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=NE(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=EF(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=Oa(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 AF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function pn(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(AF);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(TF(n.host)===!1){let c=kF(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=NE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&PF(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 jy={SCHEMES:RF,normalize:OF,resolve:CF,resolveComponent:zE,equal:IF,serialize:Br,parse:pn};Tu.exports=jy;Tu.exports.default=jy;Tu.exports.fastUri=jy});var LE=I(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var ME=jE();ME.code='require("ajv/dist/runtime/uri").default';My.default=ME});var GE=I(St=>{"use strict";Object.defineProperty(St,"__esModule",{value:!0});St.CodeGen=St.Name=St.nil=St.stringify=St.str=St._=St.KeywordCxt=void 0;var NF=Pa();Object.defineProperty(St,"KeywordCxt",{enumerable:!0,get:function(){return NF.KeywordCxt}});var Ks=pe();Object.defineProperty(St,"_",{enumerable:!0,get:function(){return Ks._}});Object.defineProperty(St,"str",{enumerable:!0,get:function(){return Ks.str}});Object.defineProperty(St,"stringify",{enumerable:!0,get:function(){return Ks.stringify}});Object.defineProperty(St,"nil",{enumerable:!0,get:function(){return Ks.nil}});Object.defineProperty(St,"Name",{enumerable:!0,get:function(){return Ks.Name}});Object.defineProperty(St,"CodeGen",{enumerable:!0,get:function(){return Ks.CodeGen}});var zF=wu(),FE=Ra(),jF=dy(),Ca=Su(),MF=pe(),Ia=ka(),Pu=$a(),Dy=Pe(),DE=$E(),LF=LE(),HE=(t,e)=>new RegExp(t,e);HE.code="new RegExp";var DF=["removeAdditional","useDefaults","coerceTypes"],qF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),ZF={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."},UF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},qE=200;function FF(t){var e,r,n,o,s,i,a,c,l,u,p,f,d,m,h,y,v,b,x,$,O,ie,X,ee,de;let F=t.strict,ne=(e=t.code)===null||e===void 0?void 0:e.optimize,ct=ne===!0||ne===void 0?1:ne||0,kt=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:HE,re=(o=t.uriResolver)!==null&&o!==void 0?o:LF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:F)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:F)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:F)!==null&&u!==void 0?u:"log",strictTuples:(f=(p=t.strictTuples)!==null&&p!==void 0?p:F)!==null&&f!==void 0?f:"log",strictRequired:(m=(d=t.strictRequired)!==null&&d!==void 0?d:F)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ct,regExp:kt}:{optimize:ct,regExp:kt},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:qE,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:qE,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:(ie=t.validateSchema)!==null&&ie!==void 0?ie:!0,validateFormats:(X=t.validateFormats)!==null&&X!==void 0?X:!0,unicodeRegExp:(ee=t.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(de=t.int32range)!==null&&de!==void 0?de:!0,uriResolver:re}}var Aa=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...FF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new MF.ValueScope({scope:{},prefixes:qF,es5:r,lines:n}),this.logger=JF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,jF.getRules)(),ZE.call(this,ZF,e,"NOT SUPPORTED"),ZE.call(this,UF,e,"DEPRECATED","warn"),this._metaOpts=VF.call(this),e.formats&&BF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&GF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),HF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=DE;n==="id"&&(o={...DE},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 FE.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,Ia.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 Ca.SchemaEnv({schema:{},schemaId:n});if(r=Ca.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,Ia.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(YF.call(this,n,r),!r)return(0,Dy.eachItem)(n,s=>Ly.call(this,s)),this;QF.call(this,r);let o={...r,type:(0,Pu.getJSONTypes)(r.type),schemaType:(0,Pu.getJSONTypes)(r.schemaType)};return(0,Dy.eachItem)(n,o.type.length===0?s=>Ly.call(this,s,o):s=>o.type.forEach(i=>Ly.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]=BE(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,Ia.normalizeId)(i||n);let l=Ia.getSchemaRefs.call(this,e,n);return c=new Ca.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):Ca.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{Ca.compileSchema.call(this,e)}finally{this.opts=r}}};Aa.ValidationError=zF.default;Aa.MissingRefError=FE.default;St.default=Aa;function ZE(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,Ia.normalizeId)(t),this.schemas[t]||this.refs[t]}function HF(){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 BF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function GF(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 VF(){let t={...this.opts};for(let e of DF)delete t[e];return t}var WF={log(){},warn(){},error(){}};function JF(t){if(t===!1)return WF;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 KF=/^[a-z_$][a-z0-9_$:-]*$/i;function YF(t,e){let{RULES:r}=this;if((0,Dy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!KF.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 Ly(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,Pu.getJSONTypes)(e.type),schemaType:(0,Pu.getJSONTypes)(e.schemaType)}};e.before?XF.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 XF(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 QF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=BE(e)),t.validateSchema=this.compile(e,!0))}var e4={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function BE(t){return{anyOf:[t,e4]}}});var VE=I(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var t4={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};qy.default=t4});var YE=I(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.callRef=Wo.getValidate=void 0;var r4=Ra(),WE=mr(),Kt=pe(),Ys=ln(),JE=Su(),Ru=Pe(),n4={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=JE.resolveRef.call(c,l,o,r);if(u===void 0)throw new r4.default(n.opts.uriResolver,o,r);if(u instanceof JE.SchemaEnv)return f(u);return d(u);function p(){if(s===l)return Ou(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return Ou(t,(0,Kt._)`${m}.validate`,l,l.$async)}function f(m){let h=KE(t,m);Ou(t,h,m,m.$async)}function d(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Kt.stringify)(m)}:{ref:m}),y=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:Kt.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function KE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Kt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Wo.getValidate=KE;function Ou(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Ys.default.this:Kt.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,Kt._)`await ${(0,WE.callValidateCode)(t,e,l)}`),d(e),i||o.assign(m,!0)},h=>{o.if((0,Kt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,WE.callValidateCode)(t,e,l),()=>d(e),()=>f(e))}function f(m){let h=(0,Kt._)`${m}.errors`;o.assign(Ys.default.vErrors,(0,Kt._)`${Ys.default.vErrors} === null ? ${h} : ${Ys.default.vErrors}.concat(${h})`),o.assign(Ys.default.errors,(0,Kt._)`${Ys.default.vErrors}.length`)}function d(m){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Ru.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Kt._)`${m}.evaluated.props`);s.props=Ru.mergeEvaluated.props(o,v,s.props,Kt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ru.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Kt._)`${m}.evaluated.items`);s.items=Ru.mergeEvaluated.items(o,v,s.items,Kt.Name)}}}Wo.callRef=Ou;Wo.default=n4});var XE=I(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var o4=VE(),s4=YE(),i4=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",o4.default,s4.default];Zy.default=i4});var QE=I(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var Cu=pe(),Un=Cu.operators,Iu={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}},a4={message:({keyword:t,schemaCode:e})=>(0,Cu.str)`must be ${Iu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Cu._)`{comparison: ${Iu[t].okStr}, limit: ${e}}`},c4={keyword:Object.keys(Iu),type:"number",schemaType:"number",$data:!0,error:a4,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Cu._)`${r} ${Iu[e].fail} ${n} || isNaN(${r})`)}};Uy.default=c4});var eT=I(Fy=>{"use strict";Object.defineProperty(Fy,"__esModule",{value:!0});var Na=pe(),l4={message:({schemaCode:t})=>(0,Na.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Na._)`{multipleOf: ${t}}`},u4={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:l4,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Na._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Na._)`${i} !== parseInt(${i})`;t.fail$data((0,Na._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Fy.default=u4});var rT=I(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});function tT(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}Hy.default=tT;tT.code='require("ajv/dist/runtime/ucs2length").default'});var nT=I(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var Jo=pe(),p4=Pe(),d4=rT(),f4={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Jo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Jo._)`{limit: ${t}}`},m4={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:f4,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Jo.operators.GT:Jo.operators.LT,i=o.opts.unicode===!1?(0,Jo._)`${r}.length`:(0,Jo._)`${(0,p4.useFunc)(t.gen,d4.default)}(${r})`;t.fail$data((0,Jo._)`${i} ${s} ${n}`)}};By.default=m4});var oT=I(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var h4=mr(),Au=pe(),g4={message:({schemaCode:t})=>(0,Au.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Au._)`{pattern: ${t}}`},y4={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:g4,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Au._)`(new RegExp(${o}, ${i}))`:(0,h4.usePattern)(t,n);t.fail$data((0,Au._)`!${a}.test(${e})`)}};Gy.default=y4});var sT=I(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var za=pe(),v4={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,za.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,za._)`{limit: ${t}}`},_4={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:v4,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?za.operators.GT:za.operators.LT;t.fail$data((0,za._)`Object.keys(${r}).length ${o} ${n}`)}};Vy.default=_4});var iT=I(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});var ja=mr(),Ma=pe(),b4=Pe(),w4={message:({params:{missingProperty:t}})=>(0,Ma.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ma._)`{missingProperty: ${t}}`},x4={keyword:"required",type:"object",schemaType:"array",$data:!0,error:w4,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 y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,b4.checkStrictMode)(i,v,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Ma.nil,p);else for(let d of r)(0,ja.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,ja.checkMissingProp)(t,r,d)),(0,ja.reportMissingProp)(t,d),e.else()}function p(){e.forOf("prop",n,d=>{t.setParams({missingProperty:d}),e.if((0,ja.noPropertyInData)(e,o,d,a.ownProperties),()=>t.error())})}function f(d,m){t.setParams({missingProperty:d}),e.forOf(d,n,()=>{e.assign(m,(0,ja.propertyInData)(e,o,d,a.ownProperties)),e.if((0,Ma.not)(m),()=>{t.error(),e.break()})},Ma.nil)}}};Wy.default=x4});var aT=I(Jy=>{"use strict";Object.defineProperty(Jy,"__esModule",{value:!0});var La=pe(),S4={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,La.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,La._)`{limit: ${t}}`},$4={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:S4,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?La.operators.GT:La.operators.LT;t.fail$data((0,La._)`${r}.length ${o} ${n}`)}};Jy.default=$4});var Nu=I(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var cT=by();cT.code='require("ajv/dist/runtime/equal").default';Ky.default=cT});var lT=I(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var Yy=$a(),$t=pe(),k4=Pe(),E4=Nu(),T4={message:({params:{i:t,j:e}})=>(0,$t.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,$t._)`{i: ${t}, j: ${e}}`},P4={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:T4,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,Yy.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,$t._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,$t._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,$t._)`${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 y=e.name("item"),v=(0,Yy.checkDataTypes)(l,y,a.opts.strictNumbers,Yy.DataType.Wrong),b=e.const("indices",(0,$t._)`{}`);e.for((0,$t._)`;${m}--;`,()=>{e.let(y,(0,$t._)`${r}[${m}]`),e.if(v,(0,$t._)`continue`),l.length>1&&e.if((0,$t._)`typeof ${y} == "string"`,(0,$t._)`${y} += "_"`),e.if((0,$t._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,$t._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,$t._)`${b}[${y}] = ${m}`)})}function d(m,h){let y=(0,k4.useFunc)(e,E4.default),v=e.name("outer");e.label(v).for((0,$t._)`;${m}--;`,()=>e.for((0,$t._)`${h} = ${m}; ${h}--;`,()=>e.if((0,$t._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};Xy.default=P4});var uT=I(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});var Qy=pe(),R4=Pe(),O4=Nu(),C4={message:"must be equal to constant",params:({schemaCode:t})=>(0,Qy._)`{allowedValue: ${t}}`},I4={keyword:"const",$data:!0,error:C4,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Qy._)`!${(0,R4.useFunc)(e,O4.default)}(${r}, ${o})`):t.fail((0,Qy._)`${s} !== ${r}`)}};ev.default=I4});var pT=I(tv=>{"use strict";Object.defineProperty(tv,"__esModule",{value:!0});var Da=pe(),A4=Pe(),N4=Nu(),z4={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Da._)`{allowedValues: ${t}}`},j4={keyword:"enum",schemaType:"array",$data:!0,error:z4,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,A4.useFunc)(e,N4.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,Da.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,Da._)`${l()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function f(d,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Da._)`${l()}(${r}, ${d}[${m}])`:(0,Da._)`${r} === ${h}`}}};tv.default=j4});var dT=I(rv=>{"use strict";Object.defineProperty(rv,"__esModule",{value:!0});var M4=QE(),L4=eT(),D4=nT(),q4=oT(),Z4=sT(),U4=iT(),F4=aT(),H4=lT(),B4=uT(),G4=pT(),V4=[M4.default,L4.default,D4.default,q4.default,Z4.default,U4.default,F4.default,H4.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},B4.default,G4.default];rv.default=V4});var ov=I(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.validateAdditionalItems=void 0;var Ko=pe(),nv=Pe(),W4={message:({params:{len:t}})=>(0,Ko.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ko._)`{limit: ${t}}`},J4={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:W4,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,nv.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}fT(t,n)}};function fT(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Ko._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ko._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,nv.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Ko._)`${a} <= ${e.length}`);r.if((0,Ko.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:nv.Type.Num},l),i.allErrors||r.if((0,Ko.not)(l),()=>r.break())})}}qa.validateAdditionalItems=fT;qa.default=J4});var sv=I(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.validateTuple=void 0;var mT=pe(),zu=Pe(),K4=mr(),Y4={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return hT(t,"additionalItems",e);r.items=!0,!(0,zu.alwaysValidSchema)(r,e)&&t.ok((0,K4.validateArray)(t))}};function hT(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=zu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,mT._)`${s}.length`);r.forEach((p,f)=>{(0,zu.alwaysValidSchema)(a,p)||(n.if((0,mT._)`${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 y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,zu.checkStrictMode)(a,y,f.strictTuples)}}}Za.validateTuple=hT;Za.default=Y4});var gT=I(iv=>{"use strict";Object.defineProperty(iv,"__esModule",{value:!0});var X4=sv(),Q4={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,X4.validateTuple)(t,"items")};iv.default=Q4});var vT=I(av=>{"use strict";Object.defineProperty(av,"__esModule",{value:!0});var yT=pe(),eH=Pe(),tH=mr(),rH=ov(),nH={message:({params:{len:t}})=>(0,yT.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,yT._)`{limit: ${t}}`},oH={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:nH,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,eH.alwaysValidSchema)(n,e)&&(o?(0,rH.validateAdditionalItems)(t,o):t.ok((0,tH.validateArray)(t)))}};av.default=oH});var _T=I(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});var gr=pe(),ju=Pe(),sH={message:({params:{min:t,max:e}})=>e===void 0?(0,gr.str)`must contain at least ${t} valid item(s)`:(0,gr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,gr._)`{minContains: ${t}}`:(0,gr._)`{minContains: ${t}, maxContains: ${e}}`},iH={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:sH,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,gr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,ju.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,ju.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,ju.alwaysValidSchema)(s,r)){let h=(0,gr._)`${u} >= ${i}`;a!==void 0&&(h=(0,gr._)`${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,gr._)`${o}.length > 0`,f)):(e.let(p,!1),f()),t.result(p,()=>t.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);d(h,()=>e.if(h,()=>m(y)))}function d(h,y){e.forRange("i",0,u,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:ju.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,gr._)`${h}++`),a===void 0?e.if((0,gr._)`${h} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,gr._)`${h} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,gr._)`${h} >= ${i}`,()=>e.assign(p,!0)))}}};cv.default=iH});var xT=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.validateSchemaDeps=Gr.validatePropertyDeps=Gr.error=void 0;var lv=pe(),aH=Pe(),Ua=mr();Gr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,lv.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,lv._)`{property: ${t},
293
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,ce._)`[${o}]`)}}}function $Z({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ce._)`${e} !== undefined`,()=>t.assign((0,ce._)`${e}[${r}]`,n))}function iy(t,e,r,n=Bs.Correct){let o=n===Bs.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===Bs.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)}}At.checkDataType=iy;function ay(t,e,r,n){if(t.length===1)return iy(t[0],e,r,n);let o,s=(0,Ik.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,iy(i,e,r,n));return o}At.checkDataTypes=ay;var kZ={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ce._)`{type: ${t}}`:(0,ce._)`{type: ${e}}`};function cy(t){let e=EZ(t);(0,_Z.reportError)(e,kZ)}At.reportTypeError=cy;function EZ(t){let{gen:e,data:r,schema:n}=t,o=(0,Ik.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var jk=I(hu=>{"use strict";Object.defineProperty(hu,"__esModule",{value:!0});hu.assignDefaults=void 0;var Gs=pe(),TZ=Re();function PZ(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)zk(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>zk(t,s,o.default))}hu.assignDefaults=PZ;function zk(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Gs._)`${s}${(0,Gs.getProperty)(e)}`;if(o){(0,TZ.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Gs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Gs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Gs._)`${a} = ${(0,Gs.stringify)(r)}`)}});var gr=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 He=pe(),ly=Re(),Dn=dn(),RZ=Re();function OZ(t,e){let{gen:r,data:n,it:o}=t;r.if(py(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,He._)`${e}`},!0),t.error()})}Ne.checkReportMissingProp=OZ;function CZ({gen:t,data:e,it:{opts:r}},n,o){return(0,He.or)(...n.map(s=>(0,He.and)(py(t,e,s,r.ownProperties),(0,He._)`${o} = ${s}`)))}Ne.checkMissingProp=CZ;function IZ(t,e){t.setParams({missingProperty:e},!0),t.error()}Ne.reportMissingProp=IZ;function Mk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,He._)`Object.prototype.hasOwnProperty`})}Ne.hasPropFunc=Mk;function uy(t,e,r){return(0,He._)`${Mk(t)}.call(${e}, ${r})`}Ne.isOwnProperty=uy;function AZ(t,e,r,n){let o=(0,He._)`${e}${(0,He.getProperty)(r)} !== undefined`;return n?(0,He._)`${o} && ${uy(t,e,r)}`:o}Ne.propertyInData=AZ;function py(t,e,r,n){let o=(0,He._)`${e}${(0,He.getProperty)(r)} === undefined`;return n?(0,He.or)(o,(0,He.not)(uy(t,e,r))):o}Ne.noPropertyInData=py;function Lk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ne.allSchemaProperties=Lk;function NZ(t,e){return Lk(e).filter(r=>!(0,ly.alwaysValidSchema)(t,e[r]))}Ne.schemaProperties=NZ;function zZ({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,l){let u=l?(0,He._)`${t}, ${e}, ${n}${o}`:e,p=[[Dn.default.instancePath,(0,He.strConcat)(Dn.default.instancePath,s)],[Dn.default.parentData,i.parentData],[Dn.default.parentDataProperty,i.parentDataProperty],[Dn.default.rootData,Dn.default.rootData]];i.opts.dynamicRef&&p.push([Dn.default.dynamicAnchors,Dn.default.dynamicAnchors]);let f=(0,He._)`${u}, ${r.object(...p)}`;return c!==He.nil?(0,He._)`${a}.call(${c}, ${f})`:(0,He._)`${a}(${f})`}Ne.callValidateCode=zZ;var jZ=(0,He._)`new RegExp`;function MZ({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,He._)`${o.code==="new RegExp"?jZ:(0,RZ.useFunc)(t,o)}(${r}, ${n})`})}Ne.usePattern=MZ;function LZ(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,He._)`${r}.length`);e.forRange("i",0,c,l=>{t.subschema({keyword:n,dataProp:l,dataPropType:ly.Type.Num},s),e.if((0,He.not)(s),a)})}}Ne.validateArray=LZ;function DZ(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,ly.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,He._)`${i} || ${a}`),t.mergeValidEvaluated(u,a)||e.if((0,He.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}Ne.validateUnion=DZ});var Zk=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.validateKeywordUsage=Gr.validSchemaType=Gr.funcKeywordCode=Gr.macroKeywordCode=void 0;var Zt=pe(),Go=dn(),qZ=gr(),ZZ=xa();function UZ(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=qk(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))}Gr.macroKeywordCode=UZ;function FZ(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;BZ(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=qk(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&&Dk(t),y(()=>t.error());else{let v=e.async?d():m();e.modifying&&Dk(t),y(()=>HZ(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?Go.default.this:Go.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,Zt._)`${v}${(0,qZ.callValidateCode)(t,u,b,x)}`,e.modifying)}function y(v){var b;n.if((0,Zt.not)((b=e.valid)!==null&&b!==void 0?b:p),v)}}Gr.funcKeywordCode=FZ;function Dk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Zt._)`${n.parentData}[${n.parentDataProperty}]`))}function HZ(t,e){let{gen:r}=t;r.if((0,Zt._)`Array.isArray(${e})`,()=>{r.assign(Go.default.vErrors,(0,Zt._)`${Go.default.vErrors} === null ? ${e} : ${Go.default.vErrors}.concat(${e})`).assign(Go.default.errors,(0,Zt._)`${Go.default.vErrors}.length`),(0,ZZ.extendErrors)(t)},()=>t.error())}function BZ({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function qk(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 GZ(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")}Gr.validSchemaType=GZ;function VZ({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)}}Gr.validateKeywordUsage=VZ});var Fk=I(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.extendSubschemaMode=qn.extendSubschemaData=qn.getSubschema=void 0;var Vr=pe(),Uk=Re();function WZ(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,Vr._)`${t.schemaPath}${(0,Vr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Vr._)`${t.schemaPath}${(0,Vr.getProperty)(e)}${(0,Vr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Uk.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')}qn.getSubschema=WZ;function JZ(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,Vr._)`${e.data}${(0,Vr.getProperty)(r)}`,!0);c(f),t.errorPath=(0,Vr.str)`${l}${(0,Uk.getErrorPath)(r,n,p.jsPropertySyntax)}`,t.parentDataProperty=(0,Vr._)`${r}`,t.dataPathArr=[...u,t.parentDataProperty]}if(o!==void 0){let l=o instanceof Vr.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]}}qn.extendSubschemaData=JZ;function KZ(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}qn.extendSubschemaMode=KZ});var dy=I((oQ,Hk)=>{"use strict";Hk.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 Gk=I((sQ,Bk)=>{"use strict";var Zn=Bk.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(){};gu(e,n,o,t,"",t)};Zn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Zn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Zn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Zn.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 gu(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 Zn.arrayKeywords)for(var f=0;f<p.length;f++)gu(t,e,r,p[f],o+"/"+u+"/"+f,s,o,u,n,f)}else if(u in Zn.propsKeywords){if(p&&typeof p=="object")for(var d in p)gu(t,e,r,p[d],o+"/"+u+"/"+YZ(d),s,o,u,n,d)}else(u in Zn.keywords||t.allKeys&&!(u in Zn.skipKeywords))&&gu(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function YZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var $a=I(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.getSchemaRefs=Yt.resolveUrl=Yt.normalizeId=Yt._getFullPath=Yt.getFullPath=Yt.inlineRef=void 0;var XZ=Re(),QZ=dy(),eU=Gk(),tU=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function rU(t,e=!0){return typeof t=="boolean"?!0:e===!0?!fy(t):e?Vk(t)<=e:!1}Yt.inlineRef=rU;var nU=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function fy(t){for(let e in t){if(nU.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(fy)||typeof r=="object"&&fy(r))return!0}return!1}function Vk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!tU.has(r)&&(typeof t[r]=="object"&&(0,XZ.eachItem)(t[r],n=>e+=Vk(n)),e===1/0))return 1/0}return e}function Wk(t,e="",r){r!==!1&&(e=Vs(e));let n=t.parse(e);return Jk(t,n)}Yt.getFullPath=Wk;function Jk(t,e){return t.serialize(e).split("#")[0]+"#"}Yt._getFullPath=Jk;var oU=/#\/?$/;function Vs(t){return t?t.replace(oU,""):""}Yt.normalizeId=Vs;function sU(t,e,r){return r=Vs(r),t.resolve(e,r)}Yt.resolveUrl=sU;var iU=/^[a-z_][-a-z0-9._]*$/i;function aU(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Vs(t[r]||e),s={"":o},i=Wk(n,o,!1),a={},c=new Set;return eU(t,{allKeys:!0},(p,f,d,m)=>{if(m===void 0)return;let h=i+f,y=s[m];typeof p[r]=="string"&&(y=v.call(this,p[r])),b.call(this,p.$anchor),b.call(this,p.$dynamicAnchor),s[f]=y;function v(x){let $=this.opts.uriResolver.resolve;if(x=Vs(y?$(y,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!==Vs(h)&&(x[0]==="#"?(l(p,a[x],x),a[x]=p):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!iU.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`)}}}),a;function l(p,f,d){if(f!==void 0&&!QZ(p,f))throw u(d)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Yt.getSchemaRefs=aU});var Ta=I(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.getData=Un.KeywordCxt=Un.validateFunctionCode=void 0;var eE=Rk(),Kk=Sa(),hy=sy(),yu=Sa(),cU=jk(),Ea=Zk(),my=Fk(),U=pe(),te=dn(),lU=$a(),fn=Re(),ka=xa();function uU(t){if(nE(t)&&(oE(t),rE(t))){fU(t);return}tE(t,()=>(0,eE.topBoolOrEmptySchema)(t))}Un.validateFunctionCode=uU;function tE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,U._)`${te.default.data}, ${te.default.valCxt}`,n.$async,()=>{t.code((0,U._)`"use strict"; ${Yk(r,o)}`),dU(t,o),t.code(s)}):t.func(e,(0,U._)`${te.default.data}, ${pU(o)}`,n.$async,()=>t.code(Yk(r,o)).code(s))}function pU(t){return(0,U._)`{${te.default.instancePath}="", ${te.default.parentData}, ${te.default.parentDataProperty}, ${te.default.rootData}=${te.default.data}${t.dynamicRef?(0,U._)`, ${te.default.dynamicAnchors}={}`:U.nil}}={}`}function dU(t,e){t.if(te.default.valCxt,()=>{t.var(te.default.instancePath,(0,U._)`${te.default.valCxt}.${te.default.instancePath}`),t.var(te.default.parentData,(0,U._)`${te.default.valCxt}.${te.default.parentData}`),t.var(te.default.parentDataProperty,(0,U._)`${te.default.valCxt}.${te.default.parentDataProperty}`),t.var(te.default.rootData,(0,U._)`${te.default.valCxt}.${te.default.rootData}`),e.dynamicRef&&t.var(te.default.dynamicAnchors,(0,U._)`${te.default.valCxt}.${te.default.dynamicAnchors}`)},()=>{t.var(te.default.instancePath,(0,U._)`""`),t.var(te.default.parentData,(0,U._)`undefined`),t.var(te.default.parentDataProperty,(0,U._)`undefined`),t.var(te.default.rootData,te.default.data),e.dynamicRef&&t.var(te.default.dynamicAnchors,(0,U._)`{}`)})}function fU(t){let{schema:e,opts:r,gen:n}=t;tE(t,()=>{r.$comment&&e.$comment&&iE(t),vU(t),n.let(te.default.vErrors,null),n.let(te.default.errors,0),r.unevaluated&&mU(t),sE(t),wU(t)})}function mU(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,U._)`${r}.evaluated`),e.if((0,U._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,U._)`${t.evaluated}.props`,(0,U._)`undefined`)),e.if((0,U._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,U._)`${t.evaluated}.items`,(0,U._)`undefined`))}function Yk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,U._)`/*# sourceURL=${r} */`:U.nil}function hU(t,e){if(nE(t)&&(oE(t),rE(t))){gU(t,e);return}(0,eE.boolOrEmptySchema)(t,e)}function rE({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 nE(t){return typeof t.schema!="boolean"}function gU(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&iE(t),_U(t),bU(t);let s=n.const("_errs",te.default.errors);sE(t,s),n.var(e,(0,U._)`${s} === ${te.default.errors}`)}function oE(t){(0,fn.checkUnknownRules)(t),yU(t)}function sE(t,e){if(t.opts.jtd)return Xk(t,[],!1,e);let r=(0,Kk.getSchemaTypes)(t.schema),n=(0,Kk.coerceAndCheckDataType)(t,r);Xk(t,r,!n,e)}function yU(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,fn.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function vU(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,fn.checkStrictMode)(t,"default is ignored in the schema root")}function _U(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,lU.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function bU(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function iE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,U._)`${te.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,U.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,U._)`${te.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function wU(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,U._)`${te.default.errors} === 0`,()=>e.return(te.default.data),()=>e.throw((0,U._)`new ${o}(${te.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,te.default.vErrors),s.unevaluated&&xU(t),e.return((0,U._)`${te.default.errors} === 0`))}function xU({gen:t,evaluated:e,props:r,items:n}){r instanceof U.Name&&t.assign((0,U._)`${e}.props`,r),n instanceof U.Name&&t.assign((0,U._)`${e}.items`,n)}function Xk(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,fn.schemaHasRulesButRef)(s,u))){o.block(()=>cE(t,"$ref",u.all.$ref.definition));return}c.jtd||SU(t,e),o.block(()=>{for(let f of u.rules)p(f);p(u.post)});function p(f){(0,hy.shouldUseGroup)(s,f)&&(f.type?(o.if((0,yu.checkDataType)(f.type,i,c.strictNumbers)),Qk(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,yu.reportTypeError)(t)),o.endIf()):Qk(t,f),a||o.if((0,U._)`${te.default.errors} === ${n||0}`))}}function Qk(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,cU.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,hy.shouldUseRule)(n,s)&&cE(t,s.keyword,s.definition,e.type)})}function SU(t,e){t.schemaEnv.meta||!t.opts.strictTypes||($U(t,e),t.opts.allowUnionTypes||kU(t,e),EU(t,t.dataTypes))}function $U(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{aE(t.dataTypes,r)||gy(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),PU(t,e)}}function kU(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&gy(t,"use allowUnionTypes to allow union type keyword")}function EU(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,hy.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>TU(e,i))&&gy(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function TU(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function aE(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function PU(t,e){let r=[];for(let n of t.dataTypes)aE(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function gy(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,fn.checkStrictMode)(t,e,t.opts.strictTypes)}var vu=class{constructor(e,r,n){if((0,Ea.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,fn.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",lE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ea.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",te.default.errors))}result(e,r,n){this.failResult((0,U.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,U.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,U._)`${r} !== undefined && (${(0,U.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?ka.reportExtraError:ka.reportError)(this,this.def.error,r)}$dataError(){(0,ka.reportError)(this,this.def.$dataError||ka.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ka.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=U.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=U.nil,r=U.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,U.or)((0,U._)`${o} === undefined`,r)),e!==U.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==U.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,U.or)(i(),a());function i(){if(n.length){if(!(r instanceof U.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,U._)`${(0,yu.checkDataTypes)(c,r,s.opts.strictNumbers,yu.DataType.Wrong)}`}return U.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,U._)`!${c}(${r})`}return U.nil}}subschema(e,r){let n=(0,my.getSubschema)(this.it,e);(0,my.extendSubschemaData)(n,this.it,e),(0,my.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return hU(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=fn.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=fn.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,U.Name)),!0}};Un.KeywordCxt=vu;function cE(t,e,r,n){let o=new vu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ea.funcKeywordCode)(o,r):"macro"in r?(0,Ea.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ea.funcKeywordCode)(o,r)}var RU=/^\/(?:[^~]|~0|~1)*$/,OU=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function lE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return te.default.rootData;if(t[0]==="/"){if(!RU.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=te.default.rootData}else{let l=OU.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,U._)`${s}${(0,U.getProperty)((0,fn.unescapeJsonPointer)(l))}`,i=(0,U._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Un.getData=lE});var _u=I(vy=>{"use strict";Object.defineProperty(vy,"__esModule",{value:!0});var yy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};vy.default=yy});var Pa=I(wy=>{"use strict";Object.defineProperty(wy,"__esModule",{value:!0});var _y=$a(),by=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,_y.resolveUrl)(e,r,n),this.missingSchema=(0,_y.normalizeId)((0,_y.getFullPath)(e,this.missingRef))}};wy.default=by});var wu=I(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.resolveSchema=yr.getCompilingSchema=yr.resolveRef=yr.compileSchema=yr.SchemaEnv=void 0;var Cr=pe(),CU=_u(),Vo=dn(),Ir=$a(),uE=Re(),IU=Ta(),Ws=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,Ir.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};yr.SchemaEnv=Ws;function Sy(t){let e=pE.call(this,t);if(e)return e;let r=(0,Ir.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Cr.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:CU.default,code:(0,Cr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Vo.default.data,parentData:Vo.default.parentData,parentDataProperty:Vo.default.parentDataProperty,dataNames:[Vo.default.data],dataPathArr:[Cr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Cr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Cr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Cr._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,IU.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Vo.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let d=new Function(`${Vo.default.self}`,`${Vo.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 Cr.Name?void 0:m,items:h instanceof Cr.Name?void 0:h,dynamicProps:m instanceof Cr.Name,dynamicItems:h instanceof Cr.Name},d.source&&(d.source.evaluated=(0,Cr.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)}}yr.compileSchema=Sy;function AU(t,e,r){var n;r=(0,Ir.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=jU.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 Ws({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=NU.call(this,s)}yr.resolveRef=AU;function NU(t){return(0,Ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Sy.call(this,t)}function pE(t){for(let e of this._compilations)if(zU(e,t))return e}yr.getCompilingSchema=pE;function zU(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function jU(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||bu.call(this,t,e)}function bu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,Ir._getFullPath)(this.opts.uriResolver,r),o=(0,Ir.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return xy.call(this,r,t);let s=(0,Ir.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=bu.call(this,t,i);return typeof a?.schema!="object"?void 0:xy.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Sy.call(this,i),s===(0,Ir.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,l=a[c];return l&&(o=(0,Ir.resolveUrl)(this.opts.uriResolver,o,l)),new Ws({schema:a,schemaId:c,root:t,baseId:o})}return xy.call(this,r,i)}}yr.resolveSchema=bu;var MU=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function xy(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,uE.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!MU.has(a)&&l&&(e=(0,Ir.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,uE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=bu.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ws({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var dE=I((pQ,LU)=>{LU.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 ky=I((dQ,gE)=>{"use strict";var DU=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),mE=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 $y(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 qU=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function fE(t){return t.length=0,!0}function ZU(t,e,r){if(t.length){let n=$y(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function UU(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=ZU;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=fE}else{o.push(l);continue}}return o.length&&(a===fE?r.zone=o.join(""):i?n.push(o.join("")):n.push($y(o))),r.address=n.join(""),r}function hE(t){if(FU(t,":")<2)return{host:t,isIPV6:!1};let e=UU(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 FU(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function HU(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 BU(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 GU(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!mE(r)){let n=hE(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}gE.exports={nonSimpleDomain:qU,recomposeAuthority:GU,normalizeComponentEncoding:BU,removeDotSegments:HU,isIPv4:mE,isUUID:DU,normalizeIPv6:hE,stringArrayToHexStripped:$y}});var wE=I((fQ,bE)=>{"use strict";var{isUUID:VU}=ky(),WU=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,JU=["http","https","ws","wss","urn","urn:uuid"];function KU(t){return JU.indexOf(t)!==-1}function Ey(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 yE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function vE(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 YU(t){return t.secure=Ey(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function XU(t){if((t.port===(Ey(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 QU(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(WU);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=Ty(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function eF(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=Ty(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 tF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!VU(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function rF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var _E={scheme:"http",domainHost:!0,parse:yE,serialize:vE},nF={scheme:"https",domainHost:_E.domainHost,parse:yE,serialize:vE},xu={scheme:"ws",domainHost:!0,parse:YU,serialize:XU},oF={scheme:"wss",domainHost:xu.domainHost,parse:xu.parse,serialize:xu.serialize},sF={scheme:"urn",parse:QU,serialize:eF,skipNormalize:!0},iF={scheme:"urn:uuid",parse:tF,serialize:rF,skipNormalize:!0},Su={http:_E,https:nF,ws:xu,wss:oF,urn:sF,"urn:uuid":iF};Object.setPrototypeOf(Su,null);function Ty(t){return t&&(Su[t]||Su[t.toLowerCase()])||void 0}bE.exports={wsIsSecure:Ey,SCHEMES:Su,isValidSchemeName:KU,getSchemeHandler:Ty}});var $E=I((mQ,ku)=>{"use strict";var{normalizeIPv6:aF,removeDotSegments:Ra,recomposeAuthority:cF,normalizeComponentEncoding:$u,isIPv4:lF,nonSimpleDomain:uF}=ky(),{SCHEMES:pF,getSchemeHandler:xE}=wE();function dF(t,e){return typeof t=="string"?t=Wr(mn(t,e),e):typeof t=="object"&&(t=mn(Wr(t,e),e)),t}function fF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=SE(mn(t,n),mn(e,n),n,!0);return n.skipEscape=!0,Wr(o,n)}function SE(t,e,r,n){let o={};return n||(t=mn(Wr(t,r),r),e=mn(Wr(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=Ra(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=Ra(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ra(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=Ra(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 mF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Wr($u(mn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Wr($u(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Wr($u(mn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Wr($u(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Wr(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=xE(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=cF(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=Ra(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 hF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function mn(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(hF);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(lF(n.host)===!1){let c=aF(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=xE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&uF(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 Py={SCHEMES:pF,normalize:dF,resolve:fF,resolveComponent:SE,equal:mF,serialize:Wr,parse:mn};ku.exports=Py;ku.exports.default=Py;ku.exports.fastUri=Py});var EE=I(Ry=>{"use strict";Object.defineProperty(Ry,"__esModule",{value:!0});var kE=$E();kE.code='require("ajv/dist/runtime/uri").default';Ry.default=kE});var NE=I($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.CodeGen=$t.Name=$t.nil=$t.stringify=$t.str=$t._=$t.KeywordCxt=void 0;var gF=Ta();Object.defineProperty($t,"KeywordCxt",{enumerable:!0,get:function(){return gF.KeywordCxt}});var Js=pe();Object.defineProperty($t,"_",{enumerable:!0,get:function(){return Js._}});Object.defineProperty($t,"str",{enumerable:!0,get:function(){return Js.str}});Object.defineProperty($t,"stringify",{enumerable:!0,get:function(){return Js.stringify}});Object.defineProperty($t,"nil",{enumerable:!0,get:function(){return Js.nil}});Object.defineProperty($t,"Name",{enumerable:!0,get:function(){return Js.Name}});Object.defineProperty($t,"CodeGen",{enumerable:!0,get:function(){return Js.CodeGen}});var yF=_u(),CE=Pa(),vF=oy(),Oa=wu(),_F=pe(),Ca=$a(),Eu=Sa(),Cy=Re(),TE=dE(),bF=EE(),IE=(t,e)=>new RegExp(t,e);IE.code="new RegExp";var wF=["removeAdditional","useDefaults","coerceTypes"],xF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),SF={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."},$F={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},PE=200;function kF(t){var e,r,n,o,s,i,a,c,l,u,p,f,d,m,h,y,v,b,x,$,O,ie,X,ee,de;let F=t.strict,ne=(e=t.code)===null||e===void 0?void 0:e.optimize,ct=ne===!0||ne===void 0?1:ne||0,Et=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:IE,re=(o=t.uriResolver)!==null&&o!==void 0?o:bF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:F)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:F)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:F)!==null&&u!==void 0?u:"log",strictTuples:(f=(p=t.strictTuples)!==null&&p!==void 0?p:F)!==null&&f!==void 0?f:"log",strictRequired:(m=(d=t.strictRequired)!==null&&d!==void 0?d:F)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ct,regExp:Et}:{optimize:ct,regExp:Et},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:PE,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:PE,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:(ie=t.validateSchema)!==null&&ie!==void 0?ie:!0,validateFormats:(X=t.validateFormats)!==null&&X!==void 0?X:!0,unicodeRegExp:(ee=t.unicodeRegExp)!==null&&ee!==void 0?ee:!0,int32range:(de=t.int32range)!==null&&de!==void 0?de:!0,uriResolver:re}}var Ia=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...kF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new _F.ValueScope({scope:{},prefixes:xF,es5:r,lines:n}),this.logger=CF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,vF.getRules)(),RE.call(this,SF,e,"NOT SUPPORTED"),RE.call(this,$F,e,"DEPRECATED","warn"),this._metaOpts=RF.call(this),e.formats&&TF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&PF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),EF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=TE;n==="id"&&(o={...TE},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 CE.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,Ca.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=OE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Oa.SchemaEnv({schema:{},schemaId:n});if(r=Oa.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=OE.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,Ca.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(AF.call(this,n,r),!r)return(0,Cy.eachItem)(n,s=>Oy.call(this,s)),this;zF.call(this,r);let o={...r,type:(0,Eu.getJSONTypes)(r.type),schemaType:(0,Eu.getJSONTypes)(r.schemaType)};return(0,Cy.eachItem)(n,o.type.length===0?s=>Oy.call(this,s,o):s=>o.type.forEach(i=>Oy.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]=AE(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,Ca.normalizeId)(i||n);let l=Ca.getSchemaRefs.call(this,e,n);return c=new Oa.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):Oa.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{Oa.compileSchema.call(this,e)}finally{this.opts=r}}};Ia.ValidationError=yF.default;Ia.MissingRefError=CE.default;$t.default=Ia;function RE(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 OE(t){return t=(0,Ca.normalizeId)(t),this.schemas[t]||this.refs[t]}function EF(){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 TF(){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 RF(){let t={...this.opts};for(let e of wF)delete t[e];return t}var OF={log(){},warn(){},error(){}};function CF(t){if(t===!1)return OF;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 IF=/^[a-z_$][a-z0-9_$:-]*$/i;function AF(t,e){let{RULES:r}=this;if((0,Cy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!IF.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 Oy(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,Eu.getJSONTypes)(e.type),schemaType:(0,Eu.getJSONTypes)(e.schemaType)}};e.before?NF.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 NF(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 zF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=AE(e)),t.validateSchema=this.compile(e,!0))}var jF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function AE(t){return{anyOf:[t,jF]}}});var zE=I(Iy=>{"use strict";Object.defineProperty(Iy,"__esModule",{value:!0});var MF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Iy.default=MF});var DE=I(Wo=>{"use strict";Object.defineProperty(Wo,"__esModule",{value:!0});Wo.callRef=Wo.getValidate=void 0;var LF=Pa(),jE=gr(),Xt=pe(),Ks=dn(),ME=wu(),Tu=Re(),DF={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=ME.resolveRef.call(c,l,o,r);if(u===void 0)throw new LF.default(n.opts.uriResolver,o,r);if(u instanceof ME.SchemaEnv)return f(u);return d(u);function p(){if(s===l)return Pu(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return Pu(t,(0,Xt._)`${m}.validate`,l,l.$async)}function f(m){let h=LE(t,m);Pu(t,h,m,m.$async)}function d(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,Xt.stringify)(m)}:{ref:m}),y=e.name("valid"),v=t.subschema({schema:m,dataTypes:[],schemaPath:Xt.nil,topSchemaRef:h,errSchemaPath:r},y);t.mergeEvaluated(v),t.ok(y)}}};function LE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Xt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Wo.getValidate=LE;function Pu(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Ks.default.this:Xt.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,Xt._)`await ${(0,jE.callValidateCode)(t,e,l)}`),d(e),i||o.assign(m,!0)},h=>{o.if((0,Xt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),f(h),i||o.assign(m,!1)}),t.ok(m)}function p(){t.result((0,jE.callValidateCode)(t,e,l),()=>d(e),()=>f(e))}function f(m){let h=(0,Xt._)`${m}.errors`;o.assign(Ks.default.vErrors,(0,Xt._)`${Ks.default.vErrors} === null ? ${h} : ${Ks.default.vErrors}.concat(${h})`),o.assign(Ks.default.errors,(0,Xt._)`${Ks.default.vErrors}.length`)}function d(m){var h;if(!s.opts.unevaluated)return;let y=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(y&&!y.dynamicProps)y.props!==void 0&&(s.props=Tu.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Xt._)`${m}.evaluated.props`);s.props=Tu.mergeEvaluated.props(o,v,s.props,Xt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Tu.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Xt._)`${m}.evaluated.items`);s.items=Tu.mergeEvaluated.items(o,v,s.items,Xt.Name)}}}Wo.callRef=Pu;Wo.default=DF});var qE=I(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var qF=zE(),ZF=DE(),UF=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",qF.default,ZF.default];Ay.default=UF});var ZE=I(Ny=>{"use strict";Object.defineProperty(Ny,"__esModule",{value:!0});var Ru=pe(),Fn=Ru.operators,Ou={maximum:{okStr:"<=",ok:Fn.LTE,fail:Fn.GT},minimum:{okStr:">=",ok:Fn.GTE,fail:Fn.LT},exclusiveMaximum:{okStr:"<",ok:Fn.LT,fail:Fn.GTE},exclusiveMinimum:{okStr:">",ok:Fn.GT,fail:Fn.LTE}},FF={message:({keyword:t,schemaCode:e})=>(0,Ru.str)`must be ${Ou[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ru._)`{comparison: ${Ou[t].okStr}, limit: ${e}}`},HF={keyword:Object.keys(Ou),type:"number",schemaType:"number",$data:!0,error:FF,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ru._)`${r} ${Ou[e].fail} ${n} || isNaN(${r})`)}};Ny.default=HF});var UE=I(zy=>{"use strict";Object.defineProperty(zy,"__esModule",{value:!0});var Aa=pe(),BF={message:({schemaCode:t})=>(0,Aa.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Aa._)`{multipleOf: ${t}}`},GF={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:BF,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,Aa._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,Aa._)`${i} !== parseInt(${i})`;t.fail$data((0,Aa._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zy.default=GF});var HE=I(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});function FE(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}jy.default=FE;FE.code='require("ajv/dist/runtime/ucs2length").default'});var BE=I(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var Jo=pe(),VF=Re(),WF=HE(),JF={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Jo.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Jo._)`{limit: ${t}}`},KF={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:JF,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Jo.operators.GT:Jo.operators.LT,i=o.opts.unicode===!1?(0,Jo._)`${r}.length`:(0,Jo._)`${(0,VF.useFunc)(t.gen,WF.default)}(${r})`;t.fail$data((0,Jo._)`${i} ${s} ${n}`)}};My.default=KF});var GE=I(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var YF=gr(),Cu=pe(),XF={message:({schemaCode:t})=>(0,Cu.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Cu._)`{pattern: ${t}}`},QF={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:XF,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,Cu._)`(new RegExp(${o}, ${i}))`:(0,YF.usePattern)(t,n);t.fail$data((0,Cu._)`!${a}.test(${e})`)}};Ly.default=QF});var VE=I(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var Na=pe(),e4={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Na.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Na._)`{limit: ${t}}`},t4={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:e4,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Na.operators.GT:Na.operators.LT;t.fail$data((0,Na._)`Object.keys(${r}).length ${o} ${n}`)}};Dy.default=t4});var WE=I(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});var za=gr(),ja=pe(),r4=Re(),n4={message:({params:{missingProperty:t}})=>(0,ja.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,ja._)`{missingProperty: ${t}}`},o4={keyword:"required",type:"object",schemaType:"array",$data:!0,error:n4,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 y=i.schemaEnv.baseId+i.errSchemaPath,v=`required property "${h}" is not defined at "${y}" (strictRequired)`;(0,r4.checkStrictMode)(i,v,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(ja.nil,p);else for(let d of r)(0,za.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,za.checkMissingProp)(t,r,d)),(0,za.reportMissingProp)(t,d),e.else()}function p(){e.forOf("prop",n,d=>{t.setParams({missingProperty:d}),e.if((0,za.noPropertyInData)(e,o,d,a.ownProperties),()=>t.error())})}function f(d,m){t.setParams({missingProperty:d}),e.forOf(d,n,()=>{e.assign(m,(0,za.propertyInData)(e,o,d,a.ownProperties)),e.if((0,ja.not)(m),()=>{t.error(),e.break()})},ja.nil)}}};qy.default=o4});var JE=I(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var Ma=pe(),s4={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ma.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ma._)`{limit: ${t}}`},i4={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:s4,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Ma.operators.GT:Ma.operators.LT;t.fail$data((0,Ma._)`${r}.length ${o} ${n}`)}};Zy.default=i4});var Iu=I(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var KE=dy();KE.code='require("ajv/dist/runtime/equal").default';Uy.default=KE});var YE=I(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});var Fy=Sa(),kt=pe(),a4=Re(),c4=Iu(),l4={message:({params:{i:t,j:e}})=>(0,kt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,kt._)`{i: ${t}, j: ${e}}`},u4={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:l4,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,Fy.getSchemaTypes)(s.items):[];t.block$data(c,u,(0,kt._)`${i} === false`),t.ok(c);function u(){let m=e.let("i",(0,kt._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,kt._)`${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 y=e.name("item"),v=(0,Fy.checkDataTypes)(l,y,a.opts.strictNumbers,Fy.DataType.Wrong),b=e.const("indices",(0,kt._)`{}`);e.for((0,kt._)`;${m}--;`,()=>{e.let(y,(0,kt._)`${r}[${m}]`),e.if(v,(0,kt._)`continue`),l.length>1&&e.if((0,kt._)`typeof ${y} == "string"`,(0,kt._)`${y} += "_"`),e.if((0,kt._)`typeof ${b}[${y}] == "number"`,()=>{e.assign(h,(0,kt._)`${b}[${y}]`),t.error(),e.assign(c,!1).break()}).code((0,kt._)`${b}[${y}] = ${m}`)})}function d(m,h){let y=(0,a4.useFunc)(e,c4.default),v=e.name("outer");e.label(v).for((0,kt._)`;${m}--;`,()=>e.for((0,kt._)`${h} = ${m}; ${h}--;`,()=>e.if((0,kt._)`${y}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(v)})))}}};Hy.default=u4});var XE=I(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var By=pe(),p4=Re(),d4=Iu(),f4={message:"must be equal to constant",params:({schemaCode:t})=>(0,By._)`{allowedValue: ${t}}`},m4={keyword:"const",$data:!0,error:f4,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,By._)`!${(0,p4.useFunc)(e,d4.default)}(${r}, ${o})`):t.fail((0,By._)`${s} !== ${r}`)}};Gy.default=m4});var QE=I(Vy=>{"use strict";Object.defineProperty(Vy,"__esModule",{value:!0});var La=pe(),h4=Re(),g4=Iu(),y4={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,La._)`{allowedValues: ${t}}`},v4={keyword:"enum",schemaType:"array",$data:!0,error:y4,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,h4.useFunc)(e,g4.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,La.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,La._)`${l()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function f(d,m){let h=o[m];return typeof h=="object"&&h!==null?(0,La._)`${l()}(${r}, ${d}[${m}])`:(0,La._)`${r} === ${h}`}}};Vy.default=v4});var eT=I(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});var _4=ZE(),b4=UE(),w4=BE(),x4=GE(),S4=VE(),$4=WE(),k4=JE(),E4=YE(),T4=XE(),P4=QE(),R4=[_4.default,b4.default,w4.default,x4.default,S4.default,$4.default,k4.default,E4.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},T4.default,P4.default];Wy.default=R4});var Ky=I(Da=>{"use strict";Object.defineProperty(Da,"__esModule",{value:!0});Da.validateAdditionalItems=void 0;var Ko=pe(),Jy=Re(),O4={message:({params:{len:t}})=>(0,Ko.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ko._)`{limit: ${t}}`},C4={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:O4,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Jy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}tT(t,n)}};function tT(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Ko._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ko._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Jy.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,Ko._)`${a} <= ${e.length}`);r.if((0,Ko.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Jy.Type.Num},l),i.allErrors||r.if((0,Ko.not)(l),()=>r.break())})}}Da.validateAdditionalItems=tT;Da.default=C4});var Yy=I(qa=>{"use strict";Object.defineProperty(qa,"__esModule",{value:!0});qa.validateTuple=void 0;var rT=pe(),Au=Re(),I4=gr(),A4={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return nT(t,"additionalItems",e);r.items=!0,!(0,Au.alwaysValidSchema)(r,e)&&t.ok((0,I4.validateArray)(t))}};function nT(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=Au.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,rT._)`${s}.length`);r.forEach((p,f)=>{(0,Au.alwaysValidSchema)(a,p)||(n.if((0,rT._)`${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 y=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${d}"`;(0,Au.checkStrictMode)(a,y,f.strictTuples)}}}qa.validateTuple=nT;qa.default=A4});var oT=I(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var N4=Yy(),z4={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,N4.validateTuple)(t,"items")};Xy.default=z4});var iT=I(Qy=>{"use strict";Object.defineProperty(Qy,"__esModule",{value:!0});var sT=pe(),j4=Re(),M4=gr(),L4=Ky(),D4={message:({params:{len:t}})=>(0,sT.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,sT._)`{limit: ${t}}`},q4={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:D4,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,j4.alwaysValidSchema)(n,e)&&(o?(0,L4.validateAdditionalItems)(t,o):t.ok((0,M4.validateArray)(t)))}};Qy.default=q4});var aT=I(ev=>{"use strict";Object.defineProperty(ev,"__esModule",{value:!0});var vr=pe(),Nu=Re(),Z4={message:({params:{min:t,max:e}})=>e===void 0?(0,vr.str)`must contain at least ${t} valid item(s)`:(0,vr.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,vr._)`{minContains: ${t}}`:(0,vr._)`{minContains: ${t}, maxContains: ${e}}`},U4={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Z4,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,vr._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Nu.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Nu.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Nu.alwaysValidSchema)(s,r)){let h=(0,vr._)`${u} >= ${i}`;a!==void 0&&(h=(0,vr._)`${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,vr._)`${o}.length > 0`,f)):(e.let(p,!1),f()),t.result(p,()=>t.reset());function f(){let h=e.name("_valid"),y=e.let("count",0);d(h,()=>e.if(h,()=>m(y)))}function d(h,y){e.forRange("i",0,u,v=>{t.subschema({keyword:"contains",dataProp:v,dataPropType:Nu.Type.Num,compositeRule:!0},h),y()})}function m(h){e.code((0,vr._)`${h}++`),a===void 0?e.if((0,vr._)`${h} >= ${i}`,()=>e.assign(p,!0).break()):(e.if((0,vr._)`${h} > ${a}`,()=>e.assign(p,!1).break()),i===1?e.assign(p,!0):e.if((0,vr._)`${h} >= ${i}`,()=>e.assign(p,!0)))}}};ev.default=U4});var uT=I(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.validateSchemaDeps=Jr.validatePropertyDeps=Jr.error=void 0;var tv=pe(),F4=Re(),Za=gr();Jr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,tv.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,tv._)`{property: ${t},
293
294
  missingProperty: ${n},
294
295
  depsCount: ${e},
295
- deps: ${r}}`};var cH={keyword:"dependencies",type:"object",schemaType:"object",error:Gr.error,code(t){let[e,r]=lH(t);bT(t,e),wT(t,r)}};function lH({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 bT(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,Ua.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,Ua.checkReportMissingProp)(t,l)}):(r.if((0,lv._)`${c} && (${(0,Ua.checkMissingProp)(t,a,s)})`),(0,Ua.reportMissingProp)(t,s),r.else())}}Gr.validatePropertyDeps=bT;function wT(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,aH.alwaysValidSchema)(s,e[a])||(r.if((0,Ua.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))}Gr.validateSchemaDeps=wT;Gr.default=cH});var $T=I(uv=>{"use strict";Object.defineProperty(uv,"__esModule",{value:!0});var ST=pe(),uH=Pe(),pH={message:"property name must be valid",params:({params:t})=>(0,ST._)`{propertyName: ${t.propertyName}}`},dH={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:pH,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,uH.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,ST.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};uv.default=dH});var dv=I(pv=>{"use strict";Object.defineProperty(pv,"__esModule",{value:!0});var Mu=mr(),Cr=pe(),fH=ln(),Lu=Pe(),mH={message:"must NOT have additional properties",params:({params:t})=>(0,Cr._)`{additionalProperty: ${t.additionalProperty}}`},hH={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:mH,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,Lu.alwaysValidSchema)(i,r))return;let l=(0,Mu.allSchemaProperties)(n.properties),u=(0,Mu.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Cr._)`${s} === ${fH.default.errors}`);function p(){e.forIn("key",o,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let v;if(l.length>8){let b=(0,Lu.schemaRefOrVal)(i,n.properties,"properties");v=(0,Mu.isOwnProperty)(e,b,y)}else l.length?v=(0,Cr.or)(...l.map(b=>(0,Cr._)`${y} === ${b}`)):v=Cr.nil;return u.length&&(v=(0,Cr.or)(v,...u.map(b=>(0,Cr._)`${(0,Mu.usePattern)(t,b)}.test(${y})`))),(0,Cr.not)(v)}function d(y){e.code((0,Cr._)`delete ${o}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){d(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Lu.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,Cr.not)(v),()=>{t.reset(),d(y)})):(h(y,v),a||e.if((0,Cr.not)(v),()=>e.break()))}}function h(y,v,b){let x={keyword:"additionalProperties",dataProp:y,dataPropType:Lu.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,v)}}};pv.default=hH});var TT=I(mv=>{"use strict";Object.defineProperty(mv,"__esModule",{value:!0});var gH=Pa(),kT=mr(),fv=Pe(),ET=dv(),yH={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&&ET.default.code(new gH.KeywordCxt(s,ET.default,"additionalProperties"));let i=(0,kT.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=fv.mergeEvaluated.props(e,(0,fv.toHash)(i),s.props));let a=i.filter(p=>!(0,fv.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,kT.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)}}};mv.default=yH});var CT=I(hv=>{"use strict";Object.defineProperty(hv,"__esModule",{value:!0});var PT=mr(),Du=pe(),RT=Pe(),OT=Pe(),vH={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,PT.allSchemaProperties)(r),c=a.filter(h=>(0,RT.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 Du.Name)&&(s.props=(0,OT.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 y in l)new RegExp(h).test(y)&&(0,RT.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Du._)`${(0,PT.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:OT.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Du._)`${p}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Du.not)(u),()=>e.break())})})}}};hv.default=vH});var IT=I(gv=>{"use strict";Object.defineProperty(gv,"__esModule",{value:!0});var _H=Pe(),bH={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,_H.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"}};gv.default=bH});var AT=I(yv=>{"use strict";Object.defineProperty(yv,"__esModule",{value:!0});var wH=mr(),xH={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:wH.validateUnion,error:{message:"must match a schema in anyOf"}};yv.default=xH});var NT=I(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});var qu=pe(),SH=Pe(),$H={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,qu._)`{passingSchemas: ${t.passing}}`},kH={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:$H,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,SH.alwaysValidSchema)(o,u)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,qu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,qu._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),f&&t.mergeEvaluated(f,qu.Name)})})}}};vv.default=kH});var zT=I(_v=>{"use strict";Object.defineProperty(_v,"__esModule",{value:!0});var EH=Pe(),TH={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,EH.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};_v.default=TH});var LT=I(bv=>{"use strict";Object.defineProperty(bv,"__esModule",{value:!0});var Zu=pe(),MT=Pe(),PH={message:({params:t})=>(0,Zu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Zu._)`{failingKeyword: ${t.ifClause}}`},RH={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:PH,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=jT(n,"then"),s=jT(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 jT(t,e){let r=t.schema[e];return r!==void 0&&!(0,MT.alwaysValidSchema)(t,r)}bv.default=RH});var DT=I(wv=>{"use strict";Object.defineProperty(wv,"__esModule",{value:!0});var OH=Pe(),CH={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,OH.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};wv.default=CH});var qT=I(xv=>{"use strict";Object.defineProperty(xv,"__esModule",{value:!0});var IH=ov(),AH=gT(),NH=sv(),zH=vT(),jH=_T(),MH=xT(),LH=$T(),DH=dv(),qH=TT(),ZH=CT(),UH=IT(),FH=AT(),HH=NT(),BH=zT(),GH=LT(),VH=DT();function WH(t=!1){let e=[UH.default,FH.default,HH.default,BH.default,GH.default,VH.default,LH.default,DH.default,MH.default,qH.default,ZH.default];return t?e.push(AH.default,zH.default):e.push(IH.default,NH.default),e.push(jH.default),e}xv.default=WH});var ZT=I(Sv=>{"use strict";Object.defineProperty(Sv,"__esModule",{value:!0});var nt=pe(),JH={message:({schemaCode:t})=>(0,nt.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,nt._)`{format: ${t}}`},KH={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:JH,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}]`),y=r.let("fType"),v=r.let("format");r.if((0,nt._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,nt._)`${h}.type || "string"`).assign(v,(0,nt._)`${h}.validate`),()=>r.assign(y,(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 && ${y} === ${e} && !${O}`}}function d(){let m=p.formats[s];if(!m){b();return}if(m===!0)return;let[h,y,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 ie=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:ie});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 y=="function"?(0,nt._)`${v}(${n})`:(0,nt._)`${v}.test(${n})`}}}};Sv.default=KH});var UT=I($v=>{"use strict";Object.defineProperty($v,"__esModule",{value:!0});var YH=ZT(),XH=[YH.default];$v.default=XH});var FT=I(Xs=>{"use strict";Object.defineProperty(Xs,"__esModule",{value:!0});Xs.contentVocabulary=Xs.metadataVocabulary=void 0;Xs.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Xs.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var BT=I(kv=>{"use strict";Object.defineProperty(kv,"__esModule",{value:!0});var QH=XE(),e9=dT(),t9=qT(),r9=UT(),HT=FT(),n9=[QH.default,e9.default,(0,t9.default)(),r9.default,HT.metadataVocabulary,HT.contentVocabulary];kv.default=n9});var VT=I(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});Uu.DiscrError=void 0;var GT;(function(t){t.Tag="tag",t.Mapping="mapping"})(GT||(Uu.DiscrError=GT={}))});var JT=I(Tv=>{"use strict";Object.defineProperty(Tv,"__esModule",{value:!0});var Qs=pe(),Ev=VT(),WT=Su(),o9=Ra(),s9=Pe(),i9={message:({params:{discrError:t,tagName:e}})=>t===Ev.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Qs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},a9={keyword:"discriminator",type:"object",schemaType:"object",error:i9,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,Qs._)`${r}${(0,Qs.getProperty)(a)}`);e.if((0,Qs._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:Ev.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,Qs._)`${l} === ${m}`),e.assign(c,p(d[m]));e.else(),t.error(!1,{discrError:Ev.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,Qs.Name),m}function f(){var d;let m={},h=v(o),y=!0;for(let $=0;$<i.length;$++){let O=i[$];if(O?.$ref&&!(0,s9.schemaHasRulesButRef)(O,s.self.RULES)){let X=O.$ref;if(O=WT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,X),O instanceof WT.SchemaEnv&&(O=O.schema),O===void 0)throw new o9.default(s.opts.uriResolver,s.baseId,X)}let ie=(d=O?.properties)===null||d===void 0?void 0:d[a];if(typeof ie!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(O)),b(ie,$)}if(!y)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 ie of $.enum)x(ie,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}}}};Tv.default=a9});var KT=I((xee,c9)=>{c9.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 Rv=I((Be,Pv)=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.MissingRefError=Be.ValidationError=Be.CodeGen=Be.Name=Be.nil=Be.stringify=Be.str=Be._=Be.KeywordCxt=Be.Ajv=void 0;var l9=GE(),u9=BT(),p9=JT(),YT=KT(),d9=["/properties"],Fu="http://json-schema.org/draft-07/schema",ei=class extends l9.default{_addVocabularies(){super._addVocabularies(),u9.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(p9.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(YT,d9):YT;this.addMetaSchema(e,Fu,!1),this.refs["http://json-schema.org/schema"]=Fu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Fu)?Fu:void 0)}};Be.Ajv=ei;Pv.exports=Be=ei;Pv.exports.Ajv=ei;Object.defineProperty(Be,"__esModule",{value:!0});Be.default=ei;var f9=Pa();Object.defineProperty(Be,"KeywordCxt",{enumerable:!0,get:function(){return f9.KeywordCxt}});var ti=pe();Object.defineProperty(Be,"_",{enumerable:!0,get:function(){return ti._}});Object.defineProperty(Be,"str",{enumerable:!0,get:function(){return ti.str}});Object.defineProperty(Be,"stringify",{enumerable:!0,get:function(){return ti.stringify}});Object.defineProperty(Be,"nil",{enumerable:!0,get:function(){return ti.nil}});Object.defineProperty(Be,"Name",{enumerable:!0,get:function(){return ti.Name}});Object.defineProperty(Be,"CodeGen",{enumerable:!0,get:function(){return ti.CodeGen}});var m9=wu();Object.defineProperty(Be,"ValidationError",{enumerable:!0,get:function(){return m9.default}});var h9=Ra();Object.defineProperty(Be,"MissingRefError",{enumerable:!0,get:function(){return h9.default}})});var sP=I(Wr=>{"use strict";Object.defineProperty(Wr,"__esModule",{value:!0});Wr.formatNames=Wr.fastFormats=Wr.fullFormats=void 0;function Vr(t,e){return{validate:t,compare:e}}Wr.fullFormats={date:Vr(tP,Av),time:Vr(Cv(!0),Nv),"date-time":Vr(XT(!0),nP),"iso-time":Vr(Cv(),rP),"iso-date-time":Vr(XT(),oP),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:w9,"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:P9,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:x9,int32:{type:"number",validate:k9},int64:{type:"number",validate:E9},float:{type:"number",validate:eP},double:{type:"number",validate:eP},password:!0,binary:!0};Wr.fastFormats={...Wr.fullFormats,date:Vr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Av),time:Vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Nv),"date-time":Vr(/^\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,nP),"iso-time":Vr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,rP),"iso-date-time":Vr(/^\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,oP),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};Wr.formatNames=Object.keys(Wr.fullFormats);function g9(t){return t%4===0&&(t%100!==0||t%400===0)}var y9=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,v9=[0,31,28,31,30,31,30,31,31,30,31,30,31];function tP(t){let e=y9.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&&g9(r)?29:v9[n])}function Av(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ov=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Cv(t){return function(r){let n=Ov.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 Nv(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 rP(t,e){if(!(t&&e))return;let r=Ov.exec(t),n=Ov.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 Iv=/t|\s/i;function XT(t){let e=Cv(t);return function(n){let o=n.split(Iv);return o.length===2&&tP(o[0])&&e(o[1])}}function nP(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function oP(t,e){if(!(t&&e))return;let[r,n]=t.split(Iv),[o,s]=e.split(Iv),i=Av(r,o);if(i!==void 0)return i||Nv(n,s)}var _9=/\/|:/,b9=/^(?:[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 w9(t){return _9.test(t)&&b9.test(t)}var QT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function x9(t){return QT.lastIndex=0,QT.test(t)}var S9=-(2**31),$9=2**31-1;function k9(t){return Number.isInteger(t)&&t<=$9&&t>=S9}function E9(t){return Number.isInteger(t)}function eP(){return!0}var T9=/[^\\]\\Z/;function P9(t){if(T9.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var iP=I(ri=>{"use strict";Object.defineProperty(ri,"__esModule",{value:!0});ri.formatLimitDefinition=void 0;var R9=Rv(),Ir=pe(),Fn=Ir.operators,Hu={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}},O9={message:({keyword:t,schemaCode:e})=>(0,Ir.str)`should be ${Hu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ir._)`{comparison: ${Hu[t].okStr}, limit: ${e}}`};ri.formatLimitDefinition={keyword:Object.keys(Hu),type:"string",schemaType:"string",$data:!0,error:O9,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 R9.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,Ir._)`${f}[${c.schemaCode}]`);t.fail$data((0,Ir.or)((0,Ir._)`typeof ${d} != "object"`,(0,Ir._)`${d} instanceof RegExp`,(0,Ir._)`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,Ir._)`${i.code.formats}${(0,Ir.getProperty)(f)}`:void 0});t.fail$data(p(m))}function p(f){return(0,Ir._)`${f}.compare(${r}, ${n}) ${Hu[o].fail} 0`}},dependencies:["format"]};var C9=t=>(t.addKeyword(ri.formatLimitDefinition),t);ri.default=C9});var uP=I((Fa,lP)=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});var ni=sP(),I9=iP(),zv=pe(),aP=new zv.Name("fullFormats"),A9=new zv.Name("fastFormats"),jv=(t,e={keywords:!0})=>{if(Array.isArray(e))return cP(t,e,ni.fullFormats,aP),t;let[r,n]=e.mode==="fast"?[ni.fastFormats,A9]:[ni.fullFormats,aP],o=e.formats||ni.formatNames;return cP(t,o,r,n),e.keywords&&(0,I9.default)(t),t};jv.get=(t,e="full")=>{let n=(e==="fast"?ni.fastFormats:ni.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function cP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,zv._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}lP.exports=Fa=jv;Object.defineProperty(Fa,"__esModule",{value:!0});Fa.default=jv});function N9(){let t=new pP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,dP.default)(t),t}var pP,dP,Bu,fP=w(()=>{pP=io(Rv(),1),dP=io(uP(),1);Bu=class{constructor(e){this._ajv=e??N9()}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 Gu,mP=w(()=>{Gu=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 hP(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 gP(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 yP=w(()=>{});var Vu,vP=w(()=>{kk();Rs();fP();fa();mP();yP();Vu=class extends cu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(sa.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 Bu,this.setRequestHandler(gl,n=>this._oninitialize(n)),this.setNotificationHandler(Mh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Hh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=sa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Gu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=$k(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(pr(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(Ps,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new q(G.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,f=await Promise.resolve(r(c,l));if(p.task){let m=In(Es,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new q(G.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let d=In(Cl,f);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new q(G.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){gP(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&hP(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:Ki.includes(r)?r:Ih,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"},ml)}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},Gh,r):this.request({method:"sampling/createMessage",params:e},Bh,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},Il,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},Il,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new q(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(G.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},Vh,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 Mv(t){return!!t&&typeof t=="object"&&bP in t}function wP(t){return t[bP]?.complete}var bP,_P,xP=w(()=>{bP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(_P||(_P={}))});var SP=w(()=>{});function j9(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"),!z9.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 M9(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 Lv(t){let e=j9(t);return M9(t,e.warnings),e.isValid}var z9,$P=w(()=>{z9=/^[A-Za-z0-9._-]{1,128}$/});var Wu,kP=w(()=>{Wu=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 Ju=w(()=>{Wl();Wl()});function PP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function D9(t){return"_def"in t||"_zod"in t||PP(t)}function Dv(t){return typeof t!="object"||t===null||D9(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(PP)}function EP(t){if(t)return Dv(t)?qo(t):t}function q9(t){let e=An(t);return e?Object.entries(e).map(([r,n])=>{let o=q$(n),s=Z$(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=Yl(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function TP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Ku,L9,Ha,RP=w(()=>{vP();fa();Hg();Rs();xP();SP();$P();kP();Ju();Ku=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 Vu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Wu(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(Ol)),this.server.assertCanSetRequestHandler(Hn(Ps)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Ol,()=>({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?Zg(o,{strictUnions:!0,pipeStrategy:"input"}):L9})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Zs(r.outputSchema);o&&(n.outputSchema=Zg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ps,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(G.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 q(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new q(G.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 q&&n.code===G.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 Jl(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Kl(a);throw new q(G.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 q(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Zs(e.outputSchema),s=await Jl(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Kl(i);throw new q(G.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 q(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Hn(Al)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Al,async e=>{switch(e.params.ref.type){case"ref/prompt":return t$(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return r$(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ha;let s=An(n.argsSchema)?.[e.params.argument.name];if(!Mv(s))return Ha;let i=wP(s);if(!i)return Ha;let a=await i(e.params.argument.value,e.params.context);return TP(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 Ha;throw new q(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ha;let s=await o(e.params.argument.value,e.params.context);return TP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(kl)),this.server.assertCanSetRequestHandler(Hn(El)),this.server.assertCanSetRequestHandler(Hn(Tl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(kl,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(El,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Tl,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new q(G.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 q(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Hn(Pl)),this.server.assertCanSetRequestHandler(Hn(Rl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Pl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?q9(r.argsSchema):void 0}))})),this.server.setRequestHandler(Rl,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Zs(n.argsSchema),s=await Jl(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Kl(c);throw new q(G.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:qo(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=qo(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 Bt?c._def?.innerType:c;return Mv(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Lv(e);let u={title:r,description:n,inputSchema:EP(o),outputSchema:EP(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"&&Lv(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=qo(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=qo(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];Dv(c)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Dv(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()}},L9={type:"object",properties:{}};Ha={completion:{values:[],hasMore:!1}}});function oi(){return`${Date.now()}-${++Z9}`}function yr(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 Ue(t,e){if(!e)return!1;let r=new Date(t).getTime();return Date.now()>r+e}var Z9,Jr=w(()=>{Z9=0});var Yu,OP=w(()=>{Jr();Yu=class{entries=new Map;async get(e){let r=this.entries.get(e);return r?Ue(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(Ue(o.setAt,o.ttlMs)){this.entries.delete(o.key);continue}e&&!yr(e,o.key)||r&&o.category!==r||n.push(o)}return n}async getAll(){let e=[];for(let r of this.entries.values())Ue(r.setAt,r.ttlMs)||e.push(r);return e}async load(e){this.entries.clear();for(let r of e)Ue(r.setAt,r.ttlMs)||this.entries.set(r.key,r)}}});var Xu,CP=w(()=>{Jr();Xu=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"&&!Ue(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"&&Ue(r.claimedAt,r.ttlMs)&&(r.status="expired"),r):null}async list(e){let r=[];for(let n of this.claims.values())n.status==="active"&&Ue(n.claimedAt,n.ttlMs)&&(n.status="expired"),n.status==="active"&&(e&&!yr(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 Qu,IP=w(()=>{Qu=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 ep,AP=w(()=>{Jr();ep=class{discoveries=[];eventStore;constructor(e){this.eventStore=e}async publish(e,r,n,o){let s={id:oi(),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 U9}from"node:crypto";var Bn,tp=w(()=>{Bn=class{messages=[];async send(e,r,n,o){let s={id:U9(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 F9}from"node:crypto";var Gn,rp=w(()=>{Gn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:F9(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,np=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 H9}from"node:crypto";var Wn,op=w(()=>{Wn=class{conflicts=new Map;eventStore;constructor(e){this.eventStore=e}async flag(e,r,n,o){let s={id:H9(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,sp=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 B9}from"node:crypto";var Kn,ip=w(()=>{Kn=class{proposals=new Map;eventStore;constructor(e){this.eventStore=e}async propose(e,r,n,o){let s={id:B9(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 G9}from"node:crypto";var Yn,ap=w(()=>{Yn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:G9(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,cp=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,lp=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 NP(){let t=new Qu,e=new Yu,r=new Xu(t),n=new ep(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 qv(t,e={}){let r=e.agentId??"agent_default",n=e.namespace&&e.namespace!=="default"?`@${e.namespace}`:"",o=new Ku({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:L.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:L.string().describe("The state key to write"),value:L.unknown().describe("The value to store (any JSON-serializable value)"),category:L.string().optional().describe('Optional category for grouping (e.g. "config", "progress")'),ttlMs:L.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:L.string().optional().describe('Glob pattern to match keys (e.g. "agent_*", "config.*")'),category:L.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:L.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:L.string().describe("Resource identifier (e.g. file path, variable name, function name)"),value:L.string().describe("What you plan to do with the resource"),ttlMs:L.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:L.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:L.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:L.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:L.string().describe('Event type (e.g. "conflict", "completed", "blocker", "warning")'),data:L.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:L.number().optional().describe("Cursor from previous call (omit for all events)"),type:L.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:L.string().describe("Short topic/title for the discovery"),content:L.string().describe("Detailed content of the discovery"),category:L.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:L.string().optional().describe("Text search query (searches topic and content)"),category:L.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:L.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 y=await Ld(l,t,s()),v=Cc(l,p,h),b=qd(l,p,h,y),x={};for(let[ie,X]of Object.entries(l.phases))x[ie]={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:y,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:L.string().describe("Why the halt is being requested"),status:L.enum(["completed","failed"]).optional().describe("Whether this is a successful completion or failure (default: completed)"),target:L.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:L.string().describe("Why the pause is being requested"),target:L.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:L.string().describe("Why the agent/protocol is being resumed"),target:L.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:L.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:L.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 Zv=w(()=>{RP();Ju();OP();CP();IP();AP();tp();rp();np();op();sp();ip();ap();cp();lp();Pi()});import{createRequire as V9}from"node:module";function zP(t){let r=V9(import.meta.url)("@honeybee-ai/carapace");return t&&console.error("[incubator] carapace loaded"),r}function si(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 Ba(o);if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}}function Yo(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 Xo(t){return typeof t=="string"?t:t==null?"":JSON.stringify(t)}function jP(t,e,r){return{state:{...t.state,set:async(n,o,s,i,a)=>(si(e,[n,Xo(o),i],r),t.state.set(n,o,s,i,a)),get:async n=>{let o=await t.state.get(n);return!o||!Yo(e,[o.key,Xo(o.value),o.category],r)?null:o},query:async(n,o)=>(await t.state.query(n,o)).filter(i=>Yo(e,[i.key,Xo(i.value),i.category],r))},events:{...t.events,publish:async(n,o,s)=>(si(e,[n,Xo(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=>Yo(e,[i.type,Xo(i.data)],r)),cursor:s.cursor}}},claims:{...t.claims,claim:async(n,o,s,i)=>(si(e,[n,o],r),t.claims.claim(n,o,s,i)),check:async n=>{let o=await t.claims.check(n);return!o||!Yo(e,[o.resource,o.value],r)?null:o},list:async n=>(await t.claims.list(n)).filter(s=>Yo(e,[s.resource,s.value],r))},discoveries:{...t.discoveries,publish:async(n,o,s,i)=>(si(e,[n,o,i],r),t.discoveries.publish(n,o,s,i)),search:async(n,o)=>(await t.discoveries.search(n,o)).filter(i=>Yo(e,[i.topic,i.content,i.category],r))},messages:{...t.messages,send:async(n,o,s,i)=>(si(e,[s],r),t.messages.send(n,o,s,i))},help:{...t.help,request:async(n,o,s,i)=>(si(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=>Yo(e,i(a),r)?!0:(n++,!1));return t.state=o(t.state,s=>[s.key,Xo(s.value),s.category]),t.claims=o(t.claims,s=>[s.resource,s.value]),t.events=o(t.events,s=>[s.type,Xo(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 Ba,up=w(()=>{Ba=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 W9(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?W9(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 Ye(t,e){let r=e.agentId??t.headers["x-agent-id"]??"rest_anonymous";return r.startsWith("honeycomb:")?"rest_anonymous":r}async function K9(t){return t.method==="GET"?{}:new Promise((e,r)=>{let n="",o=0;t.on("data",s=>{if(o+=s.length,o>J9){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 Q9(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(Y9.has(n))return{namespace:"default",rewrittenPath:t};let o=r===-1?"":e.slice(r);return{namespace:n,rewrittenPath:`/api${o}`}}async function LP(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 K9(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),y=await h.state.query(),v=await h.claims.list(),b=await h.events.getEvents(),x=await h.discoveries.search();d.push({name:m,state:y.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}=Q9(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 po(s.spec);else if(s.acp&&s.name)d=await po(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 y of Object.values(h.roles))y?.description&&m.push(String(y.description)),y?.instructions&&m.push(String(y.instructions));if(h.phases&&typeof h.phases=="object")for(let y of Object.values(h.phases))y?.description&&m.push(String(y.description));if(m.length>0){let y=`__spec_scan_${Date.now()}`;await u.state.set(y,m.join(" "),Ye(t,s),"__scan"),await u.state.delete(y)}r.setProtocol(c,d),R(e,200,{loaded:!0,name:d.name,title:d.title})}catch(d){d instanceof uo?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 y=m?.match(/^publish\/(.+)$/);if(t.method==="DELETE"&&y){let v=decodeURIComponent(y[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 X9){if(t.method!==d.method)continue;let m=l.match(d.pattern);if(m){if(n){let h=new Date().toISOString().slice(11,23),y=Ye(t,s),v=c==="default"?"":`@${c}`;console.error(` ${h} [${y}${v}] REST ${t.method} ${i}`)}try{await d.handler(t,e,u,m,s)}catch(h){if(h instanceof Ba)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 J9,Y9,X9,DP=w(()=>{up();Pi();J9=1024*1024;Y9=new Set(["state","claims","events","discoveries","health","protocol","messages","help","progress","conflicts","roles","reinforcements","governance","control","topics","runs"]),X9=[{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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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 eB}from"node:module";import{resolve as tB}from"node:path";function ZP(t){let e=t===":memory:"?t:tB(t),r=qP.get(e);if(r)return r;let o=eB(import.meta.url)("better-sqlite3"),s=new o(e);return s.pragma("journal_mode = WAL"),rB(s),e!==":memory:"&&qP.set(e,s),s}function rB(t){t.exec(`
296
+ deps: ${r}}`};var H4={keyword:"dependencies",type:"object",schemaType:"object",error:Jr.error,code(t){let[e,r]=B4(t);cT(t,e),lT(t,r)}};function B4({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 cT(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,tv._)`${c} && (${(0,Za.checkMissingProp)(t,a,s)})`),(0,Za.reportMissingProp)(t,s),r.else())}}Jr.validatePropertyDeps=cT;function lT(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,F4.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))}Jr.validateSchemaDeps=lT;Jr.default=H4});var dT=I(rv=>{"use strict";Object.defineProperty(rv,"__esModule",{value:!0});var pT=pe(),G4=Re(),V4={message:"property name must be valid",params:({params:t})=>(0,pT._)`{propertyName: ${t.propertyName}}`},W4={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:V4,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,G4.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,pT.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};rv.default=W4});var ov=I(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});var zu=gr(),Ar=pe(),J4=dn(),ju=Re(),K4={message:"must NOT have additional properties",params:({params:t})=>(0,Ar._)`{additionalProperty: ${t.additionalProperty}}`},Y4={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:K4,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,ju.alwaysValidSchema)(i,r))return;let l=(0,zu.allSchemaProperties)(n.properties),u=(0,zu.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Ar._)`${s} === ${J4.default.errors}`);function p(){e.forIn("key",o,y=>{!l.length&&!u.length?m(y):e.if(f(y),()=>m(y))})}function f(y){let v;if(l.length>8){let b=(0,ju.schemaRefOrVal)(i,n.properties,"properties");v=(0,zu.isOwnProperty)(e,b,y)}else l.length?v=(0,Ar.or)(...l.map(b=>(0,Ar._)`${y} === ${b}`)):v=Ar.nil;return u.length&&(v=(0,Ar.or)(v,...u.map(b=>(0,Ar._)`${(0,zu.usePattern)(t,b)}.test(${y})`))),(0,Ar.not)(v)}function d(y){e.code((0,Ar._)`delete ${o}[${y}]`)}function m(y){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){d(y);return}if(r===!1){t.setParams({additionalProperty:y}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ju.alwaysValidSchema)(i,r)){let v=e.name("valid");c.removeAdditional==="failing"?(h(y,v,!1),e.if((0,Ar.not)(v),()=>{t.reset(),d(y)})):(h(y,v),a||e.if((0,Ar.not)(v),()=>e.break()))}}function h(y,v,b){let x={keyword:"additionalProperties",dataProp:y,dataPropType:ju.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,v)}}};nv.default=Y4});var hT=I(iv=>{"use strict";Object.defineProperty(iv,"__esModule",{value:!0});var X4=Ta(),fT=gr(),sv=Re(),mT=ov(),Q4={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&&mT.default.code(new X4.KeywordCxt(s,mT.default,"additionalProperties"));let i=(0,fT.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=sv.mergeEvaluated.props(e,(0,sv.toHash)(i),s.props));let a=i.filter(p=>!(0,sv.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,fT.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)}}};iv.default=Q4});var _T=I(av=>{"use strict";Object.defineProperty(av,"__esModule",{value:!0});var gT=gr(),Mu=pe(),yT=Re(),vT=Re(),eH={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,gT.allSchemaProperties)(r),c=a.filter(h=>(0,yT.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 Mu.Name)&&(s.props=(0,vT.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 y in l)new RegExp(h).test(y)&&(0,yT.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Mu._)`${(0,gT.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:vT.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Mu._)`${p}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Mu.not)(u),()=>e.break())})})}}};av.default=eH});var bT=I(cv=>{"use strict";Object.defineProperty(cv,"__esModule",{value:!0});var tH=Re(),rH={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,tH.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"}};cv.default=rH});var wT=I(lv=>{"use strict";Object.defineProperty(lv,"__esModule",{value:!0});var nH=gr(),oH={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nH.validateUnion,error:{message:"must match a schema in anyOf"}};lv.default=oH});var xT=I(uv=>{"use strict";Object.defineProperty(uv,"__esModule",{value:!0});var Lu=pe(),sH=Re(),iH={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Lu._)`{passingSchemas: ${t.passing}}`},aH={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:iH,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,sH.alwaysValidSchema)(o,u)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Lu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Lu._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),f&&t.mergeEvaluated(f,Lu.Name)})})}}};uv.default=aH});var ST=I(pv=>{"use strict";Object.defineProperty(pv,"__esModule",{value:!0});var cH=Re(),lH={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,cH.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};pv.default=lH});var ET=I(dv=>{"use strict";Object.defineProperty(dv,"__esModule",{value:!0});var Du=pe(),kT=Re(),uH={message:({params:t})=>(0,Du.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Du._)`{failingKeyword: ${t.ifClause}}`},pH={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:uH,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,kT.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=$T(n,"then"),s=$T(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,Du.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,Du._)`${u}`):t.setParams({ifClause:u})}}}};function $T(t,e){let r=t.schema[e];return r!==void 0&&!(0,kT.alwaysValidSchema)(t,r)}dv.default=pH});var TT=I(fv=>{"use strict";Object.defineProperty(fv,"__esModule",{value:!0});var dH=Re(),fH={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,dH.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};fv.default=fH});var PT=I(mv=>{"use strict";Object.defineProperty(mv,"__esModule",{value:!0});var mH=Ky(),hH=oT(),gH=Yy(),yH=iT(),vH=aT(),_H=uT(),bH=dT(),wH=ov(),xH=hT(),SH=_T(),$H=bT(),kH=wT(),EH=xT(),TH=ST(),PH=ET(),RH=TT();function OH(t=!1){let e=[$H.default,kH.default,EH.default,TH.default,PH.default,RH.default,bH.default,wH.default,_H.default,xH.default,SH.default];return t?e.push(hH.default,yH.default):e.push(mH.default,gH.default),e.push(vH.default),e}mv.default=OH});var RT=I(hv=>{"use strict";Object.defineProperty(hv,"__esModule",{value:!0});var ot=pe(),CH={message:({schemaCode:t})=>(0,ot.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,ot._)`{format: ${t}}`},IH={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:CH,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,ot._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,ot._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,ot._)`${h}.type || "string"`).assign(v,(0,ot._)`${h}.validate`),()=>r.assign(y,(0,ot._)`"string"`).assign(v,h)),t.fail$data((0,ot.or)(b(),x()));function b(){return c.strictSchema===!1?ot.nil:(0,ot._)`${i} && !${v}`}function x(){let $=u.$async?(0,ot._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,ot._)`${v}(${n})`,O=(0,ot._)`(typeof ${v} == "function" ? ${$} : ${v}.test(${n}))`;return(0,ot._)`${v} && ${v} !== true && ${y} === ${e} && !${O}`}}function d(){let m=p.formats[s];if(!m){b();return}if(m===!0)return;let[h,y,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 ie=O instanceof RegExp?(0,ot.regexpCode)(O):c.code.formats?(0,ot._)`${c.code.formats}${(0,ot.getProperty)(s)}`:void 0,X=r.scopeValue("formats",{key:s,ref:O,code:ie});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,ot._)`${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,ot._)`await ${v}(${n})`}return typeof y=="function"?(0,ot._)`${v}(${n})`:(0,ot._)`${v}.test(${n})`}}}};hv.default=IH});var OT=I(gv=>{"use strict";Object.defineProperty(gv,"__esModule",{value:!0});var AH=RT(),NH=[AH.default];gv.default=NH});var CT=I(Ys=>{"use strict";Object.defineProperty(Ys,"__esModule",{value:!0});Ys.contentVocabulary=Ys.metadataVocabulary=void 0;Ys.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Ys.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var AT=I(yv=>{"use strict";Object.defineProperty(yv,"__esModule",{value:!0});var zH=qE(),jH=eT(),MH=PT(),LH=OT(),IT=CT(),DH=[zH.default,jH.default,(0,MH.default)(),LH.default,IT.metadataVocabulary,IT.contentVocabulary];yv.default=DH});var zT=I(qu=>{"use strict";Object.defineProperty(qu,"__esModule",{value:!0});qu.DiscrError=void 0;var NT;(function(t){t.Tag="tag",t.Mapping="mapping"})(NT||(qu.DiscrError=NT={}))});var MT=I(_v=>{"use strict";Object.defineProperty(_v,"__esModule",{value:!0});var Xs=pe(),vv=zT(),jT=wu(),qH=Pa(),ZH=Re(),UH={message:({params:{discrError:t,tagName:e}})=>t===vv.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Xs._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},FH={keyword:"discriminator",type:"object",schemaType:"object",error:UH,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,Xs._)`${r}${(0,Xs.getProperty)(a)}`);e.if((0,Xs._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:vv.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,Xs._)`${l} === ${m}`),e.assign(c,p(d[m]));e.else(),t.error(!1,{discrError:vv.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,Xs.Name),m}function f(){var d;let m={},h=v(o),y=!0;for(let $=0;$<i.length;$++){let O=i[$];if(O?.$ref&&!(0,ZH.schemaHasRulesButRef)(O,s.self.RULES)){let X=O.$ref;if(O=jT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,X),O instanceof jT.SchemaEnv&&(O=O.schema),O===void 0)throw new qH.default(s.opts.uriResolver,s.baseId,X)}let ie=(d=O?.properties)===null||d===void 0?void 0:d[a];if(typeof ie!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);y=y&&(h||v(O)),b(ie,$)}if(!y)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 ie of $.enum)x(ie,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}}}};_v.default=FH});var LT=I((ree,HH)=>{HH.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 wv=I((Be,bv)=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.MissingRefError=Be.ValidationError=Be.CodeGen=Be.Name=Be.nil=Be.stringify=Be.str=Be._=Be.KeywordCxt=Be.Ajv=void 0;var BH=NE(),GH=AT(),VH=MT(),DT=LT(),WH=["/properties"],Zu="http://json-schema.org/draft-07/schema",Qs=class extends BH.default{_addVocabularies(){super._addVocabularies(),GH.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(VH.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(DT,WH):DT;this.addMetaSchema(e,Zu,!1),this.refs["http://json-schema.org/schema"]=Zu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Zu)?Zu:void 0)}};Be.Ajv=Qs;bv.exports=Be=Qs;bv.exports.Ajv=Qs;Object.defineProperty(Be,"__esModule",{value:!0});Be.default=Qs;var JH=Ta();Object.defineProperty(Be,"KeywordCxt",{enumerable:!0,get:function(){return JH.KeywordCxt}});var ei=pe();Object.defineProperty(Be,"_",{enumerable:!0,get:function(){return ei._}});Object.defineProperty(Be,"str",{enumerable:!0,get:function(){return ei.str}});Object.defineProperty(Be,"stringify",{enumerable:!0,get:function(){return ei.stringify}});Object.defineProperty(Be,"nil",{enumerable:!0,get:function(){return ei.nil}});Object.defineProperty(Be,"Name",{enumerable:!0,get:function(){return ei.Name}});Object.defineProperty(Be,"CodeGen",{enumerable:!0,get:function(){return ei.CodeGen}});var KH=_u();Object.defineProperty(Be,"ValidationError",{enumerable:!0,get:function(){return KH.default}});var YH=Pa();Object.defineProperty(Be,"MissingRefError",{enumerable:!0,get:function(){return YH.default}})});var VT=I(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.formatNames=Yr.fastFormats=Yr.fullFormats=void 0;function Kr(t,e){return{validate:t,compare:e}}Yr.fullFormats={date:Kr(FT,kv),time:Kr(Sv(!0),Ev),"date-time":Kr(qT(!0),BT),"iso-time":Kr(Sv(),HT),"iso-date-time":Kr(qT(),GT),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:n9,"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:u9,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:o9,int32:{type:"number",validate:a9},int64:{type:"number",validate:c9},float:{type:"number",validate:UT},double:{type:"number",validate:UT},password:!0,binary:!0};Yr.fastFormats={...Yr.fullFormats,date:Kr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,kv),time:Kr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Ev),"date-time":Kr(/^\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,BT),"iso-time":Kr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,HT),"iso-date-time":Kr(/^\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,GT),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};Yr.formatNames=Object.keys(Yr.fullFormats);function XH(t){return t%4===0&&(t%100!==0||t%400===0)}var QH=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,e9=[0,31,28,31,30,31,30,31,31,30,31,30,31];function FT(t){let e=QH.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&&XH(r)?29:e9[n])}function kv(t,e){if(t&&e)return t>e?1:t<e?-1:0}var xv=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Sv(t){return function(r){let n=xv.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 Ev(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 HT(t,e){if(!(t&&e))return;let r=xv.exec(t),n=xv.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 $v=/t|\s/i;function qT(t){let e=Sv(t);return function(n){let o=n.split($v);return o.length===2&&FT(o[0])&&e(o[1])}}function BT(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function GT(t,e){if(!(t&&e))return;let[r,n]=t.split($v),[o,s]=e.split($v),i=kv(r,o);if(i!==void 0)return i||Ev(n,s)}var t9=/\/|:/,r9=/^(?:[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 n9(t){return t9.test(t)&&r9.test(t)}var ZT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function o9(t){return ZT.lastIndex=0,ZT.test(t)}var s9=-(2**31),i9=2**31-1;function a9(t){return Number.isInteger(t)&&t<=i9&&t>=s9}function c9(t){return Number.isInteger(t)}function UT(){return!0}var l9=/[^\\]\\Z/;function u9(t){if(l9.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var WT=I(ti=>{"use strict";Object.defineProperty(ti,"__esModule",{value:!0});ti.formatLimitDefinition=void 0;var p9=wv(),Nr=pe(),Hn=Nr.operators,Uu={formatMaximum:{okStr:"<=",ok:Hn.LTE,fail:Hn.GT},formatMinimum:{okStr:">=",ok:Hn.GTE,fail:Hn.LT},formatExclusiveMaximum:{okStr:"<",ok:Hn.LT,fail:Hn.GTE},formatExclusiveMinimum:{okStr:">",ok:Hn.GT,fail:Hn.LTE}},d9={message:({keyword:t,schemaCode:e})=>(0,Nr.str)`should be ${Uu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Nr._)`{comparison: ${Uu[t].okStr}, limit: ${e}}`};ti.formatLimitDefinition={keyword:Object.keys(Uu),type:"string",schemaType:"string",$data:!0,error:d9,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 p9.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,Nr._)`${f}[${c.schemaCode}]`);t.fail$data((0,Nr.or)((0,Nr._)`typeof ${d} != "object"`,(0,Nr._)`${d} instanceof RegExp`,(0,Nr._)`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,Nr._)`${i.code.formats}${(0,Nr.getProperty)(f)}`:void 0});t.fail$data(p(m))}function p(f){return(0,Nr._)`${f}.compare(${r}, ${n}) ${Uu[o].fail} 0`}},dependencies:["format"]};var f9=t=>(t.addKeyword(ti.formatLimitDefinition),t);ti.default=f9});var XT=I((Ua,YT)=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var ri=VT(),m9=WT(),Tv=pe(),JT=new Tv.Name("fullFormats"),h9=new Tv.Name("fastFormats"),Pv=(t,e={keywords:!0})=>{if(Array.isArray(e))return KT(t,e,ri.fullFormats,JT),t;let[r,n]=e.mode==="fast"?[ri.fastFormats,h9]:[ri.fullFormats,JT],o=e.formats||ri.formatNames;return KT(t,o,r,n),e.keywords&&(0,m9.default)(t),t};Pv.get=(t,e="full")=>{let n=(e==="fast"?ri.fastFormats:ri.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function KT(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Tv._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}YT.exports=Ua=Pv;Object.defineProperty(Ua,"__esModule",{value:!0});Ua.default=Pv});function g9(){let t=new QT.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,eP.default)(t),t}var QT,eP,Fu,tP=w(()=>{QT=ao(wv(),1),eP=ao(XT(),1);Fu=class{constructor(e){this._ajv=e??g9()}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 Hu,rP=w(()=>{Hu=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 nP(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 oP(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 sP=w(()=>{});var Bu,iP=w(()=>{fk();Ps();tP();da();rP();sP();Bu=class extends iu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(oa.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 Fu,this.setRequestHandler(ml,n=>this._oninitialize(n)),this.setNotificationHandler(Rh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(jh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=oa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Hu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=dk(this._capabilities,e)}setRequestHandler(e,r){let o=Nn(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(fr(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=An(Ts,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new q(G.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,f=await Promise.resolve(r(c,l));if(p.task){let m=An(ks,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new q(G.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let d=An(Rl,f);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new q(G.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){oP(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&nP(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:Ji.includes(r)?r:$h,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"},dl)}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},Lh,r):this.request({method:"sampling/createMessage",params:e},Mh,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},Ol,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},Ol,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new q(G.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(G.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},Dh,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 Rv(t){return!!t&&typeof t=="object"&&cP in t}function lP(t){return t[cP]?.complete}var cP,aP,uP=w(()=>{cP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(aP||(aP={}))});var pP=w(()=>{});function v9(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"),!y9.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 _9(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 Ov(t){let e=v9(t);return _9(t,e.warnings),e.isValid}var y9,dP=w(()=>{y9=/^[A-Za-z0-9._-]{1,128}$/});var Gu,fP=w(()=>{Gu=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 Vu=w(()=>{Gl();Gl()});function gP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function w9(t){return"_def"in t||"_zod"in t||gP(t)}function Cv(t){return typeof t!="object"||t===null||w9(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(gP)}function mP(t){if(t)return Cv(t)?qo(t):t}function x9(t){let e=Nn(t);return e?Object.entries(e).map(([r,n])=>{let o=P$(n),s=R$(n);return{name:r,description:o,required:!s}}):[]}function Bn(t){let r=Nn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Jl(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function hP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Wu,b9,Fa,yP=w(()=>{iP();da();jg();Ps();uP();pP();dP();fP();Vu();Wu=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 Bu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Gu(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Bn(Pl)),this.server.assertCanSetRequestHandler(Bn(Ts)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Pl,()=>({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=qs(r.inputSchema);return o?Ag(o,{strictUnions:!0,pipeStrategy:"input"}):b9})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=qs(r.outputSchema);o&&(n.outputSchema=Ag(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ts,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(G.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 q(G.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new q(G.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 q&&n.code===G.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=qs(e.inputSchema)??e.inputSchema,i=await Vl(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Wl(a);throw new q(G.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 q(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=qs(e.outputSchema),s=await Vl(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Wl(i);throw new q(G.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 q(G.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Bn(Cl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Cl,async e=>{switch(e.params.ref.type){case"ref/prompt":return FS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return HS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(G.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(G.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Fa;let s=Nn(n.argsSchema)?.[e.params.argument.name];if(!Rv(s))return Fa;let i=lP(s);if(!i)return Fa;let a=await i(e.params.argument.value,e.params.context);return hP(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 Fa;throw new q(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Fa;let s=await o(e.params.argument.value,e.params.context);return hP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Bn(Sl)),this.server.assertCanSetRequestHandler(Bn($l)),this.server.assertCanSetRequestHandler(Bn(kl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Sl,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($l,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(kl,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new q(G.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 q(G.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Bn(El)),this.server.assertCanSetRequestHandler(Bn(Tl)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(El,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?x9(r.argsSchema):void 0}))})),this.server.setRequestHandler(Tl,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=qs(n.argsSchema),s=await Vl(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Wl(c);throw new q(G.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:qo(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=qo(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 Vt?c._def?.innerType:c;return Rv(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Ov(e);let u={title:r,description:n,inputSchema:mP(o),outputSchema:mP(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"&&Ov(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=qo(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=qo(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];Cv(c)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Cv(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()}},b9={type:"object",properties:{}};Fa={completion:{values:[],hasMore:!1}}});function ni(){return`${Date.now()}-${++S9}`}function _r(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 Ue(t,e){if(!e)return!1;let r=new Date(t).getTime();return Date.now()>r+e}var S9,Xr=w(()=>{S9=0});var Ju,vP=w(()=>{Xr();Ju=class{entries=new Map;async get(e){let r=this.entries.get(e);return r?Ue(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(Ue(o.setAt,o.ttlMs)){this.entries.delete(o.key);continue}e&&!_r(e,o.key)||r&&o.category!==r||n.push(o)}return n}async getAll(){let e=[];for(let r of this.entries.values())Ue(r.setAt,r.ttlMs)||e.push(r);return e}async load(e){this.entries.clear();for(let r of e)Ue(r.setAt,r.ttlMs)||this.entries.set(r.key,r)}}});var Ku,_P=w(()=>{Xr();Ku=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"&&!Ue(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"&&Ue(r.claimedAt,r.ttlMs)&&(r.status="expired"),r):null}async list(e){let r=[];for(let n of this.claims.values())n.status==="active"&&Ue(n.claimedAt,n.ttlMs)&&(n.status="expired"),n.status==="active"&&(e&&!_r(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 Yu,bP=w(()=>{Yu=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 Xu,wP=w(()=>{Xr();Xu=class{discoveries=[];eventStore;constructor(e){this.eventStore=e}async publish(e,r,n,o){let s={id:ni(),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 $9}from"node:crypto";var Gn,Qu=w(()=>{Gn=class{messages=[];async send(e,r,n,o){let s={id:$9(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 k9}from"node:crypto";var Vn,ep=w(()=>{Vn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:k9(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 Wn,tp=w(()=>{Wn=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 E9}from"node:crypto";var Jn,rp=w(()=>{Jn=class{conflicts=new Map;eventStore;constructor(e){this.eventStore=e}async flag(e,r,n,o){let s={id:E9(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 Kn,np=w(()=>{Kn=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 T9}from"node:crypto";var Yn,op=w(()=>{Yn=class{proposals=new Map;eventStore;constructor(e){this.eventStore=e}async propose(e,r,n,o){let s={id:T9(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 Xn,sp=w(()=>{Xn=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 Qn,ip=w(()=>{Qn=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 eo,ap=w(()=>{eo=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 xP(){let t=new Yu,e=new Ju,r=new Ku(t),n=new Xu(t),o=new Gn,s=new Vn(t),i=new Wn,a=new Jn(t),c=new Kn,l=new Yn(t),u=new Xn(t),p=new Qn(t),f=new eo;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 Iv(t,e={}){let r=e.agentId??"agent_default",n=e.namespace&&e.namespace!=="default"?`@${e.namespace}`:"",o=new Wu({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:L.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:L.string().describe("The state key to write"),value:L.unknown().describe("The value to store (any JSON-serializable value)"),category:L.string().optional().describe('Optional category for grouping (e.g. "config", "progress")'),ttlMs:L.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:L.string().optional().describe('Glob pattern to match keys (e.g. "agent_*", "config.*")'),category:L.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:L.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:L.string().describe("Resource identifier (e.g. file path, variable name, function name)"),value:L.string().describe("What you plan to do with the resource"),ttlMs:L.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:L.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:L.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:L.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:L.string().describe('Event type (e.g. "conflict", "completed", "blocker", "warning")'),data:L.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:L.number().optional().describe("Cursor from previous call (omit for all events)"),type:L.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:L.string().describe("Short topic/title for the discovery"),content:L.string().describe("Detailed content of the discovery"),category:L.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:L.string().optional().describe("Text search query (searches topic and content)"),category:L.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:L.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 y=await jd(l,t,s()),v=Oc(l,p,h),b=Ld(l,p,h,y),x={};for(let[ie,X]of Object.entries(l.phases))x[ie]={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:y,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:L.string().describe("Why the halt is being requested"),status:L.enum(["completed","failed"]).optional().describe("Whether this is a successful completion or failure (default: completed)"),target:L.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:L.string().describe("Why the pause is being requested"),target:L.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:L.string().describe("Why the agent/protocol is being resumed"),target:L.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:L.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:L.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 Av=w(()=>{yP();Vu();vP();_P();bP();wP();Qu();ep();tp();rp();np();op();sp();ip();ap();Ti()});import{createRequire as R9}from"node:module";function SP(t){let r=R9(import.meta.url)("@honeybee-ai/carapace");return t&&console.error("[incubator] carapace loaded"),r}function oi(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 Ha(o);if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}}function Yo(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 Xo(t){return typeof t=="string"?t:t==null?"":JSON.stringify(t)}function $P(t,e,r){return{state:{...t.state,set:async(n,o,s,i,a)=>(oi(e,[n,Xo(o),i],r),t.state.set(n,o,s,i,a)),get:async n=>{let o=await t.state.get(n);return!o||!Yo(e,[o.key,Xo(o.value),o.category],r)?null:o},query:async(n,o)=>(await t.state.query(n,o)).filter(i=>Yo(e,[i.key,Xo(i.value),i.category],r))},events:{...t.events,publish:async(n,o,s)=>(oi(e,[n,Xo(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=>Yo(e,[i.type,Xo(i.data)],r)),cursor:s.cursor}}},claims:{...t.claims,claim:async(n,o,s,i)=>(oi(e,[n,o],r),t.claims.claim(n,o,s,i)),check:async n=>{let o=await t.claims.check(n);return!o||!Yo(e,[o.resource,o.value],r)?null:o},list:async n=>(await t.claims.list(n)).filter(s=>Yo(e,[s.resource,s.value],r))},discoveries:{...t.discoveries,publish:async(n,o,s,i)=>(oi(e,[n,o,i],r),t.discoveries.publish(n,o,s,i)),search:async(n,o)=>(await t.discoveries.search(n,o)).filter(i=>Yo(e,[i.topic,i.content,i.category],r))},messages:{...t.messages,send:async(n,o,s,i)=>(oi(e,[s],r),t.messages.send(n,o,s,i))},help:{...t.help,request:async(n,o,s,i)=>(oi(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 kP(t,e,r){let n=0,o=(s,i)=>s.filter(a=>Yo(e,i(a),r)?!0:(n++,!1));return t.state=o(t.state,s=>[s.key,Xo(s.value),s.category]),t.claims=o(t.claims,s=>[s.resource,s.value]),t.events=o(t.events,s=>[s.type,Xo(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 Ha,cp=w(()=>{Ha=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 O9(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?O9(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 Ye(t,e){let r=e.agentId??t.headers["x-agent-id"]??"rest_anonymous";return r.startsWith("honeycomb:")?"rest_anonymous":r}async function I9(t){return t.method==="GET"?{}:new Promise((e,r)=>{let n="",o=0;t.on("data",s=>{if(o+=s.length,o>C9){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 z9(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(A9.has(n))return{namespace:"default",rewrittenPath:t};let o=r===-1?"":e.slice(r);return{namespace:n,rewrittenPath:`/api${o}`}}async function EP(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 I9(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),y=await h.state.query(),v=await h.claims.list(),b=await h.events.getEvents(),x=await h.discoveries.search();d.push({name:m,state:y.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}=z9(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 fo(s.spec);else if(s.acp&&s.name)d=await fo(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 y of Object.values(h.roles))y?.description&&m.push(String(y.description)),y?.instructions&&m.push(String(y.instructions));if(h.phases&&typeof h.phases=="object")for(let y of Object.values(h.phases))y?.description&&m.push(String(y.description));if(m.length>0){let y=`__spec_scan_${Date.now()}`;await u.state.set(y,m.join(" "),Ye(t,s),"__scan"),await u.state.delete(y)}r.setProtocol(c,d),R(e,200,{loaded:!0,name:d.name,title:d.title})}catch(d){d instanceof po?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 y=m?.match(/^publish\/(.+)$/);if(t.method==="DELETE"&&y){let v=decodeURIComponent(y[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 N9){if(t.method!==d.method)continue;let m=l.match(d.pattern);if(m){if(n){let h=new Date().toISOString().slice(11,23),y=Ye(t,s),v=c==="default"?"":`@${c}`;console.error(` ${h} [${y}${v}] REST ${t.method} ${i}`)}try{await d.handler(t,e,u,m,s)}catch(h){if(h instanceof Ha)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 C9,A9,N9,TP=w(()=>{cp();Ti();C9=1024*1024;A9=new Set(["state","claims","events","discoveries","health","protocol","messages","help","progress","conflicts","roles","reinforcements","governance","control","topics","runs"]),N9=[{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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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=Ye(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 j9}from"node:module";import{resolve as M9}from"node:path";function RP(t){let e=t===":memory:"?t:M9(t),r=PP.get(e);if(r)return r;let o=j9(import.meta.url)("better-sqlite3"),s=new o(e);return s.pragma("journal_mode = WAL"),L9(s),e!==":memory:"&&PP.set(e,s),s}function L9(t){t.exec(`
296
297
  CREATE TABLE IF NOT EXISTS state (
297
298
  namespace TEXT NOT NULL,
298
299
  key TEXT NOT NULL,
@@ -346,7 +347,7 @@ data:
346
347
  CREATE INDEX IF NOT EXISTS idx_events_ns_type ON events (namespace, type);
347
348
  CREATE INDEX IF NOT EXISTS idx_claims_ns_status ON claims (namespace, status);
348
349
  CREATE INDEX IF NOT EXISTS idx_discoveries_ns_cat ON discoveries (namespace, category);
349
- `)}var qP,UP=w(()=>{qP=new Map});var pp,FP=w(()=>{Jr();pp=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 Ue(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
+ `)}var PP,OP=w(()=>{PP=new Map});var lp,CP=w(()=>{Xr();lp=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 Ue(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
351
  INSERT INTO state (namespace, key, value, category, set_by, set_at, updated_at, ttl_ms)
351
352
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
352
353
  ON CONFLICT(namespace, key) DO UPDATE SET
@@ -355,7 +356,7 @@ data:
355
356
  set_by = excluded.set_by,
356
357
  updated_at = excluded.updated_at,
357
358
  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(Ue(c.setAt,c.ttlMs)){this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,c.key);continue}e&&!yr(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=>!Ue(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)Ue(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 dp,HP=w(()=>{dp=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 fp,BP=w(()=>{Jr();fp=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"&&!Ue(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
+ `).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(Ue(c.setAt,c.ttlMs)){this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,c.key);continue}e&&!_r(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=>!Ue(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)Ue(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 up,IP=w(()=>{up=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 pp,AP=w(()=>{Xr();pp=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"&&!Ue(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
360
  INSERT INTO claims (namespace, resource, value, owner, status, claimed_at, ttl_ms)
360
361
  VALUES (?, ?, ?, ?, 'active', ?, ?)
361
362
  ON CONFLICT(namespace, resource) DO UPDATE SET
@@ -364,7 +365,7 @@ data:
364
365
  status = excluded.status,
365
366
  claimed_at = excluded.claimed_at,
366
367
  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"&&Ue(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(Ue(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&&!yr(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 mp,GP=w(()=>{Jr();mp=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=oi(),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 VP(t,e){let r=ZP(t),n=new dp(r,e),o=new pp(r,e),s=new fp(r,e,n),i=new mp(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 WP=w(()=>{UP();FP();HP();BP();GP();tp();rp();np();op();sp();ip();ap();cp();lp()});var hp,JP=w(()=>{Jr();hp=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 Ue(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(Ue(i.setAt,i.ttlMs)){await this.client.hdel(this.hashKey,i.key);continue}e&&!yr(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);Ue(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)Ue(n.setAt,n.ttlMs)||(r[n.key]=JSON.stringify(n));Object.keys(r).length>0&&await this.client.hset(this.hashKey,r)}}});var gp,KP=w(()=>{gp=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 yp,YP=w(()=>{Jr();yp=class t{client;hashKey;eventStore;constructor(e,r,n){this.client=e,this.hashKey=`incubator:${r}:claims`,this.eventStore=n}static CLAIM_SCRIPT=`
368
+ `).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"&&Ue(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(Ue(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&&!_r(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 dp,NP=w(()=>{Xr();dp=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=ni(),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 zP(t,e){let r=RP(t),n=new up(r,e),o=new lp(r,e),s=new pp(r,e,n),i=new dp(r,e,n),a=new Gn,c=new Vn(n),l=new Wn,u=new Jn(n),p=new Kn,f=new Yn(n),d=new Xn(n),m=new Qn(n),h=new eo;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 jP=w(()=>{OP();CP();IP();AP();NP();Qu();ep();tp();rp();np();op();sp();ip();ap()});var fp,MP=w(()=>{Xr();fp=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 Ue(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(Ue(i.setAt,i.ttlMs)){await this.client.hdel(this.hashKey,i.key);continue}e&&!_r(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);Ue(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)Ue(n.setAt,n.ttlMs)||(r[n.key]=JSON.stringify(n));Object.keys(r).length>0&&await this.client.hset(this.hashKey,r)}}});var mp,LP=w(()=>{mp=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 hp,DP=w(()=>{Xr();hp=class t{client;hashKey;eventStore;constructor(e,r,n){this.client=e,this.hashKey=`incubator:${r}:claims`,this.eventStore=n}static CLAIM_SCRIPT=`
368
369
  local raw = redis.call('HGET', KEYS[1], ARGV[1])
369
370
  if raw then
370
371
  local existing = cjson.decode(raw)
@@ -387,28 +388,28 @@ data:
387
388
  end
388
389
  redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
389
390
  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"&&Ue(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"&&Ue(s.claimedAt,s.ttlMs)){s.status="expired",await this.client.hset(this.hashKey,s.resource,JSON.stringify(s));continue}s.status==="active"&&(e&&!yr(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 vp,XP=w(()=>{Jr();vp=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:oi(),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 QP(t,e){let r=new gp(t,e),n=new hp(t,e),o=new yp(t,e,r),s=new vp(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 eR=w(()=>{JP();KP();YP();XP();tp();rp();np();op();sp();ip();ap();cp();lp()});function tR(t){if(t.type==="memory")return NP();if(t.type==="sqlite"){if(!t.dbPath)throw new Error("SQLite backend requires dbPath");return VP(t.dbPath,t.namespace??"default")}if(t.type==="redis"){if(!t.redisClient)throw new Error("Redis backend requires redisClient");return QP(t.redisClient,t.namespace??"default")}throw new Error(`Unknown backend type: ${t.type}`)}var rR=w(()=>{Zv();WP();eR()});var Uv,_p,nR=w(()=>{Uv="honeycomb:",_p=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(Uv))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},`${Uv}${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=`${Uv}${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 oB(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 nB,bp,oR=w(()=>{rR();up();nR();nB=new Set(["_ns"]);bp=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 _p(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(nB.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=tR({...this.backendConfig,namespace:e}),this.bus&&oB(r,this.bus,e),this.guard&&(r=jP(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 sB,writeFileSync as iB,mkdirSync as aB,readdirSync as cB}from"node:fs";import{dirname as sR,basename as lB,join as uB}from"node:path";async function pB(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()};aB(sR(t),{recursive:!0}),iB(t,JSON.stringify(r,null,2),{mode:384})}async function dB(t,e,r){try{let n=sB(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 wp(t,e){for(let r of e.list()){let n=`${t}.${r}.json`;await pB(n,e.get(r))}}async function iR(t,e,r){let n=sR(t),o=lB(t)+".",s=".json",i=0;try{let a=cB(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 dB(uB(n,c),u,r)&&i++}}catch{}return i}var aR=w(()=>{});import{EventEmitter as fB}from"node:events";var xp,Sp,cR=w(()=>{xp=class{emitter=new fB;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()}},Sp=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 Fv(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 Hv=w(()=>{});var Ga,lR=w(()=>{Hv();Ga=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 Fv(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 mB,writeFileSync as Xre,mkdirSync as Qre,existsSync as hB}from"node:fs";import{join as uR}from"node:path";import{homedir as gB}from"node:os";function yB(){return uR(gB(),".config","honeybee")}function vB(){return uR(yB(),"integrations.json")}function Bv(){let t=vB();if(!hB(t))return{};try{return JSON.parse(mB(t,"utf8"))}catch{return{}}}var pR=w(()=>{});var dR=w(()=>{lR();Hv();pR()});var $p,fR=w(()=>{$p=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 ii={};V(ii,{buildAcpHelper:()=>Vv,callDanceTool:()=>Wv,danceToolDefs:()=>Gv,loadDances:()=>_B,runInject:()=>Jv});async function _B(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 Gv(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 Vv(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 Wv(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 Jv(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 Qo=w(()=>{});import{resolve as mR,relative as bB}from"node:path";function vr(t,e){let r=mR(t,e),n=bB(t,r);if(n.startsWith("..")||mR(n)===n)throw new Error(`Path "${e}" escapes the working directory`);return r}var kp=w(()=>{});function qt(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 Va=w(()=>{});function pt(t){return{content:[{type:"text",text:typeof t=="string"?t:JSON.stringify(t)}]}}function ke(t){return pt({error:t})}var Wa=w(()=>{});import{readFile as Yv,writeFile as hR,readdir as Xv,mkdir as wB,stat as gR}from"node:fs/promises";import{join as Qv,relative as e_,dirname as xB}from"node:path";async function yR(t,e,r,n){let o=qt(r,[t.path],n);if(o)return ke(o);try{let s=vr(e,t.path),i=await gR(s);if(i.size>Kv)return ke(`File too large (${Math.round(i.size/1024)}KB, max ${Kv/1024}KB)`);let a=await Yv(s,"utf-8");return pt(a)}catch(s){return ke(s.message)}}async function vR(t,e,r,n){let o=qt(r,[t.path,t.content],n);if(o)return ke(o);try{let s=vr(e,t.path);return await wB(xB(s),{recursive:!0}),await hR(s,t.content,"utf-8"),pt({success:!0,path:t.path,bytes:Buffer.byteLength(t.content)})}catch(s){return ke(s.message)}}async function _R(t,e,r,n){let o=qt(r,[t.path,t.search,t.replace],n);if(o)return ke(o);try{let s=vr(e,t.path),i=await Yv(s,"utf-8");if(!i.includes(t.search))return ke(`Search string not found in ${t.path}`);let a=i.replace(t.search,t.replace);return await hR(s,a,"utf-8"),pt({success:!0,path:t.path})}catch(s){return ke(s.message)}}async function bR(t,e,r,n){let o=qt(r,[t.path],n);if(o)return ke(o);try{let s=t.path?vr(e,t.path):e,i=[];async function a(c){if(i.length>=Ja)return;let l=await Xv(c,{withFileTypes:!0});for(let u of l){if(i.length>=Ja)return;if(t_.has(u.name))continue;let p=Qv(c,u.name),f=e_(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>=Ja})}catch(s){return ke(s.message)}}async function wR(t,e,r,n){let o=qt(r,[t.pattern,t.path],n);if(o)return ke(o);try{let s=t.path?vr(e,t.path):e,i=await SB(s,e,t.pattern);return pt({matches:i,count:i.length})}catch(s){return ke(s.message)}}async function SB(t,e,r){let n=[],o=xR(r);async function s(i){if(n.length>=Ja)return;let a;try{a=await Xv(i,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Ja)return;if(t_.has(c.name))continue;let l=Qv(i,c.name),u=e_(e,l);o.test(u)&&n.push(u),c.isDirectory()&&await s(l)}}return await s(t),n}function xR(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 SR(t,e,r,n){let o=qt(r,[t.pattern,t.path,t.glob],n);if(o)return ke(o);try{let s=t.path?vr(e,t.path):e,i=new RegExp(t.pattern),a=t.glob?xR(t.glob):null,c=[],l=200;async function u(p){if(c.length>=l)return;let f;try{f=await Xv(p,{withFileTypes:!0})}catch{return}for(let d of f){if(c.length>=l)return;if(t_.has(d.name))continue;let m=Qv(p,d.name);if(d.isDirectory())await u(m);else if(d.isFile()){let h=e_(e,m);if(a&&!a.test(h))continue;try{if((await gR(m)).size>Kv)continue;let b=(await Yv(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 ke(s.message)}}var Kv,Ja,t_,$R=w(()=>{kp();Va();Wa();Kv=500*1024,Ja=1e3,t_=new Set([".git","node_modules",".next","__pycache__",".cache","dist","build"])});import{exec as $B}from"node:child_process";async function kR(t,e,r,n){let o=qt(r,[t.command],n);if(o)return ke(o);let s=t.cwd?vr(e,t.cwd):e,i=t.timeout??kB;return new Promise(a=>{let c=$B(t.command,{cwd:s,timeout:i,maxBuffer:r_,env:{...process.env,HOME:process.env.HOME}},(l,u,p)=>{let f=u||"";if(p&&(f+=(f?`
391
+ `;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"&&Ue(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"&&Ue(s.claimedAt,s.ttlMs)){s.status="expired",await this.client.hset(this.hashKey,s.resource,JSON.stringify(s));continue}s.status==="active"&&(e&&!_r(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 gp,qP=w(()=>{Xr();gp=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:ni(),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 ZP(t,e){let r=new mp(t,e),n=new fp(t,e),o=new hp(t,e,r),s=new gp(t,e,r),i=new Gn,a=new Vn(r),c=new Wn,l=new Jn(r),u=new Kn,p=new Yn(r),f=new Xn(r),d=new Qn(r),m=new eo;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 UP=w(()=>{MP();LP();DP();qP();Qu();ep();tp();rp();np();op();sp();ip();ap()});function FP(t){if(t.type==="memory")return xP();if(t.type==="sqlite"){if(!t.dbPath)throw new Error("SQLite backend requires dbPath");return zP(t.dbPath,t.namespace??"default")}if(t.type==="redis"){if(!t.redisClient)throw new Error("Redis backend requires redisClient");return ZP(t.redisClient,t.namespace??"default")}throw new Error(`Unknown backend type: ${t.type}`)}var HP=w(()=>{Av();jP();UP()});var Nv,yp,BP=w(()=>{Nv="honeycomb:",yp=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(Nv))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},`${Nv}${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=`${Nv}${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 q9(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 D9,vp,GP=w(()=>{HP();cp();BP();D9=new Set(["_ns"]);vp=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 yp(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(D9.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=FP({...this.backendConfig,namespace:e}),this.bus&&q9(r,this.bus,e),this.guard&&(r=$P(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 Z9,writeFileSync as U9,mkdirSync as F9,readdirSync as H9}from"node:fs";import{dirname as VP,basename as B9,join as G9}from"node:path";async function V9(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()};F9(VP(t),{recursive:!0}),U9(t,JSON.stringify(r,null,2),{mode:384})}async function W9(t,e,r){try{let n=Z9(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 _p(t,e){for(let r of e.list()){let n=`${t}.${r}.json`;await V9(n,e.get(r))}}async function WP(t,e,r){let n=VP(t),o=B9(t)+".",s=".json",i=0;try{let a=H9(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 W9(G9(n,c),u,r)&&i++}}catch{}return i}var JP=w(()=>{});import{EventEmitter as J9}from"node:events";var bp,wp,KP=w(()=>{bp=class{emitter=new J9;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()}},wp=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 zv(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 jv=w(()=>{});var Ba,YP=w(()=>{jv();Ba=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 zv(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 K9,writeFileSync as Ire,mkdirSync as Are,existsSync as Y9}from"node:fs";import{join as XP}from"node:path";import{homedir as X9}from"node:os";function Q9(){return XP(X9(),".config","honeybee")}function eB(){return XP(Q9(),"integrations.json")}function Mv(){let t=eB();if(!Y9(t))return{};try{return JSON.parse(K9(t,"utf8"))}catch{return{}}}var QP=w(()=>{});var eR=w(()=>{YP();jv();QP()});var xp,tR=w(()=>{xp=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 si={};V(si,{buildAcpHelper:()=>Dv,callDanceTool:()=>qv,danceToolDefs:()=>Lv,loadDances:()=>tB,runInject:()=>Zv});async function tB(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 Lv(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 Dv(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 qv(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 Zv(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 Qo=w(()=>{});import{resolve as rR,relative as rB}from"node:path";function br(t,e){let r=rR(t,e),n=rB(t,r);if(n.startsWith("..")||rR(n)===n)throw new Error(`Path "${e}" escapes the working directory`);return r}var Sp=w(()=>{});function Ut(t,e,r){if(!t)return null;let n=e.filter(Boolean).join(`
392
+ `);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 Ga=w(()=>{});function dt(t){return{content:[{type:"text",text:typeof t=="string"?t:JSON.stringify(t)}]}}function ke(t){return dt({error:t})}var Va=w(()=>{});import{readFile as Fv,writeFile as nR,readdir as Hv,mkdir as nB,stat as oR}from"node:fs/promises";import{join as Bv,relative as Gv,dirname as oB}from"node:path";async function sR(t,e,r,n){let o=Ut(r,[t.path],n);if(o)return ke(o);try{let s=br(e,t.path),i=await oR(s);if(i.size>Uv)return ke(`File too large (${Math.round(i.size/1024)}KB, max ${Uv/1024}KB)`);let a=await Fv(s,"utf-8");return dt(a)}catch(s){return ke(s.message)}}async function iR(t,e,r,n){let o=Ut(r,[t.path,t.content],n);if(o)return ke(o);try{let s=br(e,t.path);return await nB(oB(s),{recursive:!0}),await nR(s,t.content,"utf-8"),dt({success:!0,path:t.path,bytes:Buffer.byteLength(t.content)})}catch(s){return ke(s.message)}}async function aR(t,e,r,n){let o=Ut(r,[t.path,t.search,t.replace],n);if(o)return ke(o);try{let s=br(e,t.path),i=await Fv(s,"utf-8");if(!i.includes(t.search))return ke(`Search string not found in ${t.path}`);let a=i.replace(t.search,t.replace);return await nR(s,a,"utf-8"),dt({success:!0,path:t.path})}catch(s){return ke(s.message)}}async function cR(t,e,r,n){let o=Ut(r,[t.path],n);if(o)return ke(o);try{let s=t.path?br(e,t.path):e,i=[];async function a(c){if(i.length>=Wa)return;let l=await Hv(c,{withFileTypes:!0});for(let u of l){if(i.length>=Wa)return;if(Vv.has(u.name))continue;let p=Bv(c,u.name),f=Gv(e,p);i.push(u.isDirectory()?f+"/":f),u.isDirectory()&&t.recursive&&await a(p)}}return await a(s),dt({entries:i,count:i.length,truncated:i.length>=Wa})}catch(s){return ke(s.message)}}async function lR(t,e,r,n){let o=Ut(r,[t.pattern,t.path],n);if(o)return ke(o);try{let s=t.path?br(e,t.path):e,i=await sB(s,e,t.pattern);return dt({matches:i,count:i.length})}catch(s){return ke(s.message)}}async function sB(t,e,r){let n=[],o=uR(r);async function s(i){if(n.length>=Wa)return;let a;try{a=await Hv(i,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Wa)return;if(Vv.has(c.name))continue;let l=Bv(i,c.name),u=Gv(e,l);o.test(u)&&n.push(u),c.isDirectory()&&await s(l)}}return await s(t),n}function uR(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 pR(t,e,r,n){let o=Ut(r,[t.pattern,t.path,t.glob],n);if(o)return ke(o);try{let s=t.path?br(e,t.path):e,i=new RegExp(t.pattern),a=t.glob?uR(t.glob):null,c=[],l=200;async function u(p){if(c.length>=l)return;let f;try{f=await Hv(p,{withFileTypes:!0})}catch{return}for(let d of f){if(c.length>=l)return;if(Vv.has(d.name))continue;let m=Bv(p,d.name);if(d.isDirectory())await u(m);else if(d.isFile()){let h=Gv(e,m);if(a&&!a.test(h))continue;try{if((await oR(m)).size>Uv)continue;let b=(await Fv(m,"utf-8")).split(`
393
+ `);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),dt({matches:c,count:c.length,truncated:c.length>=l})}catch(s){return ke(s.message)}}var Uv,Wa,Vv,dR=w(()=>{Sp();Ga();Va();Uv=500*1024,Wa=1e3,Vv=new Set([".git","node_modules",".next","__pycache__",".cache","dist","build"])});import{exec as iB}from"node:child_process";async function fR(t,e,r,n){let o=Ut(r,[t.command],n);if(o)return ke(o);let s=t.cwd?br(e,t.cwd):e,i=t.timeout??aB;return new Promise(a=>{let c=iB(t.command,{cwd:s,timeout:i,maxBuffer:Wv,env:{...process.env,HOME:process.env.HOME}},(l,u,p)=>{let f=u||"";if(p&&(f+=(f?`
393
394
  --- stderr ---
394
- `:"")+p),f.length>r_&&(f=f.slice(0,r_)+`
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 kB,r_,ER=w(()=>{kp();Va();Wa();kB=6e4,r_=100*1024});import{exec as TR}from"node:child_process";function Ka(t,e){return new Promise((r,n)=>{TR(t,{cwd:e,timeout:3e4},(o,s,i)=>{if(o){n(new Error(i.trim()||o.message));return}r(s.trim())})})}async function PR(t,e){try{let r=await Ka("git status --porcelain",e);return pt(r||"(clean)")}catch(r){return ke(r.message)}}async function RR(t,e,r,n){let o=qt(r,[t.path],n);if(o)return ke(o);try{let s="git diff";if(t.staged&&(s+=" --staged"),t.path){let a=vr(e,t.path);s+=` -- "${a}"`}let i=await Ka(s,e);return pt(i||"(no diff)")}catch(s){return ke(s.message)}}async function OR(t,e,r,n){let o=qt(r,[t.message,t.files],n);if(o)return ke(o);try{if(t.files){let i=t.files.split(",").map(a=>a.trim()).filter(Boolean);for(let a of i){let c=vr(e,a);await Ka(`git add "${c}"`,e)}}else await Ka("git add -A",e);let s=await new Promise((i,a)=>{let c=TR("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 ke(s.message)}}async function CR(t,e){try{let r=t.count??10,n=await Ka(`git log --oneline -n ${r}`,e);return pt(n||"(no commits)")}catch(r){return ke(r.message)}}var IR=w(()=>{kp();Va();Wa()});function AR(t){try{let e=new URL(t);return TB.test(e.hostname)||EB.test(e.hostname)}catch{return!0}}async function NR(t,e,r,n){let{url:o,method:s="GET",headers:i={},body:a}=t;if(AR(o))return ke("Blocked: cannot fetch localhost or private IP addresses");let c=qt(r,[o,a],n);if(c)return ke(c);try{let l=new AbortController,u=setTimeout(()=>l.abort(),Ep),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>ai){m.cancel(),f.push(Buffer.from(b.slice(0,ai-(d-b.length))));break}f.push(Buffer.from(b))}let h=Buffer.concat(f).toString("utf-8"),y={};return p.headers.forEach((v,b)=>{y[b]=v}),pt({status:p.status,headers:y,body:h,truncated:d>ai})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("abort")?ke(`Request timed out after ${Ep/1e3}s`):ke(`Fetch failed: ${u}`)}}async function zR(t,e,r,n){let{url:o}=t;if(AR(o))return ke("Blocked: cannot scrape localhost or private IP addresses");let s=qt(r,[o],n);if(s)return ke(s);try{let i=new AbortController,a=setTimeout(()=>i.abort(),Ep),c=await fetch(o,{headers:{Accept:"text/html,application/xhtml+xml,*/*"},signal:i.signal});if(clearTimeout(a),!c.ok)return ke(`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>ai){p.cancel(),l.push(Buffer.from(h.slice(0,ai-(u-h.length))));break}l.push(Buffer.from(h))}let f=Buffer.concat(l).toString("utf-8"),d=PB(f);return pt({url:o,status:c.status,text:d,truncated:u>ai})}catch(i){let a=i instanceof Error?i.message:String(i);return a.includes("abort")?ke(`Request timed out after ${Ep/1e3}s`):ke(`Scrape failed: ${a}`)}}function PB(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,`
395
+ `:"")+p),f.length>Wv&&(f=f.slice(0,Wv)+`
396
+ ... (output truncated)`),l){let d=l.code;a(dt({exitCode:typeof d=="number"?d:1,output:f,error:l.killed?"Command timed out":l.message}));return}a(dt({exitCode:0,output:f}))});setTimeout(()=>{c.kill("SIGKILL")},i+1e3)})}var aB,Wv,mR=w(()=>{Sp();Ga();Va();aB=6e4,Wv=100*1024});import{exec as hR}from"node:child_process";function Ja(t,e){return new Promise((r,n)=>{hR(t,{cwd:e,timeout:3e4},(o,s,i)=>{if(o){n(new Error(i.trim()||o.message));return}r(s.trim())})})}async function gR(t,e){try{let r=await Ja("git status --porcelain",e);return dt(r||"(clean)")}catch(r){return ke(r.message)}}async function yR(t,e,r,n){let o=Ut(r,[t.path],n);if(o)return ke(o);try{let s="git diff";if(t.staged&&(s+=" --staged"),t.path){let a=br(e,t.path);s+=` -- "${a}"`}let i=await Ja(s,e);return dt(i||"(no diff)")}catch(s){return ke(s.message)}}async function vR(t,e,r,n){let o=Ut(r,[t.message,t.files],n);if(o)return ke(o);try{if(t.files){let i=t.files.split(",").map(a=>a.trim()).filter(Boolean);for(let a of i){let c=br(e,a);await Ja(`git add "${c}"`,e)}}else await Ja("git add -A",e);let s=await new Promise((i,a)=>{let c=hR("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 dt({success:!0,output:s})}catch(s){return ke(s.message)}}async function _R(t,e){try{let r=t.count??10,n=await Ja(`git log --oneline -n ${r}`,e);return dt(n||"(no commits)")}catch(r){return ke(r.message)}}var bR=w(()=>{Sp();Ga();Va()});function wR(t){try{let e=new URL(t);return lB.test(e.hostname)||cB.test(e.hostname)}catch{return!0}}async function xR(t,e,r,n){let{url:o,method:s="GET",headers:i={},body:a}=t;if(wR(o))return ke("Blocked: cannot fetch localhost or private IP addresses");let c=Ut(r,[o,a],n);if(c)return ke(c);try{let l=new AbortController,u=setTimeout(()=>l.abort(),$p),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>ii){m.cancel(),f.push(Buffer.from(b.slice(0,ii-(d-b.length))));break}f.push(Buffer.from(b))}let h=Buffer.concat(f).toString("utf-8"),y={};return p.headers.forEach((v,b)=>{y[b]=v}),dt({status:p.status,headers:y,body:h,truncated:d>ii})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("abort")?ke(`Request timed out after ${$p/1e3}s`):ke(`Fetch failed: ${u}`)}}async function SR(t,e,r,n){let{url:o}=t;if(wR(o))return ke("Blocked: cannot scrape localhost or private IP addresses");let s=Ut(r,[o],n);if(s)return ke(s);try{let i=new AbortController,a=setTimeout(()=>i.abort(),$p),c=await fetch(o,{headers:{Accept:"text/html,application/xhtml+xml,*/*"},signal:i.signal});if(clearTimeout(a),!c.ok)return ke(`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>ii){p.cancel(),l.push(Buffer.from(h.slice(0,ii-(u-h.length))));break}l.push(Buffer.from(h))}let f=Buffer.concat(l).toString("utf-8"),d=uB(f);return dt({url:o,status:c.status,text:d,truncated:u>ii})}catch(i){let a=i instanceof Error?i.message:String(i);return a.includes("abort")?ke(`Request timed out after ${$p/1e3}s`):ke(`Scrape failed: ${a}`)}}function uB(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
397
  `).replace(/<br\s*\/?>/gi,`
397
398
  `).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
399
 
399
- `).trim()}var EB,TB,ai,Ep,jR=w(()=>{Wa();Va();EB=/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.|169\.254\.|::1|fc|fd|fe80)/i,TB=/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])/i;ai=512*1024,Ep=3e4});function n_(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:L.string().describe("File path relative to working directory")},handler:n=>yR(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:L.string().describe("File path relative to working directory"),content:L.string().describe("Content to write")},handler:n=>vR(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:L.string().describe("File path relative to working directory"),search:L.string().describe("Exact text to find"),replace:L.string().describe("Text to replace with")},handler:n=>_R(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:L.string().optional().describe("Directory path relative to working directory (default: root)"),recursive:L.boolean().optional().describe("List recursively (default: false)")},handler:n=>bR(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:L.string().describe("Glob pattern to match"),path:L.string().optional().describe("Base directory for the search")},handler:n=>wR(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:L.string().describe("Regex pattern to search for"),path:L.string().optional().describe("Directory to search in"),glob:L.string().optional().describe('File glob filter (e.g. "*.ts")')},handler:n=>SR(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:L.string().describe("Shell command to execute"),cwd:L.string().optional().describe("Working directory relative to sandbox root"),timeout:L.number().optional().describe("Timeout in milliseconds (default: 60000)")},handler:n=>kR(n,t,e,r)},{def:{type:"function",function:{name:"git_status",description:"Show git status (porcelain format)",parameters:{type:"object",properties:{},required:[]}}},schema:{},handler:()=>PR({},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:L.string().optional().describe("File path to diff"),staged:L.boolean().optional().describe("Show staged changes")},handler:n=>RR(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:L.string().describe("Commit message"),files:L.string().optional().describe("Comma-separated file paths to stage (default: all)")},handler:n=>OR(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:L.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:L.string().describe("URL to fetch"),method:L.string().optional().describe("HTTP method (default: GET)"),body:L.string().optional().describe("Request body (for POST/PUT/PATCH)")},handler:n=>NR(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:L.string().describe("URL of the page to scrape")},handler:n=>zR(n,t,e,r)}]}var o_=w(()=>{Ju();$R();ER();IR();jR()});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 LR=w(()=>{o_()});function s_(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 DR=w(()=>{});function i_(t){let e=typeof t.data=="string"?t.data:JSON.stringify(t.data);return`Event from ${t.publishedBy}: [${t.type}] ${e}`}var Tp,qR=w(()=>{Qo();LR();DR();Tp=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(i_(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=i_(c);if(e.types&&!s_(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 Wv(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=Gv(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=i_(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=s_(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 Vv({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=Jv(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=ZR[r]??ZR.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 FR(t,e,r,n,o){let s={temperature:n,...o};for(let i=0;i<=a_;i++)try{return t.type==="anthropic"?await IB(t,e,r,s.temperature):t.type==="ollama"?await OB(t,e,r,s.temperature):await CB(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===a_)throw a;let u=RB*Math.pow(2,i)+Math.random()*1e3;console.error(`[hive] Rate limited, retrying in ${(u/1e3).toFixed(1)}s (attempt ${i+1}/${a_})...`),await new Promise(p=>setTimeout(p,u))}throw new Error("Unreachable")}async function OB(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=BR(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 CB(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(y=>({id:y.id,type:"function",function:{name:y.function.name,arguments:typeof y.function.arguments=="string"?y.function.arguments:JSON.stringify(y.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:c_(m.function.arguments)}}));else if(f.content&&r.length>0){let m=BR(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 IB(t,e,r,n){let o,s=[];for(let y of e){if(y.role==="system"){o=y.content??void 0;continue}if(y.role==="assistant"){let v=[];if(y.content&&v.push({type:"text",text:y.content}),y.tool_calls)for(let b of y.tool_calls)v.push({type:"tool_use",id:b.id??`call_${Date.now()}`,name:b.function.name,input:typeof b.function.arguments=="string"?c_(b.function.arguments):b.function.arguments});s.push({role:"assistant",content:v});continue}if(y.role==="tool"){let v=s[s.length-1],b={type:"tool_result",tool_use_id:y.tool_call_id??"",content:y.content??""};v?.role==="user"&&Array.isArray(v.content)?v.content.push(b):s.push({role:"user",content:[b]});continue}s.push({role:"user",content:y.content??""})}let i=r.map(y=>({name:y.function.name,description:y.function.description,input_schema:y.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 y=await c.text();throw new Error(`Anthropic error (${c.status}): ${y}`)}let l=await c.json(),u={role:"assistant",content:null},p=[],f=[];for(let y of l.content)y.type==="text"?p.push(y.text):y.type==="tool_use"&&f.push({id:y.id,type:"function",function:{name:y.name,arguments:y.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 c_(t){try{return JSON.parse(t)}catch{return{}}}function HR(t){return typeof t.function.arguments=="string"?c_(t.function.arguments):t.function.arguments}function BR(t,e){let r=new Set(e.map(s=>s.function.name)),n=[],o=AB(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 AB(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 ZR,a_,RB,l_=w(()=>{ZR={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"};a_=5,RB=2e3});function Ya(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 GR(t,e,r){return Ya(t,e,r,null)}var VR=w(()=>{});function LB(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 DB(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 WR,Xa,u_,NB,zB,jB,MB,p_,qB,ZB,JR,UB,Pp,KR=w(()=>{l_();VR();et();WR=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[91m","\x1B[92m","\x1B[93m","\x1B[94m","\x1B[95m","\x1B[96m"],Xa="\x1B[0m",u_="\x1B[2m",NB=0,zB=new Set(["write_file","patch_file"]),jB=new Set(["incubator_claim","incubator_releaseClaim","incubator_setState","incubator_publishEvent"]),MB=new Set(["publish_event","set_state","get_state","claim_resource","release_resource"]),p_=[{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"]}}}];qB={cerebras:128e3,groq:128e3,ollama:8e3,openai:128e3,anthropic:2e5},ZB=.8,JR=6,UB=3,Pp=class{stopFlag=!1;stop(){this.stopFlag=!0}async run(e,r,n,o,s,i){let a=WR[NB++%WR.length],{agentId:c,role:l,provider:u,maxIterations:p}=e,f=0,d=0,m=Date.now(),h={promptTokens:0,completionTokens:0,totalTokens:0},y=[],v=b=>{if(e.verbose){let x=new Date().toISOString().slice(11,23);console.error(`${a} ${x} [${c}] ${b}${Xa}`)}};try{o&&(await o.connect(),v("ACP runtime connected")),e.startOn&&(v(`Waiting for trigger: ${LB(e.startOn)}`),await DB(e,v),v("Trigger conditions met \u2014 starting agent"));let b=[...r.getToolDefs()];if(e.toolFilter&&e.mode==="drone"){let oe=new Set(e.toolFilter);b=b.filter(ve=>oe.has(ve.function.name))}if(n){let oe=n.getToolDefs(),ve=e.coordination??"full";if(ve==="lite")oe=oe.filter(Qe=>jB.has(Qe.function.name));else if(ve==="none")oe=[];else if(Array.isArray(ve)){let Qe=new Set(ve);oe=oe.filter(Yr=>Qe.has(Yr.function.name))}b.push(...oe),v(`Tools: ${b.length} (env: ${b.length-oe.length}, incubator: ${oe.length})`)}else o&&!e.noAcpInject?(b.push(...p_),v(`Tools: ${b.length} (env: ${b.length-p_.length}, acp: ${p_.length})`)):v(`Tools: ${b.length} (env only)`);let x=s??null;!x&&o&&(x=await o.fetchProtocol());let $=null;if(o){let oe=o.getDanceTools();oe&&oe.length>0&&(b=[...oe],$=new Set(oe.map(ve=>ve.function.name)),v(`Dance tools: ${oe.map(ve=>ve.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 ie=x?.context;ie!==void 0&&v(`Context retention: ${ie===0?"stateless":`last ${ie} exchanges`}`);let X=x?.temperature??e.temperature,ee=x?.reasoning===!1,de=x?.reasoning_effort,ne=[{role:"system",content:x?Ya(c,l,b,x,{disableReasoning:ee}):GR(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 ct=()=>{v("SIGTERM received \u2014 killing agent"),this.stopFlag=!0};process.on("SIGTERM",ct);let kt=e.contextWindow??qB[u.type]??128e3,re=Math.floor(kt*ZB),le=e.maxRetries??UB;if(O&&o){v("Sleeping \u2014 waiting for initial wake event");let oe=await o.waitForWake(O);if(oe.length===0)return v("Initial wake timeout \u2014 no events, exiting"),o&&await o.onComplete("Wake timeout",h),process.removeListener("SIGTERM",ct),{iterations:0,usage:h,agentId:c,role:l,status:"completed"};v(`Woke up with ${oe.length} event(s)`);let ve=o.getLastInject();ve&&(ne.push({role:"user",content:`[SYSTEM] ${ve}`}),v("Injected dance state context"));for(let Qe of oe)ne.push({role:"user",content:`[SYSTEM] ${Qe}`})}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 je=await o.beforeIteration(),M=o.getLastInject();if(ie!==void 0&&M){if(ie===0)ne.length=1;else if(ne.length>1+ie*2){let B=ne.slice(-(ie*2));ne.length=1,ne.push(...B)}}for(let B of je)ne.push({role:"user",content:`[SYSTEM] ${B}`});M&&ne.push({role:"user",content:`[SYSTEM] ${M}`})}let oe,ve,Qe=0;for(;;){let je=Date.now();try{let M=await FR(u,ne,b,X,{...ee?{disableReasoning:!0}:{},...de?{reasoningEffort:de}:{}});oe=M.message,ve=M.usage,i?.record("llm_call",{agentId:c,role:l,provider:u.type,model:u.model,promptTokens:ve.promptTokens,completionTokens:ve.completionTokens,latency_ms:Date.now()-je});break}catch(M){if(Qe++,i?.record("llm_error",{agentId:c,role:l,provider:u.type,model:u.model,error:M.message,retryCount:Qe,latency_ms:Date.now()-je}),Qe>le)throw M;let B=1e3*Math.pow(2,Qe-1);v(`LLM call failed (attempt ${Qe}/${le}): ${M.message} \u2014 retrying in ${B}ms`),await new Promise(wr=>setTimeout(wr,B))}}if(ne.push(oe),h.promptTokens+=ve.promptTokens,h.completionTokens+=ve.completionTokens,h.totalTokens+=ve.totalTokens,y.push(ve),ve.totalTokens>0&&v(`Tokens: +${ve.promptTokens}/${ve.completionTokens} (total: ${h.totalTokens.toLocaleString()})`),ve.promptTokens>re&&ne.length>JR+2){v(`Context compaction triggered (${ve.promptTokens.toLocaleString()} > ${re.toLocaleString()} threshold)`);let je=ne.slice(-JR);if(ne.length=1,ne.push(...je),o){let M=await o.fetchProtocol();M&&(ne[0]={role:"system",content:Ya(c,l,b,M)});let B=await o.getState();ne.push({role:"user",content:`[SYSTEM] Context was compacted. Current state: ${B}`})}else ne.push({role:"user",content:"[SYSTEM] Context was compacted. Previous messages were trimmed."});v(`Compacted to ${ne.length} messages`)}if(oe.content&&v(`${u_}${oe.content}${Xa}${a}`),oe.content&&/\bDONE\b/.test(oe.content)){v("Agent said DONE \u2014 finishing");break}if(!oe.tool_calls||oe.tool_calls.length===0){if(O&&o){let je=O.maxWakes??0;if(je>0&&++d>=je){v(`Max wakes reached (${je}) \u2014 exiting`);break}je===0&&d++,v(`Sleeping \u2014 waiting for wake events (cycle ${d})`);let M=await o.waitForWake(O);if(M.length===0){v("Wake timeout \u2014 no events, exiting");break}v(`Woke up with ${M.length} event(s)`);let B=o.getLastInject();B&&(ne.push({role:"user",content:`[SYSTEM] ${B}`}),v("Injected dance state context"));for(let wr of M)ne.push({role:"user",content:`[SYSTEM] ${wr}`});continue}v("No tool calls \u2014 agent finished");break}let Yr=!1;for(let je of oe.tool_calls){let M=je.function.name,B=HR(je),wr=Object.keys(B).length>0?`(${Object.entries(B).map(([Re,Yt])=>`${Re}=${JSON.stringify(Yt)}`).join(", ")})`:"()";if(v(`Tool: ${M}${wr}`),o&&zB.has(M)&&B.path){let Re=await o.onFileWrite(B.path);if(Re){ne.push({role:"tool",content:Re,tool_call_id:je.id??`call_${f}`}),v(`${u_}\u2192 claim conflict: ${Re}${Xa}${a}`);continue}}let ot;if($&&$.has(M)&&o)try{let Re=await o.callDanceTool(M,B);ot=JSON.stringify(Re)}catch(Re){ot=JSON.stringify({error:`Dance tool failed: ${Re.message}`})}else if(o&&MB.has(M))if(M==="publish_event"){let Re={};if(B.data)try{Re=typeof B.data=="string"?JSON.parse(B.data):B.data}catch{}ot=await o.publishEvent(B.type,Re)}else M==="set_state"?ot=await o.setState(B.key,B.value):M==="get_state"?ot=await o.getState():M==="claim_resource"?ot=await o.claimResource(B.resource,B.reason):M==="release_resource"?ot=await o.releaseResource(B.resource):ot=JSON.stringify({error:`Unknown synthetic tool: ${M}`});else if(n&&n.hasToolName(M))ot=await n.callTool(M,B);else try{ot=await r.callTool(M,B)}catch(Re){ot=JSON.stringify({error:`Tool call failed: ${Re.message}`})}if(v(`${u_}\u2192 ${ot}${Xa}${a}`),ne.push({role:"tool",content:ot,tool_call_id:je.id??`call_${f}`}),o){let Re=await o.checkControl();if(Re.halted){v(`HALTED: ${Re.reason??"no reason"}`),Yr=!0;break}if(Re.paused){v(`PAUSED: ${Re.reason??"no reason"} \u2014 waiting...`);let Yt=await o.waitForResume();v(`RESUMED: ${Yt}`),ne.push({role:"user",content:`[SYSTEM] You were paused (reason: ${Re.reason??"unknown"}). You have been resumed (reason: ${Yt}). Continue your work.`})}}}if(Yr)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:y};if(f%10===0&&o){let je=await o.fetchProtocol();if(je){let M=Ya(c,l,b,je);ne[0]={role:"system",content:M},v("Refreshed system prompt")}}}this.stopFlag?v("Stopped by runner"):f>=p&&v(`Hit max iterations (${p})`),process.off("SIGTERM",ct);let At=`Agent ${c} completed after ${f} iterations (${h.totalTokens.toLocaleString()} tokens)`;return o&&await o.onComplete(At,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:y}}catch(b){try{process.off("SIGTERM",()=>{})}catch{}let x=b.message;if(e.verbose&&console.error(`${a} [${c}] ERROR: ${x}${Xa}`),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:y}}}}});var Rp,YR=w(()=>{o_();Rp=class{entries;entryMap;defs;constructor(e,r,n,o){let s=n_(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 FB}from"node:crypto";function HB(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 y=h;c[m]=y}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 Op,XR=w(()=>{qR();KR();YR();l_();Op=class{agents=new Map;async startAgent(e,r){let n=FB(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 Tp(c),u=e.tools&&e.tools!=="all"?e.tools:null,p=new Rp(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 Pp,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?HB(o,n):null}}});import{spawn as d_}from"node:child_process";import{randomBytes as QR}from"node:crypto";import{dirname as BB,join as GB}from"node:path";import{fileURLToPath as VB}from"node:url";function f_(t){return new Promise(e=>setTimeout(e,t))}var WB,JB,Qa,eO=w(()=>{XR();WB=BB(VB(import.meta.url)),JB=GB(WB,"..","plugin"),Qa=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 f_(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=d_(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 Op,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 f_(u),o++,c==="claude"){let b=QR(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=QR(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 y={...process.env,...n.env,...n.tls?{NODE_TLS_REJECT_UNAUTHORIZED:"0"}:{}};i.prompt&&(y.AGENT_PROMPT=i.prompt);let v=d_(process.execPath,[this.hiveEntry,...h],{env:y,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??JB,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=d_("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 f_(500);let e=this.children.get("propolis");e&&(e.kill("SIGTERM"),this.log("Stopped propolis")),this.children.clear(),this.childInfo=[]}}});import{createHmac as KB}from"node:crypto";var Cp,tO=w(()=>{Cp=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=KB("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 m_={};V(m_,{getRedisClient:()=>XB,waitForReady:()=>QB});import{createRequire as YB}from"node:module";function XB(t){let e=rO.get(t);if(e)return e;let n=YB(import.meta.url)("ioredis"),o=new n(t);return rO.set(t,o),o}async function QB(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 rO,h_=w(()=>{rO=new Map});var nO={};V(nO,{IPCTransport:()=>g_});import{connect as eG}from"node:net";var g_,oO=w(()=>{g_=class{socket=null;handlers=new Map;buffer="";opts;constructor(e){this.opts=e}async connect(){return new Promise((e,r)=>{let n=eG(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)+`
400
+ `).trim()}var cB,lB,ii,$p,$R=w(()=>{Va();Ga();cB=/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.|169\.254\.|::1|fc|fd|fe80)/i,lB=/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])/i;ii=512*1024,$p=3e4});function Jv(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:L.string().describe("File path relative to working directory")},handler:n=>sR(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:L.string().describe("File path relative to working directory"),content:L.string().describe("Content to write")},handler:n=>iR(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:L.string().describe("File path relative to working directory"),search:L.string().describe("Exact text to find"),replace:L.string().describe("Text to replace with")},handler:n=>aR(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:L.string().optional().describe("Directory path relative to working directory (default: root)"),recursive:L.boolean().optional().describe("List recursively (default: false)")},handler:n=>cR(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:L.string().describe("Glob pattern to match"),path:L.string().optional().describe("Base directory for the search")},handler:n=>lR(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:L.string().describe("Regex pattern to search for"),path:L.string().optional().describe("Directory to search in"),glob:L.string().optional().describe('File glob filter (e.g. "*.ts")')},handler:n=>pR(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:L.string().describe("Shell command to execute"),cwd:L.string().optional().describe("Working directory relative to sandbox root"),timeout:L.number().optional().describe("Timeout in milliseconds (default: 60000)")},handler:n=>fR(n,t,e,r)},{def:{type:"function",function:{name:"git_status",description:"Show git status (porcelain format)",parameters:{type:"object",properties:{},required:[]}}},schema:{},handler:()=>gR({},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:L.string().optional().describe("File path to diff"),staged:L.boolean().optional().describe("Show staged changes")},handler:n=>yR(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:L.string().describe("Commit message"),files:L.string().optional().describe("Comma-separated file paths to stage (default: all)")},handler:n=>vR(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:L.number().optional().describe("Number of commits to show (default: 10)")},handler:n=>_R(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:L.string().describe("URL to fetch"),method:L.string().optional().describe("HTTP method (default: GET)"),body:L.string().optional().describe("Request body (for POST/PUT/PATCH)")},handler:n=>xR(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:L.string().describe("URL of the page to scrape")},handler:n=>SR(n,t,e,r)}]}var Kv=w(()=>{Vu();dR();mR();bR();$R()});function kR(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 ER=w(()=>{Kv()});function Yv(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 TR=w(()=>{});function Xv(t){let e=typeof t.data=="string"?t.data:JSON.stringify(t.data);return`Event from ${t.publishedBy}: [${t.type}] ${e}`}var kp,PR=w(()=>{Qo();ER();TR();kp=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(Xv(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=Xv(c);if(e.types&&!Yv(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 qv(this.danceModule,e,r,this.role,this.agentId,o,n);if("error"in s||!s.wait)return s;let i=kR(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=Lv(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=Xv(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=Yv(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 Dv({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=Zv(this.danceModule,e,this.role,this.agentId)}}});function OR(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=RR[r]??RR.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 CR(t,e,r,n,o){let s={temperature:n,...o};for(let i=0;i<=Qv;i++)try{return t.type==="anthropic"?await mB(t,e,r,s.temperature):t.type==="ollama"?await dB(t,e,r,s.temperature):await fB(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===Qv)throw a;let u=pB*Math.pow(2,i)+Math.random()*1e3;console.error(`[hive] Rate limited, retrying in ${(u/1e3).toFixed(1)}s (attempt ${i+1}/${Qv})...`),await new Promise(p=>setTimeout(p,u))}throw new Error("Unreachable")}async function dB(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=AR(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 fB(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(y=>({id:y.id,type:"function",function:{name:y.function.name,arguments:typeof y.function.arguments=="string"?y.function.arguments:JSON.stringify(y.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:e_(m.function.arguments)}}));else if(f.content&&r.length>0){let m=AR(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 mB(t,e,r,n){let o,s=[];for(let y of e){if(y.role==="system"){o=y.content??void 0;continue}if(y.role==="assistant"){let v=[];if(y.content&&v.push({type:"text",text:y.content}),y.tool_calls)for(let b of y.tool_calls)v.push({type:"tool_use",id:b.id??`call_${Date.now()}`,name:b.function.name,input:typeof b.function.arguments=="string"?e_(b.function.arguments):b.function.arguments});s.push({role:"assistant",content:v});continue}if(y.role==="tool"){let v=s[s.length-1],b={type:"tool_result",tool_use_id:y.tool_call_id??"",content:y.content??""};v?.role==="user"&&Array.isArray(v.content)?v.content.push(b):s.push({role:"user",content:[b]});continue}s.push({role:"user",content:y.content??""})}let i=r.map(y=>({name:y.function.name,description:y.function.description,input_schema:y.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 y=await c.text();throw new Error(`Anthropic error (${c.status}): ${y}`)}let l=await c.json(),u={role:"assistant",content:null},p=[],f=[];for(let y of l.content)y.type==="text"?p.push(y.text):y.type==="tool_use"&&f.push({id:y.id,type:"function",function:{name:y.name,arguments:y.input}});p.length>0&&(u.content=p.join(`
401
+ `)),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 e_(t){try{return JSON.parse(t)}catch{return{}}}function IR(t){return typeof t.function.arguments=="string"?e_(t.function.arguments):t.function.arguments}function AR(t,e){let r=new Set(e.map(s=>s.function.name)),n=[],o=hB(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 hB(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 RR,Qv,pB,t_=w(()=>{RR={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"};Qv=5,pB=2e3});function Ka(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(`
402
+ `)}function NR(t,e,r){return Ka(t,e,r,null)}var zR=w(()=>{});function bB(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 wB(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 jR,Ya,r_,gB,yB,vB,_B,n_,xB,SB,MR,$B,Ep,LR=w(()=>{t_();zR();et();jR=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[91m","\x1B[92m","\x1B[93m","\x1B[94m","\x1B[95m","\x1B[96m"],Ya="\x1B[0m",r_="\x1B[2m",gB=0,yB=new Set(["write_file","patch_file"]),vB=new Set(["incubator_claim","incubator_releaseClaim","incubator_setState","incubator_publishEvent"]),_B=new Set(["publish_event","set_state","get_state","claim_resource","release_resource"]),n_=[{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"]}}}];xB={cerebras:128e3,groq:128e3,ollama:8e3,openai:128e3,anthropic:2e5},SB=.8,MR=6,$B=3,Ep=class{stopFlag=!1;stop(){this.stopFlag=!0}async run(e,r,n,o,s,i){let a=jR[gB++%jR.length],{agentId:c,role:l,provider:u,maxIterations:p}=e,f=0,d=0,m=Date.now(),h={promptTokens:0,completionTokens:0,totalTokens:0},y=[],v=b=>{if(e.verbose){let x=new Date().toISOString().slice(11,23);console.error(`${a} ${x} [${c}] ${b}${Ya}`)}};try{o&&(await o.connect(),v("ACP runtime connected")),e.startOn&&(v(`Waiting for trigger: ${bB(e.startOn)}`),await wB(e,v),v("Trigger conditions met \u2014 starting agent"));let b=[...r.getToolDefs()];if(e.toolFilter&&e.mode==="drone"){let oe=new Set(e.toolFilter);b=b.filter(ve=>oe.has(ve.function.name))}if(n){let oe=n.getToolDefs(),ve=e.coordination??"full";if(ve==="lite")oe=oe.filter(Qe=>vB.has(Qe.function.name));else if(ve==="none")oe=[];else if(Array.isArray(ve)){let Qe=new Set(ve);oe=oe.filter(en=>Qe.has(en.function.name))}b.push(...oe),v(`Tools: ${b.length} (env: ${b.length-oe.length}, incubator: ${oe.length})`)}else o&&!e.noAcpInject?(b.push(...n_),v(`Tools: ${b.length} (env: ${b.length-n_.length}, acp: ${n_.length})`)):v(`Tools: ${b.length} (env only)`);let x=s??null;!x&&o&&(x=await o.fetchProtocol());let $=null;if(o){let oe=o.getDanceTools();oe&&oe.length>0&&(b=[...oe],$=new Set(oe.map(ve=>ve.function.name)),v(`Dance tools: ${oe.map(ve=>ve.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 ie=x?.context;ie!==void 0&&v(`Context retention: ${ie===0?"stateless":`last ${ie} exchanges`}`);let X=x?.temperature??e.temperature,ee=x?.reasoning===!1,de=x?.reasoning_effort,ne=[{role:"system",content:x?Ka(c,l,b,x,{disableReasoning:ee}):NR(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 ct=()=>{v("SIGTERM received \u2014 killing agent"),this.stopFlag=!0};process.on("SIGTERM",ct);let Et=e.contextWindow??xB[u.type]??128e3,re=Math.floor(Et*SB),le=e.maxRetries??$B;if(O&&o){v("Sleeping \u2014 waiting for initial wake event");let oe=await o.waitForWake(O);if(oe.length===0)return v("Initial wake timeout \u2014 no events, exiting"),o&&await o.onComplete("Wake timeout",h),process.removeListener("SIGTERM",ct),{iterations:0,usage:h,agentId:c,role:l,status:"completed"};v(`Woke up with ${oe.length} event(s)`);let ve=o.getLastInject();ve&&(ne.push({role:"user",content:`[SYSTEM] ${ve}`}),v("Injected dance state context"));for(let Qe of oe)ne.push({role:"user",content:`[SYSTEM] ${Qe}`})}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 je=await o.beforeIteration(),M=o.getLastInject();if(ie!==void 0&&M){if(ie===0)ne.length=1;else if(ne.length>1+ie*2){let H=ne.slice(-(ie*2));ne.length=1,ne.push(...H)}}for(let H of je)ne.push({role:"user",content:`[SYSTEM] ${H}`});M&&ne.push({role:"user",content:`[SYSTEM] ${M}`})}let oe,ve,Qe=0;for(;;){let je=Date.now();try{let M=await CR(u,ne,b,X,{...ee?{disableReasoning:!0}:{},...de?{reasoningEffort:de}:{}});oe=M.message,ve=M.usage,i?.record("llm_call",{agentId:c,role:l,provider:u.type,model:u.model,promptTokens:ve.promptTokens,completionTokens:ve.completionTokens,latency_ms:Date.now()-je});break}catch(M){if(Qe++,i?.record("llm_error",{agentId:c,role:l,provider:u.type,model:u.model,error:M.message,retryCount:Qe,latency_ms:Date.now()-je}),Qe>le)throw M;let H=1e3*Math.pow(2,Qe-1);v(`LLM call failed (attempt ${Qe}/${le}): ${M.message} \u2014 retrying in ${H}ms`),await new Promise(zt=>setTimeout(zt,H))}}if(ne.push(oe),h.promptTokens+=ve.promptTokens,h.completionTokens+=ve.completionTokens,h.totalTokens+=ve.totalTokens,y.push(ve),ve.totalTokens>0&&v(`Tokens: +${ve.promptTokens}/${ve.completionTokens} (total: ${h.totalTokens.toLocaleString()})`),ve.promptTokens>re&&ne.length>MR+2){v(`Context compaction triggered (${ve.promptTokens.toLocaleString()} > ${re.toLocaleString()} threshold)`);let je=ne.slice(-MR);if(ne.length=1,ne.push(...je),o){let M=await o.fetchProtocol();M&&(ne[0]={role:"system",content:Ka(c,l,b,M)});let H=await o.getState();ne.push({role:"user",content:`[SYSTEM] Context was compacted. Current state: ${H}`})}else ne.push({role:"user",content:"[SYSTEM] Context was compacted. Previous messages were trimmed."});v(`Compacted to ${ne.length} messages`)}if(oe.content&&v(`${r_}${oe.content}${Ya}${a}`),oe.content&&/\bDONE\b/.test(oe.content)){v("Agent said DONE \u2014 finishing");break}if(!oe.tool_calls||oe.tool_calls.length===0){if(O&&o){let je=O.maxWakes??0;if(je>0&&++d>=je){v(`Max wakes reached (${je}) \u2014 exiting`);break}je===0&&d++,v(`Sleeping \u2014 waiting for wake events (cycle ${d})`);let M=await o.waitForWake(O);if(M.length===0){v("Wake timeout \u2014 no events, exiting");break}v(`Woke up with ${M.length} event(s)`);let H=o.getLastInject();H&&(ne.push({role:"user",content:`[SYSTEM] ${H}`}),v("Injected dance state context"));for(let zt of M)ne.push({role:"user",content:`[SYSTEM] ${zt}`});continue}v("No tool calls \u2014 agent finished");break}let en=!1;for(let je of oe.tool_calls){let M=je.function.name,H=IR(je),zt=Object.keys(H).length>0?`(${Object.entries(H).map(([Ee,lt])=>`${Ee}=${JSON.stringify(lt)}`).join(", ")})`:"()";if(v(`Tool: ${M}${zt}`),o&&yB.has(M)&&H.path){let Ee=await o.onFileWrite(H.path);if(Ee){ne.push({role:"tool",content:Ee,tool_call_id:je.id??`call_${f}`}),v(`${r_}\u2192 claim conflict: ${Ee}${Ya}${a}`);continue}}let nt;if($&&$.has(M)&&o)try{let Ee=await o.callDanceTool(M,H);nt=JSON.stringify(Ee)}catch(Ee){nt=JSON.stringify({error:`Dance tool failed: ${Ee.message}`})}else if(o&&_B.has(M))if(M==="publish_event"){let Ee={};if(H.data)try{Ee=typeof H.data=="string"?JSON.parse(H.data):H.data}catch{}nt=await o.publishEvent(H.type,Ee)}else M==="set_state"?nt=await o.setState(H.key,H.value):M==="get_state"?nt=await o.getState():M==="claim_resource"?nt=await o.claimResource(H.resource,H.reason):M==="release_resource"?nt=await o.releaseResource(H.resource):nt=JSON.stringify({error:`Unknown synthetic tool: ${M}`});else if(n&&n.hasToolName(M))nt=await n.callTool(M,H);else try{nt=await r.callTool(M,H)}catch(Ee){nt=JSON.stringify({error:`Tool call failed: ${Ee.message}`})}if(v(`${r_}\u2192 ${nt}${Ya}${a}`),ne.push({role:"tool",content:nt,tool_call_id:je.id??`call_${f}`}),o){let Ee=await o.checkControl();if(Ee.halted){v(`HALTED: ${Ee.reason??"no reason"}`),en=!0;break}if(Ee.paused){v(`PAUSED: ${Ee.reason??"no reason"} \u2014 waiting...`);let lt=await o.waitForResume();v(`RESUMED: ${lt}`),ne.push({role:"user",content:`[SYSTEM] You were paused (reason: ${Ee.reason??"unknown"}). You have been resumed (reason: ${lt}). Continue your work.`})}}}if(en)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:y};if(f%10===0&&o){let je=await o.fetchProtocol();if(je){let M=Ka(c,l,b,je);ne[0]={role:"system",content:M},v("Refreshed system prompt")}}}this.stopFlag?v("Stopped by runner"):f>=p&&v(`Hit max iterations (${p})`),process.off("SIGTERM",ct);let Nt=`Agent ${c} completed after ${f} iterations (${h.totalTokens.toLocaleString()} tokens)`;return o&&await o.onComplete(Nt,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:y}}catch(b){try{process.off("SIGTERM",()=>{})}catch{}let x=b.message;if(e.verbose&&console.error(`${a} [${c}] ERROR: ${x}${Ya}`),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:y}}}}});var Tp,DR=w(()=>{Kv();Tp=class{entries;entryMap;defs;constructor(e,r,n,o){let s=Jv(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(`
403
+ `):JSON.stringify(o)}async close(){}}});import{randomBytes as kB}from"node:crypto";function EB(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 y=h;c[m]=y}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 Pp,qR=w(()=>{PR();LR();DR();t_();Pp=class{agents=new Map;async startAgent(e,r){let n=kB(3).toString("hex"),o=`${e.role}_${n}`,s=(e.modelHint&&r.models?.[e.modelHint])??r.models?.[e.role]??r.provider??"ollama/qwen3:8b",i=OR(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 kp(c),u=e.tools&&e.tools!=="all"?e.tools:null,p=new Tp(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 Ep,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?EB(o,n):null}}});import{spawn as o_}from"node:child_process";import{randomBytes as ZR}from"node:crypto";import{dirname as TB,join as PB}from"node:path";import{fileURLToPath as RB}from"node:url";function s_(t){return new Promise(e=>setTimeout(e,t))}var OB,CB,Xa,UR=w(()=>{qR();OB=TB(RB(import.meta.url)),CB=PB(OB,"..","plugin"),Xa=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 s_(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=o_(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 Pp,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 s_(u),o++,c==="claude"){let b=ZR(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=ZR(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 y={...process.env,...n.env,...n.tls?{NODE_TLS_REJECT_UNAUTHORIZED:"0"}:{}};i.prompt&&(y.AGENT_PROMPT=i.prompt);let v=o_(process.execPath,[this.hiveEntry,...h],{env:y,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??CB,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=o_("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 s_(500);let e=this.children.get("propolis");e&&(e.kill("SIGTERM"),this.log("Stopped propolis")),this.children.clear(),this.childInfo=[]}}});import{createHmac as IB}from"node:crypto";var Rp,FR=w(()=>{Rp=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=IB("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 i_={};V(i_,{getRedisClient:()=>NB,waitForReady:()=>zB});import{createRequire as AB}from"node:module";function NB(t){let e=HR.get(t);if(e)return e;let n=AB(import.meta.url)("ioredis"),o=new n(t);return HR.set(t,o),o}async function zB(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 HR,a_=w(()=>{HR=new Map});var BR={};V(BR,{IPCTransport:()=>c_});import{connect as jB}from"node:net";var c_,GR=w(()=>{c_=class{socket=null;handlers=new Map;buffer="";opts;constructor(e){this.opts=e}async connect(){return new Promise((e,r)=>{let n=jB(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
404
  `)}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 y_,resolve as tG}from"path";import{readdirSync as rG,statSync as nG}from"fs";function v_(t,e,r=""){t=tG(".",t);let n=rG(t),o=0,s,i;for(;o<n.length;o++)s=y_(t,n[o]),i=nG(s),i.isDirectory()?v_(s,e,y_(r,n[o])):e(y_(r,n[o]),s,i)}var sO=w(()=>{});import*as iO from"node:querystring";function aO(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=iO.parse(o.substring(1))))}return t._parsedUrl={pathname:n,search:o,query:s,hash:i,raw:e}}var cO=w(()=>{});function lO(t){let e=(""+t).trim().toLowerCase(),r=e.lastIndexOf(".");return oG[~r?e.substring(++r):e]}var oG,uO=w(()=>{oG={"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 fO={};V(fO,{default:()=>gG});import*as ci from"node:fs";import{join as sG,normalize as iG,resolve as aG,sep as cG}from"node:path";function uG(t,e){for(let r=0;r<e.length;r++)if(e[r].test(t))return!0}function pO(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 pG(t,e,r){let n=0,o,s=pO(e,r);for(;n<s.length;n++)if(o=t[s[n]])return o}function dG(t,e,r,n){let o=0,s=pO(r,n),i,a,c,l;for(;o<s.length;o++)if(i=iG(sG(t,c=s[o])),i.startsWith(t)&&ci.existsSync(i)){if(a=ci.statSync(i),a.isDirectory())continue;return l=dO(c,a,e),l["Cache-Control"]=e?"no-cache":"no-store",{abs:i,stats:a,headers:l}}}function fG(t,e){return e.statusCode=404,e.end()}function mG(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),ci.createReadStream(r,a).pipe(e)}function dO(t,e,r){let n=hG[t.slice(-3)],o=lO(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 gG(t,e={}){t=aG(t||".");let r=e.onNoMatch||fG,n=e.setHeaders||lG,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||v_(t,(m,h,y)=>{if(!/\.well-known[\\+\/]/.test(m)){if(!e.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(m))return}let v=dO(m,y,l);f&&(v["Cache-Control"]=f),a["/"+m.normalize().replace(/\\+/g,"/")]={abs:h,stats:y,headers:v}});let d=e.dev?dG.bind(0,t+cG,l):pG.bind(0,a);return function(m,h,y){let v=[""],b=aO(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&&!uG(b,p)&&d(c,v);if(!$)return y?y():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),mG(m,h,$.abs,$.stats,$.headers)}}var lG,hG,mO=w(()=>{sO();cO();uO();lG=()=>{};hG={".br":"br",".gz":"gzip"}});var dn=I((Toe,yO)=>{"use strict";var hO=["nodebuffer","arraybuffer","fragments"],gO=typeof Blob<"u";gO&&hO.push("blob");yO.exports={BINARY_TYPES:hO,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:gO,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var ec=I((Poe,Ip)=>{"use strict";var{EMPTY_BUFFER:yG}=dn(),__=Buffer[Symbol.species];function vG(t,e){if(t.length===0)return yG;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 __(r.buffer,r.byteOffset,n):r}function vO(t,e,r,n,o){for(let s=0;s<o;s++)r[n+s]=t[s]^e[s&3]}function _O(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function _G(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function b_(t){if(b_.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new __(t):ArrayBuffer.isView(t)?e=new __(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),b_.readOnly=!1),e}Ip.exports={concat:vG,mask:vO,toArrayBuffer:_G,toBuffer:b_,unmask:_O};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=st("bufferutil");Ip.exports.mask=function(e,r,n,o,s){s<48?vO(e,r,n,o,s):t.mask(e,r,n,o,s)},Ip.exports.unmask=function(e,r){e.length<32?_O(e,r):t.unmask(e,r)}}catch{}});var xO=I((Roe,wO)=>{"use strict";var bO=Symbol("kDone"),w_=Symbol("kRun"),x_=class{constructor(e){this[bO]=()=>{this.pending--,this[w_]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[w_]()}[w_](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[bO])}}};wO.exports=x_});var rc=I((Ooe,EO)=>{"use strict";var tc=st("zlib"),SO=ec(),bG=xO(),{kStatusCode:$O}=dn(),wG=Buffer[Symbol.species],xG=Buffer.from([0,0,255,255]),Np=Symbol("permessage-deflate"),fn=Symbol("total-length"),li=Symbol("callback"),eo=Symbol("buffers"),ui=Symbol("error"),Ap,S_=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,!Ap){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Ap=new bG(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[li];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){Ap.add(o=>{this._decompress(e,r,(s,i)=>{o(),n(s,i)})})}compress(e,r,n){Ap.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"?tc.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=tc.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Np]=this,this._inflate[fn]=0,this._inflate[eo]=[],this._inflate.on("error",$G),this._inflate.on("data",kO)}this._inflate[li]=n,this._inflate.write(e),r&&this._inflate.write(xG),this._inflate.flush(()=>{let s=this._inflate[ui];if(s){this._inflate.close(),this._inflate=null,n(s);return}let i=SO.concat(this._inflate[eo],this._inflate[fn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[fn]=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"?tc.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=tc.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[fn]=0,this._deflate[eo]=[],this._deflate.on("data",SG)}this._deflate[li]=n,this._deflate.write(e),this._deflate.flush(tc.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=SO.concat(this._deflate[eo],this._deflate[fn]);r&&(s=new wG(s.buffer,s.byteOffset,s.length-4)),this._deflate[li]=null,this._deflate[fn]=0,this._deflate[eo]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};EO.exports=S_;function SG(t){this[eo].push(t),this[fn]+=t.length}function kO(t){if(this[fn]+=t.length,this[Np]._maxPayload<1||this[fn]<=this[Np]._maxPayload){this[eo].push(t);return}this[ui]=new RangeError("Max payload size exceeded"),this[ui].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[ui][$O]=1009,this.removeListener("data",kO),this.reset()}function $G(t){if(this[Np]._inflate=null,this[ui]){this[li](this[ui]);return}t[$O]=1007,this[li](t)}});var pi=I((Coe,zp)=>{"use strict";var{isUtf8:TO}=st("buffer"),{hasBlob:kG}=dn(),EG=[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 TG(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function $_(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 PG(t){return kG&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}zp.exports={isBlob:PG,isValidStatusCode:TG,isValidUTF8:$_,tokenChars:EG};if(TO)zp.exports.isValidUTF8=function(t){return t.length<24?$_(t):TO(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=st("utf-8-validate");zp.exports.isValidUTF8=function(e){return e.length<32?$_(e):t(e)}}catch{}});var R_=I((Ioe,NO)=>{"use strict";var{Writable:RG}=st("stream"),PO=rc(),{BINARY_TYPES:OG,EMPTY_BUFFER:RO,kStatusCode:CG,kWebSocket:IG}=dn(),{concat:k_,toArrayBuffer:AG,unmask:NG}=ec(),{isValidStatusCode:zG,isValidUTF8:OO}=pi(),jp=Buffer[Symbol.species],_r=0,CO=1,IO=2,AO=3,E_=4,T_=5,Mp=6,P_=class extends RG{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||OG[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[IG]=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=_r}_write(e,r,n){if(this._opcode===8&&this._state==_r)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 jp(n.buffer,n.byteOffset+e,n.length-e),new jp(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 jp(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 _r:this.getInfo(e);break;case CO:this.getPayloadLength16(e);break;case IO:this.getPayloadLength64(e);break;case AO:this.getMask();break;case E_:this.getData(e);break;case T_:case Mp: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[PO.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=IO: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=AO:this._state=E_}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=E_}getData(e){let r=RO;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]&&NG(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=T_,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[PO.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===_r&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=_r;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=k_(n,r):this._binaryType==="arraybuffer"?o=AG(k_(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=_r):(this._state=Mp,setImmediate(()=>{this.emit("message",o,!0),this._state=_r,this.startLoop(e)}))}else{let o=k_(n,r);if(!this._skipUTF8Validation&&!OO(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===T_||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=_r):(this._state=Mp,setImmediate(()=>{this.emit("message",o,!1),this._state=_r,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,RO),this.end();else{let n=e.readUInt16BE(0);if(!zG(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new jp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!OO(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=_r;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_r):(this._state=Mp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_r,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[CG]=o,i}};NO.exports=P_});var I_=I((Noe,MO)=>{"use strict";var{Duplex:Aoe}=st("stream"),{randomFillSync:jG}=st("crypto"),zO=rc(),{EMPTY_BUFFER:MG,kWebSocket:LG,NOOP:DG}=dn(),{isBlob:di,isValidStatusCode:qG}=pi(),{mask:jO,toBuffer:es}=ec(),br=Symbol("kByteLength"),ZG=Buffer.alloc(4),Lp=8*1024,ts,fi=Lp,Ar=0,UG=1,FG=2,O_=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=Ar,this.onerror=DG,this[LG]=void 0}static frame(e,r){let n,o=!1,s=2,i=!1;r.mask&&(n=r.maskBuffer||ZG,r.generateMask?r.generateMask(n):(fi===Lp&&(ts===void 0&&(ts=Buffer.alloc(Lp)),jG(ts,0,Lp),fi=0),n[0]=ts[fi++],n[1]=ts[fi++],n[2]=ts[fi++],n[3]=ts[fi++]),i=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||i)&&r[br]!==void 0?a=r[br]:(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?(jO(e,n,l,s,a),[l]):(jO(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,o){let s;if(e===void 0)s=MG;else{if(typeof e!="number"||!qG(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={[br]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==Ar?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):di(e)?(o=e.size,s=!1):(e=es(e),o=e.length,s=es.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[br]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};di(e)?this._state!==Ar?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==Ar?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):di(e)?(o=e.size,s=!1):(e=es(e),o=e.length,s=es.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[br]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};di(e)?this._state!==Ar?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==Ar?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}send(e,r,n){let o=this._extensions[zO.extensionName],s=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):di(e)?(a=e.size,c=!1):(e=es(e),a=e.length,c=es.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={[br]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:i};di(e)?this._state!==Ar?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==Ar?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,o){this._bufferedBytes+=n[br],this._state=FG,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(C_,this,a,o);return}this._bufferedBytes-=n[br];let i=es(s);r?this.dispatch(i,r,n,o):(this._state=Ar,this.sendFrame(t.frame(i,n),o),this.dequeue())}).catch(s=>{process.nextTick(HG,this,s,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let s=this._extensions[zO.extensionName];this._bufferedBytes+=n[br],this._state=UG,s.compress(e,n.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");C_(this,c,o);return}this._bufferedBytes-=n[br],this._state=Ar,n.readOnly=!1,this.sendFrame(t.frame(a,n),o),this.dequeue()})}dequeue(){for(;this._state===Ar&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][br],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][br],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=O_;function C_(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 HG(t,e,r){C_(t,e,r),t.onerror(e)}});var GO=I((zoe,BO)=>{"use strict";var{kForOnEventAttribute:nc,kListener:A_}=dn(),LO=Symbol("kCode"),DO=Symbol("kData"),qO=Symbol("kError"),ZO=Symbol("kMessage"),UO=Symbol("kReason"),mi=Symbol("kTarget"),FO=Symbol("kType"),HO=Symbol("kWasClean"),mn=class{constructor(e){this[mi]=null,this[FO]=e}get target(){return this[mi]}get type(){return this[FO]}};Object.defineProperty(mn.prototype,"target",{enumerable:!0});Object.defineProperty(mn.prototype,"type",{enumerable:!0});var rs=class extends mn{constructor(e,r={}){super(e),this[LO]=r.code===void 0?0:r.code,this[UO]=r.reason===void 0?"":r.reason,this[HO]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[LO]}get reason(){return this[UO]}get wasClean(){return this[HO]}};Object.defineProperty(rs.prototype,"code",{enumerable:!0});Object.defineProperty(rs.prototype,"reason",{enumerable:!0});Object.defineProperty(rs.prototype,"wasClean",{enumerable:!0});var hi=class extends mn{constructor(e,r={}){super(e),this[qO]=r.error===void 0?null:r.error,this[ZO]=r.message===void 0?"":r.message}get error(){return this[qO]}get message(){return this[ZO]}};Object.defineProperty(hi.prototype,"error",{enumerable:!0});Object.defineProperty(hi.prototype,"message",{enumerable:!0});var oc=class extends mn{constructor(e,r={}){super(e),this[DO]=r.data===void 0?null:r.data}get data(){return this[DO]}};Object.defineProperty(oc.prototype,"data",{enumerable:!0});var BG={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[nc]&&o[A_]===e&&!o[nc])return;let n;if(t==="message")n=function(s,i){let a=new oc("message",{data:i?s:s.toString()});a[mi]=this,Dp(e,this,a)};else if(t==="close")n=function(s,i){let a=new rs("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[mi]=this,Dp(e,this,a)};else if(t==="error")n=function(s){let i=new hi("error",{error:s,message:s.message});i[mi]=this,Dp(e,this,i)};else if(t==="open")n=function(){let s=new mn("open");s[mi]=this,Dp(e,this,s)};else return;n[nc]=!!r[nc],n[A_]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[A_]===e&&!r[nc]){this.removeListener(t,r);break}}};BO.exports={CloseEvent:rs,ErrorEvent:hi,Event:mn,EventTarget:BG,MessageEvent:oc};function Dp(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var N_=I((joe,VO)=>{"use strict";var{tokenChars:sc}=pi();function Kr(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function GG(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&&sc[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?(Kr(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&&sc[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),Kr(r,t.slice(c,u),!0),l===44&&(Kr(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(sc[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),o=!1}else if(s)if(sc[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&&sc[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),Kr(r,a,d),l===44&&(Kr(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?Kr(e,f,r):(a===void 0?Kr(r,f,!0):n?Kr(r,a,f.replace(/\\/g,"")):Kr(r,a,f),Kr(e,i,r)),e}function VG(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(", ")}VO.exports={format:VG,parse:GG}});var Fp=I((Doe,sC)=>{"use strict";var WG=st("events"),JG=st("https"),KG=st("http"),KO=st("net"),YG=st("tls"),{randomBytes:XG,createHash:QG}=st("crypto"),{Duplex:Moe,Readable:Loe}=st("stream"),{URL:z_}=st("url"),to=rc(),eV=R_(),tV=I_(),{isBlob:rV}=pi(),{BINARY_TYPES:WO,CLOSE_TIMEOUT:nV,EMPTY_BUFFER:qp,GUID:oV,kForOnEventAttribute:j_,kListener:sV,kStatusCode:iV,kWebSocket:ht,NOOP:YO}=dn(),{EventTarget:{addEventListener:aV,removeEventListener:cV}}=GO(),{format:lV,parse:uV}=N_(),{toBuffer:pV}=ec(),XO=Symbol("kAborted"),M_=[8,13],hn=["CONNECTING","OPEN","CLOSING","CLOSED"],dV=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Xe=class t extends WG{constructor(e,r,n){super(),this._binaryType=WO[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=qp,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]),QO(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){WO.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 eV({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new tV(e,this._extensions,n.generateMask);this._receiver=o,this._sender=s,this._socket=e,o[ht]=this,s[ht]=this,e[ht]=this,o.on("conclude",hV),o.on("drain",gV),o.on("error",yV),o.on("message",vV),o.on("ping",_V),o.on("pong",bV),s.onerror=wV,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",rC),e.on("data",Up),e.on("end",nC),e.on("error",oC),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){or(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())}),tC(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){L_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||qp,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){L_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||qp,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){L_(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||qp,o,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){or(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Xe,"CONNECTING",{enumerable:!0,value:hn.indexOf("CONNECTING")});Object.defineProperty(Xe.prototype,"CONNECTING",{enumerable:!0,value:hn.indexOf("CONNECTING")});Object.defineProperty(Xe,"OPEN",{enumerable:!0,value:hn.indexOf("OPEN")});Object.defineProperty(Xe.prototype,"OPEN",{enumerable:!0,value:hn.indexOf("OPEN")});Object.defineProperty(Xe,"CLOSING",{enumerable:!0,value:hn.indexOf("CLOSING")});Object.defineProperty(Xe.prototype,"CLOSING",{enumerable:!0,value:hn.indexOf("CLOSING")});Object.defineProperty(Xe,"CLOSED",{enumerable:!0,value:hn.indexOf("CLOSED")});Object.defineProperty(Xe.prototype,"CLOSED",{enumerable:!0,value:hn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Xe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Xe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[j_])return e[sV];return null},set(e){for(let r of this.listeners(t))if(r[j_]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[j_]:!0})}})});Xe.prototype.addEventListener=aV;Xe.prototype.removeEventListener=cV;sC.exports=Xe;function QO(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:nV,protocolVersion:M_[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,!M_.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${M_.join(", ")})`);let s;if(e instanceof z_)s=e;else try{s=new z_(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=XG(16).toString("base64"),p=i?JG.request:KG.request,f=new Set,d;if(o.createConnection=o.createConnection||(i?mV:fV),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"]=lV({[to.extensionName]:d.offer()})),r.length){for(let h of r){if(typeof h!="string"||!dV.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[y,v]of Object.entries(h))n.headers[y.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",()=>{or(t,m,"Opening handshake has timed out")}),m.on("error",h=>{m===null||m[XO]||(m=t._req=null,Zp(t,h))}),m.on("response",h=>{let y=h.headers.location,v=h.statusCode;if(y&&o.followRedirects&&v>=300&&v<400){if(++t._redirects>o.maxRedirects){or(t,m,"Maximum redirects exceeded");return}m.abort();let b;try{b=new z_(y,e)}catch{let $=new SyntaxError(`Invalid URL: ${y}`);Zp(t,$);return}QO(t,b,r,n)}else t.emit("unexpected-response",m,h)||or(t,m,`Unexpected server response: ${h.statusCode}`)}),m.on("upgrade",(h,y,v)=>{if(t.emit("upgrade",h),t.readyState!==Xe.CONNECTING)return;m=t._req=null;let b=h.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){or(t,y,"Invalid Upgrade header");return}let x=QG("sha1").update(u+oV).digest("base64");if(h.headers["sec-websocket-accept"]!==x){or(t,y,"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){or(t,y,O);return}$&&(t._protocol=$);let ie=h.headers["sec-websocket-extensions"];if(ie!==void 0){if(!d){or(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let X;try{X=uV(ie)}catch{or(t,y,"Invalid Sec-WebSocket-Extensions header");return}let ee=Object.keys(X);if(ee.length!==1||ee[0]!==to.extensionName){or(t,y,"Server indicated an extension that was not requested");return}try{d.accept(X[to.extensionName])}catch{or(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[to.extensionName]=d}t.setSocket(y,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=Xe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function fV(t){return t.path=t.socketPath,KO.connect(t)}function mV(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=KO.isIP(t.host)?"":t.host),YG.connect(t)}function or(t,e,r){t._readyState=Xe.CLOSING;let n=new Error(r);Error.captureStackTrace(n,or),e.setHeader?(e[XO]=!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 L_(t,e,r){if(e){let n=rV(e)?e.size:pV(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${hn[t.readyState]})`);process.nextTick(r,n)}}function hV(t,e){let r=this[ht];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[ht]!==void 0&&(r._socket.removeListener("data",Up),process.nextTick(eC,r._socket),t===1005?r.close():r.close(t,e))}function gV(){let t=this[ht];t.isPaused||t._socket.resume()}function yV(t){let e=this[ht];e._socket[ht]!==void 0&&(e._socket.removeListener("data",Up),process.nextTick(eC,e._socket),e.close(t[iV])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function JO(){this[ht].emitClose()}function vV(t,e){this[ht].emit("message",t,e)}function _V(t){let e=this[ht];e._autoPong&&e.pong(t,!this._isServer,YO),e.emit("ping",t)}function bV(t){this[ht].emit("pong",t)}function eC(t){t.resume()}function wV(t){let e=this[ht];e.readyState!==Xe.CLOSED&&(e.readyState===Xe.OPEN&&(e._readyState=Xe.CLOSING,tC(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function tC(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function rC(){let t=this[ht];if(this.removeListener("close",rC),this.removeListener("data",Up),this.removeListener("end",nC),t._readyState=Xe.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[ht]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",JO),t._receiver.on("finish",JO))}function Up(t){this[ht]._receiver.write(t)||this.pause()}function nC(){let t=this[ht];t._readyState=Xe.CLOSING,t._receiver.end(),this.end()}function oC(){let t=this[ht];this.removeListener("error",oC),this.on("error",YO),t&&(t._readyState=Xe.CLOSING,this.destroy())}});var lC=I((Zoe,cC)=>{"use strict";var qoe=Fp(),{Duplex:xV}=st("stream");function iC(t){t.emit("close")}function SV(){!this.destroyed&&this._writableState.finished&&this.destroy()}function aC(t){this.removeListener("error",aC),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function $V(t,e){let r=!0,n=new xV({...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(iC,n);return}let i=!1;t.once("error",function(c){i=!0,s(c)}),t.once("close",function(){i||s(o),process.nextTick(iC,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",SV),n.on("error",aC),n}cC.exports=$V});var pC=I((Uoe,uC)=>{"use strict";var{tokenChars:kV}=pi();function EV(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&&kV[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}uC.exports={parse:EV}});var vC=I((Hoe,yC)=>{"use strict";var TV=st("events"),Hp=st("http"),{Duplex:Foe}=st("stream"),{createHash:PV}=st("crypto"),dC=N_(),ns=rc(),RV=pC(),OV=Fp(),{CLOSE_TIMEOUT:CV,GUID:IV,kWebSocket:AV}=dn(),NV=/^[+/0-9A-Za-z]{22}==$/,fC=0,mC=1,gC=2,D_=class extends TV{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:CV,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:OV,...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=Hp.createServer((n,o)=>{let s=Hp.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=zV(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=fC}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===gC){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(ic,this);return}if(e&&this.once("close",e),this._state!==mC)if(this._state=mC,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(ic,this):process.nextTick(ic,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{ic(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",hC);let s=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){os(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){os(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!NV.test(s)){os(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){os(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ac(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=RV.parse(c)}catch{os(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 ns(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let d=dC.parse(u);d[ns.extensionName]&&(f.accept(d[ns.extensionName]),p[ns.extensionName]=f)}catch{os(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,y)=>{if(!d)return ac(r,m||401,h,y);this.completeUpgrade(p,s,l,e,r,n,o)});return}if(!this.options.verifyClient(f))return ac(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[AV])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>fC)return ac(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${PV("sha1").update(r+IV).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[ns.extensionName]){let p=e[ns.extensionName].params,f=dC.format({[ns.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,o),s.write(l.concat(`\r
405
+ `);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 l_,resolve as MB}from"path";import{readdirSync as LB,statSync as DB}from"fs";function u_(t,e,r=""){t=MB(".",t);let n=LB(t),o=0,s,i;for(;o<n.length;o++)s=l_(t,n[o]),i=DB(s),i.isDirectory()?u_(s,e,l_(r,n[o])):e(l_(r,n[o]),s,i)}var VR=w(()=>{});import*as WR from"node:querystring";function JR(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=WR.parse(o.substring(1))))}return t._parsedUrl={pathname:n,search:o,query:s,hash:i,raw:e}}var KR=w(()=>{});function YR(t){let e=(""+t).trim().toLowerCase(),r=e.lastIndexOf(".");return qB[~r?e.substring(++r):e]}var qB,XR=w(()=>{qB={"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 tO={};V(tO,{default:()=>XB});import*as ai from"node:fs";import{join as ZB,normalize as UB,resolve as FB,sep as HB}from"node:path";function GB(t,e){for(let r=0;r<e.length;r++)if(e[r].test(t))return!0}function QR(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 VB(t,e,r){let n=0,o,s=QR(e,r);for(;n<s.length;n++)if(o=t[s[n]])return o}function WB(t,e,r,n){let o=0,s=QR(r,n),i,a,c,l;for(;o<s.length;o++)if(i=UB(ZB(t,c=s[o])),i.startsWith(t)&&ai.existsSync(i)){if(a=ai.statSync(i),a.isDirectory())continue;return l=eO(c,a,e),l["Cache-Control"]=e?"no-cache":"no-store",{abs:i,stats:a,headers:l}}}function JB(t,e){return e.statusCode=404,e.end()}function KB(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),ai.createReadStream(r,a).pipe(e)}function eO(t,e,r){let n=YB[t.slice(-3)],o=YR(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 XB(t,e={}){t=FB(t||".");let r=e.onNoMatch||JB,n=e.setHeaders||BB,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||u_(t,(m,h,y)=>{if(!/\.well-known[\\+\/]/.test(m)){if(!e.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(m))return}let v=eO(m,y,l);f&&(v["Cache-Control"]=f),a["/"+m.normalize().replace(/\\+/g,"/")]={abs:h,stats:y,headers:v}});let d=e.dev?WB.bind(0,t+HB,l):VB.bind(0,a);return function(m,h,y){let v=[""],b=JR(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&&!GB(b,p)&&d(c,v);if(!$)return y?y():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),KB(m,h,$.abs,$.stats,$.headers)}}var BB,YB,rO=w(()=>{VR();KR();XR();BB=()=>{};YB={".br":"br",".gz":"gzip"}});var hn=I((aoe,sO)=>{"use strict";var nO=["nodebuffer","arraybuffer","fragments"],oO=typeof Blob<"u";oO&&nO.push("blob");sO.exports={BINARY_TYPES:nO,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:oO,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Qa=I((coe,Op)=>{"use strict";var{EMPTY_BUFFER:QB}=hn(),p_=Buffer[Symbol.species];function eG(t,e){if(t.length===0)return QB;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 p_(r.buffer,r.byteOffset,n):r}function iO(t,e,r,n,o){for(let s=0;s<o;s++)r[n+s]=t[s]^e[s&3]}function aO(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function tG(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function d_(t){if(d_.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new p_(t):ArrayBuffer.isView(t)?e=new p_(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),d_.readOnly=!1),e}Op.exports={concat:eG,mask:iO,toArrayBuffer:tG,toBuffer:d_,unmask:aO};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=st("bufferutil");Op.exports.mask=function(e,r,n,o,s){s<48?iO(e,r,n,o,s):t.mask(e,r,n,o,s)},Op.exports.unmask=function(e,r){e.length<32?aO(e,r):t.unmask(e,r)}}catch{}});var uO=I((loe,lO)=>{"use strict";var cO=Symbol("kDone"),f_=Symbol("kRun"),m_=class{constructor(e){this[cO]=()=>{this.pending--,this[f_]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[f_]()}[f_](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[cO])}}};lO.exports=m_});var tc=I((uoe,mO)=>{"use strict";var ec=st("zlib"),pO=Qa(),rG=uO(),{kStatusCode:dO}=hn(),nG=Buffer[Symbol.species],oG=Buffer.from([0,0,255,255]),Ip=Symbol("permessage-deflate"),gn=Symbol("total-length"),ci=Symbol("callback"),to=Symbol("buffers"),li=Symbol("error"),Cp,h_=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,!Cp){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;Cp=new rG(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[ci];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){Cp.add(o=>{this._decompress(e,r,(s,i)=>{o(),n(s,i)})})}compress(e,r,n){Cp.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"?ec.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=ec.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[Ip]=this,this._inflate[gn]=0,this._inflate[to]=[],this._inflate.on("error",iG),this._inflate.on("data",fO)}this._inflate[ci]=n,this._inflate.write(e),r&&this._inflate.write(oG),this._inflate.flush(()=>{let s=this._inflate[li];if(s){this._inflate.close(),this._inflate=null,n(s);return}let i=pO.concat(this._inflate[to],this._inflate[gn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gn]=0,this._inflate[to]=[],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"?ec.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=ec.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[gn]=0,this._deflate[to]=[],this._deflate.on("data",sG)}this._deflate[ci]=n,this._deflate.write(e),this._deflate.flush(ec.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=pO.concat(this._deflate[to],this._deflate[gn]);r&&(s=new nG(s.buffer,s.byteOffset,s.length-4)),this._deflate[ci]=null,this._deflate[gn]=0,this._deflate[to]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};mO.exports=h_;function sG(t){this[to].push(t),this[gn]+=t.length}function fO(t){if(this[gn]+=t.length,this[Ip]._maxPayload<1||this[gn]<=this[Ip]._maxPayload){this[to].push(t);return}this[li]=new RangeError("Max payload size exceeded"),this[li].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[li][dO]=1009,this.removeListener("data",fO),this.reset()}function iG(t){if(this[Ip]._inflate=null,this[li]){this[ci](this[li]);return}t[dO]=1007,this[ci](t)}});var ui=I((poe,Ap)=>{"use strict";var{isUtf8:hO}=st("buffer"),{hasBlob:aG}=hn(),cG=[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 lG(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function g_(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 uG(t){return aG&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Ap.exports={isBlob:uG,isValidStatusCode:lG,isValidUTF8:g_,tokenChars:cG};if(hO)Ap.exports.isValidUTF8=function(t){return t.length<24?g_(t):hO(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=st("utf-8-validate");Ap.exports.isValidUTF8=function(e){return e.length<32?g_(e):t(e)}}catch{}});var w_=I((doe,xO)=>{"use strict";var{Writable:pG}=st("stream"),gO=tc(),{BINARY_TYPES:dG,EMPTY_BUFFER:yO,kStatusCode:fG,kWebSocket:mG}=hn(),{concat:y_,toArrayBuffer:hG,unmask:gG}=Qa(),{isValidStatusCode:yG,isValidUTF8:vO}=ui(),Np=Buffer[Symbol.species],wr=0,_O=1,bO=2,wO=3,v_=4,__=5,zp=6,b_=class extends pG{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||dG[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[mG]=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=wr}_write(e,r,n){if(this._opcode===8&&this._state==wr)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 Np(n.buffer,n.byteOffset+e,n.length-e),new Np(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 Np(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 wr:this.getInfo(e);break;case _O:this.getPayloadLength16(e);break;case bO:this.getPayloadLength64(e);break;case wO:this.getMask();break;case v_:this.getData(e);break;case __:case zp: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[gO.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=_O:this._payloadLength===127?this._state=bO: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=wO:this._state=v_}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=v_}getData(e){let r=yO;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]&&gG(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=__,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[gO.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===wr&&this.startLoop(r)})}dataMessage(e){if(!this._fin){this._state=wr;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=y_(n,r):this._binaryType==="arraybuffer"?o=hG(y_(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=wr):(this._state=zp,setImmediate(()=>{this.emit("message",o,!0),this._state=wr,this.startLoop(e)}))}else{let o=y_(n,r);if(!this._skipUTF8Validation&&!vO(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===__||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=wr):(this._state=zp,setImmediate(()=>{this.emit("message",o,!1),this._state=wr,this.startLoop(e)}))}}controlMessage(e,r){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,yO),this.end();else{let n=e.readUInt16BE(0);if(!yG(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new Np(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!vO(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=wr;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=wr):(this._state=zp,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=wr,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[fG]=o,i}};xO.exports=b_});var $_=I((moe,kO)=>{"use strict";var{Duplex:foe}=st("stream"),{randomFillSync:vG}=st("crypto"),SO=tc(),{EMPTY_BUFFER:_G,kWebSocket:bG,NOOP:wG}=hn(),{isBlob:pi,isValidStatusCode:xG}=ui(),{mask:$O,toBuffer:es}=Qa(),xr=Symbol("kByteLength"),SG=Buffer.alloc(4),jp=8*1024,ts,di=jp,zr=0,$G=1,kG=2,x_=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=zr,this.onerror=wG,this[bG]=void 0}static frame(e,r){let n,o=!1,s=2,i=!1;r.mask&&(n=r.maskBuffer||SG,r.generateMask?r.generateMask(n):(di===jp&&(ts===void 0&&(ts=Buffer.alloc(jp)),vG(ts,0,jp),di=0),n[0]=ts[di++],n[1]=ts[di++],n[2]=ts[di++],n[3]=ts[di++]),i=(n[0]|n[1]|n[2]|n[3])===0,s=6);let a;typeof e=="string"?(!r.mask||i)&&r[xr]!==void 0?a=r[xr]:(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?($O(e,n,l,s,a),[l]):($O(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,o){let s;if(e===void 0)s=_G;else{if(typeof e!="number"||!xG(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={[xr]:s.length,fin:!0,generateMask:this._generateMask,mask:n,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==zr?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):pi(e)?(o=e.size,s=!1):(e=es(e),o=e.length,s=es.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[xr]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:9,readOnly:s,rsv1:!1};pi(e)?this._state!==zr?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==zr?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):pi(e)?(o=e.size,s=!1):(e=es(e),o=e.length,s=es.readOnly),o>125)throw new RangeError("The data size must not be greater than 125 bytes");let i={[xr]:o,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:10,readOnly:s,rsv1:!1};pi(e)?this._state!==zr?this.enqueue([this.getBlobData,e,!1,i,n]):this.getBlobData(e,!1,i,n):this._state!==zr?this.enqueue([this.dispatch,e,!1,i,n]):this.sendFrame(t.frame(e,i),n)}send(e,r,n){let o=this._extensions[SO.extensionName],s=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):pi(e)?(a=e.size,c=!1):(e=es(e),a=e.length,c=es.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={[xr]:a,fin:r.fin,generateMask:this._generateMask,mask:r.mask,maskBuffer:this._maskBuffer,opcode:s,readOnly:c,rsv1:i};pi(e)?this._state!==zr?this.enqueue([this.getBlobData,e,this._compress,l,n]):this.getBlobData(e,this._compress,l,n):this._state!==zr?this.enqueue([this.dispatch,e,this._compress,l,n]):this.dispatch(e,this._compress,l,n)}getBlobData(e,r,n,o){this._bufferedBytes+=n[xr],this._state=kG,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(S_,this,a,o);return}this._bufferedBytes-=n[xr];let i=es(s);r?this.dispatch(i,r,n,o):(this._state=zr,this.sendFrame(t.frame(i,n),o),this.dequeue())}).catch(s=>{process.nextTick(EG,this,s,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let s=this._extensions[SO.extensionName];this._bufferedBytes+=n[xr],this._state=$G,s.compress(e,n.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");S_(this,c,o);return}this._bufferedBytes-=n[xr],this._state=zr,n.readOnly=!1,this.sendFrame(t.frame(a,n),o),this.dequeue()})}dequeue(){for(;this._state===zr&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][xr],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][xr],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)}};kO.exports=x_;function S_(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 EG(t,e,r){S_(t,e,r),t.onerror(e)}});var NO=I((hoe,AO)=>{"use strict";var{kForOnEventAttribute:rc,kListener:k_}=hn(),EO=Symbol("kCode"),TO=Symbol("kData"),PO=Symbol("kError"),RO=Symbol("kMessage"),OO=Symbol("kReason"),fi=Symbol("kTarget"),CO=Symbol("kType"),IO=Symbol("kWasClean"),yn=class{constructor(e){this[fi]=null,this[CO]=e}get target(){return this[fi]}get type(){return this[CO]}};Object.defineProperty(yn.prototype,"target",{enumerable:!0});Object.defineProperty(yn.prototype,"type",{enumerable:!0});var rs=class extends yn{constructor(e,r={}){super(e),this[EO]=r.code===void 0?0:r.code,this[OO]=r.reason===void 0?"":r.reason,this[IO]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[EO]}get reason(){return this[OO]}get wasClean(){return this[IO]}};Object.defineProperty(rs.prototype,"code",{enumerable:!0});Object.defineProperty(rs.prototype,"reason",{enumerable:!0});Object.defineProperty(rs.prototype,"wasClean",{enumerable:!0});var mi=class extends yn{constructor(e,r={}){super(e),this[PO]=r.error===void 0?null:r.error,this[RO]=r.message===void 0?"":r.message}get error(){return this[PO]}get message(){return this[RO]}};Object.defineProperty(mi.prototype,"error",{enumerable:!0});Object.defineProperty(mi.prototype,"message",{enumerable:!0});var nc=class extends yn{constructor(e,r={}){super(e),this[TO]=r.data===void 0?null:r.data}get data(){return this[TO]}};Object.defineProperty(nc.prototype,"data",{enumerable:!0});var TG={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[rc]&&o[k_]===e&&!o[rc])return;let n;if(t==="message")n=function(s,i){let a=new nc("message",{data:i?s:s.toString()});a[fi]=this,Mp(e,this,a)};else if(t==="close")n=function(s,i){let a=new rs("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[fi]=this,Mp(e,this,a)};else if(t==="error")n=function(s){let i=new mi("error",{error:s,message:s.message});i[fi]=this,Mp(e,this,i)};else if(t==="open")n=function(){let s=new yn("open");s[fi]=this,Mp(e,this,s)};else return;n[rc]=!!r[rc],n[k_]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[k_]===e&&!r[rc]){this.removeListener(t,r);break}}};AO.exports={CloseEvent:rs,ErrorEvent:mi,Event:yn,EventTarget:TG,MessageEvent:nc};function Mp(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var E_=I((goe,zO)=>{"use strict";var{tokenChars:oc}=ui();function Qr(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&&oc[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?(Qr(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&&oc[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),Qr(r,t.slice(c,u),!0),l===44&&(Qr(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(oc[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),o=!1}else if(s)if(oc[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&&oc[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),Qr(r,a,d),l===44&&(Qr(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?Qr(e,f,r):(a===void 0?Qr(r,f,!0):n?Qr(r,a,f.replace(/\\/g,"")):Qr(r,a,f),Qr(e,i,r)),e}function RG(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(", ")}zO.exports={format:RG,parse:PG}});var Zp=I((_oe,VO)=>{"use strict";var OG=st("events"),CG=st("https"),IG=st("http"),LO=st("net"),AG=st("tls"),{randomBytes:NG,createHash:zG}=st("crypto"),{Duplex:yoe,Readable:voe}=st("stream"),{URL:T_}=st("url"),ro=tc(),jG=w_(),MG=$_(),{isBlob:LG}=ui(),{BINARY_TYPES:jO,CLOSE_TIMEOUT:DG,EMPTY_BUFFER:Lp,GUID:qG,kForOnEventAttribute:P_,kListener:ZG,kStatusCode:UG,kWebSocket:gt,NOOP:DO}=hn(),{EventTarget:{addEventListener:FG,removeEventListener:HG}}=NO(),{format:BG,parse:GG}=E_(),{toBuffer:VG}=Qa(),qO=Symbol("kAborted"),R_=[8,13],vn=["CONNECTING","OPEN","CLOSING","CLOSED"],WG=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Xe=class t extends OG{constructor(e,r,n){super(),this._binaryType=jO[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Lp,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]),ZO(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){jO.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 jG({allowSynchronousEvents:n.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation}),s=new MG(e,this._extensions,n.generateMask);this._receiver=o,this._sender=s,this._socket=e,o[gt]=this,s[gt]=this,e[gt]=this,o.on("conclude",YG),o.on("drain",XG),o.on("error",QG),o.on("message",eV),o.on("ping",tV),o.on("pong",rV),s.onerror=nV,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",HO),e.on("data",qp),e.on("end",BO),e.on("error",GO),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[ro.extensionName]&&this._extensions[ro.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){ir(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())}),FO(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){O_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Lp,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){O_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Lp,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){O_(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[ro.extensionName]||(o.compress=!1),this._sender.send(e||Lp,o,n)}terminate(){if(this.readyState!==t.CLOSED){if(this.readyState===t.CONNECTING){ir(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=t.CLOSING,this._socket.destroy())}}};Object.defineProperty(Xe,"CONNECTING",{enumerable:!0,value:vn.indexOf("CONNECTING")});Object.defineProperty(Xe.prototype,"CONNECTING",{enumerable:!0,value:vn.indexOf("CONNECTING")});Object.defineProperty(Xe,"OPEN",{enumerable:!0,value:vn.indexOf("OPEN")});Object.defineProperty(Xe.prototype,"OPEN",{enumerable:!0,value:vn.indexOf("OPEN")});Object.defineProperty(Xe,"CLOSING",{enumerable:!0,value:vn.indexOf("CLOSING")});Object.defineProperty(Xe.prototype,"CLOSING",{enumerable:!0,value:vn.indexOf("CLOSING")});Object.defineProperty(Xe,"CLOSED",{enumerable:!0,value:vn.indexOf("CLOSED")});Object.defineProperty(Xe.prototype,"CLOSED",{enumerable:!0,value:vn.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(t=>{Object.defineProperty(Xe.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach(t=>{Object.defineProperty(Xe.prototype,`on${t}`,{enumerable:!0,get(){for(let e of this.listeners(t))if(e[P_])return e[ZG];return null},set(e){for(let r of this.listeners(t))if(r[P_]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[P_]:!0})}})});Xe.prototype.addEventListener=FG;Xe.prototype.removeEventListener=HG;VO.exports=Xe;function ZO(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:DG,protocolVersion:R_[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,!R_.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${R_.join(", ")})`);let s;if(e instanceof T_)s=e;else try{s=new T_(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;Dp(t,h);return}let l=i?443:80,u=NG(16).toString("base64"),p=i?CG.request:IG.request,f=new Set,d;if(o.createConnection=o.createConnection||(i?KG:JG),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 ro(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=BG({[ro.extensionName]:d.offer()})),r.length){for(let h of r){if(typeof h!="string"||!WG.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[y,v]of Object.entries(h))n.headers[y.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",()=>{ir(t,m,"Opening handshake has timed out")}),m.on("error",h=>{m===null||m[qO]||(m=t._req=null,Dp(t,h))}),m.on("response",h=>{let y=h.headers.location,v=h.statusCode;if(y&&o.followRedirects&&v>=300&&v<400){if(++t._redirects>o.maxRedirects){ir(t,m,"Maximum redirects exceeded");return}m.abort();let b;try{b=new T_(y,e)}catch{let $=new SyntaxError(`Invalid URL: ${y}`);Dp(t,$);return}ZO(t,b,r,n)}else t.emit("unexpected-response",m,h)||ir(t,m,`Unexpected server response: ${h.statusCode}`)}),m.on("upgrade",(h,y,v)=>{if(t.emit("upgrade",h),t.readyState!==Xe.CONNECTING)return;m=t._req=null;let b=h.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){ir(t,y,"Invalid Upgrade header");return}let x=zG("sha1").update(u+qG).digest("base64");if(h.headers["sec-websocket-accept"]!==x){ir(t,y,"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){ir(t,y,O);return}$&&(t._protocol=$);let ie=h.headers["sec-websocket-extensions"];if(ie!==void 0){if(!d){ir(t,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let X;try{X=GG(ie)}catch{ir(t,y,"Invalid Sec-WebSocket-Extensions header");return}let ee=Object.keys(X);if(ee.length!==1||ee[0]!==ro.extensionName){ir(t,y,"Server indicated an extension that was not requested");return}try{d.accept(X[ro.extensionName])}catch{ir(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[ro.extensionName]=d}t.setSocket(y,v,{allowSynchronousEvents:o.allowSynchronousEvents,generateMask:o.generateMask,maxPayload:o.maxPayload,skipUTF8Validation:o.skipUTF8Validation})}),o.finishRequest?o.finishRequest(m,t):m.end()}function Dp(t,e){t._readyState=Xe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function JG(t){return t.path=t.socketPath,LO.connect(t)}function KG(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=LO.isIP(t.host)?"":t.host),AG.connect(t)}function ir(t,e,r){t._readyState=Xe.CLOSING;let n=new Error(r);Error.captureStackTrace(n,ir),e.setHeader?(e[qO]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Dp,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function O_(t,e,r){if(e){let n=LG(e)?e.size:VG(e).length;t._socket?t._sender._bufferedBytes+=n:t._bufferedAmount+=n}if(r){let n=new Error(`WebSocket is not open: readyState ${t.readyState} (${vn[t.readyState]})`);process.nextTick(r,n)}}function YG(t,e){let r=this[gt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[gt]!==void 0&&(r._socket.removeListener("data",qp),process.nextTick(UO,r._socket),t===1005?r.close():r.close(t,e))}function XG(){let t=this[gt];t.isPaused||t._socket.resume()}function QG(t){let e=this[gt];e._socket[gt]!==void 0&&(e._socket.removeListener("data",qp),process.nextTick(UO,e._socket),e.close(t[UG])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function MO(){this[gt].emitClose()}function eV(t,e){this[gt].emit("message",t,e)}function tV(t){let e=this[gt];e._autoPong&&e.pong(t,!this._isServer,DO),e.emit("ping",t)}function rV(t){this[gt].emit("pong",t)}function UO(t){t.resume()}function nV(t){let e=this[gt];e.readyState!==Xe.CLOSED&&(e.readyState===Xe.OPEN&&(e._readyState=Xe.CLOSING,FO(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function FO(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function HO(){let t=this[gt];if(this.removeListener("close",HO),this.removeListener("data",qp),this.removeListener("end",BO),t._readyState=Xe.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[gt]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted?t.emitClose():(t._receiver.on("error",MO),t._receiver.on("finish",MO))}function qp(t){this[gt]._receiver.write(t)||this.pause()}function BO(){let t=this[gt];t._readyState=Xe.CLOSING,t._receiver.end(),this.end()}function GO(){let t=this[gt];this.removeListener("error",GO),this.on("error",DO),t&&(t._readyState=Xe.CLOSING,this.destroy())}});var YO=I((woe,KO)=>{"use strict";var boe=Zp(),{Duplex:oV}=st("stream");function WO(t){t.emit("close")}function sV(){!this.destroyed&&this._writableState.finished&&this.destroy()}function JO(t){this.removeListener("error",JO),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function iV(t,e){let r=!0,n=new oV({...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(WO,n);return}let i=!1;t.once("error",function(c){i=!0,s(c)}),t.once("close",function(){i||s(o),process.nextTick(WO,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",sV),n.on("error",JO),n}KO.exports=iV});var QO=I((xoe,XO)=>{"use strict";var{tokenChars:aV}=ui();function cV(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&&aV[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}XO.exports={parse:cV}});var iC=I(($oe,sC)=>{"use strict";var lV=st("events"),Up=st("http"),{Duplex:Soe}=st("stream"),{createHash:uV}=st("crypto"),eC=E_(),ns=tc(),pV=QO(),dV=Zp(),{CLOSE_TIMEOUT:fV,GUID:mV,kWebSocket:hV}=hn(),gV=/^[+/0-9A-Za-z]{22}==$/,tC=0,rC=1,oC=2,C_=class extends lV{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:fV,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:dV,...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=Up.createServer((n,o)=>{let s=Up.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=yV(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=tC}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===oC){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(sc,this);return}if(e&&this.once("close",e),this._state!==rC)if(this._state=rC,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(sc,this):process.nextTick(sc,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{sc(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",nC);let s=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){os(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){os(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!gV.test(s)){os(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){os(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){ic(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=pV.parse(c)}catch{os(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 ns(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let d=eC.parse(u);d[ns.extensionName]&&(f.accept(d[ns.extensionName]),p[ns.extensionName]=f)}catch{os(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,y)=>{if(!d)return ic(r,m||401,h,y);this.completeUpgrade(p,s,l,e,r,n,o)});return}if(!this.options.verifyClient(f))return ic(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[hV])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>tC)return ic(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${uV("sha1").update(r+mV).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[ns.extensionName]){let p=e[ns.extensionName].params,f=eC.format({[ns.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,o),s.write(l.concat(`\r
405
406
  `).join(`\r
406
- `)),s.removeListener("error",hC),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(ic,this)})),a(u,o)}};yC.exports=D_;function zV(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 ic(t){t._state=gC,t.emit("close")}function hC(){this.destroy()}function ac(t,e,r,n){r=r||Hp.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} ${Hp.STATUS_CODES[e]}\r
407
+ `)),s.removeListener("error",nC),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(sc,this)})),a(u,o)}};sC.exports=C_;function yV(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 sc(t){t._state=oC,t.emit("close")}function nC(){this.destroy()}function ic(t,e,r,n){r=r||Up.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} ${Up.STATUS_CODES[e]}\r
407
408
  `+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
408
409
  `)+`\r
409
410
  \r
410
- `+r)}function os(t,e,r,n,o,s){if(t.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,os),t.emit("wsClientError",i,r,e)}else ac(r,n,o,s)}});var SC={};V(SC,{Receiver:()=>bC.default,Sender:()=>wC.default,WebSocket:()=>q_.default,WebSocketServer:()=>xC.default,createWebSocketStream:()=>_C.default,default:()=>jV});var _C,bC,wC,q_,xC,jV,$C=w(()=>{_C=io(lC(),1),bC=io(R_(),1),wC=io(I_(),1),q_=io(Fp(),1),xC=io(vC(),1),jV=q_.default});var kC={};V(kC,{setupWebSocket:()=>LV});async function MV(){let t=await Promise.resolve().then(()=>($C(),SC));return(t.default??t).WebSocketServer}async function LV(t,e,r,n,o,s){let i=o??await MV(),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=>{DV(f,p,e,r,n,s)})}),{close(){a.close()}}}function DV(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 y(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:de}=await Promise.resolve().then(()=>(Qo(),ii)),F=de(s.module,ee,f,p);y({type:"event",event:X,...F?{inject:F}:{}})}else y({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 de of X)v(de)&&(await b(de),h=Math.max(h,de.id));if(h=Math.max(h,ee),y({type:"replay_done",cursor:h}),s){let{danceToolDefs:de}=await Promise.resolve().then(()=>(Qo(),ii));y({type:"dance_tools",tools:de(s.module)})}m=!1;for(let de of d)de.id>h&&await b(de);d.length=0,o&&console.error(`[incubator] WS client connected: ns=${i} since=${c??"start"} replayed=${X.length}`)}).catch(X=>{y({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(F=>{n.publish(i,F),y({type:"publish_ack",eventId:F.id})}).catch(()=>{y({type:"error",message:"Failed to publish event"})});else if(ee.type==="reset"){let de=r.get(i);de.state.getAll().then(async F=>{for(let ct of F)await de.state.delete(ct.key);let ne=await de.events.publish("reset",{},"ui");n.publish(i,ne),y({type:"reset_ack"}),o&&console.error(`[incubator] WS reset: ns=${i} (cleared ${F.length} keys)`)}).catch(()=>{y({type:"error",message:"Failed to reset state"})})}else if(ee.type==="dance_call"&&s&&typeof ee.tool=="string"){let de=ee.agentId??p??"unknown",F=ee.role??f??"unknown",ne=ee.callId,ct=()=>s.getState(i),kt=s.getAcpHelper(i,de),re=Date.now();Promise.resolve().then(()=>(Qo(),ii)).then(({callDanceTool:le})=>le(s.module,ee.tool,ee.args??{},F,de,ct,kt)).then(le=>{let At="error"in le?{error:le.error}:le.result;s?.telemetry?.record("dance_call",{tool:ee.tool,role:F,agentId:de,success:!("error"in le),latency_ms:Date.now()-re}),y({type:"dance_result",callId:ne,result:At})}).catch(le=>{s?.telemetry?.record("dance_call",{tool:ee.tool,role:F,agentId:de,success:!1,error:le.message,latency_ms:Date.now()-re}),y({type:"dance_result",callId:ne,result:{error:le.message}})})}}catch{}});let O=setInterval(()=>{y({type:"ping",ts:Date.now()})},3e4),ie=()=>{clearInterval(O),x(),o&&console.error(`[incubator] WS client disconnected: ns=${i}`)};t.on("close",ie),t.on("error",ie)}var EC=w(()=>{});var U_={};V(U_,{main:()=>FV});import{createServer as qV}from"node:http";import{createServer as ZV}from"node:https";import{randomUUID as TC}from"node:crypto";import{fileURLToPath as PC}from"node:url";import{dirname as Bp,join as RC,resolve as cc}from"node:path";import{existsSync as Z_,readFileSync as Gp}from"node:fs";function UV(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 FV(){let t=UV(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",y=d==="sqlite",v=d==="redis";y&&!m&&(console.error("[incubator] SQLite backend requires --db=<path>"),process.exit(1)),(y||v)&&s&&console.error(`[incubator] WARNING: --persist is ignored with ${d} backend (data is already persistent)`);let b;if(v){let{getRedisClient:re,waitForReady:le}=await Promise.resolve().then(()=>(h_(),m_));b=re(h),await le(b)}let x={type:d,dbPath:m,redisClient:b},$=y||v,O=typeof t.protocol=="string"?t.protocol:void 0,ie=typeof t.dances=="string"?t.dances:void 0,X;if(typeof t.agents=="string")try{X=JSON.parse(t.agents)}catch(re){console.error(`[incubator] Failed to parse --agents JSON: ${re.message}`),process.exit(1)}let ee=[];for(let re of process.argv.slice(2))re.startsWith("--integration=")&&ee.push(re.slice(14));let de=ee.length>0||t.integrations===!0,F=new bp(x),ne;if(a)console.error("[incubator] WARNING: Carapace disabled \u2014 no prompt injection scanning");else{let re=zP(i);F.setGuard(re,i),ne=le=>MP(le,re,i),console.error("[incubator] Carapace active \u2014 scanning writes, reads, and snapshots")}if(s&&!$){let re=await iR(s,F,ne);re>0&&console.error(`[incubator] Restored ${re} namespace(s) from ${s}`)}if(O)try{let re=await Oc(O);F.setProtocol("default",re),r&&re.name!=="default"&&F.setProtocol(re.name,re),console.error(`[incubator] Protocol loaded: "${re.title}" (${re.name})`)}catch(re){console.error(`[incubator] Failed to load protocol: ${re.message}`),process.exit(1)}let ct,kt=ie;if(!kt&&f)try{let re=Gp(cc(f),"utf-8"),le=f.endsWith(".json")?JSON.parse(re):Qr.load(re),At=le.hives??{},oe=Object.values(At)[0],ve=oe?.dances??oe?.logic??le.dances??le.logic;typeof ve=="string"&&(kt=cc(Bp(f),ve))}catch{}if(kt){let{loadDances:re}=await Promise.resolve().then(()=>(Qo(),ii)),le=cc(kt),At=new URL(`file://${le}`).href;ct=await re(At);let oe=[...ct.tools.keys()];console.error(`[incubator] Dances loaded: ${oe.join(", ")}${ct.inject?" + inject":""}`)}if(console.error(y?`[incubator] Backend: sqlite (${m})`:v?`[incubator] Backend: redis (${h})`:"[incubator] Backend: memory"),r){let re=new Map,le;if(v&&b){let K=b.duplicate(),{waitForReady:ae}=await Promise.resolve().then(()=>(h_(),m_));await ae(K),le=new Sp(b,K)}else le=new xp;let At,oe=process.env.HONEYCOMB_BROKER_SOCKET,ve=process.env.HONEYCOMB_HIVE_NAME;if(oe&&ve){let K=process.env.HONEYCOMB_PUBLISHES?.split(",").filter(Boolean)??[],ae=process.env.HONEYCOMB_SUBSCRIBES?.split(",").filter(Boolean)??[],{IPCTransport:Le}=await Promise.resolve().then(()=>(oO(),nO)),me=new Le({socketPath:oe,hiveName:ve,publishes:K,subscribes:ae});await me.connect(),console.error(`[incubator] Honeycomb: connected to broker as "${ve}"`),At={transport:me,hiveName:ve,hivePublishes:K,hiveSubscribes:ae}}F.setBus(le,At);let Qe=F.get("default"),Yr=new $p(le,Qe.runs);Yr.start();let je=[],M=new Cp(i);if(O){let K=F.getProtocol("default");K?.governance?.webhooks?.length&&M.register("default",K.governance.webhooks,le)}let B=u?"https":"http",wr=u?"wss":"ws",ot,Re;try{let K=await Promise.resolve().then(()=>(mO(),fO)),ae=K.default??K,Le=Bp(PC(import.meta.url)),me=RC(Le,"..","dashboard","dist");Z_(me)&&(ot=ae(me,{single:!0,dev:!0}),console.error(`[incubator] Dashboard: ${B}://localhost:${n}/dashboard`)),p&&Z_(p)&&(Re=ae(p,{single:!0,dev:!0}),console.error(`[incubator] Static: ${B}://localhost:${n}/`))}catch{}let Yt=async(K,ae)=>{if(K.url?.startsWith("/api/")){await LP(K,ae,F,i);return}let Le=new URL(K.url??"/",`${B}://localhost:${n}`);if(Le.pathname==="/dashboard"||Le.pathname.startsWith("/dashboard/")){if(ot){let xr=K.url;K.url=Le.pathname.replace(/^\/dashboard/,"")||"/",Le.search&&(K.url+=Le.search),ot(K,ae,()=>{K.url=xr,ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Not found."}))});return}ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Dashboard not available."}));return}if(Le.pathname!=="/mcp"){if(Le.pathname==="/"&&!Re&&ot){ae.writeHead(302,{Location:"/dashboard"}),ae.end();return}Re?Re(K,ae,()=>{ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."}))}):(ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."})));return}let me=K.headers["x-namespace"]||"default",Ge=F.get(me),Ce=K.headers["mcp-session-id"];if(Ce&&re.has(Ce)){await re.get(Ce).transport.handleRequest(K,ae);return}let ge=`agent_${TC().slice(0,8)}`,dt=new ql({sessionIdGenerator:()=>TC(),onsessioninitialized:xr=>{let _i=me==="default"?"":`@${me}`;console.error(`[incubator] Session ${xr} started (${ge}${_i})`),re.set(xr,{server:dc,transport:dt})}});dt.onclose=()=>{let xr=dt.sessionId;xr&&(re.delete(xr),console.error(`[incubator] Session ${xr} closed`))};let dc=qv(Ge,{agentId:ge,namespace:me,persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!$?()=>{wp(s,F)}:void 0,getProtocol:()=>F.getProtocol(me)});await dc.connect(dt),await dt.handleRequest(K,ae)},ls=u?ZV({key:Gp(l),cert:Gp(c)},Yt):qV(Yt),Nr;if(ct){let{buildAcpHelper:K}=await Promise.resolve().then(()=>(Qo(),ii));Nr={module:ct,getState:async ae=>{let me=await F.get(ae).state.query(),Ge={};for(let Ce of me)Ge[Ce.key]=typeof Ce.value=="string"?Ce.value:JSON.stringify(Ce.value);return Ge},getAcpHelper:(ae,Le)=>{let me=F.get(ae);return K({publishEvent:async(Ge,Ce,ge,dt)=>{let vi=await me.events.publish(Ce,ge??{},dt??Le);le.publish(ae,vi)},claimResource:async(Ge,Ce,ge,dt)=>(await me.claims.claim(Ce,Ce,ge,dt)).claim.resource,releaseResource:async(Ge,Ce)=>{await me.claims.release(Ce,Le)},setState:async(Ge,Ce,ge)=>{await me.state.set(Ce,ge,Le)}},ae,Le)}}}let gn;try{let{setupWebSocket:K}=await Promise.resolve().then(()=>(EC(),kC));gn=await K(ls,F,le,i,void 0,Nr)}catch{}if(f){let K=Gp(cc(f),"utf-8"),ae=f.endsWith(".json")?JSON.parse(K):Qr.load(K),Le=ae.hives??{},me=Object.values(Le)[0],Ge=(me?.agents??me?.workers??[]).map(Xt=>({role:String(Xt.role??""),type:Xt.type??"worker",prompt:typeof Xt.prompt=="string"?Xt.prompt:void 0,wakeOn:Xt.wake_on?{types:Xt.wake_on.types,maxWakes:Xt.wake_on.max_wakes}:void 0})),Ce=me?.acp??me?.spec??me?.protocol;if(typeof Ce=="string"&&O===void 0){let Xt=cc(Bp(f),Ce);if(Z_(Xt)){let so=await Oc(Xt);if(F.setProtocol("default",so),console.error(`[incubator] Protocol loaded from brood: ${Ce}`),Ge.length===0&&so.roles){for(let[fc,mc]of Object.entries(so.roles)){let DI=typeof mc.agents=="number"?mc.agents:1;for(let ib=0;ib<DI;ib++)Ge.push({role:fc,type:"worker",prompt:void 0,wakeOn:void 0})}console.error(`[incubator] Derived ${Ge.length} agents from spec roles`)}}}let ge=typeof ae.stagger=="number"?ae.stagger:0,dt=typeof ae.provider=="string"?ae.provider:"ollama/qwen3:8b",vi=ae.env??{},dc=Bp(PC(import.meta.url)),xr=RC(dc,"agent","cli.js");console.error(`[incubator] Brood loaded: ${Ge.length} agents (${dt}), waiting for "start" event`);let _i=!1;le.subscribe("default",Xt=>{if(Xt.type==="start"&&!_i){_i=!0,console.error("[orchestrator] Start event received, spawning agents...");let so={provider:dt,stagger:ge,noAcp:!1,propolisPort:0,worktree:process.cwd(),hiveEntry:xr,tls:u,env:vi,agents:Ge},fc=new Qa(so,n,le,Qe.runs,i,Qe,F,Nr?.module);fc.start().catch(mc=>{console.error(`[orchestrator] Spawn failed: ${mc.message}`)}),je.push(fc)}if(Xt.type==="reset"){_i=!1;for(let so of je)so.shutdown().catch(()=>{});je.length=0,console.error("[orchestrator] Reset \u2014 agents stopped, ready for new game")}})}let Et;if(de){let K=F.get("default");Et=new Ga({namespace:"default",bus:le,eventStore:K.events,verbose:i});let ae=Bv();if(ee.length>0)for(let me of ee){let Ge=ae[me];if(Ge)try{await Et.load(me,Ge.package,Ge.config)}catch(Ce){console.error(`[integrations] Failed to load "${me}": ${Ce.message}`)}else try{await Et.load(me,me)}catch(Ce){console.error(`[integrations] Failed to load "${me}": ${Ce.message}`)}}else await Et.loadFromConfig(ae);let Le=Et.getLoadedNames();if(Le.length>0){console.error(`[incubator] Integrations: ${Le.join(", ")}`);let me=Et.getTools();me.length>0&&console.error(`[incubator] Integration tools: ${me.map(Ge=>Ge.name).join(", ")}`)}}ls.listen(n,()=>{console.error(`[incubator] ${u?"HTTPS":"HTTP"} server listening on port ${n}`),console.error(`[incubator] MCP endpoint: ${B}://localhost:${n}/mcp`),console.error(`[incubator] REST API: ${B}://localhost:${n}/api/`),console.error(gn?`[incubator] WebSocket: ${wr}://localhost:${n}/ws`:'[incubator] WebSocket: disabled (install "ws" to enable)'),s&&!$&&console.error(`[incubator] Persistence: ${s}`),X&&(Tt=new Qa(X,n,le,Qe.runs,i,Qe,F,Nr?.module),Tt.start().catch(K=>{console.error(`[orchestrator] Fatal: ${K.message}`),process.exit(1)}))});let Tt;process.on("SIGINT",async()=>{console.error(`
411
- [incubator] Shutting down...`),Tt&&await Tt.shutdown();for(let K of je)await K.shutdown();Yr.stop(),M.close(),Et&&await Et.stopAll(),gn&&gn.close(),await le.close(),s&&!$&&(await wp(s,F),console.error("[incubator] Snapshots saved")),b&&(await b.quit(),console.error("[incubator] Redis disconnected"));for(let[,K]of re)K.server.close();ls.close(),process.exit(0)})}else{let re=F.get("default"),At=qv(re,{agentId:o??"agent_stdio",persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!$?()=>{wp(s,F)}:void 0,getProtocol:()=>F.getProtocol("default")}),oe=new zl;await At.connect(oe),console.error(`[incubator] Running on stdio (agent: ${o??"agent_stdio"})`),s&&!$&&console.error(`[incubator] Persistence: ${s}`)}}var F_=w(()=>{i$();v$();Zv();DP();up();oR();aR();cR();Pi();Ni();dR();fR();eO();tO()});var OC={};V(OC,{serve:()=>HV});async function HV(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
411
+ `+r)}function os(t,e,r,n,o,s){if(t.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,os),t.emit("wsClientError",i,r,e)}else ic(r,n,o,s)}});var pC={};V(pC,{Receiver:()=>cC.default,Sender:()=>lC.default,WebSocket:()=>I_.default,WebSocketServer:()=>uC.default,createWebSocketStream:()=>aC.default,default:()=>vV});var aC,cC,lC,I_,uC,vV,dC=w(()=>{aC=ao(YO(),1),cC=ao(w_(),1),lC=ao($_(),1),I_=ao(Zp(),1),uC=ao(iC(),1),vV=I_.default});var fC={};V(fC,{setupWebSocket:()=>bV});async function _V(){let t=await Promise.resolve().then(()=>(dC(),pC));return(t.default??t).WebSocketServer}async function bV(t,e,r,n,o,s){let i=o??await _V(),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=>{wV(f,p,e,r,n,s)})}),{close(){a.close()}}}function wV(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 y(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:de}=await Promise.resolve().then(()=>(Qo(),si)),F=de(s.module,ee,f,p);y({type:"event",event:X,...F?{inject:F}:{}})}else y({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 de of X)v(de)&&(await b(de),h=Math.max(h,de.id));if(h=Math.max(h,ee),y({type:"replay_done",cursor:h}),s){let{danceToolDefs:de}=await Promise.resolve().then(()=>(Qo(),si));y({type:"dance_tools",tools:de(s.module)})}m=!1;for(let de of d)de.id>h&&await b(de);d.length=0,o&&console.error(`[incubator] WS client connected: ns=${i} since=${c??"start"} replayed=${X.length}`)}).catch(X=>{y({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(F=>{n.publish(i,F),y({type:"publish_ack",eventId:F.id})}).catch(()=>{y({type:"error",message:"Failed to publish event"})});else if(ee.type==="reset"){let de=r.get(i);de.state.getAll().then(async F=>{for(let ct of F)await de.state.delete(ct.key);let ne=await de.events.publish("reset",{},"ui");n.publish(i,ne),y({type:"reset_ack"}),o&&console.error(`[incubator] WS reset: ns=${i} (cleared ${F.length} keys)`)}).catch(()=>{y({type:"error",message:"Failed to reset state"})})}else if(ee.type==="dance_call"&&s&&typeof ee.tool=="string"){let de=ee.agentId??p??"unknown",F=ee.role??f??"unknown",ne=ee.callId,ct=()=>s.getState(i),Et=s.getAcpHelper(i,de),re=Date.now();Promise.resolve().then(()=>(Qo(),si)).then(({callDanceTool:le})=>le(s.module,ee.tool,ee.args??{},F,de,ct,Et)).then(le=>{let Nt="error"in le?{error:le.error}:le.result;s?.telemetry?.record("dance_call",{tool:ee.tool,role:F,agentId:de,success:!("error"in le),latency_ms:Date.now()-re}),y({type:"dance_result",callId:ne,result:Nt})}).catch(le=>{s?.telemetry?.record("dance_call",{tool:ee.tool,role:F,agentId:de,success:!1,error:le.message,latency_ms:Date.now()-re}),y({type:"dance_result",callId:ne,result:{error:le.message}})})}}catch{}});let O=setInterval(()=>{y({type:"ping",ts:Date.now()})},3e4),ie=()=>{clearInterval(O),x(),o&&console.error(`[incubator] WS client disconnected: ns=${i}`)};t.on("close",ie),t.on("error",ie)}var mC=w(()=>{});var N_={};V(N_,{main:()=>kV});import{createServer as xV}from"node:http";import{createServer as SV}from"node:https";import{randomUUID as hC}from"node:crypto";import{fileURLToPath as gC}from"node:url";import{dirname as Fp,join as yC,resolve as ac}from"node:path";import{existsSync as A_,readFileSync as Hp}from"node:fs";function $V(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 kV(){let t=$V(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",y=d==="sqlite",v=d==="redis";y&&!m&&(console.error("[incubator] SQLite backend requires --db=<path>"),process.exit(1)),(y||v)&&s&&console.error(`[incubator] WARNING: --persist is ignored with ${d} backend (data is already persistent)`);let b;if(v){let{getRedisClient:re,waitForReady:le}=await Promise.resolve().then(()=>(a_(),i_));b=re(h),await le(b)}let x={type:d,dbPath:m,redisClient:b},$=y||v,O=typeof t.protocol=="string"?t.protocol:void 0,ie=typeof t.dances=="string"?t.dances:void 0,X;if(typeof t.agents=="string")try{X=JSON.parse(t.agents)}catch(re){console.error(`[incubator] Failed to parse --agents JSON: ${re.message}`),process.exit(1)}let ee=[];for(let re of process.argv.slice(2))re.startsWith("--integration=")&&ee.push(re.slice(14));let de=ee.length>0||t.integrations===!0,F=new vp(x),ne;if(a)console.error("[incubator] WARNING: Carapace disabled \u2014 no prompt injection scanning");else{let re=SP(i);F.setGuard(re,i),ne=le=>kP(le,re,i),console.error("[incubator] Carapace active \u2014 scanning writes, reads, and snapshots")}if(s&&!$){let re=await WP(s,F,ne);re>0&&console.error(`[incubator] Restored ${re} namespace(s) from ${s}`)}if(O)try{let re=await Rc(O);F.setProtocol("default",re),r&&re.name!=="default"&&F.setProtocol(re.name,re),console.error(`[incubator] Protocol loaded: "${re.title}" (${re.name})`)}catch(re){console.error(`[incubator] Failed to load protocol: ${re.message}`),process.exit(1)}let ct,Et=ie;if(!Et&&f)try{let re=Hp(ac(f),"utf-8"),le=f.endsWith(".json")?JSON.parse(re):rn.load(re),Nt=le.hives??{},oe=Object.values(Nt)[0],ve=oe?.dances??oe?.logic??le.dances??le.logic;typeof ve=="string"&&(Et=ac(Fp(f),ve))}catch{}if(Et){let{loadDances:re}=await Promise.resolve().then(()=>(Qo(),si)),le=ac(Et),Nt=new URL(`file://${le}`).href;ct=await re(Nt);let oe=[...ct.tools.keys()];console.error(`[incubator] Dances loaded: ${oe.join(", ")}${ct.inject?" + inject":""}`)}if(console.error(y?`[incubator] Backend: sqlite (${m})`:v?`[incubator] Backend: redis (${h})`:"[incubator] Backend: memory"),r){let re=new Map,le;if(v&&b){let K=b.duplicate(),{waitForReady:ae}=await Promise.resolve().then(()=>(a_(),i_));await ae(K),le=new wp(b,K)}else le=new bp;let Nt,oe=process.env.HONEYCOMB_BROKER_SOCKET,ve=process.env.HONEYCOMB_HIVE_NAME;if(oe&&ve){let K=process.env.HONEYCOMB_PUBLISHES?.split(",").filter(Boolean)??[],ae=process.env.HONEYCOMB_SUBSCRIBES?.split(",").filter(Boolean)??[],{IPCTransport:Le}=await Promise.resolve().then(()=>(GR(),BR)),me=new Le({socketPath:oe,hiveName:ve,publishes:K,subscribes:ae});await me.connect(),console.error(`[incubator] Honeycomb: connected to broker as "${ve}"`),Nt={transport:me,hiveName:ve,hivePublishes:K,hiveSubscribes:ae}}F.setBus(le,Nt);let Qe=F.get("default"),en=new xp(le,Qe.runs);en.start();let je=[],M=new Rp(i);if(O){let K=F.getProtocol("default");K?.governance?.webhooks?.length&&M.register("default",K.governance.webhooks,le)}let H=u?"https":"http",zt=u?"wss":"ws",nt,Ee;try{let K=await Promise.resolve().then(()=>(rO(),tO)),ae=K.default??K,Le=Fp(gC(import.meta.url)),me=yC(Le,"..","dashboard","dist");A_(me)&&(nt=ae(me,{single:!0,dev:!0}),console.error(`[incubator] Dashboard: ${H}://localhost:${n}/dashboard`)),p&&A_(p)&&(Ee=ae(p,{single:!0,dev:!0}),console.error(`[incubator] Static: ${H}://localhost:${n}/`))}catch{}let lt=async(K,ae)=>{if(K.url?.startsWith("/api/")){await EP(K,ae,F,i);return}let Le=new URL(K.url??"/",`${H}://localhost:${n}`);if(Le.pathname==="/dashboard"||Le.pathname.startsWith("/dashboard/")){if(nt){let $r=K.url;K.url=Le.pathname.replace(/^\/dashboard/,"")||"/",Le.search&&(K.url+=Le.search),nt(K,ae,()=>{K.url=$r,ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Not found."}))});return}ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Dashboard not available."}));return}if(Le.pathname!=="/mcp"){if(Le.pathname==="/"&&!Ee&&nt){ae.writeHead(302,{Location:"/dashboard"}),ae.end();return}Ee?Ee(K,ae,()=>{ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."}))}):(ae.writeHead(404,{"Content-Type":"application/json"}),ae.end(JSON.stringify({error:"Not found. Use /mcp or /api/ endpoints."})));return}let me=K.headers["x-namespace"]||"default",Ge=F.get(me),Ce=K.headers["mcp-session-id"];if(Ce&&re.has(Ce)){await re.get(Ce).transport.handleRequest(K,ae);return}let ge=`agent_${hC().slice(0,8)}`,ft=new Ll({sessionIdGenerator:()=>hC(),onsessioninitialized:$r=>{let vi=me==="default"?"":`@${me}`;console.error(`[incubator] Session ${$r} started (${ge}${vi})`),re.set($r,{server:pc,transport:ft})}});ft.onclose=()=>{let $r=ft.sessionId;$r&&(re.delete($r),console.error(`[incubator] Session ${$r} closed`))};let pc=Iv(Ge,{agentId:ge,namespace:me,persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!$?()=>{_p(s,F)}:void 0,getProtocol:()=>F.getProtocol(me)});await pc.connect(ft),await ft.handleRequest(K,ae)},jr=u?SV({key:Hp(l),cert:Hp(c)},lt):xV(lt),Qt;if(ct){let{buildAcpHelper:K}=await Promise.resolve().then(()=>(Qo(),si));Qt={module:ct,getState:async ae=>{let me=await F.get(ae).state.query(),Ge={};for(let Ce of me)Ge[Ce.key]=typeof Ce.value=="string"?Ce.value:JSON.stringify(Ce.value);return Ge},getAcpHelper:(ae,Le)=>{let me=F.get(ae);return K({publishEvent:async(Ge,Ce,ge,ft)=>{let yi=await me.events.publish(Ce,ge??{},ft??Le);le.publish(ae,yi)},claimResource:async(Ge,Ce,ge,ft)=>(await me.claims.claim(Ce,Ce,ge,ft)).claim.resource,releaseResource:async(Ge,Ce)=>{await me.claims.release(Ce,Le)},setState:async(Ge,Ce,ge)=>{await me.state.set(Ce,ge,Le)}},ae,Le)}}}let Sr;try{let{setupWebSocket:K}=await Promise.resolve().then(()=>(mC(),fC));Sr=await K(jr,F,le,i,void 0,Qt)}catch{}if(f){let K=Hp(ac(f),"utf-8"),ae=f.endsWith(".json")?JSON.parse(K):rn.load(K),Le=ae.hives??{},me=Object.values(Le)[0],Ge=(me?.agents??me?.workers??[]).map(er=>({role:String(er.role??""),type:er.type??"worker",prompt:typeof er.prompt=="string"?er.prompt:void 0,wakeOn:er.wake_on?{types:er.wake_on.types,maxWakes:er.wake_on.max_wakes}:void 0})),Ce=me?.acp??me?.spec??me?.protocol;if(typeof Ce=="string"&&O===void 0){let er=ac(Fp(f),Ce);if(A_(er)){let io=await Rc(er);if(F.setProtocol("default",io),console.error(`[incubator] Protocol loaded from brood: ${Ce}`),Ge.length===0&&io.roles){for(let[dc,fc]of Object.entries(io.roles)){let TI=typeof fc.agents=="number"?fc.agents:1;for(let Q_=0;Q_<TI;Q_++)Ge.push({role:dc,type:"worker",prompt:void 0,wakeOn:void 0})}console.error(`[incubator] Derived ${Ge.length} agents from spec roles`)}}}let ge=typeof ae.stagger=="number"?ae.stagger:0,ft=typeof ae.provider=="string"?ae.provider:"ollama/qwen3:8b",yi=ae.env??{},pc=Fp(gC(import.meta.url)),$r=yC(pc,"agent","cli.js");console.error(`[incubator] Brood loaded: ${Ge.length} agents (${ft}), waiting for "start" event`);let vi=!1;le.subscribe("default",er=>{if(er.type==="start"&&!vi){vi=!0,console.error("[orchestrator] Start event received, spawning agents...");let io={provider:ft,stagger:ge,noAcp:!1,propolisPort:0,worktree:process.cwd(),hiveEntry:$r,tls:u,env:yi,agents:Ge},dc=new Xa(io,n,le,Qe.runs,i,Qe,F,Qt?.module);dc.start().catch(fc=>{console.error(`[orchestrator] Spawn failed: ${fc.message}`)}),je.push(dc)}if(er.type==="reset"){vi=!1;for(let io of je)io.shutdown().catch(()=>{});je.length=0,console.error("[orchestrator] Reset \u2014 agents stopped, ready for new game")}})}let Tt;if(de){let K=F.get("default");Tt=new Ba({namespace:"default",bus:le,eventStore:K.events,verbose:i});let ae=Mv();if(ee.length>0)for(let me of ee){let Ge=ae[me];if(Ge)try{await Tt.load(me,Ge.package,Ge.config)}catch(Ce){console.error(`[integrations] Failed to load "${me}": ${Ce.message}`)}else try{await Tt.load(me,me)}catch(Ce){console.error(`[integrations] Failed to load "${me}": ${Ce.message}`)}}else await Tt.loadFromConfig(ae);let Le=Tt.getLoadedNames();if(Le.length>0){console.error(`[incubator] Integrations: ${Le.join(", ")}`);let me=Tt.getTools();me.length>0&&console.error(`[incubator] Integration tools: ${me.map(Ge=>Ge.name).join(", ")}`)}}jr.listen(n,()=>{console.error(`[incubator] ${u?"HTTPS":"HTTP"} server listening on port ${n}`),console.error(`[incubator] MCP endpoint: ${H}://localhost:${n}/mcp`),console.error(`[incubator] REST API: ${H}://localhost:${n}/api/`),console.error(Sr?`[incubator] WebSocket: ${zt}://localhost:${n}/ws`:'[incubator] WebSocket: disabled (install "ws" to enable)'),s&&!$&&console.error(`[incubator] Persistence: ${s}`),X&&(Pt=new Xa(X,n,le,Qe.runs,i,Qe,F,Qt?.module),Pt.start().catch(K=>{console.error(`[orchestrator] Fatal: ${K.message}`),process.exit(1)}))});let Pt;process.on("SIGINT",async()=>{console.error(`
412
+ [incubator] Shutting down...`),Pt&&await Pt.shutdown();for(let K of je)await K.shutdown();en.stop(),M.close(),Tt&&await Tt.stopAll(),Sr&&Sr.close(),await le.close(),s&&!$&&(await _p(s,F),console.error("[incubator] Snapshots saved")),b&&(await b.quit(),console.error("[incubator] Redis disconnected"));for(let[,K]of re)K.server.close();jr.close(),process.exit(0)})}else{let re=F.get("default"),Nt=Iv(re,{agentId:o??"agent_stdio",persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:ne,onSave:s&&!$?()=>{_p(s,F)}:void 0,getProtocol:()=>F.getProtocol("default")}),oe=new Al;await Nt.connect(oe),console.error(`[incubator] Running on stdio (agent: ${o??"agent_stdio"})`),s&&!$&&console.error(`[incubator] Persistence: ${s}`)}}var z_=w(()=>{WS();i$();Av();TP();cp();GP();JP();KP();Ti();Ai();eR();tR();UR();FR()});var vC={};V(vC,{serve:()=>EV});async function EV(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
412
413
  ${g("bold","wgl serve")} \u2014 start a local incubator server
413
414
 
414
415
  ${g("cyan","USAGE:")}
@@ -424,10 +425,10 @@ ${g("cyan","EXAMPLES:")}
424
425
  wgl serve --port 4000
425
426
  wgl serve --protocol workflow.acp
426
427
  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(()=>(F_(),U_)),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";Ee()});var IC={};V(IC,{deleteGlobalConfigValue:()=>VV,getGlobalConfigValue:()=>K_,getHomeDir:()=>wc,getWglDir:()=>BV,loadGlobalConfig:()=>ze,saveGlobalConfig:()=>GV,setGlobalConfigValue:()=>lc});import{readFileSync as H_,writeFileSync as B_,existsSync as G_}from"node:fs";import{join as V_}from"node:path";import{homedir as W_}from"node:os";function BV(){return zr}function ze(){let t=jr();return{...ss,defaultPlatform:t.platform,defaultRole:t.role??ss.defaultRole,editor:t.cli.editor,activeProfile:t.activeProfile}}function GV(t){let e={};t.defaultPlatform!==ss.defaultPlatform&&(e.platform=t.defaultPlatform),t.defaultRole!==ss.defaultRole&&(e.role=t.defaultRole),t.editor!==ss.editor&&(e.cli={...e.cli,editor:t.editor}),t.activeProfile!==ss.activeProfile&&(e.activeProfile=t.activeProfile);let r=new Set(["defaultPlatform","defaultRole","editor","activeProfile"]);for(let[i,a]of Object.entries(t))r.has(i)||(e[i]=a);let n=V_(W_(),".wglrc.json"),o=G_(n)?Y_(H_(n,"utf8")):{},s=yn(o,e);B_(n,JSON.stringify(s,null,2)+`
428
- `)}function K_(t){let r=jr(),n=J_[t];if(n){let s=bc(r,n);return s!==void 0?String(s):void 0}let o=bc(r,t);return o!==void 0&&typeof o!="object"?String(o):void 0}function lc(t,e){let r=V_(W_(),".wglrc.json"),n=G_(r)?Y_(H_(r,"utf8")):{},o=J_[t]||t;xi(n,o,WV(e)),B_(r,JSON.stringify(n,null,2)+`
429
- `)}function VV(t){if(t in ss)return!1;let e=V_(W_(),".wglrc.json");if(!G_(e))return!1;let r=Y_(H_(e,"utf8")),n=J_[t]||t;return!n.includes(".")&&n in r?(delete r[n],B_(e,JSON.stringify(r,null,2)+`
430
- `),!0):!1}function Y_(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return{}}}function WV(t){if(t==="true")return!0;if(t==="false")return!1;let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}var ss,J_,ro=w(()=>{"use strict";bn();ss={defaultPlatform:"https://hivemind.honeyb.dev",defaultRole:"developer",editor:"nano",activeProfile:"personal"},J_={defaultPlatform:"platform",defaultRole:"role",editor:"cli.editor",activeProfile:"activeProfile"}});import{request as JV}from"node:http";import{request as KV}from"node:https";function no(t,e,r,n={}){return new Promise((o,s)=>{let i=new URL(e),c=i.protocol==="https:"?KV:JV,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:YV},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 YV,X_=w(()=>{YV=1e4});function AC(){return zr}function NC(){return lo()}function zC(t){Si(t)}function oo(t){return Td(t)}function is(t,e){Pd(t,e)}function Vp(t){return Rd(t)}function uc(){return Od()}function gi(t){return Date.now()/1e3>t.expiresAt-60}async function Wp(){let t=await no("POST","https://github.com/login/device/code",{client_id:jC,scope:"read:user user:email"},{Accept:"application/json"});if(!t.ok)throw new Error("Failed to start device flow");return t.data}async function Jp(t,e,r){let n=Date.now()+r*1e3;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,e*1e3));let o=await no("POST","https://github.com/login/oauth/access_token",{client_id:jC,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 Kp(t,e){let r=await no("POST",`${t}/api/auth/device/exchange`,{github_access_token:e});if(!r.ok)throw new Error("Token exchange failed");return r.data}async function Yp(t,e){let r=await no("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 Xp(t,e){let r=await no("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 jC,Q_=w(()=>{X_();bn();jC="Ov23liy8H1qGZdVAk1Vr"});function Fe(t){let e=t?.profileName||"personal",r=oo(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 Xp(n.platform,n.refreshToken);a=d.access_token,is(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(gi(n))return c||(c=l()),c}function p(d,m,h,y=!1){let v=`${i}${m}`,b={};return y||(b.Authorization=`Bearer ${a}`),no(d,v,h,b)}async function f(d,m,h){await u();let y=await p(d,m,h);return y.status===401?(c||(c=l()),await c,p(d,m,h)):y}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 y=h.toString();return p("GET",`/marketplace/specs${y?"?"+y:""}`)},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 y=h.toString();return p("GET",`/marketplace/integrations${y?"?"+y:""}`)},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 y=h.toString();return p("GET",`/marketplace/integrations/${encodeURIComponent(d)}/reviews${y?"?"+y:""}`)},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 y=new URLSearchParams;m!==void 0&&y.set("since",String(m)),h&&y.set("type",h);let v=y.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 MC,LC=w(()=>{X_();Q_();MC=Fe});var DC={};V(DC,{createHivemindClient:()=>Fe,createPlatformClient:()=>MC,exchangeGitHubToken:()=>Kp,getActiveProfile:()=>oo,getWglDir:()=>AC,isTokenExpired:()=>gi,listProfiles:()=>uc,loadAuthStore:()=>NC,pollDeviceFlow:()=>Jp,refreshToken:()=>Xp,removeProfile:()=>Vp,saveAuthStore:()=>zC,setProfile:()=>is,startDeviceFlow:()=>Wp,verifyPat:()=>Yp});var as=w(()=>{LC();Q_()});var qC={};V(qC,{auth:()=>XV});async function XV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
428
+ `);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(()=>(z_(),N_)),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 _C=w(()=>{"use strict";Te()});var bC={};V(bC,{deleteGlobalConfigValue:()=>RV,getGlobalConfigValue:()=>U_,getHomeDir:()=>bc,getWglDir:()=>TV,loadGlobalConfig:()=>ze,saveGlobalConfig:()=>PV,setGlobalConfigValue:()=>cc});import{readFileSync as j_,writeFileSync as M_,existsSync as L_}from"node:fs";import{join as D_}from"node:path";import{homedir as q_}from"node:os";function TV(){return Mr}function ze(){let t=Lr();return{...ss,defaultPlatform:t.platform,defaultRole:t.role??ss.defaultRole,editor:t.cli.editor,activeProfile:t.activeProfile}}function PV(t){let e={};t.defaultPlatform!==ss.defaultPlatform&&(e.platform=t.defaultPlatform),t.defaultRole!==ss.defaultRole&&(e.role=t.defaultRole),t.editor!==ss.editor&&(e.cli={...e.cli,editor:t.editor}),t.activeProfile!==ss.activeProfile&&(e.activeProfile=t.activeProfile);let r=new Set(["defaultPlatform","defaultRole","editor","activeProfile"]);for(let[i,a]of Object.entries(t))r.has(i)||(e[i]=a);let n=D_(q_(),".wglrc.json"),o=L_(n)?F_(j_(n,"utf8")):{},s=_n(o,e);M_(n,JSON.stringify(s,null,2)+`
429
+ `)}function U_(t){let r=Lr(),n=Z_[t];if(n){let s=_c(r,n);return s!==void 0?String(s):void 0}let o=_c(r,t);return o!==void 0&&typeof o!="object"?String(o):void 0}function cc(t,e){let r=D_(q_(),".wglrc.json"),n=L_(r)?F_(j_(r,"utf8")):{},o=Z_[t]||t;wi(n,o,OV(e)),M_(r,JSON.stringify(n,null,2)+`
430
+ `)}function RV(t){if(t in ss)return!1;let e=D_(q_(),".wglrc.json");if(!L_(e))return!1;let r=F_(j_(e,"utf8")),n=Z_[t]||t;return!n.includes(".")&&n in r?(delete r[n],M_(e,JSON.stringify(r,null,2)+`
431
+ `),!0):!1}function F_(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return{}}}function OV(t){if(t==="true")return!0;if(t==="false")return!1;let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}var ss,Z_,no=w(()=>{"use strict";xn();ss={defaultPlatform:"https://hivemind.honeyb.dev",defaultRole:"developer",editor:"nano",activeProfile:"personal"},Z_={defaultPlatform:"platform",defaultRole:"role",editor:"cli.editor",activeProfile:"activeProfile"}});import{request as CV}from"node:http";import{request as IV}from"node:https";function oo(t,e,r,n={}){return new Promise((o,s)=>{let i=new URL(e),c=i.protocol==="https:"?IV:CV,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:AV},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 AV,H_=w(()=>{AV=1e4});function wC(){return Mr}function xC(){return uo()}function SC(t){xi(t)}function so(t){return kd(t)}function is(t,e){Ed(t,e)}function Bp(t){return Td(t)}function lc(){return Pd()}function hi(t){return Date.now()/1e3>t.expiresAt-60}async function Gp(){let t=await oo("POST","https://github.com/login/device/code",{client_id:$C,scope:"read:user user:email"},{Accept:"application/json"});if(!t.ok)throw new Error("Failed to start device flow");return t.data}async function Vp(t,e,r){let n=Date.now()+r*1e3;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,e*1e3));let o=await oo("POST","https://github.com/login/oauth/access_token",{client_id:$C,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 Wp(t,e){let r=await oo("POST",`${t}/api/auth/device/exchange`,{github_access_token:e});if(!r.ok)throw new Error("Token exchange failed");return r.data}async function Jp(t,e){let r=await oo("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 Kp(t,e){let r=await oo("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 $C,B_=w(()=>{H_();xn();$C="Ov23liy8H1qGZdVAk1Vr"});function Fe(t){let e=t?.profileName||"personal",r=so(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 Kp(n.platform,n.refreshToken);a=d.access_token,is(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(hi(n))return c||(c=l()),c}function p(d,m,h,y=!1){let v=`${i}${m}`,b={};return y||(b.Authorization=`Bearer ${a}`),oo(d,v,h,b)}async function f(d,m,h){await u();let y=await p(d,m,h);return y.status===401?(c||(c=l()),await c,p(d,m,h)):y}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 y=h.toString();return p("GET",`/marketplace/specs${y?"?"+y:""}`)},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 y=h.toString();return p("GET",`/marketplace/integrations${y?"?"+y:""}`)},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 y=h.toString();return p("GET",`/marketplace/integrations/${encodeURIComponent(d)}/reviews${y?"?"+y:""}`)},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 y=new URLSearchParams;m!==void 0&&y.set("since",String(m)),h&&y.set("type",h);let v=y.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}),setSecret:(d,m)=>f("POST","/colony/secrets",{provider:d,key:m}),listSecrets:()=>f("GET","/colony/secrets"),deleteSecret:d=>f("DELETE",`/colony/secrets/${encodeURIComponent(d)}`),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 kC,EC=w(()=>{H_();B_();kC=Fe});var TC={};V(TC,{createHivemindClient:()=>Fe,createPlatformClient:()=>kC,exchangeGitHubToken:()=>Wp,getActiveProfile:()=>so,getWglDir:()=>wC,isTokenExpired:()=>hi,listProfiles:()=>lc,loadAuthStore:()=>xC,pollDeviceFlow:()=>Vp,refreshToken:()=>Kp,removeProfile:()=>Bp,saveAuthStore:()=>SC,setProfile:()=>is,startDeviceFlow:()=>Gp,verifyPat:()=>Jp});var as=w(()=>{EC();B_()});var PC={};V(PC,{auth:()=>NV});async function NV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
431
432
  ${g("bold","wgl auth")} \u2014 Hivemind authentication
432
433
 
433
434
  ${g("cyan","USAGE:")}
@@ -437,10 +438,10 @@ ${g("cyan","USAGE:")}
437
438
  wgl auth status Show current auth state
438
439
  wgl auth switch <profile> Switch between saved profiles
439
440
  `);return}switch(e){case"login":{let r=t.indexOf("--platform"),n=t.indexOf("--token"),o=ze(),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(g("dim",`Authenticating with PAT on ${s}...
440
- `));try{let c=await Yp(s,a);is(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(A(`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(g("dim",`Authenticating via GitHub...
441
- `));try{let a=await Wp();console.log(` Visit: ${g("cyan",a.verification_uri)}`),console.log(` Enter code: ${g("bold",a.user_code)}
442
- `),console.log(g("dim","Waiting for authorization..."));let c=await Jp(a.device_code,a.interval||5,a.expires_in||300);console.log(g("dim","Exchanging token with Hivemind..."));let l=await Kp(s,c);is(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(A(`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=ze().activeProfile||"personal";Vp(n)?console.log(A(`Logged out (profile: ${n})`)):console.log(g("dim","Not logged in"));break}case"status":{let n=ze().activeProfile||"personal",o=oo(n);if(console.log(C("Auth Status")),console.log(S("Profile",n)),!o)console.log(` ${g("dim","Not logged in")}`),console.log(`
443
- Run ${g("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)),gi(o))console.log(` ${sr("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",g("green",`valid (${a}h ${c}m remaining)`)))}let s=uc();if(s.length>1){console.log(C("Available Profiles"));for(let i of s){let a=i===n?g("green"," (active)"):"",c=oo(i);console.log(` ${g("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=oo(r);if(!n){console.log(_(`Profile not found: ${r}`));let o=uc();o.length>0&&console.log(g("dim",` Available: ${o.join(", ")}`)),process.exit(1);return}lc("activeProfile",r),console.log(A(`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 ZC=w(()=>{"use strict";Ee();ro();as()});var FC={};V(FC,{configCmd:()=>QV});async function QV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
441
+ `));try{let c=await Jp(s,a);is(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(A(`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(g("dim",`Authenticating via GitHub...
442
+ `));try{let a=await Gp();console.log(` Visit: ${g("cyan",a.verification_uri)}`),console.log(` Enter code: ${g("bold",a.user_code)}
443
+ `),console.log(g("dim","Waiting for authorization..."));let c=await Vp(a.device_code,a.interval||5,a.expires_in||300);console.log(g("dim","Exchanging token with Hivemind..."));let l=await Wp(s,c);is(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(A(`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=ze().activeProfile||"personal";Bp(n)?console.log(A(`Logged out (profile: ${n})`)):console.log(g("dim","Not logged in"));break}case"status":{let n=ze().activeProfile||"personal",o=so(n);if(console.log(C("Auth Status")),console.log(S("Profile",n)),!o)console.log(` ${g("dim","Not logged in")}`),console.log(`
444
+ Run ${g("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)),hi(o))console.log(` ${ar("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",g("green",`valid (${a}h ${c}m remaining)`)))}let s=lc();if(s.length>1){console.log(C("Available Profiles"));for(let i of s){let a=i===n?g("green"," (active)"):"",c=so(i);console.log(` ${g("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=so(r);if(!n){console.log(_(`Profile not found: ${r}`));let o=lc();o.length>0&&console.log(g("dim",` Available: ${o.join(", ")}`)),process.exit(1);return}cc("activeProfile",r),console.log(A(`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 RC=w(()=>{"use strict";Te();no();as()});var CC={};V(CC,{configCmd:()=>zV});async function zV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
444
445
  ${g("bold","wgl config")} \u2014 global preferences
445
446
 
446
447
  ${g("cyan","USAGE:")}
@@ -460,7 +461,7 @@ ${g("cyan","KEYS (dotted paths supported):")}
460
461
  carapace.threshold Block threshold (0-100)
461
462
  telemetry.endpoint Telemetry endpoint URL
462
463
  telemetry.apiKey Telemetry API key
463
- `);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}lc(r,n),console.log(A(`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=K_(r);n!==void 0?console.log(n):(console.log(_(`Key not found: ${r}`)),process.exit(1));break}case"list":{let r=jr(),n=UC(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 UC(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(...UC(o,s)):o!==void 0&&o!==""&&r.push([s,String(o)])}return r}var HC=w(()=>{"use strict";Ee();ro();bn()});var BC={};V(BC,{marketplace:()=>n3});import{readFileSync as e3,writeFileSync as t3}from"node:fs";import{basename as r3}from"node:path";async function n3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
464
+ `);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}cc(r,n),console.log(A(`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=U_(r);n!==void 0?console.log(n):(console.log(_(`Key not found: ${r}`)),process.exit(1));break}case"list":{let r=Lr(),n=OC(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 OC(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(...OC(o,s)):o!==void 0&&o!==""&&r.push([s,String(o)])}return r}var IC=w(()=>{"use strict";Te();no();xn()});var AC={};V(AC,{marketplace:()=>DV});import{readFileSync as jV,writeFileSync as MV}from"node:fs";import{basename as LV}from"node:path";async function DV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
464
465
  ${g("bold","wgl marketplace")} \u2014 protocol marketplace
465
466
 
466
467
  ${g("cyan","USAGE:")}
@@ -469,10 +470,10 @@ ${g("cyan","USAGE:")}
469
470
  wgl marketplace install <name> Download + load into local server
470
471
  wgl marketplace publish <file> [--name N] [--title T] [--tags t1,t2]
471
472
  wgl marketplace list Your published specs (auth required)
472
- `);return}switch(e){case"search":{await o3(t.slice(1));break}case"info":{await s3(t.slice(1));break}case"install":{await i3(t.slice(1));break}case"publish":{await a3(t.slice(1));break}case"list":{await c3();break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl marketplace --help` for usage"),process.exit(2)}}async function o3(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 Fe({profileName:ze().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(` ${g("dim","No protocols found")}`);return}console.log(C("Marketplace")),console.log(g("dim",` ${u} protocol${u===1?"":"s"} found
473
- `));let p=l.map(f=>{let d=f.avg_rating>0?` ${g("yellow",`\u2605${f.avg_rating.toFixed(1)}`)}`:"",m=g("dim",`\u2193${f.downloads}`);return[f.name,`${f.title} ${m}${d}`]});console.log(ir(p)),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}}async function s3(t){let e=t[0];e||(console.log(_("Usage: wgl marketplace info <name>")),process.exit(2));try{let n=await Fe({profileName:ze().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(` ${g("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(` ${g("cyan",`${i+1}.`)} ${g("bold",a.name)}${a.description?` \u2014 ${a.description}`:""}`)}}}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function i3(t){let e=t[0];e||(console.log(_("Usage: wgl marketplace install <name>")),process.exit(2));try{let n=await Fe({profileName:ze().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=_e();if(s)try{if((await Q(s).loadProtocol(o)).ok){console.log(A(`Installed and loaded: ${e}`));return}}catch{}let a=`${r3(e).replace(/[/\\]/g,"_")}.acp.json`;t3(a,JSON.stringify(o,null,2)+`
474
- `),console.log(A(`Downloaded: ${a}`)),console.log(g("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 a3(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=e3(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 Fe({profileName:ze().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(A(`Published: ${f.data.name} (v${f.data.version})`))}catch(p){console.log(_(p.message)),process.exit(1)}}async function c3(){try{let e=await Fe({profileName:ze().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(` ${g("dim","No published protocols")}`);return}console.log(C("Your Protocols"));let n=r.map(o=>{let s=g("dim",`\u2193${o.downloads}`);return[o.name,`v${o.version} ${s}`]});console.log(ir(n)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}var GC=w(()=>{"use strict";Ee();as();ft();ro();et()});var KC={};V(KC,{integrations:()=>d3});import{readFileSync as eb,writeFileSync as l3,mkdirSync as u3,existsSync as VC}from"node:fs";import{join as tb}from"node:path";import{homedir as p3}from"node:os";function WC(){return tb(p3(),".config","honeybee")}function JC(){return tb(WC(),"integrations.json")}function pc(){let t=JC();if(!VC(t))return{};try{return JSON.parse(eb(t,"utf8"))}catch{return{}}}function Qp(t){let e=WC();VC(e)||u3(e,{recursive:!0}),l3(JC(),JSON.stringify(t,null,2)+`
475
- `,{mode:384})}async function d3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
473
+ `);return}switch(e){case"search":{await qV(t.slice(1));break}case"info":{await ZV(t.slice(1));break}case"install":{await UV(t.slice(1));break}case"publish":{await FV(t.slice(1));break}case"list":{await HV();break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl marketplace --help` for usage"),process.exit(2)}}async function qV(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 Fe({profileName:ze().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(` ${g("dim","No protocols found")}`);return}console.log(C("Marketplace")),console.log(g("dim",` ${u} protocol${u===1?"":"s"} found
474
+ `));let p=l.map(f=>{let d=f.avg_rating>0?` ${g("yellow",`\u2605${f.avg_rating.toFixed(1)}`)}`:"",m=g("dim",`\u2193${f.downloads}`);return[f.name,`${f.title} ${m}${d}`]});console.log(cr(p)),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}}async function ZV(t){let e=t[0];e||(console.log(_("Usage: wgl marketplace info <name>")),process.exit(2));try{let n=await Fe({profileName:ze().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(` ${g("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(` ${g("cyan",`${i+1}.`)} ${g("bold",a.name)}${a.description?` \u2014 ${a.description}`:""}`)}}}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function UV(t){let e=t[0];e||(console.log(_("Usage: wgl marketplace install <name>")),process.exit(2));try{let n=await Fe({profileName:ze().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=_e();if(s)try{if((await Q(s).loadProtocol(o)).ok){console.log(A(`Installed and loaded: ${e}`));return}}catch{}let a=`${LV(e).replace(/[/\\]/g,"_")}.acp.json`;MV(a,JSON.stringify(o,null,2)+`
475
+ `),console.log(A(`Downloaded: ${a}`)),console.log(g("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 FV(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=jV(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 Fe({profileName:ze().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(A(`Published: ${f.data.name} (v${f.data.version})`))}catch(p){console.log(_(p.message)),process.exit(1)}}async function HV(){try{let e=await Fe({profileName:ze().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(` ${g("dim","No published protocols")}`);return}console.log(C("Your Protocols"));let n=r.map(o=>{let s=g("dim",`\u2193${o.downloads}`);return[o.name,`v${o.version} ${s}`]});console.log(cr(n)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}var NC=w(()=>{"use strict";Te();as();mt();no();et()});var LC={};V(LC,{integrations:()=>WV});import{readFileSync as G_,writeFileSync as BV,mkdirSync as GV,existsSync as zC}from"node:fs";import{join as V_}from"node:path";import{homedir as VV}from"node:os";function jC(){return V_(VV(),".config","honeybee")}function MC(){return V_(jC(),"integrations.json")}function uc(){let t=MC();if(!zC(t))return{};try{return JSON.parse(G_(t,"utf8"))}catch{return{}}}function Yp(t){let e=jC();zC(e)||GV(e,{recursive:!0}),BV(MC(),JSON.stringify(t,null,2)+`
476
+ `,{mode:384})}async function WV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
476
477
  ${g("bold","wgl integrations")} \u2014 integration marketplace
477
478
 
478
479
  ${g("cyan","USAGE:")}
@@ -484,15 +485,15 @@ ${g("cyan","USAGE:")}
484
485
  wgl integrations enable <name> Enable an installed integration
485
486
  wgl integrations disable <name> Disable an integration
486
487
  wgl integrations publish <dir> Publish an integration (auth required)
487
- `);return}switch(e){case"search":{await f3(t.slice(1));break}case"info":{await m3(t.slice(1));break}case"install":{await h3(t.slice(1));break}case"remove":{await g3(t.slice(1));break}case"list":{await y3();break}case"enable":{await v3(t.slice(1));break}case"disable":{await _3(t.slice(1));break}case"publish":{await b3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl integrations --help` for usage"),process.exit(2)}}function ed(){return Fe({profileName:ze().activeProfile||"personal"})}async function f3(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 ed().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(` ${g("dim","No integrations found")}`);return}console.log(C("Integrations")),console.log(g("dim",` ${u} integration${u===1?"":"s"} found
488
- `));let p=l.map(f=>{let d=g("cyan",`[${f.category}]`),m=f.avg_rating>0?` ${g("yellow",`\u2605${f.avg_rating.toFixed(1)}`)}`:"",h=g("dim",`\u2193${f.downloads}`);return[f.name,`${f.title} ${d} ${h}${m}`]});console.log(ir(p)),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}}async function m3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations info <name>")),process.exit(2));try{let n=await ed().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?g("red"," (required)"):"";console.log(` ${g("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 h3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations install <name>")),process.exit(2));try{let n=await ed().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(g("dim",` Installing ${s}...`)),i("npm",["install","-g",s],{stdio:"inherit"});let a=pc();a[e]={package:s,enabled:!0,config:{}},Qp(a),console.log(A(`Installed and enabled: ${e}`)),console.log(g("dim",` npm package: ${s}`)),console.log(g("dim"," Run incubator with --integrations or --integration="+e+" to activate"))}catch(r){console.log(_(r.message)),process.exit(1)}}async function g3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations remove <name>")),process.exit(2));let r=pc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),delete r[e],Qp(r),console.log(A(`Removed: ${e}`))}async function y3(){let t=pc(),e=Object.entries(t);if(e.length===0){console.log(` ${g("dim","No integrations installed")}`),console.log(g("dim"," Search marketplace: wgl integrations search"));return}console.log(C("Installed Integrations"));let r=e.map(([n,o])=>{let s=o.enabled?g("green","enabled"):g("dim","disabled");return[n,`${o.package} [${s}]`]});console.log(ir(r)),console.log()}async function v3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations enable <name>")),process.exit(2));let r=pc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!0,Qp(r),console.log(A(`Enabled: ${e}`))}async function _3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations disable <name>")),process.exit(2));let r=pc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!1,Qp(r),console.log(A(`Disabled: ${e}`))}async function b3(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=eb(o,"utf8")}catch{try{s=eb(tb(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 ed().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(A(`Published: ${p.data.data.name} (v${p.data.data.version})`))}catch(u){console.log(_(u.message)),process.exit(1)}}var YC=w(()=>{"use strict";Ee();as();ro()});var XC={};V(XC,{secret:()=>w3});async function w3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
489
- ${g("bold","wgl secret")} \u2014 manage provider API keys
488
+ `);return}switch(e){case"search":{await JV(t.slice(1));break}case"info":{await KV(t.slice(1));break}case"install":{await YV(t.slice(1));break}case"remove":{await XV(t.slice(1));break}case"list":{await QV();break}case"enable":{await e3(t.slice(1));break}case"disable":{await t3(t.slice(1));break}case"publish":{await r3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl integrations --help` for usage"),process.exit(2)}}function Xp(){return Fe({profileName:ze().activeProfile||"personal"})}async function JV(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 Xp().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(` ${g("dim","No integrations found")}`);return}console.log(C("Integrations")),console.log(g("dim",` ${u} integration${u===1?"":"s"} found
489
+ `));let p=l.map(f=>{let d=g("cyan",`[${f.category}]`),m=f.avg_rating>0?` ${g("yellow",`\u2605${f.avg_rating.toFixed(1)}`)}`:"",h=g("dim",`\u2193${f.downloads}`);return[f.name,`${f.title} ${d} ${h}${m}`]});console.log(cr(p)),console.log()}catch(a){console.log(_(a.message)),process.exit(1)}}async function KV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations info <name>")),process.exit(2));try{let n=await Xp().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?g("red"," (required)"):"";console.log(` ${g("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 YV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations install <name>")),process.exit(2));try{let n=await Xp().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(g("dim",` Installing ${s}...`)),i("npm",["install","-g",s],{stdio:"inherit"});let a=uc();a[e]={package:s,enabled:!0,config:{}},Yp(a),console.log(A(`Installed and enabled: ${e}`)),console.log(g("dim",` npm package: ${s}`)),console.log(g("dim"," Run incubator with --integrations or --integration="+e+" to activate"))}catch(r){console.log(_(r.message)),process.exit(1)}}async function XV(t){let e=t[0];e||(console.log(_("Usage: wgl integrations remove <name>")),process.exit(2));let r=uc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),delete r[e],Yp(r),console.log(A(`Removed: ${e}`))}async function QV(){let t=uc(),e=Object.entries(t);if(e.length===0){console.log(` ${g("dim","No integrations installed")}`),console.log(g("dim"," Search marketplace: wgl integrations search"));return}console.log(C("Installed Integrations"));let r=e.map(([n,o])=>{let s=o.enabled?g("green","enabled"):g("dim","disabled");return[n,`${o.package} [${s}]`]});console.log(cr(r)),console.log()}async function e3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations enable <name>")),process.exit(2));let r=uc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!0,Yp(r),console.log(A(`Enabled: ${e}`))}async function t3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations disable <name>")),process.exit(2));let r=uc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!1,Yp(r),console.log(A(`Disabled: ${e}`))}async function r3(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=G_(o,"utf8")}catch{try{s=G_(V_(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 Xp().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(A(`Published: ${p.data.data.name} (v${p.data.data.version})`))}catch(u){console.log(_(u.message)),process.exit(1)}}var DC=w(()=>{"use strict";Te();as();no()});var qC={};V(qC,{secret:()=>o3});async function o3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
490
+ ${g("bold","wgl secret")} \u2014 manage provider API keys (cloud)
490
491
 
491
492
  ${g("cyan","USAGE:")}
492
- wgl secret set <provider> Set a global provider key (reads from stdin)
493
+ wgl secret set <provider> Set a user-level provider key (reads from stdin)
493
494
  wgl secret set <provider> --hive <id> Set a hive-specific provider key
494
- wgl secret list Show stored providers and scopes
495
- wgl secret delete <provider> Delete a global provider key
495
+ wgl secret list Show stored providers
496
+ wgl secret delete <provider> Delete a user-level provider key
496
497
  wgl secret delete <provider> --hive <id> Delete a hive-specific key
497
498
 
498
499
  ${g("cyan","PROVIDERS:")}
@@ -503,15 +504,16 @@ ${g("cyan","PROVIDERS:")}
503
504
  ollama ${g("dim","(local tier)")} Ollama \u2014 local models (no key needed)
504
505
 
505
506
  ${g("cyan","SCOPE HIERARCHY:")}
506
- Keys resolve in order: hive-specific \u2192 global \u2192 env var
507
- Global keys apply to all hives unless overridden.
507
+ Keys resolve in order: hive-specific \u2192 user-level \u2192 empty
508
+ User-level keys apply to all your hives unless overridden.
509
+ Keys are stored on the Hivemind platform (requires auth).
508
510
 
509
511
  ${g("cyan","EXAMPLES:")}
510
512
  echo "csk-..." | wgl secret set cerebras
511
513
  echo "sk-..." | wgl secret set openai --hive abc123
512
514
  wgl secret list
513
515
  wgl secret delete groq
514
- `);return}switch(e){case"set":await x3(t.slice(1));break;case"list":await S3();break;case"delete":await $3(t.slice(1));break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl secret --help` for usage"),process.exit(2)}}async function x3(t){let e=t[0];if(!e){console.log(_("Usage: wgl secret set <provider>")),process.exit(2);return}if(!/^[a-zA-Z0-9-]+$/.test(e)){console.log(_("Invalid provider name (use alphanumeric + hyphens)")),process.exit(2);return}uf(e)||console.log(sr(`Unknown provider "${e}" \u2014 storing anyway`));let r=t.indexOf("--hive"),n=r!==-1?t[r+1]:void 0;if(r!==-1&&!n){console.log(_("--hive requires a hive ID")),process.exit(2);return}let o=await k3();if(!o.trim()){console.log(_("No key provided on stdin.")),console.log(g("dim",' Usage: echo "csk-..." | wgl secret set cerebras')),process.exit(1);return}if(n){af(n,e,o.trim());try{let{createHivemindClient:s}=await Promise.resolve().then(()=>(as(),DC)),{loadGlobalConfig:i}=await Promise.resolve().then(()=>(ro(),IC));(await s({profileName:i().activeProfile||"personal"}).setProviderKey(n,e,o.trim())).ok?console.log(A(`Set ${e} key for hive ${n} (local + Colony)`)):(console.log(A(`Set ${e} key for hive ${n} (local only)`)),console.log(sr("Colony push failed \u2014 key stored locally")))}catch{console.log(A(`Set ${e} key for hive ${n} (local only)`))}}else sf(e,o.trim()),console.log(A(`Set global ${e} key`))}async function S3(){let t=lf();if(t.providers.length===0&&Object.keys(t.hives).length===0){console.log(` ${g("dim","No secrets stored")}`),console.log(g("dim"," Run `wgl secret set <provider>` to add one"));return}if(t.providers.length>0){console.log(C("Global"));for(let e of t.providers)console.log(S(e,g("green","set")))}for(let[e,r]of Object.entries(t.hives))if(r.length>0){console.log(C(`Hive: ${e}`));for(let n of r)console.log(S(n,g("green","set")))}console.log()}async function $3(t){let e=t[0];if(!e){console.log(_("Usage: wgl secret delete <provider>")),process.exit(2);return}let r=t.indexOf("--hive"),n=r!==-1?t[r+1]:void 0;if(cf(e,n)){let s=n?`hive ${n}`:"global";console.log(A(`Deleted ${e} key (${s})`))}else console.log(_(`No ${e} key found${n?` for hive ${n}`:""}`)),process.exit(1)}async function k3(){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")}var QC=w(()=>{"use strict";Ee();pf()});var tI={};V(tI,{hive:()=>P3});import{readFileSync as rb,existsSync as E3}from"node:fs";import{resolve as eI,dirname as T3}from"node:path";async function P3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
516
+ `);return}switch(e){case"set":await s3(t.slice(1));break;case"list":await i3();break;case"delete":await a3(t.slice(1));break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl secret --help` for usage"),process.exit(2)}}async function W_(){let{createHivemindClient:t}=await Promise.resolve().then(()=>(as(),TC)),{loadGlobalConfig:e}=await Promise.resolve().then(()=>(no(),bC));return t({profileName:e().activeProfile||"personal"})}async function s3(t){let e=t[0];if(!e){console.log(_("Usage: wgl secret set <provider>")),process.exit(2);return}if(!/^[a-zA-Z0-9-]+$/.test(e)){console.log(_("Invalid provider name (use alphanumeric + hyphens)")),process.exit(2);return}n3.has(e)||console.log(ar(`Unknown provider "${e}" \u2014 storing anyway`));let r=t.indexOf("--hive"),n=r!==-1?t[r+1]:void 0;if(r!==-1&&!n){console.log(_("--hive requires a hive ID")),process.exit(2);return}let o=await c3();if(!o.trim()){console.log(_("No key provided on stdin.")),console.log(g("dim",' Usage: echo "csk-..." | wgl secret set cerebras')),process.exit(1);return}try{let s=await W_();n?(await s.setProviderKey(n,e,o.trim())).ok?console.log(A(`Set ${e} key for hive ${n}`)):(console.log(_("Failed to set hive secret")),process.exit(1)):(await s.setSecret(e,o.trim())).ok?console.log(A(`Set ${e} key (user-level)`)):(console.log(_("Failed to set secret")),process.exit(1))}catch(s){console.log(_(s.message)),process.exit(1)}}async function i3(){try{let e=await(await W_()).listSecrets();if(!e.ok||!e.data){console.log(_("Failed to list secrets")),process.exit(1);return}let r=e.data.secrets;if(r.length===0){console.log(` ${g("dim","No secrets stored")}`),console.log(g("dim"," Run `wgl secret set <provider>` to add one"));return}console.log(C("User Secrets"));for(let n of r)console.log(S(n.provider,g("green","set")+g("dim",` (updated ${n.updated_at})`)));console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}async function a3(t){let e=t[0];if(!e){console.log(_("Usage: wgl secret delete <provider>")),process.exit(2);return}let r=t.indexOf("--hive"),n=r!==-1?t[r+1]:void 0;try{let o=await W_();if(n){console.log(ar("Hive-specific key deletion not yet supported")),console.log(g("dim"," The hive will fall back to your user-level key")),process.exit(1);return}let s=await o.deleteSecret(e);s.ok?console.log(A(`Deleted ${e} key`)):s.status===404?(console.log(_(`No ${e} key found`)),process.exit(1)):(console.log(_("Failed to delete secret")),process.exit(1))}catch(o){console.log(_(o.message)),process.exit(1)}}async function c3(){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")}var n3,ZC=w(()=>{"use strict";Te();n3=new Set(["cerebras","groq","openai","anthropic","ollama"])});var FC={};V(FC,{hive:()=>p3});import{readFileSync as J_,existsSync as l3}from"node:fs";import{resolve as UC,dirname as u3}from"node:path";async function p3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
515
517
  ${g("bold","wgl hive")} \u2014 managed hive coordination (Colony)
516
518
 
517
519
  ${g("cyan","USAGE:")}
@@ -527,7 +529,7 @@ ${g("cyan","USAGE:")}
527
529
  wgl hive keys list List API keys
528
530
  wgl hive keys revoke <id> Revoke an API key
529
531
  wgl hive logs <id> Tail hive events
530
- `);return}if(e==="keys"){await Z3(t.slice(1));return}if(e==="config"){await j3(t.slice(1));return}switch(e){case"create":{await R3(t.slice(1));break}case"list":{await O3();break}case"info":{await C3(t.slice(1));break}case"start":{await z3(t.slice(1));break}case"delete":{await I3(t.slice(1));break}case"pause":{await A3(t.slice(1));break}case"resume":{await N3(t.slice(1));break}case"logs":{await q3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl hive --help` for usage"),process.exit(2)}}async function R3(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=rb(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=rb(c,"utf8")}catch{console.log(_(`Cannot read brood file: ${c}`)),process.exit(1);return}let u=D3(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=T3(eI(c)),f=eI(p,u.acpFile);if(E3(f))try{let d=rb(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(g("dim"," Or use --brood <file> with a name: field in the brood YAML")),process.exit(2);return}try{let l=await Fe({profileName:ze().activeProfile||"personal"}).createHive(a);l.ok||(console.log(_(`Server returned ${l.status}`)),process.exit(1));let u=l.data.hive;console.log(A(`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 O3(){try{let e=await Fe({profileName:ze().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(` ${g("dim","No hives")}`);return}console.log(C("Hives"));let n=r.map(o=>{let s=o.status==="active"?g("green",o.status):o.status==="paused"?g("yellow",o.status):g("dim",o.status);return[o.id.slice(0,8),`${g("bold",o.name)} ${s} (max: ${o.max_agents})`]});console.log(ir(n)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}async function C3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive info <id>")),process.exit(2);return}try{let r=Fe({profileName:ze().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.hive;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?g("green","enabled"):g("dim","disabled"))),console.log(S("Scan",o.scan_enabled?`${g("green","enabled")} (threshold: ${o.scan_threshold})`:g("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(` ${g("bold",a.agentId)} ${g("dim",a.role)} ${g(c,a.status)} iter:${a.iteration} tokens:${L3(l)} ${u}`),a.error&&console.log(` ${g("red",a.error)}`)}}}catch{}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function I3(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(sr(`This will permanently delete hive ${e}`)),console.log(g("dim"," Pass --yes to confirm")),process.exit(1);return}try{let n=await Fe({profileName:ze().activeProfile||"personal"}).deleteHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(A(`Deleted hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function A3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive pause <id>")),process.exit(2);return}try{let n=await Fe({profileName:ze().activeProfile||"personal"}).pauseHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(A(`Paused hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function N3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive resume <id>")),process.exit(2);return}try{let n=await Fe({profileName:ze().activeProfile||"personal"}).resumeHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(A(`Resumed hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function z3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive start <id>")),process.exit(2);return}try{let n=await Fe({profileName:ze().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(A(`Started hive: ${e}`)),console.log(g("dim"," Agents will begin executing on the next alarm cycle."))}catch(r){console.log(_(r.message)),process.exit(1)}}async function j3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
532
+ `);return}if(e==="keys"){await $3(t.slice(1));return}if(e==="config"){await _3(t.slice(1));return}switch(e){case"create":{await d3(t.slice(1));break}case"list":{await f3();break}case"info":{await m3(t.slice(1));break}case"start":{await v3(t.slice(1));break}case"delete":{await h3(t.slice(1));break}case"pause":{await g3(t.slice(1));break}case"resume":{await y3(t.slice(1));break}case"logs":{await S3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl hive --help` for usage"),process.exit(2)}}async function d3(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=J_(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=J_(c,"utf8")}catch{console.log(_(`Cannot read brood file: ${c}`)),process.exit(1);return}let u=x3(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=u3(UC(c)),f=UC(p,u.acpFile);if(l3(f))try{let d=J_(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(g("dim"," Or use --brood <file> with a name: field in the brood YAML")),process.exit(2);return}try{let l=await Fe({profileName:ze().activeProfile||"personal"}).createHive(a);l.ok||(console.log(_(`Server returned ${l.status}`)),process.exit(1));let u=l.data.hive;console.log(A(`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 f3(){try{let e=await Fe({profileName:ze().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(` ${g("dim","No hives")}`);return}console.log(C("Hives"));let n=r.map(o=>{let s=o.status==="active"?g("green",o.status):o.status==="paused"?g("yellow",o.status):g("dim",o.status);return[o.id.slice(0,8),`${g("bold",o.name)} ${s} (max: ${o.max_agents})`]});console.log(cr(n)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}async function m3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive info <id>")),process.exit(2);return}try{let r=Fe({profileName:ze().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.hive;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?g("green","enabled"):g("dim","disabled"))),console.log(S("Scan",o.scan_enabled?`${g("green","enabled")} (threshold: ${o.scan_threshold})`:g("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(` ${g("bold",a.agentId)} ${g("dim",a.role)} ${g(c,a.status)} iter:${a.iteration} tokens:${w3(l)} ${u}`),a.error&&console.log(` ${g("red",a.error)}`)}}}catch{}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function h3(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(ar(`This will permanently delete hive ${e}`)),console.log(g("dim"," Pass --yes to confirm")),process.exit(1);return}try{let n=await Fe({profileName:ze().activeProfile||"personal"}).deleteHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(A(`Deleted hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function g3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive pause <id>")),process.exit(2);return}try{let n=await Fe({profileName:ze().activeProfile||"personal"}).pauseHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(A(`Paused hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function y3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive resume <id>")),process.exit(2);return}try{let n=await Fe({profileName:ze().activeProfile||"personal"}).resumeHive(e);n.ok||(console.log(_(`Server returned ${n.status}`)),process.exit(1)),console.log(A(`Resumed hive: ${e}`))}catch(r){console.log(_(r.message)),process.exit(1)}}async function v3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive start <id>")),process.exit(2);return}try{let n=await Fe({profileName:ze().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(A(`Started hive: ${e}`)),console.log(g("dim"," Agents will begin executing on the next alarm cycle."))}catch(r){console.log(_(r.message)),process.exit(1)}}async function _3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
531
533
  ${g("bold","wgl hive config")} \u2014 hive configuration
532
534
 
533
535
  ${g("cyan","USAGE:")}
@@ -536,17 +538,17 @@ ${g("cyan","USAGE:")}
536
538
  ${g("cyan","EXAMPLES:")}
537
539
  echo "sk-..." | wgl hive config set-key abc123 openai
538
540
  cat ~/.secrets/cerebras.key | wgl hive config set-key abc123 cerebras
539
- `);return}if(e==="set-key"){console.log(sr("`wgl hive config set-key` is deprecated. Use `wgl secret set <provider> --hive <id>` instead.")),console.log();let r=t[1],n=t[2];if(!r||!n){console.log(_("Usage: wgl hive config set-key <hive-id> <provider>")),console.log(g("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 M3();if(!o.trim()){console.log(_("No key provided on stdin.")),console.log(g("dim",' Usage: echo "sk-..." | wgl hive config set-key <id> <provider>')),process.exit(1);return}try{let i=await Fe({profileName:ze().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(A(`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 M3(){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 L3(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function D3(t){let e={agents:[],env:{}},r=t.split(`
540
- `);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(),y=h.match(/^(?:acp|spec|protocol):\s*(.+)$/);if(y&&!i){let v=y[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(ie=>ie.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 q3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive logs <id>")),process.exit(2);return}console.log(g("dim",`Tailing hive ${e} events... Ctrl+C to stop
541
+ `);return}if(e==="set-key"){console.log(ar("`wgl hive config set-key` is deprecated. Use `wgl secret set <provider> --hive <id>` instead.")),console.log();let r=t[1],n=t[2];if(!r||!n){console.log(_("Usage: wgl hive config set-key <hive-id> <provider>")),console.log(g("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 b3();if(!o.trim()){console.log(_("No key provided on stdin.")),console.log(g("dim",' Usage: echo "sk-..." | wgl hive config set-key <id> <provider>')),process.exit(1);return}try{let i=await Fe({profileName:ze().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(A(`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 b3(){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 w3(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function x3(t){let e={agents:[],env:{}},r=t.split(`
542
+ `);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(),y=h.match(/^(?:acp|spec|protocol):\s*(.+)$/);if(y&&!i){let v=y[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(ie=>ie.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 S3(t){let e=t[0];if(!e){console.log(_("Usage: wgl hive logs <id>")),process.exit(2);return}console.log(g("dim",`Tailing hive ${e} events... Ctrl+C to stop
541
543
  `));let r=0,n=async()=>{try{let i=await Fe({profileName:ze().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(` ${g("dim",`#${a.id}`)} ${g("bold",a.type)} by ${a.publishedBy||a.agent_id} ${g("dim",c)}`),a.id>r&&(r=a.id)}}catch{}};await n();let o=setInterval(n,2e3);process.on("SIGINT",()=>{clearInterval(o),console.log(g("dim",`
542
- Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{})}async function Z3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
544
+ Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{})}async function $3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
543
545
  ${g("bold","wgl hive keys")} \u2014 API key management
544
546
 
545
547
  ${g("cyan","USAGE:")}
546
548
  wgl hive keys create <hive-id> --name N [--permissions all|read|write]
547
549
  wgl hive keys list
548
550
  wgl hive keys revoke <id>
549
- `);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 Fe({profileName:ze().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(A(`Created API key: ${l.name}`)),console.log(S("ID",l.id)),console.log(S("Permissions",l.permissions)),console.log(),console.log(` ${g("yellow","KEY:")} ${g("bold",l.key)}`),console.log(` ${sr("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 Fe({profileName:ze().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(` ${g("dim","No API keys")}`);return}console.log(C("API Keys"));let s=o.map(i=>[i.id.slice(0,8),`${g("bold",i.name)} (${i.hive_name}) ${g("dim",i.permissions)}`]);console.log(ir(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 Fe({profileName:ze().activeProfile||"personal"}).revokeKey(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1)),console.log(A(`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 rI=w(()=>{"use strict";Ee();as();ro()});var nI={};V(nI,{runCarapace:()=>B3});import{createRequire as U3}from"node:module";import{dirname as F3,join as H3}from"node:path";async function B3(t){let e=U3(import.meta.url),r=e.resolve("@honeybee-ai/carapace"),n=F3(r),o=H3(n,"cli.js"),s=process.argv;process.argv=["node","carapace",...t];try{e(o)}finally{process.argv=s}}var oI=w(()=>{"use strict"});var sI={};V(sI,{handleSessionStart:()=>V3});import{appendFileSync as G3}from"node:fs";async function V3(t,e,r){let n=process.env.CLAUDE_ENV_FILE;if(n){let i=a=>a.replace(/["\\`$!]/g,"\\$&");G3(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(`
551
+ `);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 Fe({profileName:ze().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(A(`Created API key: ${l.name}`)),console.log(S("ID",l.id)),console.log(S("Permissions",l.permissions)),console.log(),console.log(` ${g("yellow","KEY:")} ${g("bold",l.key)}`),console.log(` ${ar("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 Fe({profileName:ze().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(` ${g("dim","No API keys")}`);return}console.log(C("API Keys"));let s=o.map(i=>[i.id.slice(0,8),`${g("bold",i.name)} (${i.hive_name}) ${g("dim",i.permissions)}`]);console.log(cr(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 Fe({profileName:ze().activeProfile||"personal"}).revokeKey(r);o.ok||(console.log(_(`Server returned ${o.status}`)),process.exit(1)),console.log(A(`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 HC=w(()=>{"use strict";Te();as();no()});var BC={};V(BC,{runCarapace:()=>P3});import{createRequire as k3}from"node:module";import{dirname as E3,join as T3}from"node:path";async function P3(t){let e=k3(import.meta.url),r=e.resolve("@honeybee-ai/carapace"),n=E3(r),o=T3(n,"cli.js"),s=process.argv;process.argv=["node","carapace",...t];try{e(o)}finally{process.argv=s}}var GC=w(()=>{"use strict"});var VC={};V(VC,{handleSessionStart:()=>O3});import{appendFileSync as R3}from"node:fs";async function O3(t,e,r){let n=process.env.CLAUDE_ENV_FILE;if(n){let i=a=>a.replace(/["\\`$!]/g,"\\$&");R3(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(`
550
552
  `)+`
551
553
  `)}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:
552
554
  ${p.rules.map(f=>` - ${f}`).join(`
@@ -559,11 +561,11 @@ ${s.join(`
559
561
 
560
562
  `)}
561
563
 
562
- File edits are auto-claimed. Use wgl commands for manual coordination.`};console.log(JSON.stringify(i))}}var iI=w(()=>{"use strict";et()});var aI={};V(aI,{handlePreToolUse:()=>W3});async function W3(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 cI=w(()=>{"use strict";et()});var lI={};V(lI,{handlePostToolUse:()=>J3});async function J3(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 uI=w(()=>{"use strict";et()});var pI={};V(pI,{handleStop:()=>K3});async function K3(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:
564
+ File edits are auto-claimed. Use wgl commands for manual coordination.`};console.log(JSON.stringify(i))}}var WC=w(()=>{"use strict";et()});var JC={};V(JC,{handlePreToolUse:()=>C3});async function C3(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 KC=w(()=>{"use strict";et()});var YC={};V(YC,{handlePostToolUse:()=>I3});async function I3(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 XC=w(()=>{"use strict";et()});var QC={};V(QC,{handleStop:()=>A3});async function A3(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:
563
565
  ${i.map(c=>` \u2022 ${c}`).join(`
564
- `)}`};console.log(JSON.stringify(a));return}}catch{}r.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role}).catch(()=>{})}var dI=w(()=>{"use strict";et()});var fI={};V(fI,{handlePromptSubmit:()=>X3});import{writeFileSync as Y3}from"node:fs";async function X3(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{Y3(e,JSON.stringify(t,null,2)+`
566
+ `)}`};console.log(JSON.stringify(a));return}}catch{}r.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role}).catch(()=>{})}var eI=w(()=>{"use strict";et()});var tI={};V(tI,{handlePromptSubmit:()=>z3});import{writeFileSync as N3}from"node:fs";async function z3(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{N3(e,JSON.stringify(t,null,2)+`
565
567
  `)}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(`
566
- `)}`)}var mI=w(()=>{"use strict";et()});var gI={};V(gI,{runHook:()=>tW});import{readFileSync as hI,existsSync as Q3}from"node:fs";import{join as eW}from"node:path";async function tW(t){let e=t[0],r=t[1]??eW(process.cwd(),".wgl.json");e||process.exit(0),Q3(r)||process.exit(0);let n;try{n=JSON.parse(hI(r,"utf8"))}catch{process.exit(0)}let o;try{let s=hI(0,"utf8");o=s?JSON.parse(s):{}}catch{o={}}switch(e){case"session-start":{let{handleSessionStart:s}=await Promise.resolve().then(()=>(iI(),sI));await s(n,r,o);break}case"pre-tool-use":{let{handlePreToolUse:s}=await Promise.resolve().then(()=>(cI(),aI));await s(n,o);break}case"post-tool-use":{let{handlePostToolUse:s}=await Promise.resolve().then(()=>(uI(),lI));await s(n,o);break}case"stop":{let{handleStop:s}=await Promise.resolve().then(()=>(dI(),pI));await s(n,o);break}case"prompt-submit":{let{handlePromptSubmit:s}=await Promise.resolve().then(()=>(mI(),fI));await s(n,r,o);break}default:process.exit(0)}}var yI=w(()=>{"use strict"});var _I={};V(_I,{scan:()=>oW});import{readFileSync as rW}from"node:fs";import{createRequire as nW}from"node:module";async function oW(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
568
+ `)}`)}var rI=w(()=>{"use strict";et()});var oI={};V(oI,{runHook:()=>L3});import{readFileSync as nI,existsSync as j3}from"node:fs";import{join as M3}from"node:path";async function L3(t){let e=t[0],r=t[1]??M3(process.cwd(),".wgl.json");e||process.exit(0),j3(r)||process.exit(0);let n;try{n=JSON.parse(nI(r,"utf8"))}catch{process.exit(0)}let o;try{let s=nI(0,"utf8");o=s?JSON.parse(s):{}}catch{o={}}switch(e){case"session-start":{let{handleSessionStart:s}=await Promise.resolve().then(()=>(WC(),VC));await s(n,r,o);break}case"pre-tool-use":{let{handlePreToolUse:s}=await Promise.resolve().then(()=>(KC(),JC));await s(n,o);break}case"post-tool-use":{let{handlePostToolUse:s}=await Promise.resolve().then(()=>(XC(),YC));await s(n,o);break}case"stop":{let{handleStop:s}=await Promise.resolve().then(()=>(eI(),QC));await s(n,o);break}case"prompt-submit":{let{handlePromptSubmit:s}=await Promise.resolve().then(()=>(rI(),tI));await s(n,r,o);break}default:process.exit(0)}}var sI=w(()=>{"use strict"});var aI={};V(aI,{scan:()=>Z3});import{readFileSync as D3}from"node:fs";import{createRequire as q3}from"node:module";async function Z3(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
567
569
  ${g("bold","wgl scan")} \u2014 scan text for prompt injection
568
570
 
569
571
  ${g("cyan","USAGE:")}
@@ -583,10 +585,10 @@ ${g("cyan","EXAMPLES:")}
583
585
  wgl scan --file user-input.txt
584
586
  wgl scan --json "hello world" | jq .score
585
587
  wgl scan --strict --file untrusted.txt
586
- `);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=rW(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=nW(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)),vI(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",g(f,p.action))),console.log(S("Pass",p.pass?g("green","yes"):g("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 y=m==="critical"||m==="high"?"red":m==="medium"?"yellow":"dim";for(let v of h)if(console.log(` ${g(y,`[${m.toUpperCase()}]`)} ${v.description}`),console.log(` ${g("dim",`Category: ${v.category} | Pattern: ${v.pattern} | Score: ${v.score}`)}`),v.matches.length>0){let b=v.matches[0].slice(0,80);console.log(` ${g("dim",`Match: "${b}"${v.matches[0].length>80?"...":""}`)}`)}}}else console.log(`
587
- ${g("green","No findings \u2014 text appears clean")}`);console.log(),vI(p,n)}function vI(t,e){t.action==="BLOCK"&&process.exit(2),e&&t.findings.length>0&&process.exit(1)}var bI=w(()=>{"use strict";Ee()});import{mkdirSync as sW,appendFileSync as iW,readdirSync as aW,unlinkSync as cW}from"node:fs";import{join as nb}from"node:path";function ob(t){let e=t.getTime(),r=e-e%ud;return new Date(r).toISOString()}function uW(){return new Date().toISOString().slice(0,10)}function wI(t){return new yi({endpoint:process.env.TELEMETRY_ENDPOINT,apiKey:process.env.TELEMETRY_API_KEY,projectRoot:t??process.cwd()})}var lW,yi,xI,SI=w(()=>{co();xc();lW=new Set(["latency_ms","total_tokens","prompt_tokens","completion_tokens","score"]);yi=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??ld,e.localDir)this.localDir=e.localDir;else if(e.projectRoot)try{this.localDir=nb(fs(e.projectRoot),bi)}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&&(sW(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=ob(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=uW(),n=nb(this.localDir,`${r}.jsonl`);try{iW(n,JSON.stringify(e)+`
588
- `)}catch{}}rotateFiles(){if(this.localDir)try{let e=aW(this.localDir).filter(r=>r.endsWith(".jsonl")).sort().reverse();for(let r=cd;r<e.length;r++)cW(nb(this.localDir,e[r]))}catch{}}aggregate(e){let r=ob(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 lW){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=ob(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{}}};xI=new yi});import{readFileSync as pW,readdirSync as dW,existsSync as fW}from"node:fs";import{join as $I}from"node:path";function kI(t){return $I(fs(t),bi)}function sb(t,e){if(!fW(t))return[];let r=new Date;r.setDate(r.getDate()-e);let n=r.toISOString().slice(0,10),o=dW(t).filter(i=>i.endsWith(".jsonl")&&i.slice(0,10)>=n).sort(),s=[];for(let i of o)try{let a=pW($I(t,i),"utf8");for(let c of a.split(`
589
- `))if(c.trim())try{s.push(JSON.parse(c))}catch{}}catch{}return s}function EI(t,e=30){let r=sb(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,y=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"&&y++;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:y,totalCompactions:v,totalTokens:b}}function TI(t,e=30){let r=sb(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 PI(t,e={}){let{limit:r=20,offset:n=0,eventType:o,days:s=30}=e,i=sb(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 RI=w(()=>{co();xc()});var OI={};V(OI,{NO_OP_TELEMETRY:()=>xI,TelemetryReporter:()=>yi,createTelemetryFromEnv:()=>wI,getTelemetryDir:()=>kI,localEvents:()=>PI,localOverview:()=>EI,localTimeline:()=>TI});var CI=w(()=>{SI();RI()});var II={};V(II,{telemetry:()=>mW});async function mW(t){let e=t[0];if(e==="--help"||e==="-h"||!e){console.log(`
588
+ `);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=D3(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=q3(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)),iI(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",g(f,p.action))),console.log(S("Pass",p.pass?g("green","yes"):g("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 y=m==="critical"||m==="high"?"red":m==="medium"?"yellow":"dim";for(let v of h)if(console.log(` ${g(y,`[${m.toUpperCase()}]`)} ${v.description}`),console.log(` ${g("dim",`Category: ${v.category} | Pattern: ${v.pattern} | Score: ${v.score}`)}`),v.matches.length>0){let b=v.matches[0].slice(0,80);console.log(` ${g("dim",`Match: "${b}"${v.matches[0].length>80?"...":""}`)}`)}}}else console.log(`
589
+ ${g("green","No findings \u2014 text appears clean")}`);console.log(),iI(p,n)}function iI(t,e){t.action==="BLOCK"&&process.exit(2),e&&t.findings.length>0&&process.exit(1)}var cI=w(()=>{"use strict";Te()});import{mkdirSync as U3,appendFileSync as F3,readdirSync as H3,unlinkSync as B3}from"node:fs";import{join as K_}from"node:path";function Y_(t){let e=t.getTime(),r=e-e%cd;return new Date(r).toISOString()}function V3(){return new Date().toISOString().slice(0,10)}function lI(t){return new gi({endpoint:process.env.TELEMETRY_ENDPOINT,apiKey:process.env.TELEMETRY_API_KEY,projectRoot:t??process.cwd()})}var G3,gi,uI,pI=w(()=>{lo();wc();G3=new Set(["latency_ms","total_tokens","prompt_tokens","completion_tokens","score"]);gi=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??ad,e.localDir)this.localDir=e.localDir;else if(e.projectRoot)try{this.localDir=K_(ds(e.projectRoot),_i)}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&&(U3(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=Y_(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=V3(),n=K_(this.localDir,`${r}.jsonl`);try{F3(n,JSON.stringify(e)+`
590
+ `)}catch{}}rotateFiles(){if(this.localDir)try{let e=H3(this.localDir).filter(r=>r.endsWith(".jsonl")).sort().reverse();for(let r=id;r<e.length;r++)B3(K_(this.localDir,e[r]))}catch{}}aggregate(e){let r=Y_(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 G3){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=Y_(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{}}};uI=new gi});import{readFileSync as W3,readdirSync as J3,existsSync as K3}from"node:fs";import{join as dI}from"node:path";function fI(t){return dI(ds(t),_i)}function X_(t,e){if(!K3(t))return[];let r=new Date;r.setDate(r.getDate()-e);let n=r.toISOString().slice(0,10),o=J3(t).filter(i=>i.endsWith(".jsonl")&&i.slice(0,10)>=n).sort(),s=[];for(let i of o)try{let a=W3(dI(t,i),"utf8");for(let c of a.split(`
591
+ `))if(c.trim())try{s.push(JSON.parse(c))}catch{}}catch{}return s}function mI(t,e=30){let r=X_(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,y=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"&&y++;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:y,totalCompactions:v,totalTokens:b}}function hI(t,e=30){let r=X_(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 gI(t,e={}){let{limit:r=20,offset:n=0,eventType:o,days:s=30}=e,i=X_(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 yI=w(()=>{lo();wc()});var vI={};V(vI,{NO_OP_TELEMETRY:()=>uI,TelemetryReporter:()=>gi,createTelemetryFromEnv:()=>lI,getTelemetryDir:()=>fI,localEvents:()=>gI,localOverview:()=>mI,localTimeline:()=>hI});var _I=w(()=>{pI();yI()});var bI={};V(bI,{telemetry:()=>Y3});async function Y3(t){let e=t[0];if(e==="--help"||e==="-h"||!e){console.log(`
590
592
  ${g("bold","wgl telemetry")} \u2014 view telemetry data from Carapace
591
593
 
592
594
  ${g("cyan","USAGE:")}
@@ -606,7 +608,7 @@ ${g("cyan","EXAMPLES:")}
606
608
  wgl telemetry overview --days 7
607
609
  wgl telemetry events --local --type scan
608
610
  wgl telemetry timeline --json
609
- `);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 hW(e,{days:s,limit:a,eventType:l,json:r});return}let u;try{u=Fe({profileName:ze().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 gW(u,s,r);break;case"events":await yW(u,a,r);break;case"timeline":await vW(u,s,r);break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl telemetry --help` for usage"),process.exit(2)}}async function hW(t,e){let{localOverview:r,localTimeline:n,localEvents:o,getTelemetryDir:s}=await Promise.resolve().then(()=>(CI(),OI)),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?g("red",String(c.threatsBlocked)):"0"]];c.totalLlmCalls!=null&&l.push(["LLM Calls",String(c.totalLlmCalls)],["LLM Errors",c.totalLlmErrors?g("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?g("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(ir(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(` ${g("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(` ${g("dim",p)} ${g(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(` ${g("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(` ${g("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(` ${g("bold",u)} ${g("dim",`(${f} events)`)}`);for(let d of p){let m="|".repeat(Math.min(d.count,40));console.log(` ${d.type.padEnd(18)} ${g("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 gW(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(ir([["Scans",String(o.totalScans)],["Threats Blocked",o.threatsBlocked>0?g("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 yW(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(` ${g("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(` ${g("dim",a)} ${g(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(` ${g("dim",c)}`)}}console.log()}async function vW(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(` ${g("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(` ${g("bold",i)} ${g("dim",`(${c} events)`)}`);for(let l of a){let u="|".repeat(Math.min(l.count,40));console.log(` ${l.type.padEnd(18)} ${g("cyan",u)} ${l.count}`)}}console.log()}var AI=w(()=>{"use strict";as();Ee();ro()});var NI={};V(NI,{completion:()=>bW});async function bW(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
611
+ `);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 X3(e,{days:s,limit:a,eventType:l,json:r});return}let u;try{u=Fe({profileName:ze().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 Q3(u,s,r);break;case"events":await eW(u,a,r);break;case"timeline":await tW(u,s,r);break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl telemetry --help` for usage"),process.exit(2)}}async function X3(t,e){let{localOverview:r,localTimeline:n,localEvents:o,getTelemetryDir:s}=await Promise.resolve().then(()=>(_I(),vI)),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?g("red",String(c.threatsBlocked)):"0"]];c.totalLlmCalls!=null&&l.push(["LLM Calls",String(c.totalLlmCalls)],["LLM Errors",c.totalLlmErrors?g("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?g("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(cr(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(` ${g("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(` ${g("dim",p)} ${g(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(` ${g("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(` ${g("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(` ${g("bold",u)} ${g("dim",`(${f} events)`)}`);for(let d of p){let m="|".repeat(Math.min(d.count,40));console.log(` ${d.type.padEnd(18)} ${g("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 Q3(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(cr([["Scans",String(o.totalScans)],["Threats Blocked",o.threatsBlocked>0?g("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 eW(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(` ${g("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(` ${g("dim",a)} ${g(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(` ${g("dim",c)}`)}}console.log()}async function tW(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(` ${g("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(` ${g("bold",i)} ${g("dim",`(${c} events)`)}`);for(let l of a){let u="|".repeat(Math.min(l.count,40));console.log(` ${l.type.padEnd(18)} ${g("cyan",u)} ${l.count}`)}}console.log()}var wI=w(()=>{"use strict";as();Te();no()});var xI={};V(xI,{completion:()=>nW});async function nW(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
610
612
  ${g("bold","wgl completion")} \u2014 generate shell completion scripts
611
613
 
612
614
  ${g("cyan","USAGE:")}
@@ -618,7 +620,7 @@ ${g("cyan","SETUP:")}
618
620
  eval "$(wgl completion bash)" # add to .bashrc
619
621
  eval "$(wgl completion zsh)" # add to .zshrc
620
622
  wgl completion fish | source # add to config.fish
621
- `);return}switch(e){case"bash":console.log(wW());break;case"zsh":console.log(xW());break;case"fish":console.log(SW());break;default:console.log(_(`Unknown shell: ${e}. Supported: bash, zsh, fish`)),process.exit(2)}}function wW(){let t=Object.entries(td).filter(([,e])=>e.length>0).map(([e,r])=>` ${e}) COMPREPLY=( $(compgen -W "${r.join(" ")}" -- "$cur") ) ;;`).join(`
623
+ `);return}switch(e){case"bash":console.log(oW());break;case"zsh":console.log(sW());break;case"fish":console.log(iW());break;default:console.log(_(`Unknown shell: ${e}. Supported: bash, zsh, fish`)),process.exit(2)}}function oW(){let t=Object.entries(Qp).filter(([,e])=>e.length>0).map(([e,r])=>` ${e}) COMPREPLY=( $(compgen -W "${r.join(" ")}" -- "$cur") ) ;;`).join(`
622
624
  `);return`# wgl bash completion \u2014 generated by wgl completion bash
623
625
  _wgl_completions() {
624
626
  local cur prev
@@ -627,7 +629,7 @@ _wgl_completions() {
627
629
  prev="\${COMP_WORDS[COMP_CWORD-1]}"
628
630
 
629
631
  if [ "$COMP_CWORD" -eq 1 ]; then
630
- COMPREPLY=( $(compgen -W "${_W} --help --version" -- "$cur") )
632
+ COMPREPLY=( $(compgen -W "${rW} --help --version" -- "$cur") )
631
633
  return
632
634
  fi
633
635
 
@@ -636,7 +638,7 @@ ${t}
636
638
  keys) COMPREPLY=( $(compgen -W "create list revoke" -- "$cur") ) ;;
637
639
  esac
638
640
  }
639
- complete -F _wgl_completions wgl`}function xW(){return`#compdef wgl
641
+ complete -F _wgl_completions wgl`}function sW(){return`#compdef wgl
640
642
  # wgl zsh completion \u2014 generated by wgl completion zsh
641
643
  _wgl() {
642
644
  local -a commands
@@ -675,22 +677,22 @@ _wgl() {
675
677
  fi
676
678
 
677
679
  case "\${words[2]}" in
678
- ${Object.entries(td).filter(([,e])=>e.length>0).map(([e,r])=>{let n=r.map(o=>`'${o}[${o}]'`).join(" ");return` ${e}) _arguments '1:subcommand:(${r.join(" ")})' ;;`}).join(`
680
+ ${Object.entries(Qp).filter(([,e])=>e.length>0).map(([e,r])=>{let n=r.map(o=>`'${o}[${o}]'`).join(" ");return` ${e}) _arguments '1:subcommand:(${r.join(" ")})' ;;`}).join(`
679
681
  `)}
680
682
  esac
681
683
  }
682
- _wgl "$@"`}function SW(){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(td))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(`
683
- `)}var td,_W,zI=w(()=>{"use strict";Ee();td={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:[]},_W=Object.keys(td).join(" ")});var jI={};V(jI,{upgrade:()=>IW});import{readFileSync as $W}from"node:fs";import{join as kW,dirname as EW}from"node:path";import{request as TW}from"node:https";import{execSync as PW}from"node:child_process";function OW(){return"1.0.10";try{let t=kW(EW(new URL(import.meta.url).pathname),"..","package.json");return JSON.parse($W(t,"utf8")).version}catch{return"0.0.0-dev"}}function CW(){return new Promise((t,e)=>{let r=TW(RW,{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 IW(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
684
+ _wgl "$@"`}function iW(){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(Qp))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(`
685
+ `)}var Qp,rW,SI=w(()=>{"use strict";Te();Qp={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:[]},rW=Object.keys(Qp).join(" ")});var $I={};V($I,{upgrade:()=>hW});import{readFileSync as aW}from"node:fs";import{join as cW,dirname as lW}from"node:path";import{request as uW}from"node:https";import{execSync as pW}from"node:child_process";function fW(){return"1.0.11";try{let t=cW(lW(new URL(import.meta.url).pathname),"..","package.json");return JSON.parse(aW(t,"utf8")).version}catch{return"0.0.0-dev"}}function mW(){return new Promise((t,e)=>{let r=uW(dW,{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 hW(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
684
686
  ${g("bold","wgl upgrade")} \u2014 update waggle-cli to the latest version
685
687
 
686
688
  ${g("cyan","USAGE:")}
687
689
  wgl upgrade Update to latest version
688
690
  wgl upgrade --check Just check, don't install
689
- `);return}let e=t.includes("--check"),r=OW();console.log(S("Current",r));let n;try{n=await CW()}catch{console.log(_("Cannot reach npm registry")),process.exit(1);return}if(console.log(S("Latest",n)),r===n){console.log(`
691
+ `);return}let e=t.includes("--check"),r=fW();console.log(S("Current",r));let n;try{n=await mW()}catch{console.log(_("Cannot reach npm registry")),process.exit(1);return}if(console.log(S("Latest",n)),r===n){console.log(`
690
692
  ${g("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(`
691
693
  ${g("green","Already up to date (or ahead)")}`);return}if(e){console.log(`
692
694
  ${g("yellow",`Update available: ${r} \u2192 ${n}`)}`),console.log(g("dim"," Run `wgl upgrade` to install"));return}console.log(`
693
- Upgrading ${r} \u2192 ${n}...`);try{PW("npm install -g @honeybee-ai/waggle-cli@latest",{stdio:"inherit"}),console.log(A(`Updated to ${n}`))}catch{console.log(_("Upgrade failed. Try manually: npm install -g @honeybee-ai/waggle-cli@latest")),process.exit(1)}}var RW,MI=w(()=>{"use strict";Ee();RW="https://registry.npmjs.org/@honeybee-ai/waggle-cli/latest"});Ee();var LI=process.argv.slice(2),cs=LI[0],Oe=LI.slice(1);function AW(){console.log(`
695
+ Upgrading ${r} \u2192 ${n}...`);try{pW("npm install -g @honeybee-ai/waggle-cli@latest",{stdio:"inherit"}),console.log(A(`Updated to ${n}`))}catch{console.log(_("Upgrade failed. Try manually: npm install -g @honeybee-ai/waggle-cli@latest")),process.exit(1)}}var dW,kI=w(()=>{"use strict";Te();dW="https://registry.npmjs.org/@honeybee-ai/waggle-cli/latest"});Te();var EI=process.argv.slice(2),cs=EI[0],Oe=EI.slice(1);function gW(){console.log(`
694
696
  ${g("bold","wgl")} \u2014 waggle-cli: bridge AI agents to ACP coordination servers
695
697
 
696
698
  ${g("cyan","USAGE:")}
@@ -827,7 +829,7 @@ ${g("cyan","EXAMPLES:")}
827
829
  wgl carapace gateway
828
830
  wgl incubator --port=8080 --brood=brood.yaml
829
831
  wgl leave
830
- `)}async function NW(){if(!cs||cs==="--help"||cs==="-h"){AW();return}if(cs==="--version"||cs==="-v"){console.log("1.0.10");return}switch(cs){case"init":{let{init:t}=await Promise.resolve().then(()=>(Rb(),Pb));await t(Oe);break}case"join":{let{join:t}=await Promise.resolve().then(()=>(Cb(),Ob));await t(Oe);break}case"status":{let{status:t}=await Promise.resolve().then(()=>(Ab(),Ib));await t();break}case"leave":{let{leave:t}=await Promise.resolve().then(()=>(zb(),Nb));await t();break}case"protocol":{let{protocol:t}=await Promise.resolve().then(()=>(Ww(),Vw));await t(Oe);break}case"team":{let{team:t}=await Promise.resolve().then(()=>(Kw(),Jw));await t();break}case"claim":{let{claim:t}=await Promise.resolve().then(()=>(Xw(),Yw));await t(Oe);break}case"release":{let{release:t}=await Promise.resolve().then(()=>(ex(),Qw));await t(Oe);break}case"halt":{let{halt:t}=await Promise.resolve().then(()=>(rx(),tx));await t(Oe);break}case"pause":{let{pause:t}=await Promise.resolve().then(()=>(rf(),tf));await t(Oe);break}case"resume":{let{resume:t}=await Promise.resolve().then(()=>(rf(),tf));await t();break}case"events":{let{events:t}=await Promise.resolve().then(()=>(sx(),ox));await t(Oe);break}case"state":{let{state:t}=await Promise.resolve().then(()=>(ax(),ix));await t(Oe);break}case"msg":{let{msg:t}=await Promise.resolve().then(()=>(lx(),cx));await t(Oe);break}case"help":{let{helpCmd:t}=await Promise.resolve().then(()=>(px(),ux));await t(Oe);break}case"namespace":{let{namespace:t}=await Promise.resolve().then(()=>(fx(),dx));await t(Oe);break}case"hooks":{let{hooksCmd:t}=await Promise.resolve().then(()=>(hx(),mx));await t(Oe);break}case"up":{let{up:t}=await Promise.resolve().then(()=>(Lx(),Mx));await t(Oe);break}case"down":{let{down:t}=await Promise.resolve().then(()=>(Ux(),Zx));await t(Oe);break}case"logs":{let{logs:t}=await Promise.resolve().then(()=>(Hx(),Fx));await t(Oe);break}case"inspect":{let{inspect:t}=await Promise.resolve().then(()=>(Vx(),Gx));await t(Oe);break}case"serve":{let{serve:t}=await Promise.resolve().then(()=>(CC(),OC));await t(Oe);break}case"auth":{let{auth:t}=await Promise.resolve().then(()=>(ZC(),qC));await t(Oe);break}case"config":{let{configCmd:t}=await Promise.resolve().then(()=>(HC(),FC));await t(Oe);break}case"marketplace":{let{marketplace:t}=await Promise.resolve().then(()=>(GC(),BC));await t(Oe);break}case"integrations":{let{integrations:t}=await Promise.resolve().then(()=>(YC(),KC));await t(Oe);break}case"secret":{let{secret:t}=await Promise.resolve().then(()=>(QC(),XC));await t(Oe);break}case"hive":{let{hive:t}=await Promise.resolve().then(()=>(rI(),tI));await t(Oe);break}case"carapace":{let{runCarapace:t}=await Promise.resolve().then(()=>(oI(),nI));await t(Oe);break}case"incubator":{let{main:t}=await Promise.resolve().then(()=>(F_(),U_)),e=process.argv;process.argv=["node","incubator",...Oe];try{await t()}finally{process.argv=e}break}case"hook":{let{runHook:t}=await Promise.resolve().then(()=>(yI(),gI));await t(Oe);break}case"scan":{let{scan:t}=await Promise.resolve().then(()=>(bI(),_I));await t(Oe);break}case"telemetry":{let{telemetry:t}=await Promise.resolve().then(()=>(AI(),II));await t(Oe);break}case"completion":{let{completion:t}=await Promise.resolve().then(()=>(zI(),NI));await t(Oe);break}case"upgrade":{let{upgrade:t}=await Promise.resolve().then(()=>(MI(),jI));await t(Oe);break}default:console.error(g("red",`Unknown command: ${cs}`)),console.log("Run `wgl --help` for usage"),process.exit(2)}}NW().catch(t=>{console.error(g("red",`Error: ${t.message}`)),process.exit(2)});
832
+ `)}async function yW(){if(!cs||cs==="--help"||cs==="-h"){gW();return}if(cs==="--version"||cs==="-v"){console.log("1.0.11");return}switch(cs){case"init":{let{init:t}=await Promise.resolve().then(()=>(xb(),wb));await t(Oe);break}case"join":{let{join:t}=await Promise.resolve().then(()=>($b(),Sb));await t(Oe);break}case"status":{let{status:t}=await Promise.resolve().then(()=>(Eb(),kb));await t();break}case"leave":{let{leave:t}=await Promise.resolve().then(()=>(Pb(),Tb));await t();break}case"protocol":{let{protocol:t}=await Promise.resolve().then(()=>(Zw(),qw));await t(Oe);break}case"team":{let{team:t}=await Promise.resolve().then(()=>(Fw(),Uw));await t();break}case"claim":{let{claim:t}=await Promise.resolve().then(()=>(Bw(),Hw));await t(Oe);break}case"release":{let{release:t}=await Promise.resolve().then(()=>(Vw(),Gw));await t(Oe);break}case"halt":{let{halt:t}=await Promise.resolve().then(()=>(Jw(),Ww));await t(Oe);break}case"pause":{let{pause:t}=await Promise.resolve().then(()=>(ef(),Qd));await t(Oe);break}case"resume":{let{resume:t}=await Promise.resolve().then(()=>(ef(),Qd));await t();break}case"events":{let{events:t}=await Promise.resolve().then(()=>(Xw(),Yw));await t(Oe);break}case"state":{let{state:t}=await Promise.resolve().then(()=>(ex(),Qw));await t(Oe);break}case"msg":{let{msg:t}=await Promise.resolve().then(()=>(rx(),tx));await t(Oe);break}case"help":{let{helpCmd:t}=await Promise.resolve().then(()=>(ox(),nx));await t(Oe);break}case"namespace":{let{namespace:t}=await Promise.resolve().then(()=>(ix(),sx));await t(Oe);break}case"hooks":{let{hooksCmd:t}=await Promise.resolve().then(()=>(cx(),ax));await t(Oe);break}case"up":{let{up:t}=await Promise.resolve().then(()=>(Ex(),kx));await t(Oe);break}case"down":{let{down:t}=await Promise.resolve().then(()=>(Ox(),Rx));await t(Oe);break}case"logs":{let{logs:t}=await Promise.resolve().then(()=>(Ix(),Cx));await t(Oe);break}case"inspect":{let{inspect:t}=await Promise.resolve().then(()=>(zx(),Nx));await t(Oe);break}case"serve":{let{serve:t}=await Promise.resolve().then(()=>(_C(),vC));await t(Oe);break}case"auth":{let{auth:t}=await Promise.resolve().then(()=>(RC(),PC));await t(Oe);break}case"config":{let{configCmd:t}=await Promise.resolve().then(()=>(IC(),CC));await t(Oe);break}case"marketplace":{let{marketplace:t}=await Promise.resolve().then(()=>(NC(),AC));await t(Oe);break}case"integrations":{let{integrations:t}=await Promise.resolve().then(()=>(DC(),LC));await t(Oe);break}case"secret":{let{secret:t}=await Promise.resolve().then(()=>(ZC(),qC));await t(Oe);break}case"hive":{let{hive:t}=await Promise.resolve().then(()=>(HC(),FC));await t(Oe);break}case"carapace":{let{runCarapace:t}=await Promise.resolve().then(()=>(GC(),BC));await t(Oe);break}case"incubator":{let{main:t}=await Promise.resolve().then(()=>(z_(),N_)),e=process.argv;process.argv=["node","incubator",...Oe];try{await t()}finally{process.argv=e}break}case"hook":{let{runHook:t}=await Promise.resolve().then(()=>(sI(),oI));await t(Oe);break}case"scan":{let{scan:t}=await Promise.resolve().then(()=>(cI(),aI));await t(Oe);break}case"telemetry":{let{telemetry:t}=await Promise.resolve().then(()=>(wI(),bI));await t(Oe);break}case"completion":{let{completion:t}=await Promise.resolve().then(()=>(SI(),xI));await t(Oe);break}case"upgrade":{let{upgrade:t}=await Promise.resolve().then(()=>(kI(),$I));await t(Oe);break}default:console.error(g("red",`Unknown command: ${cs}`)),console.log("Run `wgl --help` for usage"),process.exit(2)}}yW().catch(t=>{console.error(g("red",`Error: ${t.message}`)),process.exit(2)});
831
833
  /*! Bundled license information:
832
834
 
833
835
  js-yaml/dist/js-yaml.mjs: