@honeybee-ai/waggle-cli 1.0.14 → 1.0.15

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 PI=Object.create;var ed=Object.defineProperty;var RI=Object.getOwnPropertyDescriptor;var OI=Object.getOwnPropertyNames;var CI=Object.getPrototypeOf,II=Object.prototype.hasOwnProperty;var it=(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`
3
+ var UI=Object.create;var od=Object.defineProperty;var ZI=Object.getOwnPropertyDescriptor;var FI=Object.getOwnPropertyNames;var HI=Object.getPrototypeOf,BI=Object.prototype.hasOwnProperty;var it=(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),G=(t,e)=>{for(var r in e)od(t,r,{get:e[r],enumerable:!0})},GI=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of FI(e))!BI.call(t,o)&&o!==r&&od(t,o,{get:()=>e[o],enumerable:!(n=ZI(e,o))||n.enumerable});return t};var po=(t,e,r)=>(r=t!=null?UI(HI(t)):{},GI(e||!t||!t.__esModule?od(r,"default",{value:t,enumerable:!0}):r,t));function g(t,e){return`${sb[t]}${e}${sb.reset}`}function fo(t){return g("dim",t)}function P(t){return`
4
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 ee(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=ee(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=ee(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=ee(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=ee(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:
5
+ `)}var sb,$e=w(()=>{"use strict";sb={red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",cyan:"\x1B[36m",gray:"\x1B[90m",bold:"\x1B[1m",dim:"\x1B[2m",reset:"\x1B[0m"}});import{randomBytes as VI}from"node:crypto";function _c(){return`wgl_${VI(4).toString("hex")}`}var sd=w(()=>{"use strict"});import{join as ib}from"node:path";import{homedir as ab}from"node:os";var yt,Mr,fs,id,ms,ad,bc,mo,hs,wc,cd,ld,ho,ud,pd,dd,fd,md,bn=w(()=>{yt=ib(ab(),".honeyb"),Mr=ib(ab(),".wgl"),fs="auth.json",id="integrations.json",ms=".honeyb",ad=".honeybee",bc=[".wglrc.yaml",".wglrc.json",".wglrc"],mo=".wgl.json",hs="session.json",wc="brood.state.json",cd="logs",ld=10,ho="telemetry",ud=30,pd=3e5,dd=3e5,fd={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"},md={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 pb,writeFileSync as hd,existsSync as Ft,mkdirSync as xc,copyFileSync as gd,chmodSync as WI}from"node:fs";import{join as tr,resolve as JI}from"node:path";import{homedir as cb}from"node:os";function yd(){if(lb)return;lb=!0;let t=tr(Mr,"auth.json"),e=tr(yt,fs);Ft(t)&&!Ft(e)&&(Ft(yt)||xc(yt,{recursive:!0}),gd(t,e),WI(e,384),console.error("[honeyb] Migrated auth store: ~/.wgl/auth.json \u2192 ~/.honeyb/auth.json"));let r=tr(Mr,"config.json"),n=cb(),o=tr(n,".wglrc.json");if(Ft(r)&&!Ft(o))try{let a=JSON.parse(pb(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&&(hd(o,JSON.stringify(c,null,2)+`
6
+ `),console.error("[honeyb] Migrated global config: ~/.wgl/config.json \u2192 ~/.wglrc.json"))}catch{}let s=tr(cb(),".config","honeybee","integrations.json"),i=tr(yt,id);Ft(s)&&!Ft(i)&&(Ft(yt)||xc(yt,{recursive:!0}),gd(s,i),console.error("[honeyb] Migrated integrations: ~/.config/honeybee/integrations.json \u2192 ~/.honeyb/integrations.json"))}function vd(t){let e=JI(t||process.cwd());if(ub.has(e))return;ub.add(e);let r=tr(e,mo),n=tr(e,".wglrc.json"),o=tr(e,ms),s=tr(o,hs);if(Ft(r)&&!Ft(n))try{let l=JSON.parse(pb(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&&hd(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)||xc(o,{recursive:!0}),hd(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,ad),a=tr(i,"brood.state.json"),c=tr(o,wc);Ft(a)&&!Ft(c)&&(Ft(o)||xc(o,{recursive:!0}),gd(a,c),console.error("[honeyb] Migrated brood state: .honeybee/brood.state.json \u2192 .honeyb/brood.state.json"))}var lb,ub,_d=w(()=>{bn();lb=!1,ub=new Set});import{readFileSync as wd,writeFileSync as XI,existsSync as xn,mkdirSync as Sc,readdirSync as QI,unlinkSync as e1}from"node:fs";import{join as kr,dirname as db,resolve as xi,sep as t1}from"node:path";import{homedir as r1}from"node:os";function xd(t){let e=xi(t||process.cwd()),r=t1==="/"?"/":e.slice(0,3);for(;;){for(let o of bc){let s=kr(e,o);if(xn(s))return s}let n=db(e);if(n===e||e===r)return null;e=n}}function fb(){let t=r1();for(let e of bc){let r=kr(t,e);if(xn(r))return r}return null}function bd(t){let e=wd(t,"utf8").trim();return e?t.endsWith(".yaml")?n1(e):t.endsWith(".json")?mb(e):s1(e):{}}function mb(t){try{let e=JSON.parse(t);return typeof e!="object"||e===null||Array.isArray(e)?{}:e}catch{return{}}}function n1(t){try{return o1(t)}catch{return mb(t)}}function o1(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]=Sd(l)}return e}function s1(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();Si(e,s,Sd(i))}return e}function Sd(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 Si(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 wn(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]=wn(s,o):r[n]=o}return r}function i1(){let t={};for(let[e,r]of Object.entries(fd)){let n=process.env[e];n!==void 0&&n!==""&&Si(t,r,Sd(n))}return t}function Lr(t){yd(),vd(t);let e=structuredClone(md),r=fb();r&&(e=wn(e,bd(r)));let n=xd(t);if(n&&(e=wn(e,bd(n))),!n){let o=a1(t);if(o){let s=c1(o);s&&(e=wn(e,s))}}return e=wn(e,i1()),Object.freeze(e)}function kc(){return xn(yt)||Sc(yt,{recursive:!0}),yt}function hb(t){return xi(t||process.cwd()).replace(/^\//,"").replace(/\//g,"-")}function Sn(t){let e=hb(t),r=kr(kc(),"projects",e);return xn(r)||Sc(r,{recursive:!0}),r}function gb(t){let e=xi(t||process.cwd()),r=kr(e,ms);return xn(r)||Sc(r,{recursive:!0}),r}function $d(t){let e=kr(xi(t||process.cwd()),ms),r=kr(e,hs);if(!xn(r))return{};try{return JSON.parse(wd(r,"utf8"))}catch{return{}}}function kd(t,e){let r=gb(e),n=kr(r,hs);XI(n,JSON.stringify(t,null,2)+`
11
+ `)}function $n(t){let e=kr(Sn(t),cd);return xn(e)||Sc(e,{recursive:!0}),e}function Ed(t){let e=$n(t),r=new Date().toISOString().replace(/[:.]/g,"-");return kr(e,`${r}.jsonl`)}function Td(t){let e=$n(t);try{let r=QI(e).filter(n=>n.endsWith(".jsonl")).sort().reverse();for(let n=ld;n<r.length;n++)e1(kr(e,r[n]))}catch{}}function a1(t){let e=xi(t||process.cwd()),r="/";for(;;){let n=kr(e,mo);if(xn(n))return n;let o=db(e);if(o===e||e===r)return null;e=o}}function c1(t){try{let e=JSON.parse(wd(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 $i=w(()=>{bn();_d()});import{readFileSync as l1,writeFileSync as u1,existsSync as Ec,mkdirSync as p1,chmodSync as d1}from"node:fs";import{join as Pd}from"node:path";function f1(){let t=Pd(yt,fs);if(Ec(t))return t;let e=Pd(Mr,"auth.json");return Ec(e)?e:t}function go(){let t=f1();if(!Ec(t))return{profiles:{}};try{return JSON.parse(l1(t,"utf8"))}catch{return{profiles:{}}}}function ki(t){Ec(yt)||p1(yt,{recursive:!0});let e=Pd(yt,fs);u1(e,JSON.stringify(t,null,2)+`
12
+ `,{mode:384}),d1(e,384)}function Rd(t){return go().profiles[t]||null}function Cd(t,e){let r=go();r.profiles[t]=e,ki(r)}function Od(t){let e=go();return t in e.profiles?(delete e.profiles[t],ki(e),!0):!1}function Id(){let t=go();return Object.keys(t.profiles)}var yb=w(()=>{bn()});var kn=w(()=>{bn();$i();yb();_d()});import{writeFileSync as m1,existsSync as vb,unlinkSync as _b}from"node:fs";import{join as Ad}from"node:path";function _e(t){let e=Lr(t),r=$d(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 Tc(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=Ad(r,".wglrc.json");m1(o,JSON.stringify(n,null,2)+`
13
+ `);let s={agentId:t.agentId,lastEventCursor:t.lastEventCursor,autoPublishDiscoveries:t.autoPublishDiscoveries};return kd(s,r),o}function bb(t){let e=t||process.cwd(),r=!1;for(let o of[".wglrc.json",".wglrc.yaml",".wglrc"]){let s=Ad(e,o);vb(s)&&(_b(s),r=!0)}let n=Ad(e,mo);return vb(n)&&(_b(n),r=!0),r}function Pc(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";kn()});import{readFileSync as h1,writeFileSync as g1,existsSync as wb,mkdirSync as y1}from"node:fs";import{join as v1,dirname as _1}from"node:path";function xb(){return v1(process.cwd(),".claude","settings.local.json")}function Sb(){let t=xb();if(!wb(t))return{};try{return JSON.parse(h1(t,"utf8"))}catch{return{}}}function $b(t){let e=xb(),r=_1(e);wb(r)||y1(r,{recursive:!0}),g1(e,JSON.stringify(t,null,2)+`
14
+ `)}function Rc(t){return t.includes("waggle-cli")||t.includes("/cli/hooks/")||t.includes(" hook ")}function gs(t=10){let e=process.argv[1],r=Sb();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=>Rc(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 Cc(){let t=Sb();if(t.hooks){for(let e of Object.keys(t.hooks))t.hooks[e]=t.hooks[e].filter(r=>!Rc(r.command)),t.hooks[e].length===0&&delete t.hooks[e];Object.keys(t.hooks).length===0&&delete t.hooks,$b(t)}}var Ei=w(()=>{"use strict"});import{request as b1}from"node:http";import{request as w1}from"node:https";function ee(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:"?w1:b1,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:x1},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 x1,kb=w(()=>{x1=3e3});var et=w(()=>{kb()});var Eb={};G(Eb,{init:()=>$1});import{createInterface as S1}from"node:readline";function Nd(t,e,r){let n=r?` ${g("dim",`[${r}]`)}`:"";return new Promise(o=>{t.question(` ${e}${n}: `,s=>{o(s.trim()||r||"")})})}async function $1(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=S1({input:process.stdin,output:process.stdout});console.log(P("waggle-cli setup")),console.log(),n=await Nd(d,"Server URL","http://localhost:3100"),o=await Nd(d,"Namespace","default"),s=await Nd(d,"Role","developer"),d.close(),console.log()}let l=_c(),u=Pc(n,l,s,o),p=ee(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=Tc(u);gs(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 Tb=w(()=>{"use strict";sd();mt();Ei();et();$e()});var Pb={};G(Pb,{join:()=>k1});async function k1(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=_c(),c=Pc(r,a,s,i),l=ee(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{}Tc(c),gs(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(P("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(P("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 Rb=w(()=>{"use strict";sd();mt();Ei();et();$e()});var Cb={};G(Cb,{status:()=>E1});async function E1(){let t=_e();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=ee(t);console.log(P("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(P("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(P("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(P("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 Ob=w(()=>{"use strict";mt();et();$e()});var Ib={};G(Ib,{leave:()=>T1});async function T1(){let t=_e();t||(console.log(_("Not initialized. Nothing to do.")),process.exit(1));let e=ee(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{}Cc(),bb(),console.log(A("Left coordination server. Hooks removed, config deleted."))}var Ab=w(()=>{"use strict";mt();Ei();et();$e()});var Oc,zd=w(()=>{Oc="1.0"});var Nb={};G(Nb,{SpecValidationError:()=>yo,normalizeAgents:()=>Md,normalizeRules:()=>Ti,validateSpec:()=>jd});function jd(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]=Oc.split(".").map(Number);n!==o&&e.push(`Unsupported ACP version ${r.acp} (this parser supports ${Oc})`)}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 Ti(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 Md(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 yo,Ic=w(()=>{zd();yo=class extends Error{errors;constructor(e){super(`Invalid ACP spec:
16
16
  - ${e.join(`
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+=`
17
+ - `)}`),this.errors=e,this.name="SpecValidationError"}}});import{readFile as P1}from"node:fs/promises";async function R1(){if(!Pi)try{let{createRequire:t}=await import("node:module");Pi=t(import.meta.url)("js-yaml")}catch{}}function C1(t){if(Pi)return Pi.load(t,{schema:Pi.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 vo(t,e){let{validateSpec:r,SpecValidationError:n}=await Promise.resolve().then(()=>(Ic(),Nb));await R1();let o=C1(t);(e?.variables||o&&typeof o=="object"&&o.variables)&&(o=zb(o,e?.variables??{}));let s=r(o);if(s.length>0)throw new n(s);return o}async function Ac(t,e){let r=await P1(t,"utf-8");return vo(r,e)}function zb(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 Ld(t,o)}function Ld(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=>Ld(r,e));if(t&&typeof t=="object"){let r={};for(let[n,o]of Object.entries(t))r[n]=Ld(o,e);return r}return t}var Pi,O1,Dd=w(()=>{Ic();O1=/^\$\{([a-zA-Z_][a-zA-Z0-9_]*)\}$/});async function qd(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 Ri(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 Ud=w(()=>{});function Nc(t,e,r){return Ti(t.rules)[e]?.[r]??{steps:[]}}function I1(t,e,r,n){let o=e+1,s=n(t.action),i=t.description?` \u2014 ${Ri(t.description,r)}`:"",a=t.hint?`
19
+ Hint: ${Ri(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"?Ri(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 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?`
25
+ If value equals ${l}: skip remaining steps`)}return c+=a,c}function A1(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 w1(t){if(!t)return"";let e=[`
30
+ `):""}function N1(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 x1(t){if(!t)return"";let e=[`
34
+ `)}function z1(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 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?`
38
+ `):""}function j1(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 $1(t){if(!t||t.length===0)return"";let e=[`
43
+ `):""}function M1(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 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(`
47
+ `)}function Zd(t,e,r,n,o){let s=o?.toolMapping??jb,i=d=>s[d]??d,a=t.roles[e],c=t.phases[r],l=Nc(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(_1(l.steps[d],d,n,i))}else c.terminal?u.push(`
55
+ `);for(let d=0;d<l.steps.length;d++)u.push(I1(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(b1(t.resources)),u.push(w1(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(A1(t.resources)),u.push(N1(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($1(n.$team)),u.push(x1(t.governance)),u.push(S1(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(M1(n.$team)),u.push(z1(t.governance)),u.push(j1(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 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+=`
70
+ `)}var jb,Mb=w(()=>{Dd();Ud();jb={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 Ci=w(()=>{zd();Ic();Dd();Ud();Mb()});function Qb(t){return typeof t>"u"||t===null}function L1(t){return typeof t=="object"&&t!==null}function D1(t){return Array.isArray(t)?t:Qb(t)?[]:[t]}function q1(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 U1(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 ew(t,e){var r="",n=t.reason||"(unknown reason)";return t.mark?(t.mark.name&&(r+='in "'+t.mark.name+'" '),r+="("+(t.mark.line+1)+":"+(t.mark.column+1)+")",!e&&t.mark.snippet&&(r+=`
71
71
 
72
- `+t.mark.snippet),n+" "+r):n}function 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+`
72
+ `+t.mark.snippet),n+" "+r):n}function Ii(t,e){Error.call(this),this.name="YAMLException",this.reason=t,this.mark=e,this.message=ew(this,!1),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||""}function Fd(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 Hd(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=Fd(t.buffer,n[i-c],o[i-c],t.position-(n[i]-n[i-c]),p),a=ut.repeat(" ",e.indent)+Hd((t.line-c+1).toString(),u)+" | "+l.str+`
73
+ `+a;for(l=Fd(t.buffer,n[i],o[i],t.position,p),a+=ut.repeat(" ",e.indent)+Hd((t.line+1).toString(),u)+" | "+l.str+`
74
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 H(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||H(t,"expected valid JSON character");else EA.test(a)&&H(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)||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],$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])&&H(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,H(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++):H(t,"a line break is expected"),t.line+=1,t.lineStart=t.position,t.firstTabInLine=-1}function at(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,at(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,at(t,!1,e)),n=o=t.position):t.position===t.lineStart&&jc(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 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))at(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:H(t,"expected hexadecimal character");t.result+=IA(s),t.position++}else H(t,"unknown escape sequence");r=n=t.position}else Dr(a)?(Sn(t,r,n,!0),Kd(t,at(t,!1,e)),r=n=t.position):t.position===t.lineStart&&jc(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 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(at(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),Ht(l)&&(p=f=!0,t.position++,at(t,!0,e))),n=t.line,o=t.lineStart,s=t.position,ys(t,e,Cc,!1,!0),y=t.tag,h=t.result,at(t,!0,e),b=t.input.charCodeAt(t.position),(f||t.line===n)&&b===58&&(p=!0,b=t.input.charCodeAt(++t.position),at(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),at(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 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:H(t,"repeat of a chomping mode identifier");else if((u=CA(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(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(`
75
+ `,c=1;c<=e.linesAfter&&!(i+c>=o.length);c++)l=Fd(t.buffer,n[i+c],o[i+c],t.position-(n[i]-n[i+c]),p),a+=ut.repeat(" ",e.indent)+Hd((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 eA(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(Y1.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),X1.indexOf(this.kind)===-1)throw new jt('Unknown kind "'+this.kind+'" is specified for "'+t+'" YAML type.')}function Lb(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 tA(){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 Gd(t){return this.extend(t)}function rA(t){if(t===null)return!0;var e=t.length;return e===1&&t==="~"||e===4&&(t==="null"||t==="Null"||t==="NULL")}function nA(){return null}function oA(t){return t===null}function sA(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 iA(t){return t==="true"||t==="True"||t==="TRUE"}function aA(t){return Object.prototype.toString.call(t)==="[object Boolean]"}function cA(t){return 48<=t&&t<=57||65<=t&&t<=70||97<=t&&t<=102}function lA(t){return 48<=t&&t<=55}function uA(t){return 48<=t&&t<=57}function pA(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(!cA(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}if(o==="o"){for(r++;r<e;r++)if(o=t[r],o!=="_"){if(!lA(t.charCodeAt(r)))return!1;n=!0}return n&&o!=="_"}}if(o==="_")return!1;for(;r<e;r++)if(o=t[r],o!=="_"){if(!uA(t.charCodeAt(r)))return!1;n=!0}return!(!n||o==="_")}function dA(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 fA(t){return Object.prototype.toString.call(t)==="[object Number]"&&t%1===0&&!ut.isNegativeZero(t)}function hA(t){return!(t===null||!mA.test(t)||t[t.length-1]==="_")}function gA(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 vA(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),yA.test(r)?r.replace("e",".e"):r}function _A(t){return Object.prototype.toString.call(t)==="[object Number]"&&(t%1!==0||ut.isNegativeZero(t))}function bA(t){return t===null?!1:dw.exec(t)!==null||fw.exec(t)!==null}function wA(t){var e,r,n,o,s,i,a,c=0,l=null,u,p,f;if(e=dw.exec(t),e===null&&(e=fw.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 xA(t){return t.toISOString()}function SA(t){return t==="<<"||t===null}function $A(t){if(t===null)return!1;var e,r,n=0,o=t.length,s=Yd;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 kA(t){var e,r,n=t.replace(/[\r\n=]/g,""),o=n.length,s=Yd,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 EA(t){var e="",r=0,n,o,s=t.length,i=Yd;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 TA(t){return Object.prototype.toString.call(t)==="[object Uint8Array]"}function CA(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,RA.call(o)!=="[object Object]")return!1;for(s in o)if(PA.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 AA(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],IA.call(n)!=="[object Object]"||(o=Object.keys(n),o.length!==1))return!1;s[e]=[o[0],n[o[0]]]}return!0}function NA(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 jA(t){if(t===null)return!0;var e,r=t;for(e in r)if(zA.call(r,e)&&r[e]!==null)return!1;return!0}function MA(t){return t!==null?t:{}}function qb(t){return Object.prototype.toString.call(t)}function Dr(t){return t===10||t===13}function bo(t){return t===9||t===32}function Ht(t){return t===9||t===32||t===10||t===13}function vs(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 FA(t){return t===120?2:t===117?4:t===85?8:0}function HA(t){return 48<=t&&t<=57?t-48:-1}function Ub(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 BA(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 GA(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||Xd,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 Tw(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=K1(r),new jt(e,r)}function H(t,e){throw Tw(t,e)}function Mc(t,e){t.onWarning&&t.onWarning.call(null,Tw(t,e))}function En(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 DA.test(a)&&H(t,"the stream contains non-printable characters");t.result+=a}}function Fb(t,e,r,n){var o,s,i,a;for(ut.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],Tn.call(e,s)||($w(e,s,r[s]),n[s]=!0)}function _s(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"&&qb(o[l])==="[object Object]"&&(o[l]="[object Object]");if(typeof o=="object"&&qb(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)Fb(t,e,s[l],r);else Fb(t,e,s,r);else!t.json&&!Tn.call(r,o)&&Tn.call(e,o)&&(t.line=i||t.line,t.lineStart=a||t.lineStart,t.position=c||t.position,H(t,"duplicated mapping key")),$w(e,o,s),delete r[o];return e}function Qd(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 at(t,e,r){for(var n=0,o=t.input.charCodeAt(t.position);o!==0;){for(;bo(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(Qd(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&&Mc(t,"deficient indentation"),n}function qc(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 ef(t,e){e===1?t.result+=" ":e>1&&(t.result+=ut.repeat(`
78
+ `,e-1))}function VA(t,e,r){var n,o,s,i,a,c,l,u,p=t.kind,f=t.result,d;if(d=t.input.charCodeAt(t.position),Ht(d)||vs(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&&vs(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&&vs(o))break}else if(d===35){if(n=t.input.charCodeAt(t.position-1),Ht(n))break}else{if(t.position===t.lineStart&&qc(t)||r&&vs(d))break;if(Dr(d))if(c=t.line,l=t.lineStart,u=t.lineIndent,at(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&&(En(t,s,i,!1),ef(t,t.line-c),s=i=t.position,a=!1),bo(d)||(i=t.position+1),d=t.input.charCodeAt(++t.position)}return En(t,s,i,!1),t.result?!0:(t.kind=p,t.result=f,!1)}function WA(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(En(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)?(En(t,n,o,!0),ef(t,at(t,!1,e)),n=o=t.position):t.position===t.lineStart&&qc(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 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 En(t,r,t.position,!0),t.position++,!0;if(a===92){if(En(t,r,t.position,!0),a=t.input.charCodeAt(++t.position),Dr(a))at(t,!1,e);else if(a<256&&kw[a])t.result+=Ew[a],t.position++;else if((i=FA(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+=BA(s),t.position++}else H(t,"unknown escape sequence");r=n=t.position}else Dr(a)?(En(t,r,n,!0),ef(t,at(t,!1,e)),r=n=t.position):t.position===t.lineStart&&qc(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 KA(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(at(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),Ht(l)&&(p=f=!0,t.position++,at(t,!0,e))),n=t.line,o=t.lineStart,s=t.position,bs(t,e,zc,!1,!0),y=t.tag,h=t.result,at(t,!0,e),b=t.input.charCodeAt(t.position),(f||t.line===n)&&b===58&&(p=!0,b=t.input.charCodeAt(++t.position),at(t,!0,e),bs(t,e,zc,!1,!0),v=t.result),d?_s(t,a,m,y,h,v,n,o,s):p?a.push(_s(t,null,m,y,h,v,n,o,s)):a.push(h),at(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 YA(t,e){var r,n,o=Bd,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)Bd===o?o=p===43?Db:LA:H(t,"repeat of a chomping mode identifier");else if((u=HA(p))>=0)u===0?H(t,"bad explicit indentation width of a block scalar; it cannot be less than one"):i?H(t,"repeat of an indentation width identifier"):(a=e+u-1,i=!0);else break;if(bo(p)){do p=t.input.charCodeAt(++t.position);while(bo(p));if(p===35)do p=t.input.charCodeAt(++t.position);while(!Dr(p)&&p!==0)}for(;p!==0;){for(Qd(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===Db?t.result+=ut.repeat(`
79
+ `,s?1+c:c):o===Bd&&s&&(t.result+=`
80
+ `);break}for(n?bo(p)?(l=!0,t.result+=ut.repeat(`
81
81
  `,s?1+c:c)):l?(l=!1,t.result+=ut.repeat(`
82
82
  `,c+1)):c===0?s&&(t.result+=" "):t.result+=ut.repeat(`
83
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,H(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++,at(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),at(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 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,H(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):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,!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)||H(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)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),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),at(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&&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&&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&&!Ht(i);)i===33&&(n?H(t,"tag suffix cannot contain exclamation marks"):(o=t.input.slice(e-1,t.position+1),yw.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),PA.test(s)&&H(t,"tag suffix cannot contain flow indicator characters")}s&&!vw.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:$n.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 ZA(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&&!Ht(r)&&!hs(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 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&&H(t,"name of an alias node must contain at least one character"),r=t.input.slice(e,t.position),$n.call(t.anchorMap,r)||H(t,'unidentified alias "'+r+'"'),t.result=t.anchorMap[r],at(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&&at(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);)at(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)&&H(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"&&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($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||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 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&&(at(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&&H(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(at(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,at(t,!0,-1)):s&&H(t,"directives end mark is expected"),ys(t,t.lineIndent-1,Ic,!1,!0),at(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,at(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 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,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;)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(`
84
+ `,s?1+c:c),s=!0,i=!0,c=0,r=t.position;!Dr(p)&&p!==0;)p=t.input.charCodeAt(++t.position);En(t,r,t.position,!1)}return!0}function Hb(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),!Ht(i))));){if(a=!0,t.position++,at(t,!0,-1)&&t.lineIndent<=e){s.push(null),c=t.input.charCodeAt(t.position);continue}if(r=t.line,bs(t,e,ww,!1,!0),s.push(t.result),at(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 XA(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)&&Ht(n))b===63?(y&&(_s(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,!bs(t,r,bw,!1,!0))break;if(t.line===s){for(b=t.input.charCodeAt(t.position);bo(b);)b=t.input.charCodeAt(++t.position);if(b===58)b=t.input.charCodeAt(++t.position),Ht(b)||H(t,"a whitespace character is expected after the key-value separator within a block mapping"),y&&(_s(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),bs(t,e,jc,!0,o)&&(y?m=t.result:h=t.result),y||(_s(t,p,f,d,m,h,i,a,c),d=m=h=null),at(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&&_s(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&&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&&!Ht(i);)i===33&&(n?H(t,"tag suffix cannot contain exclamation marks"):(o=t.input.slice(e-1,t.position+1),xw.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),UA.test(s)&&H(t,"tag suffix cannot contain flow indicator characters")}s&&!Sw.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:Tn.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 eN(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&&!Ht(r)&&!vs(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 tN(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)&&!vs(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),Tn.call(t.anchorMap,r)||H(t,'unidentified alias "'+r+'"'),t.result=t.anchorMap[r],at(t,!0,-1),!0}function bs(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=jc===r||ww===r,n&&at(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)||eN(t);)at(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||jc===r)&&(zc===r||bw===r?h=e:h=e+1,y=t.position-t.lineStart,c===1?a&&(Hb(t,y)||XA(t,y,h))||KA(t,h)?u=!0:(i&&YA(t,h)||WA(t,h)||JA(t,h)?u=!0:tN(t)?(u=!0,(t.tag!==null||t.anchor!==null)&&H(t,"alias node should not have any properties")):VA(t,h,zc===r)&&(u=!0,t.tag===null&&(t.tag="?")),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):c===0&&(u=a&&Hb(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(Tn.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 rN(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&&(at(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&&H(t,"directive name must not be less than one character in length");i!==0;){for(;bo(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&&Qd(t),Tn.call(Zb,n)?Zb[n](t,n,o):Mc(t,'unknown document directive "'+n+'"')}if(at(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,at(t,!0,-1)):s&&H(t,"directives end mark is expected"),bs(t,t.lineIndent-1,jc,!1,!0),at(t,!0,-1),t.checkLineBreaks&&qA.test(t.input.slice(e,t.position))&&Mc(t,"non-ASCII line breaks are interpreted as content"),t.documents.push(t.result),t.position===t.lineStart&&qc(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,at(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 Pw(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 GA(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;)rN(r);return r.documents}function nN(t,e,r){e!==null&&typeof e=="object"&&typeof r>"u"&&(r=e,e=null);var n=Pw(t,r);if(typeof e!="function")return n;for(var o=0,s=n.length;o<s;o+=1)e(n[o])}function oN(t,e){var r=Pw(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 kN(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&&Ow.call(c.styleAliases,a)&&(a=c.styleAliases[a]),r[i]=a;return r}function EN(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 PN(t){this.schema=t.schema||Xd,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=kN(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==='"'?Ni:TN,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 Bb(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 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]===`
87
+ `&&(s+=r),s+=i;return s}function Wd(t,e){return`
88
+ `+ut.repeat(" ",t.indent*e)}function RN(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 Dc(t){return t===lN||t===aN}function zi(t){return 32<=t&&t<=126||161<=t&&t<=55295&&t!==8232&&t!==8233||57344<=t&&t<=65533&&t!==tf||65536<=t&&t<=1114111}function Gb(t){return zi(t)&&t!==tf&&t!==cN&&t!==Ai}function Vb(t,e,r){var n=Gb(t),o=n&&!Dc(t);return(r?n:n&&t!==Iw&&t!==Aw&&t!==Nw&&t!==zw&&t!==jw)&&t!==Vd&&!(e===Lc&&!o)||Gb(e)&&!Dc(e)&&t===Vd||e===Lc&&o}function CN(t){return zi(t)&&t!==tf&&!Dc(t)&&t!==gN&&t!==_N&&t!==Lc&&t!==Iw&&t!==Aw&&t!==Nw&&t!==zw&&t!==jw&&t!==Vd&&t!==fN&&t!==hN&&t!==uN&&t!==xN&&t!==yN&&t!==vN&&t!==mN&&t!==pN&&t!==dN&&t!==bN&&t!==wN}function ON(t){return!Dc(t)&&t!==Lc}function Oi(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 Mw(t){var e=/^\n* /;return e.test(t)}function IN(t,e,r,n,o,s,i,a){var c,l=0,u=null,p=!1,f=!1,d=n!==-1,m=-1,h=CN(Oi(t,0))&&ON(Oi(t,t.length-1));if(e||i)for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=Oi(t,c),!zi(l))return ys;h=h&&Vb(l,u,a),u=l}else{for(c=0;c<t.length;l>=65536?c+=2:c++){if(l=Oi(t,c),l===Ai)p=!0,d&&(f=f||c-m-1>n&&t[m+1]!==" ",m=c);else if(!zi(l))return ys;h=h&&Vb(l,u,a),u=l}f=f||d&&c-m-1>n&&t[m+1]!==" "}return!p&&!f?h&&!i&&!o(t)?Lw:s===Ni?ys:Jd:r>9&&Mw(t)?ys:i?s===Ni?ys:Jd:f?qw:Dw}function AN(t,e,r,n,o){t.dump=function(){if(e.length===0)return t.quotingType===Ni?'""':"''";if(!t.noCompatMode&&(SN.indexOf(e)!==-1||$N.test(e)))return t.quotingType===Ni?'"'+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 RN(t,l)}switch(IN(e,a,t.indent,i,c,t.quotingType,t.forceQuotes&&!n,o)){case Lw:return e;case Jd:return"'"+e.replace(/'/g,"''")+"'";case Dw:return"|"+Wb(e,t.indent)+Jb(Bb(e,s));case qw:return">"+Wb(e,t.indent)+Jb(Bb(NN(e,i),s));case ys:return'"'+zN(e)+'"';default:throw new jt("impossible error: invalid scalar style")}}()}function Wb(t,e){var r=Mw(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 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]===`
92
+ `}function Jb(t){return t[t.length-1]===`
93
+ `?t.slice(0,-1):t}function NN(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,Kb(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
- `:"")+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+=`
96
+ `:"")+Kb(c,e),o=s}return n}function Kb(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 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&&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&&Ac(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],yw.test(o)||H(e,"ill-formed tag handle (first argument) of the TAG directive"),$n.call(e.tagMap,o)&&H(e,'there is a previously declared suffix for "'+o+'" tag handle'),vw.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}};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(`
99
+ `+t.slice(i+1):c+=t.slice(o),c.slice(1)}function zN(t){for(var e="",r=0,n,o=0;o<t.length;r>=65536?o+=2:o++)r=Oi(t,o),n=Rt[r],!n&&zi(r)?(e+=t[o],r>=65536&&(e+=t[o+1])):e+=n||EN(r);return e}function jN(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 Yb(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+=Wd(t,e)),t.dump&&Ai===t.dump.charCodeAt(0)?o+="-":o+="- ",o+=t.dump);t.tag=s,t.dump=o||"[]"}function MN(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 LN(t,e,r,n){var o="",s=t.tag,i=Object.keys(r),a,c,l,u,p,f;if(t.sortKeys===!0)i.sort();else if(typeof t.sortKeys=="function")i.sort(t.sortKeys);else if(t.sortKeys)throw new jt("sortKeys must be a boolean or a function");for(a=0,c=i.length;a<c;a+=1)f="",(!n||o!=="")&&(f+=Wd(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&&Ai===t.dump.charCodeAt(0)?f+="?":f+="? "),f+=t.dump,p&&(f+=Wd(t,e)),tn(t,e+1,u,!0,p)&&(t.dump&&Ai===t.dump.charCodeAt(0)?f+=":":f+=": ",f+=t.dump,o+=f));t.tag=s,t.dump=o||"{}"}function Xb(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,Cw.call(a.represent)==="[object Function]")n=a.represent(e,c);else if(Ow.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,Xb(t,r,!1)||Xb(t,r,!0);var a=Cw.call(t.dump),c=n,l;n&&(n=t.flowLevel<0||t.flowLevel>e);var u=a==="[object Object]"||a==="[object Array]",p,f;if(u&&(p=t.duplicates.indexOf(r),f=p!==-1),(t.tag!==null&&t.tag!=="?"||f||t.indent!==2&&e>0)&&(o=!1),f&&t.usedDuplicates[p])t.dump="*ref_"+p;else{if(u&&f&&!t.usedDuplicates[p]&&(t.usedDuplicates[p]=!0),a==="[object Object]")n&&Object.keys(t.dump).length!==0?(LN(t,e,t.dump,o),f&&(t.dump="&ref_"+p+t.dump)):(MN(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?Yb(t,e-1,t.dump,o):Yb(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 String]")t.tag!=="?"&&AN(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 DN(t,e){var r=[],n=[],o,s;for(Kd(t,r,n),o=0,s=n.length;o<s;o+=1)e.duplicates.push(r[n[o]]);e.usedDuplicates=new Array(s)}function Kd(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)Kd(t[o],e,r);else for(n=Object.keys(t),o=0,s=n.length;o<s;o+=1)Kd(t[n[o]],e,r)}function qN(t,e){e=e||{};var r=new PN(e);r.noRefs||DN(t,r);var n=t;return r.replacer&&(n=r.replacer.call({"":n},"",n)),tn(r,0,n,!0,!0)?r.dump+`
100
+ `:""}function rf(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 F1,H1,B1,G1,V1,W1,ut,jt,K1,Y1,X1,vt,tw,rw,nw,ow,sw,iw,aw,cw,mA,yA,lw,uw,pw,dw,fw,mw,hw,Yd,gw,PA,RA,yw,IA,vw,zA,_w,Xd,Tn,zc,bw,ww,jc,Bd,LA,Db,DA,qA,UA,xw,Sw,kw,Ew,_o,Zb,sN,iN,Rw,Cw,Ow,tf,aN,Ai,cN,lN,uN,pN,Vd,dN,fN,mN,hN,Iw,gN,Lc,yN,vN,_N,bN,Aw,Nw,wN,zw,xN,jw,Rt,SN,$N,TN,Ni,Lw,Jd,Dw,qw,ys,UN,ZN,FN,HN,BN,GN,VN,WN,JN,KN,YN,XN,QN,ez,tz,rz,rn,ji=w(()=>{F1=Qb,H1=L1,B1=D1,G1=U1,V1=Z1,W1=q1,ut={isNothing:F1,isObject:H1,toArray:B1,repeat:G1,isNegativeZero:V1,extend:W1};Ii.prototype=Object.create(Error.prototype);Ii.prototype.constructor=Ii;Ii.prototype.toString=function(e){return this.name+": "+ew(this,e)};jt=Ii;K1=J1,Y1=["kind","multi","resolve","construct","instanceOf","predicate","represent","representName","defaultStyle","styleAliases"],X1=["scalar","sequence","mapping"];vt=eA;Gd.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(Gd.prototype);return o.implicit=(this.implicit||[]).concat(r),o.explicit=(this.explicit||[]).concat(n),o.compiledImplicit=Lb(o,"implicit"),o.compiledExplicit=Lb(o,"explicit"),o.compiledTypeMap=tA(o.compiledImplicit,o.compiledExplicit),o};tw=Gd,rw=new vt("tag:yaml.org,2002:str",{kind:"scalar",construct:function(t){return t!==null?t:""}}),nw=new vt("tag:yaml.org,2002:seq",{kind:"sequence",construct:function(t){return t!==null?t:[]}}),ow=new vt("tag:yaml.org,2002:map",{kind:"mapping",construct:function(t){return t!==null?t:{}}}),sw=new tw({explicit:[rw,nw,ow]});iw=new vt("tag:yaml.org,2002:null",{kind:"scalar",resolve:rA,construct:nA,predicate:oA,represent:{canonical:function(){return"~"},lowercase:function(){return"null"},uppercase:function(){return"NULL"},camelcase:function(){return"Null"},empty:function(){return""}},defaultStyle:"lowercase"});aw=new vt("tag:yaml.org,2002:bool",{kind:"scalar",resolve:sA,construct:iA,predicate:aA,represent:{lowercase:function(t){return t?"true":"false"},uppercase:function(t){return t?"TRUE":"FALSE"},camelcase:function(t){return t?"True":"False"}},defaultStyle:"lowercase"});cw=new vt("tag:yaml.org,2002:int",{kind:"scalar",resolve:pA,construct:dA,predicate:fA,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"]}}),mA=new RegExp("^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?\\.(?:inf|Inf|INF)|\\.(?:nan|NaN|NAN))$");yA=/^[-+]?[0-9]+e/;lw=new vt("tag:yaml.org,2002:float",{kind:"scalar",resolve:hA,construct:gA,predicate:_A,represent:vA,defaultStyle:"lowercase"}),uw=sw.extend({implicit:[iw,aw,cw,lw]}),pw=uw,dw=new RegExp("^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$"),fw=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]))?))?$");mw=new vt("tag:yaml.org,2002:timestamp",{kind:"scalar",resolve:bA,construct:wA,instanceOf:Date,represent:xA});hw=new vt("tag:yaml.org,2002:merge",{kind:"scalar",resolve:SA}),Yd=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=
101
+ \r`;gw=new vt("tag:yaml.org,2002:binary",{kind:"scalar",resolve:$A,construct:kA,predicate:TA,represent:EA}),PA=Object.prototype.hasOwnProperty,RA=Object.prototype.toString;yw=new vt("tag:yaml.org,2002:omap",{kind:"sequence",resolve:CA,construct:OA}),IA=Object.prototype.toString;vw=new vt("tag:yaml.org,2002:pairs",{kind:"sequence",resolve:AA,construct:NA}),zA=Object.prototype.hasOwnProperty;_w=new vt("tag:yaml.org,2002:set",{kind:"mapping",resolve:jA,construct:MA}),Xd=pw.extend({implicit:[mw,hw],explicit:[gw,yw,vw,_w]}),Tn=Object.prototype.hasOwnProperty,zc=1,bw=2,ww=3,jc=4,Bd=1,LA=2,Db=3,DA=/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/,qA=/[\x85\u2028\u2029]/,UA=/[,\[\]\{\}]/,xw=/^(?:!|!!|![a-z\-]+!)$/i,Sw=/^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i;kw=new Array(256),Ew=new Array(256);for(_o=0;_o<256;_o++)kw[_o]=Ub(_o)?1:0,Ew[_o]=Ub(_o);Zb={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&&Mc(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],xw.test(o)||H(e,"ill-formed tag handle (first argument) of the TAG directive"),Tn.call(e.tagMap,o)&&H(e,'there is a previously declared suffix for "'+o+'" tag handle'),Sw.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}};sN=nN,iN=oN,Rw={loadAll:sN,load:iN},Cw=Object.prototype.toString,Ow=Object.prototype.hasOwnProperty,tf=65279,aN=9,Ai=10,cN=13,lN=32,uN=33,pN=34,Vd=35,dN=37,fN=38,mN=39,hN=42,Iw=44,gN=45,Lc=58,yN=61,vN=62,_N=63,bN=64,Aw=91,Nw=93,wN=96,zw=123,xN=124,jw=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";SN=["y","Y","yes","Yes","YES","on","On","ON","n","N","no","No","NO","off","Off","OFF"],$N=/^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/;TN=1,Ni=2;Lw=1,Jd=2,Dw=3,qw=4,ys=5;UN=qN,ZN={dump:UN};FN=vt,HN=tw,BN=sw,GN=uw,VN=pw,WN=Xd,JN=Rw.load,KN=Rw.loadAll,YN=ZN.dump,XN=jt,QN={binary:gw,float:lw,map:ow,null:iw,pairs:vw,set:_w,timestamp:mw,bool:aw,int:cw,merge:hw,omap:yw,seq:nw,str:rw},ez=rf("safeLoad","load"),tz=rf("safeLoadAll","loadAll"),rz=rf("safeDump","dump"),rn={Type:FN,Schema:HN,FAILSAFE_SCHEMA:BN,JSON_SCHEMA:GN,CORE_SCHEMA:VN,DEFAULT_SCHEMA:WN,load:JN,loadAll:KN,dump:YN,YAMLException:XN,types:QN,safeLoad:ez,safeLoadAll:tz,safeDump:rz}});var Bw={};G(Bw,{protocol:()=>iz});import{readFileSync as Zw,writeFileSync as nz,existsSync as oz}from"node:fs";import{basename as sz}from"node:path";function Fw(t){if(console.log(P("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(P("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(P("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(P("Resources"));for(let e of t.resources)console.log(` \u2022 ${e}`)}if(t.rules?.length){console.log(P("Rules"));for(let e of t.rules)console.log(` \u2022 ${e}`)}console.log()}async function Hw(t){try{return await vo(t)}catch{}try{return JSON.parse(t)}catch{}try{return rn.load(t)}catch{}return null}async function iz(t=[]){let e=t[0];if(e==="validate"){await cz(t.slice(1));return}if(e==="load"){await lz(t.slice(1));return}if(e==="init"){await uz(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 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=ee(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=ee(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=ee(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=ee(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=ee(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=ee(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=ee(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=ee(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(`
116
+ `);return}if(e==="show"||!e){await az();return}console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl protocol --help` for usage"),process.exit(2)}async function az(){let t=_e();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=ee(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}Fw(n)}catch{console.log(_("Cannot reach server")),process.exit(1)}}async function cz(t){let e=t[0];e||(console.log(_("Usage: wgl protocol validate <file>")),process.exit(2));let r;try{r=Zw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let n=await Hw(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}`)),Fw(o)}async function lz(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=Zw(e,"utf8")}catch{console.log(_(`Cannot read file: ${e}`)),process.exit(1);return}let o=await Hw(n);if(!o){console.log(_("Cannot parse protocol file")),process.exit(1);return}let s=ee(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 uz(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=Uw[n];if(!s){console.log(_(`Unknown template: ${n}`)),console.log(g("dim",` Available: ${Object.keys(Uw).join(", ")}`)),process.exit(2);return}let i={...s};o&&(i.name=o);let c=`${sz(i.name).replace(/[/\\]/g,"_")}.acp.json`;if(oz(c)){console.log(_(`File already exists: ${c}`)),process.exit(1);return}nz(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 Uw,Gw=w(()=>{"use strict";mt();et();$e();Ci();ji();Uw={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 Vw={};G(Vw,{team:()=>pz});async function pz(){let t=_e();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=ee(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(P("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 Ww=w(()=>{"use strict";mt();et();$e()});var Jw={};G(Jw,{claim:()=>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 claim <resource>")),process.exit(1));let n=ee(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 Kw=w(()=>{"use strict";mt();et();$e()});var Yw={};G(Yw,{release:()=>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[0];r||(console.log(_("Usage: wgl release <resource>")),process.exit(1));let n=ee(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 Xw=w(()=>{"use strict";mt();et();$e()});var Qw={};G(Qw,{halt:()=>mz});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=ee(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 ex=w(()=>{"use strict";mt();et();$e()});var nf={};G(nf,{pause:()=>hz,resume:()=>gz});async function hz(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=ee(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 gz(){let t=_e();t||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let e=ee(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 of=w(()=>{"use strict";mt();et();$e()});var rx={};G(rx,{events:()=>yz});function tx(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 yz(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=ee(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(`
124
+ `);return}let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=ee(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(P("Events"));for(let u of l)console.log(tx(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(tx(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 nx=w(()=>{"use strict";mt();et();$e()});var ox={};G(ox,{state:()=>vz});async function vz(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=ee(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(`
133
+ `);return}let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=ee(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(P("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 sx=w(()=>{"use strict";mt();et();$e()});var ix={};G(ix,{msg:()=>bz});function _z(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 bz(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=ee(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(`
140
+ `);return}let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=ee(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(P("Messages"));for(let a of i)console.log(_z(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 ax=w(()=>{"use strict";mt();et();$e()});var cx={};G(cx,{helpCmd:()=>Sz});function xz(t,e){let r=wz[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 Sz(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=ee(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(`
149
+ `);return}let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=ee(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(P("Help Requests"));for(let i of s)console.log(xz(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 wz,lx=w(()=>{"use strict";mt();et();$e();wz={low:"dim",normal:"cyan",high:"red"}});var ux={};G(ux,{namespace:()=>$z});async function $z(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=ee(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(`
156
+ `);return}let r=_e();r||(console.log(_("Not initialized. Run `wgl init` or `wgl join` first.")),process.exit(1));let n=ee(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(P("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 px=w(()=>{"use strict";mt();et();$e()});var dx={};G(dx,{hooksCmd:()=>Pz});import{readFileSync as kz,existsSync as Ez}from"node:fs";import{join as Tz}from"node:path";async function Pz(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{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(G=>typeof G=="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(G=>typeof G=="string"))ie=$.coordination;else throw new Error(`hive "${u}".agents[${x}].coordination must be 'lite', 'full', 'none', or an array of strings`);let Q;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'`);Q=$.type}let te=$.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 G=$.wake_on;de={types:Array.isArray(G.types)?G.types.filter(ot=>typeof ot=="string"):void 0,timeout:typeof G.timeout=="number"?G.timeout:void 0,max_wakes:typeof G.max_wakes=="number"?G.max_wakes:void 0}}let K;if($.workspace!==void 0){if($.workspace!=="memfs"&&$.workspace!=="real")throw new Error(`hive "${u}".agents[${x}].workspace must be 'memfs' or 'real'`);K=$.workspace}return{role:$.role,count:typeof $.count=="number"?$.count:void 0,type:Q,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:te,wake_on:de,workspace:K}})}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(`
163
+ `);return}switch(e){case"install":{let n=_e()?.hookTimeout||10;try{gs(n),console.log(A("Hooks installed"))}catch(o){console.log(_(`Failed to install hooks: ${o.message}`)),process.exit(1)}break}case"uninstall":{try{Cc(),console.log(A("Hooks uninstalled"))}catch(r){console.log(_(`Failed to uninstall hooks: ${r.message}`)),process.exit(1)}break}case"list":{let r=Tz(process.cwd(),".claude","settings.local.json");if(!Ez(r)){console.log(` ${g("dim","No hooks installed (no settings.local.json)")}`);return}let n;try{n=JSON.parse(kz(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(P("Installed Hooks"));for(let[o,s]of Object.entries(n.hooks))for(let i of s){let c=Rc(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 fx=w(()=>{"use strict";mt();Ei();$e()});import{readFileSync as Rz,existsSync as mx}from"node:fs";import{join as Cz,resolve as Oz}from"node:path";function gx(t){if(typeof t=="string")return{conditions:[{event:t,count:1}],timeout:hx};let e=typeof t.timeout=="number"?t.timeout:hx;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 yx(t){if(t){let e=Oz(t);return mx(e)?e:null}for(let e of Iz){let r=Cz(process.cwd(),e);if(mx(r))return r}return null}async function vx(t){let e=Rz(t,"utf8"),r=t.endsWith(".json")?JSON.parse(e):Az(e);return Nz(r)}function Az(t){return rn.load(t)}function Nz(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(V=>typeof V=="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(V=>typeof V=="string"))ie=$.coordination;else throw new Error(`hive "${u}".agents[${x}].coordination must be 'lite', 'full', 'none', or an array of strings`);let Q;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'`);Q=$.type}let te=$.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 V=$.wake_on;de={types:Array.isArray(V.types)?V.types.filter(ot=>typeof ot=="string"):void 0,timeout:typeof V.timeout=="number"?V.timeout:void 0,max_wakes:typeof V.max_wakes=="number"?V.max_wakes:void 0}}let K;if($.workspace!==void 0){if($.workspace!=="memfs"&&$.workspace!=="real")throw new Error(`hive "${u}".agents[${x}].workspace must be 'memfs' or 'real'`);K=$.workspace}return{role:$.role,count:typeof $.count=="number"?$.count:void 0,type:Q,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:te,wake_on:de,workspace:K}})}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 hx,Iz,_x=w(()=>{"use strict";ji();hx=0;Iz=["brood.yaml","brood.yml","brood.json"]});import{createServer as zz}from"node:net";var Uc,bx=w(()=>{"use strict";Uc=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=zz(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 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)+`
165
+ `;s.socket.write(i)}}}});import{createWriteStream as jz}from"node:fs";import{readdirSync as Mz,readFileSync as Lz,existsSync as wx}from"node:fs";import{join as Dz}from"node:path";function xx(t){if(!wx(t))return[];let e=Lz(t,"utf8").split(`
166
+ `).filter(Boolean),r=[];for(let n of e)try{r.push(JSON.parse(n))}catch{}return r}function sf(t){let e=$n(t);return wx(e)?Mz(e).filter(r=>r.endsWith(".jsonl")).sort().reverse().map(r=>Dz(e,r)):[]}function Sx(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 qz,Zc,af=w(()=>{"use strict";kn();qz=/\x1b\[[0-9;]*m/g,Zc=class{stream;path;constructor(e){Td(e),this.path=Ed(e),this.stream=jz(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(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(`
168
+ `);return}}catch{}this.write({ts:new Date().toISOString(),level:n,source:r,msg:o.replace(qz,"")})}}close(){this.stream.end()}}});var Cx={};G(Cx,{up:()=>Wz});import{spawn as Uz}from"node:child_process";import{mkdirSync as lf,writeFileSync as kx,existsSync as Zz,unlinkSync as $x,readFileSync as Ex,readdirSync as Fz}from"node:fs";import{join as qr,dirname as ws,resolve as Mi}from"node:path";import{tmpdir as Tx,homedir as Hz}from"node:os";import{randomBytes as Px}from"node:crypto";import{createRequire as Bz}from"node:module";function Vz(t,e){let r=[qr(e,"__placeholder.js"),import.meta.url];for(let n of r)try{return Bz(n).resolve(t)}catch{}return null}function Rx(){return qr(process.cwd(),".honeyb")}function cf(){return qr(Rx(),"brood.state.json")}async function Wz(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,13 +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}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(F=>!F.type||F.type==="worker"||F.type==="drone")),ie=process.cwd(),Q=process.argv[1],te=null;if(O&&(te=Nz(Az,ie),!te)){console.log(_("Hive not installed (required for worker/drone agents)")),console.log(`
196
+ `);return}Zz(cf())&&(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=yx(o??r),b;if(v)try{b=await vx(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(F=>!F.type||F.type==="worker"||F.type==="drone")),ie=process.cwd(),Q=process.argv[1],te=null;if(O&&(te=Vz(Gz,ie),!te)){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 M=qr(Cz(),".secrets"),F=Oz(M).filter(zt=>zt.endsWith(".env"));for(let zt of F){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 K={...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 G=Sx(4).toString("hex"),ot=qr(xx(),`honeybee-brood-${G}`);of(ot,{recursive:!0});let Et=qr(ot,"broker.sock"),ne=new Mc({onHiveConnect:M=>console.log(A(`Hive "${M}" connected to broker`)),onHiveDisconnect:M=>console.log(ar(`Hive "${M}" disconnected`))});await ne.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,F]of Object.entries(b.hives)){let zt=F.port??oe++,nt=F.worktree?Ni(vs(v),F.worktree):vs(v),Ee=Mz(F,v,M),lt=["--http",`--port=${zt}`,"--log-format=json"];Ee&&lt.push(`--protocol=${Ee}`);let jr=y??F.dances??b.dances;if(jr){let Pt=Ni(vs(v),jr);lt.push(`--dances=${Pt}`)}let Qt=F.agents?.length?F.agents:jz(Ee);if(Qt.length){let Pt=ve++,Y=F.worktree?Ni(vs(v),F.worktree):Ni(vs(v)),ae={provider:b.provider??"ollama/qwen3:8b",stagger:b.stagger??2,noAcp:a,propolisPort:Pt,worktree:Y,hiveEntry:te??"",...Ee?{protocolPath:Ee}:{},agents:Qt.map(he=>({role:he.role,count:he.count,type:he.type,tools:he.tools,coordination:he.coordination,modelHint:he.model_hint??null,prompt:he.prompt??null,workspace:he.workspace,startOn:he.startOn?px(he.startOn):null,wakeOn:he.wake_on?{types:he.wake_on.types??null,timeout:he.wake_on.timeout??0,maxWakes:he.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(he=>!he.type||he.type==="worker").reduce((he,ft)=>he+(ft.count??1),0),me=Qt.filter(he=>he.type==="drone").reduce((he,ft)=>he+(ft.count??1),0),Ge=Qt.filter(he=>he.type==="claude").reduce((he,ft)=>he+(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={...K,HONEYCOMB_BROKER_SOCKET:Et,HONEYCOMB_HIVE_NAME:M};F.honeycomb?.publishes?.length&&(Sr.HONEYCOMB_PUBLISHES=F.honeycomb.publishes.join(",")),F.honeycomb?.subscribes?.length&&(Sr.HONEYCOMB_SUBSCRIBES=F.honeycomb.subscribes.join(","));let Tt=Pz(process.execPath,[Q,"incubator",...lt],{env:Sr,cwd:nt,stdio:["ignore","pipe","pipe"]});Tt.stdout?.on("data",Pt=>{for(let Y of Pt.toString().split(`
201
- `))Y.trim()&&Qe?.writeLine(Y,M,"info")}),Tt.stderr?.on("data",Pt=>{let Y=Pt.toString().trim();Y&&(console.log(g("dim",`[${M}] ${Y}`)),Qe?.writeLine(Y,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,F]of le)F.kill("SIGTERM"),console.log(g("dim",` Stopped ${M}`));await ne.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(`
199
+ `),process.exit(1);return}let de={};try{let M=qr(Hz(),".secrets"),F=Fz(M).filter(zt=>zt.endsWith(".env"));for(let zt of F){let nt=Ex(qr(M,zt),"utf8");for(let Te of nt.split(`
200
+ `)){let lt=Te.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 K={...process.env,...de,...b.env};console.log(P(`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 V=Px(4).toString("hex"),ot=qr(Tx(),`honeybee-brood-${V}`);lf(ot,{recursive:!0});let Et=qr(ot,"broker.sock"),ne=new Uc({onHiveConnect:M=>console.log(A(`Hive "${M}" connected to broker`)),onHiveDisconnect:M=>console.log(ar(`Hive "${M}" disconnected`))});await ne.listen(Et),console.log(A("IPC broker started"));let le=new Map,Nt={},oe=i,ve=i+100,Qe=null;try{Qe=new Zc,console.log(g("dim",` Logging to ${Qe.path}`))}catch{}for(let[M,F]of Object.entries(b.hives)){let zt=F.port??oe++,nt=F.worktree?Mi(ws(v),F.worktree):ws(v),Te=Kz(F,v,M),lt=["--http",`--port=${zt}`,"--log-format=json"];Te&&lt.push(`--protocol=${Te}`);let jr=y??F.dances??b.dances;if(jr){let Pt=Mi(ws(v),jr);lt.push(`--dances=${Pt}`)}let Qt=F.agents?.length?F.agents:Jz(Te);if(Qt.length){let Pt=ve++,Y=F.worktree?Mi(ws(v),F.worktree):Mi(ws(v)),ae={provider:b.provider??"ollama/qwen3:8b",stagger:b.stagger??2,noAcp:a,propolisPort:Pt,worktree:Y,hiveEntry:te??"",...Te?{protocolPath:Te}:{},agents:Qt.map(he=>({role:he.role,count:he.count,type:he.type,tools:he.tools,coordination:he.coordination,modelHint:he.model_hint??null,prompt:he.prompt??null,workspace:he.workspace,startOn:he.startOn?gx(he.startOn):null,wakeOn:he.wake_on?{types:he.wake_on.types??null,timeout:he.wake_on.timeout??0,maxWakes:he.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(he=>!he.type||he.type==="worker").reduce((he,ft)=>he+(ft.count??1),0),me=Qt.filter(he=>he.type==="drone").reduce((he,ft)=>he+(ft.count??1),0),Ge=Qt.filter(he=>he.type==="claude").reduce((he,ft)=>he+(ft.count??1),0),Oe=[];Le>0&&Oe.push(`${Le} worker${Le!==1?"s":""}`),me>0&&Oe.push(`${me} drone${me!==1?"s":""}`),Ge>0&&Oe.push(`${Ge} claude${Ge!==1?"s":""}`),console.log(S(`${M}/agents`,`${Oe.join(" + ")} (delegated to incubator)`))}let Sr={...K,HONEYCOMB_BROKER_SOCKET:Et,HONEYCOMB_HIVE_NAME:M};F.honeycomb?.publishes?.length&&(Sr.HONEYCOMB_PUBLISHES=F.honeycomb.publishes.join(",")),F.honeycomb?.subscribes?.length&&(Sr.HONEYCOMB_SUBSCRIBES=F.honeycomb.subscribes.join(","));let Tt=Uz(process.execPath,[Q,"incubator",...lt],{env:Sr,cwd:nt,stdio:["ignore","pipe","pipe"]});Tt.stdout?.on("data",Pt=>{for(let Y of Pt.toString().split(`
201
+ `))Y.trim()&&Qe?.writeLine(Y,M,"info")}),Tt.stderr?.on("data",Pt=>{let Y=Pt.toString().trim();Y&&(console.log(g("dim",`[${M}] ${Y}`)),Qe?.writeLine(Y,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})`)))}lf(Rx(),{recursive:!0});let en={name:b.name,socketPath:Et,hives:Nt,startedAt:new Date().toISOString()};kx(cf(),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,F]of le)F.kill("SIGTERM"),console.log(g("dim",` Stopped ${M}`));await ne.close(),Qe?.close();try{$x(Et)}catch{}try{$x(cf())}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=Ex(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 Kz(t,e,r){let n=t.acp??t.protocol;if(!n)return;if(typeof n=="string")return n.startsWith("http://")||n.startsWith("https://")?n:Mi(ws(e),n);let o=qr(Tx(),`honeybee-protocol-${Px(4).toString("hex")}`);lf(o,{recursive:!0});let s=qr(o,`${r}.acp.json`);return kx(s,JSON.stringify(n,null,2)),s}var Gz,Ox=w(()=>{"use strict";$e();_x();bx();af();ji();Gz="@honeybee-ai/hive"});var Nx={};G(Nx,{down:()=>ej});import{readFileSync as Yz,existsSync as uf,unlinkSync as Ix,rmSync as Xz}from"node:fs";import{join as Ax}from"node:path";function Qz(){let t=Ax(process.cwd(),".honeyb","brood.state.json");if(uf(t))return t;let e=Ax(process.cwd(),".honeybee","brood.state.json");return uf(e)?e:t}async function ej(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
203
203
  ${g("bold","wgl down")} \u2014 stop a running brood
204
204
 
205
205
  ${g("cyan","USAGE:")}
@@ -212,7 +212,7 @@ ${g("cyan","DESCRIPTION:")}
212
212
 
213
213
  ${g("cyan","EXAMPLES:")}
214
214
  wgl down
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
+ `);return}let e=Qz();if(!uf(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(Yz(e,"utf8"))}catch{console.log(_("Corrupt state file")),process.exit(1);return}console.log(P(`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{Ix(r.socketPath)}catch{}let{dirname:s}=await import("node:path");try{Xz(s(r.socketPath),{recursive:!0,force:!0})}catch{}}try{Ix(e)}catch{}let o=Object.keys(r.hives).length;console.log(),console.log(A(`Brood stopped (${o} hive${o!==1?"s":""} terminated)`))}var zx=w(()=>{"use strict";$e()});var jx={};G(jx,{logs:()=>ij});import{existsSync as tj,readdirSync as rj,unlinkSync as nj,statSync as oj}from"node:fs";import{join as sj}from"node:path";async function ij(t){let e=t[0];if(e==="--help"||e==="-h"){console.log(`
216
216
  ${g("bold","wgl logs")} \u2014 view brood run logs
217
217
 
218
218
  ${g("cyan","USAGE:")}
@@ -226,7 +226,7 @@ ${g("cyan","USAGE:")}
226
226
  wgl logs --json Raw JSONL output (default for pipe)
227
227
  wgl logs --clean Delete old log files
228
228
  wgl logs --list List available log files
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
+ `);return}let r=aj(t);if(r.clean){await lj();return}if(r.list){await uj();return}let n=sf();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=xx(s),a=i;if(r.level){let l=cj(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(P(`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?Sx(l):JSON.stringify(l))}function aj(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 cj(t){let e=["debug","info","warn","error"],r=e.indexOf(t);return r<0?new Set(e):new Set(e.slice(r))}async function lj(){let t=$n();if(!tj(t)){console.log("No log directory found");return}let e=rj(t).filter(r=>r.endsWith(".jsonl"));for(let r of e)nj(sj(t,r));console.log(`Deleted ${e.length} log file(s)`)}async function uj(){let t=sf();if(t.length===0){console.log("No log files");return}console.log(P("Log Files"));for(let e=0;e<t.length;e++){let r=t[e].split("/").pop(),n=oj(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 Mx=w(()=>{"use strict";$e();af();kn()});var Dx={};G(Dx,{inspect:()=>pj});async function pj(t){let e=t[0]||"overview";if(e==="--help"||e==="-h"){console.log(`
230
230
  ${g("bold","wgl inspect")} \u2014 runtime introspection
231
231
 
232
232
  ${g("cyan","USAGE:")}
@@ -242,9 +242,9 @@ ${g("cyan","USAGE:")}
242
242
 
243
243
  ${g("cyan","OPTIONS:")}
244
244
  --server=URL Override incubator URL (default: from .wglrc or localhost:3100)
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
+ `);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 dj(o);case"agents":return fj(o);case"agent":return mj(o,t[1]);case"events":return hj(o,t);case"protocol":return gj(o);case"tokens":return yj(o,n);case"health":return vj(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 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 dj(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(P("Incubator Overview")),console.log(S("Server",t)),console.log(S("Uptime",Fc(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(P("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 fj(t){try{let r=(await rr(t,"/api/runs")).runs||[];if(r.length===0){console.log("No agents registered");return}console.log(P("Agents")),console.log();let n=Lx("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(Lx(o.agentId,o.role,g(s,o.status),String(o.iterations||0),(o.usage?.totalTokens||0).toLocaleString(),o.elapsed?Fc(o.elapsed):"-"))}}catch(e){console.log(_(`Cannot connect to ${t}`)),console.log(g("dim",` ${e.message}`)),process.exit(1)}}async function mj(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(P(`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",Fc(n.elapsed))),console.log(S("Iterations",String(n.iterations||0))),n.usage&&(console.log(),console.log(P("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(P("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 hj(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(P(`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 gj(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(P("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(P("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(P("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(P("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 yj(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(P("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 vj(t){try{let e=await rr(t,"/api/health");console.log(P("Server Health")),console.log(S("Server",t)),console.log(S("Uptime",Fc(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([rr(t,"/api/governance/proposals").catch(()=>({proposals:[]})),rr(t,"/api/control/status").catch(()=>({}))]);console.log(P("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(P("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 Fc(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 Lx(...t){let e=[20,14,12,6,12,10];return t.map((r,n)=>r.padEnd(e[n]||10)).join(" ")}var qx=w(()=>{"use strict";$e();kn()});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(Hc,t),Hc}var bj,wj,nn,Hc,xs=w(()=>{bj=Object.freeze({status:"aborted"});wj=Symbol("zod_brand"),nn=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Hc={}});var be={};G(be,{BIGINT_FORMAT_RANGES:()=>Zx,Class:()=>df,NUMBER_FORMAT_RANGES:()=>_f,aborted:()=>xo,allowsEval:()=>gf,assert:()=>Ej,assertEqual:()=>xj,assertIs:()=>$j,assertNever:()=>kj,assertNotEqual:()=>Sj,assignProp:()=>hf,cached:()=>qi,captureStackTrace:()=>Gc,cleanEnum:()=>Dj,cleanRegex:()=>Zi,clone:()=>or,createTransparentProxy:()=>Ij,defineLazy:()=>De,esc:()=>wo,escapeRegex:()=>Pn,extend:()=>zj,finalizeIssue:()=>Er,floatSafeRemainder:()=>mf,getElementAtPath:()=>Tj,getEnumValues:()=>Di,getLengthableOrigin:()=>Fi,getParsedType:()=>Oj,getSizableOrigin:()=>Fx,isObject:()=>Ss,isPlainObject:()=>$s,issue:()=>bf,joinValues:()=>Bc,jsonStringifyReplacer:()=>ff,merge:()=>jj,normalizeParams:()=>W,nullish:()=>Ui,numKeys:()=>Cj,omit:()=>Nj,optionalKeys:()=>vf,partial:()=>Mj,pick:()=>Aj,prefixIssues:()=>Ur,primitiveTypes:()=>Ux,promiseAllObject:()=>Pj,propertyKeyTypes:()=>yf,randomString:()=>Rj,required:()=>Lj,stringifyPrimitive:()=>Vc,unwrapMessage:()=>Li});function xj(t){return t}function Sj(t){return t}function $j(t){}function kj(t){throw new Error}function Ej(t){}function Di(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 Bc(t,e="|"){return t.map(r=>Vc(r)).join(e)}function ff(t,e){return typeof e=="bigint"?e.toString():e}function qi(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Ui(t){return t==null}function Zi(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function mf(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 hf(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Tj(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function Pj(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 Rj(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function wo(t){return JSON.stringify(t)}function Ss(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function $s(t){if(Ss(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ss(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function Cj(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Pn(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 Ij(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 Vc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function vf(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function Aj(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 Nj(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 zj(t,e){if(!$s(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 hf(this,"shape",n),n},checks:[]};return or(t,r)}function jj(t,e){return or(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return hf(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function Mj(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 Lj(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 xo(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Ur(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Li(t){return typeof t=="string"?t:t?.message}function Er(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Li(t.inst?._zod.def?.error?.(t))??Li(e?.error?.(t))??Li(r.customError?.(t))??Li(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Fx(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Fi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function bf(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function Dj(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Gc,gf,Oj,yf,Ux,_f,Zx,df,Zr=w(()=>{Gc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};gf=qi(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});Oj=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}`)}},yf=new Set(["string","number","symbol"]),Ux=new Set(["string","number","bigint","boolean","symbol","undefined"]);_f={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]},Zx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};df=class{constructor(...e){}}});function wf(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 xf(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 Hx,Wc,Hi,Sf=w(()=>{xs();Zr();Hx=(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,ff,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Wc=E("$ZodError",Hx),Hi=E("$ZodError",Hx,{Parent:Error})});var $f,kf,Ef,Tf,Pf,So,Rf,$o,Cf=w(()=>{xs();Sf();Zr();$f=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 Gc(a,o?.callee),a}return i.value},kf=$f(Hi),Ef=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 Gc(a,o?.callee),a}return i.value},Tf=Ef(Hi),Pf=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??Wc)(s.issues.map(i=>Er(i,o,nr())))}:{success:!0,data:s.value}},So=Pf(Hi),Rf=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=Rf(Hi)});function e0(){return new RegExp(Uj,"u")}function u0(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 p0(t){return new RegExp(`^${u0(t)}$`)}function d0(t){let e=u0({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(`^${c0}T(?:${n})$`)}var Bx,Gx,Vx,Wx,Jx,Kx,Yx,Xx,Of,Qx,Uj,t0,r0,n0,o0,s0,If,i0,a0,c0,l0,f0,m0,h0,g0,y0,v0,_0,Kc=w(()=>{Bx=/^[cC][^\s-]{8,}$/,Gx=/^[0-9a-z]+$/,Vx=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Wx=/^[0-9a-vA-V]{20}$/,Jx=/^[A-Za-z0-9]{27}$/,Kx=/^[a-zA-Z0-9_-]{21}$/,Yx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Xx=/^([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})$/,Of=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)$/,Qx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Uj="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";t0=/^(?:(?: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])$/,r0=/^(([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})$/,n0=/^((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])$/,o0=/^(([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])$/,s0=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,If=/^[A-Za-z0-9_-]*$/,i0=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,a0=/^\+(?:[0-9]){6,14}[0-9]$/,c0="(?:(?:\\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])))",l0=new RegExp(`^${c0}$`);f0=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},m0=/^\d+$/,h0=/^-?\d+(?:\.\d+)?/i,g0=/true|false/i,y0=/null/i,v0=/^[^A-Z]*$/,_0=/^[^a-z]*$/});var _t,b0,Af,Nf,w0,x0,S0,$0,k0,Bi,E0,T0,P0,R0,C0,O0,I0,Yc=w(()=>{xs();Kc();Zr();_t=E("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),b0={number:"number",bigint:"bigint",object:"date"},Af=E("$ZodCheckLessThan",(t,e)=>{_t.init(t,e);let r=b0[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})}}),Nf=E("$ZodCheckGreaterThan",(t,e)=>{_t.init(t,e);let r=b0[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})}}),w0=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):mf(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})}}),x0=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]=_f[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=m0)}),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})}}),S0=E("$ZodCheckMaxLength",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ui(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=Fi(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!Ui(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=Fi(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),k0=E("$ZodCheckLengthEquals",(t,e)=>{var r;_t.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Ui(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=Fi(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})}}),Bi=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=()=>{})}),E0=E("$ZodCheckRegex",(t,e)=>{Bi.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})}}),T0=E("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=v0),Bi.init(t,e)}),P0=E("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=_0),Bi.init(t,e)}),R0=E("$ZodCheckIncludes",(t,e)=>{_t.init(t,e);let r=Pn(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})}}),C0=E("$ZodCheckStartsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`^${Pn(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})}}),O0=E("$ZodCheckEndsWith",(t,e)=>{_t.init(t,e);let r=new RegExp(`.*${Pn(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})}}),I0=E("$ZodCheckOverwrite",(t,e)=>{_t.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Xc,zf=w(()=>{Xc=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(`
246
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(`
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
+ `))}}});var N0,jf=w(()=>{N0={major:4,minor:0,patch:0}});function W0(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function Zj(t){if(!If.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return W0(r)}function Fj(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function z0(t,e,r){t.issues.length&&e.issues.push(...Ur(r,t.issues)),e.value[r]=t.value}function Qc(t,e,r){t.issues.length&&e.issues.push(...Ur(r,t.issues)),e.value[r]=t.value}function j0(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(...Ur(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function M0(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 Mf(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($s(t)&&$s(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=Mf(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=Mf(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 L0(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),xo(t))return t;let n=Mf(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 D0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function q0(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 U0(t,e,r){return xo(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Z0(t){return t.value=Object.freeze(t.value),t}function F0(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(bf(o))}}var Ae,Gi,qe,Lf,Df,qf,Uf,Zf,Ff,Hf,Bf,Gf,Vf,Wf,H0,B0,G0,V0,Jf,Kf,Yf,Xf,Qf,em,tm,rm,el,nm,om,sm,im,am,cm,tl,rl,lm,um,pm,dm,fm,mm,hm,gm,ym,vm,_m,bm,wm,xm,Sm,J0=w(()=>{Yc();xs();zf();Cf();Kc();Zr();jf();Zr();Ae=E("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=N0;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=xo(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=xo(s,p)))});else{if(s.issues.length===p)continue;c||(c=xo(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=So(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}}),Gi=E("$ZodString",(t,e)=>{Ae.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??f0(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)=>{Bi.init(t,e),Gi.init(t,e)}),Lf=E("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Xx),qe.init(t,e)}),Df=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=Of(n))}else e.pattern??(e.pattern=Of());qe.init(t,e)}),qf=E("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Qx),qe.init(t,e)}),Uf=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:i0.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})}}}),Zf=E("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=e0()),qe.init(t,e)}),Ff=E("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Kx),qe.init(t,e)}),Hf=E("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Bx),qe.init(t,e)}),Bf=E("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Gx),qe.init(t,e)}),Gf=E("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Vx),qe.init(t,e)}),Vf=E("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Wx),qe.init(t,e)}),Wf=E("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Jx),qe.init(t,e)}),H0=E("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=d0(e)),qe.init(t,e)}),B0=E("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=l0),qe.init(t,e)}),G0=E("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=p0(e)),qe.init(t,e)}),V0=E("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Yx),qe.init(t,e)}),Jf=E("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=t0),qe.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Kf=E("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=r0),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})}}}),Yf=E("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=n0),qe.init(t,e)}),Xf=E("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=o0),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})}}});Qf=E("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=s0),qe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{W0(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});em=E("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=If),qe.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{Zj(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),tm=E("$ZodE164",(t,e)=>{e.pattern??(e.pattern=a0),qe.init(t,e)});rm=E("$ZodJWT",(t,e)=>{qe.init(t,e),t._zod.check=r=>{Fj(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),el=E("$ZodNumber",(t,e)=>{Ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??h0,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}}),nm=E("$ZodNumber",(t,e)=>{x0.init(t,e),el.init(t,e)}),om=E("$ZodBoolean",(t,e)=>{Ae.init(t,e),t._zod.pattern=g0,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}}),sm=E("$ZodNull",(t,e)=>{Ae.init(t,e),t._zod.pattern=y0,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}}),im=E("$ZodUnknown",(t,e)=>{Ae.init(t,e),t._zod.parse=r=>r}),am=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)});cm=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=>z0(l,r,i))):z0(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});tl=E("$ZodObject",(t,e)=>{Ae.init(t,e);let r=qi(()=>{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=vf(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 Xc(["shape","payload","ctx"]),d=r.value,m=b=>{let x=wo(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 $=wo(b);f.write(`
248
248
  if (${x}.issues.length) {
249
249
  if (input[${$}] === undefined) {
250
250
  if (${$} in input) {
@@ -266,12 +266,12 @@ ${g("cyan","OPTIONS:")}
266
266
  `)}else{let x=h[b];f.write(`const ${x} = ${m(b)};`),f.write(`
267
267
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
268
268
  ...iss,
269
- path: iss.path ? [${go(b)}, ...iss.path] : [${go(b)}]
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),Q=O._zod.optin==="optional"&&O._zod.optout==="optional";ie instanceof Promise?m.push(ie.then(te=>Q?C0(te,p,$,d):Jc(te,p,$))):Q?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>
269
+ path: iss.path ? [${wo(b)}, ...iss.path] : [${wo(b)}]
270
+ })));`),f.write(`newResult[${wo(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=Ss,i=!Hc.jitless,c=i&&gf.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),Q=O._zod.optin==="optional"&&O._zod.optout==="optional";ie instanceof Promise?m.push(ie.then(te=>Q?j0(te,p,$,d):Qc(te,p,$))):Q?j0(ie,p,$,d):Qc(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=>Qc(O,p,x))):Qc($,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}});rl=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=>Zi(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=>M0(i,r,t,n)):M0(s,r,t,n)}}),lm=E("$ZodDiscriminatedUnion",(t,e)=>{rl.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=qi(()=>{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(!Ss(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)}}),um=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])=>L0(r,c,l)):L0(r,s,i)}});pm=E("$ZodRecord",(t,e)=>{Ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!$s(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(...Ur(c,u.issues)),r.value[c]=u.value})):(l.issues.length&&r.issues.push(...Ur(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(...Ur(i,l.issues)),r.value[a.value]=l.value})):(c.issues.length&&r.issues.push(...Ur(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),dm=E("$ZodEnum",(t,e)=>{Ae.init(t,e);let r=Di(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>yf.has(typeof n)).map(n=>typeof n=="string"?Pn(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}}),fm=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"?Pn(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}}),mm=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}}),hm=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(`^(${Zi(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)}),gm=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(`^(${Zi(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)}),ym=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=>D0(s,e)):D0(o,e)}});vm=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))}),_m=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=>q0(s,t)):q0(o,t)}});bm=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)}}),wm=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=>U0(s,e,n)):U0(o,e,n)}});xm=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(Z0):Z0(o)}});Sm=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=>F0(s,r,n,t));F0(o,r,n,t)}})});function K0(){return{localeError:Bj()}}var Hj,Bj,Y0=w(()=>{Zr();Hj=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},Bj=()=>{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 ${Hj(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Vc(n.values[0])}`:`Invalid option: expected one of ${Bc(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":""}: ${Bc(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 nl=w(()=>{});function X0(){return new Vi}var Gj,Vj,Vi,Rn,km=w(()=>{Gj=Symbol("ZodOutput"),Vj=Symbol("ZodInput"),Vi=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)}};Rn=X0()});function Em(t,e){return new t({type:"string",...W(e)})}function Tm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...W(e)})}function ol(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...W(e)})}function Pm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...W(e)})}function Rm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...W(e)})}function Cm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...W(e)})}function Om(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...W(e)})}function Im(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...W(e)})}function Am(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...W(e)})}function Nm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...W(e)})}function zm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...W(e)})}function jm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...W(e)})}function Mm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...W(e)})}function Lm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...W(e)})}function Dm(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...W(e)})}function qm(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...W(e)})}function Um(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...W(e)})}function Zm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...W(e)})}function Fm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...W(e)})}function Hm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...W(e)})}function Bm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...W(e)})}function Gm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...W(e)})}function Vm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...W(e)})}function Q0(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...W(e)})}function eS(t,e){return new t({type:"string",format:"date",check:"string_format",...W(e)})}function tS(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...W(e)})}function rS(t,e){return new t({type:"string",format:"duration",check:"string_format",...W(e)})}function Wm(t,e){return new t({type:"number",checks:[],...W(e)})}function Jm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...W(e)})}function Km(t,e){return new t({type:"boolean",...W(e)})}function Ym(t,e){return new t({type:"null",...W(e)})}function Xm(t){return new t({type:"unknown"})}function Qm(t,e){return new t({type:"never",...W(e)})}function sl(t,e){return new Af({check:"less_than",...W(e),value:t,inclusive:!1})}function Wi(t,e){return new Af({check:"less_than",...W(e),value:t,inclusive:!0})}function il(t,e){return new Nf({check:"greater_than",...W(e),value:t,inclusive:!1})}function Ji(t,e){return new Nf({check:"greater_than",...W(e),value:t,inclusive:!0})}function al(t,e){return new w0({check:"multiple_of",...W(e),value:t})}function cl(t,e){return new S0({check:"max_length",...W(e),maximum:t})}function ks(t,e){return new $0({check:"min_length",...W(e),minimum:t})}function ll(t,e){return new k0({check:"length_equals",...W(e),length:t})}function eh(t,e){return new E0({check:"string_format",format:"regex",...W(e),pattern:t})}function th(t){return new T0({check:"string_format",format:"lowercase",...W(t)})}function rh(t){return new P0({check:"string_format",format:"uppercase",...W(t)})}function nh(t,e){return new R0({check:"string_format",format:"includes",...W(e),includes:t})}function oh(t,e){return new C0({check:"string_format",format:"starts_with",...W(e),prefix:t})}function sh(t,e){return new O0({check:"string_format",format:"ends_with",...W(e),suffix:t})}function ko(t){return new I0({check:"overwrite",tx:t})}function ih(t){return ko(e=>e.normalize(t))}function ah(){return ko(t=>t.trim())}function ch(){return ko(t=>t.toLowerCase())}function lh(){return ko(t=>t.toUpperCase())}function nS(t,e,r){return new t({type:"array",element:e,...W(r)})}function uh(t,e,r){let n=W(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function ph(t,e,r){return new t({type:"custom",check:"custom",fn:e,...W(r)})}var oS=w(()=>{Yc();Zr()});var sS=w(()=>{});function dh(t,e){if(t instanceof Vi){let n=new ul(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 ul(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 ul,iS=w(()=>{km();Zr();ul=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Rn,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=Di(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>
271
271
 
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,B,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"})(B||(B={}));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===B.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(B.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}
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 aS=w(()=>{});var Mt=w(()=>{xs();Cf();Sf();J0();Yc();jf();Zr();Kc();nl();km();zf();sS();oS();iS();aS()});var fh=w(()=>{Mt()});var Ki={};G(Ki,{ZodISODate:()=>lS,ZodISODateTime:()=>cS,ZodISODuration:()=>pS,ZodISOTime:()=>uS,date:()=>hh,datetime:()=>mh,duration:()=>yh,time:()=>gh});function mh(t){return Q0(cS,t)}function hh(t){return eS(lS,t)}function gh(t){return tS(uS,t)}function yh(t){return rS(pS,t)}var cS,lS,uS,pS,vh=w(()=>{Mt();_h();cS=E("ZodISODateTime",(t,e)=>{H0.init(t,e),Ve.init(t,e)});lS=E("ZodISODate",(t,e)=>{B0.init(t,e),Ve.init(t,e)});uS=E("ZodISOTime",(t,e)=>{G0.init(t,e),Ve.init(t,e)});pS=E("ZodISODuration",(t,e)=>{V0.init(t,e),Ve.init(t,e)})});var dS,O5,Yi,bh=w(()=>{Mt();Mt();dS=(t,e)=>{Wc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>xf(t,r)},flatten:{value:r=>wf(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},O5=E("ZodError",dS),Yi=E("ZodError",dS,{Parent:Error})});var fS,mS,hS,gS,wh=w(()=>{Mt();bh();fS=$f(Yi),mS=Ef(Yi),hS=Pf(Yi),gS=Rf(Yi)});function k(t){return Em(NM,t)}function Ie(t){return Wm(wS,t)}function vS(t){return Jm(XM,t)}function ht(t){return Km(QM,t)}function $h(t){return Ym(eL,t)}function We(){return Xm(tL)}function nL(t){return Qm(rL,t)}function we(t,e){return nS(oL,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 xS(r)}function Lt(t,e){return new xS({type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},catchall:We(),...be.normalizeParams(e)})}function Ue(t,e){return new SS({type:"union",options:t,...be.normalizeParams(e)})}function kh(t,e,r){return new sL({type:"union",options:e,discriminator:t,...be.normalizeParams(r)})}function dl(t,e){return new iL({type:"intersection",left:t,right:e})}function Je(t,e,r){return new aL({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 xh({type:"enum",entries:r,...be.normalizeParams(e)})}function U(t,e){return new cL({type:"literal",values:Array.isArray(t)?t:[t],...be.normalizeParams(e)})}function $S(t){return new lL({type:"transform",transform:t})}function tt(t){return new kS({type:"optional",innerType:t})}function _S(t){return new uL({type:"nullable",innerType:t})}function dL(t,e){return new pL({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function mL(t,e){return new fL({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function hL(t,e){return new ES({type:"nonoptional",innerType:t,...be.normalizeParams(e)})}function yL(t,e){return new gL({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Sh(t,e){return new vL({type:"pipe",in:t,out:e})}function bL(t){return new _L({type:"readonly",innerType:t})}function wL(t){let e=new _t({check:"custom"});return e._zod.check=t,e}function PS(t,e){return uh(TS,t??(()=>!0),e)}function xL(t,e={}){return ph(TS,t,e)}function SL(t){let e=wL(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 Eh(t,e){return Sh($S(t),e)}var rt,bS,NM,Ve,zM,yS,pl,jM,MM,LM,DM,qM,UM,ZM,FM,HM,BM,GM,VM,WM,JM,KM,YM,wS,XM,QM,eL,tL,rL,oL,xS,SS,sL,iL,aL,xh,cL,lL,kS,uL,pL,fL,ES,gL,vL,_L,TS,_h=w(()=>{Mt();Mt();fh();vh();wh();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)=>fS(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>hS(t,r,n),t.parseAsync=async(r,n)=>mS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>gS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(xL(r,n)),t.superRefine=r=>t.check(SL(r)),t.overwrite=r=>t.check(ko(r)),t.optional=()=>tt(t),t.nullable=()=>_S(t),t.nullish=()=>tt(_S(t)),t.nonoptional=r=>hL(t,r),t.array=()=>we(t),t.or=r=>Ue([t,r]),t.and=r=>dl(t,r),t.transform=r=>Sh(t,$S(r)),t.default=r=>dL(t,r),t.prefault=r=>mL(t,r),t.catch=r=>yL(t,r),t.pipe=r=>Sh(t,r),t.readonly=()=>bL(t),t.describe=r=>{let n=t.clone();return Rn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Rn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Rn.get(t);let n=t.clone();return Rn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),bS=E("_ZodString",(t,e)=>{Gi.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(eh(...n)),t.includes=(...n)=>t.check(nh(...n)),t.startsWith=(...n)=>t.check(oh(...n)),t.endsWith=(...n)=>t.check(sh(...n)),t.min=(...n)=>t.check(ks(...n)),t.max=(...n)=>t.check(cl(...n)),t.length=(...n)=>t.check(ll(...n)),t.nonempty=(...n)=>t.check(ks(1,...n)),t.lowercase=n=>t.check(th(n)),t.uppercase=n=>t.check(rh(n)),t.trim=()=>t.check(ah()),t.normalize=(...n)=>t.check(ih(...n)),t.toLowerCase=()=>t.check(ch()),t.toUpperCase=()=>t.check(lh())}),NM=E("ZodString",(t,e)=>{Gi.init(t,e),bS.init(t,e),t.email=r=>t.check(Tm(zM,r)),t.url=r=>t.check(Im(jM,r)),t.jwt=r=>t.check(Vm(YM,r)),t.emoji=r=>t.check(Am(MM,r)),t.guid=r=>t.check(ol(yS,r)),t.uuid=r=>t.check(Pm(pl,r)),t.uuidv4=r=>t.check(Rm(pl,r)),t.uuidv6=r=>t.check(Cm(pl,r)),t.uuidv7=r=>t.check(Om(pl,r)),t.nanoid=r=>t.check(Nm(LM,r)),t.guid=r=>t.check(ol(yS,r)),t.cuid=r=>t.check(zm(DM,r)),t.cuid2=r=>t.check(jm(qM,r)),t.ulid=r=>t.check(Mm(UM,r)),t.base64=r=>t.check(Hm(WM,r)),t.base64url=r=>t.check(Bm(JM,r)),t.xid=r=>t.check(Lm(ZM,r)),t.ksuid=r=>t.check(Dm(FM,r)),t.ipv4=r=>t.check(qm(HM,r)),t.ipv6=r=>t.check(Um(BM,r)),t.cidrv4=r=>t.check(Zm(GM,r)),t.cidrv6=r=>t.check(Fm(VM,r)),t.e164=r=>t.check(Gm(KM,r)),t.datetime=r=>t.check(mh(r)),t.date=r=>t.check(hh(r)),t.time=r=>t.check(gh(r)),t.duration=r=>t.check(yh(r))});Ve=E("ZodStringFormat",(t,e)=>{qe.init(t,e),bS.init(t,e)}),zM=E("ZodEmail",(t,e)=>{qf.init(t,e),Ve.init(t,e)}),yS=E("ZodGUID",(t,e)=>{Lf.init(t,e),Ve.init(t,e)}),pl=E("ZodUUID",(t,e)=>{Df.init(t,e),Ve.init(t,e)}),jM=E("ZodURL",(t,e)=>{Uf.init(t,e),Ve.init(t,e)}),MM=E("ZodEmoji",(t,e)=>{Zf.init(t,e),Ve.init(t,e)}),LM=E("ZodNanoID",(t,e)=>{Ff.init(t,e),Ve.init(t,e)}),DM=E("ZodCUID",(t,e)=>{Hf.init(t,e),Ve.init(t,e)}),qM=E("ZodCUID2",(t,e)=>{Bf.init(t,e),Ve.init(t,e)}),UM=E("ZodULID",(t,e)=>{Gf.init(t,e),Ve.init(t,e)}),ZM=E("ZodXID",(t,e)=>{Vf.init(t,e),Ve.init(t,e)}),FM=E("ZodKSUID",(t,e)=>{Wf.init(t,e),Ve.init(t,e)}),HM=E("ZodIPv4",(t,e)=>{Jf.init(t,e),Ve.init(t,e)}),BM=E("ZodIPv6",(t,e)=>{Kf.init(t,e),Ve.init(t,e)}),GM=E("ZodCIDRv4",(t,e)=>{Yf.init(t,e),Ve.init(t,e)}),VM=E("ZodCIDRv6",(t,e)=>{Xf.init(t,e),Ve.init(t,e)}),WM=E("ZodBase64",(t,e)=>{Qf.init(t,e),Ve.init(t,e)}),JM=E("ZodBase64URL",(t,e)=>{em.init(t,e),Ve.init(t,e)}),KM=E("ZodE164",(t,e)=>{tm.init(t,e),Ve.init(t,e)}),YM=E("ZodJWT",(t,e)=>{rm.init(t,e),Ve.init(t,e)}),wS=E("ZodNumber",(t,e)=>{el.init(t,e),rt.init(t,e),t.gt=(n,o)=>t.check(il(n,o)),t.gte=(n,o)=>t.check(Ji(n,o)),t.min=(n,o)=>t.check(Ji(n,o)),t.lt=(n,o)=>t.check(sl(n,o)),t.lte=(n,o)=>t.check(Wi(n,o)),t.max=(n,o)=>t.check(Wi(n,o)),t.int=n=>t.check(vS(n)),t.safe=n=>t.check(vS(n)),t.positive=n=>t.check(il(0,n)),t.nonnegative=n=>t.check(Ji(0,n)),t.negative=n=>t.check(sl(0,n)),t.nonpositive=n=>t.check(Wi(0,n)),t.multipleOf=(n,o)=>t.check(al(n,o)),t.step=(n,o)=>t.check(al(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});XM=E("ZodNumberFormat",(t,e)=>{nm.init(t,e),wS.init(t,e)});QM=E("ZodBoolean",(t,e)=>{om.init(t,e),rt.init(t,e)});eL=E("ZodNull",(t,e)=>{sm.init(t,e),rt.init(t,e)});tL=E("ZodUnknown",(t,e)=>{im.init(t,e),rt.init(t,e)});rL=E("ZodNever",(t,e)=>{am.init(t,e),rt.init(t,e)});oL=E("ZodArray",(t,e)=>{cm.init(t,e),rt.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(ks(r,n)),t.nonempty=r=>t.check(ks(1,r)),t.max=(r,n)=>t.check(cl(r,n)),t.length=(r,n)=>t.check(ll(r,n)),t.unwrap=()=>t.element});xS=E("ZodObject",(t,e)=>{tl.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:nL()}),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(kS,t,r[0]),t.required=(...r)=>be.required(ES,t,r[0])});SS=E("ZodUnion",(t,e)=>{rl.init(t,e),rt.init(t,e),t.options=e.options});sL=E("ZodDiscriminatedUnion",(t,e)=>{SS.init(t,e),lm.init(t,e)});iL=E("ZodIntersection",(t,e)=>{um.init(t,e),rt.init(t,e)});aL=E("ZodRecord",(t,e)=>{pm.init(t,e),rt.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});xh=E("ZodEnum",(t,e)=>{dm.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 xh({...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 xh({...e,checks:[],...be.normalizeParams(o),entries:s})}});cL=E("ZodLiteral",(t,e)=>{fm.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]}})});lL=E("ZodTransform",(t,e)=>{mm.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)}});kS=E("ZodOptional",(t,e)=>{hm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});uL=E("ZodNullable",(t,e)=>{gm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});pL=E("ZodDefault",(t,e)=>{ym.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});fL=E("ZodPrefault",(t,e)=>{vm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});ES=E("ZodNonOptional",(t,e)=>{_m.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType});gL=E("ZodCatch",(t,e)=>{bm.init(t,e),rt.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});vL=E("ZodPipe",(t,e)=>{wm.init(t,e),rt.init(t,e),t.in=e.in,t.out=e.out});_L=E("ZodReadonly",(t,e)=>{xm.init(t,e),rt.init(t,e)});TS=E("ZodCustom",(t,e)=>{Sm.init(t,e),rt.init(t,e)})});var RS=w(()=>{});var CS=w(()=>{});var OS=w(()=>{Mt();_h();fh();bh();wh();RS();Mt();Y0();nl();vh();CS();nr(K0())});var IS=w(()=>{OS()});var AS=w(()=>{IS()});function WS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function JS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Ph,NS,Xi,Cn,ml,bt,zS,jS,V5,EL,TL,Rh,sr,Qi,MS,wt,lr,ur,xt,hl,LS,On,DS,qS,Ch,on,B,Oh,Ts,ea,W5,gl,PL,yl,RL,ta,Es,US,CL,OL,IL,AL,NL,zL,vl,Ih,jL,ML,Ah,_l,LL,DL,bl,qL,ra,na,UL,oa,Ps,ZL,sa,wl,xl,Sl,J5,$l,kl,El,ZS,FS,HS,Nh,BS,ia,Rs,GS,FL,Tl,HL,Pl,BL,zh,GL,Rl,VL,WL,JL,KL,YL,XL,QL,eD,tD,rD,Cl,nD,oD,Ol,jh,Mh,Lh,sD,iD,aD,Dh,cD,lD,uD,pD,dD,VS,Il,fD,Al,K5,mD,Cs,hD,Y5,aa,gD,qh,yD,vD,_D,bD,wD,xD,SD,fl,$D,kD,ED,Uh,Zh,TD,PD,RD,CD,OD,ID,AD,ND,zD,jD,MD,LD,DD,qD,UD,ZD,FD,HD,Nl,BD,GD,VD,zl,WD,JD,KD,Fh,YD,X5,Q5,e8,t8,r8,n8,q,Th,Os=w(()=>{AS();Ph="2025-11-25",NS="2025-03-26",Xi=[Ph,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Cn="io.modelcontextprotocol/related-task",ml="2.0",bt=PS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),zS=Ue([k(),Ie().int()]),jS=k(),V5=Lt({ttl:Ue([Ie(),$h()]).optional(),pollInterval:Ie().optional()}),EL=j({ttl:Ie().optional()}),TL=j({taskId:k()}),Rh=Lt({progressToken:zS.optional(),[Cn]:TL.optional()}),sr=j({_meta:Rh.optional()}),Qi=sr.extend({task:EL.optional()}),MS=t=>Qi.safeParse(t).success,wt=j({method:k(),params:sr.loose().optional()}),lr=j({_meta:Rh.optional()}),ur=j({method:k(),params:lr.loose().optional()}),xt=Lt({_meta:Rh.optional()}),hl=Ue([k(),Ie().int()]),LS=j({jsonrpc:U(ml),id:hl,...wt.shape}).strict(),On=t=>LS.safeParse(t).success,DS=j({jsonrpc:U(ml),...ur.shape}).strict(),qS=t=>DS.safeParse(t).success,Ch=j({jsonrpc:U(ml),id:hl,result:xt}).strict(),on=t=>Ch.safeParse(t).success;(function(t){t[t.ConnectionClosed=-32e3]="ConnectionClosed",t[t.RequestTimeout=-32001]="RequestTimeout",t[t.ParseError=-32700]="ParseError",t[t.InvalidRequest=-32600]="InvalidRequest",t[t.MethodNotFound=-32601]="MethodNotFound",t[t.InvalidParams=-32602]="InvalidParams",t[t.InternalError=-32603]="InternalError",t[t.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(B||(B={}));Oh=j({jsonrpc:U(ml),id:hl.optional(),error:j({code:Ie().int(),message:k(),data:We().optional()})}).strict(),Ts=t=>Oh.safeParse(t).success,ea=Ue([LS,DS,Ch,Oh]),W5=Ue([Ch,Oh]),gl=xt.strict(),PL=lr.extend({requestId:hl.optional(),reason:k().optional()}),yl=ur.extend({method:U("notifications/cancelled"),params:PL}),RL=j({src:k(),mimeType:k().optional(),sizes:we(k()).optional(),theme:Bt(["light","dark"]).optional()}),ta=j({icons:we(RL).optional()}),Es=j({name:k(),title:k().optional()}),US=Es.extend({...Es.shape,...ta.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),CL=dl(j({applyDefaults:ht().optional()}),Je(k(),We())),OL=Eh(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,dl(j({form:CL.optional(),url:bt.optional()}),Je(k(),We()).optional())),IL=Lt({list:bt.optional(),cancel:bt.optional(),requests:Lt({sampling:Lt({createMessage:bt.optional()}).optional(),elicitation:Lt({create:bt.optional()}).optional()}).optional()}),AL=Lt({list:bt.optional(),cancel:bt.optional(),requests:Lt({tools:Lt({call:bt.optional()}).optional()}).optional()}),NL=j({experimental:Je(k(),bt).optional(),sampling:j({context:bt.optional(),tools:bt.optional()}).optional(),elicitation:OL.optional(),roots:j({listChanged:ht().optional()}).optional(),tasks:IL.optional()}),zL=sr.extend({protocolVersion:k(),capabilities:NL,clientInfo:US}),vl=wt.extend({method:U("initialize"),params:zL}),Ih=t=>vl.safeParse(t).success,jL=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:AL.optional()}),ML=xt.extend({protocolVersion:k(),capabilities:jL,serverInfo:US,instructions:k().optional()}),Ah=ur.extend({method:U("notifications/initialized"),params:lr.optional()}),_l=wt.extend({method:U("ping"),params:sr.optional()}),LL=j({progress:Ie(),total:tt(Ie()),message:tt(k())}),DL=j({...lr.shape,...LL.shape,progressToken:zS}),bl=ur.extend({method:U("notifications/progress"),params:DL}),qL=sr.extend({cursor:jS.optional()}),ra=wt.extend({params:qL.optional()}),na=xt.extend({nextCursor:jS.optional()}),UL=Bt(["working","input_required","completed","failed","cancelled"]),oa=j({taskId:k(),status:UL,ttl:Ue([Ie(),$h()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:tt(Ie()),statusMessage:tt(k())}),Ps=xt.extend({task:oa}),ZL=lr.merge(oa),sa=ur.extend({method:U("notifications/tasks/status"),params:ZL}),wl=wt.extend({method:U("tasks/get"),params:sr.extend({taskId:k()})}),xl=xt.merge(oa),Sl=wt.extend({method:U("tasks/result"),params:sr.extend({taskId:k()})}),J5=xt.loose(),$l=ra.extend({method:U("tasks/list")}),kl=na.extend({tasks:we(oa)}),El=wt.extend({method:U("tasks/cancel"),params:sr.extend({taskId:k()})}),ZS=xt.merge(oa),FS=j({uri:k(),mimeType:tt(k()),_meta:Je(k(),We()).optional()}),HS=FS.extend({text:k()}),Nh=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),BS=FS.extend({blob:Nh}),ia=Bt(["user","assistant"]),Rs=j({audience:we(ia).optional(),priority:Ie().min(0).max(1).optional(),lastModified:Ki.datetime({offset:!0}).optional()}),GS=j({...Es.shape,...ta.shape,uri:k(),description:tt(k()),mimeType:tt(k()),annotations:Rs.optional(),_meta:tt(Lt({}))}),FL=j({...Es.shape,...ta.shape,uriTemplate:k(),description:tt(k()),mimeType:tt(k()),annotations:Rs.optional(),_meta:tt(Lt({}))}),Tl=ra.extend({method:U("resources/list")}),HL=na.extend({resources:we(GS)}),Pl=ra.extend({method:U("resources/templates/list")}),BL=na.extend({resourceTemplates:we(FL)}),zh=sr.extend({uri:k()}),GL=zh,Rl=wt.extend({method:U("resources/read"),params:GL}),VL=xt.extend({contents:we(Ue([HS,BS]))}),WL=ur.extend({method:U("notifications/resources/list_changed"),params:lr.optional()}),JL=zh,KL=wt.extend({method:U("resources/subscribe"),params:JL}),YL=zh,XL=wt.extend({method:U("resources/unsubscribe"),params:YL}),QL=lr.extend({uri:k()}),eD=ur.extend({method:U("notifications/resources/updated"),params:QL}),tD=j({name:k(),description:tt(k()),required:tt(ht())}),rD=j({...Es.shape,...ta.shape,description:tt(k()),arguments:tt(we(tD)),_meta:tt(Lt({}))}),Cl=ra.extend({method:U("prompts/list")}),nD=na.extend({prompts:we(rD)}),oD=sr.extend({name:k(),arguments:Je(k(),k()).optional()}),Ol=wt.extend({method:U("prompts/get"),params:oD}),jh=j({type:U("text"),text:k(),annotations:Rs.optional(),_meta:Je(k(),We()).optional()}),Mh=j({type:U("image"),data:Nh,mimeType:k(),annotations:Rs.optional(),_meta:Je(k(),We()).optional()}),Lh=j({type:U("audio"),data:Nh,mimeType:k(),annotations:Rs.optional(),_meta:Je(k(),We()).optional()}),sD=j({type:U("tool_use"),name:k(),id:k(),input:Je(k(),We()),_meta:Je(k(),We()).optional()}),iD=j({type:U("resource"),resource:Ue([HS,BS]),annotations:Rs.optional(),_meta:Je(k(),We()).optional()}),aD=GS.extend({type:U("resource_link")}),Dh=Ue([jh,Mh,Lh,aD,iD]),cD=j({role:ia,content:Dh}),lD=xt.extend({description:k().optional(),messages:we(cD)}),uD=ur.extend({method:U("notifications/prompts/list_changed"),params:lr.optional()}),pD=j({title:k().optional(),readOnlyHint:ht().optional(),destructiveHint:ht().optional(),idempotentHint:ht().optional(),openWorldHint:ht().optional()}),dD=j({taskSupport:Bt(["required","optional","forbidden"]).optional()}),VS=j({...Es.shape,...ta.shape,description:k().optional(),inputSchema:j({type:U("object"),properties:Je(k(),bt).optional(),required:we(k()).optional()}).catchall(We()),outputSchema:j({type:U("object"),properties:Je(k(),bt).optional(),required:we(k()).optional()}).catchall(We()).optional(),annotations:pD.optional(),execution:dD.optional(),_meta:Je(k(),We()).optional()}),Il=ra.extend({method:U("tools/list")}),fD=na.extend({tools:we(VS)}),Al=xt.extend({content:we(Dh).default([]),structuredContent:Je(k(),We()).optional(),isError:ht().optional()}),K5=Al.or(xt.extend({toolResult:We()})),mD=Qi.extend({name:k(),arguments:Je(k(),We()).optional()}),Cs=wt.extend({method:U("tools/call"),params:mD}),hD=ur.extend({method:U("notifications/tools/list_changed"),params:lr.optional()}),Y5=j({autoRefresh:ht().default(!0),debounceMs:Ie().int().nonnegative().default(300)}),aa=Bt(["debug","info","notice","warning","error","critical","alert","emergency"]),gD=sr.extend({level:aa}),qh=wt.extend({method:U("logging/setLevel"),params:gD}),yD=lr.extend({level:aa,logger:k().optional(),data:We()}),vD=ur.extend({method:U("notifications/message"),params:yD}),_D=j({name:k().optional()}),bD=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()}),wD=j({mode:Bt(["auto","required","none"]).optional()}),xD=j({type:U("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:we(Dh).default([]),structuredContent:j({}).loose().optional(),isError:ht().optional(),_meta:Je(k(),We()).optional()}),SD=kh("type",[jh,Mh,Lh]),fl=kh("type",[jh,Mh,Lh,sD,xD]),$D=j({role:ia,content:Ue([fl,we(fl)]),_meta:Je(k(),We()).optional()}),kD=Qi.extend({messages:we($D),modelPreferences:bD.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(VS).optional(),toolChoice:wD.optional()}),ED=wt.extend({method:U("sampling/createMessage"),params:kD}),Uh=xt.extend({model:k(),stopReason:tt(Bt(["endTurn","stopSequence","maxTokens"]).or(k())),role:ia,content:SD}),Zh=xt.extend({model:k(),stopReason:tt(Bt(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:ia,content:Ue([fl,we(fl)])}),TD=j({type:U("boolean"),title:k().optional(),description:k().optional(),default:ht().optional()}),PD=j({type:U("string"),title:k().optional(),description:k().optional(),minLength:Ie().optional(),maxLength:Ie().optional(),format:Bt(["email","uri","date","date-time"]).optional(),default:k().optional()}),RD=j({type:Bt(["number","integer"]),title:k().optional(),description:k().optional(),minimum:Ie().optional(),maximum:Ie().optional(),default:Ie().optional()}),CD=j({type:U("string"),title:k().optional(),description:k().optional(),enum:we(k()),default:k().optional()}),OD=j({type:U("string"),title:k().optional(),description:k().optional(),oneOf:we(j({const:k(),title:k()})),default:k().optional()}),ID=j({type:U("string"),title:k().optional(),description:k().optional(),enum:we(k()),enumNames:we(k()).optional(),default:k().optional()}),AD=Ue([CD,OD]),ND=j({type:U("array"),title:k().optional(),description:k().optional(),minItems:Ie().optional(),maxItems:Ie().optional(),items:j({type:U("string"),enum:we(k())}),default:we(k()).optional()}),zD=j({type:U("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()}),jD=Ue([ND,zD]),MD=Ue([ID,AD,jD]),LD=Ue([MD,TD,PD,RD]),DD=Qi.extend({mode:U("form").optional(),message:k(),requestedSchema:j({type:U("object"),properties:Je(k(),LD),required:we(k()).optional()})}),qD=Qi.extend({mode:U("url"),message:k(),elicitationId:k(),url:k().url()}),UD=Ue([DD,qD]),ZD=wt.extend({method:U("elicitation/create"),params:UD}),FD=lr.extend({elicitationId:k()}),HD=ur.extend({method:U("notifications/elicitation/complete"),params:FD}),Nl=xt.extend({action:Bt(["accept","decline","cancel"]),content:Eh(t=>t===null?void 0:t,Je(k(),Ue([k(),Ie(),ht(),we(k())])).optional())}),BD=j({type:U("ref/resource"),uri:k()}),GD=j({type:U("ref/prompt"),name:k()}),VD=sr.extend({ref:Ue([GD,BD]),argument:j({name:k(),value:k()}),context:j({arguments:Je(k(),k()).optional()}).optional()}),zl=wt.extend({method:U("completion/complete"),params:VD});WD=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()}),KD=wt.extend({method:U("roots/list"),params:sr.optional()}),Fh=xt.extend({roots:we(JD)}),YD=ur.extend({method:U("notifications/roots/list_changed"),params:lr.optional()}),X5=Ue([_l,vl,zl,qh,Ol,Cl,Tl,Pl,Rl,KL,XL,Cs,Il,wl,Sl,$l,El]),Q5=Ue([yl,bl,Ah,YD,sa]),e8=Ue([gl,Uh,Zh,Nl,Fh,xl,kl,Ps]),t8=Ue([_l,ED,ZD,KD,wl,Sl,$l,El]),r8=Ue([yl,bl,vD,eD,WL,hD,uD,sa,HD]),n8=Ue([gl,ML,WD,lD,nD,HL,BL,VL,Al,fD,xl,kl,Ps]),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===B.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Th(o.elicitations,r)}return new t(e,r,n)}},Th=class extends q{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(B.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function XD(t){return ea.parse(JSON.parse(t))}function KS(t){return JSON.stringify(t)+`
273
+ `}var jl,YS=w(()=>{Os();jl=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),XD(r)}clear(){this._buffer=void 0}}});import XS from"node:process";var Ml,QS=w(()=>{YS();Ml=class{constructor(e=XS.stdin,r=XS.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new jl,this._started=!1,this._ondata=n=>{this._readBuffer.append(n),this.processReadBuffer()},this._onerror=n=>{this.onerror?.(n)}}async start(){if(this._started)throw new Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(r=>{let n=KS(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});import{Http2ServerRequest as QD}from"http2";import{Http2ServerRequest as Hh}from"http2";import{Readable as e$}from"stream";import p2 from"crypto";async function c2(t){return Promise.race([t,Promise.resolve().then(()=>Promise.resolve(void 0))])}function o$(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 l2(t,e){if(t.locked)throw new TypeError("ReadableStream is locked.");return e.destroyed?void 0:o$(t.getReader(),e)}var To,e2,t2,ca,r2,r$,n2,Ns,o2,Ll,Dl,s2,As,i2,ql,a2,t$,Is,Po,Gh,la,s$,u2,Vh,d2,i$,Bh,a$,c$,f2,m2,Wh,l$=w(()=>{To=class extends Error{constructor(t,e){super(t,e),this.name="RequestError"}},e2=t=>t instanceof To?t:new To(t.message,{cause:t}),t2=global.Request,ca=class extends t2{constructor(t,e){typeof t=="object"&&Ns in t&&(t=t[Ns]()),typeof e?.body?.getReader<"u"&&(e.duplex??="half"),super(t,e)}},r2=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)},r$=Symbol("wrapBodyStream"),n2=(t,e,r,n,o)=>{let s={method:t,headers:r,signal:o.signal};if(t==="TRACE"){s.method="GET";let i=new ca(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[r$]){let i;s.body=new ReadableStream({async pull(a){try{i||=e$.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=e$.toWeb(n);return new ca(e,s)},Ns=Symbol("getRequestCache"),o2=Symbol("requestCache"),Ll=Symbol("incomingKey"),Dl=Symbol("urlKey"),s2=Symbol("headersKey"),As=Symbol("abortControllerKey"),i2=Symbol("getAbortController"),ql={get method(){return this[Ll].method||"GET"},get url(){return this[Dl]},get headers(){return this[s2]||=r2(this[Ll])},[i2](){return this[Ns](),this[As]},[Ns](){return this[As]||=new AbortController,this[o2]||=n2(this.method,this[Dl],this.headers,this[Ll],this[As])}};["body","bodyUsed","cache","credentials","destination","integrity","mode","redirect","referrer","referrerPolicy","signal","keepalive"].forEach(t=>{Object.defineProperty(ql,t,{get(){return this[Ns]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(ql,t,{value:function(){return this[Ns]()[t]()}})});Object.setPrototypeOf(ql,ca.prototype);a2=(t,e)=>{let r=Object.create(ql);r[Ll]=t;let n=t.url||"";if(n[0]!=="/"&&(n.startsWith("http://")||n.startsWith("https://"))){if(t instanceof Hh)throw new To("Absolute URL for :path is not allowed in HTTP/2");try{let a=new URL(n);r[Dl]=a.href}catch(a){throw new To("Invalid absolute URL",{cause:a})}return r}let o=(t instanceof Hh?t.authority:t.headers.host)||e;if(!o)throw new To("Missing host header");let s;if(t instanceof Hh){if(s=t.scheme,!(s==="http"||s==="https"))throw new To("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 To("Invalid host header");return r[Dl]=i.href,r},t$=Symbol("responseCache"),Is=Symbol("getResponseCache"),Po=Symbol("cache"),Gh=global.Response,la=class n${#t;#e;[Is](){return delete this[Po],this[t$]||=new Gh(this.#t,this.#e)}constructor(e,r){let n;if(this.#t=e,r instanceof n$){let o=r[t$];if(o){this.#e=o,this[Is]();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[Po]=[r?.status||200,e,n])}get headers(){let e=this[Po];return e?(e[2]instanceof Headers||(e[2]=new Headers(e[2])),e[2]):this[Is]().headers}get status(){return this[Po]?.[0]??this[Is]().status}get ok(){let e=this.status;return e>=200&&e<300}};["body","bodyUsed","redirected","statusText","trailers","type","url"].forEach(t=>{Object.defineProperty(la.prototype,t,{get(){return this[Is]()[t]}})});["arrayBuffer","blob","clone","formData","json","text"].forEach(t=>{Object.defineProperty(la.prototype,t,{value:function(){return this[Is]()[t]()}})});Object.setPrototypeOf(la,Gh);Object.setPrototypeOf(la.prototype,Gh.prototype);s$=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},u2="x-hono-already-sent";typeof global.crypto>"u"&&(global.crypto=p2);Vh=Symbol("outgoingEnded"),d2=()=>new Response(null,{status:400}),i$=t=>new Response(null,{status:t instanceof Error&&(t.name==="TimeoutError"||t.constructor.name==="TimeoutError")?504:500}),Bh=(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))},a$=t=>{"flushHeaders"in t&&t.writable&&t.flushHeaders()},c$=async(t,e)=>{let[r,n,o]=t[Po];o instanceof Headers&&(o=s$(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())):(a$(e),await l2(n,e)?.catch(s=>Bh(s,e))),e[Vh]?.()},f2=t=>typeof t.then=="function",m2=async(t,e,r={})=>{if(f2(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(i$);if(Po in t)return c$(t,e);let n=s$(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 c2(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&&a$(e),await o$(o,e,a))}else n[u2]||(e.writeHead(t.status,n),e.end());e[Vh]?.()},Wh=(t,e={})=>{let r=e.autoCleanupIncoming??!0;return e.overrideGlobalObjects!==!1&&global.Request!==ca&&(Object.defineProperty(global,"Request",{value:ca}),Object.defineProperty(global,"Response",{value:la})),async(n,o)=>{let s,i;try{i=a2(n,e.hostname);let a=!r||n.method==="GET"||n.method==="HEAD";if(a||(n[r$]=!0,n.on("end",()=>{a=!0}),n instanceof QD&&(o[Vh]=()=>{a||setTimeout(()=>{a||setTimeout(()=>{n.destroy(),o.destroy()})})})),o.on("close",()=>{i[As]&&(n.errored?i[As].abort(n.errored.toString()):o.writableFinished||i[As].abort("Client connection prematurely closed.")),a||setTimeout(()=>{a||setTimeout(()=>{n.destroy()})})}),s=t(i,{incoming:n,outgoing:o}),Po in s)return c$(s,o)}catch(a){if(s)return Bh(a,o);if(e.errorHandler){if(s=await e.errorHandler(i?a:e2(a)),!s)return}else i?s=i$(a):s=d2()}try{return await m2(s,o,e)}catch(a){return Bh(a,o)}}}});var Ul,u$=w(()=>{Os();Ul=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}
275
275
  data:
276
276
 
277
277
  `;this._retryInterval!==void 0&&(i=`id: ${s}
@@ -282,18 +282,18 @@ data:
282
282
  `;return o&&(s+=`id: ${o}
283
283
  `),s+=`data: ${JSON.stringify(n)}
284
284
 
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=X(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();ct()});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 X(t.type._def,e)}var eu=w(()=>{ct()});var L$,sg=w(()=>{ct();L$=(t,e)=>X(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{...X(t.innerType._def,e),default:t.defaultValue()}}var cg=w(()=>{ct()});function q$(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):Ke(e)}var lg=w(()=>{ct();mr()});function Z$(t){return{type:"string",enum:Array.from(t.values)}}var ug=w(()=>{});function U$(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(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(()=>{ct();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
+ `,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=>ea.parse(v)):a=[ea.parse(i)]}catch{return this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let c=a.some(Ih);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(On)){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=>Ih(v)),f=p?p.params.protocolVersion:e.headers.get("mcp-protocol-version")??NS;if(this._enableJsonResponse)return new Promise(v=>{this._streamMapping.set(u,{resolveJson:v,cleanup:()=>{this._streamMapping.delete(u)}});for(let b of a)On(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)On(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;On(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&&!Xi.includes(r))return this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${Xi.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)||Ts(e))&&(n=e.id),n===void 0){if(on(e)||Ts(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)||Ts(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 Zl,p$=w(()=>{l$();u$();Zl=class{constructor(e={}){this._requestContext=new WeakMap,this._webStandardTransport=new Ul(e),this._requestListener=Wh(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 Wh(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,Jh,z,Fr,ua=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})})(Jh||(Jh={}));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,h2,Gt,Fl=w(()=>{ua();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"]),h2=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 g2,sn,Kh=w(()=>{Fl();ua();g2=(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=g2});function y2(t){d$=t}function zs(){return d$}var d$,Hl=w(()=>{Kh();d$=sn});function N(t,e){let r=zs(),n=pa({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 pa,v2,St,J,Ro,Ct,Bl,Gl,In,js,Yh=w(()=>{Hl();Kh();pa=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}},v2=[];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"}),Ro=t=>({status:"dirty",value:t}),Ct=t=>({status:"valid",value:t}),Bl=t=>t.status==="aborted",Gl=t=>t.status==="dirty",In=t=>t.status==="valid",js=t=>typeof Promise<"u"&&t instanceof Promise});var f$=w(()=>{});var D,m$=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 v$(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 z2(t){return new RegExp(`^${v$(t)}$`)}function _$(t){let e=`${y$}T${v$(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 j2(t,e){return!!((e==="v4"||!e)&&P2.test(t)||(e==="v6"||!e)&&C2.test(t))}function M2(t,e){if(!$2.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 L2(t,e){return!!((e==="v4"||!e)&&R2.test(t)||(e==="v6"||!e)&&O2.test(t))}function D2(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 Ms(t){if(t instanceof Wt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=Vt.create(Ms(n))}return new Wt({...t._def,shape:()=>e})}else return t instanceof ln?new ln({...t._def,type:Ms(t.element)}):t instanceof Vt?Vt.create(Ms(t.unwrap())):t instanceof Br?Br.create(Ms(t.unwrap())):t instanceof Hr?Hr.create(t.items.map(e=>Ms(e))):t}function Qh(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=Qh(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=Qh(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 b$(t,e){return new qo({values:t,typeName:R.ZodEnum,...se(e)})}function g$(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function w$(t,e={},r){return t?Nn.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=g$(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=g$(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Nn.create()}var pr,h$,ue,_2,b2,w2,x2,S2,$2,k2,E2,T2,Xh,P2,R2,C2,O2,I2,A2,y$,N2,An,Co,Oo,Io,Ao,Ls,No,zo,Nn,cn,Tr,Ds,ln,Wt,jo,an,Vl,Mo,Hr,Wl,qs,Us,Jl,Lo,Do,qo,Uo,zn,dr,Vt,Br,Zo,Fo,Zs,q2,da,fa,Ho,U2,R,Z2,x$,S$,F2,H2,$$,B2,G2,V2,W2,J2,K2,Y2,X2,Q2,eg,eq,tq,rq,nq,oq,sq,iq,aq,cq,lq,uq,pq,dq,fq,mq,hq,gq,yq,vq,_q,bq,wq,xq,Sq,k$=w(()=>{Fl();Hl();m$();Yh();ua();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}},h$=(t,e)=>{if(In(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(js(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 h$(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 In(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=>In(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(js(o)?o:Promise.resolve(o));return h$(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:R.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 zn.create(this,this._def)}or(e){return jo.create([this,e],this._def)}and(e){return Mo.create(this,e,this._def)}transform(e){return new dr({...se(this._def),schema:this,typeName:R.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Zo({...se(this._def),innerType:this,defaultValue:r,typeName:R.ZodDefault})}brand(){return new da({typeName:R.ZodBranded,type:this,...se(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Fo({...se(this._def),innerType:this,catchValue:r,typeName:R.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return fa.create(this,e)}readonly(){return Ho.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},_2=/^c[^\s-]{8,}$/i,b2=/^[0-9a-z]+$/,w2=/^[0-9A-HJKMNP-TV-Z]{26}$/i,x2=/^[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,S2=/^[a-z0-9_-]{21}$/i,$2=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,k2=/^[-+]?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)?)??$/,E2=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,T2="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",P2=/^(?:(?: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])$/,R2=/^(?:(?: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])$/,C2=/^(([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]))$/,O2=/^(([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])$/,I2=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,A2=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,y$="((\\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])))",N2=new RegExp(`^${y$}$`);An=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")E2.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")Xh||(Xh=new RegExp(T2,"u")),Xh.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")x2.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")S2.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")b2.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")w2.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"?_$(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"?N2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{code:T.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?z2(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"?k2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"duration",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?j2(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"?M2(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"?L2(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"?I2.test(e.data)||(o=this._getOrReturnCtx(e,o),N(o,{validation:"base64",code:T.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?A2.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}};An.create=t=>new An({checks:[],typeName:R.ZodString,coerce:t?.coerce??!1,...se(t)});Co=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"?D2(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)}};Co.create=t=>new Co({checks:[],typeName:R.ZodNumber,coerce:t?.coerce||!1,...se(t)});Oo=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}};Oo.create=t=>new Oo({checks:[],typeName:R.ZodBigInt,coerce:t?.coerce??!1,...se(t)});Io=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 Ct(e.data)}};Io.create=t=>new Io({typeName:R.ZodBoolean,coerce:t?.coerce||!1,...se(t)});Ao=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}};Ao.create=t=>new Ao({checks:[],coerce:t?.coerce||!1,typeName:R.ZodDate,...se(t)});Ls=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 Ct(e.data)}};Ls.create=t=>new Ls({typeName:R.ZodSymbol,...se(t)});No=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 Ct(e.data)}};No.create=t=>new No({typeName:R.ZodUndefined,...se(t)});zo=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 Ct(e.data)}};zo.create=t=>new zo({typeName:R.ZodNull,...se(t)});Nn=class extends ue{constructor(){super(...arguments),this._any=!0}_parse(e){return Ct(e.data)}};Nn.create=t=>new Nn({typeName:R.ZodAny,...se(t)});cn=class extends ue{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ct(e.data)}};cn.create=t=>new cn({typeName:R.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:R.ZodNever,...se(t)});Ds=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 Ct(e.data)}};Ds.create=t=>new Ds({typeName:R.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:R.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:R.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 Ms(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 b$(ye.objectKeys(this.shape))}};Wt.create=(t,e)=>new Wt({shape:()=>t,unknownKeys:"strip",catchall:Tr.create(),typeName:R.ZodObject,...se(e)});Wt.strictCreate=(t,e)=>new Wt({shape:()=>t,unknownKeys:"strict",catchall:Tr.create(),typeName:R.ZodObject,...se(e)});Wt.lazycreate=(t,e)=>new Wt({shape:t,unknownKeys:"strip",catchall:Tr.create(),typeName:R.ZodObject,...se(e)});jo=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}};jo.create=(t,e)=>new jo({options:t,typeName:R.ZodUnion,...se(e)});an=t=>t instanceof Lo?an(t.schema):t instanceof dr?an(t.innerType()):t instanceof Do?[t.value]:t instanceof qo?t.options:t instanceof Uo?ye.objectValues(t.enum):t instanceof Zo?an(t._def.innerType):t instanceof No?[void 0]:t instanceof zo?[null]:t instanceof Vt?[void 0,...an(t.unwrap())]:t instanceof Br?[null,...an(t.unwrap())]:t instanceof da||t instanceof Ho?an(t.unwrap()):t instanceof Fo?an(t._def.innerType):[],Vl=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:R.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...se(n)})}};Mo=class extends ue{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(Bl(s)||Bl(i))return J;let a=Qh(s.value,i.value);return a.valid?((Gl(s)||Gl(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}))}};Mo.create=(t,e,r)=>new Mo({left:t,right:e,typeName:R.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:R.ZodTuple,rest:null,...se(e)})};Wl=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:R.ZodRecord,...se(n)}):new t({keyType:An.create(),valueType:e,typeName:R.ZodRecord,...se(r)})}},qs=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}}}};qs.create=(t,e,r)=>new qs({valueType:e,keyType:t,typeName:R.ZodMap,...se(r)});Us=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)}};Us.create=(t,e)=>new Us({valueType:t,minSize:null,maxSize:null,typeName:R.ZodSet,...se(e)});Jl=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 pa({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,zs(),sn].filter(l=>!!l),issueData:{code:T.invalid_arguments,argumentsError:c}})}function o(a,c){return pa({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,zs(),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 zn){let a=this;return Ct(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 Ct(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:R.ZodFunction,...se(n)})}},Lo=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})}};Lo.create=(t,e)=>new Lo({getter:t,typeName:R.ZodLazy,...se(e)});Do=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}};Do.create=(t,e)=>new Do({value:t,typeName:R.ZodLiteral,...se(e)});qo=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 Ct(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})}};qo.create=b$;Uo=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 Ct(e.data)}get enum(){return this._def.values}};Uo.create=(t,e)=>new Uo({values:t,typeName:R.ZodNativeEnum,...se(e)});zn=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 Ct(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};zn.create=(t,e)=>new zn({type:t,typeName:R.ZodPromise,...se(e)});dr=class extends ue{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===R.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"?Ro(c.value):r.value==="dirty"?Ro(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"?Ro(a.value):r.value==="dirty"?Ro(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(!In(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=>In(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:R.ZodEffects,effect:e,...se(r)});dr.createWithPreprocess=(t,e,r)=>new dr({schema:e,effect:{type:"preprocess",transform:t},typeName:R.ZodEffects,...se(r)});Vt=class extends ue{_parse(e){return this._getType(e)===z.undefined?Ct(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Vt.create=(t,e)=>new Vt({innerType:t,typeName:R.ZodOptional,...se(e)});Br=class extends ue{_parse(e){return this._getType(e)===z.null?Ct(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Br.create=(t,e)=>new Br({innerType:t,typeName:R.ZodNullable,...se(e)});Zo=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}};Zo.create=(t,e)=>new Zo({innerType:t,typeName:R.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...se(e)});Fo=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 js(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}};Fo.create=(t,e)=>new Fo({innerType:t,typeName:R.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...se(e)});Zs=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}}};Zs.create=t=>new Zs({typeName:R.ZodNaN,...se(t)});q2=Symbol("zod_brand"),da=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}},fa=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(),Ro(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:R.ZodPipeline})}},Ho=class extends ue{_parse(e){let r=this._def.innerType._parse(e),n=o=>(In(o)&&(o.value=Object.freeze(o.value)),o);return js(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};Ho.create=(t,e)=>new Ho({innerType:t,typeName:R.ZodReadonly,...se(e)});U2={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"})(R||(R={}));Z2=(t,e={message:`Input not instance of ${t.name}`})=>w$(r=>r instanceof t,e),x$=An.create,S$=Co.create,F2=Zs.create,H2=Oo.create,$$=Io.create,B2=Ao.create,G2=Ls.create,V2=No.create,W2=zo.create,J2=Nn.create,K2=cn.create,Y2=Tr.create,X2=Ds.create,Q2=ln.create,eg=Wt.create,eq=Wt.strictCreate,tq=jo.create,rq=Vl.create,nq=Mo.create,oq=Hr.create,sq=Wl.create,iq=qs.create,aq=Us.create,cq=Jl.create,lq=Lo.create,uq=Do.create,pq=qo.create,dq=Uo.create,fq=zn.create,mq=dr.create,hq=Vt.create,gq=Br.create,yq=dr.createWithPreprocess,vq=fa.create,_q=()=>x$().optional(),bq=()=>S$().optional(),wq=()=>$$().optional(),xq={string:t=>An.create({...t,coerce:!0}),number:t=>Co.create({...t,coerce:!0}),boolean:t=>Io.create({...t,coerce:!0}),bigint:t=>Oo.create({...t,coerce:!0}),date:t=>Ao.create({...t,coerce:!0})},Sq=J});var L={};G(L,{BRAND:()=>q2,DIRTY:()=>Ro,EMPTY_PATH:()=>v2,INVALID:()=>J,NEVER:()=>Sq,OK:()=>Ct,ParseStatus:()=>St,Schema:()=>ue,ZodAny:()=>Nn,ZodArray:()=>ln,ZodBigInt:()=>Oo,ZodBoolean:()=>Io,ZodBranded:()=>da,ZodCatch:()=>Fo,ZodDate:()=>Ao,ZodDefault:()=>Zo,ZodDiscriminatedUnion:()=>Vl,ZodEffects:()=>dr,ZodEnum:()=>qo,ZodError:()=>Gt,ZodFirstPartyTypeKind:()=>R,ZodFunction:()=>Jl,ZodIntersection:()=>Mo,ZodIssueCode:()=>T,ZodLazy:()=>Lo,ZodLiteral:()=>Do,ZodMap:()=>qs,ZodNaN:()=>Zs,ZodNativeEnum:()=>Uo,ZodNever:()=>Tr,ZodNull:()=>zo,ZodNullable:()=>Br,ZodNumber:()=>Co,ZodObject:()=>Wt,ZodOptional:()=>Vt,ZodParsedType:()=>z,ZodPipeline:()=>fa,ZodPromise:()=>zn,ZodReadonly:()=>Ho,ZodRecord:()=>Wl,ZodSchema:()=>ue,ZodSet:()=>Us,ZodString:()=>An,ZodSymbol:()=>Ls,ZodTransformer:()=>dr,ZodTuple:()=>Hr,ZodType:()=>ue,ZodUndefined:()=>No,ZodUnion:()=>jo,ZodUnknown:()=>cn,ZodVoid:()=>Ds,addIssueToContext:()=>N,any:()=>J2,array:()=>Q2,bigint:()=>H2,boolean:()=>$$,coerce:()=>xq,custom:()=>w$,date:()=>B2,datetimeRegex:()=>_$,defaultErrorMap:()=>sn,discriminatedUnion:()=>rq,effect:()=>mq,enum:()=>pq,function:()=>cq,getErrorMap:()=>zs,getParsedType:()=>Fr,instanceof:()=>Z2,intersection:()=>nq,isAborted:()=>Bl,isAsync:()=>js,isDirty:()=>Gl,isValid:()=>In,late:()=>U2,lazy:()=>lq,literal:()=>uq,makeIssue:()=>pa,map:()=>iq,nan:()=>F2,nativeEnum:()=>dq,never:()=>Y2,null:()=>W2,nullable:()=>gq,number:()=>S$,object:()=>eg,objectUtil:()=>Jh,oboolean:()=>wq,onumber:()=>bq,optional:()=>hq,ostring:()=>_q,pipeline:()=>vq,preprocess:()=>yq,promise:()=>fq,quotelessJson:()=>h2,record:()=>sq,set:()=>aq,setErrorMap:()=>y2,strictObject:()=>eq,string:()=>x$,symbol:()=>G2,transformer:()=>mq,tuple:()=>oq,undefined:()=>V2,union:()=>tq,unknown:()=>K2,util:()=>ye,void:()=>X2});var Kl=w(()=>{Hl();Yh();f$();ua();k$();Fl()});var ma=w(()=>{Kl()});var tg=w(()=>{Mt()});function rg(t,e){let r={type:"object",get shape(){return be.assignProp(this,"shape",{...t}),this.shape},...be.normalizeParams(e)};return new Tq(r)}var Eq,Tq,E$=w(()=>{Mt();Mt();tg();Eq=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)=>kf(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>So(t,r,n),t.parseAsync=async(r,n)=>Tf(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)}),Tq=E("ZodMiniObject",(t,e)=>{tl.init(t,e),Eq.init(t,e),be.defineLazy(t,"shape",()=>e.shape)})});var T$=w(()=>{});var P$=w(()=>{});var R$=w(()=>{});var C$=w(()=>{Mt();tg();E$();T$();Mt();nl();P$();R$()});var O$=w(()=>{C$()});var ng=w(()=>{O$()});function fr(t){return!!t._zod}function Bo(t){let e=Object.values(t);if(e.length===0)return rg({});let r=e.every(fr),n=e.every(o=>!fr(o));if(r)return rg(t);if(n)return eg(t);throw new Error("Mixed Zod versions detected in object shape.")}function jn(t,e){return fr(t)?So(t,e):t.safeParse(e)}async function Yl(t,e){return fr(t)?await $o(t,e):await t.safeParseAsync(e)}function Mn(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 Fs(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 Bo(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 Xl(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 A$(t){return t.description}function N$(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 Ql(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 ha=w(()=>{ma();ng()});function Ln(t){return t==="completed"||t==="failed"||t==="cancelled"}var z$=w(()=>{});var M$,j$,L$,eu=w(()=>{M$=Symbol("Let zodToJsonSchema decide on which parser to use"),j$={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"},L$=t=>typeof t=="string"?{...j$,name:t}:{...j$,...t}});var D$,og=w(()=>{eu();D$=t=>{let e=L$(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 sg(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function xe(t,e,r,n,o){t[e]=r,sg(t,e,n,o)}var Dn=w(()=>{});var tu,ru=w(()=>{tu=(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"?tu(e,t.currentPath):e.join("/")}}var mr=w(()=>{ru()});function q$(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==R.ZodAny&&(r.items=X(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 ig=w(()=>{ma();Dn();ct()});function U$(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 ag=w(()=>{Dn()});function Z$(){return{type:"boolean"}}var cg=w(()=>{});function nu(t,e){return X(t.type._def,e)}var ou=w(()=>{ct()});var F$,lg=w(()=>{ct();F$=(t,e)=>X(t.innerType._def,e)});function ug(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ug(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 Cq(t,e)}}var Cq,pg=w(()=>{Dn();Cq=(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 H$(t,e){return{...X(t.innerType._def,e),default:t.defaultValue()}}var dg=w(()=>{ct()});function B$(t,e){return e.effectStrategy==="input"?X(t.schema._def,e):Ke(e)}var fg=w(()=>{ct();mr()});function G$(t){return{type:"string",enum:Array.from(t.values)}}var mg=w(()=>{});function V$(t,e){let r=[X(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),X(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(Oq(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 Oq,hg=w(()=>{ct();Oq=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function W$(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 gg=w(()=>{});function su(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(`^${vg(n.value,e)}`),n.message,e);break;case"endsWith":Dt(r,RegExp(`${vg(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(vg(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 vg(t,e){return e.patternStrategy==="escape"?Aq(t):t}function Aq(t){let e="";for(let r=0;r<t.length;r++)Iq.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:J$(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):xe(t,"pattern",J$(e,n),r,n)}function J$(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
286
286
  ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
287
287
  ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
288
288
  `:`[${n[c]}\r
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]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(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();ct();ru();eu();mr()});function B$(t,e){if(e.mapStrategy==="record")return nu(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ke(e),n=X(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(()=>{ct();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(()=>{ct();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)=>X(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=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var _g=w(()=>{ct();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=X(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 X(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(()=>{ct()});var ek,xg=w(()=>{ct();mr();ek=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(e)},r]}:Ke(e)}});var tk,Sg=w(()=>{ct();tk=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(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 X(t.type._def,e)}var $g=w(()=>{ct()});function nk(t,e){let n={type:"array",uniqueItems:!0,items:X(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();ct()});function ok(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Eg=w(()=>{ct()});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(()=>{ct();ak=(t,e)=>X(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 X(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"?X(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,ct=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(()=>{ct();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]:X(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=X(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();ct();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(B.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(B.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(B.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(B.InvalidParams,`Task not found: ${r.params.taskId}`);if(zn(o.status))throw new q(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new q(B.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof q?o:new q(B.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),q.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),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(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Tn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:B.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=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(B.ConnectionClosed,"Request was cancelled");let d={...f,relatedRequestId:e.id};s&&!d.relatedTask&&(d.relatedTask={taskId:s});let m=d.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,d)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:B.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),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(B.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(B.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(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof q?i:new q(B.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=b=>{u(b)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){p(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(d.params={...d.params,task:a}),c&&(d.params={...d.params,_meta:{...d.params?._meta||{},[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(B.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=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(B.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(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new q(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new q(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new q(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=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(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(zn(a.status))throw new q(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=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(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.checkStrictMode=ge.getErrorPath=ge.Type=ge.useFunc=ge.setEvaluated=ge.evaluatedPropsToName=ge.mergeEvaluated=ge.eachItem=ge.unescapeJsonPointer=ge.escapeJsonPointer=ge.escapeFragment=ge.unescapeFragment=ge.schemaRefOrVal=ge.schemaHasRulesButRef=ge.schemaHasRules=ge.checkUnknownRules=ge.alwaysValidSchema=ge.toHash=void 0;var Me=pe(),Zq=ga();function Uq(t){let e={};for(let r of t)e[r]=!0;return e}ge.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))}ge.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}"`)}ge.checkUnknownRules=bk;function wk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ge.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}ge.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)}`}ge.schemaRefOrVal=Bq;function Gq(t){return xk(decodeURIComponent(t))}ge.unescapeFragment=Gq;function Vq(t){return encodeURIComponent(ty(t))}ge.escapeFragment=Vq;function ty(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ge.escapeJsonPointer=ty;function xk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ge.unescapeJsonPointer=xk;function Wq(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ge.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}}ge.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}ge.evaluatedPropsToName=Sk;function ry(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Me._)`${e}${(0,Me.getProperty)(n)}`,!0))}ge.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))})}ge.useFunc=Jq;var ey;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(ey||(ge.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)}ge.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)}}ge.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
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 yg,Pr,Iq,iu=w(()=>{Dn();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:()=>(yg===void 0&&(yg=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),yg),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-_]*$/};Iq=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function au(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===R.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ke(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:X(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===R.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=su(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===R.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===R.ZodBranded&&t.keyType._def.type._def.typeName===R.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=nu(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var cu=w(()=>{ma();ct();iu();ou();mr()});function K$(t,e){if(e.mapStrategy==="record")return au(t,e);let r=X(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ke(e),n=X(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 _g=w(()=>{ct();cu();mr()});function Y$(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 bg=w(()=>{});function X$(t){return t.target==="openAi"?void 0:{not:Ke({...t,currentPath:[...t.currentPath,"not"]})}}var wg=w(()=>{mr()});function Q$(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var xg=w(()=>{});function tk(t,e){if(e.target==="openApi3")return ek(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ga&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=ga[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 ek(t,e)}var ga,ek,lu=w(()=>{ct();ga={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};ek=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>X(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 rk(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:ga[t.innerType._def.typeName],nullable:!0}:{type:[ga[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=X(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Sg=w(()=>{ct();lu()});function nk(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",sg(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 $g=w(()=>{Dn()});function ok(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=zq(c);l&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),l=!1);let u=X(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=Nq(t,e);return i!==void 0&&(n.additionalProperties=i),n}function Nq(t,e){if(t.catchall._def.typeName!=="ZodNever")return X(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 zq(t){try{return t.isOptional()}catch{return!0}}var kg=w(()=>{ct()});var sk,Eg=w(()=>{ct();mr();sk=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return X(t.innerType._def,e);let r=X(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ke(e)},r]}:Ke(e)}});var ik,Tg=w(()=>{ct();ik=(t,e)=>{if(e.pipeStrategy==="input")return X(t.in._def,e);if(e.pipeStrategy==="output")return X(t.out._def,e);let r=X(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=X(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function ak(t,e){return X(t.type._def,e)}var Pg=w(()=>{ct()});function ck(t,e){let n={type:"array",uniqueItems:!0,items:X(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 Rg=w(()=>{Dn();ct()});function lk(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:X(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>X(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Cg=w(()=>{ct()});function uk(t){return{not:Ke(t)}}var Og=w(()=>{mr()});function pk(t){return Ke(t)}var Ig=w(()=>{mr()});var dk,Ag=w(()=>{ct();dk=(t,e)=>X(t.innerType._def,e)});var fk,Ng=w(()=>{ma();mr();ig();ag();cg();ou();lg();pg();dg();fg();mg();hg();gg();_g();bg();wg();xg();Sg();$g();kg();Eg();Tg();Pg();cu();Rg();iu();Cg();Og();lu();Ig();Ag();fk=(t,e,r)=>{switch(e){case R.ZodString:return su(t,r);case R.ZodNumber:return nk(t,r);case R.ZodObject:return ok(t,r);case R.ZodBigInt:return U$(t,r);case R.ZodBoolean:return Z$();case R.ZodDate:return ug(t,r);case R.ZodUndefined:return uk(r);case R.ZodNull:return Q$(r);case R.ZodArray:return q$(t,r);case R.ZodUnion:case R.ZodDiscriminatedUnion:return tk(t,r);case R.ZodIntersection:return V$(t,r);case R.ZodTuple:return lk(t,r);case R.ZodRecord:return au(t,r);case R.ZodLiteral:return W$(t,r);case R.ZodEnum:return G$(t);case R.ZodNativeEnum:return Y$(t);case R.ZodNullable:return rk(t,r);case R.ZodOptional:return sk(t,r);case R.ZodMap:return K$(t,r);case R.ZodSet:return ck(t,r);case R.ZodLazy:return()=>t.getter()._def;case R.ZodPromise:return ak(t,r);case R.ZodNaN:case R.ZodNever:return X$(r);case R.ZodEffects:return B$(t,r);case R.ZodAny:return Ke(r);case R.ZodUnknown:return pk(r);case R.ZodDefault:return H$(t,r);case R.ZodBranded:return nu(t,r);case R.ZodReadonly:return dk(t,r);case R.ZodCatch:return F$(t,r);case R.ZodPipeline:return ik(t,r);case R.ZodFunction:case R.ZodVoid:case R.ZodSymbol:return;default:return(n=>{})(e)}}});function X(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==M$)return a}if(n&&!r){let a=jq(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=fk(t,t.typeName,e),i=typeof s=="function"?X(s(),e):s;if(i&&Mq(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var jq,Mq,ct=w(()=>{eu();Ng();ru();mr();jq=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:tu(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}},Mq=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var mk=w(()=>{});var zg,jg=w(()=>{ct();og();mr();zg=(t,e)=>{let r=D$(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[l,u])=>({...c,[l]:X(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=X(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 hk=w(()=>{eu();og();Dn();ru();ct();mk();mr();ig();ag();cg();ou();lg();pg();dg();fg();mg();hg();gg();_g();bg();wg();xg();Sg();$g();kg();Eg();Tg();Pg();Ag();cu();Rg();iu();Cg();Og();lu();Ig();Ng();jg();jg()});function Lq(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Mg(t,e){return fr(t)?dh(t,{target:Lq(e?.target),io:e?.pipeStrategy??"input"}):zg(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Lg(t){let r=Mn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ql(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Dg(t,e){let r=jn(t,e);if(!r.success)throw r.error;return r.data}var qg=w(()=>{ng();ha();hk()});function gk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function yk(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];gk(i)&&gk(s)?r[o]={...i,...s}:r[o]=s}return r}var Dq,uu,vk=w(()=>{ha();Os();z$();qg();Dq=6e4,uu=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(yl,r=>{this._oncancel(r)}),this.setNotificationHandler(bl,r=>{this._onprogress(r)}),this.setRequestHandler(_l,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(wl,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(B.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Sl,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(B.InvalidParams,`Task not found: ${s}`);if(!Ln(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Ln(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Cn]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler($l,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(B.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(El,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new q(B.InvalidParams,`Task not found: ${r.params.taskId}`);if(Ln(o.status))throw new q(B.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new q(B.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof q?o:new q(B.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),q.fromError(B.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),on(s)||Ts(s)?this._onresponse(s):On(s)?this._onrequest(s,i):qS(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(B.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Cn]?.taskId;if(n===void 0){let u={jsonrpc:"2.0",id:e.id,error:{code:B.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:u,timestamp:Date.now()},o?.sessionId).catch(p=>this._onerror(new Error(`Failed to enqueue error response: ${p}`))):o?.send(u).catch(p=>this._onerror(new Error(`Failed to send an error response: ${p}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=MS(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(B.ConnectionClosed,"Request was cancelled");let d={...f,relatedRequestId:e.id};s&&!d.relatedTask&&(d.relatedTask={taskId:s});let m=d.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(u,p,d)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,l)).then(async u=>{if(i.signal.aborted)return;let p={result:u,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)},async u=>{if(i.signal.aborted)return;let p={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:B.InternalError,message:u.message??"Internal error",...u.data!==void 0&&{data:u.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:p,timestamp:Date.now()},o?.sessionId):await o?.send(p)}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),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(B.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Ps,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new q(B.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Ln(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(B.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new q(B.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(l=>setTimeout(l,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof q?i:new q(B.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((l,u)=>{let p=b=>{u(b)};if(!this._transport){p(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(b){p(b);return}n?.signal?.throwIfAborted();let f=this._requestMessageId++,d={...e,jsonrpc:"2.0",id:f};n?.onprogress&&(this._progressHandlers.set(f,n.onprogress),d.params={...e.params,_meta:{...e.params?._meta||{},progressToken:f}}),a&&(d.params={...d.params,task:a}),c&&(d.params={...d.params,_meta:{...d.params?._meta||{},[Cn]: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(B.RequestTimeout,String(b));u(x)};this._responseHandlers.set(f,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return u(b);try{let x=jn(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??Dq,y=()=>m(q.fromError(B.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},xl,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},kl,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ZS,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||{},[Cn]: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||{},[Cn]: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||{},[Cn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Lg(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Dg(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=Lg(e);this._notificationHandlers.set(n,o=>{let s=Dg(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"&&On(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new q(B.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new q(B.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new q(B.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new q(B.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=sa.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Ln(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(B.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Ln(a.status))throw new q(B.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let l=sa.parse({method:"notifications/tasks/status",params:c});await this.notification(l),Ln(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var _a=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 ya=class{};Pe._CodeOrName=ya;Pe.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Go=class extends ya{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=Go;var hr=class extends ya{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 Go&&(r[n.str]=(r[n.str]||0)+1),r),{})}};Pe._Code=hr;Pe.nil=new hr("");function _k(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Zg(r,e[n]),r.push(t[++n]);return new hr(r)}Pe._=_k;var Ug=new hr("+");function bk(t,...e){let r=[va(t[0])],n=0;for(;n<e.length;)r.push(Ug),Zg(r,e[n]),r.push(Ug,va(t[++n]));return qq(r),new hr(r)}Pe.str=bk;function Zg(t,e){e instanceof hr?t.push(...e._items):e instanceof Go?t.push(e):t.push(Fq(e))}Pe.addCodeArg=Zg;function qq(t){let e=1;for(;e<t.length-1;){if(t[e]===Ug){let r=Uq(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function Uq(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Go||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 Go))return`"${t}${e.slice(1)}`}function Zq(t,e){return e.emptyStr()?t:t.emptyStr()?e:bk`${t}${e}`}Pe.strConcat=Zq;function Fq(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:va(Array.isArray(t)?t.join(","):t)}function Hq(t){return new hr(va(t))}Pe.stringify=Hq;function va(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Pe.safeStringify=va;function Bq(t){return typeof t=="string"&&Pe.IDENTIFIER.test(t)?new hr(`.${t}`):_k`[${t}]`}Pe.getProperty=Bq;function Gq(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=Gq;function Vq(t){return new hr(t.toString())}Pe.regexpCode=Vq});var Bg=I(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.ValueScope=Kt.ValueScopeName=Kt.Scope=Kt.varKinds=Kt.UsedValueState=void 0;var Jt=_a(),Fg=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},pu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(pu||(Kt.UsedValueState=pu={}));Kt.varKinds={const:new Jt.Name("const"),let:new Jt.Name("let"),var:new Jt.Name("var")};var du=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=du;var fu=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=fu;var Wq=(0,Jt._)`\n`,Hg=class extends du{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?Wq:Jt.nil}}get(){return this._scope}name(e){return new fu(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,pu.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 Fg(l);c.set(l,pu.Completed)})}return s}};Kt.ValueScope=Hg});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=_a(),Cr=Bg(),qn=_a();Object.defineProperty(fe,"_",{enumerable:!0,get:function(){return qn._}});Object.defineProperty(fe,"str",{enumerable:!0,get:function(){return qn.str}});Object.defineProperty(fe,"strConcat",{enumerable:!0,get:function(){return qn.strConcat}});Object.defineProperty(fe,"nil",{enumerable:!0,get:function(){return qn.nil}});Object.defineProperty(fe,"getProperty",{enumerable:!0,get:function(){return qn.getProperty}});Object.defineProperty(fe,"stringify",{enumerable:!0,get:function(){return qn.stringify}});Object.defineProperty(fe,"regexpCode",{enumerable:!0,get:function(){return qn.regexpCode}});Object.defineProperty(fe,"Name",{enumerable:!0,get:function(){return qn.Name}});var yu=Bg();Object.defineProperty(fe,"Scope",{enumerable:!0,get:function(){return yu.Scope}});Object.defineProperty(fe,"ValueScope",{enumerable:!0,get:function(){return yu.ValueScope}});Object.defineProperty(fe,"ValueScopeName",{enumerable:!0,get:function(){return yu.ValueScopeName}});Object.defineProperty(fe,"varKinds",{enumerable:!0,get:function(){return yu.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}},Gg=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?Cr.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=Bs(this.rhs,e,r)),this}get names(){return this.rhs instanceof Se._CodeOrName?this.rhs.names:{}}},mu=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=Bs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof Se.Name?{}:{...this.lhs.names};return gu(e,this.rhs)}},Vg=class extends mu{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wg=class extends un{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Jg=class extends un{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Kg=class extends un{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Yg=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=Bs(this.code,e,r),this}get names(){return this.code instanceof Se._CodeOrName?this.code.names:{}}},ba=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)=>Jo(e,r.names),{})}},pn=class extends ba{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Xg=class extends ba{},Hs=class extends pn{};Hs.kind="else";var Vo=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 Hs(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(wk(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=Bs(this.condition,e,r),this}get names(){let e=super.names;return gu(e,this.condition),this.else&&Jo(e,this.else.names),e}};Vo.kind="if";var Wo=class extends pn{};Wo.kind="for";var Qg=class extends Wo{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=Bs(this.iteration,e,r),this}get names(){return Jo(super.names,this.iteration.names)}},ey=class extends Wo{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Cr.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=gu(super.names,this.from);return gu(e,this.to)}},hu=class extends Wo{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=Bs(this.iterable,e,r),this}get names(){return Jo(super.names,this.iterable.names)}},wa=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)}};wa.kind="func";var xa=class extends ba{render(e){return"return "+super.render(e)}};xa.kind="return";var ty=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&&Jo(e,this.catch.names),this.finally&&Jo(e,this.finally.names),e}},Sa=class extends pn{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Sa.kind="catch";var $a=class extends pn{render(e){return"finally"+super.render(e)}};$a.kind="finally";var ry=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
290
+ `:""},this._extScope=e,this._scope=new Cr.Scope({parent:e}),this._nodes=[new Xg]}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 Gg(e,s,n)),s}const(e,r,n){return this._def(Cr.varKinds.const,e,r,n)}let(e,r,n){return this._def(Cr.varKinds.let,e,r,n)}var(e,r,n){return this._def(Cr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new mu(e,r,n))}add(e,r){return this._leafNode(new Vg(e,fe.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==Se.nil&&this._leafNode(new Yg(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 Vo(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 Vo(e))}else(){return this._elseNode(new Hs)}endIf(){return this._endBlockNode(Vo,Hs)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Qg(e),r)}forRange(e,r,n,o,s=this.opts.es5?Cr.varKinds.var:Cr.varKinds.let){let i=this._scope.toName(e);return this._for(new ey(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Cr.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 hu("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Cr.varKinds.var:Cr.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 hu("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(Wo)}label(e){return this._leafNode(new Wg(e))}break(e){return this._leafNode(new Jg(e))}return(e){let r=new xa;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(xa)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let o=new ty;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new Sa(s),r(s)}return n&&(this._currNode=o.finally=new $a,this.code(n)),this._endBlockNode(Sa,$a)}throw(e){return this._leafNode(new Kg(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 wa(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(wa)}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 Vo))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=ry;function Jo(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function gu(t,e){return e instanceof Se._CodeOrName?Jo(t,e.names):t}function Bs(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 wk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,Se._)`!${ny(t)}`}fe.not=wk;var Kq=xk(fe.operators.AND);function Yq(...t){return t.reduce(Kq)}fe.and=Yq;var Xq=xk(fe.operators.OR);function Qq(...t){return t.reduce(Xq)}fe.or=Qq;function xk(t){return(e,r)=>e===Se.nil?r:r===Se.nil?e:(0,Se._)`${ny(e)} ${t} ${ny(r)}`}function ny(t){return t instanceof Se.Name?t:(0,Se._)`(${t})`}});var Re=I(ge=>{"use strict";Object.defineProperty(ge,"__esModule",{value:!0});ge.checkStrictMode=ge.getErrorPath=ge.Type=ge.useFunc=ge.setEvaluated=ge.evaluatedPropsToName=ge.mergeEvaluated=ge.eachItem=ge.unescapeJsonPointer=ge.escapeJsonPointer=ge.escapeFragment=ge.unescapeFragment=ge.schemaRefOrVal=ge.schemaHasRulesButRef=ge.schemaHasRules=ge.checkUnknownRules=ge.alwaysValidSchema=ge.toHash=void 0;var Me=pe(),eU=_a();function tU(t){let e={};for(let r of t)e[r]=!0;return e}ge.toHash=tU;function rU(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(kk(t,e),!Ek(e,t.self.RULES.all))}ge.alwaysValidSchema=rU;function kk(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]||Rk(t,`unknown keyword: "${s}"`)}ge.checkUnknownRules=kk;function Ek(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ge.schemaHasRules=Ek;function nU(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ge.schemaHasRulesButRef=nU;function oU({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)}`}ge.schemaRefOrVal=oU;function sU(t){return Tk(decodeURIComponent(t))}ge.unescapeFragment=sU;function iU(t){return encodeURIComponent(sy(t))}ge.escapeFragment=iU;function sy(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ge.escapeJsonPointer=sy;function Tk(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ge.unescapeJsonPointer=Tk;function aU(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ge.eachItem=aU;function Sk({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}}ge.mergeEvaluated={props:Sk({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} || {}`),iy(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Pk}),items:Sk({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 Pk(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Me._)`{}`);return e!==void 0&&iy(t,r,e),r}ge.evaluatedPropsToName=Pk;function iy(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Me._)`${e}${(0,Me.getProperty)(n)}`,!0))}ge.setEvaluated=iy;var $k={};function cU(t,e){return t.scopeValue("func",{ref:e,code:$k[e.code]||($k[e.code]=new eU._Code(e.code))})}ge.useFunc=cU;var oy;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(oy||(ge.Type=oy={}));function lU(t,e,r){if(t instanceof Me.Name){let n=e===oy.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():"/"+sy(t)}ge.getErrorPath=lU;function Rk(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ge.checkStrictMode=Rk});var dn=I(ay=>{"use strict";Object.defineProperty(ay,"__esModule",{value:!0});var Ot=pe(),uU={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")};ay.default=uU});var ka=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 ke=pe(),vu=Re(),qt=dn();It.keywordError={message:({keyword:t})=>(0,ke.str)`must pass "${t}" keyword validation`};It.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,ke.str)`"${t}" keyword must be ${e} ($data)`:(0,ke.str)`"${t}" keyword is invalid ($data)`};function pU(t,e=It.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Ik(t,e,r);n??(i||a)?Ck(s,c):Ok(o,(0,ke._)`[${c}]`)}It.reportError=pU;function dU(t,e=It.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Ik(t,e,r);Ck(o,a),s||i||Ok(n,qt.default.vErrors)}It.reportExtraError=dU;function fU(t,e){t.assign(qt.default.errors,e),t.if((0,ke._)`${qt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,ke._)`${qt.default.vErrors}.length`,e),()=>t.assign(qt.default.vErrors,null)))}It.resetErrorsCount=fU;function mU({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,ke._)`${qt.default.vErrors}[${a}]`),t.if((0,ke._)`${i}.instancePath === undefined`,()=>t.assign((0,ke._)`${i}.instancePath`,(0,ke.strConcat)(qt.default.instancePath,s.errorPath))),t.assign((0,ke._)`${i}.schemaPath`,(0,ke.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,ke._)`${i}.schema`,r),t.assign((0,ke._)`${i}.data`,n))})}It.extendErrors=mU;function Ck(t,e){let r=t.const("err",e);t.if((0,ke._)`${qt.default.vErrors} === null`,()=>t.assign(qt.default.vErrors,(0,ke._)`[${r}]`),(0,ke._)`${qt.default.vErrors}.push(${r})`),t.code((0,ke._)`${qt.default.errors}++`)}function Ok(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,ke._)`new ${t.ValidationError}(${e})`):(r.assign((0,ke._)`${n}.errors`,e),r.return(!1))}var Ko={keyword:new ke.Name("keyword"),schemaPath:new ke.Name("schemaPath"),params:new ke.Name("params"),propertyName:new ke.Name("propertyName"),message:new ke.Name("message"),schema:new ke.Name("schema"),parentSchema:new ke.Name("parentSchema")};function Ik(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,ke._)`{}`:hU(t,e,r)}function hU(t,e,r={}){let{gen:n,it:o}=t,s=[gU(o,r),yU(t,r)];return vU(t,e,s),n.object(...s)}function gU({errorPath:t},{instancePath:e}){let r=e?(0,ke.str)`${t}${(0,vu.getErrorPath)(e,vu.Type.Str)}`:t;return[qt.default.instancePath,(0,ke.strConcat)(qt.default.instancePath,r)]}function yU({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,ke.str)`${e}/${t}`;return r&&(o=(0,ke.str)`${o}${(0,vu.getErrorPath)(r,vu.Type.Str)}`),[Ko.schemaPath,o]}function vU(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([Ko.keyword,o],[Ko.params,typeof e=="function"?e(t):e||(0,ke._)`{}`]),c.messages&&n.push([Ko.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Ko.schema,i],[Ko.parentSchema,(0,ke._)`${u}${p}`],[qt.default.data,s]),l&&n.push([Ko.propertyName,l])}});var Nk=I(Gs=>{"use strict";Object.defineProperty(Gs,"__esModule",{value:!0});Gs.boolOrEmptySchema=Gs.topBoolOrEmptySchema=void 0;var _U=ka(),bU=pe(),wU=dn(),xU={message:"boolean schema is false"};function SU(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ak(t,!1):typeof r=="object"&&r.$async===!0?e.return(wU.default.data):(e.assign((0,bU._)`${n}.errors`,null),e.return(!0))}Gs.topBoolOrEmptySchema=SU;function $U(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ak(t)):r.var(e,!0)}Gs.boolOrEmptySchema=$U;function Ak(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,_U.reportError)(o,xU,void 0,e)}});var cy=I(Vs=>{"use strict";Object.defineProperty(Vs,"__esModule",{value:!0});Vs.getRules=Vs.isJSONType=void 0;var kU=["string","number","integer","boolean","null","object","array"],EU=new Set(kU);function TU(t){return typeof t=="string"&&EU.has(t)}Vs.isJSONType=TU;function PU(){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:{}}}Vs.getRules=PU});var ly=I(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.shouldUseRule=Un.shouldUseGroup=Un.schemaHasRulesForType=void 0;function RU({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&zk(t,n)}Un.schemaHasRulesForType=RU;function zk(t,e){return e.rules.some(r=>jk(t,r))}Un.shouldUseGroup=zk;function jk(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))}Un.shouldUseRule=jk});var Ea=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 CU=cy(),OU=ly(),IU=ka(),ce=pe(),Mk=Re(),Ws;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ws||(At.DataType=Ws={}));function AU(t){let e=Lk(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=AU;function Lk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(CU.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}At.getJSONTypes=Lk;function NU(t,e){let{gen:r,data:n,opts:o}=t,s=zU(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,OU.schemaHasRulesForType)(t,e[0]));if(i){let a=py(e,n,o.strictNumbers,Ws.Wrong);r.if(a,()=>{s.length?jU(t,e,s):dy(t)})}return i}At.coerceAndCheckDataType=NU;var Dk=new Set(["string","number","integer","boolean","null"]);function zU(t,e){return e?t.filter(r=>Dk.has(r)||e==="array"&&r==="array"):[]}function jU(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(py(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,ce._)`${a} !== undefined`);for(let l of r)(Dk.has(l)||l==="array"&&s.coerceTypes==="array")&&c(l);n.else(),dy(t),n.endIf(),n.if((0,ce._)`${a} !== undefined`,()=>{n.assign(o,a),MU(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
291
291
  || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,ce._)`+${o}`);return;case"integer":n.elseIf((0,ce._)`${i} === "boolean" || ${o} === null
292
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"
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(),re=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._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{t.code((0,U._)`"use strict"; ${Yk(r,o)}`),dU(t,o),t.code(s)}):t.func(e,(0,U._)`${re.default.data}, ${pU(o)}`,n.$async,()=>t.code(Yk(r,o)).code(s))}function pU(t){return(0,U._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${t.dynamicRef?(0,U._)`, ${re.default.dynamicAnchors}={}`:U.nil}}={}`}function dU(t,e){t.if(re.default.valCxt,()=>{t.var(re.default.instancePath,(0,U._)`${re.default.valCxt}.${re.default.instancePath}`),t.var(re.default.parentData,(0,U._)`${re.default.valCxt}.${re.default.parentData}`),t.var(re.default.parentDataProperty,(0,U._)`${re.default.valCxt}.${re.default.parentDataProperty}`),t.var(re.default.rootData,(0,U._)`${re.default.valCxt}.${re.default.rootData}`),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,U._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{t.var(re.default.instancePath,(0,U._)`""`),t.var(re.default.parentData,(0,U._)`undefined`),t.var(re.default.parentDataProperty,(0,U._)`undefined`),t.var(re.default.rootData,re.default.data),e.dynamicRef&&t.var(re.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(re.default.vErrors,null),n.let(re.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",re.default.errors);sE(t,s),n.var(e,(0,U._)`${s} === ${re.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._)`${re.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._)`${re.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._)`${re.default.errors} === 0`,()=>e.return(re.default.data),()=>e.throw((0,U._)`new ${o}(${re.default.vErrors})`)):(e.assign((0,U._)`${n}.errors`,re.default.vErrors),s.unevaluated&&xU(t),e.return((0,U._)`${re.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._)`${re.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",re.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 re.default.rootData;if(t[0]==="/"){if(!RU.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=re.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,Q,te,de;let K=t.strict,G=(e=t.code)===null||e===void 0?void 0:e.optimize,ot=G===!0||G===void 0?1:G||0,Et=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:IE,ne=(o=t.uriResolver)!==null&&o!==void 0?o:bF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:K)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:K)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:K)!==null&&u!==void 0?u:"log",strictTuples:(f=(p=t.strictTuples)!==null&&p!==void 0?p:K)!==null&&f!==void 0?f:"log",strictRequired:(m=(d=t.strictRequired)!==null&&d!==void 0?d:K)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ot,regExp:Et}:{optimize:ot,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:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(te=t.unicodeRegExp)!==null&&te!==void 0?te:!0,int32range:(de=t.int32range)!==null&&de!==void 0?de:!0,uriResolver:ne}}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
+ || ${i} === "boolean" || ${o} === null`).assign(a,(0,ce._)`[${o}]`)}}}function MU({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ce._)`${e} !== undefined`,()=>t.assign((0,ce._)`${e}[${r}]`,n))}function uy(t,e,r,n=Ws.Correct){let o=n===Ws.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===Ws.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=uy;function py(t,e,r,n){if(t.length===1)return uy(t[0],e,r,n);let o,s=(0,Mk.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,uy(i,e,r,n));return o}At.checkDataTypes=py;var LU={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ce._)`{type: ${t}}`:(0,ce._)`{type: ${e}}`};function dy(t){let e=DU(t);(0,IU.reportError)(e,LU)}At.reportTypeError=dy;function DU(t){let{gen:e,data:r,schema:n}=t,o=(0,Mk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Uk=I(_u=>{"use strict";Object.defineProperty(_u,"__esModule",{value:!0});_u.assignDefaults=void 0;var Js=pe(),qU=Re();function UU(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)qk(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>qk(t,s,o.default))}_u.assignDefaults=UU;function qk(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Js._)`${s}${(0,Js.getProperty)(e)}`;if(o){(0,qU.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Js._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Js._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Js._)`${a} = ${(0,Js.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(),fy=Re(),Zn=dn(),ZU=Re();function FU(t,e){let{gen:r,data:n,it:o}=t;r.if(hy(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,He._)`${e}`},!0),t.error()})}Ne.checkReportMissingProp=FU;function HU({gen:t,data:e,it:{opts:r}},n,o){return(0,He.or)(...n.map(s=>(0,He.and)(hy(t,e,s,r.ownProperties),(0,He._)`${o} = ${s}`)))}Ne.checkMissingProp=HU;function BU(t,e){t.setParams({missingProperty:e},!0),t.error()}Ne.reportMissingProp=BU;function Zk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,He._)`Object.prototype.hasOwnProperty`})}Ne.hasPropFunc=Zk;function my(t,e,r){return(0,He._)`${Zk(t)}.call(${e}, ${r})`}Ne.isOwnProperty=my;function GU(t,e,r,n){let o=(0,He._)`${e}${(0,He.getProperty)(r)} !== undefined`;return n?(0,He._)`${o} && ${my(t,e,r)}`:o}Ne.propertyInData=GU;function hy(t,e,r,n){let o=(0,He._)`${e}${(0,He.getProperty)(r)} === undefined`;return n?(0,He.or)(o,(0,He.not)(my(t,e,r))):o}Ne.noPropertyInData=hy;function Fk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}Ne.allSchemaProperties=Fk;function VU(t,e){return Fk(e).filter(r=>!(0,fy.alwaysValidSchema)(t,e[r]))}Ne.schemaProperties=VU;function WU({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=[[Zn.default.instancePath,(0,He.strConcat)(Zn.default.instancePath,s)],[Zn.default.parentData,i.parentData],[Zn.default.parentDataProperty,i.parentDataProperty],[Zn.default.rootData,Zn.default.rootData]];i.opts.dynamicRef&&p.push([Zn.default.dynamicAnchors,Zn.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=WU;var JU=(0,He._)`new RegExp`;function KU({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"?JU:(0,ZU.useFunc)(t,o)}(${r}, ${n})`})}Ne.usePattern=KU;function YU(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:fy.Type.Num},s),e.if((0,He.not)(s),a)})}}Ne.validateArray=YU;function XU(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,fy.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=XU});var Gk=I(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.validateKeywordUsage=Gr.validSchemaType=Gr.funcKeywordCode=Gr.macroKeywordCode=void 0;var Ut=pe(),Yo=dn(),QU=gr(),eZ=ka();function tZ(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Bk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let l=r.name("valid");t.subschema({schema:a,schemaPath:Ut.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},l),t.pass(l,()=>t.error(!0))}Gr.macroKeywordCode=tZ;function rZ(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;oZ(c,e);let l=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,u=Bk(n,o,l),p=n.let("valid");t.block$data(p,f),t.ok((r=e.valid)!==null&&r!==void 0?r:p);function f(){if(e.errors===!1)h(),e.modifying&&Hk(t),y(()=>t.error());else{let v=e.async?d():m();e.modifying&&Hk(t),y(()=>nZ(t,v))}}function d(){let v=n.let("ruleErrs",null);return n.try(()=>h((0,Ut._)`await `),b=>n.assign(p,!1).if((0,Ut._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(v,(0,Ut._)`${b}.errors`),()=>n.throw(b))),v}function m(){let v=(0,Ut._)`${u}.errors`;return n.assign(v,null),h(Ut.nil),v}function h(v=e.async?(0,Ut._)`await `:Ut.nil){let b=c.opts.passContext?Yo.default.this:Yo.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(p,(0,Ut._)`${v}${(0,QU.callValidateCode)(t,u,b,x)}`,e.modifying)}function y(v){var b;n.if((0,Ut.not)((b=e.valid)!==null&&b!==void 0?b:p),v)}}Gr.funcKeywordCode=rZ;function Hk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,Ut._)`${n.parentData}[${n.parentDataProperty}]`))}function nZ(t,e){let{gen:r}=t;r.if((0,Ut._)`Array.isArray(${e})`,()=>{r.assign(Yo.default.vErrors,(0,Ut._)`${Yo.default.vErrors} === null ? ${e} : ${Yo.default.vErrors}.concat(${e})`).assign(Yo.default.errors,(0,Ut._)`${Yo.default.vErrors}.length`),(0,eZ.extendErrors)(t)},()=>t.error())}function oZ({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Bk(t,e,r){if(r===void 0)throw new Error(`keyword "${e}" failed to compile`);return t.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Ut.stringify)(r)})}function sZ(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=sZ;function iZ({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=iZ});var Wk=I(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.extendSubschemaMode=Fn.extendSubschemaData=Fn.getSubschema=void 0;var Vr=pe(),Vk=Re();function aZ(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,Vk.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')}Fn.getSubschema=aZ;function cZ(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,Vk.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]}}Fn.extendSubschemaData=cZ;function lZ(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}Fn.extendSubschemaMode=lZ});var gy=I(($Q,Jk)=>{"use strict";Jk.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 Yk=I((kQ,Kk)=>{"use strict";var Hn=Kk.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};bu(e,n,o,t,"",t)};Hn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Hn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Hn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Hn.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 bu(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 Hn.arrayKeywords)for(var f=0;f<p.length;f++)bu(t,e,r,p[f],o+"/"+u+"/"+f,s,o,u,n,f)}else if(u in Hn.propsKeywords){if(p&&typeof p=="object")for(var d in p)bu(t,e,r,p[d],o+"/"+u+"/"+uZ(d),s,o,u,n,d)}else(u in Hn.keywords||t.allKeys&&!(u in Hn.skipKeywords))&&bu(t,e,r,p,o+"/"+u,s,o,u,n)}r(n,o,s,i,a,c,l)}}function uZ(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ta=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 pZ=Re(),dZ=gy(),fZ=Yk(),mZ=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function hZ(t,e=!0){return typeof t=="boolean"?!0:e===!0?!yy(t):e?Xk(t)<=e:!1}Yt.inlineRef=hZ;var gZ=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function yy(t){for(let e in t){if(gZ.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(yy)||typeof r=="object"&&yy(r))return!0}return!1}function Xk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!mZ.has(r)&&(typeof t[r]=="object"&&(0,pZ.eachItem)(t[r],n=>e+=Xk(n)),e===1/0))return 1/0}return e}function Qk(t,e="",r){r!==!1&&(e=Ks(e));let n=t.parse(e);return eE(t,n)}Yt.getFullPath=Qk;function eE(t,e){return t.serialize(e).split("#")[0]+"#"}Yt._getFullPath=eE;var yZ=/#\/?$/;function Ks(t){return t?t.replace(yZ,""):""}Yt.normalizeId=Ks;function vZ(t,e,r){return r=Ks(r),t.resolve(e,r)}Yt.resolveUrl=vZ;var _Z=/^[a-z_][-a-z0-9._]*$/i;function bZ(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Ks(t[r]||e),s={"":o},i=Qk(n,o,!1),a={},c=new Set;return fZ(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=Ks(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!==Ks(h)&&(x[0]==="#"?(l(p,a[x],x),a[x]=p):this.refs[x]=h),x}function b(x){if(typeof x=="string"){if(!_Z.test(x))throw new Error(`invalid anchor "${x}"`);v.call(this,`#${x}`)}}}),a;function l(p,f,d){if(f!==void 0&&!dZ(p,f))throw u(d)}function u(p){return new Error(`reference "${p}" resolves to more than one schema`)}}Yt.getSchemaRefs=bZ});var Ca=I(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.getData=Bn.KeywordCxt=Bn.validateFunctionCode=void 0;var sE=Nk(),tE=Ea(),_y=ly(),wu=Ea(),wZ=Uk(),Ra=Gk(),vy=Wk(),Z=pe(),re=dn(),xZ=Ta(),fn=Re(),Pa=ka();function SZ(t){if(cE(t)&&(lE(t),aE(t))){EZ(t);return}iE(t,()=>(0,sE.topBoolOrEmptySchema)(t))}Bn.validateFunctionCode=SZ;function iE({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,Z._)`${re.default.data}, ${re.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${rE(r,o)}`),kZ(t,o),t.code(s)}):t.func(e,(0,Z._)`${re.default.data}, ${$Z(o)}`,n.$async,()=>t.code(rE(r,o)).code(s))}function $Z(t){return(0,Z._)`{${re.default.instancePath}="", ${re.default.parentData}, ${re.default.parentDataProperty}, ${re.default.rootData}=${re.default.data}${t.dynamicRef?(0,Z._)`, ${re.default.dynamicAnchors}={}`:Z.nil}}={}`}function kZ(t,e){t.if(re.default.valCxt,()=>{t.var(re.default.instancePath,(0,Z._)`${re.default.valCxt}.${re.default.instancePath}`),t.var(re.default.parentData,(0,Z._)`${re.default.valCxt}.${re.default.parentData}`),t.var(re.default.parentDataProperty,(0,Z._)`${re.default.valCxt}.${re.default.parentDataProperty}`),t.var(re.default.rootData,(0,Z._)`${re.default.valCxt}.${re.default.rootData}`),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,Z._)`${re.default.valCxt}.${re.default.dynamicAnchors}`)},()=>{t.var(re.default.instancePath,(0,Z._)`""`),t.var(re.default.parentData,(0,Z._)`undefined`),t.var(re.default.parentDataProperty,(0,Z._)`undefined`),t.var(re.default.rootData,re.default.data),e.dynamicRef&&t.var(re.default.dynamicAnchors,(0,Z._)`{}`)})}function EZ(t){let{schema:e,opts:r,gen:n}=t;iE(t,()=>{r.$comment&&e.$comment&&pE(t),OZ(t),n.let(re.default.vErrors,null),n.let(re.default.errors,0),r.unevaluated&&TZ(t),uE(t),NZ(t)})}function TZ(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function rE(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function PZ(t,e){if(cE(t)&&(lE(t),aE(t))){RZ(t,e);return}(0,sE.boolOrEmptySchema)(t,e)}function aE({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 cE(t){return typeof t.schema!="boolean"}function RZ(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&pE(t),IZ(t),AZ(t);let s=n.const("_errs",re.default.errors);uE(t,s),n.var(e,(0,Z._)`${s} === ${re.default.errors}`)}function lE(t){(0,fn.checkUnknownRules)(t),CZ(t)}function uE(t,e){if(t.opts.jtd)return nE(t,[],!1,e);let r=(0,tE.getSchemaTypes)(t.schema),n=(0,tE.coerceAndCheckDataType)(t,r);nE(t,r,!n,e)}function CZ(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 OZ(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 IZ(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,xZ.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function AZ(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function pE({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,Z._)`${re.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${re.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function NZ(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,Z._)`${re.default.errors} === 0`,()=>e.return(re.default.data),()=>e.throw((0,Z._)`new ${o}(${re.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,re.default.vErrors),s.unevaluated&&zZ(t),e.return((0,Z._)`${re.default.errors} === 0`))}function zZ({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function nE(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(()=>fE(t,"$ref",u.all.$ref.definition));return}c.jtd||jZ(t,e),o.block(()=>{for(let f of u.rules)p(f);p(u.post)});function p(f){(0,_y.shouldUseGroup)(s,f)&&(f.type?(o.if((0,wu.checkDataType)(f.type,i,c.strictNumbers)),oE(t,f),e.length===1&&e[0]===f.type&&r&&(o.else(),(0,wu.reportTypeError)(t)),o.endIf()):oE(t,f),a||o.if((0,Z._)`${re.default.errors} === ${n||0}`))}}function oE(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,wZ.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,_y.shouldUseRule)(n,s)&&fE(t,s.keyword,s.definition,e.type)})}function jZ(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(MZ(t,e),t.opts.allowUnionTypes||LZ(t,e),DZ(t,t.dataTypes))}function MZ(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{dE(t.dataTypes,r)||by(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),UZ(t,e)}}function LZ(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&by(t,"use allowUnionTypes to allow union type keyword")}function DZ(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,_y.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>qZ(e,i))&&by(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function qZ(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function dE(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function UZ(t,e){let r=[];for(let n of t.dataTypes)dE(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function by(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,fn.checkStrictMode)(t,e,t.opts.strictTypes)}var xu=class{constructor(e,r,n){if((0,Ra.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",mE(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ra.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=e.gen.const("_errs",re.default.errors))}result(e,r,n){this.failResult((0,Z.not)(e),r,n)}failResult(e,r,n){this.gen.if(e),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,r){this.failResult((0,Z.not)(e),void 0,r)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:r}=this;this.fail((0,Z._)`${r} !== undefined && (${(0,Z.or)(this.invalid$data(),e)})`)}error(e,r,n){if(r){this.setParams(r),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,r){(e?Pa.reportExtraError:Pa.reportError)(this,this.def.error,r)}$dataError(){(0,Pa.reportError)(this,this.def.$dataError||Pa.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Pa.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,r){r?Object.assign(this.params,e):this.params=e}block$data(e,r,n=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,Z.or)((0,Z._)`${o} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,wu.checkDataTypes)(c,r,s.opts.strictNumbers,wu.DataType.Wrong)}`}return Z.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,vy.getSubschema)(this.it,e);(0,vy.extendSubschemaData)(n,this.it,e),(0,vy.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return PZ(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,Z.Name)),!0}};Bn.KeywordCxt=xu;function fE(t,e,r,n){let o=new xu(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,Ra.funcKeywordCode)(o,r):"macro"in r?(0,Ra.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,Ra.funcKeywordCode)(o,r)}var ZZ=/^\/(?:[^~]|~0|~1)*$/,FZ=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function mE(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return re.default.rootData;if(t[0]==="/"){if(!ZZ.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=re.default.rootData}else{let l=FZ.exec(t);if(!l)throw new Error(`Invalid JSON-pointer: ${t}`);let u=+l[1];if(o=l[2],o==="#"){if(u>=e)throw new Error(c("property/index",u));return n[e-u]}if(u>e)throw new Error(c("data",u));if(s=r[e-u],!o)return s}let i=s,a=o.split("/");for(let l of a)l&&(s=(0,Z._)`${s}${(0,Z.getProperty)((0,fn.unescapeJsonPointer)(l))}`,i=(0,Z._)`${i} && ${s}`);return i;function c(l,u){return`Cannot access ${l} ${u} levels up, current level is ${e}`}}Bn.getData=mE});var Su=I(xy=>{"use strict";Object.defineProperty(xy,"__esModule",{value:!0});var wy=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};xy.default=wy});var Oa=I(ky=>{"use strict";Object.defineProperty(ky,"__esModule",{value:!0});var Sy=Ta(),$y=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Sy.resolveUrl)(e,r,n),this.missingSchema=(0,Sy.normalizeId)((0,Sy.getFullPath)(e,this.missingRef))}};ky.default=$y});var ku=I(yr=>{"use strict";Object.defineProperty(yr,"__esModule",{value:!0});yr.resolveSchema=yr.getCompilingSchema=yr.resolveRef=yr.compileSchema=yr.SchemaEnv=void 0;var Or=pe(),HZ=Su(),Xo=dn(),Ir=Ta(),hE=Re(),BZ=Ca(),Ys=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=Ys;function Ty(t){let e=gE.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 Or.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:HZ.default,code:(0,Or._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let l={gen:i,allErrors:this.opts.allErrors,data:Xo.default.data,parentData:Xo.default.parentData,parentDataProperty:Xo.default.parentDataProperty,dataNames:[Xo.default.data],dataPathArr:[Or.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Or.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Or.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Or._)`""`,opts:this.opts,self:this},u;try{this._compilations.add(t),(0,BZ.validateFunctionCode)(l),i.optimize(this.opts.code.optimize);let p=i.toString();u=`${i.scopeRefs(Xo.default.scope)}return ${p}`,this.opts.code.process&&(u=this.opts.code.process(u,t));let d=new Function(`${Xo.default.self}`,`${Xo.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 Or.Name?void 0:m,items:h instanceof Or.Name?void 0:h,dynamicProps:m instanceof Or.Name,dynamicItems:h instanceof Or.Name},d.source&&(d.source.evaluated=(0,Or.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=Ty;function GZ(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=JZ.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 Ys({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=VZ.call(this,s)}yr.resolveRef=GZ;function VZ(t){return(0,Ir.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:Ty.call(this,t)}function gE(t){for(let e of this._compilations)if(WZ(e,t))return e}yr.getCompilingSchema=gE;function WZ(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function JZ(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||$u.call(this,t,e)}function $u(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 Ey.call(this,r,t);let s=(0,Ir.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=$u.call(this,t,i);return typeof a?.schema!="object"?void 0:Ey.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||Ty.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 Ys({schema:a,schemaId:c,root:t,baseId:o})}return Ey.call(this,r,i)}}yr.resolveSchema=$u;var KZ=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Ey(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,hE.unescapeFragment)(a)];if(c===void 0)return;r=c;let l=typeof r=="object"&&r[this.opts.schemaId];!KZ.has(a)&&l&&(e=(0,Ir.resolveUrl)(this.opts.uriResolver,e,l))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,hE.schemaHasRulesButRef)(r,this.RULES)){let a=(0,Ir.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=$u.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Ys({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var yE=I((OQ,YZ)=>{YZ.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 Ry=I((IQ,wE)=>{"use strict";var XZ=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),_E=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 Py(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 QZ=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function vE(t){return t.length=0,!0}function eF(t,e,r){if(t.length){let n=Py(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function tF(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=eF;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=vE}else{o.push(l);continue}}return o.length&&(a===vE?r.zone=o.join(""):i?n.push(o.join("")):n.push(Py(o))),r.address=n.join(""),r}function bE(t){if(rF(t,":")<2)return{host:t,isIPV6:!1};let e=tF(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 rF(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function nF(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 oF(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 sF(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!_E(r)){let n=bE(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}wE.exports={nonSimpleDomain:QZ,recomposeAuthority:sF,normalizeComponentEncoding:oF,removeDotSegments:nF,isIPv4:_E,isUUID:XZ,normalizeIPv6:bE,stringArrayToHexStripped:Py}});var EE=I((AQ,kE)=>{"use strict";var{isUUID:iF}=Ry(),aF=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,cF=["http","https","ws","wss","urn","urn:uuid"];function lF(t){return cF.indexOf(t)!==-1}function Cy(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 xE(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function SE(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 uF(t){return t.secure=Cy(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function pF(t){if((t.port===(Cy(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 dF(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(aF);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=Oy(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function fF(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=Oy(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 mF(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!iF(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function hF(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var $E={scheme:"http",domainHost:!0,parse:xE,serialize:SE},gF={scheme:"https",domainHost:$E.domainHost,parse:xE,serialize:SE},Eu={scheme:"ws",domainHost:!0,parse:uF,serialize:pF},yF={scheme:"wss",domainHost:Eu.domainHost,parse:Eu.parse,serialize:Eu.serialize},vF={scheme:"urn",parse:dF,serialize:fF,skipNormalize:!0},_F={scheme:"urn:uuid",parse:mF,serialize:hF,skipNormalize:!0},Tu={http:$E,https:gF,ws:Eu,wss:yF,urn:vF,"urn:uuid":_F};Object.setPrototypeOf(Tu,null);function Oy(t){return t&&(Tu[t]||Tu[t.toLowerCase()])||void 0}kE.exports={wsIsSecure:Cy,SCHEMES:Tu,isValidSchemeName:lF,getSchemeHandler:Oy}});var RE=I((NQ,Ru)=>{"use strict";var{normalizeIPv6:bF,removeDotSegments:Ia,recomposeAuthority:wF,normalizeComponentEncoding:Pu,isIPv4:xF,nonSimpleDomain:SF}=Ry(),{SCHEMES:$F,getSchemeHandler:TE}=EE();function kF(t,e){return typeof t=="string"?t=Wr(mn(t,e),e):typeof t=="object"&&(t=mn(Wr(t,e),e)),t}function EF(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=PE(mn(t,n),mn(e,n),n,!0);return n.skipEscape=!0,Wr(o,n)}function PE(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=Ia(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=Ia(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=Ia(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=Ia(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 TF(t,e,r){return typeof t=="string"?(t=unescape(t),t=Wr(Pu(mn(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Wr(Pu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Wr(Pu(mn(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Wr(Pu(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=TE(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=wF(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=Ia(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 PF=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\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(PF);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(xF(n.host)===!1){let c=bF(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=TE(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&SF(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 Iy={SCHEMES:$F,normalize:kF,resolve:EF,resolveComponent:PE,equal:TF,serialize:Wr,parse:mn};Ru.exports=Iy;Ru.exports.default=Iy;Ru.exports.fastUri=Iy});var OE=I(Ay=>{"use strict";Object.defineProperty(Ay,"__esModule",{value:!0});var CE=RE();CE.code='require("ajv/dist/runtime/uri").default';Ay.default=CE});var DE=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 RF=Ca();Object.defineProperty($t,"KeywordCxt",{enumerable:!0,get:function(){return RF.KeywordCxt}});var Xs=pe();Object.defineProperty($t,"_",{enumerable:!0,get:function(){return Xs._}});Object.defineProperty($t,"str",{enumerable:!0,get:function(){return Xs.str}});Object.defineProperty($t,"stringify",{enumerable:!0,get:function(){return Xs.stringify}});Object.defineProperty($t,"nil",{enumerable:!0,get:function(){return Xs.nil}});Object.defineProperty($t,"Name",{enumerable:!0,get:function(){return Xs.Name}});Object.defineProperty($t,"CodeGen",{enumerable:!0,get:function(){return Xs.CodeGen}});var CF=Su(),jE=Oa(),OF=cy(),Aa=ku(),IF=pe(),Na=Ta(),Cu=Ea(),zy=Re(),IE=yE(),AF=OE(),ME=(t,e)=>new RegExp(t,e);ME.code="new RegExp";var NF=["removeAdditional","useDefaults","coerceTypes"],zF=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),jF={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."},MF={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},AE=200;function LF(t){var e,r,n,o,s,i,a,c,l,u,p,f,d,m,h,y,v,b,x,$,O,ie,Q,te,de;let K=t.strict,V=(e=t.code)===null||e===void 0?void 0:e.optimize,ot=V===!0||V===void 0?1:V||0,Et=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:ME,ne=(o=t.uriResolver)!==null&&o!==void 0?o:AF.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s:K)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:K)!==null&&c!==void 0?c:!0,strictTypes:(u=(l=t.strictTypes)!==null&&l!==void 0?l:K)!==null&&u!==void 0?u:"log",strictTuples:(f=(p=t.strictTuples)!==null&&p!==void 0?p:K)!==null&&f!==void 0?f:"log",strictRequired:(m=(d=t.strictRequired)!==null&&d!==void 0?d:K)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ot,regExp:Et}:{optimize:ot,regExp:Et},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:AE,loopEnum:(y=t.loopEnum)!==null&&y!==void 0?y:AE,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:(Q=t.validateFormats)!==null&&Q!==void 0?Q:!0,unicodeRegExp:(te=t.unicodeRegExp)!==null&&te!==void 0?te:!0,int32range:(de=t.int32range)!==null&&de!==void 0?de:!0,uriResolver:ne}}var za=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...LF(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new IF.ValueScope({scope:{},prefixes:zF,es5:r,lines:n}),this.logger=HF(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,OF.getRules)(),NE.call(this,jF,e,"NOT SUPPORTED"),NE.call(this,MF,e,"DEPRECATED","warn"),this._metaOpts=ZF.call(this),e.formats&&qF.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&UF.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),DF.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=IE;n==="id"&&(o={...IE},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 jE.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,Na.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=zE.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new Aa.SchemaEnv({schema:{},schemaId:n});if(r=Aa.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=zE.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,Na.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw new Error("ajv.removeSchema: invalid parameter")}}addVocabulary(e){for(let r of e)this.addKeyword(r);return this}addKeyword(e,r){let n;if(typeof e=="string")n=e,typeof r=="object"&&(this.logger.warn("these parameters are deprecated, see docs for addKeyword"),r.keyword=n);else if(typeof e=="object"&&r===void 0){if(r=e,n=r.keyword,Array.isArray(n)&&!n.length)throw new Error("addKeywords: keyword must be string or non-empty array")}else throw new Error("invalid addKeywords parameters");if(GF.call(this,n,r),!r)return(0,zy.eachItem)(n,s=>Ny.call(this,s)),this;WF.call(this,r);let o={...r,type:(0,Cu.getJSONTypes)(r.type),schemaType:(0,Cu.getJSONTypes)(r.schemaType)};return(0,zy.eachItem)(n,o.type.length===0?s=>Ny.call(this,s,o):s=>o.type.forEach(i=>Ny.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]=LE(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,Na.normalizeId)(i||n);let l=Na.getSchemaRefs.call(this,e,n);return c=new Aa.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):Aa.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{Aa.compileSchema.call(this,e)}finally{this.opts=r}}};za.ValidationError=CF.default;za.MissingRefError=jE.default;$t.default=za;function NE(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 zE(t){return t=(0,Na.normalizeId)(t),this.schemas[t]||this.refs[t]}function DF(){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 qF(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function UF(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 ZF(){let t={...this.opts};for(let e of NF)delete t[e];return t}var FF={log(){},warn(){},error(){}};function HF(t){if(t===!1)return FF;if(t===void 0)return console;if(t.log&&t.warn&&t.error)return t;throw new Error("logger must implement log, warn and error methods")}var BF=/^[a-z_$][a-z0-9_$:-]*$/i;function GF(t,e){let{RULES:r}=this;if((0,zy.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!BF.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 Ny(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,Cu.getJSONTypes)(e.type),schemaType:(0,Cu.getJSONTypes)(e.schemaType)}};e.before?VF.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 VF(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 WF(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=LE(e)),t.validateSchema=this.compile(e,!0))}var JF={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function LE(t){return{anyOf:[t,JF]}}});var qE=I(jy=>{"use strict";Object.defineProperty(jy,"__esModule",{value:!0});var KF={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};jy.default=KF});var HE=I(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.callRef=Qo.getValidate=void 0;var YF=Oa(),UE=gr(),Xt=pe(),Qs=dn(),ZE=ku(),Ou=Re(),XF={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:l}=s;if((r==="#"||r==="#/")&&o===l.baseId)return p();let u=ZE.resolveRef.call(c,l,o,r);if(u===void 0)throw new YF.default(n.opts.uriResolver,o,r);if(u instanceof ZE.SchemaEnv)return f(u);return d(u);function p(){if(s===l)return Iu(t,i,s,s.$async);let m=e.scopeValue("root",{ref:l});return Iu(t,(0,Xt._)`${m}.validate`,l,l.$async)}function f(m){let h=FE(t,m);Iu(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 FE(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Xt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Qo.getValidate=FE;function Iu(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,l=c.passContext?Qs.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,UE.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,UE.callValidateCode)(t,e,l),()=>d(e),()=>f(e))}function f(m){let h=(0,Xt._)`${m}.errors`;o.assign(Qs.default.vErrors,(0,Xt._)`${Qs.default.vErrors} === null ? ${h} : ${Qs.default.vErrors}.concat(${h})`),o.assign(Qs.default.errors,(0,Xt._)`${Qs.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=Ou.mergeEvaluated.props(o,y.props,s.props));else{let v=o.var("props",(0,Xt._)`${m}.evaluated.props`);s.props=Ou.mergeEvaluated.props(o,v,s.props,Xt.Name)}if(s.items!==!0)if(y&&!y.dynamicItems)y.items!==void 0&&(s.items=Ou.mergeEvaluated.items(o,y.items,s.items));else{let v=o.var("items",(0,Xt._)`${m}.evaluated.items`);s.items=Ou.mergeEvaluated.items(o,v,s.items,Xt.Name)}}}Qo.callRef=Iu;Qo.default=XF});var BE=I(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});var QF=qE(),e4=HE(),t4=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",QF.default,e4.default];My.default=t4});var GE=I(Ly=>{"use strict";Object.defineProperty(Ly,"__esModule",{value:!0});var Au=pe(),Gn=Au.operators,Nu={maximum:{okStr:"<=",ok:Gn.LTE,fail:Gn.GT},minimum:{okStr:">=",ok:Gn.GTE,fail:Gn.LT},exclusiveMaximum:{okStr:"<",ok:Gn.LT,fail:Gn.GTE},exclusiveMinimum:{okStr:">",ok:Gn.GT,fail:Gn.LTE}},r4={message:({keyword:t,schemaCode:e})=>(0,Au.str)`must be ${Nu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Au._)`{comparison: ${Nu[t].okStr}, limit: ${e}}`},n4={keyword:Object.keys(Nu),type:"number",schemaType:"number",$data:!0,error:r4,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Au._)`${r} ${Nu[e].fail} ${n} || isNaN(${r})`)}};Ly.default=n4});var VE=I(Dy=>{"use strict";Object.defineProperty(Dy,"__esModule",{value:!0});var ja=pe(),o4={message:({schemaCode:t})=>(0,ja.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,ja._)`{multipleOf: ${t}}`},s4={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:o4,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,ja._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,ja._)`${i} !== parseInt(${i})`;t.fail$data((0,ja._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Dy.default=s4});var JE=I(qy=>{"use strict";Object.defineProperty(qy,"__esModule",{value:!0});function WE(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}qy.default=WE;WE.code='require("ajv/dist/runtime/ucs2length").default'});var KE=I(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});var es=pe(),i4=Re(),a4=JE(),c4={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,es.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,es._)`{limit: ${t}}`},l4={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:c4,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?es.operators.GT:es.operators.LT,i=o.opts.unicode===!1?(0,es._)`${r}.length`:(0,es._)`${(0,i4.useFunc)(t.gen,a4.default)}(${r})`;t.fail$data((0,es._)`${i} ${s} ${n}`)}};Uy.default=l4});var YE=I(Zy=>{"use strict";Object.defineProperty(Zy,"__esModule",{value:!0});var u4=gr(),zu=pe(),p4={message:({schemaCode:t})=>(0,zu.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,zu._)`{pattern: ${t}}`},d4={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:p4,code(t){let{data:e,$data:r,schema:n,schemaCode:o,it:s}=t,i=s.opts.unicodeRegExp?"u":"",a=r?(0,zu._)`(new RegExp(${o}, ${i}))`:(0,u4.usePattern)(t,n);t.fail$data((0,zu._)`!${a}.test(${e})`)}};Zy.default=d4});var XE=I(Fy=>{"use strict";Object.defineProperty(Fy,"__esModule",{value:!0});var Ma=pe(),f4={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ma.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ma._)`{limit: ${t}}`},m4={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:f4,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?Ma.operators.GT:Ma.operators.LT;t.fail$data((0,Ma._)`Object.keys(${r}).length ${o} ${n}`)}};Fy.default=m4});var QE=I(Hy=>{"use strict";Object.defineProperty(Hy,"__esModule",{value:!0});var La=gr(),Da=pe(),h4=Re(),g4={message:({params:{missingProperty:t}})=>(0,Da.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Da._)`{missingProperty: ${t}}`},y4={keyword:"required",type:"object",schemaType:"array",$data:!0,error:g4,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,h4.checkStrictMode)(i,v,i.opts.strictRequired)}}function l(){if(c||s)t.block$data(Da.nil,p);else for(let d of r)(0,La.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,La.checkMissingProp)(t,r,d)),(0,La.reportMissingProp)(t,d),e.else()}function p(){e.forOf("prop",n,d=>{t.setParams({missingProperty:d}),e.if((0,La.noPropertyInData)(e,o,d,a.ownProperties),()=>t.error())})}function f(d,m){t.setParams({missingProperty:d}),e.forOf(d,n,()=>{e.assign(m,(0,La.propertyInData)(e,o,d,a.ownProperties)),e.if((0,Da.not)(m),()=>{t.error(),e.break()})},Da.nil)}}};Hy.default=y4});var eT=I(By=>{"use strict";Object.defineProperty(By,"__esModule",{value:!0});var qa=pe(),v4={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,qa.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,qa._)`{limit: ${t}}`},_4={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:v4,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?qa.operators.GT:qa.operators.LT;t.fail$data((0,qa._)`${r}.length ${o} ${n}`)}};By.default=_4});var ju=I(Gy=>{"use strict";Object.defineProperty(Gy,"__esModule",{value:!0});var tT=gy();tT.code='require("ajv/dist/runtime/equal").default';Gy.default=tT});var rT=I(Wy=>{"use strict";Object.defineProperty(Wy,"__esModule",{value:!0});var Vy=Ea(),kt=pe(),b4=Re(),w4=ju(),x4={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}}`},S4={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:x4,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,Vy.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,Vy.checkDataTypes)(l,y,a.opts.strictNumbers,Vy.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,b4.useFunc)(e,w4.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)})))}}};Wy.default=S4});var nT=I(Ky=>{"use strict";Object.defineProperty(Ky,"__esModule",{value:!0});var Jy=pe(),$4=Re(),k4=ju(),E4={message:"must be equal to constant",params:({schemaCode:t})=>(0,Jy._)`{allowedValue: ${t}}`},T4={keyword:"const",$data:!0,error:E4,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,Jy._)`!${(0,$4.useFunc)(e,k4.default)}(${r}, ${o})`):t.fail((0,Jy._)`${s} !== ${r}`)}};Ky.default=T4});var oT=I(Yy=>{"use strict";Object.defineProperty(Yy,"__esModule",{value:!0});var Ua=pe(),P4=Re(),R4=ju(),C4={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ua._)`{allowedValues: ${t}}`},O4={keyword:"enum",schemaType:"array",$data:!0,error:C4,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,P4.useFunc)(e,R4.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,Ua.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,Ua._)`${l()}(${r}, ${d})`,()=>e.assign(u,!0).break()))}function f(d,m){let h=o[m];return typeof h=="object"&&h!==null?(0,Ua._)`${l()}(${r}, ${d}[${m}])`:(0,Ua._)`${r} === ${h}`}}};Yy.default=O4});var sT=I(Xy=>{"use strict";Object.defineProperty(Xy,"__esModule",{value:!0});var I4=GE(),A4=VE(),N4=KE(),z4=YE(),j4=XE(),M4=QE(),L4=eT(),D4=rT(),q4=nT(),U4=oT(),Z4=[I4.default,A4.default,N4.default,z4.default,j4.default,M4.default,L4.default,D4.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},q4.default,U4.default];Xy.default=Z4});var ev=I(Za=>{"use strict";Object.defineProperty(Za,"__esModule",{value:!0});Za.validateAdditionalItems=void 0;var ts=pe(),Qy=Re(),F4={message:({params:{len:t}})=>(0,ts.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,ts._)`{limit: ${t}}`},H4={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:F4,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Qy.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}iT(t,n)}};function iT(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,ts._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,ts._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Qy.alwaysValidSchema)(i,n)){let l=r.var("valid",(0,ts._)`${a} <= ${e.length}`);r.if((0,ts.not)(l),()=>c(l)),t.ok(l)}function c(l){r.forRange("i",e.length,a,u=>{t.subschema({keyword:s,dataProp:u,dataPropType:Qy.Type.Num},l),i.allErrors||r.if((0,ts.not)(l),()=>r.break())})}}Za.validateAdditionalItems=iT;Za.default=H4});var tv=I(Fa=>{"use strict";Object.defineProperty(Fa,"__esModule",{value:!0});Fa.validateTuple=void 0;var aT=pe(),Mu=Re(),B4=gr(),G4={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return cT(t,"additionalItems",e);r.items=!0,!(0,Mu.alwaysValidSchema)(r,e)&&t.ok((0,B4.validateArray)(t))}};function cT(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=Mu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),l=n.const("len",(0,aT._)`${s}.length`);r.forEach((p,f)=>{(0,Mu.alwaysValidSchema)(a,p)||(n.if((0,aT._)`${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,Mu.checkStrictMode)(a,y,f.strictTuples)}}}Fa.validateTuple=cT;Fa.default=G4});var lT=I(rv=>{"use strict";Object.defineProperty(rv,"__esModule",{value:!0});var V4=tv(),W4={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,V4.validateTuple)(t,"items")};rv.default=W4});var pT=I(nv=>{"use strict";Object.defineProperty(nv,"__esModule",{value:!0});var uT=pe(),J4=Re(),K4=gr(),Y4=ev(),X4={message:({params:{len:t}})=>(0,uT.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,uT._)`{limit: ${t}}`},Q4={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:X4,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,J4.alwaysValidSchema)(n,e)&&(o?(0,Y4.validateAdditionalItems)(t,o):t.ok((0,K4.validateArray)(t)))}};nv.default=Q4});var dT=I(ov=>{"use strict";Object.defineProperty(ov,"__esModule",{value:!0});var vr=pe(),Lu=Re(),eH={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}}`},tH={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:eH,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,Lu.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Lu.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Lu.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:Lu.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)))}}};ov.default=tH});var hT=I(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.validateSchemaDeps=Jr.validatePropertyDeps=Jr.error=void 0;var sv=pe(),rH=Re(),Ha=gr();Jr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,sv.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,sv._)`{property: ${t},
294
294
  missingProperty: ${n},
295
295
  depsCount: ${e},
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 st=pe(),CH={message:({schemaCode:t})=>(0,st.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,st._)`{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,st._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,st._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,st._)`${h}.type || "string"`).assign(v,(0,st._)`${h}.validate`),()=>r.assign(y,(0,st._)`"string"`).assign(v,h)),t.fail$data((0,st.or)(b(),x()));function b(){return c.strictSchema===!1?st.nil:(0,st._)`${i} && !${v}`}function x(){let $=u.$async?(0,st._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,st._)`${v}(${n})`,O=(0,st._)`(typeof ${v} == "function" ? ${$} : ${v}.test(${n}))`;return(0,st._)`${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,st.regexpCode)(O):c.code.formats?(0,st._)`${c.code.formats}${(0,st.getProperty)(s)}`:void 0,Q=r.scopeValue("formats",{key:s,ref:O,code:ie});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,st._)`${Q}.validate`]:["string",O,Q]}function $(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,st._)`await ${v}(${n})`}return typeof y=="function"?(0,st._)`${v}(${n})`:(0,st._)`${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 Q=O.$ref;if(O=jT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Q),O instanceof jT.SchemaEnv&&(O=O.schema),O===void 0)throw new qH.default(s.opts.uriResolver,s.baseId,Q)}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(B.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(B.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(B.InvalidParams,`Invalid tools/call result: ${m}`)}return d.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){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(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},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(B.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(B.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new q(B.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new q(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof q&&n.code===B.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=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(B.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new q(B.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(B.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let p=await n.taskStore.getTask(c);if(!p)throw new q(B.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(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(B.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(B.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(B.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(B.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new q(B.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(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(B.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(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0: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,Q]of Object.entries(l.phases))x[ie]={description:Q.description,...Q.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
+ deps: ${r}}`};var nH={keyword:"dependencies",type:"object",schemaType:"object",error:Jr.error,code(t){let[e,r]=oH(t);fT(t,e),mT(t,r)}};function oH({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 fT(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,Ha.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,Ha.checkReportMissingProp)(t,l)}):(r.if((0,sv._)`${c} && (${(0,Ha.checkMissingProp)(t,a,s)})`),(0,Ha.reportMissingProp)(t,s),r.else())}}Jr.validatePropertyDeps=fT;function mT(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,rH.alwaysValidSchema)(s,e[a])||(r.if((0,Ha.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=mT;Jr.default=nH});var yT=I(iv=>{"use strict";Object.defineProperty(iv,"__esModule",{value:!0});var gT=pe(),sH=Re(),iH={message:"property name must be valid",params:({params:t})=>(0,gT._)`{propertyName: ${t.propertyName}}`},aH={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:iH,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,sH.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,gT.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};iv.default=aH});var cv=I(av=>{"use strict";Object.defineProperty(av,"__esModule",{value:!0});var Du=gr(),Ar=pe(),cH=dn(),qu=Re(),lH={message:"must NOT have additional properties",params:({params:t})=>(0,Ar._)`{additionalProperty: ${t.additionalProperty}}`},uH={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:lH,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,qu.alwaysValidSchema)(i,r))return;let l=(0,Du.allSchemaProperties)(n.properties),u=(0,Du.allSchemaProperties)(n.patternProperties);p(),t.ok((0,Ar._)`${s} === ${cH.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,qu.schemaRefOrVal)(i,n.properties,"properties");v=(0,Du.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,Du.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,qu.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:qu.Type.Str};b===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,v)}}};av.default=uH});var bT=I(uv=>{"use strict";Object.defineProperty(uv,"__esModule",{value:!0});var pH=Ca(),vT=gr(),lv=Re(),_T=cv(),dH={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&&_T.default.code(new pH.KeywordCxt(s,_T.default,"additionalProperties"));let i=(0,vT.allSchemaProperties)(r);for(let p of i)s.definedProperties.add(p);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=lv.mergeEvaluated.props(e,(0,lv.toHash)(i),s.props));let a=i.filter(p=>!(0,lv.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,vT.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)}}};uv.default=dH});var $T=I(pv=>{"use strict";Object.defineProperty(pv,"__esModule",{value:!0});var wT=gr(),Uu=pe(),xT=Re(),ST=Re(),fH={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,wT.allSchemaProperties)(r),c=a.filter(h=>(0,xT.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 Uu.Name)&&(s.props=(0,ST.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,xT.checkStrictMode)(s,`property ${y} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,y=>{e.if((0,Uu._)`${(0,wT.usePattern)(t,h)}.test(${y})`,()=>{let v=c.includes(h);v||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:y,dataPropType:ST.Type.Str},u),s.opts.unevaluated&&p!==!0?e.assign((0,Uu._)`${p}[${y}]`,!0):!v&&!s.allErrors&&e.if((0,Uu.not)(u),()=>e.break())})})}}};pv.default=fH});var kT=I(dv=>{"use strict";Object.defineProperty(dv,"__esModule",{value:!0});var mH=Re(),hH={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,mH.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"}};dv.default=hH});var ET=I(fv=>{"use strict";Object.defineProperty(fv,"__esModule",{value:!0});var gH=gr(),yH={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:gH.validateUnion,error:{message:"must match a schema in anyOf"}};fv.default=yH});var TT=I(mv=>{"use strict";Object.defineProperty(mv,"__esModule",{value:!0});var Zu=pe(),vH=Re(),_H={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Zu._)`{passingSchemas: ${t.passing}}`},bH={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,vH.alwaysValidSchema)(o,u)?e.var(c,!0):f=t.subschema({keyword:"oneOf",schemaProp:p,compositeRule:!0},c),p>0&&e.if((0,Zu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Zu._)`[${a}, ${p}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,p),f&&t.mergeEvaluated(f,Zu.Name)})})}}};mv.default=bH});var PT=I(hv=>{"use strict";Object.defineProperty(hv,"__esModule",{value:!0});var wH=Re(),xH={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,wH.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};hv.default=xH});var OT=I(gv=>{"use strict";Object.defineProperty(gv,"__esModule",{value:!0});var Fu=pe(),CT=Re(),SH={message:({params:t})=>(0,Fu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Fu._)`{failingKeyword: ${t.ifClause}}`},$H={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:SH,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,CT.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=RT(n,"then"),s=RT(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,Fu.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,Fu._)`${u}`):t.setParams({ifClause:u})}}}};function RT(t,e){let r=t.schema[e];return r!==void 0&&!(0,CT.alwaysValidSchema)(t,r)}gv.default=$H});var IT=I(yv=>{"use strict";Object.defineProperty(yv,"__esModule",{value:!0});var kH=Re(),EH={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,kH.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};yv.default=EH});var AT=I(vv=>{"use strict";Object.defineProperty(vv,"__esModule",{value:!0});var TH=ev(),PH=lT(),RH=tv(),CH=pT(),OH=dT(),IH=hT(),AH=yT(),NH=cv(),zH=bT(),jH=$T(),MH=kT(),LH=ET(),DH=TT(),qH=PT(),UH=OT(),ZH=IT();function FH(t=!1){let e=[MH.default,LH.default,DH.default,qH.default,UH.default,ZH.default,AH.default,NH.default,IH.default,zH.default,jH.default];return t?e.push(PH.default,CH.default):e.push(TH.default,RH.default),e.push(OH.default),e}vv.default=FH});var NT=I(_v=>{"use strict";Object.defineProperty(_v,"__esModule",{value:!0});var st=pe(),HH={message:({schemaCode:t})=>(0,st.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,st._)`{format: ${t}}`},BH={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:HH,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,st._)`${m}[${i}]`),y=r.let("fType"),v=r.let("format");r.if((0,st._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(y,(0,st._)`${h}.type || "string"`).assign(v,(0,st._)`${h}.validate`),()=>r.assign(y,(0,st._)`"string"`).assign(v,h)),t.fail$data((0,st.or)(b(),x()));function b(){return c.strictSchema===!1?st.nil:(0,st._)`${i} && !${v}`}function x(){let $=u.$async?(0,st._)`(${h}.async ? await ${v}(${n}) : ${v}(${n}))`:(0,st._)`${v}(${n})`,O=(0,st._)`(typeof ${v} == "function" ? ${$} : ${v}.test(${n}))`;return(0,st._)`${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,st.regexpCode)(O):c.code.formats?(0,st._)`${c.code.formats}${(0,st.getProperty)(s)}`:void 0,Q=r.scopeValue("formats",{key:s,ref:O,code:ie});return typeof O=="object"&&!(O instanceof RegExp)?[O.type||"string",O.validate,(0,st._)`${Q}.validate`]:["string",O,Q]}function $(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!u.$async)throw new Error("async format in sync schema");return(0,st._)`await ${v}(${n})`}return typeof y=="function"?(0,st._)`${v}(${n})`:(0,st._)`${v}.test(${n})`}}}};_v.default=BH});var zT=I(bv=>{"use strict";Object.defineProperty(bv,"__esModule",{value:!0});var GH=NT(),VH=[GH.default];bv.default=VH});var jT=I(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.contentVocabulary=ei.metadataVocabulary=void 0;ei.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];ei.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var LT=I(wv=>{"use strict";Object.defineProperty(wv,"__esModule",{value:!0});var WH=BE(),JH=sT(),KH=AT(),YH=zT(),MT=jT(),XH=[WH.default,JH.default,(0,KH.default)(),YH.default,MT.metadataVocabulary,MT.contentVocabulary];wv.default=XH});var qT=I(Hu=>{"use strict";Object.defineProperty(Hu,"__esModule",{value:!0});Hu.DiscrError=void 0;var DT;(function(t){t.Tag="tag",t.Mapping="mapping"})(DT||(Hu.DiscrError=DT={}))});var ZT=I(Sv=>{"use strict";Object.defineProperty(Sv,"__esModule",{value:!0});var ti=pe(),xv=qT(),UT=ku(),QH=Oa(),e9=Re(),t9={message:({params:{discrError:t,tagName:e}})=>t===xv.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,ti._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},r9={keyword:"discriminator",type:"object",schemaType:"object",error:t9,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,ti._)`${r}${(0,ti.getProperty)(a)}`);e.if((0,ti._)`typeof ${l} == "string"`,()=>u(),()=>t.error(!1,{discrError:xv.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,ti._)`${l} === ${m}`),e.assign(c,p(d[m]));e.else(),t.error(!1,{discrError:xv.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,ti.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,e9.schemaHasRulesButRef)(O,s.self.RULES)){let Q=O.$ref;if(O=UT.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,Q),O instanceof UT.SchemaEnv&&(O=O.schema),O===void 0)throw new QH.default(s.opts.uriResolver,s.baseId,Q)}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}}}};Sv.default=r9});var FT=I((xee,n9)=>{n9.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 kv=I((Be,$v)=>{"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 o9=DE(),s9=LT(),i9=ZT(),HT=FT(),a9=["/properties"],Bu="http://json-schema.org/draft-07/schema",ri=class extends o9.default{_addVocabularies(){super._addVocabularies(),s9.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i9.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(HT,a9):HT;this.addMetaSchema(e,Bu,!1),this.refs["http://json-schema.org/schema"]=Bu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Bu)?Bu:void 0)}};Be.Ajv=ri;$v.exports=Be=ri;$v.exports.Ajv=ri;Object.defineProperty(Be,"__esModule",{value:!0});Be.default=ri;var c9=Ca();Object.defineProperty(Be,"KeywordCxt",{enumerable:!0,get:function(){return c9.KeywordCxt}});var ni=pe();Object.defineProperty(Be,"_",{enumerable:!0,get:function(){return ni._}});Object.defineProperty(Be,"str",{enumerable:!0,get:function(){return ni.str}});Object.defineProperty(Be,"stringify",{enumerable:!0,get:function(){return ni.stringify}});Object.defineProperty(Be,"nil",{enumerable:!0,get:function(){return ni.nil}});Object.defineProperty(Be,"Name",{enumerable:!0,get:function(){return ni.Name}});Object.defineProperty(Be,"CodeGen",{enumerable:!0,get:function(){return ni.CodeGen}});var l9=Su();Object.defineProperty(Be,"ValidationError",{enumerable:!0,get:function(){return l9.default}});var u9=Oa();Object.defineProperty(Be,"MissingRefError",{enumerable:!0,get:function(){return u9.default}})});var XT=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(WT,Rv),time:Kr(Tv(!0),Cv),"date-time":Kr(BT(!0),KT),"iso-time":Kr(Tv(),JT),"iso-date-time":Kr(BT(),YT),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:g9,"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:S9,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:y9,int32:{type:"number",validate:b9},int64:{type:"number",validate:w9},float:{type:"number",validate:VT},double:{type:"number",validate:VT},password:!0,binary:!0};Yr.fastFormats={...Yr.fullFormats,date:Kr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Rv),time:Kr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Cv),"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,KT),"iso-time":Kr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,JT),"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,YT),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 p9(t){return t%4===0&&(t%100!==0||t%400===0)}var d9=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,f9=[0,31,28,31,30,31,30,31,31,30,31,30,31];function WT(t){let e=d9.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&&p9(r)?29:f9[n])}function Rv(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Ev=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Tv(t){return function(r){let n=Ev.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 Cv(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 JT(t,e){if(!(t&&e))return;let r=Ev.exec(t),n=Ev.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 Pv=/t|\s/i;function BT(t){let e=Tv(t);return function(n){let o=n.split(Pv);return o.length===2&&WT(o[0])&&e(o[1])}}function KT(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function YT(t,e){if(!(t&&e))return;let[r,n]=t.split(Pv),[o,s]=e.split(Pv),i=Rv(r,o);if(i!==void 0)return i||Cv(n,s)}var m9=/\/|:/,h9=/^(?:[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 g9(t){return m9.test(t)&&h9.test(t)}var GT=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y9(t){return GT.lastIndex=0,GT.test(t)}var v9=-(2**31),_9=2**31-1;function b9(t){return Number.isInteger(t)&&t<=_9&&t>=v9}function w9(t){return Number.isInteger(t)}function VT(){return!0}var x9=/[^\\]\\Z/;function S9(t){if(x9.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var QT=I(oi=>{"use strict";Object.defineProperty(oi,"__esModule",{value:!0});oi.formatLimitDefinition=void 0;var $9=kv(),Nr=pe(),Vn=Nr.operators,Gu={formatMaximum:{okStr:"<=",ok:Vn.LTE,fail:Vn.GT},formatMinimum:{okStr:">=",ok:Vn.GTE,fail:Vn.LT},formatExclusiveMaximum:{okStr:"<",ok:Vn.LT,fail:Vn.GTE},formatExclusiveMinimum:{okStr:">",ok:Vn.GT,fail:Vn.LTE}},k9={message:({keyword:t,schemaCode:e})=>(0,Nr.str)`should be ${Gu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Nr._)`{comparison: ${Gu[t].okStr}, limit: ${e}}`};oi.formatLimitDefinition={keyword:Object.keys(Gu),type:"string",schemaType:"string",$data:!0,error:k9,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 $9.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}) ${Gu[o].fail} 0`}},dependencies:["format"]};var E9=t=>(t.addKeyword(oi.formatLimitDefinition),t);oi.default=E9});var nP=I((Ba,rP)=>{"use strict";Object.defineProperty(Ba,"__esModule",{value:!0});var si=XT(),T9=QT(),Ov=pe(),eP=new Ov.Name("fullFormats"),P9=new Ov.Name("fastFormats"),Iv=(t,e={keywords:!0})=>{if(Array.isArray(e))return tP(t,e,si.fullFormats,eP),t;let[r,n]=e.mode==="fast"?[si.fastFormats,P9]:[si.fullFormats,eP],o=e.formats||si.formatNames;return tP(t,o,r,n),e.keywords&&(0,T9.default)(t),t};Iv.get=(t,e="full")=>{let n=(e==="fast"?si.fastFormats:si.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function tP(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Ov._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}rP.exports=Ba=Iv;Object.defineProperty(Ba,"__esModule",{value:!0});Ba.default=Iv});function R9(){let t=new oP.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,sP.default)(t),t}var oP,sP,Vu,iP=w(()=>{oP=po(kv(),1),sP=po(nP(),1);Vu=class{constructor(e){this._ajv=e??R9()}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 Wu,aP=w(()=>{Wu=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 cP(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 lP(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 uP=w(()=>{});var Ju,pP=w(()=>{vk();Os();iP();ha();aP();uP();Ju=class extends uu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(aa.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 Vu,this.setRequestHandler(vl,n=>this._oninitialize(n)),this.setNotificationHandler(Ah,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(qh,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=aa.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Wu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=yk(this._capabilities,e)}setRequestHandler(e,r){let o=Mn(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=jn(Cs,c);if(!u.success){let m=u.error instanceof Error?u.error.message:String(u.error);throw new q(B.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:p}=u.data,f=await Promise.resolve(r(c,l));if(p.task){let m=jn(Ps,f);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new q(B.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let d=jn(Al,f);if(!d.success){let m=d.error instanceof Error?d.error.message:String(d.error);throw new q(B.InvalidParams,`Invalid tools/call result: ${m}`)}return d.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){lP(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&cP(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:Xi.includes(r)?r:Ph,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"},gl)}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},Zh,r):this.request({method:"sampling/createMessage",params:e},Uh,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},Nl,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},Nl,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(B.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof q?i:new q(B.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},Fh,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 Av(t){return!!t&&typeof t=="object"&&fP in t}function mP(t){return t[fP]?.complete}var fP,dP,hP=w(()=>{fP=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(dP||(dP={}))});var gP=w(()=>{});function O9(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"),!C9.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 I9(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 Nv(t){let e=O9(t);return I9(t,e.warnings),e.isValid}var C9,yP=w(()=>{C9=/^[A-Za-z0-9._-]{1,128}$/});var Ku,vP=w(()=>{Ku=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 Yu=w(()=>{Kl();Kl()});function wP(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function N9(t){return"_def"in t||"_zod"in t||wP(t)}function zv(t){return typeof t!="object"||t===null||N9(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(wP)}function _P(t){if(t)return zv(t)?Bo(t):t}function z9(t){let e=Mn(t);return e?Object.entries(e).map(([r,n])=>{let o=A$(n),s=N$(n);return{name:r,description:o,required:!s}}):[]}function Wn(t){let r=Mn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ql(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function bP(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Xu,A9,Ga,xP=w(()=>{pP();ha();qg();Os();hP();gP();yP();vP();Yu();Xu=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 Ju(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Ku(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Il)),this.server.assertCanSetRequestHandler(Wn(Cs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Il,()=>({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=Fs(r.inputSchema);return o?Mg(o,{strictUnions:!0,pipeStrategy:"input"}):A9})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Fs(r.outputSchema);o&&(n.outputSchema=Mg(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Cs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(B.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(B.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new q(B.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new q(B.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof q&&n.code===B.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Fs(e.inputSchema)??e.inputSchema,i=await Yl(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Xl(a);throw new q(B.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${c}`)}return i.data}async validateToolOutput(e,r,n){if(!e.outputSchema||!("content"in r)||r.isError)return;if(!r.structuredContent)throw new q(B.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Fs(e.outputSchema),s=await Yl(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=Xl(i);throw new q(B.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,l=a.task,u=l.pollInterval??5e3;for(;l.status!=="completed"&&l.status!=="failed"&&l.status!=="cancelled";){await new Promise(f=>setTimeout(f,u));let p=await n.taskStore.getTask(c);if(!p)throw new q(B.InternalError,`Task ${c} not found during polling`);l=p}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(Wn(zl)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(zl,async e=>{switch(e.params.ref.type){case"ref/prompt":return WS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return JS(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(B.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new q(B.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new q(B.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Ga;let s=Mn(n.argsSchema)?.[e.params.argument.name];if(!Av(s))return Ga;let i=mP(s);if(!i)return Ga;let a=await i(e.params.argument.value,e.params.context);return bP(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 Ga;throw new q(B.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Ga;let s=await o(e.params.argument.value,e.params.context);return bP(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Tl)),this.server.assertCanSetRequestHandler(Wn(Pl)),this.server.assertCanSetRequestHandler(Wn(Rl)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Tl,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(Pl,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Rl,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new q(B.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new q(B.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(Wn(Cl)),this.server.assertCanSetRequestHandler(Wn(Ol)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Cl,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?z9(r.argsSchema):void 0}))})),this.server.setRequestHandler(Ol,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(B.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(B.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Fs(n.argsSchema),s=await Yl(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",l=Xl(c);throw new q(B.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${l}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:l=>{typeof l.name<"u"&&l.name!==e&&(delete this._registeredResourceTemplates[e],l.name&&(this._registeredResourceTemplates[l.name]=i)),typeof l.title<"u"&&(i.title=l.title),typeof l.template<"u"&&(i.resourceTemplate=l.template),typeof l.metadata<"u"&&(i.metadata=l.metadata),typeof l.callback<"u"&&(i.readCallback=l.callback),typeof l.enabled<"u"&&(i.enabled=l.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(l=>!!n.completeCallback(l))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Bo(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=Bo(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 Av(l)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,l){Nv(e);let u={title:r,description:n,inputSchema:_P(o),outputSchema:_P(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"&&Nv(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=Bo(p.paramsSchema)),typeof p.outputSchema<"u"&&(u.outputSchema=Bo(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];zv(c)?(o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!zv(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()}},A9={type:"object",properties:{}};Ga={completion:{values:[],hasMore:!1}}});function ii(){return`${Date.now()}-${++j9}`}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 Ze(t,e){if(!e)return!1;let r=new Date(t).getTime();return Date.now()>r+e}var j9,Xr=w(()=>{j9=0});var Qu,SP=w(()=>{Xr();Qu=class{entries=new Map;async get(e){let r=this.entries.get(e);return r?Ze(r.setAt,r.ttlMs)?(this.entries.delete(e),null):r:null}async set(e,r,n,o,s){let i=new Date().toISOString(),a=this.entries.get(e),c={key:e,value:r,category:o,setBy:n,setAt:a?.setAt??i,updatedAt:i,ttlMs:s};return this.entries.set(e,c),c}async delete(e){return this.entries.delete(e)}async query(e,r){let n=[];for(let o of this.entries.values()){if(Ze(o.setAt,o.ttlMs)){this.entries.delete(o.key);continue}e&&!_r(e,o.key)||r&&o.category!==r||n.push(o)}return n}async getAll(){let e=[];for(let r of this.entries.values())Ze(r.setAt,r.ttlMs)||e.push(r);return e}async load(e){this.entries.clear();for(let r of e)Ze(r.setAt,r.ttlMs)||this.entries.set(r.key,r)}}});var ep,$P=w(()=>{Xr();ep=class{claims=new Map;eventStore;constructor(e){this.eventStore=e}async claim(e,r,n,o){let s=this.claims.get(e);if(s&&s.status==="active"&&!Ze(s.claimedAt,s.ttlMs))return s.owner!==n?{status:"rejected",claim:s}:(s.value=r,s.ttlMs=o,{status:"approved",claim:s});let i={resource:e,value:r,owner:n,status:"active",claimedAt:new Date().toISOString(),ttlMs:o};return this.claims.set(e,i),await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),{status:"approved",claim:i}}async release(e,r){let n=this.claims.get(e);return!n||n.status!=="active"||n.owner!==r?null:(n.status="released",await this.eventStore.publish("claim.released",{resource:e,owner:r},r),n)}async check(e){let r=this.claims.get(e);return r?(r.status==="active"&&Ze(r.claimedAt,r.ttlMs)&&(r.status="expired"),r):null}async list(e){let r=[];for(let n of this.claims.values())n.status==="active"&&Ze(n.claimedAt,n.ttlMs)&&(n.status="expired"),n.status==="active"&&(e&&!_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 tp,kP=w(()=>{tp=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 rp,EP=w(()=>{Xr();rp=class{discoveries=[];eventStore;constructor(e){this.eventStore=e}async publish(e,r,n,o){let s={id:ii(),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 M9}from"node:crypto";var Jn,np=w(()=>{Jn=class{messages=[];async send(e,r,n,o){let s={id:M9(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 L9}from"node:crypto";var Kn,op=w(()=>{Kn=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:L9(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 Yn,sp=w(()=>{Yn=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 D9}from"node:crypto";var Xn,ip=w(()=>{Xn=class{conflicts=new Map;eventStore;constructor(e){this.eventStore=e}async flag(e,r,n,o){let s={id:D9(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 Qn,ap=w(()=>{Qn=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 q9}from"node:crypto";var eo,cp=w(()=>{eo=class{proposals=new Map;eventStore;constructor(e){this.eventStore=e}async propose(e,r,n,o){let s={id:q9(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 U9}from"node:crypto";var to,lp=w(()=>{to=class{requests=new Map;eventStore;constructor(e){this.eventStore=e}async request(e,r,n,o){let s={id:U9(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 ro,up=w(()=>{ro=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 no,pp=w(()=>{no=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 TP(){let t=new tp,e=new Qu,r=new ep(t),n=new rp(t),o=new Jn,s=new Kn(t),i=new Yn,a=new Xn(t),c=new Qn,l=new eo(t),u=new to(t),p=new ro(t),f=new no;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 jv(t,e={}){let r=e.agentId??"agent_default",n=e.namespace&&e.namespace!=="default"?`@${e.namespace}`:"",o=new Xu({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 qd(l,t,s()),v=Nc(l,p,h),b=Zd(l,p,h,y),x={};for(let[ie,Q]of Object.entries(l.phases))x[ie]={description:Q.description,...Q.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 Mv=w(()=>{xP();Yu();SP();$P();kP();EP();np();op();sp();ip();ap();cp();lp();up();pp();Ci()});import{createRequire as Z9}from"node:module";function PP(t){let r=Z9(import.meta.url)("@honeybee-ai/carapace");return t&&console.error("[incubator] carapace loaded"),r}function ai(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 Va(o);if(o.action==="WARN"&&r){let s=new Date().toISOString().slice(11,23);console.error(` ${s} [carapace] WARN: ${o.summary}`)}}function rs(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 ns(t){return typeof t=="string"?t:t==null?"":JSON.stringify(t)}function RP(t,e,r){return{state:{...t.state,set:async(n,o,s,i,a)=>(ai(e,[n,ns(o),i],r),t.state.set(n,o,s,i,a)),get:async n=>{let o=await t.state.get(n);return!o||!rs(e,[o.key,ns(o.value),o.category],r)?null:o},query:async(n,o)=>(await t.state.query(n,o)).filter(i=>rs(e,[i.key,ns(i.value),i.category],r))},events:{...t.events,publish:async(n,o,s)=>(ai(e,[n,ns(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=>rs(e,[i.type,ns(i.data)],r)),cursor:s.cursor}}},claims:{...t.claims,claim:async(n,o,s,i)=>(ai(e,[n,o],r),t.claims.claim(n,o,s,i)),check:async n=>{let o=await t.claims.check(n);return!o||!rs(e,[o.resource,o.value],r)?null:o},list:async n=>(await t.claims.list(n)).filter(s=>rs(e,[s.resource,s.value],r))},discoveries:{...t.discoveries,publish:async(n,o,s,i)=>(ai(e,[n,o,i],r),t.discoveries.publish(n,o,s,i)),search:async(n,o)=>(await t.discoveries.search(n,o)).filter(i=>rs(e,[i.topic,i.content,i.category],r))},messages:{...t.messages,send:async(n,o,s,i)=>(ai(e,[s],r),t.messages.send(n,o,s,i))},help:{...t.help,request:async(n,o,s,i)=>(ai(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 CP(t,e,r){let n=0,o=(s,i)=>s.filter(a=>rs(e,i(a),r)?!0:(n++,!1));return t.state=o(t.state,s=>[s.key,ns(s.value),s.category]),t.claims=o(t.claims,s=>[s.resource,s.value]),t.events=o(t.events,s=>[s.type,ns(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 Va,dp=w(()=>{Va=class extends Error{score;action;findings;constructor(e){super(`[carapace] Blocked: ${e.summary}`),this.name="CarapaceBlockedError",this.score=e.score,this.action=e.action,this.findings=e.findings}}});function F9(t){let e=t.headers.origin||"";if(/^https?:\/\/localhost(:\d+)?$/.test(e)||/^https:\/\/[a-z0-9-]+\.honeyb\.dev$/.test(e))return e;let r=process.env.INCUBATOR_CORS_ORIGINS;if(r)for(let n of r.split(",")){let o=n.trim();if(o&&e===o)return e;if(o.startsWith("*.")){let s=o.slice(1);if(new RegExp(`^https://[a-z0-9-]+${s.replace(/\./g,"\\.")}(:\\d+)?$`).test(e))return e}}return""}function C(t,e,r,n){let o=n?F9(n):"http://localhost:5173",s={"Content-Type":"application/json","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, OPTIONS","Access-Control-Allow-Headers":"Content-Type, X-Agent-Id, X-Namespace"};o&&(s["Access-Control-Allow-Origin"]=o),t.writeHead(e,s),t.end(JSON.stringify(r))}function Ye(t,e){let r=e.agentId??t.headers["x-agent-id"]??"rest_anonymous";return r.startsWith("honeycomb:")?"rest_anonymous":r}async function B9(t){return t.method==="GET"?{}:new Promise((e,r)=>{let n="",o=0;t.on("data",s=>{if(o+=s.length,o>H9){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 W9(t){let e=t.slice(5),r=e.indexOf("/"),n=r===-1?e:e.slice(0,r);if(n==="_ns")return{namespace:null,rewrittenPath:t};if(G9.has(n))return{namespace:"default",rewrittenPath:t};let o=r===-1?"":e.slice(r);return{namespace:n,rewrittenPath:`/api${o}`}}async function OP(t,e,r,n){let o=t.url??"/";if(!o.startsWith("/api/"))return!1;if(t.method==="OPTIONS")return C(e,204,""),!0;let s=await B9(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 C(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 C(e,200,{deleted:m}),!0}let{namespace:c,rewrittenPath:l}=W9(i);if(c===null)return C(e,404,{error:`No route: ${t.method} ${i}`}),!0;let u;try{u=r.get(c)}catch(d){return C(e,400,{error:d.message}),!0}if(l==="/api/protocol"){if(t.method==="GET"){let d=r.getProtocol(c);if(!d)C(e,200,{loaded:!1});else{let m=await u.roles.getAssignments();C(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 vo(s.spec);else if(s.acp&&s.name)d=await vo(JSON.stringify(s));else return C(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),C(e,200,{loaded:!0,name:d.name,title:d.title})}catch(d){d instanceof yo?C(e,400,{error:"Invalid spec",details:d.errors}):C(e,400,{error:d.message})}return!0}}let p=l.match(/^\/api\/topics(?:\/(.+))?$/);if(p){let d=r.getRouter();if(!d)return C(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 C(e,200,v),!0}if(t.method==="POST"&&m==="subscribe"){let v=s.topic;return v?(d.subscribe(c,v),C(e,200,{subscribed:!0,topic:v}),!0):(C(e,400,{error:"Missing required field: topic"}),!0)}if(t.method==="POST"&&m==="publish"){let v=s.topic;return v?(d.publish(c,v),C(e,200,{published:!0,topic:v}),!0):(C(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),C(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),C(e,200,{unpublished:!0,topic:v}),!0}return C(e,404,{error:`No route: ${t.method} ${i}`}),!0}if(l.match(/^\/api\/dance\/(.+)$/)&&t.method==="POST")return C(e,501,{error:"Dance tool calls via REST not yet implemented (use WebSocket)"},t),!0;for(let d of V9){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 Va)C(e,403,{error:"prompt_injection_detected",message:h.message,score:h.score,action:h.action,findings:h.findings});else throw h}return!0}}return C(e,404,{error:`No route: ${t.method} ${i}`}),!0}var H9,G9,V9,IP=w(()=>{dp();Ci();H9=1024*1024;G9=new Set(["state","claims","events","discoveries","health","protocol","messages","help","progress","conflicts","roles","reinforcements","governance","control","topics","runs"]),V9=[{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();C(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);C(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){C(e,200,{found:!1,key:o});return}C(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)){C(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);C(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);C(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){C(e,400,{error:"Missing required fields: resource, value"});return}let a=Ye(t,o),c=await r.claims.claim(s,i,a,o.ttlMs);C(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){C(e,200,{released:!1,reason:"No active claim found or not owner"});return}C(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){C(e,200,{claimed:!1,resource:o});return}C(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);C(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){C(e,400,{error:"Missing required field: type"});return}let i=Ye(t,o),a=await r.events.publish(s,o.data??null,i);C(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);C(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){C(e,400,{error:"Missing required fields: topic, content"});return}let a=Ye(t,o),c=await r.discoveries.publish(s,i,a,o.category);C(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);C(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){C(e,400,{error:"Missing required fields: to, content"});return}let a=Ye(t,o),c=await r.messages.send(a,s,i,o.replyTo);C(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);C(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){C(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),C(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();C(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){C(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);C(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){C(e,200,{claimed:!1,reason:"Request not found or not open"});return}C(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){C(e,200,{resolved:!1,reason:"Request not found or not claimed"});return}C(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);C(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){C(e,400,{error:"Missing required fields: claim, progress"});return}let a=Ye(t,o),c=await r.progress.report(s,a,i,o.note);C(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){C(e,200,{found:!1,claim:o});return}C(e,200,{found:!0,report:s})}},{method:"GET",pattern:/^\/api\/progress$/,handler:async(t,e,r)=>{let n=await r.progress.list();C(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){C(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);C(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){C(e,400,{error:"Missing required field: resolution"});return}let a=Ye(t,o),c=await r.conflicts.resolve(s,a,i);if(!c){C(e,200,{resolved:!1,reason:"Conflict not found or not open"});return}C(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);C(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){C(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);C(e,200,{requested:!0,request:c})}},{method:"GET",pattern:/^\/api\/reinforcements$/,handler:async(t,e,r)=>{let n=await r.reinforcements.list();C(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){C(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),C(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){C(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),C(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){C(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);C(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){C(e,200,{endorsed:!1,reason:"Proposal not found or not open"});return}C(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);C(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){C(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),C(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){C(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);C(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){C(e,400,{error:"Missing required field: reason"});return}let i=Ye(t,o),a=o.target,c=await r.control.pause(s,i,a);C(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){C(e,400,{error:"Missing required field: reason"});return}let i=Ye(t,o),a=o.target,c=await r.control.resume(i,s,a);C(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);C(e,200,s)}},{method:"GET",pattern:/^\/api\/runs\/summary$/,handler:async(t,e,r)=>{let n=await r.runs.summary();C(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){C(e,200,{found:!1,agentId:o});return}C(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);C(e,200,{count:s.length,runs:s})}}]});import{createRequire as J9}from"node:module";import{resolve as K9}from"node:path";function NP(t){let e=t===":memory:"?t:K9(t),r=AP.get(e);if(r)return r;let o=J9(import.meta.url)("better-sqlite3"),s=new o(e);return s.pragma("journal_mode = WAL"),Y9(s),e!==":memory:"&&AP.set(e,s),s}function Y9(t){t.exec(`
297
297
  CREATE TABLE IF NOT EXISTS state (
298
298
  namespace TEXT NOT NULL,
299
299
  key TEXT NOT NULL,
@@ -347,7 +347,7 @@ data:
347
347
  CREATE INDEX IF NOT EXISTS idx_events_ns_type ON events (namespace, type);
348
348
  CREATE INDEX IF NOT EXISTS idx_claims_ns_status ON claims (namespace, status);
349
349
  CREATE INDEX IF NOT EXISTS idx_discoveries_ns_cat ON discoveries (namespace, category);
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
+ `)}var AP,zP=w(()=>{AP=new Map});var fp,jP=w(()=>{Xr();fp=class{db;ns;constructor(e,r){this.db=e,this.ns=r}async get(e){let r=this.db.prepare("SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ? AND key = ?").get(this.ns,e);if(!r)return null;let n=this.rowToEntry(r);return Ze(n.setAt,n.ttlMs)?(this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,e),null):n}async set(e,r,n,o,s){let i=new Date().toISOString(),c=(await this.get(e))?.setAt??i;return this.db.prepare(`
351
351
  INSERT INTO state (namespace, key, value, category, set_by, set_at, updated_at, ttl_ms)
352
352
  VALUES (?, ?, ?, ?, ?, ?, ?, ?)
353
353
  ON CONFLICT(namespace, key) DO UPDATE SET
@@ -356,7 +356,7 @@ data:
356
356
  set_by = excluded.set_by,
357
357
  updated_at = excluded.updated_at,
358
358
  ttl_ms = excluded.ttl_ms
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
+ `).run(this.ns,e,JSON.stringify(r),o??null,n,c,i,s??null),{key:e,value:r,category:o,setBy:n,setAt:c,updatedAt:i,ttlMs:s}}async delete(e){return this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,e).changes>0}async query(e,r){let n="SELECT key, value, category, set_by, set_at, updated_at, ttl_ms FROM state WHERE namespace = ?",o=[this.ns];r&&(n+=" AND category = ?",o.push(r));let s=this.db.prepare(n).all(...o),i=[];for(let a of s){let c=this.rowToEntry(a);if(Ze(c.setAt,c.ttlMs)){this.db.prepare("DELETE FROM state WHERE namespace = ? AND key = ?").run(this.ns,c.key);continue}e&&!_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=>!Ze(r.setAt,r.ttlMs))}async load(e){this.db.transaction(()=>{this.db.prepare("DELETE FROM state WHERE namespace = ?").run(this.ns);let n=this.db.prepare("INSERT INTO state (namespace, key, value, category, set_by, set_at, updated_at, ttl_ms) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");for(let o of e)Ze(o.setAt,o.ttlMs)||n.run(this.ns,o.key,JSON.stringify(o.value),o.category??null,o.setBy,o.setAt,o.updatedAt,o.ttlMs??null)})()}rowToEntry(e){return{key:e.key,value:JSON.parse(e.value),category:e.category??void 0,setBy:e.set_by,setAt:e.set_at,updatedAt:e.updated_at,ttlMs:e.ttl_ms??void 0}}}});var mp,MP=w(()=>{mp=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 hp,LP=w(()=>{Xr();hp=class{db;ns;eventStore;constructor(e,r,n){this.db=e,this.ns=r,this.eventStore=n}async claim(e,r,n,o){let s,i=!1;return this.db.transaction(()=>{let c=this.getClaimRow(e);if(c&&c.status==="active"&&!Ze(c.claimed_at,c.ttl_ms??void 0)){if(c.owner!==n){s={status:"rejected",claim:this.rowToClaim(c)};return}this.db.prepare("UPDATE claims SET value = ?, ttl_ms = ? WHERE namespace = ? AND resource = ?").run(r,o??null,this.ns,e),s={status:"approved",claim:{...this.rowToClaim(c),value:r,ttlMs:o}};return}let l=new Date().toISOString();this.db.prepare(`
360
360
  INSERT INTO claims (namespace, resource, value, owner, status, claimed_at, ttl_ms)
361
361
  VALUES (?, ?, ?, ?, 'active', ?, ?)
362
362
  ON CONFLICT(namespace, resource) DO UPDATE SET
@@ -365,7 +365,7 @@ data:
365
365
  status = excluded.status,
366
366
  claimed_at = excluded.claimed_at,
367
367
  ttl_ms = excluded.ttl_ms
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
+ `).run(this.ns,e,r,n,l,o??null);let u={resource:e,value:r,owner:n,status:"active",claimedAt:l,ttlMs:o};i=!0,s={status:"approved",claim:u}})(),i&&await this.eventStore.publish("claim.acquired",{resource:e,value:r,owner:n},n),s}async release(e,r){let n=this.getClaimRow(e);return!n||n.status!=="active"||n.owner!==r?null:(this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("released",this.ns,e),await this.eventStore.publish("claim.released",{resource:e,owner:r},r),{...this.rowToClaim(n),status:"released"})}async check(e){let r=this.getClaimRow(e);return r?r.status==="active"&&Ze(r.claimed_at,r.ttl_ms??void 0)?(this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("expired",this.ns,e),{...this.rowToClaim(r),status:"expired"}):this.rowToClaim(r):null}async list(e){let r=this.db.prepare("SELECT resource, value, owner, status, claimed_at, ttl_ms FROM claims WHERE namespace = ? AND status = ?").all(this.ns,"active"),n=[];for(let o of r){if(Ze(o.claimed_at,o.ttl_ms??void 0)){this.db.prepare("UPDATE claims SET status = ? WHERE namespace = ? AND resource = ?").run("expired",this.ns,o.resource);continue}e&&!_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 gp,DP=w(()=>{Xr();gp=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=ii(),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 qP(t,e){let r=NP(t),n=new mp(r,e),o=new fp(r,e),s=new hp(r,e,n),i=new gp(r,e,n),a=new Jn,c=new Kn(n),l=new Yn,u=new Xn(n),p=new Qn,f=new eo(n),d=new to(n),m=new ro(n),h=new no;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 UP=w(()=>{zP();jP();MP();LP();DP();np();op();sp();ip();ap();cp();lp();up();pp()});var yp,ZP=w(()=>{Xr();yp=class{client;hashKey;constructor(e,r){this.client=e,this.hashKey=`incubator:${r}:state`}async get(e){let r=await this.client.hget(this.hashKey,e);if(!r)return null;let n=JSON.parse(r);return Ze(n.setAt,n.ttlMs)?(await this.client.hdel(this.hashKey,e),null):n}async set(e,r,n,o,s){let i=new Date().toISOString(),c=(await this.get(e))?.setAt??i,l={key:e,value:r,category:o,setBy:n,setAt:c,updatedAt:i,ttlMs:s};return await this.client.hset(this.hashKey,e,JSON.stringify(l)),l}async delete(e){return await this.client.hdel(this.hashKey,e)>0}async query(e,r){let n=await this.client.hgetall(this.hashKey),o=[];for(let[,s]of Object.entries(n)){let i=JSON.parse(s);if(Ze(i.setAt,i.ttlMs)){await this.client.hdel(this.hashKey,i.key);continue}e&&!_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);Ze(o.setAt,o.ttlMs)||r.push(o)}return r}async load(e){if(await this.client.del(this.hashKey),e.length===0)return;let r={};for(let n of e)Ze(n.setAt,n.ttlMs)||(r[n.key]=JSON.stringify(n));Object.keys(r).length>0&&await this.client.hset(this.hashKey,r)}}});var vp,FP=w(()=>{vp=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 _p,HP=w(()=>{Xr();_p=class t{client;hashKey;eventStore;constructor(e,r,n){this.client=e,this.hashKey=`incubator:${r}:claims`,this.eventStore=n}static CLAIM_SCRIPT=`
369
369
  local raw = redis.call('HGET', KEYS[1], ARGV[1])
370
370
  if raw then
371
371
  local existing = cjson.decode(raw)
@@ -388,28 +388,28 @@ data:
388
388
  end
389
389
  redis.call('HSET', KEYS[1], ARGV[1], ARGV[2])
390
390
  return nil
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?`
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"&&Ze(n.claimedAt,n.ttlMs)&&(n.status="expired",await this.client.hset(this.hashKey,e,JSON.stringify(n))),n}async list(e){let r=await this.client.hgetall(this.hashKey),n=[];for(let[,o]of Object.entries(r)){let s=JSON.parse(o);if(s.status==="active"&&Ze(s.claimedAt,s.ttlMs)){s.status="expired",await this.client.hset(this.hashKey,s.resource,JSON.stringify(s));continue}s.status==="active"&&(e&&!_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 bp,BP=w(()=>{Xr();bp=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:ii(),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 GP(t,e){let r=new vp(t,e),n=new yp(t,e),o=new _p(t,e,r),s=new bp(t,e,r),i=new Jn,a=new Kn(r),c=new Yn,l=new Xn(r),u=new Qn,p=new eo(r),f=new to(r),d=new ro(r),m=new no;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 VP=w(()=>{ZP();FP();HP();BP();np();op();sp();ip();ap();cp();lp();up();pp()});function WP(t){if(t.type==="memory")return TP();if(t.type==="sqlite"){if(!t.dbPath)throw new Error("SQLite backend requires dbPath");return qP(t.dbPath,t.namespace??"default")}if(t.type==="redis"){if(!t.redisClient)throw new Error("Redis backend requires redisClient");return GP(t.redisClient,t.namespace??"default")}throw new Error(`Unknown backend type: ${t.type}`)}var JP=w(()=>{Mv();UP();VP()});var Lv,wp,KP=w(()=>{Lv="honeycomb:",wp=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(Lv))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},`${Lv}${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=`${Lv}${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 X9,xp,YP=w(()=>{JP();dp();KP();X9=new Set(["_ns"]);xp=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 wp(n=>this.get(n),e,r);for(let[n,o]of this.protocols)o.topics&&this.router.registerProtocol(n,o)}getRouter(){return this.router}get(e){if(X9.has(e))throw new Error(`'${e}' is a reserved name and cannot be used as a namespace`);if(!/^[a-z0-9][a-z0-9_-]{0,63}$/.test(e))throw new Error("Invalid namespace: must match /^[a-z0-9][a-z0-9_-]{0,63}$/");let r=this.namespaces.get(e);if(r)return r;if(this.namespaces.size>=100)throw new Error("Maximum namespace count (100) reached");return r=WP({...this.backendConfig,namespace:e}),this.bus&&Q9(r,this.bus,e),this.guard&&(r=RP(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 eB,writeFileSync as tB,mkdirSync as rB,readdirSync as nB}from"node:fs";import{dirname as XP,basename as oB,join as sB}from"node:path";async function iB(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()};rB(XP(t),{recursive:!0}),tB(t,JSON.stringify(r,null,2),{mode:384})}async function aB(t,e,r){try{let n=eB(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 Sp(t,e){for(let r of e.list()){let n=`${t}.${r}.json`;await iB(n,e.get(r))}}async function QP(t,e,r){let n=XP(t),o=oB(t)+".",s=".json",i=0;try{let a=nB(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 aB(sB(n,c),u,r)&&i++}}catch{}return i}var eR=w(()=>{});import{EventEmitter as cB}from"node:events";var $p,kp,tR=w(()=>{$p=class{emitter=new cB;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()}},kp=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 Dv(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 qv=w(()=>{});var Wa,rR=w(()=>{qv();Wa=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 Dv(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 lB,writeFileSync as Xre,mkdirSync as Qre,existsSync as uB}from"node:fs";import{join as nR}from"node:path";import{homedir as pB}from"node:os";function dB(){return nR(pB(),".config","honeybee")}function fB(){return nR(dB(),"integrations.json")}function Uv(){let t=fB();if(!uB(t))return{};try{return JSON.parse(lB(t,"utf8"))}catch{return{}}}var oR=w(()=>{});var sR=w(()=>{rR();qv();oR()});var Ep,iR=w(()=>{Ep=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 ci={};G(ci,{buildAcpHelper:()=>Fv,callDanceTool:()=>Hv,danceToolDefs:()=>Zv,loadDances:()=>mB,runInject:()=>Bv});async function mB(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 Zv(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 Fv(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 Hv(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 Bv(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 os=w(()=>{});import{resolve as aR,relative as hB}from"node:path";function br(t,e){let r=aR(t,e),n=hB(t,r);if(n.startsWith("..")||aR(n)===n)throw new Error(`Path "${e}" escapes the working directory`);return r}var Tp=w(()=>{});function Zt(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 Ja=w(()=>{});function dt(t){return{content:[{type:"text",text:typeof t=="string"?t:JSON.stringify(t)}]}}function Ee(t){return dt({error:t})}var Ka=w(()=>{});import{readFile as Vv,writeFile as cR,readdir as Wv,mkdir as gB,stat as lR}from"node:fs/promises";import{join as Jv,relative as Kv,dirname as yB}from"node:path";async function uR(t,e,r,n){let o=Zt(r,[t.path],n);if(o)return Ee(o);try{let s=br(e,t.path),i=await lR(s);if(i.size>Gv)return Ee(`File too large (${Math.round(i.size/1024)}KB, max ${Gv/1024}KB)`);let a=await Vv(s,"utf-8");return dt(a)}catch(s){return Ee(s.message)}}async function pR(t,e,r,n){let o=Zt(r,[t.path,t.content],n);if(o)return Ee(o);try{let s=br(e,t.path);return await gB(yB(s),{recursive:!0}),await cR(s,t.content,"utf-8"),dt({success:!0,path:t.path,bytes:Buffer.byteLength(t.content)})}catch(s){return Ee(s.message)}}async function dR(t,e,r,n){let o=Zt(r,[t.path,t.search,t.replace],n);if(o)return Ee(o);try{let s=br(e,t.path),i=await Vv(s,"utf-8");if(!i.includes(t.search))return Ee(`Search string not found in ${t.path}`);let a=i.replace(t.search,t.replace);return await cR(s,a,"utf-8"),dt({success:!0,path:t.path})}catch(s){return Ee(s.message)}}async function fR(t,e,r,n){let o=Zt(r,[t.path],n);if(o)return Ee(o);try{let s=t.path?br(e,t.path):e,i=[];async function a(c){if(i.length>=Ya)return;let l=await Wv(c,{withFileTypes:!0});for(let u of l){if(i.length>=Ya)return;if(Yv.has(u.name))continue;let p=Jv(c,u.name),f=Kv(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>=Ya})}catch(s){return Ee(s.message)}}async function mR(t,e,r,n){let o=Zt(r,[t.pattern,t.path],n);if(o)return Ee(o);try{let s=t.path?br(e,t.path):e,i=await vB(s,e,t.pattern);return dt({matches:i,count:i.length})}catch(s){return Ee(s.message)}}async function vB(t,e,r){let n=[],o=hR(r);async function s(i){if(n.length>=Ya)return;let a;try{a=await Wv(i,{withFileTypes:!0})}catch{return}for(let c of a){if(n.length>=Ya)return;if(Yv.has(c.name))continue;let l=Jv(i,c.name),u=Kv(e,l);o.test(u)&&n.push(u),c.isDirectory()&&await s(l)}}return await s(t),n}function hR(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 gR(t,e,r,n){let o=Zt(r,[t.pattern,t.path,t.glob],n);if(o)return Ee(o);try{let s=t.path?br(e,t.path):e,i=new RegExp(t.pattern),a=t.glob?hR(t.glob):null,c=[],l=200;async function u(p){if(c.length>=l)return;let f;try{f=await Wv(p,{withFileTypes:!0})}catch{return}for(let d of f){if(c.length>=l)return;if(Yv.has(d.name))continue;let m=Jv(p,d.name);if(d.isDirectory())await u(m);else if(d.isFile()){let h=Kv(e,m);if(a&&!a.test(h))continue;try{if((await lR(m)).size>Gv)continue;let b=(await Vv(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 Ee(s.message)}}var Gv,Ya,Yv,yR=w(()=>{Tp();Ja();Ka();Gv=500*1024,Ya=1e3,Yv=new Set([".git","node_modules",".next","__pycache__",".cache","dist","build"])});import{exec as _B}from"node:child_process";async function vR(t,e,r,n){let o=Zt(r,[t.command],n);if(o)return Ee(o);let s=t.cwd?br(e,t.cwd):e,i=t.timeout??bB;return new Promise(a=>{let c=_B(t.command,{cwd:s,timeout:i,maxBuffer:Xv,env:{...process.env,HOME:process.env.HOME}},(l,u,p)=>{let f=u||"";if(p&&(f+=(f?`
394
394
  --- stderr ---
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,`
395
+ `:"")+p),f.length>Xv&&(f=f.slice(0,Xv)+`
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 bB,Xv,_R=w(()=>{Tp();Ja();Ka();bB=6e4,Xv=100*1024});import{exec as bR}from"node:child_process";function Xa(t,e){return new Promise((r,n)=>{bR(t,{cwd:e,timeout:3e4},(o,s,i)=>{if(o){n(new Error(i.trim()||o.message));return}r(s.trim())})})}async function wR(t,e){try{let r=await Xa("git status --porcelain",e);return dt(r||"(clean)")}catch(r){return Ee(r.message)}}async function xR(t,e,r,n){let o=Zt(r,[t.path],n);if(o)return Ee(o);try{let s="git diff";if(t.staged&&(s+=" --staged"),t.path){let a=br(e,t.path);s+=` -- "${a}"`}let i=await Xa(s,e);return dt(i||"(no diff)")}catch(s){return Ee(s.message)}}async function SR(t,e,r,n){let o=Zt(r,[t.message,t.files],n);if(o)return Ee(o);try{if(t.files){let i=t.files.split(",").map(a=>a.trim()).filter(Boolean);for(let a of i){let c=br(e,a);await Xa(`git add "${c}"`,e)}}else await Xa("git add -A",e);let s=await new Promise((i,a)=>{let c=bR("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 Ee(s.message)}}async function $R(t,e){try{let r=t.count??10,n=await Xa(`git log --oneline -n ${r}`,e);return dt(n||"(no commits)")}catch(r){return Ee(r.message)}}var kR=w(()=>{Tp();Ja();Ka()});function ER(t){try{let e=new URL(t);return xB.test(e.hostname)||wB.test(e.hostname)}catch{return!0}}async function TR(t,e,r,n){let{url:o,method:s="GET",headers:i={},body:a}=t;if(ER(o))return Ee("Blocked: cannot fetch localhost or private IP addresses");let c=Zt(r,[o,a],n);if(c)return Ee(c);try{let l=new AbortController,u=setTimeout(()=>l.abort(),Pp),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>li){m.cancel(),f.push(Buffer.from(b.slice(0,li-(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>li})}catch(l){let u=l instanceof Error?l.message:String(l);return u.includes("abort")?Ee(`Request timed out after ${Pp/1e3}s`):Ee(`Fetch failed: ${u}`)}}async function PR(t,e,r,n){let{url:o}=t;if(ER(o))return Ee("Blocked: cannot scrape localhost or private IP addresses");let s=Zt(r,[o],n);if(s)return Ee(s);try{let i=new AbortController,a=setTimeout(()=>i.abort(),Pp),c=await fetch(o,{headers:{Accept:"text/html,application/xhtml+xml,*/*"},signal:i.signal});if(clearTimeout(a),!c.ok)return Ee(`HTTP ${c.status}: ${c.statusText}`);let l=[],u=0,p=c.body?.getReader();if(p)for(;;){let{done:m,value:h}=await p.read();if(m)break;if(u+=h.length,u>li){p.cancel(),l.push(Buffer.from(h.slice(0,li-(u-h.length))));break}l.push(Buffer.from(h))}let f=Buffer.concat(l).toString("utf-8"),d=SB(f);return dt({url:o,status:c.status,text:d,truncated:u>li})}catch(i){let a=i instanceof Error?i.message:String(i);return a.includes("abort")?Ee(`Request timed out after ${Pp/1e3}s`):Ee(`Scrape failed: ${a}`)}}function SB(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,`
397
397
  `).replace(/<br\s*\/?>/gi,`
398
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,`
399
399
 
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=ee({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 Q=x?.temperature??e.temperature,te=x?.reasoning===!1,de=x?.reasoning_effort,G=[{role:"system",content:x?Ka(c,l,b,x,{disableReasoning:te}):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 ot=()=>{v("SIGTERM received \u2014 killing agent"),this.stopFlag=!0};process.on("SIGTERM",ot);let Et=e.contextWindow??xB[u.type]??128e3,ne=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",ot),{iterations:0,usage:h,agentId:c,role:l,status:"completed"};v(`Woke up with ${oe.length} event(s)`);let ve=o.getLastInject();ve&&(G.push({role:"user",content:`[SYSTEM] ${ve}`}),v("Injected dance state context"));for(let Qe of oe)G.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)G.length=1;else if(G.length>1+ie*2){let F=G.slice(-(ie*2));G.length=1,G.push(...F)}}for(let F of je)G.push({role:"user",content:`[SYSTEM] ${F}`});M&&G.push({role:"user",content:`[SYSTEM] ${M}`})}let oe,ve,Qe=0;for(;;){let je=Date.now();try{let M=await CR(u,G,b,Q,{...te?{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 F=1e3*Math.pow(2,Qe-1);v(`LLM call failed (attempt ${Qe}/${le}): ${M.message} \u2014 retrying in ${F}ms`),await new Promise(zt=>setTimeout(zt,F))}}if(G.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>ne&&G.length>MR+2){v(`Context compaction triggered (${ve.promptTokens.toLocaleString()} > ${ne.toLocaleString()} threshold)`);let je=G.slice(-MR);if(G.length=1,G.push(...je),o){let M=await o.fetchProtocol();M&&(G[0]={role:"system",content:Ka(c,l,b,M)});let F=await o.getState();G.push({role:"user",content:`[SYSTEM] Context was compacted. Current state: ${F}`})}else G.push({role:"user",content:"[SYSTEM] Context was compacted. Previous messages were trimmed."});v(`Compacted to ${G.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 F=o.getLastInject();F&&(G.push({role:"user",content:`[SYSTEM] ${F}`}),v("Injected dance state context"));for(let zt of M)G.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,F=IR(je),zt=Object.keys(F).length>0?`(${Object.entries(F).map(([Ee,lt])=>`${Ee}=${JSON.stringify(lt)}`).join(", ")})`:"()";if(v(`Tool: ${M}${zt}`),o&&yB.has(M)&&F.path){let Ee=await o.onFileWrite(F.path);if(Ee){G.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,F);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(F.data)try{Ee=typeof F.data=="string"?JSON.parse(F.data):F.data}catch{}nt=await o.publishEvent(F.type,Ee)}else M==="set_state"?nt=await o.setState(F.key,F.value):M==="get_state"?nt=await o.getState():M==="claim_resource"?nt=await o.claimResource(F.resource,F.reason):M==="release_resource"?nt=await o.releaseResource(F.resource):nt=JSON.stringify({error:`Unknown synthetic tool: ${M}`});else if(n&&n.hasToolName(M))nt=await n.callTool(M,F);else try{nt=await r.callTool(M,F)}catch(Ee){nt=JSON.stringify({error:`Tool call failed: ${Ee.message}`})}if(v(`${r_}\u2192 ${nt}${Ya}${a}`),G.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}`),G.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);G[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",ot);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)+`
400
+ `).trim()}var wB,xB,li,Pp,RR=w(()=>{Ka();Ja();wB=/^(127\.|10\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.|0\.|169\.254\.|::1|fc|fd|fe80)/i,xB=/^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\])/i;li=512*1024,Pp=3e4});function Qv(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=>uR(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=>pR(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=>dR(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=>fR(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=>mR(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=>gR(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=>vR(n,t,e,r)},{def:{type:"function",function:{name:"git_status",description:"Show git status (porcelain format)",parameters:{type:"object",properties:{},required:[]}}},schema:{},handler:()=>wR({},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=>xR(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=>SR(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=>TR(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=>PR(n,t,e,r)}]}var e_=w(()=>{Yu();yR();_R();kR();RR()});function CR(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 OR=w(()=>{e_()});function t_(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 IR=w(()=>{});function r_(t){let e=typeof t.data=="string"?t.data:JSON.stringify(t.data);return`Event from ${t.publishedBy}: [${t.type}] ${e}`}var Rp,AR=w(()=>{os();OR();IR();Rp=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(r_(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=r_(c);if(e.types&&!t_(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 Hv(this.danceModule,e,r,this.role,this.agentId,o,n);if("error"in s||!s.wait)return s;let i=CR(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=Zv(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=r_(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=t_(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 Fv({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=Bv(this.danceModule,e,this.role,this.agentId)}}});function zR(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=NR[r]??NR.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 jR(t,e,r,n,o){let s={temperature:n,...o};for(let i=0;i<=n_;i++)try{return t.type==="anthropic"?await TB(t,e,r,s.temperature):t.type==="ollama"?await kB(t,e,r,s.temperature):await EB(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===n_)throw a;let u=$B*Math.pow(2,i)+Math.random()*1e3;console.error(`[hive] Rate limited, retrying in ${(u/1e3).toFixed(1)}s (attempt ${i+1}/${n_})...`),await new Promise(p=>setTimeout(p,u))}throw new Error("Unreachable")}async function kB(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=LR(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 EB(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:o_(m.function.arguments)}}));else if(f.content&&r.length>0){let m=LR(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 TB(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"?o_(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 o_(t){try{return JSON.parse(t)}catch{return{}}}function MR(t){return typeof t.function.arguments=="string"?o_(t.function.arguments):t.function.arguments}function LR(t,e){let r=new Set(e.map(s=>s.function.name)),n=[],o=PB(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 PB(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 NR,n_,$B,s_=w(()=>{NR={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"};n_=5,$B=2e3});function Qa(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 DR(t,e,r){return Qa(t,e,r,null)}var qR=w(()=>{});function AB(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 NB(t,e){let{startOn:r}=t;if(!r)return;let n=ee({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 UR,ec,i_,RB,CB,OB,IB,a_,zB,jB,ZR,MB,Cp,FR=w(()=>{s_();qR();et();UR=["\x1B[36m","\x1B[33m","\x1B[35m","\x1B[32m","\x1B[34m","\x1B[91m","\x1B[92m","\x1B[93m","\x1B[94m","\x1B[95m","\x1B[96m"],ec="\x1B[0m",i_="\x1B[2m",RB=0,CB=new Set(["write_file","patch_file"]),OB=new Set(["incubator_claim","incubator_releaseClaim","incubator_setState","incubator_publishEvent"]),IB=new Set(["publish_event","set_state","get_state","claim_resource","release_resource"]),a_=[{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"]}}}];zB={cerebras:128e3,groq:128e3,ollama:8e3,openai:128e3,anthropic:2e5},jB=.8,ZR=6,MB=3,Cp=class{stopFlag=!1;stop(){this.stopFlag=!0}async run(e,r,n,o,s,i){let a=UR[RB++%UR.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}${ec}`)}};try{o&&(await o.connect(),v("ACP runtime connected")),e.startOn&&(v(`Waiting for trigger: ${AB(e.startOn)}`),await NB(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=>OB.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(...a_),v(`Tools: ${b.length} (env: ${b.length-a_.length}, acp: ${a_.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 Q=x?.temperature??e.temperature,te=x?.reasoning===!1,de=x?.reasoning_effort,V=[{role:"system",content:x?Qa(c,l,b,x,{disableReasoning:te}):DR(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 ot=()=>{v("SIGTERM received \u2014 killing agent"),this.stopFlag=!0};process.on("SIGTERM",ot);let Et=e.contextWindow??zB[u.type]??128e3,ne=Math.floor(Et*jB),le=e.maxRetries??MB;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",ot),{iterations:0,usage:h,agentId:c,role:l,status:"completed"};v(`Woke up with ${oe.length} event(s)`);let ve=o.getLastInject();ve&&(V.push({role:"user",content:`[SYSTEM] ${ve}`}),v("Injected dance state context"));for(let Qe of oe)V.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)V.length=1;else if(V.length>1+ie*2){let F=V.slice(-(ie*2));V.length=1,V.push(...F)}}for(let F of je)V.push({role:"user",content:`[SYSTEM] ${F}`});M&&V.push({role:"user",content:`[SYSTEM] ${M}`})}let oe,ve,Qe=0;for(;;){let je=Date.now();try{let M=await jR(u,V,b,Q,{...te?{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 F=1e3*Math.pow(2,Qe-1);v(`LLM call failed (attempt ${Qe}/${le}): ${M.message} \u2014 retrying in ${F}ms`),await new Promise(zt=>setTimeout(zt,F))}}if(V.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>ne&&V.length>ZR+2){v(`Context compaction triggered (${ve.promptTokens.toLocaleString()} > ${ne.toLocaleString()} threshold)`);let je=V.slice(-ZR);if(V.length=1,V.push(...je),o){let M=await o.fetchProtocol();M&&(V[0]={role:"system",content:Qa(c,l,b,M)});let F=await o.getState();V.push({role:"user",content:`[SYSTEM] Context was compacted. Current state: ${F}`})}else V.push({role:"user",content:"[SYSTEM] Context was compacted. Previous messages were trimmed."});v(`Compacted to ${V.length} messages`)}if(oe.content&&v(`${i_}${oe.content}${ec}${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 F=o.getLastInject();F&&(V.push({role:"user",content:`[SYSTEM] ${F}`}),v("Injected dance state context"));for(let zt of M)V.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,F=MR(je),zt=Object.keys(F).length>0?`(${Object.entries(F).map(([Te,lt])=>`${Te}=${JSON.stringify(lt)}`).join(", ")})`:"()";if(v(`Tool: ${M}${zt}`),o&&CB.has(M)&&F.path){let Te=await o.onFileWrite(F.path);if(Te){V.push({role:"tool",content:Te,tool_call_id:je.id??`call_${f}`}),v(`${i_}\u2192 claim conflict: ${Te}${ec}${a}`);continue}}let nt;if($&&$.has(M)&&o)try{let Te=await o.callDanceTool(M,F);nt=JSON.stringify(Te)}catch(Te){nt=JSON.stringify({error:`Dance tool failed: ${Te.message}`})}else if(o&&IB.has(M))if(M==="publish_event"){let Te={};if(F.data)try{Te=typeof F.data=="string"?JSON.parse(F.data):F.data}catch{}nt=await o.publishEvent(F.type,Te)}else M==="set_state"?nt=await o.setState(F.key,F.value):M==="get_state"?nt=await o.getState():M==="claim_resource"?nt=await o.claimResource(F.resource,F.reason):M==="release_resource"?nt=await o.releaseResource(F.resource):nt=JSON.stringify({error:`Unknown synthetic tool: ${M}`});else if(n&&n.hasToolName(M))nt=await n.callTool(M,F);else try{nt=await r.callTool(M,F)}catch(Te){nt=JSON.stringify({error:`Tool call failed: ${Te.message}`})}if(v(`${i_}\u2192 ${nt}${ec}${a}`),V.push({role:"tool",content:nt,tool_call_id:je.id??`call_${f}`}),o){let Te=await o.checkControl();if(Te.halted){v(`HALTED: ${Te.reason??"no reason"}`),en=!0;break}if(Te.paused){v(`PAUSED: ${Te.reason??"no reason"} \u2014 waiting...`);let lt=await o.waitForResume();v(`RESUMED: ${lt}`),V.push({role:"user",content:`[SYSTEM] You were paused (reason: ${Te.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=Qa(c,l,b,je);V[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",ot);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}${ec}`),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 Op,HR=w(()=>{e_();Op=class{entries;entryMap;defs;constructor(e,r,n,o){let s=Qv(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 LB}from"node:crypto";function DB(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 Ip,BR=w(()=>{AR();FR();HR();s_();Ip=class{agents=new Map;async startAgent(e,r){let n=LB(3).toString("hex"),o=`${e.role}_${n}`,s=(e.modelHint&&r.models?.[e.modelHint])??r.models?.[e.role]??r.provider??"ollama/qwen3:8b",i=zR(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 Rp(c),u=e.tools&&e.tools!=="all"?e.tools:null,p=new Op(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 Cp,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?DB(o,n):null}}});import{spawn as c_}from"node:child_process";import{randomBytes as GR}from"node:crypto";import{dirname as qB,join as UB}from"node:path";import{fileURLToPath as ZB}from"node:url";function l_(t){return new Promise(e=>setTimeout(e,t))}var FB,HB,tc,VR=w(()=>{BR();FB=qB(ZB(import.meta.url)),HB=UB(FB,"..","plugin"),tc=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 l_(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=c_(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 Ip,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 l_(u),o++,c==="claude"){let b=GR(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=GR(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=c_(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??HB,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=c_("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 l_(500);let e=this.children.get("propolis");e&&(e.kill("SIGTERM"),this.log("Stopped propolis")),this.children.clear(),this.childInfo=[]}}});import{createHmac as BB}from"node:crypto";var Ap,WR=w(()=>{Ap=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=BB("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 u_={};G(u_,{getRedisClient:()=>VB,waitForReady:()=>WB});import{createRequire as GB}from"node:module";function VB(t){let e=JR.get(t);if(e)return e;let n=GB(import.meta.url)("ioredis"),o=new n(t);return JR.set(t,o),o}async function WB(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 JR,p_=w(()=>{JR=new Map});var KR={};G(KR,{IPCTransport:()=>d_});import{connect as JB}from"node:net";var d_,YR=w(()=>{d_=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)+`
404
404
  `)}onData(e){this.buffer+=e;let r=this.buffer.split(`
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=it("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=it("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}=it("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=it("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}=it("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}=it("stream"),{randomFillSync:vG}=it("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=it("events"),CG=it("https"),IG=it("http"),LO=it("net"),AG=it("tls"),{randomBytes:NG,createHash:zG}=it("crypto"),{Duplex:yoe,Readable:voe}=it("stream"),{URL:T_}=it("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 Q;try{Q=GG(ie)}catch{ir(t,y,"Invalid Sec-WebSocket-Extensions header");return}let te=Object.keys(Q);if(te.length!==1||te[0]!==ro.extensionName){ir(t,y,"Server indicated an extension that was not requested");return}try{d.accept(Q[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}=it("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=it("events"),Up=it("http"),{Duplex:Soe}=it("stream"),{createHash:uV}=it("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
+ `);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 f_,resolve as KB}from"path";import{readdirSync as YB,statSync as XB}from"fs";function m_(t,e,r=""){t=KB(".",t);let n=YB(t),o=0,s,i;for(;o<n.length;o++)s=f_(t,n[o]),i=XB(s),i.isDirectory()?m_(s,e,f_(r,n[o])):e(f_(r,n[o]),s,i)}var XR=w(()=>{});import*as QR from"node:querystring";function eC(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=QR.parse(o.substring(1))))}return t._parsedUrl={pathname:n,search:o,query:s,hash:i,raw:e}}var tC=w(()=>{});function rC(t){let e=(""+t).trim().toLowerCase(),r=e.lastIndexOf(".");return QB[~r?e.substring(++r):e]}var QB,nC=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 iC={};G(iC,{default:()=>pG});import*as ui from"node:fs";import{join as eG,normalize as tG,resolve as rG,sep as nG}from"node:path";function sG(t,e){for(let r=0;r<e.length;r++)if(e[r].test(t))return!0}function oC(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 iG(t,e,r){let n=0,o,s=oC(e,r);for(;n<s.length;n++)if(o=t[s[n]])return o}function aG(t,e,r,n){let o=0,s=oC(r,n),i,a,c,l;for(;o<s.length;o++)if(i=tG(eG(t,c=s[o])),i.startsWith(t)&&ui.existsSync(i)){if(a=ui.statSync(i),a.isDirectory())continue;return l=sC(c,a,e),l["Cache-Control"]=e?"no-cache":"no-store",{abs:i,stats:a,headers:l}}}function cG(t,e){return e.statusCode=404,e.end()}function lG(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),ui.createReadStream(r,a).pipe(e)}function sC(t,e,r){let n=uG[t.slice(-3)],o=rC(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 pG(t,e={}){t=rG(t||".");let r=e.onNoMatch||cG,n=e.setHeaders||oG,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||m_(t,(m,h,y)=>{if(!/\.well-known[\\+\/]/.test(m)){if(!e.dotfiles&&/(^\.|[\\+|\/+]\.)/.test(m))return}let v=sC(m,y,l);f&&(v["Cache-Control"]=f),a["/"+m.normalize().replace(/\\+/g,"/")]={abs:h,stats:y,headers:v}});let d=e.dev?aG.bind(0,t+nG,l):iG.bind(0,a);return function(m,h,y){let v=[""],b=eC(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&&!sG(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),lG(m,h,$.abs,$.stats,$.headers)}}var oG,uG,aC=w(()=>{XR();tC();nC();oG=()=>{};uG={".br":"br",".gz":"gzip"}});var hn=I((Toe,uC)=>{"use strict";var cC=["nodebuffer","arraybuffer","fragments"],lC=typeof Blob<"u";lC&&cC.push("blob");uC.exports={BINARY_TYPES:cC,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:lC,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var rc=I((Poe,Np)=>{"use strict";var{EMPTY_BUFFER:dG}=hn(),h_=Buffer[Symbol.species];function fG(t,e){if(t.length===0)return dG;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 h_(r.buffer,r.byteOffset,n):r}function pC(t,e,r,n,o){for(let s=0;s<o;s++)r[n+s]=t[s]^e[s&3]}function dC(t,e){for(let r=0;r<t.length;r++)t[r]^=e[r&3]}function mG(t){return t.length===t.buffer.byteLength?t.buffer:t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function g_(t){if(g_.readOnly=!0,Buffer.isBuffer(t))return t;let e;return t instanceof ArrayBuffer?e=new h_(t):ArrayBuffer.isView(t)?e=new h_(t.buffer,t.byteOffset,t.byteLength):(e=Buffer.from(t),g_.readOnly=!1),e}Np.exports={concat:fG,mask:pC,toArrayBuffer:mG,toBuffer:g_,unmask:dC};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=it("bufferutil");Np.exports.mask=function(e,r,n,o,s){s<48?pC(e,r,n,o,s):t.mask(e,r,n,o,s)},Np.exports.unmask=function(e,r){e.length<32?dC(e,r):t.unmask(e,r)}}catch{}});var hC=I((Roe,mC)=>{"use strict";var fC=Symbol("kDone"),y_=Symbol("kRun"),v_=class{constructor(e){this[fC]=()=>{this.pending--,this[y_]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[y_]()}[y_](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[fC])}}};mC.exports=v_});var oc=I((Coe,_C)=>{"use strict";var nc=it("zlib"),gC=rc(),hG=hC(),{kStatusCode:yC}=hn(),gG=Buffer[Symbol.species],yG=Buffer.from([0,0,255,255]),jp=Symbol("permessage-deflate"),gn=Symbol("total-length"),pi=Symbol("callback"),oo=Symbol("buffers"),di=Symbol("error"),zp,__=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,!zp){let o=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;zp=new hG(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[pi];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){zp.add(o=>{this._decompress(e,r,(s,i)=>{o(),n(s,i)})})}compress(e,r,n){zp.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"?nc.Z_DEFAULT_WINDOWBITS:this.params[s];this._inflate=nc.createInflateRaw({...this._options.zlibInflateOptions,windowBits:i}),this._inflate[jp]=this,this._inflate[gn]=0,this._inflate[oo]=[],this._inflate.on("error",_G),this._inflate.on("data",vC)}this._inflate[pi]=n,this._inflate.write(e),r&&this._inflate.write(yG),this._inflate.flush(()=>{let s=this._inflate[di];if(s){this._inflate.close(),this._inflate=null,n(s);return}let i=gC.concat(this._inflate[oo],this._inflate[gn]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[gn]=0,this._inflate[oo]=[],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"?nc.Z_DEFAULT_WINDOWBITS:this.params[s];this._deflate=nc.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:i}),this._deflate[gn]=0,this._deflate[oo]=[],this._deflate.on("data",vG)}this._deflate[pi]=n,this._deflate.write(e),this._deflate.flush(nc.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let s=gC.concat(this._deflate[oo],this._deflate[gn]);r&&(s=new gG(s.buffer,s.byteOffset,s.length-4)),this._deflate[pi]=null,this._deflate[gn]=0,this._deflate[oo]=[],r&&this.params[`${o}_no_context_takeover`]&&this._deflate.reset(),n(null,s)})}};_C.exports=__;function vG(t){this[oo].push(t),this[gn]+=t.length}function vC(t){if(this[gn]+=t.length,this[jp]._maxPayload<1||this[gn]<=this[jp]._maxPayload){this[oo].push(t);return}this[di]=new RangeError("Max payload size exceeded"),this[di].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[di][yC]=1009,this.removeListener("data",vC),this.reset()}function _G(t){if(this[jp]._inflate=null,this[di]){this[pi](this[di]);return}t[yC]=1007,this[pi](t)}});var fi=I((Ooe,Mp)=>{"use strict";var{isUtf8:bC}=it("buffer"),{hasBlob:bG}=hn(),wG=[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 xG(t){return t>=1e3&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3e3&&t<=4999}function b_(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 SG(t){return bG&&typeof t=="object"&&typeof t.arrayBuffer=="function"&&typeof t.type=="string"&&typeof t.stream=="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}Mp.exports={isBlob:SG,isValidStatusCode:xG,isValidUTF8:b_,tokenChars:wG};if(bC)Mp.exports.isValidUTF8=function(t){return t.length<24?b_(t):bC(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=it("utf-8-validate");Mp.exports.isValidUTF8=function(e){return e.length<32?b_(e):t(e)}}catch{}});var k_=I((Ioe,TC)=>{"use strict";var{Writable:$G}=it("stream"),wC=oc(),{BINARY_TYPES:kG,EMPTY_BUFFER:xC,kStatusCode:EG,kWebSocket:TG}=hn(),{concat:w_,toArrayBuffer:PG,unmask:RG}=rc(),{isValidStatusCode:CG,isValidUTF8:SC}=fi(),Lp=Buffer[Symbol.species],wr=0,$C=1,kC=2,EC=3,x_=4,S_=5,Dp=6,$_=class extends $G{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||kG[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[TG]=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 Lp(n.buffer,n.byteOffset+e,n.length-e),new Lp(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 Lp(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 $C:this.getPayloadLength16(e);break;case kC:this.getPayloadLength64(e);break;case EC:this.getMask();break;case x_:this.getData(e);break;case S_:case Dp: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[wC.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=$C:this._payloadLength===127?this._state=kC: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=EC:this._state=x_}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=x_}getData(e){let r=xC;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]&&RG(r,this._mask)}if(this._opcode>7){this.controlMessage(r,e);return}if(this._compressed){this._state=S_,this.decompress(r,e);return}r.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(r)),this.dataMessage(e)}decompress(e,r){this._extensions[wC.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=w_(n,r):this._binaryType==="arraybuffer"?o=PG(w_(n,r)):this._binaryType==="blob"?o=new Blob(n):o=n,this._allowSynchronousEvents?(this.emit("message",o,!0),this._state=wr):(this._state=Dp,setImmediate(()=>{this.emit("message",o,!0),this._state=wr,this.startLoop(e)}))}else{let o=w_(n,r);if(!this._skipUTF8Validation&&!SC(o)){let s=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(s);return}this._state===S_||this._allowSynchronousEvents?(this.emit("message",o,!1),this._state=wr):(this._state=Dp,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,xC),this.end();else{let n=e.readUInt16BE(0);if(!CG(n)){let s=this.createError(RangeError,`invalid status code ${n}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");r(s);return}let o=new Lp(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!SC(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=Dp,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[EG]=o,i}};TC.exports=$_});var P_=I((Noe,CC)=>{"use strict";var{Duplex:Aoe}=it("stream"),{randomFillSync:OG}=it("crypto"),PC=oc(),{EMPTY_BUFFER:IG,kWebSocket:AG,NOOP:NG}=hn(),{isBlob:mi,isValidStatusCode:zG}=fi(),{mask:RC,toBuffer:ss}=rc(),xr=Symbol("kByteLength"),jG=Buffer.alloc(4),qp=8*1024,is,hi=qp,zr=0,MG=1,LG=2,E_=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=NG,this[AG]=void 0}static frame(e,r){let n,o=!1,s=2,i=!1;r.mask&&(n=r.maskBuffer||jG,r.generateMask?r.generateMask(n):(hi===qp&&(is===void 0&&(is=Buffer.alloc(qp)),OG(is,0,qp),hi=0),n[0]=is[hi++],n[1]=is[hi++],n[2]=is[hi++],n[3]=is[hi++]),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?(RC(e,n,l,s,a),[l]):(RC(e,n,e,0,a),[l,e])):[l,e]}close(e,r,n,o){let s;if(e===void 0)s=IG;else{if(typeof e!="number"||!zG(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):mi(e)?(o=e.size,s=!1):(e=ss(e),o=e.length,s=ss.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};mi(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):mi(e)?(o=e.size,s=!1):(e=ss(e),o=e.length,s=ss.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};mi(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[PC.extensionName],s=r.binary?2:1,i=r.compress,a,c;typeof e=="string"?(a=Buffer.byteLength(e),c=!1):mi(e)?(a=e.size,c=!1):(e=ss(e),a=e.length,c=ss.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};mi(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=LG,e.arrayBuffer().then(s=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(T_,this,a,o);return}this._bufferedBytes-=n[xr];let i=ss(s);r?this.dispatch(i,r,n,o):(this._state=zr,this.sendFrame(t.frame(i,n),o),this.dequeue())}).catch(s=>{process.nextTick(DG,this,s,o)})}dispatch(e,r,n,o){if(!r){this.sendFrame(t.frame(e,n),o);return}let s=this._extensions[PC.extensionName];this._bufferedBytes+=n[xr],this._state=MG,s.compress(e,n.fin,(i,a)=>{if(this._socket.destroyed){let c=new Error("The socket was closed while data was being compressed");T_(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)}};CC.exports=E_;function T_(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 DG(t,e,r){T_(t,e,r),t.onerror(e)}});var DC=I((zoe,LC)=>{"use strict";var{kForOnEventAttribute:sc,kListener:R_}=hn(),OC=Symbol("kCode"),IC=Symbol("kData"),AC=Symbol("kError"),NC=Symbol("kMessage"),zC=Symbol("kReason"),gi=Symbol("kTarget"),jC=Symbol("kType"),MC=Symbol("kWasClean"),yn=class{constructor(e){this[gi]=null,this[jC]=e}get target(){return this[gi]}get type(){return this[jC]}};Object.defineProperty(yn.prototype,"target",{enumerable:!0});Object.defineProperty(yn.prototype,"type",{enumerable:!0});var as=class extends yn{constructor(e,r={}){super(e),this[OC]=r.code===void 0?0:r.code,this[zC]=r.reason===void 0?"":r.reason,this[MC]=r.wasClean===void 0?!1:r.wasClean}get code(){return this[OC]}get reason(){return this[zC]}get wasClean(){return this[MC]}};Object.defineProperty(as.prototype,"code",{enumerable:!0});Object.defineProperty(as.prototype,"reason",{enumerable:!0});Object.defineProperty(as.prototype,"wasClean",{enumerable:!0});var yi=class extends yn{constructor(e,r={}){super(e),this[AC]=r.error===void 0?null:r.error,this[NC]=r.message===void 0?"":r.message}get error(){return this[AC]}get message(){return this[NC]}};Object.defineProperty(yi.prototype,"error",{enumerable:!0});Object.defineProperty(yi.prototype,"message",{enumerable:!0});var ic=class extends yn{constructor(e,r={}){super(e),this[IC]=r.data===void 0?null:r.data}get data(){return this[IC]}};Object.defineProperty(ic.prototype,"data",{enumerable:!0});var qG={addEventListener(t,e,r={}){for(let o of this.listeners(t))if(!r[sc]&&o[R_]===e&&!o[sc])return;let n;if(t==="message")n=function(s,i){let a=new ic("message",{data:i?s:s.toString()});a[gi]=this,Up(e,this,a)};else if(t==="close")n=function(s,i){let a=new as("close",{code:s,reason:i.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[gi]=this,Up(e,this,a)};else if(t==="error")n=function(s){let i=new yi("error",{error:s,message:s.message});i[gi]=this,Up(e,this,i)};else if(t==="open")n=function(){let s=new yn("open");s[gi]=this,Up(e,this,s)};else return;n[sc]=!!r[sc],n[R_]=e,r.once?this.once(t,n):this.on(t,n)},removeEventListener(t,e){for(let r of this.listeners(t))if(r[R_]===e&&!r[sc]){this.removeListener(t,r);break}}};LC.exports={CloseEvent:as,ErrorEvent:yi,Event:yn,EventTarget:qG,MessageEvent:ic};function Up(t,e,r){typeof t=="object"&&t.handleEvent?t.handleEvent.call(t,r):t.call(e,r)}});var C_=I((joe,qC)=>{"use strict";var{tokenChars:ac}=fi();function Qr(t,e,r){t[e]===void 0?t[e]=[r]:t[e].push(r)}function UG(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&&ac[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&&ac[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(ac[l]!==1)throw new SyntaxError(`Unexpected character at index ${p}`);c===-1?c=p:n||(n=!0),o=!1}else if(s)if(ac[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&&ac[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 ZG(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(", ")}qC.exports={format:ZG,parse:UG}});var Bp=I((Doe,XC)=>{"use strict";var FG=it("events"),HG=it("https"),BG=it("http"),FC=it("net"),GG=it("tls"),{randomBytes:VG,createHash:WG}=it("crypto"),{Duplex:Moe,Readable:Loe}=it("stream"),{URL:O_}=it("url"),so=oc(),JG=k_(),KG=P_(),{isBlob:YG}=fi(),{BINARY_TYPES:UC,CLOSE_TIMEOUT:XG,EMPTY_BUFFER:Zp,GUID:QG,kForOnEventAttribute:I_,kListener:eV,kStatusCode:tV,kWebSocket:gt,NOOP:HC}=hn(),{EventTarget:{addEventListener:rV,removeEventListener:nV}}=DC(),{format:oV,parse:sV}=C_(),{toBuffer:iV}=rc(),BC=Symbol("kAborted"),A_=[8,13],vn=["CONNECTING","OPEN","CLOSING","CLOSED"],aV=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,Xe=class t extends FG{constructor(e,r,n){super(),this._binaryType=UC[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Zp,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]),GC(this,e,r,n)):(this._autoPong=n.autoPong,this._closeTimeout=n.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){UC.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 KG(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",uV),o.on("drain",pV),o.on("error",dV),o.on("message",fV),o.on("ping",mV),o.on("pong",hV),s.onerror=gV,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),r.length>0&&e.unshift(r),e.on("close",JC),e.on("data",Hp),e.on("end",KC),e.on("error",YC),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[so.extensionName]&&this._extensions[so.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())}),WC(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){N_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.ping(e||Zp,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){N_(this,e,n);return}r===void 0&&(r=!this._isServer),this._sender.pong(e||Zp,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){N_(this,e,n);return}let o={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...r};this._extensions[so.extensionName]||(o.compress=!1),this._sender.send(e||Zp,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[I_])return e[eV];return null},set(e){for(let r of this.listeners(t))if(r[I_]){this.removeListener(t,r);break}typeof e=="function"&&this.addEventListener(t,e,{[I_]:!0})}})});Xe.prototype.addEventListener=rV;Xe.prototype.removeEventListener=nV;XC.exports=Xe;function GC(t,e,r,n){let o={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:XG,protocolVersion:A_[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,!A_.includes(o.protocolVersion))throw new RangeError(`Unsupported protocol version: ${o.protocolVersion} (supported versions: ${A_.join(", ")})`);let s;if(e instanceof O_)s=e;else try{s=new O_(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;Fp(t,h);return}let l=i?443:80,u=VG(16).toString("base64"),p=i?HG.request:BG.request,f=new Set,d;if(o.createConnection=o.createConnection||(i?lV:cV),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 so(o.perMessageDeflate!==!0?o.perMessageDeflate:{},!1,o.maxPayload),o.headers["Sec-WebSocket-Extensions"]=oV({[so.extensionName]:d.offer()})),r.length){for(let h of r){if(typeof h!="string"||!aV.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[BC]||(m=t._req=null,Fp(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 O_(y,e)}catch{let $=new SyntaxError(`Invalid URL: ${y}`);Fp(t,$);return}GC(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=WG("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 Q;try{Q=sV(ie)}catch{ir(t,y,"Invalid Sec-WebSocket-Extensions header");return}let te=Object.keys(Q);if(te.length!==1||te[0]!==so.extensionName){ir(t,y,"Server indicated an extension that was not requested");return}try{d.accept(Q[so.extensionName])}catch{ir(t,y,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[so.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 Fp(t,e){t._readyState=Xe.CLOSING,t._errorEmitted=!0,t.emit("error",e),t.emitClose()}function cV(t){return t.path=t.socketPath,FC.connect(t)}function lV(t){return t.path=void 0,!t.servername&&t.servername!==""&&(t.servername=FC.isIP(t.host)?"":t.host),GG.connect(t)}function ir(t,e,r){t._readyState=Xe.CLOSING;let n=new Error(r);Error.captureStackTrace(n,ir),e.setHeader?(e[BC]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Fp,t,n)):(e.destroy(n),e.once("error",t.emit.bind(t,"error")),e.once("close",t.emitClose.bind(t)))}function N_(t,e,r){if(e){let n=YG(e)?e.size:iV(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 uV(t,e){let r=this[gt];r._closeFrameReceived=!0,r._closeMessage=e,r._closeCode=t,r._socket[gt]!==void 0&&(r._socket.removeListener("data",Hp),process.nextTick(VC,r._socket),t===1005?r.close():r.close(t,e))}function pV(){let t=this[gt];t.isPaused||t._socket.resume()}function dV(t){let e=this[gt];e._socket[gt]!==void 0&&(e._socket.removeListener("data",Hp),process.nextTick(VC,e._socket),e.close(t[tV])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t))}function ZC(){this[gt].emitClose()}function fV(t,e){this[gt].emit("message",t,e)}function mV(t){let e=this[gt];e._autoPong&&e.pong(t,!this._isServer,HC),e.emit("ping",t)}function hV(t){this[gt].emit("pong",t)}function VC(t){t.resume()}function gV(t){let e=this[gt];e.readyState!==Xe.CLOSED&&(e.readyState===Xe.OPEN&&(e._readyState=Xe.CLOSING,WC(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",t)))}function WC(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function JC(){let t=this[gt];if(this.removeListener("close",JC),this.removeListener("data",Hp),this.removeListener("end",KC),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",ZC),t._receiver.on("finish",ZC))}function Hp(t){this[gt]._receiver.write(t)||this.pause()}function KC(){let t=this[gt];t._readyState=Xe.CLOSING,t._receiver.end(),this.end()}function YC(){let t=this[gt];this.removeListener("error",YC),this.on("error",HC),t&&(t._readyState=Xe.CLOSING,this.destroy())}});var rO=I((Uoe,tO)=>{"use strict";var qoe=Bp(),{Duplex:yV}=it("stream");function QC(t){t.emit("close")}function vV(){!this.destroyed&&this._writableState.finished&&this.destroy()}function eO(t){this.removeListener("error",eO),this.destroy(),this.listenerCount("error")===0&&this.emit("error",t)}function _V(t,e){let r=!0,n=new yV({...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(QC,n);return}let i=!1;t.once("error",function(c){i=!0,s(c)}),t.once("close",function(){i||s(o),process.nextTick(QC,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",vV),n.on("error",eO),n}tO.exports=_V});var oO=I((Zoe,nO)=>{"use strict";var{tokenChars:bV}=fi();function wV(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&&bV[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}nO.exports={parse:wV}});var pO=I((Hoe,uO)=>{"use strict";var xV=it("events"),Gp=it("http"),{Duplex:Foe}=it("stream"),{createHash:SV}=it("crypto"),sO=C_(),cs=oc(),$V=oO(),kV=Bp(),{CLOSE_TIMEOUT:EV,GUID:TV,kWebSocket:PV}=hn(),RV=/^[+/0-9A-Za-z]{22}==$/,iO=0,aO=1,lO=2,z_=class extends xV{constructor(e,r){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:EV,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:kV,...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=Gp.createServer((n,o)=>{let s=Gp.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=CV(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=iO}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===lO){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(cc,this);return}if(e&&this.once("close",e),this._state!==aO)if(this._state=aO,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(cc,this):process.nextTick(cc,this);else{let r=this._server;this._removeListeners(),this._removeListeners=this._server=null,r.close(()=>{cc(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",cO);let s=e.headers["sec-websocket-key"],i=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){ls(this,e,r,405,"Invalid HTTP method");return}if(i===void 0||i.toLowerCase()!=="websocket"){ls(this,e,r,400,"Invalid Upgrade header");return}if(s===void 0||!RV.test(s)){ls(this,e,r,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){ls(this,e,r,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){lc(r,400);return}let c=e.headers["sec-websocket-protocol"],l=new Set;if(c!==void 0)try{l=$V.parse(c)}catch{ls(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 cs(this.options.perMessageDeflate,!0,this.options.maxPayload);try{let d=sO.parse(u);d[cs.extensionName]&&(f.accept(d[cs.extensionName]),p[cs.extensionName]=f)}catch{ls(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 lc(r,m||401,h,y);this.completeUpgrade(p,s,l,e,r,n,o)});return}if(!this.options.verifyClient(f))return lc(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[PV])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>iO)return lc(s,503);let l=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${SV("sha1").update(r+TV).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[cs.extensionName]){let p=e[cs.extensionName].params,f=sO.format({[cs.extensionName]:[p]});l.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",l,o),s.write(l.concat(`\r
406
406
  `).join(`\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
+ `)),s.removeListener("error",cO),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(cc,this)})),a(u,o)}};uO.exports=z_;function CV(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 cc(t){t._state=lO,t.emit("close")}function cO(){this.destroy()}function lc(t,e,r,n){r=r||Gp.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} ${Gp.STATUS_CODES[e]}\r
408
408
  `+Object.keys(n).map(o=>`${o}: ${n[o]}`).join(`\r
409
409
  `)+`\r
410
410
  \r
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(Q){t.readyState===t.OPEN&&t.send(JSON.stringify(Q))}function v(Q){return u?u.has(Q.type):!0}async function b(Q){if(s&&p&&f){let te=await s.getState(i),{runInject:de}=await Promise.resolve().then(()=>(Qo(),si)),K=de(s.module,te,f,p);y({type:"event",event:Q,...K?{inject:K}:{}})}else y({type:"event",event:Q})}let x=n.subscribe(i,Q=>{v(Q)&&(m?d.push(Q):b(Q))});r.get(i).events.getEvents(c).then(async({events:Q,cursor:te})=>{for(let de of Q)v(de)&&(await b(de),h=Math.max(h,de.id));if(h=Math.max(h,te),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=${Q.length}`)}).catch(Q=>{y({type:"error",message:"Replay failed"}),o&&console.error("[incubator] WS replay error:",Q),t.close()}),t.on("message",Q=>{try{let te=JSON.parse(String(Q));if(te.type==="subscribe")u=te.types?new Set(te.types):null;else if(te.type==="publish"&&typeof te.event=="string")r.get(i).events.publish(te.event,te.data??{},te.agentId??"ui").then(K=>{n.publish(i,K),y({type:"publish_ack",eventId:K.id})}).catch(()=>{y({type:"error",message:"Failed to publish event"})});else if(te.type==="reset"){let de=r.get(i);de.state.getAll().then(async K=>{for(let ot of K)await de.state.delete(ot.key);let G=await de.events.publish("reset",{},"ui");n.publish(i,G),y({type:"reset_ack"}),o&&console.error(`[incubator] WS reset: ns=${i} (cleared ${K.length} keys)`)}).catch(()=>{y({type:"error",message:"Failed to reset state"})})}else if(te.type==="dance_call"&&s&&typeof te.tool=="string"){let de=te.agentId??p??"unknown",K=te.role??f??"unknown",G=te.callId,ot=()=>s.getState(i),Et=s.getAcpHelper(i,de),ne=Date.now();Promise.resolve().then(()=>(Qo(),si)).then(({callDanceTool:le})=>le(s.module,te.tool,te.args??{},K,de,ot,Et)).then(le=>{let Nt="error"in le?{error:le.error}:le.result;s?.telemetry?.record("dance_call",{tool:te.tool,role:K,agentId:de,success:!("error"in le),latency_ms:Date.now()-ne}),y({type:"dance_result",callId:G,result:Nt})}).catch(le=>{s?.telemetry?.record("dance_call",{tool:te.tool,role:K,agentId:de,success:!1,error:le.message,latency_ms:Date.now()-ne}),y({type:"dance_result",callId:G,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:ne,waitForReady:le}=await Promise.resolve().then(()=>(a_(),i_));b=ne(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,Q;if(typeof t.agents=="string")try{Q=JSON.parse(t.agents)}catch(ne){console.error(`[incubator] Failed to parse --agents JSON: ${ne.message}`),process.exit(1)}let te=[];for(let ne of process.argv.slice(2))ne.startsWith("--integration=")&&te.push(ne.slice(14));let de=te.length>0||t.integrations===!0,K=new vp(x),G;if(a)console.error("[incubator] WARNING: Carapace disabled \u2014 no prompt injection scanning");else{let ne=SP(i);K.setGuard(ne,i),G=le=>kP(le,ne,i),console.error("[incubator] Carapace active \u2014 scanning writes, reads, and snapshots")}if(s&&!$){let ne=await WP(s,K,G);ne>0&&console.error(`[incubator] Restored ${ne} namespace(s) from ${s}`)}if(O)try{let ne=await Rc(O);K.setProtocol("default",ne),r&&ne.name!=="default"&&K.setProtocol(ne.name,ne),console.error(`[incubator] Protocol loaded: "${ne.title}" (${ne.name})`)}catch(ne){console.error(`[incubator] Failed to load protocol: ${ne.message}`),process.exit(1)}let ot,Et=ie;if(!Et&&f)try{let ne=Hp(ac(f),"utf-8"),le=f.endsWith(".json")?JSON.parse(ne):rn.load(ne),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:ne}=await Promise.resolve().then(()=>(Qo(),si)),le=ac(Et),Nt=new URL(`file://${le}`).href;ot=await ne(Nt);let oe=[...ot.tools.keys()];console.error(`[incubator] Dances loaded: ${oe.join(", ")}${ot.inject?" + inject":""}`)}if(console.error(y?`[incubator] Backend: sqlite (${m})`:v?`[incubator] Backend: redis (${h})`:"[incubator] Backend: memory"),r){let ne=new Map,le;if(v&&b){let Y=b.duplicate(),{waitForReady:ae}=await Promise.resolve().then(()=>(a_(),i_));await ae(Y),le=new wp(b,Y)}else le=new bp;let Nt,oe=process.env.HONEYCOMB_BROKER_SOCKET,ve=process.env.HONEYCOMB_HIVE_NAME;if(oe&&ve){let Y=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:Y,subscribes:ae});await me.connect(),console.error(`[incubator] Honeycomb: connected to broker as "${ve}"`),Nt={transport:me,hiveName:ve,hivePublishes:Y,hiveSubscribes:ae}}K.setBus(le,Nt);let Qe=K.get("default"),en=new xp(le,Qe.runs);en.start();let je=[],M=new Rp(i);if(O){let Y=K.getProtocol("default");Y?.governance?.webhooks?.length&&M.register("default",Y.governance.webhooks,le)}let F=u?"https":"http",zt=u?"wss":"ws",nt,Ee;try{let Y=await Promise.resolve().then(()=>(rO(),tO)),ae=Y.default??Y,Le=Fp(gC(import.meta.url)),me=yC(Le,"..","dashboard","dist");A_(me)&&(nt=ae(me,{single:!0,dev:!0}),console.error(`[incubator] Dashboard: ${F}://localhost:${n}/dashboard`)),p&&A_(p)&&(Ee=ae(p,{single:!0,dev:!0}),console.error(`[incubator] Static: ${F}://localhost:${n}/`))}catch{}let lt=async(Y,ae)=>{if(Y.url?.startsWith("/api/")){await EP(Y,ae,K,i);return}let Le=new URL(Y.url??"/",`${F}://localhost:${n}`);if(Le.pathname==="/dashboard"||Le.pathname.startsWith("/dashboard/")){if(nt){let $r=Y.url;Y.url=Le.pathname.replace(/^\/dashboard/,"")||"/",Le.search&&(Y.url+=Le.search),nt(Y,ae,()=>{Y.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(Y,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=Y.headers["x-namespace"]||"default",Ge=K.get(me),Ce=Y.headers["mcp-session-id"];if(Ce&&ne.has(Ce)){await ne.get(Ce).transport.handleRequest(Y,ae);return}let he=`agent_${hC().slice(0,8)}`,ft=new Ll({sessionIdGenerator:()=>hC(),onsessioninitialized:$r=>{let vi=me==="default"?"":`@${me}`;console.error(`[incubator] Session ${$r} started (${he}${vi})`),ne.set($r,{server:pc,transport:ft})}});ft.onclose=()=>{let $r=ft.sessionId;$r&&(ne.delete($r),console.error(`[incubator] Session ${$r} closed`))};let pc=Iv(Ge,{agentId:he,namespace:me,persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:G,onSave:s&&!$?()=>{_p(s,K)}:void 0,getProtocol:()=>K.getProtocol(me)});await pc.connect(ft),await ft.handleRequest(Y,ae)},jr=u?SV({key:Hp(l),cert:Hp(c)},lt):xV(lt),Qt;if(ot){let{buildAcpHelper:Y}=await Promise.resolve().then(()=>(Qo(),si));Qt={module:ot,getState:async ae=>{let me=await K.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=K.get(ae);return Y({publishEvent:async(Ge,Ce,he,ft)=>{let yi=await me.events.publish(Ce,he??{},ft??Le);le.publish(ae,yi)},claimResource:async(Ge,Ce,he,ft)=>(await me.claims.claim(Ce,Ce,he,ft)).claim.resource,releaseResource:async(Ge,Ce)=>{await me.claims.release(Ce,Le)},setState:async(Ge,Ce,he)=>{await me.state.set(Ce,he,Le)}},ae,Le)}}}let Sr;try{let{setupWebSocket:Y}=await Promise.resolve().then(()=>(mC(),fC));Sr=await Y(jr,K,le,i,void 0,Qt)}catch{}if(f){let Y=Hp(ac(f),"utf-8"),ae=f.endsWith(".json")?JSON.parse(Y):rn.load(Y),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(K.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 he=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:he,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,K,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 Y=K.get("default");Tt=new Ba({namespace:"default",bus:le,eventStore:Y.events,verbose:i});let ae=Mv();if(te.length>0)for(let me of te){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: ${F}://localhost:${n}/mcp`),console.error(`[incubator] REST API: ${F}://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}`),Q&&(Pt=new Xa(Q,n,le,Qe.runs,i,Qe,K,Qt?.module),Pt.start().catch(Y=>{console.error(`[orchestrator] Fatal: ${Y.message}`),process.exit(1)}))});let Pt;process.on("SIGINT",async()=>{console.error(`
412
- [incubator] Shutting down...`),Pt&&await Pt.shutdown();for(let Y of je)await Y.shutdown();en.stop(),M.close(),Tt&&await Tt.stopAll(),Sr&&Sr.close(),await le.close(),s&&!$&&(await _p(s,K),console.error("[incubator] Snapshots saved")),b&&(await b.quit(),console.error("[incubator] Redis disconnected"));for(let[,Y]of ne)Y.server.close();jr.close(),process.exit(0)})}else{let ne=K.get("default"),Nt=Iv(ne,{agentId:o??"agent_stdio",persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:G,onSave:s&&!$?()=>{_p(s,K)}:void 0,getProtocol:()=>K.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(`
411
+ `+r)}function ls(t,e,r,n,o,s){if(t.listenerCount("wsClientError")){let i=new Error(o);Error.captureStackTrace(i,ls),t.emit("wsClientError",i,r,e)}else lc(r,n,o,s)}});var gO={};G(gO,{Receiver:()=>fO.default,Sender:()=>mO.default,WebSocket:()=>j_.default,WebSocketServer:()=>hO.default,createWebSocketStream:()=>dO.default,default:()=>OV});var dO,fO,mO,j_,hO,OV,yO=w(()=>{dO=po(rO(),1),fO=po(k_(),1),mO=po(P_(),1),j_=po(Bp(),1),hO=po(pO(),1),OV=j_.default});var vO={};G(vO,{setupWebSocket:()=>AV});async function IV(){let t=await Promise.resolve().then(()=>(yO(),gO));return(t.default??t).WebSocketServer}async function AV(t,e,r,n,o,s){let i=o??await IV(),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=>{NV(f,p,e,r,n,s)})}),{close(){a.close()}}}function NV(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(Q){t.readyState===t.OPEN&&t.send(JSON.stringify(Q))}function v(Q){return u?u.has(Q.type):!0}async function b(Q){if(s&&p&&f){let te=await s.getState(i),{runInject:de}=await Promise.resolve().then(()=>(os(),ci)),K=de(s.module,te,f,p);y({type:"event",event:Q,...K?{inject:K}:{}})}else y({type:"event",event:Q})}let x=n.subscribe(i,Q=>{v(Q)&&(m?d.push(Q):b(Q))});r.get(i).events.getEvents(c).then(async({events:Q,cursor:te})=>{for(let de of Q)v(de)&&(await b(de),h=Math.max(h,de.id));if(h=Math.max(h,te),y({type:"replay_done",cursor:h}),s){let{danceToolDefs:de}=await Promise.resolve().then(()=>(os(),ci));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=${Q.length}`)}).catch(Q=>{y({type:"error",message:"Replay failed"}),o&&console.error("[incubator] WS replay error:",Q),t.close()}),t.on("message",Q=>{try{let te=JSON.parse(String(Q));if(te.type==="subscribe")u=te.types?new Set(te.types):null;else if(te.type==="publish"&&typeof te.event=="string")r.get(i).events.publish(te.event,te.data??{},te.agentId??"ui").then(K=>{n.publish(i,K),y({type:"publish_ack",eventId:K.id})}).catch(()=>{y({type:"error",message:"Failed to publish event"})});else if(te.type==="reset"){let de=r.get(i);de.state.getAll().then(async K=>{for(let ot of K)await de.state.delete(ot.key);let V=await de.events.publish("reset",{},"ui");n.publish(i,V),y({type:"reset_ack"}),o&&console.error(`[incubator] WS reset: ns=${i} (cleared ${K.length} keys)`)}).catch(()=>{y({type:"error",message:"Failed to reset state"})})}else if(te.type==="dance_call"&&s&&typeof te.tool=="string"){let de=te.agentId??p??"unknown",K=te.role??f??"unknown",V=te.callId,ot=()=>s.getState(i),Et=s.getAcpHelper(i,de),ne=Date.now();Promise.resolve().then(()=>(os(),ci)).then(({callDanceTool:le})=>le(s.module,te.tool,te.args??{},K,de,ot,Et)).then(le=>{let Nt="error"in le?{error:le.error}:le.result;s?.telemetry?.record("dance_call",{tool:te.tool,role:K,agentId:de,success:!("error"in le),latency_ms:Date.now()-ne}),y({type:"dance_result",callId:V,result:Nt})}).catch(le=>{s?.telemetry?.record("dance_call",{tool:te.tool,role:K,agentId:de,success:!1,error:le.message,latency_ms:Date.now()-ne}),y({type:"dance_result",callId:V,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 _O=w(()=>{});var L_={};G(L_,{main:()=>LV});import{createServer as zV}from"node:http";import{createServer as jV}from"node:https";import{randomUUID as bO}from"node:crypto";import{fileURLToPath as wO}from"node:url";import{dirname as Vp,join as xO,resolve as uc}from"node:path";import{existsSync as M_,readFileSync as Wp}from"node:fs";function MV(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 LV(){let t=MV(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:ne,waitForReady:le}=await Promise.resolve().then(()=>(p_(),u_));b=ne(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,Q;if(typeof t.agents=="string")try{Q=JSON.parse(t.agents)}catch(ne){console.error(`[incubator] Failed to parse --agents JSON: ${ne.message}`),process.exit(1)}let te=[];for(let ne of process.argv.slice(2))ne.startsWith("--integration=")&&te.push(ne.slice(14));let de=te.length>0||t.integrations===!0,K=new xp(x),V;if(a)console.error("[incubator] WARNING: Carapace disabled \u2014 no prompt injection scanning");else{let ne=PP(i);K.setGuard(ne,i),V=le=>CP(le,ne,i),console.error("[incubator] Carapace active \u2014 scanning writes, reads, and snapshots")}if(s&&!$){let ne=await QP(s,K,V);ne>0&&console.error(`[incubator] Restored ${ne} namespace(s) from ${s}`)}if(O)try{let ne=await Ac(O);K.setProtocol("default",ne),r&&ne.name!=="default"&&K.setProtocol(ne.name,ne),console.error(`[incubator] Protocol loaded: "${ne.title}" (${ne.name})`)}catch(ne){console.error(`[incubator] Failed to load protocol: ${ne.message}`),process.exit(1)}let ot,Et=ie;if(!Et&&f)try{let ne=Wp(uc(f),"utf-8"),le=f.endsWith(".json")?JSON.parse(ne):rn.load(ne),Nt=le.hives??{},oe=Object.values(Nt)[0],ve=oe?.dances??oe?.logic??le.dances??le.logic;typeof ve=="string"&&(Et=uc(Vp(f),ve))}catch{}if(Et){let{loadDances:ne}=await Promise.resolve().then(()=>(os(),ci)),le=uc(Et),Nt=new URL(`file://${le}`).href;ot=await ne(Nt);let oe=[...ot.tools.keys()];console.error(`[incubator] Dances loaded: ${oe.join(", ")}${ot.inject?" + inject":""}`)}if(console.error(y?`[incubator] Backend: sqlite (${m})`:v?`[incubator] Backend: redis (${h})`:"[incubator] Backend: memory"),r){let ne=new Map,le;if(v&&b){let Y=b.duplicate(),{waitForReady:ae}=await Promise.resolve().then(()=>(p_(),u_));await ae(Y),le=new kp(b,Y)}else le=new $p;let Nt,oe=process.env.HONEYCOMB_BROKER_SOCKET,ve=process.env.HONEYCOMB_HIVE_NAME;if(oe&&ve){let Y=process.env.HONEYCOMB_PUBLISHES?.split(",").filter(Boolean)??[],ae=process.env.HONEYCOMB_SUBSCRIBES?.split(",").filter(Boolean)??[],{IPCTransport:Le}=await Promise.resolve().then(()=>(YR(),KR)),me=new Le({socketPath:oe,hiveName:ve,publishes:Y,subscribes:ae});await me.connect(),console.error(`[incubator] Honeycomb: connected to broker as "${ve}"`),Nt={transport:me,hiveName:ve,hivePublishes:Y,hiveSubscribes:ae}}K.setBus(le,Nt);let Qe=K.get("default"),en=new Ep(le,Qe.runs);en.start();let je=[],M=new Ap(i);if(O){let Y=K.getProtocol("default");Y?.governance?.webhooks?.length&&M.register("default",Y.governance.webhooks,le)}let F=u?"https":"http",zt=u?"wss":"ws",nt,Te;try{let Y=await Promise.resolve().then(()=>(aC(),iC)),ae=Y.default??Y,Le=Vp(wO(import.meta.url)),me=xO(Le,"..","dashboard","dist");M_(me)&&(nt=ae(me,{single:!0,dev:!0}),console.error(`[incubator] Dashboard: ${F}://localhost:${n}/dashboard`)),p&&M_(p)&&(Te=ae(p,{single:!0,dev:!0}),console.error(`[incubator] Static: ${F}://localhost:${n}/`))}catch{}let lt=async(Y,ae)=>{if(Y.url?.startsWith("/api/")){await OP(Y,ae,K,i);return}let Le=new URL(Y.url??"/",`${F}://localhost:${n}`);if(Le.pathname==="/dashboard"||Le.pathname.startsWith("/dashboard/")){if(nt){let $r=Y.url;Y.url=Le.pathname.replace(/^\/dashboard/,"")||"/",Le.search&&(Y.url+=Le.search),nt(Y,ae,()=>{Y.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==="/"&&!Te&&nt){ae.writeHead(302,{Location:"/dashboard"}),ae.end();return}Te?Te(Y,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=Y.headers["x-namespace"]||"default",Ge=K.get(me),Oe=Y.headers["mcp-session-id"];if(Oe&&ne.has(Oe)){await ne.get(Oe).transport.handleRequest(Y,ae);return}let he=`agent_${bO().slice(0,8)}`,ft=new Zl({sessionIdGenerator:()=>bO(),onsessioninitialized:$r=>{let wi=me==="default"?"":`@${me}`;console.error(`[incubator] Session ${$r} started (${he}${wi})`),ne.set($r,{server:gc,transport:ft})}});ft.onclose=()=>{let $r=ft.sessionId;$r&&(ne.delete($r),console.error(`[incubator] Session ${$r} closed`))};let gc=jv(Ge,{agentId:he,namespace:me,persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:V,onSave:s&&!$?()=>{Sp(s,K)}:void 0,getProtocol:()=>K.getProtocol(me)});await gc.connect(ft),await ft.handleRequest(Y,ae)},jr=u?jV({key:Wp(l),cert:Wp(c)},lt):zV(lt),Qt;if(ot){let{buildAcpHelper:Y}=await Promise.resolve().then(()=>(os(),ci));Qt={module:ot,getState:async ae=>{let me=await K.get(ae).state.query(),Ge={};for(let Oe of me)Ge[Oe.key]=typeof Oe.value=="string"?Oe.value:JSON.stringify(Oe.value);return Ge},getAcpHelper:(ae,Le)=>{let me=K.get(ae);return Y({publishEvent:async(Ge,Oe,he,ft)=>{let bi=await me.events.publish(Oe,he??{},ft??Le);le.publish(ae,bi)},claimResource:async(Ge,Oe,he,ft)=>(await me.claims.claim(Oe,Oe,he,ft)).claim.resource,releaseResource:async(Ge,Oe)=>{await me.claims.release(Oe,Le)},setState:async(Ge,Oe,he)=>{await me.state.set(Oe,he,Le)}},ae,Le)}}}let Sr;try{let{setupWebSocket:Y}=await Promise.resolve().then(()=>(_O(),vO));Sr=await Y(jr,K,le,i,void 0,Qt)}catch{}if(f){let Y=Wp(uc(f),"utf-8"),ae=f.endsWith(".json")?JSON.parse(Y):rn.load(Y),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})),Oe=me?.acp??me?.spec??me?.protocol;if(typeof Oe=="string"&&O===void 0){let er=uc(Vp(f),Oe);if(M_(er)){let uo=await Ac(er);if(K.setProtocol("default",uo),console.error(`[incubator] Protocol loaded from brood: ${Oe}`),Ge.length===0&&uo.roles){for(let[yc,vc]of Object.entries(uo.roles)){let qI=typeof vc.agents=="number"?vc.agents:1;for(let ob=0;ob<qI;ob++)Ge.push({role:yc,type:"worker",prompt:void 0,wakeOn:void 0})}console.error(`[incubator] Derived ${Ge.length} agents from spec roles`)}}}let he=typeof ae.stagger=="number"?ae.stagger:0,ft=typeof ae.provider=="string"?ae.provider:"ollama/qwen3:8b",bi=ae.env??{},gc=Vp(wO(import.meta.url)),$r=xO(gc,"agent","cli.js");console.error(`[incubator] Brood loaded: ${Ge.length} agents (${ft}), waiting for "start" event`);let wi=!1;le.subscribe("default",er=>{if(er.type==="start"&&!wi){wi=!0,console.error("[orchestrator] Start event received, spawning agents...");let uo={provider:ft,stagger:he,noAcp:!1,propolisPort:0,worktree:process.cwd(),hiveEntry:$r,tls:u,env:bi,agents:Ge},yc=new tc(uo,n,le,Qe.runs,i,Qe,K,Qt?.module);yc.start().catch(vc=>{console.error(`[orchestrator] Spawn failed: ${vc.message}`)}),je.push(yc)}if(er.type==="reset"){wi=!1;for(let uo of je)uo.shutdown().catch(()=>{});je.length=0,console.error("[orchestrator] Reset \u2014 agents stopped, ready for new game")}})}let Tt;if(de){let Y=K.get("default");Tt=new Wa({namespace:"default",bus:le,eventStore:Y.events,verbose:i});let ae=Uv();if(te.length>0)for(let me of te){let Ge=ae[me];if(Ge)try{await Tt.load(me,Ge.package,Ge.config)}catch(Oe){console.error(`[integrations] Failed to load "${me}": ${Oe.message}`)}else try{await Tt.load(me,me)}catch(Oe){console.error(`[integrations] Failed to load "${me}": ${Oe.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: ${F}://localhost:${n}/mcp`),console.error(`[incubator] REST API: ${F}://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}`),Q&&(Pt=new tc(Q,n,le,Qe.runs,i,Qe,K,Qt?.module),Pt.start().catch(Y=>{console.error(`[orchestrator] Fatal: ${Y.message}`),process.exit(1)}))});let Pt;process.on("SIGINT",async()=>{console.error(`
412
+ [incubator] Shutting down...`),Pt&&await Pt.shutdown();for(let Y of je)await Y.shutdown();en.stop(),M.close(),Tt&&await Tt.stopAll(),Sr&&Sr.close(),await le.close(),s&&!$&&(await Sp(s,K),console.error("[incubator] Snapshots saved")),b&&(await b.quit(),console.error("[incubator] Redis disconnected"));for(let[,Y]of ne)Y.server.close();jr.close(),process.exit(0)})}else{let ne=K.get("default"),Nt=jv(ne,{agentId:o??"agent_stdio",persistPath:$?void 0:s,verbose:i,sanitizeSnapshot:V,onSave:s&&!$?()=>{Sp(s,K)}:void 0,getProtocol:()=>K.getProtocol("default")}),oe=new Ml;await Nt.connect(oe),console.error(`[incubator] Running on stdio (agent: ${o??"agent_stdio"})`),s&&!$&&console.error(`[incubator] Persistence: ${s}`)}}var D_=w(()=>{QS();p$();Mv();IP();dp();YP();eR();tR();Ci();ji();sR();iR();VR();WR()});var SO={};G(SO,{serve:()=>DV});async function DV(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
413
413
  ${g("bold","wgl serve")} \u2014 start a local incubator server
414
414
 
415
415
  ${g("cyan","USAGE:")}
@@ -425,10 +425,10 @@ ${g("cyan","EXAMPLES:")}
425
425
  wgl serve --port 4000
426
426
  wgl serve --protocol workflow.acp
427
427
  wgl serve --persist ./data.db
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(`
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(P("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(()=>(D_(),L_)),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 $O=w(()=>{"use strict";$e()});var W_={};G(W_,{deleteGlobalConfigValue:()=>ZV,getGlobalConfigValue:()=>G_,getHomeDir:()=>kc,getWglDir:()=>qV,loadGlobalConfig:()=>ze,saveGlobalConfig:()=>UV,setGlobalConfigValue:()=>pc});import{readFileSync as q_,writeFileSync as U_,existsSync as Z_}from"node:fs";import{join as F_}from"node:path";import{homedir as H_}from"node:os";function qV(){return Mr}function ze(){let t=Lr();return{...us,defaultPlatform:t.platform,defaultRole:t.role??us.defaultRole,editor:t.cli.editor,activeProfile:t.activeProfile}}function UV(t){let e={};t.defaultPlatform!==us.defaultPlatform&&(e.platform=t.defaultPlatform),t.defaultRole!==us.defaultRole&&(e.role=t.defaultRole),t.editor!==us.editor&&(e.cli={...e.cli,editor:t.editor}),t.activeProfile!==us.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=F_(H_(),".wglrc.json"),o=Z_(n)?V_(q_(n,"utf8")):{},s=wn(o,e);U_(n,JSON.stringify(s,null,2)+`
429
+ `)}function G_(t){let r=Lr(),n=B_[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 pc(t,e){let r=F_(H_(),".wglrc.json"),n=Z_(r)?V_(q_(r,"utf8")):{},o=B_[t]||t;Si(n,o,FV(e)),U_(r,JSON.stringify(n,null,2)+`
430
+ `)}function ZV(t){if(t in us)return!1;let e=F_(H_(),".wglrc.json");if(!Z_(e))return!1;let r=V_(q_(e,"utf8")),n=B_[t]||t;return!n.includes(".")&&n in r?(delete r[n],U_(e,JSON.stringify(r,null,2)+`
431
+ `),!0):!1}function V_(t){try{let e=JSON.parse(t);return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}catch{return{}}}function FV(t){if(t==="true")return!0;if(t==="false")return!1;let e=Number(t);return!Number.isNaN(e)&&t!==""?e:t}var us,B_,_n=w(()=>{"use strict";kn();us={defaultPlatform:"https://hivemind.honeyb.dev",defaultRole:"developer",editor:"nano",activeProfile:"personal"},B_={defaultPlatform:"platform",defaultRole:"role",editor:"cli.editor",activeProfile:"activeProfile"}});import{request as HV}from"node:http";import{request as BV}from"node:https";function io(t,e,r,n={}){return new Promise((o,s)=>{let i=new URL(e),c=i.protocol==="https:"?BV:HV,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:GV},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 GV,J_=w(()=>{GV=1e4});function kO(){return Mr}function EO(){return go()}function TO(t){ki(t)}function ao(t){return Rd(t)}function ps(t,e){Cd(t,e)}function Jp(t){return Od(t)}function dc(){return Id()}function vi(t){return Date.now()/1e3>t.expiresAt-60}async function Kp(){let t=await io("POST","https://github.com/login/device/code",{client_id:PO,scope:"read:user user:email"},{Accept:"application/json"});if(!t.ok)throw new Error("Failed to start device flow");return t.data}async function Yp(t,e,r){let n=Date.now()+r*1e3;for(;Date.now()<n;){await new Promise(s=>setTimeout(s,e*1e3));let o=await io("POST","https://github.com/login/oauth/access_token",{client_id:PO,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 Xp(t,e){let r=await io("POST",`${t}/api/auth/device/exchange`,{github_access_token:e});if(!r.ok)throw new Error("Token exchange failed");return r.data}async function Qp(t,e){let r=await io("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 ed(t,e){let r=await io("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 PO,K_=w(()=>{J_();kn();PO="Ov23liy8H1qGZdVAk1Vr"});function Fe(t){let e=t?.profileName||"personal",r=ao(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 ed(n.platform,n.refreshToken);a=d.access_token,ps(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(vi(n))return c||(c=l()),c}function p(d,m,h,y=!1){let v=`${i}${m}`,b={};return y||(b.Authorization=`Bearer ${a}`),io(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)}`),getBalance:()=>f("GET","/colony/billing/balance"),getTransactions:d=>{let m=new URLSearchParams;d?.limit&&m.set("limit",String(d.limit)),d?.offset&&m.set("offset",String(d.offset)),d?.type&&m.set("type",d.type);let h=m.toString();return f("GET",`/colony/billing/transactions${h?"?"+h:""}`)},getRates:d=>{let m=d?`?category=${encodeURIComponent(d)}`:"";return f("GET",`/colony/billing/rates${m}`)},purchasePollen:d=>f("POST","/colony/billing/purchase",{pollen_amount:d}),estimateCost:d=>{let m=new URLSearchParams;d?.agent_type&&m.set("agent_type",d.agent_type),d?.provider&&m.set("provider",d.provider),d?.hours&&m.set("hours",String(d.hours)),d?.agents&&m.set("agents",String(d.agents));let h=m.toString();return f("GET",`/colony/billing/estimate${h?"?"+h:""}`)},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 RO,CO=w(()=>{J_();K_();RO=Fe});var Y_={};G(Y_,{createHivemindClient:()=>Fe,createPlatformClient:()=>RO,exchangeGitHubToken:()=>Xp,getActiveProfile:()=>ao,getWglDir:()=>kO,isTokenExpired:()=>vi,listProfiles:()=>dc,loadAuthStore:()=>EO,pollDeviceFlow:()=>Yp,refreshToken:()=>ed,removeProfile:()=>Jp,saveAuthStore:()=>TO,setProfile:()=>ps,startDeviceFlow:()=>Kp,verifyPat:()=>Qp});var co=w(()=>{CO();K_()});var OO={};G(OO,{auth:()=>VV});async function VV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
432
432
  ${g("bold","wgl auth")} \u2014 Hivemind authentication
433
433
 
434
434
  ${g("cyan","USAGE:")}
@@ -438,10 +438,10 @@ ${g("cyan","USAGE:")}
438
438
  wgl auth status Show current auth state
439
439
  wgl auth switch <profile> Switch between saved profiles
440
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}...
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(`
441
+ `));try{let c=await Qp(s,a);ps(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 Kp();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 Yp(a.device_code,a.interval||5,a.expires_in||300);console.log(g("dim","Exchanging token with Hivemind..."));let l=await Xp(s,c);ps(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";Jp(n)?console.log(A(`Logged out (profile: ${n})`)):console.log(g("dim","Not logged in"));break}case"status":{let n=ze().activeProfile||"personal",o=ao(n);if(console.log(P("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)),vi(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=dc();if(s.length>1){console.log(P("Available Profiles"));for(let i of s){let a=i===n?g("green"," (active)"):"",c=ao(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=ao(r);if(!n){console.log(_(`Profile not found: ${r}`));let o=dc();o.length>0&&console.log(g("dim",` Available: ${o.join(", ")}`)),process.exit(1);return}pc("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 IO=w(()=>{"use strict";$e();_n();co()});var NO={};G(NO,{configCmd:()=>WV});async function WV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
445
445
  ${g("bold","wgl config")} \u2014 global preferences
446
446
 
447
447
  ${g("cyan","USAGE:")}
@@ -461,7 +461,7 @@ ${g("cyan","KEYS (dotted paths supported):")}
461
461
  carapace.threshold Block threshold (0-100)
462
462
  telemetry.endpoint Telemetry endpoint URL
463
463
  telemetry.apiKey Telemetry API key
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
+ `);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}pc(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=G_(r);n!==void 0?console.log(n):(console.log(_(`Key not found: ${r}`)),process.exit(1));break}case"list":{let r=Lr(),n=AO(r);console.log(P("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 AO(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(...AO(o,s)):o!==void 0&&o!==""&&r.push([s,String(o)])}return r}var zO=w(()=>{"use strict";$e();_n();kn()});var jO={};G(jO,{marketplace:()=>XV});import{readFileSync as JV,writeFileSync as KV}from"node:fs";import{basename as YV}from"node:path";async function XV(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
465
465
  ${g("bold","wgl marketplace")} \u2014 protocol marketplace
466
466
 
467
467
  ${g("cyan","USAGE:")}
@@ -470,10 +470,10 @@ ${g("cyan","USAGE:")}
470
470
  wgl marketplace install <name> Download + load into local server
471
471
  wgl marketplace publish <file> [--name N] [--title T] [--tags t1,t2]
472
472
  wgl marketplace list Your published specs (auth required)
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 ee(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(`
473
+ `);return}switch(e){case"search":{await QV(t.slice(1));break}case"info":{await e3(t.slice(1));break}case"install":{await t3(t.slice(1));break}case"publish":{await r3(t.slice(1));break}case"list":{await n3();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(P("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 e3(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(P("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(P("Roles"));for(let i of s.roles)console.log(` ${g("bold",i.name)}${i.description?` \u2014 ${i.description}`:""}`)}if(s.phases?.length){console.log(P("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 t3(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 ee(s).loadProtocol(o)).ok){console.log(A(`Installed and loaded: ${e}`));return}}catch{}let a=`${YV(e).replace(/[/\\]/g,"_")}.acp.json`;KV(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 r3(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 n3(){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(P("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 MO=w(()=>{"use strict";$e();co();mt();_n();et()});var UO={};G(UO,{integrations:()=>a3});import{readFileSync as X_,writeFileSync as o3,mkdirSync as s3,existsSync as LO}from"node:fs";import{join as Q_}from"node:path";import{homedir as i3}from"node:os";function DO(){return Q_(i3(),".config","honeybee")}function qO(){return Q_(DO(),"integrations.json")}function fc(){let t=qO();if(!LO(t))return{};try{return JSON.parse(X_(t,"utf8"))}catch{return{}}}function td(t){let e=DO();LO(e)||s3(e,{recursive:!0}),o3(qO(),JSON.stringify(t,null,2)+`
476
+ `,{mode:384})}async function a3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
477
477
  ${g("bold","wgl integrations")} \u2014 integration marketplace
478
478
 
479
479
  ${g("cyan","USAGE:")}
@@ -485,8 +485,8 @@ ${g("cyan","USAGE:")}
485
485
  wgl integrations enable <name> Enable an installed integration
486
486
  wgl integrations disable <name> Disable an integration
487
487
  wgl integrations publish <dir> Publish an integration (auth required)
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(`
488
+ `);return}switch(e){case"search":{await c3(t.slice(1));break}case"info":{await l3(t.slice(1));break}case"install":{await u3(t.slice(1));break}case"remove":{await p3(t.slice(1));break}case"list":{await d3();break}case"enable":{await f3(t.slice(1));break}case"disable":{await m3(t.slice(1));break}case"publish":{await h3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl integrations --help` for usage"),process.exit(2)}}function rd(){return Fe({profileName:ze().activeProfile||"personal"})}async function c3(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 rd().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(P("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 l3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations info <name>")),process.exit(2));try{let n=await rd().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(P("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(P("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 u3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations install <name>")),process.exit(2));try{let n=await rd().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=fc();a[e]={package:s,enabled:!0,config:{}},td(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 p3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations remove <name>")),process.exit(2));let r=fc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),delete r[e],td(r),console.log(A(`Removed: ${e}`))}async function d3(){let t=fc(),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(P("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 f3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations enable <name>")),process.exit(2));let r=fc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!0,td(r),console.log(A(`Enabled: ${e}`))}async function m3(t){let e=t[0];e||(console.log(_("Usage: wgl integrations disable <name>")),process.exit(2));let r=fc();r[e]||(console.log(_(`Integration not installed: ${e}`)),process.exit(1)),r[e].enabled=!1,td(r),console.log(A(`Disabled: ${e}`))}async function h3(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=X_(o,"utf8")}catch{try{s=X_(Q_(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 rd().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 ZO=w(()=>{"use strict";$e();co();_n()});var FO={};G(FO,{secret:()=>y3});async function y3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
490
490
  ${g("bold","wgl secret")} \u2014 manage provider API keys (cloud)
491
491
 
492
492
  ${g("cyan","USAGE:")}
@@ -513,7 +513,29 @@ ${g("cyan","EXAMPLES:")}
513
513
  echo "sk-..." | wgl secret set openai --hive abc123
514
514
  wgl secret list
515
515
  wgl secret delete groq
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(`
516
+ `);return}switch(e){case"set":await v3(t.slice(1));break;case"list":await _3();break;case"delete":await b3(t.slice(1));break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl secret --help` for usage"),process.exit(2)}}async function eb(){let{createHivemindClient:t}=await Promise.resolve().then(()=>(co(),Y_)),{loadGlobalConfig:e}=await Promise.resolve().then(()=>(_n(),W_));return t({profileName:e().activeProfile||"personal"})}async function v3(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}g3.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 w3();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 eb();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 _3(){try{let e=await(await eb()).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(P("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 b3(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 eb();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 w3(){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 g3,HO=w(()=>{"use strict";$e();g3=new Set(["cerebras","groq","openai","anthropic","ollama"])});var BO={};G(BO,{billing:()=>x3});async function x3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
517
+ ${g("bold","wgl billing")} \u2014 pollen credits & usage
518
+
519
+ ${g("cyan","USAGE:")}
520
+ wgl billing balance Show pollen balance
521
+ wgl billing history [--limit N] Transaction history
522
+ wgl billing rates [--category CAT] Current pricing rates
523
+ wgl billing purchase <amount> Buy pollen credits
524
+ wgl billing estimate [options] Estimate cost for a hive run
525
+
526
+ ${g("cyan","ESTIMATE OPTIONS:")}
527
+ --type drone|worker|claude|queen Agent type (default: drone)
528
+ --provider cerebras|groq|openai|... LLM provider (default: cerebras)
529
+ --hours N Run duration (default: 1)
530
+ --agents N Agent count (default: 1)
531
+
532
+ ${g("cyan","EXAMPLES:")}
533
+ wgl billing balance
534
+ wgl billing history --limit 10
535
+ wgl billing rates --category orchestration
536
+ wgl billing purchase 50000
537
+ wgl billing estimate --type worker --provider cerebras --hours 2 --agents 3
538
+ `);return}switch(e){case"balance":await S3();break;case"history":await $3(t.slice(1));break;case"rates":await k3(t.slice(1));break;case"purchase":await E3(t.slice(1));break;case"estimate":await T3(t.slice(1));break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl billing --help` for usage"),process.exit(2)}}async function mc(){let{createHivemindClient:t}=await Promise.resolve().then(()=>(co(),Y_)),{loadGlobalConfig:e}=await Promise.resolve().then(()=>(_n(),W_));return t({profileName:e().activeProfile||"personal"})}function lo(t,e){let r=t.indexOf(e);return r!==-1?t[r+1]:void 0}async function S3(){try{let e=await(await mc()).getBalance();if(!e.ok||!e.data){console.log(_("Failed to fetch balance")),process.exit(1);return}let r=e.data;console.log(P("Pollen Balance")),console.log(S("Balance",`${g("bold",String(r.balance))} pollen (${g("green","$"+r.balance_usd.toFixed(2))} USD)`)),console.log(S("Lifetime purchased",String(r.lifetime_purchased))),console.log(S("Lifetime spent",String(r.lifetime_spent))),console.log(S("Lifetime credited",String(r.lifetime_credited))),console.log(S("Last updated",r.updated_at)),console.log()}catch(t){console.log(_(t.message)),process.exit(1)}}async function $3(t){try{let e=await mc(),r=parseInt(lo(t,"--limit")||"20",10),n=parseInt(lo(t,"--offset")||"0",10),o=lo(t,"--type"),s=await e.getTransactions({limit:r,offset:n,type:o});if(!s.ok||!s.data){console.log(_("Failed to fetch transactions")),process.exit(1);return}let{transactions:i,total:a}=s.data;if(console.log(P(`Transactions (${a} total)`)),i.length===0){console.log(fo(" No transactions yet"));return}for(let c of i){let u=`${c.amount>=0?g("green","+"):g("red","")}${c.amount} pollen`,p=g("cyan",c.type);console.log(` ${u} ${p} ${fo(c.description)}`),console.log(fo(` ${c.created_at} balance: ${c.balance_after}`))}console.log()}catch(e){console.log(_(e.message)),process.exit(1)}}async function k3(t){try{let e=await mc(),r=lo(t,"--category"),n=await e.getRates(r);if(!n.ok||!n.data){console.log(_("Failed to fetch rates")),process.exit(1);return}let{rates:o,pricing_tiers:s,pollen_to_usd:i}=n.data;console.log(P("Pollen Rates")),console.log(fo(` 1 pollen = $${i}`)),console.log();for(let[a,c]of Object.entries(o)){console.log(` ${g("bold",a.toUpperCase())}`);for(let l of c){let u=(l.pollen_cost*i).toFixed(4);console.log(` ${S(l.name,`${l.pollen_cost} pollen/${l.unit} ($${u})`)}`)}console.log()}console.log(g("bold"," PURCHASE TIERS"));for(let a of s){let c=a.max_pollen?a.max_pollen.toLocaleString():"\u221E";console.log(` ${S(a.label,`${a.min_pollen.toLocaleString()}-${c} pollen @ $${a.price_per_pollen}/pollen`)}`)}console.log()}catch(e){console.log(_(e.message)),process.exit(1)}}async function E3(t){let e=t[0];if(!e){console.log(_("Usage: wgl billing purchase <pollen_amount>")),console.log(fo(" Amount must be between 1,000 and 10,000,000")),process.exit(2);return}let r=parseInt(e,10);if(isNaN(r)||r<1e3||r>1e7){console.log(_("pollen_amount must be between 1,000 and 10,000,000")),process.exit(2);return}try{let o=await(await mc()).purchasePollen(r);if(!o.ok||!o.data){console.log(_("Failed to initiate purchase")),process.exit(1);return}let s=o.data;console.log(P("Pollen Purchase")),console.log(S("Amount",`${s.pollen_amount.toLocaleString()} pollen`)),console.log(S("Price",`$${s.usd_amount.toFixed(2)} USD`)),console.log(S("Tier",s.pricing_tier)),s.checkout_url?(console.log(),console.log(A("Checkout URL:")),console.log(` ${s.checkout_url}`)):s.message&&(console.log(),console.log(fo(` ${s.message}`))),console.log()}catch(n){console.log(_(n.message)),process.exit(1)}}async function T3(t){try{let e=await mc(),r={},n=lo(t,"--type"),o=lo(t,"--provider"),s=lo(t,"--hours"),i=lo(t,"--agents");n&&(r.agent_type=n),o&&(r.provider=o),s&&(r.hours=parseFloat(s)),i&&(r.agents=parseInt(i,10));let a=await e.estimateCost(r);if(!a.ok||!a.data){console.log(_("Failed to get estimate")),process.exit(1);return}let c=a.data.estimate;console.log(P("Cost Estimate")),console.log(S("Agent type",c.agent_type)),console.log(S("Agent count",String(c.agent_count))),console.log(S("Provider",c.provider)),console.log(S("Duration",`${c.hours}h`)),console.log(),console.log(S("Orchestration",`${c.orchestration_pph} pollen/hr per agent`)),console.log(S("Inference (est)",`${c.inference_pph_estimate} pollen/hr per agent`)),console.log(),console.log(S("Total pollen",g("bold",String(c.total_pollen)))),console.log(S("Total USD",g("green","$"+c.total_usd.toFixed(2)))),console.log()}catch(e){console.log(_(e.message)),process.exit(1)}}var GO=w(()=>{"use strict";$e()});var WO={};G(WO,{hive:()=>C3});import{readFileSync as tb,existsSync as P3}from"node:fs";import{resolve as VO,dirname as R3}from"node:path";async function C3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
517
539
  ${g("bold","wgl hive")} \u2014 managed hive coordination (Colony)
518
540
 
519
541
  ${g("cyan","USAGE:")}
@@ -529,7 +551,7 @@ ${g("cyan","USAGE:")}
529
551
  wgl hive keys list List API keys
530
552
  wgl hive keys revoke <id> Revoke an API key
531
553
  wgl hive logs <id> Tail hive events
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(`
554
+ `);return}if(e==="keys"){await F3(t.slice(1));return}if(e==="config"){await L3(t.slice(1));return}switch(e){case"create":{await O3(t.slice(1));break}case"list":{await I3();break}case"info":{await A3(t.slice(1));break}case"start":{await M3(t.slice(1));break}case"delete":{await N3(t.slice(1));break}case"pause":{await z3(t.slice(1));break}case"resume":{await j3(t.slice(1));break}case"logs":{await Z3(t.slice(1));break}default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl hive --help` for usage"),process.exit(2)}}async function O3(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=tb(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=tb(c,"utf8")}catch{console.log(_(`Cannot read brood file: ${c}`)),process.exit(1);return}let u=U3(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=R3(VO(c)),f=VO(p,u.acpFile);if(P3(f))try{let d=tb(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 I3(){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(P("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 A3(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(P("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(P("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:${q3(l)} ${u}`),a.error&&console.log(` ${g("red",a.error)}`)}}}catch{}console.log()}catch(r){console.log(_(r.message)),process.exit(1)}}async function N3(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 z3(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 j3(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 M3(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 L3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
533
555
  ${g("bold","wgl hive config")} \u2014 hive configuration
534
556
 
535
557
  ${g("cyan","USAGE:")}
@@ -538,17 +560,17 @@ ${g("cyan","USAGE:")}
538
560
  ${g("cyan","EXAMPLES:")}
539
561
  echo "sk-..." | wgl hive config set-key abc123 openai
540
562
  cat ~/.secrets/cerebras.key | wgl hive config set-key abc123 cerebras
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
563
+ `);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 D3();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 D3(){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 q3(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}k`:String(t)}function U3(t){let e={agents:[],env:{}},r=t.split(`
564
+ `);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 Z3(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
543
565
  `));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",`
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(`
566
+ Stopped tailing.`)),process.exit(0)}),await new Promise(()=>{})}async function F3(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
545
567
  ${g("bold","wgl hive keys")} \u2014 API key management
546
568
 
547
569
  ${g("cyan","USAGE:")}
548
570
  wgl hive keys create <hive-id> --name N [--permissions all|read|write]
549
571
  wgl hive keys list
550
572
  wgl hive keys revoke <id>
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(`
573
+ `);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(P("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 JO=w(()=>{"use strict";$e();co();_n()});var KO={};G(KO,{runCarapace:()=>V3});import{createRequire as H3}from"node:module";import{dirname as B3,join as G3}from"node:path";async function V3(t){let e=H3(import.meta.url),r=e.resolve("@honeybee-ai/carapace"),n=B3(r),o=G3(n,"cli.js"),s=process.argv;process.argv=["node","carapace",...t];try{e(o)}finally{process.argv=s}}var YO=w(()=>{"use strict"});var XO={};G(XO,{handleSessionStart:()=>J3});import{appendFileSync as W3}from"node:fs";async function J3(t,e,r){let n=process.env.CLAUDE_ENV_FILE;if(n){let i=a=>a.replace(/["\\`$!]/g,"\\$&");W3(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(`
552
574
  `)+`
553
575
  `)}let o=ee(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:
554
576
  ${p.rules.map(f=>` - ${f}`).join(`
@@ -561,11 +583,11 @@ ${s.join(`
561
583
 
562
584
  `)}
563
585
 
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=ee(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=ee(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=ee(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:
586
+ File edits are auto-claimed. Use wgl commands for manual coordination.`};console.log(JSON.stringify(i))}}var QO=w(()=>{"use strict";et()});var eI={};G(eI,{handlePreToolUse:()=>K3});async function K3(t,e){let r=ee(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 tI=w(()=>{"use strict";et()});var rI={};G(rI,{handlePostToolUse:()=>Y3});async function Y3(t,e){let r=ee(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 nI=w(()=>{"use strict";et()});var oI={};G(oI,{handleStop:()=>X3});async function X3(t,e){let r=ee(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:
565
587
  ${i.map(c=>` \u2022 ${c}`).join(`
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=ee(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)+`
588
+ `)}`};console.log(JSON.stringify(a));return}}catch{}r.publishEvent("agent.session_complete",{agentId:t.agentId,role:t.role}).catch(()=>{})}var sI=w(()=>{"use strict";et()});var iI={};G(iI,{handlePromptSubmit:()=>eW});import{writeFileSync as Q3}from"node:fs";async function eW(t,e,r){let n=ee(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{Q3(e,JSON.stringify(t,null,2)+`
567
589
  `)}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(`
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(`
590
+ `)}`)}var aI=w(()=>{"use strict";et()});var lI={};G(lI,{runHook:()=>nW});import{readFileSync as cI,existsSync as tW}from"node:fs";import{join as rW}from"node:path";async function nW(t){let e=t[0],r=t[1]??rW(process.cwd(),".wgl.json");e||process.exit(0),tW(r)||process.exit(0);let n;try{n=JSON.parse(cI(r,"utf8"))}catch{process.exit(0)}let o;try{let s=cI(0,"utf8");o=s?JSON.parse(s):{}}catch{o={}}switch(e){case"session-start":{let{handleSessionStart:s}=await Promise.resolve().then(()=>(QO(),XO));await s(n,r,o);break}case"pre-tool-use":{let{handlePreToolUse:s}=await Promise.resolve().then(()=>(tI(),eI));await s(n,o);break}case"post-tool-use":{let{handlePostToolUse:s}=await Promise.resolve().then(()=>(nI(),rI));await s(n,o);break}case"stop":{let{handleStop:s}=await Promise.resolve().then(()=>(sI(),oI));await s(n,o);break}case"prompt-submit":{let{handlePromptSubmit:s}=await Promise.resolve().then(()=>(aI(),iI));await s(n,r,o);break}default:process.exit(0)}}var uI=w(()=>{"use strict"});var dI={};G(dI,{scan:()=>iW});import{readFileSync as oW}from"node:fs";import{createRequire as sW}from"node:module";async function iW(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
569
591
  ${g("bold","wgl scan")} \u2014 scan text for prompt injection
570
592
 
571
593
  ${g("cyan","USAGE:")}
@@ -585,10 +607,10 @@ ${g("cyan","EXAMPLES:")}
585
607
  wgl scan --file user-input.txt
586
608
  wgl scan --json "hello world" | jq .score
587
609
  wgl scan --strict --file untrusted.txt
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(`
610
+ `);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=oW(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=sW(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)),pI(p,n);return}let f=p.action==="BLOCK"?"red":p.action==="WARN"||p.action==="LOG"?"yellow":"green";if(console.log(P("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(P("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(`
611
+ ${g("green","No findings \u2014 text appears clean")}`);console.log(),pI(p,n)}function pI(t,e){t.action==="BLOCK"&&process.exit(2),e&&t.findings.length>0&&process.exit(1)}var fI=w(()=>{"use strict";$e()});import{mkdirSync as mI,appendFileSync as aW,readdirSync as cW,unlinkSync as lW,writeFileSync as uW}from"node:fs";import{join as hc}from"node:path";function rb(t){let e=t.getTime(),r=e-e%dd;return new Date(r).toISOString()}function dW(){return new Date().toISOString().slice(0,10)}function hI(t){let e=process.env.NECTAR_CAPTURE==="true"||process.env.NECTAR_CAPTURE==="1";return new _i({endpoint:process.env.TELEMETRY_ENDPOINT,apiKey:process.env.TELEMETRY_API_KEY,projectRoot:t??process.cwd(),auditCapture:e,nectarEndpoint:process.env.NECTAR_ENDPOINT,nectarApiKey:process.env.NECTAR_API_KEY})}var pW,_i,gI,yI=w(()=>{bn();$i();pW=new Set(["latency_ms","total_tokens","prompt_tokens","completion_tokens","score"]);_i=class t{endpoint;apiKey;syncInterval;localDir;windows=new Map;syncTimer=null;currentLogFd=null;auditCapture;auditDir=null;nectarEndpoint;nectarApiKey;nectarQueue=[];nectarTimer=null;static MAX_NECTAR_BACKLOG=1e3;static NECTAR_SYNC_INTERVAL=6e4;static NECTAR_BATCH_SIZE=50;localEnabled;cloudEnabled;auditEnabled;nectarEnabled;constructor(e={}){if(this.endpoint=e.endpoint??null,this.apiKey=e.apiKey??null,this.syncInterval=e.syncInterval??pd,e.localDir)this.localDir=e.localDir;else if(e.projectRoot)try{this.localDir=hc(Sn(e.projectRoot),ho)}catch{this.localDir=null}else this.localDir=null;this.auditCapture=e.auditCapture??!1,this.nectarEndpoint=e.nectarEndpoint??null,this.nectarApiKey=e.nectarApiKey??null,this.localEnabled=!!this.localDir,this.cloudEnabled=!!(this.endpoint&&this.apiKey),this.auditEnabled=this.auditCapture&&this.localEnabled,this.nectarEnabled=!!(this.nectarEndpoint&&this.nectarApiKey)}start(){if(!(!this.localEnabled&&!this.cloudEnabled&&!this.nectarEnabled)){if(this.localDir&&(mI(this.localDir,{recursive:!0}),this.rotateFiles()),this.auditEnabled&&this.localDir){this.auditDir=hc(this.localDir,"audit");try{mI(this.auditDir,{recursive:!0})}catch{this.auditDir=null}}this.cloudEnabled&&(this.syncTimer=setInterval(()=>this.syncToCloud(),this.syncInterval),this.syncTimer.unref()),this.nectarEnabled&&(this.nectarTimer=setInterval(()=>this.syncToNectar(),t.NECTAR_SYNC_INTERVAL),this.nectarTimer.unref())}}record(e,r={}){if(!this.localEnabled&&!this.cloudEnabled&&!this.nectarEnabled)return;let n,o={...r};if("_payload"in o){let i=o._payload,a=o.traceId??"unknown",c=Buffer.byteLength(i,"utf8");if(this.auditEnabled&&this.auditDir){let l=`${a}__${e}.json`;try{uW(hc(this.auditDir,l),i),o._payloadRef=l,o._payloadBytes=c}catch{}}n=i,delete o._payload}let s={event_type:e,metadata:o,timestamp:new Date().toISOString()};this.localEnabled&&this.appendLocal(s),this.aggregate(s),this.nectarEnabled&&this.queueNectar(e,o,n)}async stop(){this.syncTimer&&(clearInterval(this.syncTimer),this.syncTimer=null),this.nectarTimer&&(clearInterval(this.nectarTimer),this.nectarTimer=null),this.cloudEnabled&&await this.syncToCloud(),this.nectarEnabled&&await this.syncToNectar()}get nectarQueueLength(){return this.nectarQueue.length}get windowCount(){return this.windows.size}getSnapshot(){if(!this.localEnabled&&!this.cloudEnabled)return null;let e=rb(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=dW(),n=hc(this.localDir,`${r}.jsonl`);try{aW(n,JSON.stringify(e)+`
612
+ `)}catch{}}rotateFiles(){if(this.localDir)try{let e=cW(this.localDir).filter(r=>r.endsWith(".jsonl")).sort().reverse();for(let r=ud;r<e.length;r++)lW(hc(this.localDir,e[r]))}catch{}}aggregate(e){let r=rb(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 pW){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=rb(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{}}queueNectar(e,r,n){if(this.nectarQueue.length>=t.MAX_NECTAR_BACKLOG)return;let o={event_type:e,metadata:{...r}};typeof r.traceId=="string"&&(o.trace_id=r.traceId),typeof r.runId=="string"&&(o.run_id=r.runId),typeof r.agentId=="string"&&(o.agent_id=r.agentId),n&&(o.payload=n),this.nectarQueue.push(o)}async syncToNectar(){if(!this.nectarEnabled||this.nectarQueue.length===0)return;let e=this.nectarQueue.splice(0,t.NECTAR_BATCH_SIZE);try{!(await fetch(this.nectarEndpoint+"/v1/ingest",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.nectarApiKey}`},body:JSON.stringify({events:e})})).ok&&this.nectarQueue.length<t.MAX_NECTAR_BACKLOG&&this.nectarQueue.unshift(...e)}catch{this.nectarQueue.length+e.length<=t.MAX_NECTAR_BACKLOG&&this.nectarQueue.unshift(...e)}}};gI=new _i});import{readFileSync as fW,readdirSync as mW,existsSync as hW}from"node:fs";import{join as vI}from"node:path";function _I(t){return vI(Sn(t),ho)}function nb(t,e){if(!hW(t))return[];let r=new Date;r.setDate(r.getDate()-e);let n=r.toISOString().slice(0,10),o=mW(t).filter(i=>i.endsWith(".jsonl")&&i.slice(0,10)>=n).sort(),s=[];for(let i of o)try{let a=fW(vI(t,i),"utf8");for(let c of a.split(`
613
+ `))if(c.trim())try{s.push(JSON.parse(c))}catch{}}catch{}return s}function bI(t,e=30){let r=nb(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 wI(t,e=30){let r=nb(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 xI(t,e={}){let{limit:r=20,offset:n=0,eventType:o,days:s=30}=e,i=nb(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 SI=w(()=>{bn();$i()});import{readdirSync as $I,readFileSync as gW}from"node:fs";import{join as kI}from"node:path";function EI(t){return kI(Sn(t),ho,"audit")}function TI(t){if(!t.endsWith(".json"))return null;let e=t.slice(0,-5),r=e.indexOf("__");return r===-1?null:{traceId:e.slice(0,r),eventType:e.slice(r+2)}}function PI(t,e){let r=EI(t),n=[];try{let o=$I(r);for(let s of o){let i=TI(s);if(!(!i||i.traceId!==e))try{let a=gW(kI(r,s),"utf8");n.push({traceId:i.traceId,eventType:i.eventType,filename:s,content:a})}catch{}}}catch{}return n}function RI(t,e){let r=EI(t),n=Math.min(Math.max(e?.limit??50,1),100),o=Math.max(e?.offset??0,0),s=new Map;try{let a=$I(r).sort().reverse();for(let c of a){let l=TI(c);if(!l)continue;let u=s.get(l.traceId);u?u.push(l.eventType):s.set(l.traceId,[l.eventType])}}catch{return[]}let i=[];for(let[a,c]of s)i.push({traceId:a,eventTypes:c,fileCount:c.length});return i.slice(o,o+n)}var CI=w(()=>{$i();bn()});var OI={};G(OI,{NO_OP_TELEMETRY:()=>gI,TelemetryReporter:()=>_i,createTelemetryFromEnv:()=>hI,getTelemetryDir:()=>_I,getTracePayloads:()=>PI,listAuditTraces:()=>RI,localEvents:()=>xI,localOverview:()=>bI,localTimeline:()=>wI});var II=w(()=>{yI();SI();CI()});var AI={};G(AI,{telemetry:()=>yW});async function yW(t){let e=t[0];if(e==="--help"||e==="-h"||!e){console.log(`
592
614
  ${g("bold","wgl telemetry")} \u2014 view telemetry data from Carapace
593
615
 
594
616
  ${g("cyan","USAGE:")}
@@ -608,7 +630,7 @@ ${g("cyan","EXAMPLES:")}
608
630
  wgl telemetry overview --days 7
609
631
  wgl telemetry events --local --type scan
610
632
  wgl telemetry timeline --json
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(`
633
+ `);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 vW(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 _W(u,s,r);break;case"events":await bW(u,a,r);break;case"timeline":await wW(u,s,r);break;default:console.log(_(`Unknown subcommand: ${e}`)),console.log("Run `wgl telemetry --help` for usage"),process.exit(2)}}async function vW(t,e){let{localOverview:r,localTimeline:n,localEvents:o,getTelemetryDir:s}=await Promise.resolve().then(()=>(II(),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(P(`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(P(`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(P(`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 _W(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(P(`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 bW(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(P(`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 wW(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(P(`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 NI=w(()=>{"use strict";co();$e();_n()});var zI={};G(zI,{completion:()=>SW});async function SW(t){let e=t[0];if(!e||e==="--help"||e==="-h"){console.log(`
612
634
  ${g("bold","wgl completion")} \u2014 generate shell completion scripts
613
635
 
614
636
  ${g("cyan","USAGE:")}
@@ -620,7 +642,7 @@ ${g("cyan","SETUP:")}
620
642
  eval "$(wgl completion bash)" # add to .bashrc
621
643
  eval "$(wgl completion zsh)" # add to .zshrc
622
644
  wgl completion fish | source # add to config.fish
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(`
645
+ `);return}switch(e){case"bash":console.log($W());break;case"zsh":console.log(kW());break;case"fish":console.log(EW());break;default:console.log(_(`Unknown shell: ${e}. Supported: bash, zsh, fish`)),process.exit(2)}}function $W(){let t=Object.entries(nd).filter(([,e])=>e.length>0).map(([e,r])=>` ${e}) COMPREPLY=( $(compgen -W "${r.join(" ")}" -- "$cur") ) ;;`).join(`
624
646
  `);return`# wgl bash completion \u2014 generated by wgl completion bash
625
647
  _wgl_completions() {
626
648
  local cur prev
@@ -629,7 +651,7 @@ _wgl_completions() {
629
651
  prev="\${COMP_WORDS[COMP_CWORD-1]}"
630
652
 
631
653
  if [ "$COMP_CWORD" -eq 1 ]; then
632
- COMPREPLY=( $(compgen -W "${rW} --help --version" -- "$cur") )
654
+ COMPREPLY=( $(compgen -W "${xW} --help --version" -- "$cur") )
633
655
  return
634
656
  fi
635
657
 
@@ -638,7 +660,7 @@ ${t}
638
660
  keys) COMPREPLY=( $(compgen -W "create list revoke" -- "$cur") ) ;;
639
661
  esac
640
662
  }
641
- complete -F _wgl_completions wgl`}function sW(){return`#compdef wgl
663
+ complete -F _wgl_completions wgl`}function kW(){return`#compdef wgl
642
664
  # wgl zsh completion \u2014 generated by wgl completion zsh
643
665
  _wgl() {
644
666
  local -a commands
@@ -677,22 +699,22 @@ _wgl() {
677
699
  fi
678
700
 
679
701
  case "\${words[2]}" in
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(`
702
+ ${Object.entries(nd).filter(([,e])=>e.length>0).map(([e,r])=>{let n=r.map(o=>`'${o}[${o}]'`).join(" ");return` ${e}) _arguments '1:subcommand:(${r.join(" ")})' ;;`}).join(`
681
703
  `)}
682
704
  esac
683
705
  }
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.14";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(`
706
+ _wgl "$@"`}function EW(){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(nd))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(`
707
+ `)}var nd,xW,jI=w(()=>{"use strict";$e();nd={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:[]},xW=Object.keys(nd).join(" ")});var MI={};G(MI,{upgrade:()=>zW});import{readFileSync as TW}from"node:fs";import{join as PW,dirname as RW}from"node:path";import{request as CW}from"node:https";import{execSync as OW}from"node:child_process";function AW(){return"1.0.15";try{let t=PW(RW(new URL(import.meta.url).pathname),"..","package.json");return JSON.parse(TW(t,"utf8")).version}catch{return"0.0.0-dev"}}function NW(){return new Promise((t,e)=>{let r=CW(IW,{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 zW(t){if(t[0]==="--help"||t[0]==="-h"){console.log(`
686
708
  ${g("bold","wgl upgrade")} \u2014 update waggle-cli to the latest version
687
709
 
688
710
  ${g("cyan","USAGE:")}
689
711
  wgl upgrade Update to latest version
690
712
  wgl upgrade --check Just check, don't install
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(`
713
+ `);return}let e=t.includes("--check"),r=AW();console.log(S("Current",r));let n;try{n=await NW()}catch{console.log(_("Cannot reach npm registry")),process.exit(1);return}if(console.log(S("Latest",n)),r===n){console.log(`
692
714
  ${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(`
693
715
  ${g("green","Already up to date (or ahead)")}`);return}if(e){console.log(`
694
716
  ${g("yellow",`Update available: ${r} \u2192 ${n}`)}`),console.log(g("dim"," Run `wgl upgrade` to install"));return}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(`
717
+ Upgrading ${r} \u2192 ${n}...`);try{OW("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 IW,LI=w(()=>{"use strict";$e();IW="https://registry.npmjs.org/@honeybee-ai/waggle-cli/latest"});$e();var DI=process.argv.slice(2),ds=DI[0],Ce=DI.slice(1);function jW(){console.log(`
696
718
  ${g("bold","wgl")} \u2014 waggle-cli: bridge AI agents to ACP coordination servers
697
719
 
698
720
  ${g("cyan","USAGE:")}
@@ -775,6 +797,13 @@ ${g("cyan","SECRETS:")}
775
797
  secret list Show stored providers and scopes
776
798
  secret delete <provider> Delete a provider key
777
799
 
800
+ ${g("cyan","BILLING:")}
801
+ billing balance Show pollen balance
802
+ billing history [--limit N] Transaction history
803
+ billing rates [--category CAT] Current pricing rates
804
+ billing purchase <amount> Buy pollen credits
805
+ billing estimate [options] Estimate cost for a hive run
806
+
778
807
  ${g("cyan","CLOUD:")}
779
808
  marketplace search Search protocol marketplace
780
809
  marketplace info Show protocol details
@@ -829,7 +858,7 @@ ${g("cyan","EXAMPLES:")}
829
858
  wgl carapace gateway
830
859
  wgl incubator --port=8080 --brood=brood.yaml
831
860
  wgl leave
832
- `)}async function yW(){if(!cs||cs==="--help"||cs==="-h"){gW();return}if(cs==="--version"||cs==="-v"){console.log("1.0.14");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)});
861
+ `)}async function MW(){if(!ds||ds==="--help"||ds==="-h"){jW();return}if(ds==="--version"||ds==="-v"){console.log("1.0.15");return}switch(ds){case"init":{let{init:t}=await Promise.resolve().then(()=>(Tb(),Eb));await t(Ce);break}case"join":{let{join:t}=await Promise.resolve().then(()=>(Rb(),Pb));await t(Ce);break}case"status":{let{status:t}=await Promise.resolve().then(()=>(Ob(),Cb));await t();break}case"leave":{let{leave:t}=await Promise.resolve().then(()=>(Ab(),Ib));await t();break}case"protocol":{let{protocol:t}=await Promise.resolve().then(()=>(Gw(),Bw));await t(Ce);break}case"team":{let{team:t}=await Promise.resolve().then(()=>(Ww(),Vw));await t();break}case"claim":{let{claim:t}=await Promise.resolve().then(()=>(Kw(),Jw));await t(Ce);break}case"release":{let{release:t}=await Promise.resolve().then(()=>(Xw(),Yw));await t(Ce);break}case"halt":{let{halt:t}=await Promise.resolve().then(()=>(ex(),Qw));await t(Ce);break}case"pause":{let{pause:t}=await Promise.resolve().then(()=>(of(),nf));await t(Ce);break}case"resume":{let{resume:t}=await Promise.resolve().then(()=>(of(),nf));await t();break}case"events":{let{events:t}=await Promise.resolve().then(()=>(nx(),rx));await t(Ce);break}case"state":{let{state:t}=await Promise.resolve().then(()=>(sx(),ox));await t(Ce);break}case"msg":{let{msg:t}=await Promise.resolve().then(()=>(ax(),ix));await t(Ce);break}case"help":{let{helpCmd:t}=await Promise.resolve().then(()=>(lx(),cx));await t(Ce);break}case"namespace":{let{namespace:t}=await Promise.resolve().then(()=>(px(),ux));await t(Ce);break}case"hooks":{let{hooksCmd:t}=await Promise.resolve().then(()=>(fx(),dx));await t(Ce);break}case"up":{let{up:t}=await Promise.resolve().then(()=>(Ox(),Cx));await t(Ce);break}case"down":{let{down:t}=await Promise.resolve().then(()=>(zx(),Nx));await t(Ce);break}case"logs":{let{logs:t}=await Promise.resolve().then(()=>(Mx(),jx));await t(Ce);break}case"inspect":{let{inspect:t}=await Promise.resolve().then(()=>(qx(),Dx));await t(Ce);break}case"serve":{let{serve:t}=await Promise.resolve().then(()=>($O(),SO));await t(Ce);break}case"auth":{let{auth:t}=await Promise.resolve().then(()=>(IO(),OO));await t(Ce);break}case"config":{let{configCmd:t}=await Promise.resolve().then(()=>(zO(),NO));await t(Ce);break}case"marketplace":{let{marketplace:t}=await Promise.resolve().then(()=>(MO(),jO));await t(Ce);break}case"integrations":{let{integrations:t}=await Promise.resolve().then(()=>(ZO(),UO));await t(Ce);break}case"secret":{let{secret:t}=await Promise.resolve().then(()=>(HO(),FO));await t(Ce);break}case"billing":{let{billing:t}=await Promise.resolve().then(()=>(GO(),BO));await t(Ce);break}case"hive":{let{hive:t}=await Promise.resolve().then(()=>(JO(),WO));await t(Ce);break}case"carapace":{let{runCarapace:t}=await Promise.resolve().then(()=>(YO(),KO));await t(Ce);break}case"incubator":{let{main:t}=await Promise.resolve().then(()=>(D_(),L_)),e=process.argv;process.argv=["node","incubator",...Ce];try{await t()}finally{process.argv=e}break}case"hook":{let{runHook:t}=await Promise.resolve().then(()=>(uI(),lI));await t(Ce);break}case"scan":{let{scan:t}=await Promise.resolve().then(()=>(fI(),dI));await t(Ce);break}case"telemetry":{let{telemetry:t}=await Promise.resolve().then(()=>(NI(),AI));await t(Ce);break}case"completion":{let{completion:t}=await Promise.resolve().then(()=>(jI(),zI));await t(Ce);break}case"upgrade":{let{upgrade:t}=await Promise.resolve().then(()=>(LI(),MI));await t(Ce);break}default:console.error(g("red",`Unknown command: ${ds}`)),console.log("Run `wgl --help` for usage"),process.exit(2)}}MW().catch(t=>{console.error(g("red",`Error: ${t.message}`)),process.exit(2)});
833
862
  /*! Bundled license information:
834
863
 
835
864
  js-yaml/dist/js-yaml.mjs: