@keepur/hive 0.3.6 → 0.4.0

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.
Files changed (2) hide show
  1. package/package.json +3 -2
  2. package/pkg/server.min.js +285 -245
package/pkg/server.min.js CHANGED
@@ -1,201 +1,240 @@
1
1
  import { createRequire as __hiveCreateRequire } from 'module'; const require = __hiveCreateRequire(import.meta.url);
2
- var sm=Object.create;var Ci=Object.defineProperty;var nm=Object.getOwnPropertyDescriptor;var rm=Object.getOwnPropertyNames;var im=Object.getPrototypeOf,om=Object.prototype.hasOwnProperty;var H=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var j=(n,e)=>()=>(n&&(e=n(n=0)),e);var T=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ue=(n,e)=>{for(var t in e)Ci(n,t,{get:e[t],enumerable:!0})},am=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rm(e))!om.call(n,r)&&r!==t&&Ci(n,r,{get:()=>e[r],enumerable:!(s=nm(e,r))||s.enumerable});return n};var Ae=(n,e,t)=>(t=n!=null?sm(im(n)):{},am(e||!n||!n.__esModule?Ci(t,"default",{value:n,enumerable:!0}):t,n));import{existsSync as cm}from"node:fs";import{resolve as ce}from"node:path";function dm(){return process.env.HIVE_HOME?ce(process.env.HIVE_HOME):cm(ce(process.cwd(),"hive.yaml"))?process.cwd():ce(lm,"hive")}function Cc(n){let e=process.env.HIVE_CONFIG||"hive.yaml";return ce(n,e)}function Ec(n){let t=(process.env.HIVE_CONFIG||"hive.yaml").match(/^hive-(.+)\.yaml$/)?.[1];return ce(n,t?`.env-${t}`:".env")}function fn(n=V){return ce(n,"agents")}function pn(n,e=V){return ce(fn(e),n,"scratch")}function xc(n,e=V){return ce(fn(e),n,"playwright")}function Oc(n,e=V){return ce(fn(e),n,"reports")}function Mc(n,e=V){return ce(fn(e),n,"feeds")}var lm,V,Xe,cs,hn,bv,Nc,ls=j(()=>{"use strict";lm=process.env.HOME??"/tmp";V=dm(),Xe=ce(V,"skills"),cs=ce(V,".hive"),hn=ce(V,".hive-state"),bv=ce(hn,"git"),Nc=ce(import.meta.dirname,"..","seeds")});function mn(n,e,t,s){if(Dc[n]<Dc[um])return;let r={ts:new Date().toISOString(),level:n,component:e,msg:t,...s};(n==="error"?process.stderr:process.stdout).write(JSON.stringify(r)+`
3
- `)}function k(n){return{debug:(e,t)=>mn("debug",n,e,t),info:(e,t)=>mn("info",n,e,t),warn:(e,t)=>mn("warn",n,e,t),error:(e,t)=>mn("error",n,e,t)}}var Dc,um,M=j(()=>{"use strict";Dc={debug:0,info:1,warn:2,error:3},um=process.env.LOG_LEVEL||"info"});import{execFileSync as Ei}from"node:child_process";import{existsSync as Ni,mkdirSync as hm,unlinkSync as fm}from"node:fs";import{join as pm,resolve as Lc}from"node:path";function Pc(n){let e=Lc(n,".hive-state");return{stateDir:e,gitDir:Lc(e,"git")}}function $c(n){let{stateDir:e,gitDir:t}=Pc(n);if(Ni(t))return;hm(e,{recursive:!0});let s=(...r)=>Ei("git",[...r],{cwd:n,env:{...process.env,GIT_DIR:t,GIT_WORK_TREE:n},stdio:"pipe"});s("init"),s("config","user.name","hive-instance"),s("config","user.email","hive@localhost"),s("checkout","-b","installed"),s("commit","--allow-empty","-m","init: installed branch"),s("checkout","-b","state"),s("commit","--allow-empty","-m","init: state branch"),gn.info("Instance-local git initialized",{gitDir:t})}function Rc(n,e,t,s){let{gitDir:r}=Pc(n);if(!Ni(r)){gn.warn("Instance git not initialized \u2014 skipping state commit");return}let i=pm(r,"state-index.tmp"),o={...process.env,GIT_DIR:r,GIT_WORK_TREE:n,GIT_INDEX_FILE:i},a=(...l)=>Ei("git",[...l],{cwd:n,env:o,stdio:"pipe",encoding:"utf-8"}).trim();try{a("read-tree","state");for(let p of e)a("add","--force","--",p);try{a("rm","--cached","--ignore-unmatch","-r","--","**/.DS_Store")}catch{}let l=a("write-tree"),c=a("rev-parse","state"),d=a("rev-parse","state^{tree}");if(l===d)return;let u=s?{GIT_AUTHOR_NAME:s,GIT_AUTHOR_EMAIL:`${s}@hive`,GIT_COMMITTER_NAME:s,GIT_COMMITTER_EMAIL:`${s}@hive`}:{GIT_AUTHOR_NAME:"hive",GIT_AUTHOR_EMAIL:"hive@localhost",GIT_COMMITTER_NAME:"hive",GIT_COMMITTER_EMAIL:"hive@localhost"},h=Ei("git",["commit-tree",l,"-p",c,"-m",t],{env:{...o,...u},encoding:"utf-8"}).trim();a("update-ref","refs/heads/state",h),gn.debug("State branch commit",{message:t,files:e.length})}catch(l){gn.warn("Failed to commit to state branch",{error:String(l),message:t})}finally{try{Ni(i)&&fm(i)}catch{}}}var gn,xi=j(()=>{"use strict";M();gn=k("instance-git")});var zc=T((Fv,je)=>{var Li=H("fs"),yn=H("path"),km=H("os"),bm=H("crypto"),Wc=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function _m(){return Wc[Math.floor(Math.random()*Wc.length)]}function Rt(n){return typeof n=="string"?!["false","0","no","off",""].includes(n.toLowerCase()):!!n}function vm(){return process.stdout.isTTY}function Tm(n){return vm()?`\x1B[2m${n}\x1B[0m`:n}var Im=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Am(n){let e={},t=n.toString();t=t.replace(/\r\n?/mg,`
4
- `);let s;for(;(s=Im.exec(t))!=null;){let r=s[1],i=s[2]||"";i=i.trim();let o=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(i=i.replace(/\\n/g,`
5
- `),i=i.replace(/\\r/g,"\r")),e[r]=i}return e}function Cm(n){n=n||{};let e=Jc(n);n.path=e;let t=te.configDotenv(n);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let s=Yc(n).split(","),r=s.length,i;for(let o=0;o<r;o++)try{let a=s[o].trim(),l=Nm(t,a);i=te.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=r)throw a}return te.parse(i)}function Em(n){console.error(`\u26A0 ${n}`)}function ds(n){console.log(`\u2506 ${n}`)}function Vc(n){console.log(`\u25C7 ${n}`)}function Yc(n){return n&&n.DOTENV_KEY&&n.DOTENV_KEY.length>0?n.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function Nm(n,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let s=t.password;if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let r=t.searchParams.get("environment");if(!r){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let i=`DOTENV_VAULT_${r.toUpperCase()}`,o=n.parsed[i];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:s}}function Jc(n){let e=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path))for(let t of n.path)Li.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else e=yn.resolve(process.cwd(),".env.vault");return Li.existsSync(e)?e:null}function Gc(n){return n[0]==="~"?yn.join(km.homedir(),n.slice(1)):n}function xm(n){let e=Rt(process.env.DOTENV_CONFIG_DEBUG||n&&n.debug),t=Rt(process.env.DOTENV_CONFIG_QUIET||n&&n.quiet);(e||!t)&&Vc("loading env from encrypted .env.vault");let s=te._parseVault(n),r=process.env;return n&&n.processEnv!=null&&(r=n.processEnv),te.populate(r,s,n),{parsed:s}}function Om(n){let e=yn.resolve(process.cwd(),".env"),t="utf8",s=process.env;n&&n.processEnv!=null&&(s=n.processEnv);let r=Rt(s.DOTENV_CONFIG_DEBUG||n&&n.debug),i=Rt(s.DOTENV_CONFIG_QUIET||n&&n.quiet);n&&n.encoding?t=n.encoding:r&&ds("no encoding is specified (UTF-8 is used by default)");let o=[e];if(n&&n.path)if(!Array.isArray(n.path))o=[Gc(n.path)];else{o=[];for(let d of n.path)o.push(Gc(d))}let a,l={};for(let d of o)try{let u=te.parse(Li.readFileSync(d,{encoding:t}));te.populate(l,u,n)}catch(u){r&&ds(`failed to load ${d} ${u.message}`),a=u}let c=te.populate(s,l,n);if(r=Rt(s.DOTENV_CONFIG_DEBUG||r),i=Rt(s.DOTENV_CONFIG_QUIET||i),r||!i){let d=Object.keys(c).length,u=[];for(let h of o)try{let p=yn.relative(process.cwd(),h);u.push(p)}catch(p){r&&ds(`failed to load ${h} ${p.message}`),a=p}Vc(`injected env (${d}) from ${u.join(",")} ${Tm(`// tip: ${_m()}`)}`)}return a?{parsed:l,error:a}:{parsed:l}}function Mm(n){if(Yc(n).length===0)return te.configDotenv(n);let e=Jc(n);return e?te._configVault(n):(Em(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),te.configDotenv(n))}function Dm(n,e){let t=Buffer.from(e.slice(-64),"hex"),s=Buffer.from(n,"base64"),r=s.subarray(0,12),i=s.subarray(-16);s=s.subarray(12,-16);try{let o=bm.createDecipheriv("aes-256-gcm",t,r);return o.setAuthTag(i),`${o.update(s)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",c=o.message==="Unsupported state or unable to authenticate data";if(a||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(c){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw o}}function Lm(n,e,t={}){let s=!!(t&&t.debug),r=!!(t&&t.override),i={};if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(n,o)?(r===!0&&(n[o]=e[o],i[o]=e[o]),s&&ds(r===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(n[o]=e[o],i[o]=e[o]);return i}var te={configDotenv:Om,_configVault:xm,_parseVault:Cm,config:Mm,decrypt:Dm,parse:Am,populate:Lm};je.exports.configDotenv=te.configDotenv;je.exports._configVault=te._configVault;je.exports._parseVault=te._parseVault;je.exports.config=te.config;je.exports.decrypt=te.decrypt;je.exports.parse=te.parse;je.exports.populate=te.populate;je.exports=te});var U=T(oe=>{"use strict";var Pi=Symbol.for("yaml.alias"),Qc=Symbol.for("yaml.document"),wn=Symbol.for("yaml.map"),Xc=Symbol.for("yaml.pair"),$i=Symbol.for("yaml.scalar"),Sn=Symbol.for("yaml.seq"),qe=Symbol.for("yaml.node.type"),Pm=n=>!!n&&typeof n=="object"&&n[qe]===Pi,$m=n=>!!n&&typeof n=="object"&&n[qe]===Qc,Rm=n=>!!n&&typeof n=="object"&&n[qe]===wn,Bm=n=>!!n&&typeof n=="object"&&n[qe]===Xc,Zc=n=>!!n&&typeof n=="object"&&n[qe]===$i,Um=n=>!!n&&typeof n=="object"&&n[qe]===Sn;function el(n){if(n&&typeof n=="object")switch(n[qe]){case wn:case Sn:return!0}return!1}function jm(n){if(n&&typeof n=="object")switch(n[qe]){case Pi:case wn:case $i:case Sn:return!0}return!1}var qm=n=>(Zc(n)||el(n))&&!!n.anchor;oe.ALIAS=Pi;oe.DOC=Qc;oe.MAP=wn;oe.NODE_TYPE=qe;oe.PAIR=Xc;oe.SCALAR=$i;oe.SEQ=Sn;oe.hasAnchor=qm;oe.isAlias=Pm;oe.isCollection=el;oe.isDocument=$m;oe.isMap=Rm;oe.isNode=jm;oe.isPair=Bm;oe.isScalar=Zc;oe.isSeq=Um});var us=T(Ri=>{"use strict";var se=U(),he=Symbol("break visit"),tl=Symbol("skip children"),Le=Symbol("remove node");function kn(n,e){let t=sl(e);se.isDocument(n)?Bt(null,n.contents,t,Object.freeze([n]))===Le&&(n.contents=null):Bt(null,n,t,Object.freeze([]))}kn.BREAK=he;kn.SKIP=tl;kn.REMOVE=Le;function Bt(n,e,t,s){let r=nl(n,e,t,s);if(se.isNode(r)||se.isPair(r))return rl(n,s,r),Bt(n,r,t,s);if(typeof r!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=Bt(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===he)return he;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=Bt("key",e.key,t,s);if(i===he)return he;i===Le&&(e.key=null);let o=Bt("value",e.value,t,s);if(o===he)return he;o===Le&&(e.value=null)}}return r}async function bn(n,e){let t=sl(e);se.isDocument(n)?await Ut(null,n.contents,t,Object.freeze([n]))===Le&&(n.contents=null):await Ut(null,n,t,Object.freeze([]))}bn.BREAK=he;bn.SKIP=tl;bn.REMOVE=Le;async function Ut(n,e,t,s){let r=await nl(n,e,t,s);if(se.isNode(r)||se.isPair(r))return rl(n,s,r),Ut(n,r,t,s);if(typeof r!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await Ut(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===he)return he;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=await Ut("key",e.key,t,s);if(i===he)return he;i===Le&&(e.key=null);let o=await Ut("value",e.value,t,s);if(o===he)return he;o===Le&&(e.value=null)}}return r}function sl(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function nl(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(se.isMap(e))return t.Map?.(n,e,s);if(se.isSeq(e))return t.Seq?.(n,e,s);if(se.isPair(e))return t.Pair?.(n,e,s);if(se.isScalar(e))return t.Scalar?.(n,e,s);if(se.isAlias(e))return t.Alias?.(n,e,s)}function rl(n,e,t){let s=e[e.length-1];if(se.isCollection(s))s.items[n]=t;else if(se.isPair(s))n==="key"?s.key=t:s.value=t;else if(se.isDocument(s))s.contents=t;else{let r=se.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Ri.visit=kn;Ri.visitAsync=bn});var Bi=T(ol=>{"use strict";var il=U(),Fm=us(),Km={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hm=n=>n.replace(/[!,[\]{}]/g,e=>Km[e]),hs=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),r=s.shift();switch(r){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;let[i,o]=s;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=s;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,s,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Hm(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags),r;if(e&&s.length>0&&il.isNode(e.contents)){let i={};Fm.visit(e.contents,(o,a)=>{il.isNode(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
6
- `)}};hs.defaultYaml={explicit:!1,version:"1.2"};hs.defaultTags={"!!":"tag:yaml.org,2002:"};ol.Directives=hs});var _n=T(fs=>{"use strict";var al=U(),Wm=us();function Gm(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function cl(n){let e=new Set;return Wm.visit(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}function ll(n,e){for(let t=1;;++t){let s=`${n}${t}`;if(!e.has(s))return s}}function Vm(n,e){let t=[],s=new Map,r=null;return{onAnchor:i=>{t.push(i),r??(r=cl(n));let o=ll(e,r);return r.add(o),o},setAnchors:()=>{for(let i of t){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(al.isScalar(o.node)||al.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:s}}fs.anchorIsValid=Gm;fs.anchorNames=cl;fs.createNodeAnchors=Vm;fs.findNewAnchor=ll});var Ui=T(dl=>{"use strict";function ps(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let r=0,i=s.length;r<i;++r){let o=s[r],a=ps(n,s,String(r),o);a===void 0?delete s[r]:a!==o&&(s[r]=a)}else if(s instanceof Map)for(let r of Array.from(s.keys())){let i=s.get(r),o=ps(n,s,r,i);o===void 0?s.delete(r):o!==i&&s.set(r,o)}else if(s instanceof Set)for(let r of Array.from(s)){let i=ps(n,s,r,r);i===void 0?s.delete(r):i!==r&&(s.delete(r),s.add(i))}else for(let[r,i]of Object.entries(s)){let o=ps(n,s,r,i);o===void 0?delete s[r]:o!==i&&(s[r]=o)}return n.call(e,t,s)}dl.applyReviver=ps});var Ze=T(hl=>{"use strict";var Ym=U();function ul(n,e,t){if(Array.isArray(n))return n.map((s,r)=>ul(s,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!Ym.hasAnchor(n))return n.toJSON(e,t);let s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=i=>{s.res=i,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}hl.toJS=ul});var vn=T(pl=>{"use strict";var Jm=Ui(),fl=U(),zm=Ze(),ji=class{constructor(e){Object.defineProperty(this,fl.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:s,onAnchor:r,reviver:i}={}){if(!fl.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=zm.toJS(this,"",o);if(typeof r=="function")for(let{count:l,res:c}of o.anchors.values())r(c,l);return typeof i=="function"?Jm.applyReviver(i,{"":a},"",a):a}};pl.NodeBase=ji});var ms=T(ml=>{"use strict";var Qm=_n(),Xm=us(),jt=U(),Zm=vn(),eg=Ze(),qi=class extends Zm.NodeBase{constructor(e){super(jt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],Xm.visit(e,{Node:(i,o)=>{(jt.isAlias(o)||jt.hasAnchor(o))&&s.push(o)}}),t&&(t.aliasResolveCache=s));let r;for(let i of s){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:s,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=s.get(o);if(a||(eg.toJS(o,null,t),a=s.get(o)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Tn(r,o,s)),a.count*a.aliasCount>i)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,s){let r=`*${this.source}`;if(e){if(Qm.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}};function Tn(n,e,t){if(jt.isAlias(e)){let s=e.resolve(n),r=t&&s&&t.get(s);return r?r.count*r.aliasCount:0}else if(jt.isCollection(e)){let s=0;for(let r of e.items){let i=Tn(n,r,t);i>s&&(s=i)}return s}else if(jt.isPair(e)){let s=Tn(n,e.key,t),r=Tn(n,e.value,t);return Math.max(s,r)}return 1}ml.Alias=qi});var Z=T(Fi=>{"use strict";var tg=U(),sg=vn(),ng=Ze(),rg=n=>!n||typeof n!="function"&&typeof n!="object",et=class extends sg.NodeBase{constructor(e){super(tg.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:ng.toJS(this.value,e,t)}toString(){return String(this.value)}};et.BLOCK_FOLDED="BLOCK_FOLDED";et.BLOCK_LITERAL="BLOCK_LITERAL";et.PLAIN="PLAIN";et.QUOTE_DOUBLE="QUOTE_DOUBLE";et.QUOTE_SINGLE="QUOTE_SINGLE";Fi.Scalar=et;Fi.isScalarValue=rg});var gs=T(yl=>{"use strict";var ig=ms(),gt=U(),gl=Z(),og="tag:yaml.org,2002:";function ag(n,e,t){if(e){let s=t.filter(i=>i.tag===e),r=s.find(i=>!i.format)??s[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(s=>s.identify?.(n)&&!s.format)}function cg(n,e,t){if(gt.isDocument(n)&&(n=n.contents),gt.isNode(n))return n;if(gt.isPair(n)){let u=t.schema[gt.MAP].createNode?.(t.schema,null,t);return u.items.push(n),u}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:s,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t,l;if(s&&n&&typeof n=="object"){if(l=a.get(n),l)return l.anchor??(l.anchor=r(n)),new ig.Alias(l.anchor);l={anchor:null,node:null},a.set(n,l)}e?.startsWith("!!")&&(e=og+e.slice(2));let c=ag(n,e,o.tags);if(!c){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let u=new gl.Scalar(n);return l&&(l.node=u),u}c=n instanceof Map?o[gt.MAP]:Symbol.iterator in Object(n)?o[gt.SEQ]:o[gt.MAP]}i&&(i(c),delete t.onTagObj);let d=c?.createNode?c.createNode(t.schema,n,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,n,t):new gl.Scalar(n);return e?d.tag=e:c.default||(d.tag=c.tag),l&&(l.node=d),d}yl.createNode=cg});var An=T(In=>{"use strict";var lg=gs(),Pe=U(),dg=vn();function Ki(n,e,t){let s=t;for(let r=e.length-1;r>=0;--r){let i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return lg.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var wl=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Hi=class extends dg.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(s=>Pe.isNode(s)||Pe.isPair(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(wl(e))this.add(t);else{let[s,...r]=e,i=this.get(s,!0);if(Pe.isCollection(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(s,Ki(this.schema,r,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}deleteIn(e){let[t,...s]=e;if(s.length===0)return this.delete(t);let r=this.get(t,!0);if(Pe.isCollection(r))return r.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){let[s,...r]=e,i=this.get(s,!0);return r.length===0?!t&&Pe.isScalar(i)?i.value:i:Pe.isCollection(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Pe.isPair(t))return!1;let s=t.value;return s==null||e&&Pe.isScalar(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){let[t,...s]=e;if(s.length===0)return this.has(t);let r=this.get(t,!0);return Pe.isCollection(r)?r.hasIn(s):!1}setIn(e,t){let[s,...r]=e;if(r.length===0)this.set(s,t);else{let i=this.get(s,!0);if(Pe.isCollection(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(s,Ki(this.schema,r,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}};In.Collection=Hi;In.collectionFromPath=Ki;In.isEmptyPath=wl});var ys=T(Cn=>{"use strict";var ug=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function Wi(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var hg=(n,e,t)=>n.endsWith(`
7
- `)?Wi(t,e):t.includes(`
2
+ var wT=Object.create;var jl=Object.defineProperty;var bT=Object.getOwnPropertyDescriptor;var kT=Object.getOwnPropertyNames;var ST=Object.getPrototypeOf,$T=Object.prototype.hasOwnProperty;var ne=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var S=(n,e)=>()=>(n&&(e=n(n=0)),e);var N=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),we=(n,e)=>{for(var t in e)jl(n,t,{get:e[t],enumerable:!0})},xT=(n,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of kT(e))!$T.call(n,r)&&r!==t&&jl(n,r,{get:()=>e[r],enumerable:!(i=bT(e,r))||i.enumerable});return n};var nt=(n,e,t)=>(t=n!=null?wT(ST(n)):{},xT(e||!n||!n.__esModule?jl(t,"default",{value:n,enumerable:!0}):t,n));import{existsSync as IT}from"node:fs";import{resolve as Oe}from"node:path";function ET(){return process.env.HIVE_HOME?Oe(process.env.HIVE_HOME):IT(Oe(process.cwd(),"hive.yaml"))?process.cwd():Oe(TT,"hive")}function Hy(n){let e=process.env.HIVE_CONFIG||"hive.yaml";return Oe(n,e)}function Yy(n){let t=(process.env.HIVE_CONFIG||"hive.yaml").match(/^hive-(.+)\.yaml$/)?.[1];return Oe(n,t?`.env-${t}`:".env")}function No(n=se){return Oe(n,"agents")}function Do(n,e=se){return Oe(No(e),n,"scratch")}function Qy(n,e=se){return Oe(No(e),n,"playwright")}function ev(n,e=se){return Oe(No(e),n,"reports")}function tv(n,e=se){return Oe(No(e),n,"feeds")}var TT,se,Lt,Vr,Co,Tj,Xy,Wr=S(()=>{"use strict";TT=process.env.HOME??"/tmp";se=ET(),Lt=Oe(se,"skills"),Vr=Oe(se,".hive"),Co=Oe(se,".hive-state"),Tj=Oe(Co,"git"),Xy=Oe(import.meta.dirname,"..","seeds")});function Po(n,e,t,i){if(nv[n]<nv[AT])return;let r={ts:new Date().toISOString(),level:n,component:e,msg:t,...i};(n==="error"?process.stderr:process.stdout).write(JSON.stringify(r)+`
3
+ `)}function $(n){return{debug:(e,t)=>Po("debug",n,e,t),info:(e,t)=>Po("info",n,e,t),warn:(e,t)=>Po("warn",n,e,t),error:(e,t)=>Po("error",n,e,t)}}var nv,AT,R=S(()=>{"use strict";nv={debug:0,info:1,warn:2,error:3},AT=process.env.LOG_LEVEL||"info"});import{execFileSync as Ul}from"node:child_process";import{existsSync as Rl,mkdirSync as OT,unlinkSync as CT}from"node:fs";import{join as NT,resolve as rv}from"node:path";function iv(n){let e=rv(n,".hive-state");return{stateDir:e,gitDir:rv(e,"git")}}function ov(n){let{stateDir:e,gitDir:t}=iv(n);if(Rl(t))return;OT(e,{recursive:!0});let i=(...r)=>Ul("git",[...r],{cwd:n,env:{...process.env,GIT_DIR:t,GIT_WORK_TREE:n},stdio:"pipe"});i("init"),i("config","user.name","hive-instance"),i("config","user.email","hive@localhost"),i("checkout","-b","installed"),i("commit","--allow-empty","-m","init: installed branch"),i("checkout","-b","state"),i("commit","--allow-empty","-m","init: state branch"),Mo.info("Instance-local git initialized",{gitDir:t})}function sv(n,e,t,i){let{gitDir:r}=iv(n);if(!Rl(r)){Mo.warn("Instance git not initialized \u2014 skipping state commit");return}let o=NT(r,"state-index.tmp"),s={...process.env,GIT_DIR:r,GIT_WORK_TREE:n,GIT_INDEX_FILE:o},a=(...l)=>Ul("git",[...l],{cwd:n,env:s,stdio:"pipe",encoding:"utf-8"}).trim();try{a("read-tree","state");for(let p of e)a("add","--force","--",p);try{a("rm","--cached","--ignore-unmatch","-r","--","**/.DS_Store")}catch{}let l=a("write-tree"),c=a("rev-parse","state"),u=a("rev-parse","state^{tree}");if(l===u)return;let d=i?{GIT_AUTHOR_NAME:i,GIT_AUTHOR_EMAIL:`${i}@hive`,GIT_COMMITTER_NAME:i,GIT_COMMITTER_EMAIL:`${i}@hive`}:{GIT_AUTHOR_NAME:"hive",GIT_AUTHOR_EMAIL:"hive@localhost",GIT_COMMITTER_NAME:"hive",GIT_COMMITTER_EMAIL:"hive@localhost"},f=Ul("git",["commit-tree",l,"-p",c,"-m",t],{env:{...s,...d},encoding:"utf-8"}).trim();a("update-ref","refs/heads/state",f),Mo.debug("State branch commit",{message:t,files:e.length})}catch(l){Mo.warn("Failed to commit to state branch",{error:String(l),message:t})}finally{try{Rl(o)&&CT(o)}catch{}}}var Mo,Bl=S(()=>{"use strict";R();Mo=$("instance-git")});var _v=N((Gj,bt)=>{var Kl=ne("fs"),Lo=ne("path"),jT=ne("os"),UT=ne("crypto"),mv=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function RT(){return mv[Math.floor(Math.random()*mv.length)]}function Zn(n){return typeof n=="string"?!["false","0","no","off",""].includes(n.toLowerCase()):!!n}function BT(){return process.stdout.isTTY}function FT(n){return BT()?`\x1B[2m${n}\x1B[0m`:n}var qT=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function ZT(n){let e={},t=n.toString();t=t.replace(/\r\n?/mg,`
4
+ `);let i;for(;(i=qT.exec(t))!=null;){let r=i[1],o=i[2]||"";o=o.trim();let s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),s==='"'&&(o=o.replace(/\\n/g,`
5
+ `),o=o.replace(/\\r/g,"\r")),e[r]=o}return e}function KT(n){n=n||{};let e=vv(n);n.path=e;let t=ye.configDotenv(n);if(!t.parsed){let s=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw s.code="MISSING_DATA",s}let i=yv(n).split(","),r=i.length,o;for(let s=0;s<r;s++)try{let a=i[s].trim(),l=WT(t,a);o=ye.decrypt(l.ciphertext,l.key);break}catch(a){if(s+1>=r)throw a}return ye.parse(o)}function VT(n){console.error(`\u26A0 ${n}`)}function Gr(n){console.log(`\u2506 ${n}`)}function gv(n){console.log(`\u25C7 ${n}`)}function yv(n){return n&&n.DOTENV_KEY&&n.DOTENV_KEY.length>0?n.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function WT(n,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let i=t.password;if(!i){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let r=t.searchParams.get("environment");if(!r){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let o=`DOTENV_VAULT_${r.toUpperCase()}`,s=n.parsed[o];if(!s){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${o} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:s,key:i}}function vv(n){let e=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path))for(let t of n.path)Kl.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else e=Lo.resolve(process.cwd(),".env.vault");return Kl.existsSync(e)?e:null}function hv(n){return n[0]==="~"?Lo.join(jT.homedir(),n.slice(1)):n}function GT(n){let e=Zn(process.env.DOTENV_CONFIG_DEBUG||n&&n.debug),t=Zn(process.env.DOTENV_CONFIG_QUIET||n&&n.quiet);(e||!t)&&gv("loading env from encrypted .env.vault");let i=ye._parseVault(n),r=process.env;return n&&n.processEnv!=null&&(r=n.processEnv),ye.populate(r,i,n),{parsed:i}}function JT(n){let e=Lo.resolve(process.cwd(),".env"),t="utf8",i=process.env;n&&n.processEnv!=null&&(i=n.processEnv);let r=Zn(i.DOTENV_CONFIG_DEBUG||n&&n.debug),o=Zn(i.DOTENV_CONFIG_QUIET||n&&n.quiet);n&&n.encoding?t=n.encoding:r&&Gr("no encoding is specified (UTF-8 is used by default)");let s=[e];if(n&&n.path)if(!Array.isArray(n.path))s=[hv(n.path)];else{s=[];for(let u of n.path)s.push(hv(u))}let a,l={};for(let u of s)try{let d=ye.parse(Kl.readFileSync(u,{encoding:t}));ye.populate(l,d,n)}catch(d){r&&Gr(`failed to load ${u} ${d.message}`),a=d}let c=ye.populate(i,l,n);if(r=Zn(i.DOTENV_CONFIG_DEBUG||r),o=Zn(i.DOTENV_CONFIG_QUIET||o),r||!o){let u=Object.keys(c).length,d=[];for(let f of s)try{let p=Lo.relative(process.cwd(),f);d.push(p)}catch(p){r&&Gr(`failed to load ${f} ${p.message}`),a=p}gv(`injected env (${u}) from ${d.join(",")} ${FT(`// tip: ${RT()}`)}`)}return a?{parsed:l,error:a}:{parsed:l}}function HT(n){if(yv(n).length===0)return ye.configDotenv(n);let e=vv(n);return e?ye._configVault(n):(VT(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),ye.configDotenv(n))}function YT(n,e){let t=Buffer.from(e.slice(-64),"hex"),i=Buffer.from(n,"base64"),r=i.subarray(0,12),o=i.subarray(-16);i=i.subarray(12,-16);try{let s=UT.createDecipheriv("aes-256-gcm",t,r);return s.setAuthTag(o),`${s.update(i)}${s.final()}`}catch(s){let a=s instanceof RangeError,l=s.message==="Invalid key length",c=s.message==="Unsupported state or unable to authenticate data";if(a||l){let u=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw u.code="INVALID_DOTENV_KEY",u}else if(c){let u=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw u.code="DECRYPTION_FAILED",u}else throw s}}function XT(n,e,t={}){let i=!!(t&&t.debug),r=!!(t&&t.override),o={};if(typeof e!="object"){let s=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw s.code="OBJECT_REQUIRED",s}for(let s of Object.keys(e))Object.prototype.hasOwnProperty.call(n,s)?(r===!0&&(n[s]=e[s],o[s]=e[s]),i&&Gr(r===!0?`"${s}" is already defined and WAS overwritten`:`"${s}" is already defined and was NOT overwritten`)):(n[s]=e[s],o[s]=e[s]);return o}var ye={configDotenv:JT,_configVault:GT,_parseVault:KT,config:HT,decrypt:YT,parse:ZT,populate:XT};bt.exports.configDotenv=ye.configDotenv;bt.exports._configVault=ye._configVault;bt.exports._parseVault=ye._parseVault;bt.exports.config=ye.config;bt.exports.decrypt=ye.decrypt;bt.exports.parse=ye.parse;bt.exports.populate=ye.populate;bt.exports=ye});var Y=N($e=>{"use strict";var Vl=Symbol.for("yaml.alias"),wv=Symbol.for("yaml.document"),zo=Symbol.for("yaml.map"),bv=Symbol.for("yaml.pair"),Wl=Symbol.for("yaml.scalar"),jo=Symbol.for("yaml.seq"),kt=Symbol.for("yaml.node.type"),QT=n=>!!n&&typeof n=="object"&&n[kt]===Vl,eE=n=>!!n&&typeof n=="object"&&n[kt]===wv,tE=n=>!!n&&typeof n=="object"&&n[kt]===zo,nE=n=>!!n&&typeof n=="object"&&n[kt]===bv,kv=n=>!!n&&typeof n=="object"&&n[kt]===Wl,rE=n=>!!n&&typeof n=="object"&&n[kt]===jo;function Sv(n){if(n&&typeof n=="object")switch(n[kt]){case zo:case jo:return!0}return!1}function iE(n){if(n&&typeof n=="object")switch(n[kt]){case Vl:case zo:case Wl:case jo:return!0}return!1}var oE=n=>(kv(n)||Sv(n))&&!!n.anchor;$e.ALIAS=Vl;$e.DOC=wv;$e.MAP=zo;$e.NODE_TYPE=kt;$e.PAIR=bv;$e.SCALAR=Wl;$e.SEQ=jo;$e.hasAnchor=oE;$e.isAlias=QT;$e.isCollection=Sv;$e.isDocument=eE;$e.isMap=tE;$e.isNode=iE;$e.isPair=nE;$e.isScalar=kv;$e.isSeq=rE});var Jr=N(Gl=>{"use strict";var ve=Y(),Le=Symbol("break visit"),$v=Symbol("skip children"),ft=Symbol("remove node");function Uo(n,e){let t=xv(e);ve.isDocument(n)?Kn(null,n.contents,t,Object.freeze([n]))===ft&&(n.contents=null):Kn(null,n,t,Object.freeze([]))}Uo.BREAK=Le;Uo.SKIP=$v;Uo.REMOVE=ft;function Kn(n,e,t,i){let r=Iv(n,e,t,i);if(ve.isNode(r)||ve.isPair(r))return Tv(n,i,r),Kn(n,r,t,i);if(typeof r!="symbol"){if(ve.isCollection(e)){i=Object.freeze(i.concat(e));for(let o=0;o<e.items.length;++o){let s=Kn(o,e.items[o],t,i);if(typeof s=="number")o=s-1;else{if(s===Le)return Le;s===ft&&(e.items.splice(o,1),o-=1)}}}else if(ve.isPair(e)){i=Object.freeze(i.concat(e));let o=Kn("key",e.key,t,i);if(o===Le)return Le;o===ft&&(e.key=null);let s=Kn("value",e.value,t,i);if(s===Le)return Le;s===ft&&(e.value=null)}}return r}async function Ro(n,e){let t=xv(e);ve.isDocument(n)?await Vn(null,n.contents,t,Object.freeze([n]))===ft&&(n.contents=null):await Vn(null,n,t,Object.freeze([]))}Ro.BREAK=Le;Ro.SKIP=$v;Ro.REMOVE=ft;async function Vn(n,e,t,i){let r=await Iv(n,e,t,i);if(ve.isNode(r)||ve.isPair(r))return Tv(n,i,r),Vn(n,r,t,i);if(typeof r!="symbol"){if(ve.isCollection(e)){i=Object.freeze(i.concat(e));for(let o=0;o<e.items.length;++o){let s=await Vn(o,e.items[o],t,i);if(typeof s=="number")o=s-1;else{if(s===Le)return Le;s===ft&&(e.items.splice(o,1),o-=1)}}}else if(ve.isPair(e)){i=Object.freeze(i.concat(e));let o=await Vn("key",e.key,t,i);if(o===Le)return Le;o===ft&&(e.key=null);let s=await Vn("value",e.value,t,i);if(s===Le)return Le;s===ft&&(e.value=null)}}return r}function xv(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function Iv(n,e,t,i){if(typeof t=="function")return t(n,e,i);if(ve.isMap(e))return t.Map?.(n,e,i);if(ve.isSeq(e))return t.Seq?.(n,e,i);if(ve.isPair(e))return t.Pair?.(n,e,i);if(ve.isScalar(e))return t.Scalar?.(n,e,i);if(ve.isAlias(e))return t.Alias?.(n,e,i)}function Tv(n,e,t){let i=e[e.length-1];if(ve.isCollection(i))i.items[n]=t;else if(ve.isPair(i))n==="key"?i.key=t:i.value=t;else if(ve.isDocument(i))i.contents=t;else{let r=ve.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Gl.visit=Uo;Gl.visitAsync=Ro});var Jl=N(Av=>{"use strict";var Ev=Y(),sE=Jr(),aE={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},cE=n=>n.replace(/[!,[\]{}]/g,e=>aE[e]),Hr=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[o,s]=i;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=i;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,s),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),s)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let o=this.tags[i];if(o)try{return o+decodeURIComponent(r)}catch(s){return t(String(s)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+cE(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&Ev.isNode(e.contents)){let o={};sE.visit(e.contents,(s,a)=>{Ev.isNode(a)&&a.tag&&(o[a.tag]=!0)}),r=Object.keys(o)}else r=[];for(let[o,s]of i)o==="!!"&&s==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(s)))&&t.push(`%TAG ${o} ${s}`);return t.join(`
6
+ `)}};Hr.defaultYaml={explicit:!1,version:"1.2"};Hr.defaultTags={"!!":"tag:yaml.org,2002:"};Av.Directives=Hr});var Bo=N(Yr=>{"use strict";var Ov=Y(),lE=Jr();function uE(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function Cv(n){let e=new Set;return lE.visit(n,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function Nv(n,e){for(let t=1;;++t){let i=`${n}${t}`;if(!e.has(i))return i}}function dE(n,e){let t=[],i=new Map,r=null;return{onAnchor:o=>{t.push(o),r??(r=Cv(n));let s=Nv(e,r);return r.add(s),s},setAnchors:()=>{for(let o of t){let s=i.get(o);if(typeof s=="object"&&s.anchor&&(Ov.isScalar(s.node)||Ov.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:i}}Yr.anchorIsValid=uE;Yr.anchorNames=Cv;Yr.createNodeAnchors=dE;Yr.findNewAnchor=Nv});var Hl=N(Dv=>{"use strict";function Xr(n,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,o=i.length;r<o;++r){let s=i[r],a=Xr(n,i,String(r),s);a===void 0?delete i[r]:a!==s&&(i[r]=a)}else if(i instanceof Map)for(let r of Array.from(i.keys())){let o=i.get(r),s=Xr(n,i,r,o);s===void 0?i.delete(r):s!==o&&i.set(r,s)}else if(i instanceof Set)for(let r of Array.from(i)){let o=Xr(n,i,r,r);o===void 0?i.delete(r):o!==r&&(i.delete(r),i.add(o))}else for(let[r,o]of Object.entries(i)){let s=Xr(n,i,r,o);s===void 0?delete i[r]:s!==o&&(i[r]=s)}return n.call(e,t,i)}Dv.applyReviver=Xr});var zt=N(Mv=>{"use strict";var fE=Y();function Pv(n,e,t){if(Array.isArray(n))return n.map((i,r)=>Pv(i,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!fE.hasAnchor(n))return n.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(n,i),t.onCreate=o=>{i.res=o,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}Mv.toJS=Pv});var Fo=N(zv=>{"use strict";var pE=Hl(),Lv=Y(),mE=zt(),Yl=class{constructor(e){Object.defineProperty(this,Lv.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:r,reviver:o}={}){if(!Lv.isDocument(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=mE.toJS(this,"",s);if(typeof r=="function")for(let{count:l,res:c}of s.anchors.values())r(c,l);return typeof o=="function"?pE.applyReviver(o,{"":a},"",a):a}};zv.NodeBase=Yl});var Qr=N(jv=>{"use strict";var hE=Bo(),gE=Jr(),Wn=Y(),yE=Fo(),vE=zt(),Xl=class extends yE.NodeBase{constructor(e){super(Wn.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],gE.visit(e,{Node:(o,s)=>{(Wn.isAlias(s)||Wn.hasAnchor(s))&&i.push(s)}}),t&&(t.aliasResolveCache=i));let r;for(let o of i){if(o===this)break;o.anchor===this.source&&(r=o)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:i,doc:r,maxAliasCount:o}=t,s=this.resolve(r,t);if(!s){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=i.get(s);if(a||(vE.toJS(s,null,t),a=i.get(s)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(o>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=qo(r,s,i)),a.count*a.aliasCount>o)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,i){let r=`*${this.source}`;if(e){if(hE.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${r} `}return r}};function qo(n,e,t){if(Wn.isAlias(e)){let i=e.resolve(n),r=t&&i&&t.get(i);return r?r.count*r.aliasCount:0}else if(Wn.isCollection(e)){let i=0;for(let r of e.items){let o=qo(n,r,t);o>i&&(i=o)}return i}else if(Wn.isPair(e)){let i=qo(n,e.key,t),r=qo(n,e.value,t);return Math.max(i,r)}return 1}jv.Alias=Xl});var he=N(Ql=>{"use strict";var _E=Y(),wE=Fo(),bE=zt(),kE=n=>!n||typeof n!="function"&&typeof n!="object",jt=class extends wE.NodeBase{constructor(e){super(_E.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:bE.toJS(this.value,e,t)}toString(){return String(this.value)}};jt.BLOCK_FOLDED="BLOCK_FOLDED";jt.BLOCK_LITERAL="BLOCK_LITERAL";jt.PLAIN="PLAIN";jt.QUOTE_DOUBLE="QUOTE_DOUBLE";jt.QUOTE_SINGLE="QUOTE_SINGLE";Ql.Scalar=jt;Ql.isScalarValue=kE});var ei=N(Rv=>{"use strict";var SE=Qr(),fn=Y(),Uv=he(),$E="tag:yaml.org,2002:";function xE(n,e,t){if(e){let i=t.filter(o=>o.tag===e),r=i.find(o=>!o.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(i=>i.identify?.(n)&&!i.format)}function IE(n,e,t){if(fn.isDocument(n)&&(n=n.contents),fn.isNode(n))return n;if(fn.isPair(n)){let d=t.schema[fn.MAP].createNode?.(t.schema,null,t);return d.items.push(n),d}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:o,schema:s,sourceObjects:a}=t,l;if(i&&n&&typeof n=="object"){if(l=a.get(n),l)return l.anchor??(l.anchor=r(n)),new SE.Alias(l.anchor);l={anchor:null,node:null},a.set(n,l)}e?.startsWith("!!")&&(e=$E+e.slice(2));let c=xE(n,e,s.tags);if(!c){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let d=new Uv.Scalar(n);return l&&(l.node=d),d}c=n instanceof Map?s[fn.MAP]:Symbol.iterator in Object(n)?s[fn.SEQ]:s[fn.MAP]}o&&(o(c),delete t.onTagObj);let u=c?.createNode?c.createNode(t.schema,n,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,n,t):new Uv.Scalar(n);return e?u.tag=e:c.default||(u.tag=c.tag),l&&(l.node=u),u}Rv.createNode=IE});var Ko=N(Zo=>{"use strict";var TE=ei(),pt=Y(),EE=Fo();function eu(n,e,t){let i=t;for(let r=e.length-1;r>=0;--r){let o=e[r];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let s=[];s[o]=i,i=s}else i=new Map([[o,i]])}return TE.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var Bv=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,tu=class extends EE.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(i=>pt.isNode(i)||pt.isPair(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Bv(e))this.add(t);else{let[i,...r]=e,o=this.get(i,!0);if(pt.isCollection(o))o.addIn(r,t);else if(o===void 0&&this.schema)this.set(i,eu(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let r=this.get(t,!0);if(pt.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...r]=e,o=this.get(i,!0);return r.length===0?!t&&pt.isScalar(o)?o.value:o:pt.isCollection(o)?o.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!pt.isPair(t))return!1;let i=t.value;return i==null||e&&pt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let r=this.get(t,!0);return pt.isCollection(r)?r.hasIn(i):!1}setIn(e,t){let[i,...r]=e;if(r.length===0)this.set(i,t);else{let o=this.get(i,!0);if(pt.isCollection(o))o.setIn(r,t);else if(o===void 0&&this.schema)this.set(i,eu(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Zo.Collection=tu;Zo.collectionFromPath=eu;Zo.isEmptyPath=Bv});var ti=N(Vo=>{"use strict";var AE=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function nu(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var OE=(n,e,t)=>n.endsWith(`
7
+ `)?nu(t,e):t.includes(`
8
8
  `)?`
9
- `+Wi(t,e):(n.endsWith(" ")?"":" ")+t;Cn.indentComment=Wi;Cn.lineComment=hg;Cn.stringifyComment=ug});var kl=T(ws=>{"use strict";var fg="flow",Gi="block",En="quoted";function pg(n,e,t="flow",{indentAtStart:s,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return n;r<i&&(i=0);let l=Math.max(1+i,1+r-e.length);if(n.length<=l)return n;let c=[],d={},u=r-e.length;typeof s=="number"&&(s>r-Math.max(2,i)?c.push(0):u=r-s);let h,p,m=!1,f=-1,y=-1,w=-1;t===Gi&&(f=Sl(n,f,e.length),f!==-1&&(u=f+l));for(let _;_=n[f+=1];){if(t===En&&_==="\\"){switch(y=f,n[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}w=f}if(_===`
10
- `)t===Gi&&(f=Sl(n,f,e.length)),u=f+e.length+l,h=void 0;else{if(_===" "&&p&&p!==" "&&p!==`
11
- `&&p!==" "){let v=n[f+1];v&&v!==" "&&v!==`
12
- `&&v!==" "&&(h=f)}if(f>=u)if(h)c.push(h),u=h+l,h=void 0;else if(t===En){for(;p===" "||p===" ";)p=_,_=n[f+=1],m=!0;let v=f>w+1?f-2:y-1;if(d[v])return n;c.push(v),d[v]=!0,u=v+l,h=void 0}else m=!0}p=_}if(m&&a&&a(),c.length===0)return n;o&&o();let S=n.slice(0,c[0]);for(let _=0;_<c.length;++_){let v=c[_],I=c[_+1]||n.length;v===0?S=`
13
- ${e}${n.slice(0,I)}`:(t===En&&d[v]&&(S+=`${n[v]}\\`),S+=`
14
- ${e}${n.slice(v+1,I)}`)}return S}function Sl(n,e,t){let s=e,r=e+1,i=n[r];for(;i===" "||i===" ";)if(e<r+t)i=n[++e];else{do i=n[++e];while(i&&i!==`
15
- `);s=e,r=e+1,i=n[r]}return s}ws.FOLD_BLOCK=Gi;ws.FOLD_FLOW=fg;ws.FOLD_QUOTED=En;ws.foldFlowLines=pg});var ks=T(bl=>{"use strict";var Ce=Z(),tt=kl(),xn=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),On=n=>/^(%|---|\.\.\.)/m.test(n);function mg(n,e,t){if(!e||e<0)return!1;let s=e-t,r=n.length;if(r<=s)return!1;for(let i=0,o=0;i<r;++i)if(n[i]===`
16
- `){if(i-o>s)return!0;if(o=i+1,r-o<=s)return!1}return!0}function Ss(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:s}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(On(n)?" ":""),o="",a=0;for(let l=0,c=t[l];c;c=t[++l])if(c===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);let d=t.substr(l+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(s||t[l+2]==='"'||t.length<r)l+=1;else{for(o+=t.slice(a,l)+`
17
-
18
- `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
19
- `,l+=2;o+=i,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,s?o:tt.foldFlowLines(o,i,tt.FOLD_QUOTED,xn(e,!1))}function Vi(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
20
- `)||/[ \t]\n|\n[ \t]/.test(n))return Ss(n,e);let t=e.indent||(On(n)?" ":""),s="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
21
- ${t}`)+"'";return e.implicitKey?s:tt.foldFlowLines(s,t,tt.FOLD_FLOW,xn(e,!1))}function qt(n,e){let{singleQuote:t}=e.options,s;if(t===!1)s=Ss;else{let r=n.includes('"'),i=n.includes("'");r&&!i?s=Vi:i&&!r?s=Ss:s=t?Vi:Ss}return s(n,e)}var Yi;try{Yi=new RegExp(`(^|(?<!
9
+ `+nu(t,e):(n.endsWith(" ")?"":" ")+t;Vo.indentComment=nu;Vo.lineComment=OE;Vo.stringifyComment=AE});var qv=N(ni=>{"use strict";var CE="flow",ru="block",Wo="quoted";function NE(n,e,t="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:o=20,onFold:s,onOverflow:a}={}){if(!r||r<0)return n;r<o&&(o=0);let l=Math.max(1+o,1+r-e.length);if(n.length<=l)return n;let c=[],u={},d=r-e.length;typeof i=="number"&&(i>r-Math.max(2,o)?c.push(0):d=r-i);let f,p,h=!1,m=-1,y=-1,_=-1;t===ru&&(m=Fv(n,m,e.length),m!==-1&&(d=m+l));for(let k;k=n[m+=1];){if(t===Wo&&k==="\\"){switch(y=m,n[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}_=m}if(k===`
10
+ `)t===ru&&(m=Fv(n,m,e.length)),d=m+e.length+l,f=void 0;else{if(k===" "&&p&&p!==" "&&p!==`
11
+ `&&p!==" "){let O=n[m+1];O&&O!==" "&&O!==`
12
+ `&&O!==" "&&(f=m)}if(m>=d)if(f)c.push(f),d=f+l,f=void 0;else if(t===Wo){for(;p===" "||p===" ";)p=k,k=n[m+=1],h=!0;let O=m>_+1?m-2:y-1;if(u[O])return n;c.push(O),u[O]=!0,d=O+l,f=void 0}else h=!0}p=k}if(h&&a&&a(),c.length===0)return n;s&&s();let b=n.slice(0,c[0]);for(let k=0;k<c.length;++k){let O=c[k],A=c[k+1]||n.length;O===0?b=`
13
+ ${e}${n.slice(0,A)}`:(t===Wo&&u[O]&&(b+=`${n[O]}\\`),b+=`
14
+ ${e}${n.slice(O+1,A)}`)}return b}function Fv(n,e,t){let i=e,r=e+1,o=n[r];for(;o===" "||o===" ";)if(e<r+t)o=n[++e];else{do o=n[++e];while(o&&o!==`
15
+ `);i=e,r=e+1,o=n[r]}return i}ni.FOLD_BLOCK=ru;ni.FOLD_FLOW=CE;ni.FOLD_QUOTED=Wo;ni.foldFlowLines=NE});var ii=N(Zv=>{"use strict";var rt=he(),Ut=qv(),Jo=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),Ho=n=>/^(%|---|\.\.\.)/m.test(n);function DE(n,e,t){if(!e||e<0)return!1;let i=e-t,r=n.length;if(r<=i)return!1;for(let o=0,s=0;o<r;++o)if(n[o]===`
16
+ `){if(o-s>i)return!0;if(s=o+1,r-s<=i)return!1}return!0}function ri(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,o=e.indent||(Ho(n)?" ":""),s="",a=0;for(let l=0,c=t[l];c;c=t[++l])if(c===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(s+=t.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(t[l+1]){case"u":{s+=t.slice(a,l);let u=t.substr(l+2,4);switch(u){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:u.substr(0,2)==="00"?s+="\\x"+u.substr(2):s+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(i||t[l+2]==='"'||t.length<r)l+=1;else{for(s+=t.slice(a,l)+`
17
+
18
+ `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)s+=`
19
+ `,l+=2;s+=o,t[l+2]===" "&&(s+="\\"),l+=1,a=l+1}break;default:l+=1}return s=a?s+t.slice(a):t,i?s:Ut.foldFlowLines(s,o,Ut.FOLD_QUOTED,Jo(e,!1))}function iu(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
20
+ `)||/[ \t]\n|\n[ \t]/.test(n))return ri(n,e);let t=e.indent||(Ho(n)?" ":""),i="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
21
+ ${t}`)+"'";return e.implicitKey?i:Ut.foldFlowLines(i,t,Ut.FOLD_FLOW,Jo(e,!1))}function Gn(n,e){let{singleQuote:t}=e.options,i;if(t===!1)i=ri;else{let r=n.includes('"'),o=n.includes("'");r&&!o?i=iu:o&&!r?i=ri:i=t?iu:ri}return i(n,e)}var ou;try{ou=new RegExp(`(^|(?<!
22
22
  ))
23
23
  +(?!
24
- |$)`,"g")}catch{Yi=/\n+(?!\n|$)/g}function Nn({comment:n,type:e,value:t},s,r,i){let{blockQuote:o,commentString:a,lineWidth:l}=s.options;if(!o||/\n[\t ]+$/.test(t))return qt(t,s);let c=s.indent||(s.forceBlockIndent||On(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===Ce.Scalar.BLOCK_FOLDED?!1:e===Ce.Scalar.BLOCK_LITERAL?!0:!mg(t,l,c.length);if(!t)return d?`|
24
+ |$)`,"g")}catch{ou=/\n+(?!\n|$)/g}function Go({comment:n,type:e,value:t},i,r,o){let{blockQuote:s,commentString:a,lineWidth:l}=i.options;if(!s||/\n[\t ]+$/.test(t))return Gn(t,i);let c=i.indent||(i.forceBlockIndent||Ho(t)?" ":""),u=s==="literal"?!0:s==="folded"||e===rt.Scalar.BLOCK_FOLDED?!1:e===rt.Scalar.BLOCK_LITERAL?!0:!DE(t,l,c.length);if(!t)return u?`|
25
25
  `:`>
26
- `;let u,h;for(h=t.length;h>0;--h){let I=t[h-1];if(I!==`
27
- `&&I!==" "&&I!==" ")break}let p=t.substring(h),m=p.indexOf(`
28
- `);m===-1?u="-":t===p||m!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
29
- `&&(p=p.slice(0,-1)),p=p.replace(Yi,`$&${c}`));let f=!1,y,w=-1;for(y=0;y<t.length;++y){let I=t[y];if(I===" ")f=!0;else if(I===`
30
- `)w=y;else break}let S=t.substring(0,w<y?w+1:y);S&&(t=t.substring(S.length),S=S.replace(/\n+/g,`$&${c}`));let v=(f?c?"2":"1":"")+u;if(n&&(v+=" "+a(n.replace(/ ?[\r\n]+/g," ")),r&&r()),!d){let I=t.replace(/\n+/g,`
31
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),N=!1,D=xn(s,!0);o!=="folded"&&e!==Ce.Scalar.BLOCK_FOLDED&&(D.onOverflow=()=>{N=!0});let A=tt.foldFlowLines(`${S}${I}${p}`,c,tt.FOLD_BLOCK,D);if(!N)return`>${v}
32
- ${c}${A}`}return t=t.replace(/\n+/g,`$&${c}`),`|${v}
33
- ${c}${S}${t}${p}`}function gg(n,e,t,s){let{type:r,value:i}=n,{actualString:o,implicitKey:a,indent:l,indentStep:c,inFlow:d}=e;if(a&&i.includes(`
34
- `)||d&&/[[\]{},]/.test(i))return qt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
35
- `)?qt(i,e):Nn(n,e,t,s);if(!a&&!d&&r!==Ce.Scalar.PLAIN&&i.includes(`
36
- `))return Nn(n,e,t,s);if(On(i)){if(l==="")return e.forceBlockIndent=!0,Nn(n,e,t,s);if(a&&l===c)return qt(i,e)}let u=i.replace(/\n+/g,`$&
37
- ${l}`);if(o){let h=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(h)||p?.some(h))return qt(i,e)}return a?u:tt.foldFlowLines(u,l,tt.FOLD_FLOW,xn(e,!1))}function yg(n,e,t,s){let{implicitKey:r,inFlow:i}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==Ce.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ce.Scalar.QUOTE_DOUBLE);let l=d=>{switch(d){case Ce.Scalar.BLOCK_FOLDED:case Ce.Scalar.BLOCK_LITERAL:return r||i?qt(o.value,e):Nn(o,e,t,s);case Ce.Scalar.QUOTE_DOUBLE:return Ss(o.value,e);case Ce.Scalar.QUOTE_SINGLE:return Vi(o.value,e);case Ce.Scalar.PLAIN:return gg(o,e,t,s);default:return null}},c=l(a);if(c===null){let{defaultKeyType:d,defaultStringType:u}=e.options,h=r&&d||u;if(c=l(h),c===null)throw new Error(`Unsupported default string type ${h}`)}return c}bl.stringifyString=yg});var bs=T(Ji=>{"use strict";var wg=_n(),st=U(),Sg=ys(),kg=ks();function bg(n,e){let t=Object.assign({blockQuote:!0,commentString:Sg.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),s;switch(t.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}function _g(n,e){if(e.tag){let r=n.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,s;if(st.isScalar(e)){s=e.value;let r=n.filter(i=>i.identify?.(s));if(r.length>1){let i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else s=e,t=n.find(r=>r.nodeClass&&s instanceof r.nodeClass);if(!t){let r=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${r} value`)}return t}function vg(n,e,{anchors:t,doc:s}){if(!s.directives)return"";let r=[],i=(st.isScalar(n)||st.isCollection(n))&&n.anchor;i&&wg.anchorIsValid(i)&&(t.add(i),r.push(`&${i}`));let o=n.tag??(e.default?null:e.tag);return o&&r.push(s.directives.tagString(o)),r.join(" ")}function Tg(n,e,t,s){if(st.isPair(n))return n.toString(e,t,s);if(st.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,i=st.isNode(n)?n:e.doc.createNode(n,{onTagObj:l=>r=l});r??(r=_g(e.doc.schema.tags,i));let o=vg(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(i,e,t,s):st.isScalar(i)?kg.stringifyString(i,e,t,s):i.toString(e,t,s);return o?st.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
38
- ${e.indent}${a}`:a}Ji.createStringifyContext=bg;Ji.stringify=Tg});var Il=T(Tl=>{"use strict";var Fe=U(),_l=Z(),vl=bs(),_s=ys();function Ig({key:n,value:e},t,s,r){let{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:c,indentSeq:d,simpleKeys:u}}=t,h=Fe.isNode(n)&&n.comment||null;if(u){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Fe.isCollection(n)||!Fe.isNode(n)&&typeof n=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let p=!u&&(!n||h&&e==null&&!t.inFlow||Fe.isCollection(n)||(Fe.isScalar(n)?n.type===_l.Scalar.BLOCK_FOLDED||n.type===_l.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+l});let m=!1,f=!1,y=vl.stringify(n,t,()=>m=!0,()=>f=!0);if(!p&&!t.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return m&&s&&s(),y===""?"?":p?`? ${y}`:y}else if(i&&!u||e==null&&p)return y=`? ${y}`,h&&!m?y+=_s.lineComment(y,t.indent,c(h)):f&&r&&r(),y;m&&(h=null),p?(h&&(y+=_s.lineComment(y,t.indent,c(h))),y=`? ${y}
39
- ${a}:`):(y=`${y}:`,h&&(y+=_s.lineComment(y,t.indent,c(h))));let w,S,_;Fe.isNode(e)?(w=!!e.spaceBefore,S=e.commentBefore,_=e.comment):(w=!1,S=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!h&&Fe.isScalar(e)&&(t.indentAtStart=y.length+1),f=!1,!d&&l.length>=2&&!t.inFlow&&!p&&Fe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let v=!1,I=vl.stringify(e,t,()=>v=!0,()=>f=!0),N=" ";if(h||w||S){if(N=w?`
40
- `:"",S){let D=c(S);N+=`
41
- ${_s.indentComment(D,t.indent)}`}I===""&&!t.inFlow?N===`
42
- `&&_&&(N=`
43
-
44
- `):N+=`
45
- ${t.indent}`}else if(!p&&Fe.isCollection(e)){let D=I[0],A=I.indexOf(`
46
- `),E=A!==-1,G=t.inFlow??e.flow??e.items.length===0;if(E||!G){let W=!1;if(E&&(D==="&"||D==="!")){let $=I.indexOf(" ");D==="&"&&$!==-1&&$<A&&I[$+1]==="!"&&($=I.indexOf(" ",$+1)),($===-1||A<$)&&(W=!0)}W||(N=`
47
- ${t.indent}`)}}else(I===""||I[0]===`
48
- `)&&(N="");return y+=N+I,t.inFlow?v&&s&&s():_&&!v?y+=_s.lineComment(y,t.indent,c(_)):f&&r&&r(),y}Tl.stringifyPair=Ig});var Qi=T(zi=>{"use strict";var Al=H("process");function Ag(n,...e){n==="debug"&&console.log(...e)}function Cg(n,e){(n==="debug"||n==="warn")&&(typeof Al.emitWarning=="function"?Al.emitWarning(e):console.warn(e))}zi.debug=Ag;zi.warn=Cg});var Pn=T(Ln=>{"use strict";var vs=U(),Cl=Z(),Mn="<<",Dn={identify:n=>n===Mn||typeof n=="symbol"&&n.description===Mn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Cl.Scalar(Symbol(Mn)),{addToJSMap:El}),stringify:()=>Mn},Eg=(n,e)=>(Dn.identify(e)||vs.isScalar(e)&&(!e.type||e.type===Cl.Scalar.PLAIN)&&Dn.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Dn.tag&&t.default);function El(n,e,t){if(t=n&&vs.isAlias(t)?t.resolve(n.doc):t,vs.isSeq(t))for(let s of t.items)Xi(n,e,s);else if(Array.isArray(t))for(let s of t)Xi(n,e,s);else Xi(n,e,t)}function Xi(n,e,t){let s=n&&vs.isAlias(t)?t.resolve(n.doc):t;if(!vs.isMap(s))throw new Error("Merge sources must be maps or map aliases");let r=s.toJSON(null,n,Map);for(let[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}Ln.addMergeToJSMap=El;Ln.isMergeKey=Eg;Ln.merge=Dn});var eo=T(Ol=>{"use strict";var Ng=Qi(),Nl=Pn(),xg=bs(),xl=U(),Zi=Ze();function Og(n,e,{key:t,value:s}){if(xl.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,s);else if(Nl.isMergeKey(n,t))Nl.addMergeToJSMap(n,e,s);else{let r=Zi.toJS(t,"",n);if(e instanceof Map)e.set(r,Zi.toJS(s,r,n));else if(e instanceof Set)e.add(r);else{let i=Mg(t,r,n),o=Zi.toJS(s,i,n);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Mg(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(xl.isNode(n)&&t?.doc){let s=xg.createStringifyContext(t.doc,{});s.anchors=new Set;for(let i of t.anchors.keys())s.anchors.add(i.anchor);s.inFlow=!0,s.inStringifyKey=!0;let r=n.toString(s);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Ng.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}Ol.addPairToJSMap=Og});var nt=T(to=>{"use strict";var Ml=gs(),Dg=Il(),Lg=eo(),$n=U();function Pg(n,e,t){let s=Ml.createNode(n,void 0,t),r=Ml.createNode(e,void 0,t);return new Rn(s,r)}var Rn=class n{constructor(e,t=null){Object.defineProperty(this,$n.NODE_TYPE,{value:$n.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return $n.isNode(t)&&(t=t.clone(e)),$n.isNode(s)&&(s=s.clone(e)),new n(t,s)}toJSON(e,t){let s=t?.mapAsMap?new Map:{};return Lg.addPairToJSMap(t,s,this)}toString(e,t,s){return e?.doc?Dg.stringifyPair(this,e,t,s):JSON.stringify(this)}};to.Pair=Rn;to.createPair=Pg});var so=T(Ll=>{"use strict";var yt=U(),Dl=bs(),Bn=ys();function $g(n,e,t){return(e.inFlow??n.flow?Bg:Rg)(n,e,t)}function Rg({comment:n,items:e},t,{blockItemPrefix:s,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:l,options:{commentString:c}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,h=[];for(let m=0;m<e.length;++m){let f=e[m],y=null;if(yt.isNode(f))!u&&f.spaceBefore&&h.push(""),Un(t,h,f.commentBefore,u),f.comment&&(y=f.comment);else if(yt.isPair(f)){let S=yt.isNode(f.key)?f.key:null;S&&(!u&&S.spaceBefore&&h.push(""),Un(t,h,S.commentBefore,u))}u=!1;let w=Dl.stringify(f,d,()=>y=null,()=>u=!0);y&&(w+=Bn.lineComment(w,i,c(y))),u&&y&&(u=!1),h.push(s+w)}let p;if(h.length===0)p=r.start+r.end;else{p=h[0];for(let m=1;m<h.length;++m){let f=h[m];p+=f?`
49
- ${l}${f}`:`
26
+ `;let d,f;for(f=t.length;f>0;--f){let A=t[f-1];if(A!==`
27
+ `&&A!==" "&&A!==" ")break}let p=t.substring(f),h=p.indexOf(`
28
+ `);h===-1?d="-":t===p||h!==p.length-1?(d="+",o&&o()):d="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
29
+ `&&(p=p.slice(0,-1)),p=p.replace(ou,`$&${c}`));let m=!1,y,_=-1;for(y=0;y<t.length;++y){let A=t[y];if(A===" ")m=!0;else if(A===`
30
+ `)_=y;else break}let b=t.substring(0,_<y?_+1:y);b&&(t=t.substring(b.length),b=b.replace(/\n+/g,`$&${c}`));let O=(m?c?"2":"1":"")+d;if(n&&(O+=" "+a(n.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let A=t.replace(/\n+/g,`
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),j=!1,L=Jo(i,!0);s!=="folded"&&e!==rt.Scalar.BLOCK_FOLDED&&(L.onOverflow=()=>{j=!0});let P=Ut.foldFlowLines(`${b}${A}${p}`,c,Ut.FOLD_BLOCK,L);if(!j)return`>${O}
32
+ ${c}${P}`}return t=t.replace(/\n+/g,`$&${c}`),`|${O}
33
+ ${c}${b}${t}${p}`}function PE(n,e,t,i){let{type:r,value:o}=n,{actualString:s,implicitKey:a,indent:l,indentStep:c,inFlow:u}=e;if(a&&o.includes(`
34
+ `)||u&&/[[\]{},]/.test(o))return Gn(o,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
35
+ `)?Gn(o,e):Go(n,e,t,i);if(!a&&!u&&r!==rt.Scalar.PLAIN&&o.includes(`
36
+ `))return Go(n,e,t,i);if(Ho(o)){if(l==="")return e.forceBlockIndent=!0,Go(n,e,t,i);if(a&&l===c)return Gn(o,e)}let d=o.replace(/\n+/g,`$&
37
+ ${l}`);if(s){let f=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(d),{compat:p,tags:h}=e.doc.schema;if(h.some(f)||p?.some(f))return Gn(o,e)}return a?d:Ut.foldFlowLines(d,l,Ut.FOLD_FLOW,Jo(e,!1))}function ME(n,e,t,i){let{implicitKey:r,inFlow:o}=e,s=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==rt.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(a=rt.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case rt.Scalar.BLOCK_FOLDED:case rt.Scalar.BLOCK_LITERAL:return r||o?Gn(s.value,e):Go(s,e,t,i);case rt.Scalar.QUOTE_DOUBLE:return ri(s.value,e);case rt.Scalar.QUOTE_SINGLE:return iu(s.value,e);case rt.Scalar.PLAIN:return PE(s,e,t,i);default:return null}},c=l(a);if(c===null){let{defaultKeyType:u,defaultStringType:d}=e.options,f=r&&u||d;if(c=l(f),c===null)throw new Error(`Unsupported default string type ${f}`)}return c}Zv.stringifyString=ME});var oi=N(su=>{"use strict";var LE=Bo(),Rt=Y(),zE=ti(),jE=ii();function UE(n,e){let t=Object.assign({blockQuote:!0,commentString:zE.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),i;switch(t.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:i,options:t}}function RE(n,e){if(e.tag){let r=n.filter(o=>o.tag===e.tag);if(r.length>0)return r.find(o=>o.format===e.format)??r[0]}let t,i;if(Rt.isScalar(e)){i=e.value;let r=n.filter(o=>o.identify?.(i));if(r.length>1){let o=r.filter(s=>s.test);o.length>0&&(r=o)}t=r.find(o=>o.format===e.format)??r.find(o=>!o.format)}else i=e,t=n.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!t){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return t}function BE(n,e,{anchors:t,doc:i}){if(!i.directives)return"";let r=[],o=(Rt.isScalar(n)||Rt.isCollection(n))&&n.anchor;o&&LE.anchorIsValid(o)&&(t.add(o),r.push(`&${o}`));let s=n.tag??(e.default?null:e.tag);return s&&r.push(i.directives.tagString(s)),r.join(" ")}function FE(n,e,t,i){if(Rt.isPair(n))return n.toString(e,t,i);if(Rt.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,o=Rt.isNode(n)?n:e.doc.createNode(n,{onTagObj:l=>r=l});r??(r=RE(e.doc.schema.tags,o));let s=BE(o,r,e);s.length>0&&(e.indentAtStart=(e.indentAtStart??0)+s.length+1);let a=typeof r.stringify=="function"?r.stringify(o,e,t,i):Rt.isScalar(o)?jE.stringifyString(o,e,t,i):o.toString(e,t,i);return s?Rt.isScalar(o)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
38
+ ${e.indent}${a}`:a}su.createStringifyContext=UE;su.stringify=FE});var Gv=N(Wv=>{"use strict";var St=Y(),Kv=he(),Vv=oi(),si=ti();function qE({key:n,value:e},t,i,r){let{allNullValues:o,doc:s,indent:a,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:d}}=t,f=St.isNode(n)&&n.comment||null;if(d){if(f)throw new Error("With simple keys, key nodes cannot have comments");if(St.isCollection(n)||!St.isNode(n)&&typeof n=="object"){let L="With simple keys, collection cannot be used as a key value";throw new Error(L)}}let p=!d&&(!n||f&&e==null&&!t.inFlow||St.isCollection(n)||(St.isScalar(n)?n.type===Kv.Scalar.BLOCK_FOLDED||n.type===Kv.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(d||!o),indent:a+l});let h=!1,m=!1,y=Vv.stringify(n,t,()=>h=!0,()=>m=!0);if(!p&&!t.inFlow&&y.length>1024){if(d)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(o||e==null)return h&&i&&i(),y===""?"?":p?`? ${y}`:y}else if(o&&!d||e==null&&p)return y=`? ${y}`,f&&!h?y+=si.lineComment(y,t.indent,c(f)):m&&r&&r(),y;h&&(f=null),p?(f&&(y+=si.lineComment(y,t.indent,c(f))),y=`? ${y}
39
+ ${a}:`):(y=`${y}:`,f&&(y+=si.lineComment(y,t.indent,c(f))));let _,b,k;St.isNode(e)?(_=!!e.spaceBefore,b=e.commentBefore,k=e.comment):(_=!1,b=null,k=null,e&&typeof e=="object"&&(e=s.createNode(e))),t.implicitKey=!1,!p&&!f&&St.isScalar(e)&&(t.indentAtStart=y.length+1),m=!1,!u&&l.length>=2&&!t.inFlow&&!p&&St.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let O=!1,A=Vv.stringify(e,t,()=>O=!0,()=>m=!0),j=" ";if(f||_||b){if(j=_?`
40
+ `:"",b){let L=c(b);j+=`
41
+ ${si.indentComment(L,t.indent)}`}A===""&&!t.inFlow?j===`
42
+ `&&k&&(j=`
43
+
44
+ `):j+=`
45
+ ${t.indent}`}else if(!p&&St.isCollection(e)){let L=A[0],P=A.indexOf(`
46
+ `),z=P!==-1,ae=t.inFlow??e.flow??e.items.length===0;if(z||!ae){let ue=!1;if(z&&(L==="&"||L==="!")){let W=A.indexOf(" ");L==="&"&&W!==-1&&W<P&&A[W+1]==="!"&&(W=A.indexOf(" ",W+1)),(W===-1||P<W)&&(ue=!0)}ue||(j=`
47
+ ${t.indent}`)}}else(A===""||A[0]===`
48
+ `)&&(j="");return y+=j+A,t.inFlow?O&&i&&i():k&&!O?y+=si.lineComment(y,t.indent,c(k)):m&&r&&r(),y}Wv.stringifyPair=qE});var cu=N(au=>{"use strict";var Jv=ne("process");function ZE(n,...e){n==="debug"&&console.log(...e)}function KE(n,e){(n==="debug"||n==="warn")&&(typeof Jv.emitWarning=="function"?Jv.emitWarning(e):console.warn(e))}au.debug=ZE;au.warn=KE});var es=N(Qo=>{"use strict";var ai=Y(),Hv=he(),Yo="<<",Xo={identify:n=>n===Yo||typeof n=="symbol"&&n.description===Yo,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Hv.Scalar(Symbol(Yo)),{addToJSMap:Yv}),stringify:()=>Yo},VE=(n,e)=>(Xo.identify(e)||ai.isScalar(e)&&(!e.type||e.type===Hv.Scalar.PLAIN)&&Xo.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Xo.tag&&t.default);function Yv(n,e,t){if(t=n&&ai.isAlias(t)?t.resolve(n.doc):t,ai.isSeq(t))for(let i of t.items)lu(n,e,i);else if(Array.isArray(t))for(let i of t)lu(n,e,i);else lu(n,e,t)}function lu(n,e,t){let i=n&&ai.isAlias(t)?t.resolve(n.doc):t;if(!ai.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,n,Map);for(let[o,s]of r)e instanceof Map?e.has(o)||e.set(o,s):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}Qo.addMergeToJSMap=Yv;Qo.isMergeKey=VE;Qo.merge=Xo});var du=N(e_=>{"use strict";var WE=cu(),Xv=es(),GE=oi(),Qv=Y(),uu=zt();function JE(n,e,{key:t,value:i}){if(Qv.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,i);else if(Xv.isMergeKey(n,t))Xv.addMergeToJSMap(n,e,i);else{let r=uu.toJS(t,"",n);if(e instanceof Map)e.set(r,uu.toJS(i,r,n));else if(e instanceof Set)e.add(r);else{let o=HE(t,r,n),s=uu.toJS(i,o,n);o in e?Object.defineProperty(e,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):e[o]=s}}return e}function HE(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Qv.isNode(n)&&t?.doc){let i=GE.createStringifyContext(t.doc,{});i.anchors=new Set;for(let o of t.anchors.keys())i.anchors.add(o.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=n.toString(i);if(!t.mapKeyWarned){let o=JSON.stringify(r);o.length>40&&(o=o.substring(0,36)+'..."'),WE.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}e_.addPairToJSMap=JE});var Bt=N(fu=>{"use strict";var t_=ei(),YE=Gv(),XE=du(),ts=Y();function QE(n,e,t){let i=t_.createNode(n,void 0,t),r=t_.createNode(e,void 0,t);return new ns(i,r)}var ns=class n{constructor(e,t=null){Object.defineProperty(this,ts.NODE_TYPE,{value:ts.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:i}=this;return ts.isNode(t)&&(t=t.clone(e)),ts.isNode(i)&&(i=i.clone(e)),new n(t,i)}toJSON(e,t){let i=t?.mapAsMap?new Map:{};return XE.addPairToJSMap(t,i,this)}toString(e,t,i){return e?.doc?YE.stringifyPair(this,e,t,i):JSON.stringify(this)}};fu.Pair=ns;fu.createPair=QE});var pu=N(r_=>{"use strict";var pn=Y(),n_=oi(),rs=ti();function eA(n,e,t){return(e.inFlow??n.flow?nA:tA)(n,e,t)}function tA({comment:n,items:e},t,{blockItemPrefix:i,flowChars:r,itemIndent:o,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:c}}=t,u=Object.assign({},t,{indent:o,type:null}),d=!1,f=[];for(let h=0;h<e.length;++h){let m=e[h],y=null;if(pn.isNode(m))!d&&m.spaceBefore&&f.push(""),is(t,f,m.commentBefore,d),m.comment&&(y=m.comment);else if(pn.isPair(m)){let b=pn.isNode(m.key)?m.key:null;b&&(!d&&b.spaceBefore&&f.push(""),is(t,f,b.commentBefore,d))}d=!1;let _=n_.stringify(m,u,()=>y=null,()=>d=!0);y&&(_+=rs.lineComment(_,o,c(y))),d&&y&&(d=!1),f.push(i+_)}let p;if(f.length===0)p=r.start+r.end;else{p=f[0];for(let h=1;h<f.length;++h){let m=f[h];p+=m?`
49
+ ${l}${m}`:`
50
50
  `}}return n?(p+=`
51
- `+Bn.indentComment(c(n),l),a&&a()):u&&o&&o(),p}function Bg({items:n},e,{flowChars:t,itemIndent:s}){let{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;s+=i;let l=Object.assign({},e,{indent:s,inFlow:!0,type:null}),c=!1,d=0,u=[];for(let m=0;m<n.length;++m){let f=n[m],y=null;if(yt.isNode(f))f.spaceBefore&&u.push(""),Un(e,u,f.commentBefore,!1),f.comment&&(y=f.comment);else if(yt.isPair(f)){let S=yt.isNode(f.key)?f.key:null;S&&(S.spaceBefore&&u.push(""),Un(e,u,S.commentBefore,!1),S.comment&&(c=!0));let _=yt.isNode(f.value)?f.value:null;_?(_.comment&&(y=_.comment),_.commentBefore&&(c=!0)):f.value==null&&S?.comment&&(y=S.comment)}y&&(c=!0);let w=Dl.stringify(f,l,()=>y=null);c||(c=u.length>d||w.includes(`
52
- `)),m<n.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=u.reduce((S,_)=>S+_.length+2,2)+(w.length+2)>e.options.lineWidth)),c&&(w+=",")),y&&(w+=Bn.lineComment(w,s,a(y))),u.push(w),d=u.length}let{start:h,end:p}=t;if(u.length===0)return h+p;if(!c){let m=u.reduce((f,y)=>f+y.length+2,2);c=e.options.lineWidth>0&&m>e.options.lineWidth}if(c){let m=h;for(let f of u)m+=f?`
53
- ${i}${r}${f}`:`
54
- `;return`${m}
55
- ${r}${p}`}else return`${h}${o}${u.join(" ")}${o}${p}`}function Un({indent:n,options:{commentString:e}},t,s,r){if(s&&r&&(s=s.replace(/^\n+/,"")),s){let i=Bn.indentComment(e(s),n);t.push(i.trimStart())}}Ll.stringifyCollection=$g});var it=T(ro=>{"use strict";var Ug=so(),jg=eo(),qg=An(),rt=U(),jn=nt(),Fg=Z();function Ts(n,e){let t=rt.isScalar(e)?e.value:e;for(let s of n)if(rt.isPair(s)&&(s.key===e||s.key===t||rt.isScalar(s.key)&&s.key.value===t))return s}var no=class extends qg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(rt.MAP,e),this.items=[]}static from(e,t,s){let{keepUndefined:r,replacer:i}=s,o=new this(e),a=(l,c)=>{if(typeof i=="function")c=i.call(t,l,c);else if(Array.isArray(i)&&!i.includes(l))return;(c!==void 0||r)&&o.items.push(jn.createPair(l,c,s))};if(t instanceof Map)for(let[l,c]of t)a(l,c);else if(t&&typeof t=="object")for(let l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let s;rt.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new jn.Pair(e,e?.value):s=new jn.Pair(e.key,e.value);let r=Ts(this.items,s.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${s.key} already set`);rt.isScalar(r.value)&&Fg.isScalarValue(s.value)?r.value.value=s.value:r.value=s.value}else if(i){let o=this.items.findIndex(a=>i(s,a)<0);o===-1?this.items.push(s):this.items.splice(o,0,s)}else this.items.push(s)}delete(e){let t=Ts(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=Ts(this.items,e)?.value;return(!t&&rt.isScalar(r)?r.value:r)??void 0}has(e){return!!Ts(this.items,e)}set(e,t){this.add(new jn.Pair(e,t),!0)}toJSON(e,t,s){let r=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let i of this.items)jg.addPairToJSMap(t,r,i);return r}toString(e,t,s){if(!e)return JSON.stringify(this);for(let r of this.items)if(!rt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ug.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}};ro.YAMLMap=no;ro.findPair=Ts});var Ft=T($l=>{"use strict";var Kg=U(),Pl=it(),Hg={collection:"map",default:!0,nodeClass:Pl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return Kg.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>Pl.YAMLMap.from(n,e,t)};$l.map=Hg});var ot=T(Rl=>{"use strict";var Wg=gs(),Gg=so(),Vg=An(),Fn=U(),Yg=Z(),Jg=Ze(),io=class extends Vg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Fn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=qn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let s=qn(e);if(typeof s!="number")return;let r=this.items[s];return!t&&Fn.isScalar(r)?r.value:r}has(e){let t=qn(e);return typeof t=="number"&&t<this.items.length}set(e,t){let s=qn(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[s];Fn.isScalar(r)&&Yg.isScalarValue(t)?r.value=t:this.items[s]=t}toJSON(e,t){let s=[];t?.onCreate&&t.onCreate(s);let r=0;for(let i of this.items)s.push(Jg.toJS(i,String(r++),t));return s}toString(e,t,s){return e?Gg.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){let{replacer:r}=s,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof r=="function"){let l=t instanceof Set?a:String(o++);a=r.call(t,l,a)}i.items.push(Wg.createNode(a,void 0,s))}}return i}};function qn(n){let e=Fn.isScalar(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Rl.YAMLSeq=io});var Kt=T(Ul=>{"use strict";var zg=U(),Bl=ot(),Qg={collection:"seq",default:!0,nodeClass:Bl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return zg.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>Bl.YAMLSeq.from(n,e,t)};Ul.seq=Qg});var Is=T(jl=>{"use strict";var Xg=ks(),Zg={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,s){return e=Object.assign({actualString:!0},e),Xg.stringifyString(n,e,t,s)}};jl.string=Zg});var Kn=T(Kl=>{"use strict";var ql=Z(),Fl={identify:n=>n==null,createNode:()=>new ql.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ql.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&Fl.test.test(n)?n:e.options.nullStr};Kl.nullTag=Fl});var oo=T(Wl=>{"use strict";var ey=Z(),Hl={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new ey.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&Hl.test.test(n)){let s=n[0]==="t"||n[0]==="T";if(e===s)return n}return e?t.options.trueStr:t.options.falseStr}};Wl.boolTag=Hl});var Ht=T(Gl=>{"use strict";function ty({format:n,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);let r=typeof s=="number"?s:Number(s);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=Object.is(s,-0)?"-0":JSON.stringify(s);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}Gl.stringifyNumber=ty});var co=T(Hn=>{"use strict";var sy=Z(),ao=Ht(),ny={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ao.stringifyNumber},ry={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():ao.stringifyNumber(n)}},iy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new sy.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:ao.stringifyNumber};Hn.float=iy;Hn.floatExp=ry;Hn.floatNaN=ny});var uo=T(Gn=>{"use strict";var Vl=Ht(),Wn=n=>typeof n=="bigint"||Number.isInteger(n),lo=(n,e,t,{intAsBigInt:s})=>s?BigInt(n):parseInt(n.substring(e),t);function Yl(n,e,t){let{value:s}=n;return Wn(s)&&s>=0?t+s.toString(e):Vl.stringifyNumber(n)}var oy={identify:n=>Wn(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>lo(n,2,8,t),stringify:n=>Yl(n,8,"0o")},ay={identify:Wn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>lo(n,0,10,t),stringify:Vl.stringifyNumber},cy={identify:n=>Wn(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>lo(n,2,16,t),stringify:n=>Yl(n,16,"0x")};Gn.int=ay;Gn.intHex=cy;Gn.intOct=oy});var zl=T(Jl=>{"use strict";var ly=Ft(),dy=Kn(),uy=Kt(),hy=Is(),fy=oo(),ho=co(),fo=uo(),py=[ly.map,uy.seq,hy.string,dy.nullTag,fy.boolTag,fo.intOct,fo.int,fo.intHex,ho.floatNaN,ho.floatExp,ho.float];Jl.schema=py});var Zl=T(Xl=>{"use strict";var my=Z(),gy=Ft(),yy=Kt();function Ql(n){return typeof n=="bigint"||Number.isInteger(n)}var Vn=({value:n})=>JSON.stringify(n),wy=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:Vn},{identify:n=>n==null,createNode:()=>new my.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Vn},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:Vn},{identify:Ql,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>Ql(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:Vn}],Sy={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},ky=[gy.map,yy.seq].concat(wy,Sy);Xl.schema=ky});var mo=T(ed=>{"use strict";var As=H("buffer"),po=Z(),by=ks(),_y={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof As.Buffer=="function")return As.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let r=0;r<t.length;++r)s[r]=t.charCodeAt(r);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},s,r,i){if(!t)return"";let o=t,a;if(typeof As.Buffer=="function")a=o instanceof As.Buffer?o.toString("base64"):As.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=po.Scalar.BLOCK_LITERAL),e!==po.Scalar.QUOTE_DOUBLE){let l=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),c=Math.ceil(a.length/l),d=new Array(c);for(let u=0,h=0;u<c;++u,h+=l)d[u]=a.substr(h,l);a=d.join(e===po.Scalar.BLOCK_LITERAL?`
56
- `:" ")}return by.stringifyString({comment:n,type:e,value:a},s,r,i)}};ed.binary=_y});var zn=T(Jn=>{"use strict";var Yn=U(),go=nt(),vy=Z(),Ty=ot();function td(n,e){if(Yn.isSeq(n))for(let t=0;t<n.items.length;++t){let s=n.items[t];if(!Yn.isPair(s)){if(Yn.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let r=s.items[0]||new go.Pair(new vy.Scalar(null));if(s.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${s.commentBefore}
57
- ${r.key.commentBefore}`:s.commentBefore),s.comment){let i=r.value??r.key;i.comment=i.comment?`${s.comment}
58
- ${i.comment}`:s.comment}s=r}n.items[t]=Yn.isPair(s)?s:new go.Pair(s)}}else e("Expected a sequence for this tag");return n}function sd(n,e,t){let{replacer:s}=t,r=new Ty.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(i++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)a=c[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=o;r.items.push(go.createPair(a,l,t))}return r}var Iy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:td,createNode:sd};Jn.createPairs=sd;Jn.pairs=Iy;Jn.resolvePairs=td});var So=T(wo=>{"use strict";var nd=U(),yo=Ze(),Cs=it(),Ay=ot(),rd=zn(),wt=class n extends Ay.YAMLSeq{constructor(){super(),this.add=Cs.YAMLMap.prototype.add.bind(this),this.delete=Cs.YAMLMap.prototype.delete.bind(this),this.get=Cs.YAMLMap.prototype.get.bind(this),this.has=Cs.YAMLMap.prototype.has.bind(this),this.set=Cs.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let s=new Map;t?.onCreate&&t.onCreate(s);for(let r of this.items){let i,o;if(nd.isPair(r)?(i=yo.toJS(r.key,"",t),o=yo.toJS(r.value,i,t)):i=yo.toJS(r,"",t),s.has(i))throw new Error("Ordered maps must not include duplicate keys");s.set(i,o)}return s}static from(e,t,s){let r=rd.createPairs(e,t,s),i=new this;return i.items=r.items,i}};wt.tag="tag:yaml.org,2002:omap";var Cy={collection:"seq",identify:n=>n instanceof Map,nodeClass:wt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=rd.resolvePairs(n,e),s=[];for(let{key:r}of t.items)nd.isScalar(r)&&(s.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):s.push(r.value));return Object.assign(new wt,t)},createNode:(n,e,t)=>wt.from(n,e,t)};wo.YAMLOMap=wt;wo.omap=Cy});var ld=T(ko=>{"use strict";var id=Z();function od({value:n,source:e},t){return e&&(n?ad:cd).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var ad={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new id.Scalar(!0),stringify:od},cd={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new id.Scalar(!1),stringify:od};ko.falseTag=cd;ko.trueTag=ad});var dd=T(Qn=>{"use strict";var Ey=Z(),bo=Ht(),Ny={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:bo.stringifyNumber},xy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():bo.stringifyNumber(n)}},Oy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new Ey.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:bo.stringifyNumber};Qn.float=Oy;Qn.floatExp=xy;Qn.floatNaN=Ny});var hd=T(Ns=>{"use strict";var ud=Ht(),Es=n=>typeof n=="bigint"||Number.isInteger(n);function Xn(n,e,t,{intAsBigInt:s}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let o=BigInt(n);return r==="-"?BigInt(-1)*o:o}let i=parseInt(n,t);return r==="-"?-1*i:i}function _o(n,e,t){let{value:s}=n;if(Es(s)){let r=s.toString(e);return s<0?"-"+t+r.substr(1):t+r}return ud.stringifyNumber(n)}var My={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>Xn(n,2,2,t),stringify:n=>_o(n,2,"0b")},Dy={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>Xn(n,1,8,t),stringify:n=>_o(n,8,"0")},Ly={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>Xn(n,0,10,t),stringify:ud.stringifyNumber},Py={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>Xn(n,2,16,t),stringify:n=>_o(n,16,"0x")};Ns.int=Ly;Ns.intBin=My;Ns.intHex=Py;Ns.intOct=Dy});var To=T(vo=>{"use strict";var tr=U(),Zn=nt(),er=it(),St=class n extends er.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;tr.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Zn.Pair(e.key,null):t=new Zn.Pair(e,null),er.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let s=er.findPair(this.items,e);return!t&&tr.isPair(s)?tr.isScalar(s.key)?s.key.value:s.key:s}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let s=er.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Zn.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){let{replacer:r}=s,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(Zn.createPair(o,null,s));return i}};St.tag="tag:yaml.org,2002:set";var $y={collection:"map",identify:n=>n instanceof Set,nodeClass:St,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>St.from(n,e,t),resolve(n,e){if(tr.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new St,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};vo.YAMLSet=St;vo.set=$y});var Ao=T(sr=>{"use strict";var Ry=Ht();function Io(n,e){let t=n[0],s=t==="-"||t==="+"?n.substring(1):n,r=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}function fd(n){let{value:e}=n,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ry.stringifyNumber(n);let s="";e<0&&(s="-",e*=t(-1));let r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var By={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>Io(n,t),stringify:fd},Uy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>Io(n,!1),stringify:fd},pd={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(pd.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,s,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,s-1,r,i||0,o||0,a||0,l),d=e[8];if(d&&d!=="Z"){let u=Io(d,!1);Math.abs(u)<30&&(u*=60),c-=6e4*u}return new Date(c)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};sr.floatTime=Uy;sr.intTime=By;sr.timestamp=pd});var yd=T(gd=>{"use strict";var jy=Ft(),qy=Kn(),Fy=Kt(),Ky=Is(),Hy=mo(),md=ld(),Co=dd(),nr=hd(),Wy=Pn(),Gy=So(),Vy=zn(),Yy=To(),Eo=Ao(),Jy=[jy.map,Fy.seq,Ky.string,qy.nullTag,md.trueTag,md.falseTag,nr.intBin,nr.intOct,nr.int,nr.intHex,Co.floatNaN,Co.floatExp,Co.float,Hy.binary,Wy.merge,Gy.omap,Vy.pairs,Yy.set,Eo.intTime,Eo.floatTime,Eo.timestamp];gd.schema=Jy});var Cd=T(Oo=>{"use strict";var bd=Ft(),zy=Kn(),_d=Kt(),Qy=Is(),Xy=oo(),No=co(),xo=uo(),Zy=zl(),ew=Zl(),vd=mo(),xs=Pn(),Td=So(),Id=zn(),wd=yd(),Ad=To(),rr=Ao(),Sd=new Map([["core",Zy.schema],["failsafe",[bd.map,_d.seq,Qy.string]],["json",ew.schema],["yaml11",wd.schema],["yaml-1.1",wd.schema]]),kd={binary:vd.binary,bool:Xy.boolTag,float:No.float,floatExp:No.floatExp,floatNaN:No.floatNaN,floatTime:rr.floatTime,int:xo.int,intHex:xo.intHex,intOct:xo.intOct,intTime:rr.intTime,map:bd.map,merge:xs.merge,null:zy.nullTag,omap:Td.omap,pairs:Id.pairs,seq:_d.seq,set:Ad.set,timestamp:rr.timestamp},tw={"tag:yaml.org,2002:binary":vd.binary,"tag:yaml.org,2002:merge":xs.merge,"tag:yaml.org,2002:omap":Td.omap,"tag:yaml.org,2002:pairs":Id.pairs,"tag:yaml.org,2002:set":Ad.set,"tag:yaml.org,2002:timestamp":rr.timestamp};function sw(n,e,t){let s=Sd.get(e);if(s&&!n)return t&&!s.includes(xs.merge)?s.concat(xs.merge):s.slice();let r=s;if(!r)if(Array.isArray(n))r=[];else{let i=Array.from(Sd.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(n))for(let i of n)r=r.concat(i);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(xs.merge)),r.reduce((i,o)=>{let a=typeof o=="string"?kd[o]:o;if(!a){let l=JSON.stringify(o),c=Object.keys(kd).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return i.includes(a)||i.push(a),i},[])}Oo.coreKnownTags=tw;Oo.getTags=sw});var Lo=T(Ed=>{"use strict";var Mo=U(),nw=Ft(),rw=Kt(),iw=Is(),ir=Cd(),ow=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,Do=class n{constructor({compat:e,customTags:t,merge:s,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ir.getTags(e,"compat"):e?ir.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?ir.coreKnownTags:{},this.tags=ir.getTags(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,Mo.MAP,{value:nw.map}),Object.defineProperty(this,Mo.SCALAR,{value:iw.string}),Object.defineProperty(this,Mo.SEQ,{value:rw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ow:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ed.Schema=Do});var xd=T(Nd=>{"use strict";var aw=U(),Po=bs(),Os=ys();function cw(n,e){let t=[],s=e.directives===!0;if(e.directives!==!1&&n.directives){let l=n.directives.toString(n);l?(t.push(l),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");let r=Po.createStringifyContext(n,e),{commentString:i}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let l=i(n.commentBefore);t.unshift(Os.indentComment(l,""))}let o=!1,a=null;if(n.contents){if(aw.isNode(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){let d=i(n.contents.commentBefore);t.push(Os.indentComment(d,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let l=a?void 0:()=>o=!0,c=Po.stringify(n.contents,r,()=>a=null,l);a&&(c+=Os.lineComment(c,"",i(a))),(c[0]==="|"||c[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${c}`:t.push(c)}else t.push(Po.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let l=i(n.comment);l.includes(`
59
- `)?(t.push("..."),t.push(Os.indentComment(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=n.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Os.indentComment(i(l),"")))}return t.join(`
51
+ `+rs.indentComment(c(n),l),a&&a()):d&&s&&s(),p}function nA({items:n},e,{flowChars:t,itemIndent:i}){let{indent:r,indentStep:o,flowCollectionPadding:s,options:{commentString:a}}=e;i+=o;let l=Object.assign({},e,{indent:i,inFlow:!0,type:null}),c=!1,u=0,d=[];for(let h=0;h<n.length;++h){let m=n[h],y=null;if(pn.isNode(m))m.spaceBefore&&d.push(""),is(e,d,m.commentBefore,!1),m.comment&&(y=m.comment);else if(pn.isPair(m)){let b=pn.isNode(m.key)?m.key:null;b&&(b.spaceBefore&&d.push(""),is(e,d,b.commentBefore,!1),b.comment&&(c=!0));let k=pn.isNode(m.value)?m.value:null;k?(k.comment&&(y=k.comment),k.commentBefore&&(c=!0)):m.value==null&&b?.comment&&(y=b.comment)}y&&(c=!0);let _=n_.stringify(m,l,()=>y=null);c||(c=d.length>u||_.includes(`
52
+ `)),h<n.length-1?_+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=d.reduce((b,k)=>b+k.length+2,2)+(_.length+2)>e.options.lineWidth)),c&&(_+=",")),y&&(_+=rs.lineComment(_,i,a(y))),d.push(_),u=d.length}let{start:f,end:p}=t;if(d.length===0)return f+p;if(!c){let h=d.reduce((m,y)=>m+y.length+2,2);c=e.options.lineWidth>0&&h>e.options.lineWidth}if(c){let h=f;for(let m of d)h+=m?`
53
+ ${o}${r}${m}`:`
54
+ `;return`${h}
55
+ ${r}${p}`}else return`${f}${s}${d.join(" ")}${s}${p}`}function is({indent:n,options:{commentString:e}},t,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let o=rs.indentComment(e(i),n);t.push(o.trimStart())}}r_.stringifyCollection=eA});var qt=N(hu=>{"use strict";var rA=pu(),iA=du(),oA=Ko(),Ft=Y(),os=Bt(),sA=he();function ci(n,e){let t=Ft.isScalar(e)?e.value:e;for(let i of n)if(Ft.isPair(i)&&(i.key===e||i.key===t||Ft.isScalar(i.key)&&i.key.value===t))return i}var mu=class extends oA.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Ft.MAP,e),this.items=[]}static from(e,t,i){let{keepUndefined:r,replacer:o}=i,s=new this(e),a=(l,c)=>{if(typeof o=="function")c=o.call(t,l,c);else if(Array.isArray(o)&&!o.includes(l))return;(c!==void 0||r)&&s.items.push(os.createPair(l,c,i))};if(t instanceof Map)for(let[l,c]of t)a(l,c);else if(t&&typeof t=="object")for(let l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let i;Ft.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new os.Pair(e,e?.value):i=new os.Pair(e.key,e.value);let r=ci(this.items,i.key),o=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${i.key} already set`);Ft.isScalar(r.value)&&sA.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(o){let s=this.items.findIndex(a=>o(i,a)<0);s===-1?this.items.push(i):this.items.splice(s,0,i)}else this.items.push(i)}delete(e){let t=ci(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=ci(this.items,e)?.value;return(!t&&Ft.isScalar(r)?r.value:r)??void 0}has(e){return!!ci(this.items,e)}set(e,t){this.add(new os.Pair(e,t),!0)}toJSON(e,t,i){let r=i?new i:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let o of this.items)iA.addPairToJSMap(t,r,o);return r}toString(e,t,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Ft.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),rA.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:t})}};hu.YAMLMap=mu;hu.findPair=ci});var Jn=N(o_=>{"use strict";var aA=Y(),i_=qt(),cA={collection:"map",default:!0,nodeClass:i_.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return aA.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>i_.YAMLMap.from(n,e,t)};o_.map=cA});var Zt=N(s_=>{"use strict";var lA=ei(),uA=pu(),dA=Ko(),as=Y(),fA=he(),pA=zt(),gu=class extends dA.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(as.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=ss(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let i=ss(e);if(typeof i!="number")return;let r=this.items[i];return!t&&as.isScalar(r)?r.value:r}has(e){let t=ss(e);return typeof t=="number"&&t<this.items.length}set(e,t){let i=ss(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[i];as.isScalar(r)&&fA.isScalarValue(t)?r.value=t:this.items[i]=t}toJSON(e,t){let i=[];t?.onCreate&&t.onCreate(i);let r=0;for(let o of this.items)i.push(pA.toJS(o,String(r++),t));return i}toString(e,t,i){return e?uA.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:i,onComment:t}):JSON.stringify(this)}static from(e,t,i){let{replacer:r}=i,o=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let a of t){if(typeof r=="function"){let l=t instanceof Set?a:String(s++);a=r.call(t,l,a)}o.items.push(lA.createNode(a,void 0,i))}}return o}};function ss(n){let e=as.isScalar(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}s_.YAMLSeq=gu});var Hn=N(c_=>{"use strict";var mA=Y(),a_=Zt(),hA={collection:"seq",default:!0,nodeClass:a_.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return mA.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>a_.YAMLSeq.from(n,e,t)};c_.seq=hA});var li=N(l_=>{"use strict";var gA=ii(),yA={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,i){return e=Object.assign({actualString:!0},e),gA.stringifyString(n,e,t,i)}};l_.string=yA});var cs=N(f_=>{"use strict";var u_=he(),d_={identify:n=>n==null,createNode:()=>new u_.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new u_.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&d_.test.test(n)?n:e.options.nullStr};f_.nullTag=d_});var yu=N(m_=>{"use strict";var vA=he(),p_={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new vA.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&p_.test.test(n)){let i=n[0]==="t"||n[0]==="T";if(e===i)return n}return e?t.options.trueStr:t.options.falseStr}};m_.boolTag=p_});var Yn=N(h_=>{"use strict";function _A({format:n,minFractionDigits:e,tag:t,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=Object.is(i,-0)?"-0":JSON.stringify(i);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(o)){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let a=e-(o.length-s-1);for(;a-- >0;)o+="0"}return o}h_.stringifyNumber=_A});var _u=N(ls=>{"use strict";var wA=he(),vu=Yn(),bA={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:vu.stringifyNumber},kA={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():vu.stringifyNumber(n)}},SA={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new wA.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:vu.stringifyNumber};ls.float=SA;ls.floatExp=kA;ls.floatNaN=bA});var bu=N(ds=>{"use strict";var g_=Yn(),us=n=>typeof n=="bigint"||Number.isInteger(n),wu=(n,e,t,{intAsBigInt:i})=>i?BigInt(n):parseInt(n.substring(e),t);function y_(n,e,t){let{value:i}=n;return us(i)&&i>=0?t+i.toString(e):g_.stringifyNumber(n)}var $A={identify:n=>us(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>wu(n,2,8,t),stringify:n=>y_(n,8,"0o")},xA={identify:us,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>wu(n,0,10,t),stringify:g_.stringifyNumber},IA={identify:n=>us(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>wu(n,2,16,t),stringify:n=>y_(n,16,"0x")};ds.int=xA;ds.intHex=IA;ds.intOct=$A});var __=N(v_=>{"use strict";var TA=Jn(),EA=cs(),AA=Hn(),OA=li(),CA=yu(),ku=_u(),Su=bu(),NA=[TA.map,AA.seq,OA.string,EA.nullTag,CA.boolTag,Su.intOct,Su.int,Su.intHex,ku.floatNaN,ku.floatExp,ku.float];v_.schema=NA});var k_=N(b_=>{"use strict";var DA=he(),PA=Jn(),MA=Hn();function w_(n){return typeof n=="bigint"||Number.isInteger(n)}var fs=({value:n})=>JSON.stringify(n),LA=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:fs},{identify:n=>n==null,createNode:()=>new DA.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:fs},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:fs},{identify:w_,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>w_(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:fs}],zA={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},jA=[PA.map,MA.seq].concat(LA,zA);b_.schema=jA});var xu=N(S_=>{"use strict";var ui=ne("buffer"),$u=he(),UA=ii(),RA={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof ui.Buffer=="function")return ui.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),i=new Uint8Array(t.length);for(let r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},i,r,o){if(!t)return"";let s=t,a;if(typeof ui.Buffer=="function")a=s instanceof ui.Buffer?s.toString("base64"):ui.Buffer.from(s.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<s.length;++c)l+=String.fromCharCode(s[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=$u.Scalar.BLOCK_LITERAL),e!==$u.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(a.length/l),u=new Array(c);for(let d=0,f=0;d<c;++d,f+=l)u[d]=a.substr(f,l);a=u.join(e===$u.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return UA.stringifyString({comment:n,type:e,value:a},i,r,o)}};S_.binary=RA});var hs=N(ms=>{"use strict";var ps=Y(),Iu=Bt(),BA=he(),FA=Zt();function $_(n,e){if(ps.isSeq(n))for(let t=0;t<n.items.length;++t){let i=n.items[t];if(!ps.isPair(i)){if(ps.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new Iu.Pair(new BA.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore}
57
+ ${r.key.commentBefore}`:i.commentBefore),i.comment){let o=r.value??r.key;o.comment=o.comment?`${i.comment}
58
+ ${o.comment}`:i.comment}i=r}n.items[t]=ps.isPair(i)?i:new Iu.Pair(i)}}else e("Expected a sequence for this tag");return n}function x_(n,e,t){let{replacer:i}=t,r=new FA.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let s of e){typeof i=="function"&&(s=i.call(e,String(o++),s));let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let c=Object.keys(s);if(c.length===1)a=c[0],l=s[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=s;r.items.push(Iu.createPair(a,l,t))}return r}var qA={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:$_,createNode:x_};ms.createPairs=x_;ms.pairs=qA;ms.resolvePairs=$_});var Au=N(Eu=>{"use strict";var I_=Y(),Tu=zt(),di=qt(),ZA=Zt(),T_=hs(),mn=class n extends ZA.YAMLSeq{constructor(){super(),this.add=di.YAMLMap.prototype.add.bind(this),this.delete=di.YAMLMap.prototype.delete.bind(this),this.get=di.YAMLMap.prototype.get.bind(this),this.has=di.YAMLMap.prototype.has.bind(this),this.set=di.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let i=new Map;t?.onCreate&&t.onCreate(i);for(let r of this.items){let o,s;if(I_.isPair(r)?(o=Tu.toJS(r.key,"",t),s=Tu.toJS(r.value,o,t)):o=Tu.toJS(r,"",t),i.has(o))throw new Error("Ordered maps must not include duplicate keys");i.set(o,s)}return i}static from(e,t,i){let r=T_.createPairs(e,t,i),o=new this;return o.items=r.items,o}};mn.tag="tag:yaml.org,2002:omap";var KA={collection:"seq",identify:n=>n instanceof Map,nodeClass:mn,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=T_.resolvePairs(n,e),i=[];for(let{key:r}of t.items)I_.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new mn,t)},createNode:(n,e,t)=>mn.from(n,e,t)};Eu.YAMLOMap=mn;Eu.omap=KA});var N_=N(Ou=>{"use strict";var E_=he();function A_({value:n,source:e},t){return e&&(n?O_:C_).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var O_={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new E_.Scalar(!0),stringify:A_},C_={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new E_.Scalar(!1),stringify:A_};Ou.falseTag=C_;Ou.trueTag=O_});var D_=N(gs=>{"use strict";var VA=he(),Cu=Yn(),WA={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Cu.stringifyNumber},GA={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Cu.stringifyNumber(n)}},JA={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new VA.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let i=n.substring(t+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Cu.stringifyNumber};gs.float=JA;gs.floatExp=GA;gs.floatNaN=WA});var M_=N(pi=>{"use strict";var P_=Yn(),fi=n=>typeof n=="bigint"||Number.isInteger(n);function ys(n,e,t,{intAsBigInt:i}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),i){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let s=BigInt(n);return r==="-"?BigInt(-1)*s:s}let o=parseInt(n,t);return r==="-"?-1*o:o}function Nu(n,e,t){let{value:i}=n;if(fi(i)){let r=i.toString(e);return i<0?"-"+t+r.substr(1):t+r}return P_.stringifyNumber(n)}var HA={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>ys(n,2,2,t),stringify:n=>Nu(n,2,"0b")},YA={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>ys(n,1,8,t),stringify:n=>Nu(n,8,"0")},XA={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>ys(n,0,10,t),stringify:P_.stringifyNumber},QA={identify:fi,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>ys(n,2,16,t),stringify:n=>Nu(n,16,"0x")};pi.int=XA;pi.intBin=HA;pi.intHex=QA;pi.intOct=YA});var Pu=N(Du=>{"use strict";var ws=Y(),vs=Bt(),_s=qt(),hn=class n extends _s.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;ws.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new vs.Pair(e.key,null):t=new vs.Pair(e,null),_s.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let i=_s.findPair(this.items,e);return!t&&ws.isPair(i)?ws.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=_s.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new vs.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,i);throw new Error("Set items must all have null values")}static from(e,t,i){let{replacer:r}=i,o=new this(e);if(t&&Symbol.iterator in Object(t))for(let s of t)typeof r=="function"&&(s=r.call(t,s,s)),o.items.push(vs.createPair(s,null,i));return o}};hn.tag="tag:yaml.org,2002:set";var eO={collection:"map",identify:n=>n instanceof Set,nodeClass:hn,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>hn.from(n,e,t),resolve(n,e){if(ws.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new hn,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};Du.YAMLSet=hn;Du.set=eO});var Lu=N(bs=>{"use strict";var tO=Yn();function Mu(n,e){let t=n[0],i=t==="-"||t==="+"?n.substring(1):n,r=s=>e?BigInt(s):Number(s),o=i.replace(/_/g,"").split(":").reduce((s,a)=>s*r(60)+r(a),r(0));return t==="-"?r(-1)*o:o}function L_(n){let{value:e}=n,t=s=>s;if(typeof e=="bigint")t=s=>BigInt(s);else if(isNaN(e)||!isFinite(e))return tO.stringifyNumber(n);let i="";e<0&&(i="-",e*=t(-1));let r=t(60),o=[e%r];return e<60?o.unshift(0):(e=(e-o[0])/r,o.unshift(e%r),e>=60&&(e=(e-o[0])/r,o.unshift(e))),i+o.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var nO={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>Mu(n,t),stringify:L_},rO={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>Mu(n,!1),stringify:L_},z_={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(z_.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,i,r,o,s,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,i-1,r,o||0,s||0,a||0,l),u=e[8];if(u&&u!=="Z"){let d=Mu(u,!1);Math.abs(d)<30&&(d*=60),c-=6e4*d}return new Date(c)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};bs.floatTime=rO;bs.intTime=nO;bs.timestamp=z_});var R_=N(U_=>{"use strict";var iO=Jn(),oO=cs(),sO=Hn(),aO=li(),cO=xu(),j_=N_(),zu=D_(),ks=M_(),lO=es(),uO=Au(),dO=hs(),fO=Pu(),ju=Lu(),pO=[iO.map,sO.seq,aO.string,oO.nullTag,j_.trueTag,j_.falseTag,ks.intBin,ks.intOct,ks.int,ks.intHex,zu.floatNaN,zu.floatExp,zu.float,cO.binary,lO.merge,uO.omap,dO.pairs,fO.set,ju.intTime,ju.floatTime,ju.timestamp];U_.schema=pO});var H_=N(Bu=>{"use strict";var Z_=Jn(),mO=cs(),K_=Hn(),hO=li(),gO=yu(),Uu=_u(),Ru=bu(),yO=__(),vO=k_(),V_=xu(),mi=es(),W_=Au(),G_=hs(),B_=R_(),J_=Pu(),Ss=Lu(),F_=new Map([["core",yO.schema],["failsafe",[Z_.map,K_.seq,hO.string]],["json",vO.schema],["yaml11",B_.schema],["yaml-1.1",B_.schema]]),q_={binary:V_.binary,bool:gO.boolTag,float:Uu.float,floatExp:Uu.floatExp,floatNaN:Uu.floatNaN,floatTime:Ss.floatTime,int:Ru.int,intHex:Ru.intHex,intOct:Ru.intOct,intTime:Ss.intTime,map:Z_.map,merge:mi.merge,null:mO.nullTag,omap:W_.omap,pairs:G_.pairs,seq:K_.seq,set:J_.set,timestamp:Ss.timestamp},_O={"tag:yaml.org,2002:binary":V_.binary,"tag:yaml.org,2002:merge":mi.merge,"tag:yaml.org,2002:omap":W_.omap,"tag:yaml.org,2002:pairs":G_.pairs,"tag:yaml.org,2002:set":J_.set,"tag:yaml.org,2002:timestamp":Ss.timestamp};function wO(n,e,t){let i=F_.get(e);if(i&&!n)return t&&!i.includes(mi.merge)?i.concat(mi.merge):i.slice();let r=i;if(!r)if(Array.isArray(n))r=[];else{let o=Array.from(F_.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${o} or define customTags array`)}if(Array.isArray(n))for(let o of n)r=r.concat(o);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(mi.merge)),r.reduce((o,s)=>{let a=typeof s=="string"?q_[s]:s;if(!a){let l=JSON.stringify(s),c=Object.keys(q_).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return o.includes(a)||o.push(a),o},[])}Bu.coreKnownTags=_O;Bu.getTags=wO});var Zu=N(Y_=>{"use strict";var Fu=Y(),bO=Jn(),kO=Hn(),SO=li(),$s=H_(),$O=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,qu=class n{constructor({compat:e,customTags:t,merge:i,resolveKnownTags:r,schema:o,sortMapEntries:s,toStringDefaults:a}){this.compat=Array.isArray(e)?$s.getTags(e,"compat"):e?$s.getTags(null,e):null,this.name=typeof o=="string"&&o||"core",this.knownTags=r?$s.coreKnownTags:{},this.tags=$s.getTags(t,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Fu.MAP,{value:bO.map}),Object.defineProperty(this,Fu.SCALAR,{value:SO.string}),Object.defineProperty(this,Fu.SEQ,{value:kO.seq}),this.sortMapEntries=typeof s=="function"?s:s===!0?$O:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Y_.Schema=qu});var Q_=N(X_=>{"use strict";var xO=Y(),Ku=oi(),hi=ti();function IO(n,e){let t=[],i=e.directives===!0;if(e.directives!==!1&&n.directives){let l=n.directives.toString(n);l?(t.push(l),i=!0):n.directives.docStart&&(i=!0)}i&&t.push("---");let r=Ku.createStringifyContext(n,e),{commentString:o}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let l=o(n.commentBefore);t.unshift(hi.indentComment(l,""))}let s=!1,a=null;if(n.contents){if(xO.isNode(n.contents)){if(n.contents.spaceBefore&&i&&t.push(""),n.contents.commentBefore){let u=o(n.contents.commentBefore);t.push(hi.indentComment(u,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let l=a?void 0:()=>s=!0,c=Ku.stringify(n.contents,r,()=>a=null,l);a&&(c+=hi.lineComment(c,"",o(a))),(c[0]==="|"||c[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${c}`:t.push(c)}else t.push(Ku.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let l=o(n.comment);l.includes(`
59
+ `)?(t.push("..."),t.push(hi.indentComment(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=n.comment;l&&s&&(l=l.replace(/^\n+/,"")),l&&((!s||a)&&t[t.length-1]!==""&&t.push(""),t.push(hi.indentComment(o(l),"")))}return t.join(`
60
60
  `)+`
61
- `}Nd.stringifyDocument=cw});var Ms=T(Od=>{"use strict";var lw=ms(),Wt=An(),ke=U(),dw=nt(),uw=Ze(),hw=Lo(),fw=xd(),$o=_n(),pw=Ui(),mw=gs(),Ro=Bi(),Bo=class n{constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ke.NODE_TYPE,{value:ke.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:s===void 0&&t&&(s=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},s);this.options=i;let{version:o}=i;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ro.Directives({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,r,s)}clone(){let e=Object.create(n.prototype,{[ke.NODE_TYPE]:{value:ke.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ke.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Gt(this.contents)&&this.contents.add(e)}addIn(e,t){Gt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let s=$o.anchorNames(this);e.anchor=!t||s.has(t)?$o.findNewAnchor(t||"a",s):t}return new lw.Alias(e.anchor)}createNode(e,t,s){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let y=S=>typeof S=="number"||S instanceof String||S instanceof Number,w=t.filter(y).map(String);w.length>0&&(t=t.concat(w)),r=t}else s===void 0&&t&&(s=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:c,tag:d}=s??{},{onAnchor:u,setAnchors:h,sourceObjects:p}=$o.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p},f=mw.createNode(e,d,m);return a&&ke.isCollection(f)&&(f.flow=!0),h(),f}createPair(e,t,s={}){let r=this.createNode(e,null,s),i=this.createNode(t,null,s);return new dw.Pair(r,i)}delete(e){return Gt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Wt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Gt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ke.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Wt.isEmptyPath(e)?!t&&ke.isScalar(this.contents)?this.contents.value:this.contents:ke.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ke.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Wt.isEmptyPath(e)?this.contents!==void 0:ke.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Wt.collectionFromPath(this.schema,[e],t):Gt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Wt.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Wt.collectionFromPath(this.schema,Array.from(e),t):Gt(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ro.Directives({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ro.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(s)this.schema=new hw.Schema(Object.assign(s,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:s,maxAliasCount:r,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=uw.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:c,res:d}of a.anchors.values())i(d,c);return typeof o=="function"?pw.applyReviver(o,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return fw.stringifyDocument(this,e)}};function Gt(n){if(ke.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}Od.Document=Bo});var Ps=T(Ls=>{"use strict";var Ds=class extends Error{constructor(e,t,s,r){super(),this.name=e,this.code=s,this.message=r,this.pos=t}},Uo=class extends Ds{constructor(e,t,s){super("YAMLParseError",e,t,s)}},jo=class extends Ds{constructor(e,t,s){super("YAMLWarning",e,t,s)}},gw=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:s,col:r}=t.linePos[0];t.message+=` at line ${s}, column ${r}`;let i=r-1,o=n.substring(e.lineStarts[s-1],e.lineStarts[s]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),s>1&&/^ *$/.test(o.substring(0,i))){let a=n.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
62
- `),o=a+o}if(/[^ ]/.test(o)){let a=1,l=t.linePos[1];l?.line===s&&l.col>r&&(a=Math.max(1,Math.min(l.col-r,80-i)));let c=" ".repeat(i)+"^".repeat(a);t.message+=`:
61
+ `}X_.stringifyDocument=IO});var gi=N(ew=>{"use strict";var TO=Qr(),Xn=Ko(),Ge=Y(),EO=Bt(),AO=zt(),OO=Zu(),CO=Q_(),Vu=Bo(),NO=Hl(),DO=ei(),Wu=Jl(),Gu=class n{constructor(e,t,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Ge.NODE_TYPE,{value:Ge.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t,t=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=o;let{version:s}=o;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new Wu.Directives({version:s}),this.setSchema(s,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(n.prototype,{[Ge.NODE_TYPE]:{value:Ge.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Ge.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Qn(this.contents)&&this.contents.add(e)}addIn(e,t){Qn(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let i=Vu.anchorNames(this);e.anchor=!t||i.has(t)?Vu.findNewAnchor(t||"a",i):t}return new TO.Alias(e.anchor)}createNode(e,t,i){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let y=b=>typeof b=="number"||b instanceof String||b instanceof Number,_=t.filter(y).map(String);_.length>0&&(t=t.concat(_)),r=t}else i===void 0&&t&&(i=t,t=void 0);let{aliasDuplicateObjects:o,anchorPrefix:s,flow:a,keepUndefined:l,onTagObj:c,tag:u}=i??{},{onAnchor:d,setAnchors:f,sourceObjects:p}=Vu.createNodeAnchors(this,s||"a"),h={aliasDuplicateObjects:o??!0,keepUndefined:l??!1,onAnchor:d,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p},m=DO.createNode(e,u,h);return a&&Ge.isCollection(m)&&(m.flow=!0),f(),m}createPair(e,t,i={}){let r=this.createNode(e,null,i),o=this.createNode(t,null,i);return new EO.Pair(r,o)}delete(e){return Qn(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Xn.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Qn(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Ge.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Xn.isEmptyPath(e)?!t&&Ge.isScalar(this.contents)?this.contents.value:this.contents:Ge.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Ge.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Xn.isEmptyPath(e)?this.contents!==void 0:Ge.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Xn.collectionFromPath(this.schema,[e],t):Qn(this.contents)&&this.contents.set(e,t)}setIn(e,t){Xn.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Xn.collectionFromPath(this.schema,Array.from(e),t):Qn(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Wu.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Wu.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(i)this.schema=new OO.Schema(Object.assign(i,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:i,maxAliasCount:r,onAnchor:o,reviver:s}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=AO.toJS(this.contents,t??"",a);if(typeof o=="function")for(let{count:c,res:u}of a.anchors.values())o(u,c);return typeof s=="function"?NO.applyReviver(s,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return CO.stringifyDocument(this,e)}};function Qn(n){if(Ge.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}ew.Document=Gu});var _i=N(vi=>{"use strict";var yi=class extends Error{constructor(e,t,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=t}},Ju=class extends yi{constructor(e,t,i){super("YAMLParseError",e,t,i)}},Hu=class extends yi{constructor(e,t,i){super("YAMLWarning",e,t,i)}},PO=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:i,col:r}=t.linePos[0];t.message+=` at line ${i}, column ${r}`;let o=r-1,s=n.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(o>=60&&s.length>80){let a=Math.min(o-39,s.length-79);s="\u2026"+s.substring(a),o-=a-1}if(s.length>80&&(s=s.substring(0,79)+"\u2026"),i>1&&/^ *$/.test(s.substring(0,o))){let a=n.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
62
+ `),s=a+s}if(/[^ ]/.test(s)){let a=1,l=t.linePos[1];l?.line===i&&l.col>r&&(a=Math.max(1,Math.min(l.col-r,80-o)));let c=" ".repeat(o)+"^".repeat(a);t.message+=`:
63
63
 
64
- ${o}
64
+ ${s}
65
65
  ${c}
66
- `}};Ls.YAMLError=Ds;Ls.YAMLParseError=Uo;Ls.YAMLWarning=jo;Ls.prettifyError=gw});var $s=T(Md=>{"use strict";function yw(n,{flow:e,indicator:t,next:s,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,c=a,d=a,u="",h="",p=!1,m=!1,f=null,y=null,w=null,S=null,_=null,v=null,I=null;for(let A of n)switch(m&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),f&&(c&&A.type!=="comment"&&A.type!=="newline"&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),A.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&A.source.includes(" ")&&(f=A),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=A.source.substring(1)||" ";u?u+=h+E:u=E,h="",c=!1;break}case"newline":c?u?u+=A.source:(!v||t!=="seq-item-ind")&&(l=!0):h+=A.source,c=!0,p=!0,(y||w)&&(S=A),d=!0;break;case"anchor":y&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=A,I??(I=A.offset),c=!1,d=!1,m=!0;break;case"tag":{w&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),w=A,I??(I=A.offset),c=!1,d=!1,m=!0;break}case t:(y||w)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),v&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),v=A,c=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){_&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=A,c=!1,d=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),c=!1,d=!1}let N=n[n.length-1],D=N?N.offset+N.source.length:r;return m&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(c&&f.indent<=o||s?.type==="block-map"||s?.type==="block-seq")&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:v,spaceBefore:l,comment:u,hasNewline:p,anchor:y,tag:w,newlineAfterProp:S,end:D,start:I??D}}Md.resolveProps=yw});var or=T(Dd=>{"use strict";function qo(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
67
- `))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(qo(e.key)||qo(e.value))return!0}return!1;default:return!0}}Dd.containsNewline=qo});var Fo=T(Ld=>{"use strict";var ww=or();function Sw(n,e,t){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===n&&(s.source==="]"||s.source==="}")&&ww.containsNewline(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ld.flowIndentCheck=Sw});var Ko=T($d=>{"use strict";var Pd=U();function kw(n,e,t){let{uniqueKeys:s}=n.options;if(s===!1)return!1;let r=typeof s=="function"?s:(i,o)=>i===o||Pd.isScalar(i)&&Pd.isScalar(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}$d.mapIncludes=kw});var Fd=T(qd=>{"use strict";var Rd=nt(),bw=it(),Bd=$s(),_w=or(),Ud=Fo(),vw=Ko(),jd="All mapping items must start at the same column";function Tw({composeNode:n,composeEmptyNode:e},t,s,r,i){let o=i?.nodeClass??bw.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=s.offset,c=null;for(let d of s.items){let{start:u,key:h,sep:p,value:m}=d,f=Bd.resolveProps(u,{indicator:"explicit-key-ind",next:h??p?.[0],offset:l,onError:r,parentIndent:s.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==s.indent&&r(l,"BAD_INDENT",jd)),!f.anchor&&!f.tag&&!p){c=f.end,f.comment&&(a.comment?a.comment+=`
68
- `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||_w.containsNewline(h))&&r(h??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==s.indent&&r(l,"BAD_INDENT",jd);t.atKey=!0;let w=f.end,S=h?n(t,h,f,r):e(t,w,u,null,f,r);t.schema.compat&&Ud.flowIndentCheck(s.indent,h,r),t.atKey=!1,vw.mapIncludes(t,a.items,S)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let _=Bd.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:S.range[2],onError:r,parentIndent:s.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=_.end,_.found){y&&(m?.type==="block-map"&&!_.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<_.found.offset-1024&&r(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let v=m?n(t,m,_,r):e(t,l,p,null,_,r);t.schema.compat&&Ud.flowIndentCheck(s.indent,m,r),l=v.range[2];let I=new Rd.Pair(S,v);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}else{y&&r(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),_.comment&&(S.comment?S.comment+=`
69
- `+_.comment:S.comment=_.comment);let v=new Rd.Pair(S);t.options.keepSourceTokens&&(v.srcToken=d),a.items.push(v)}}return c&&c<l&&r(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,l,c??l],a}qd.resolveBlockMap=Tw});var Hd=T(Kd=>{"use strict";var Iw=ot(),Aw=$s(),Cw=Fo();function Ew({composeNode:n,composeEmptyNode:e},t,s,r,i){let o=i?.nodeClass??Iw.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=s.offset,c=null;for(let{start:d,value:u}of s.items){let h=Aw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:l,onError:r,parentIndent:s.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||u)u?.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{c=h.end,h.comment&&(a.comment=h.comment);continue}let p=u?n(t,u,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Cw.flowIndentCheck(s.indent,u,r),l=p.range[2],a.items.push(p)}return a.range=[s.offset,l,c??l],a}Kd.resolveBlockSeq=Ew});var Vt=T(Wd=>{"use strict";function Nw(n,e,t,s){let r="";if(n){let i=!1,o="";for(let a of n){let{source:l,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{t&&!i&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=l.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=l),i=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:r,offset:e}}Wd.resolveEnd=Nw});var Jd=T(Yd=>{"use strict";var xw=U(),Ow=nt(),Gd=it(),Mw=ot(),Dw=Vt(),Vd=$s(),Lw=or(),Pw=Ko(),Ho="Block collections are not allowed within flow collections",Wo=n=>n&&(n.type==="block-map"||n.type==="block-seq");function $w({composeNode:n,composeEmptyNode:e},t,s,r,i){let o=s.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?Gd.YAMLMap:Mw.YAMLSeq),c=new l(t.schema);c.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=s.offset+s.start.source.length;for(let y=0;y<s.items.length;++y){let w=s.items[y],{start:S,key:_,sep:v,value:I}=w,N=Vd.resolveProps(S,{flow:a,indicator:"explicit-key-ind",next:_??v?.[0],offset:u,onError:r,parentIndent:s.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!v&&!I){y===0&&N.comma?r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&r(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(c.comment?c.comment+=`
70
- `+N.comment:c.comment=N.comment),u=N.end;continue}!o&&t.options.strict&&Lw.containsNewline(_)&&r(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)N.comma&&r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||r(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(let A of S)switch(A.type){case"comma":case"space":break;case"comment":D=A.source.substring(1);break e;default:break e}if(D){let A=c.items[c.items.length-1];xw.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
71
- `+D:A.comment=D,N.comment=N.comment.substring(D.length+1)}}if(!o&&!v&&!N.found){let D=I?n(t,I,N,r):e(t,N.end,v,null,N,r);c.items.push(D),u=D.range[2],Wo(I)&&r(D.range,"BLOCK_IN_FLOW",Ho)}else{t.atKey=!0;let D=N.end,A=_?n(t,_,N,r):e(t,D,S,null,N,r);Wo(_)&&r(A.range,"BLOCK_IN_FLOW",Ho),t.atKey=!1;let E=Vd.resolveProps(v??[],{flow:a,indicator:"map-value-ind",next:I,offset:A.range[2],onError:r,parentIndent:s.indent,startOnNewline:!1});if(E.found){if(!o&&!N.found&&t.options.strict){if(v)for(let $ of v){if($===E.found)break;if($.type==="newline"){r($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<E.found.offset-1024&&r(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else I&&("source"in I&&I.source?.[0]===":"?r(I,"MISSING_CHAR",`Missing space after : in ${a}`):r(E.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let G=I?n(t,I,E,r):E.found?e(t,E.end,v,null,E,r):null;G?Wo(I)&&r(G.range,"BLOCK_IN_FLOW",Ho):E.comment&&(A.comment?A.comment+=`
72
- `+E.comment:A.comment=E.comment);let W=new Ow.Pair(A,G);if(t.options.keepSourceTokens&&(W.srcToken=w),o){let $=c;Pw.mapIncludes(t,$.items,A)&&r(D,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(W)}else{let $=new Gd.YAMLMap(t.schema);$.flow=!0,$.items.push(W);let le=(G??A).range;$.range=[A.range[0],le[1],le[2]],c.items.push($)}u=G?G.range[2]:E.end}}let h=o?"}":"]",[p,...m]=s.end,f=u;if(p?.source===h)f=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),w=d?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;r(u,d?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let y=Dw.resolveEnd(m,f,t.options.strict,r);y.comment&&(c.comment?c.comment+=`
73
- `+y.comment:c.comment=y.comment),c.range=[s.offset,f,y.offset]}else c.range=[s.offset,f,f];return c}Yd.resolveFlowCollection=$w});var Qd=T(zd=>{"use strict";var Rw=U(),Bw=Z(),Uw=it(),jw=ot(),qw=Fd(),Fw=Hd(),Kw=Jd();function Go(n,e,t,s,r,i){let o=t.type==="block-map"?qw.resolveBlockMap(n,e,t,s,i):t.type==="block-seq"?Fw.resolveBlockSeq(n,e,t,s,i):Kw.resolveFlowCollection(n,e,t,s,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Hw(n,e,t,s,r){let i=s.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:p}=s,m=h&&i?h.offset>i.offset?h:i:h??i;m&&(!p||p.offset<m.offset)&&r(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Uw.YAMLMap.tagName&&a==="map"||o===jw.YAMLSeq.tagName&&a==="seq")return Go(n,e,t,r,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){let h=e.schema.knownTags[o];if(h?.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Go(n,e,t,r,o)}let c=Go(n,e,t,r,o,l),d=l.resolve?.(c,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??c,u=Rw.isNode(d)?d:new Bw.Scalar(d);return u.range=c.range,u.tag=o,l?.format&&(u.format=l.format),u}zd.composeCollection=Hw});var Yo=T(Xd=>{"use strict";var Vo=Z();function Ww(n,e,t){let s=e.offset,r=Gw(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[s,s,s]};let i=r.mode===">"?Vo.Scalar.BLOCK_FOLDED:Vo.Scalar.BLOCK_LITERAL,o=e.source?Vw(e.source):[],a=o.length;for(let f=o.length-1;f>=0;--f){let y=o[f][1];if(y===""||y==="\r")a=f;else break}if(a===0){let f=r.chomp==="+"&&o.length>0?`
74
- `.repeat(Math.max(1,o.length-1)):"",y=s+r.length;return e.source&&(y+=e.source.length),{value:f,type:i,comment:r.comment,range:[s,y,y]}}let l=e.indent+r.indent,c=e.offset+r.length,d=0;for(let f=0;f<a;++f){let[y,w]=o[f];if(w===""||w==="\r")r.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(c+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=y.length),d=f,l===0&&!n.atRoot&&t(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=y.length+w.length+1}for(let f=o.length-1;f>=a;--f)o[f][0].length>l&&(a=f+1);let u="",h="",p=!1;for(let f=0;f<d;++f)u+=o[f][0].slice(l)+`
75
- `;for(let f=d;f<a;++f){let[y,w]=o[f];c+=y.length+w.length+1;let S=w[w.length-1]==="\r";if(S&&(w=w.slice(0,-1)),w&&y.length<l){let v=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(c-w.length-(S?2:1),"BAD_INDENT",v),y=""}i===Vo.Scalar.BLOCK_LITERAL?(u+=h+y.slice(l)+w,h=`
76
- `):y.length>l||w[0]===" "?(h===" "?h=`
77
- `:!p&&h===`
78
- `&&(h=`
79
-
80
- `),u+=h+y.slice(l)+w,h=`
81
- `,p=!0):w===""?h===`
82
- `?u+=`
83
- `:h=`
84
- `:(u+=h+w,h=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let f=a;f<o.length;++f)u+=`
85
- `+o[f][0].slice(l);u[u.length-1]!==`
86
- `&&(u+=`
87
- `);break;default:u+=`
88
- `}let m=s+r.length+e.source.length;return{value:u,type:i,comment:r.comment,range:[s,m,m]}}function Gw({offset:n,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],i=r[0],o=0,a="",l=-1;for(let h=1;h<r.length;++h){let p=r[h];if(!a&&(p==="-"||p==="+"))a=p;else{let m=Number(p);!o&&m?o=m:l===-1&&(l=n+h)}}l!==-1&&s(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let c=!1,d="",u=r.length;for(let h=1;h<e.length;++h){let p=e[h];switch(p.type){case"space":c=!0;case"newline":u+=p.source.length;break;case"comment":t&&!c&&s(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,d=p.source.substring(1);break;case"error":s(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;s(p,"UNEXPECTED_TOKEN",m);let f=p.source;f&&typeof f=="string"&&(u+=f.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function Vw(n){let e=n.split(/\n( *)/),t=e[0],s=t.match(/^( *)/),i=[s?.[1]?[s[1],t.slice(s[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Xd.resolveBlockScalar=Ww});var zo=T(eu=>{"use strict";var Jo=Z(),Yw=Vt();function Jw(n,e,t){let{offset:s,type:r,source:i,end:o}=n,a,l,c=(h,p,m)=>t(s+h,p,m);switch(r){case"scalar":a=Jo.Scalar.PLAIN,l=zw(i,c);break;case"single-quoted-scalar":a=Jo.Scalar.QUOTE_SINGLE,l=Qw(i,c);break;case"double-quoted-scalar":a=Jo.Scalar.QUOTE_DOUBLE,l=Xw(i,c);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[s,s+i.length,s+i.length]}}let d=s+i.length,u=Yw.resolveEnd(o,d,e,t);return{value:l,type:a,comment:u.comment,range:[s,d,u.offset]}}function zw(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Zd(n)}function Qw(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),Zd(n.slice(1,-1)).replace(/''/g,"'")}function Zd(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
66
+ `}};vi.YAMLError=yi;vi.YAMLParseError=Ju;vi.YAMLWarning=Hu;vi.prettifyError=PO});var wi=N(tw=>{"use strict";function MO(n,{flow:e,indicator:t,next:i,offset:r,onError:o,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,d="",f="",p=!1,h=!1,m=null,y=null,_=null,b=null,k=null,O=null,A=null;for(let P of n)switch(h&&(P.type!=="space"&&P.type!=="newline"&&P.type!=="comma"&&o(P.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),h=!1),m&&(c&&P.type!=="comment"&&P.type!=="newline"&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),P.type){case"space":!e&&(t!=="doc-start"||i?.type!=="flow-collection")&&P.source.includes(" ")&&(m=P),u=!0;break;case"comment":{u||o(P,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let z=P.source.substring(1)||" ";d?d+=f+z:d=z,f="",c=!1;break}case"newline":c?d?d+=P.source:(!O||t!=="seq-item-ind")&&(l=!0):f+=P.source,c=!0,p=!0,(y||_)&&(b=P),u=!0;break;case"anchor":y&&o(P,"MULTIPLE_ANCHORS","A node can have at most one anchor"),P.source.endsWith(":")&&o(P.offset+P.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=P,A??(A=P.offset),c=!1,u=!1,h=!0;break;case"tag":{_&&o(P,"MULTIPLE_TAGS","A node can have at most one tag"),_=P,A??(A=P.offset),c=!1,u=!1,h=!0;break}case t:(y||_)&&o(P,"BAD_PROP_ORDER",`Anchors and tags must be after the ${P.source} indicator`),O&&o(P,"UNEXPECTED_TOKEN",`Unexpected ${P.source} in ${e??"collection"}`),O=P,c=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){k&&o(P,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),k=P,c=!1,u=!1;break}default:o(P,"UNEXPECTED_TOKEN",`Unexpected ${P.type} token`),c=!1,u=!1}let j=n[n.length-1],L=j?j.offset+j.source.length:r;return h&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&o(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(c&&m.indent<=s||i?.type==="block-map"||i?.type==="block-seq")&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:k,found:O,spaceBefore:l,comment:d,hasNewline:p,anchor:y,tag:_,newlineAfterProp:b,end:L,start:A??L}}tw.resolveProps=MO});var xs=N(nw=>{"use strict";function Yu(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
67
+ `))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(Yu(e.key)||Yu(e.value))return!0}return!1;default:return!0}}nw.containsNewline=Yu});var Xu=N(rw=>{"use strict";var LO=xs();function zO(n,e,t){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===n&&(i.source==="]"||i.source==="}")&&LO.containsNewline(e)&&t(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}rw.flowIndentCheck=zO});var Qu=N(ow=>{"use strict";var iw=Y();function jO(n,e,t){let{uniqueKeys:i}=n.options;if(i===!1)return!1;let r=typeof i=="function"?i:(o,s)=>o===s||iw.isScalar(o)&&iw.isScalar(s)&&o.value===s.value;return e.some(o=>r(o.key,t))}ow.mapIncludes=jO});var dw=N(uw=>{"use strict";var sw=Bt(),UO=qt(),aw=wi(),RO=xs(),cw=Xu(),BO=Qu(),lw="All mapping items must start at the same column";function FO({composeNode:n,composeEmptyNode:e},t,i,r,o){let s=o?.nodeClass??UO.YAMLMap,a=new s(t.schema);t.atRoot&&(t.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:d,key:f,sep:p,value:h}=u,m=aw.resolveProps(d,{indicator:"explicit-key-ind",next:f??p?.[0],offset:l,onError:r,parentIndent:i.indent,startOnNewline:!0}),y=!m.found;if(y){if(f&&(f.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in f&&f.indent!==i.indent&&r(l,"BAD_INDENT",lw)),!m.anchor&&!m.tag&&!p){c=m.end,m.comment&&(a.comment?a.comment+=`
68
+ `+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||RO.containsNewline(f))&&r(f??d[d.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&r(l,"BAD_INDENT",lw);t.atKey=!0;let _=m.end,b=f?n(t,f,m,r):e(t,_,d,null,m,r);t.schema.compat&&cw.flowIndentCheck(i.indent,f,r),t.atKey=!1,BO.mapIncludes(t,a.items,b)&&r(_,"DUPLICATE_KEY","Map keys must be unique");let k=aw.resolveProps(p??[],{indicator:"map-value-ind",next:h,offset:b.range[2],onError:r,parentIndent:i.indent,startOnNewline:!f||f.type==="block-scalar"});if(l=k.end,k.found){y&&(h?.type==="block-map"&&!k.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<k.found.offset-1024&&r(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let O=h?n(t,h,k,r):e(t,l,p,null,k,r);t.schema.compat&&cw.flowIndentCheck(i.indent,h,r),l=O.range[2];let A=new sw.Pair(b,O);t.options.keepSourceTokens&&(A.srcToken=u),a.items.push(A)}else{y&&r(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),k.comment&&(b.comment?b.comment+=`
69
+ `+k.comment:b.comment=k.comment);let O=new sw.Pair(b);t.options.keepSourceTokens&&(O.srcToken=u),a.items.push(O)}}return c&&c<l&&r(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[i.offset,l,c??l],a}uw.resolveBlockMap=FO});var pw=N(fw=>{"use strict";var qO=Zt(),ZO=wi(),KO=Xu();function VO({composeNode:n,composeEmptyNode:e},t,i,r,o){let s=o?.nodeClass??qO.YAMLSeq,a=new s(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:d}of i.items){let f=ZO.resolveProps(u,{indicator:"seq-item-ind",next:d,offset:l,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!f.found)if(f.anchor||f.tag||d)d?.type==="block-seq"?r(f.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{c=f.end,f.comment&&(a.comment=f.comment);continue}let p=d?n(t,d,f,r):e(t,f.end,u,null,f,r);t.schema.compat&&KO.flowIndentCheck(i.indent,d,r),l=p.range[2],a.items.push(p)}return a.range=[i.offset,l,c??l],a}fw.resolveBlockSeq=VO});var er=N(mw=>{"use strict";function WO(n,e,t,i){let r="";if(n){let o=!1,s="";for(let a of n){let{source:l,type:c}=a;switch(c){case"space":o=!0;break;case"comment":{t&&!o&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";r?r+=s+u:r=u,s="";break}case"newline":r&&(s+=l),o=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:r,offset:e}}mw.resolveEnd=WO});var vw=N(yw=>{"use strict";var GO=Y(),JO=Bt(),hw=qt(),HO=Zt(),YO=er(),gw=wi(),XO=xs(),QO=Qu(),ed="Block collections are not allowed within flow collections",td=n=>n&&(n.type==="block-map"||n.type==="block-seq");function eC({composeNode:n,composeEmptyNode:e},t,i,r,o){let s=i.start.source==="{",a=s?"flow map":"flow sequence",l=o?.nodeClass??(s?hw.YAMLMap:HO.YAMLSeq),c=new l(t.schema);c.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let d=i.offset+i.start.source.length;for(let y=0;y<i.items.length;++y){let _=i.items[y],{start:b,key:k,sep:O,value:A}=_,j=gw.resolveProps(b,{flow:a,indicator:"explicit-key-ind",next:k??O?.[0],offset:d,onError:r,parentIndent:i.indent,startOnNewline:!1});if(!j.found){if(!j.anchor&&!j.tag&&!O&&!A){y===0&&j.comma?r(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<i.items.length-1&&r(j.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),j.comment&&(c.comment?c.comment+=`
70
+ `+j.comment:c.comment=j.comment),d=j.end;continue}!s&&t.options.strict&&XO.containsNewline(k)&&r(k,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)j.comma&&r(j.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(j.comma||r(j.start,"MISSING_CHAR",`Missing , between ${a} items`),j.comment){let L="";e:for(let P of b)switch(P.type){case"comma":case"space":break;case"comment":L=P.source.substring(1);break e;default:break e}if(L){let P=c.items[c.items.length-1];GO.isPair(P)&&(P=P.value??P.key),P.comment?P.comment+=`
71
+ `+L:P.comment=L,j.comment=j.comment.substring(L.length+1)}}if(!s&&!O&&!j.found){let L=A?n(t,A,j,r):e(t,j.end,O,null,j,r);c.items.push(L),d=L.range[2],td(A)&&r(L.range,"BLOCK_IN_FLOW",ed)}else{t.atKey=!0;let L=j.end,P=k?n(t,k,j,r):e(t,L,b,null,j,r);td(k)&&r(P.range,"BLOCK_IN_FLOW",ed),t.atKey=!1;let z=gw.resolveProps(O??[],{flow:a,indicator:"map-value-ind",next:A,offset:P.range[2],onError:r,parentIndent:i.indent,startOnNewline:!1});if(z.found){if(!s&&!j.found&&t.options.strict){if(O)for(let W of O){if(W===z.found)break;if(W.type==="newline"){r(W,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}j.start<z.found.offset-1024&&r(z.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else A&&("source"in A&&A.source?.[0]===":"?r(A,"MISSING_CHAR",`Missing space after : in ${a}`):r(z.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let ae=A?n(t,A,z,r):z.found?e(t,z.end,O,null,z,r):null;ae?td(A)&&r(ae.range,"BLOCK_IN_FLOW",ed):z.comment&&(P.comment?P.comment+=`
72
+ `+z.comment:P.comment=z.comment);let ue=new JO.Pair(P,ae);if(t.options.keepSourceTokens&&(ue.srcToken=_),s){let W=c;QO.mapIncludes(t,W.items,P)&&r(L,"DUPLICATE_KEY","Map keys must be unique"),W.items.push(ue)}else{let W=new hw.YAMLMap(t.schema);W.flow=!0,W.items.push(ue);let Se=(ae??P).range;W.range=[P.range[0],Se[1],Se[2]],c.items.push(W)}d=ae?ae.range[2]:z.end}}let f=s?"}":"]",[p,...h]=i.end,m=d;if(p?.source===f)m=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),_=u?`${y} must end with a ${f}`:`${y} in block collection must be sufficiently indented and end with a ${f}`;r(d,u?"MISSING_CHAR":"BAD_INDENT",_),p&&p.source.length!==1&&h.unshift(p)}if(h.length>0){let y=YO.resolveEnd(h,m,t.options.strict,r);y.comment&&(c.comment?c.comment+=`
73
+ `+y.comment:c.comment=y.comment),c.range=[i.offset,m,y.offset]}else c.range=[i.offset,m,m];return c}yw.resolveFlowCollection=eC});var ww=N(_w=>{"use strict";var tC=Y(),nC=he(),rC=qt(),iC=Zt(),oC=dw(),sC=pw(),aC=vw();function nd(n,e,t,i,r,o){let s=t.type==="block-map"?oC.resolveBlockMap(n,e,t,i,o):t.type==="block-seq"?sC.resolveBlockSeq(n,e,t,i,o):aC.resolveFlowCollection(n,e,t,i,o),a=s.constructor;return r==="!"||r===a.tagName?(s.tag=a.tagName,s):(r&&(s.tag=r),s)}function cC(n,e,t,i,r){let o=i.tag,s=o?e.directives.tagName(o.source,f=>r(o,"TAG_RESOLVE_FAILED",f)):null;if(t.type==="block-seq"){let{anchor:f,newlineAfterProp:p}=i,h=f&&o?f.offset>o.offset?f:o:f??o;h&&(!p||p.offset<h.offset)&&r(h,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!o||!s||s==="!"||s===rC.YAMLMap.tagName&&a==="map"||s===iC.YAMLSeq.tagName&&a==="seq")return nd(n,e,t,r,s);let l=e.schema.tags.find(f=>f.tag===s&&f.collection===a);if(!l){let f=e.schema.knownTags[s];if(f?.collection===a)e.schema.tags.push(Object.assign({},f,{default:!1})),l=f;else return f?r(o,"BAD_COLLECTION_TYPE",`${f.tag} used for ${a} collection, but expects ${f.collection??"scalar"}`,!0):r(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),nd(n,e,t,r,s)}let c=nd(n,e,t,r,s,l),u=l.resolve?.(c,f=>r(o,"TAG_RESOLVE_FAILED",f),e.options)??c,d=tC.isNode(u)?u:new nC.Scalar(u);return d.range=c.range,d.tag=s,l?.format&&(d.format=l.format),d}_w.composeCollection=cC});var id=N(bw=>{"use strict";var rd=he();function lC(n,e,t){let i=e.offset,r=uC(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let o=r.mode===">"?rd.Scalar.BLOCK_FOLDED:rd.Scalar.BLOCK_LITERAL,s=e.source?dC(e.source):[],a=s.length;for(let m=s.length-1;m>=0;--m){let y=s[m][1];if(y===""||y==="\r")a=m;else break}if(a===0){let m=r.chomp==="+"&&s.length>0?`
74
+ `.repeat(Math.max(1,s.length-1)):"",y=i+r.length;return e.source&&(y+=e.source.length),{value:m,type:o,comment:r.comment,range:[i,y,y]}}let l=e.indent+r.indent,c=e.offset+r.length,u=0;for(let m=0;m<a;++m){let[y,_]=s[m];if(_===""||_==="\r")r.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(c+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=y.length),u=m,l===0&&!n.atRoot&&t(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=y.length+_.length+1}for(let m=s.length-1;m>=a;--m)s[m][0].length>l&&(a=m+1);let d="",f="",p=!1;for(let m=0;m<u;++m)d+=s[m][0].slice(l)+`
75
+ `;for(let m=u;m<a;++m){let[y,_]=s[m];c+=y.length+_.length+1;let b=_[_.length-1]==="\r";if(b&&(_=_.slice(0,-1)),_&&y.length<l){let O=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(c-_.length-(b?2:1),"BAD_INDENT",O),y=""}o===rd.Scalar.BLOCK_LITERAL?(d+=f+y.slice(l)+_,f=`
76
+ `):y.length>l||_[0]===" "?(f===" "?f=`
77
+ `:!p&&f===`
78
+ `&&(f=`
79
+
80
+ `),d+=f+y.slice(l)+_,f=`
81
+ `,p=!0):_===""?f===`
82
+ `?d+=`
83
+ `:f=`
84
+ `:(d+=f+_,f=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let m=a;m<s.length;++m)d+=`
85
+ `+s[m][0].slice(l);d[d.length-1]!==`
86
+ `&&(d+=`
87
+ `);break;default:d+=`
88
+ `}let h=i+r.length+e.source.length;return{value:d,type:o,comment:r.comment,range:[i,h,h]}}function uC({offset:n,props:e},t,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],o=r[0],s=0,a="",l=-1;for(let f=1;f<r.length;++f){let p=r[f];if(!a&&(p==="-"||p==="+"))a=p;else{let h=Number(p);!s&&h?s=h:l===-1&&(l=n+f)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let c=!1,u="",d=r.length;for(let f=1;f<e.length;++f){let p=e[f];switch(p.type){case"space":c=!0;case"newline":d+=p.source.length;break;case"comment":t&&!c&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),d+=p.source.length,u=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),d+=p.source.length;break;default:{let h=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",h);let m=p.source;m&&typeof m=="string"&&(d+=m.length)}}}return{mode:o,indent:s,chomp:a,comment:u,length:d}}function dC(n){let e=n.split(/\n( *)/),t=e[0],i=t.match(/^( *)/),o=[i?.[1]?[i[1],t.slice(i[1].length)]:["",t]];for(let s=1;s<e.length;s+=2)o.push([e[s],e[s+1]]);return o}bw.resolveBlockScalar=lC});var sd=N(Sw=>{"use strict";var od=he(),fC=er();function pC(n,e,t){let{offset:i,type:r,source:o,end:s}=n,a,l,c=(f,p,h)=>t(i+f,p,h);switch(r){case"scalar":a=od.Scalar.PLAIN,l=mC(o,c);break;case"single-quoted-scalar":a=od.Scalar.QUOTE_SINGLE,l=hC(o,c);break;case"double-quoted-scalar":a=od.Scalar.QUOTE_DOUBLE,l=gC(o,c);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+o.length,i+o.length]}}let u=i+o.length,d=fC.resolveEnd(s,u,e,t);return{value:l,type:a,comment:d.comment,range:[i,u,d.offset]}}function mC(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),kw(n)}function hC(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),kw(n.slice(1,-1)).replace(/''/g,"'")}function kw(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
89
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
90
- `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(n);if(!s)return n;let r=s[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;s=t.exec(n);)s[1]===""?i===`
91
- `?r+=i:i=`
92
- `:(r+=i+s[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(n),r+i+(s?.[1]??"")}function Xw(n,e){let t="";for(let s=1;s<n.length-1;++s){let r=n[s];if(!(r==="\r"&&n[s+1]===`
90
+ `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let i=e.exec(n);if(!i)return n;let r=i[1],o=" ",s=e.lastIndex;for(t.lastIndex=s;i=t.exec(n);)i[1]===""?o===`
91
+ `?r+=o:o=`
92
+ `:(r+=o+i[1],o=" "),s=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=s,i=a.exec(n),r+o+(i?.[1]??"")}function gC(n,e){let t="";for(let i=1;i<n.length-1;++i){let r=n[i];if(!(r==="\r"&&n[i+1]===`
93
93
  `))if(r===`
94
- `){let{fold:i,offset:o}=Zw(n,s);t+=i,s=o}else if(r==="\\"){let i=n[++s],o=eS[i];if(o)t+=o;else if(i===`
95
- `)for(i=n[s+1];i===" "||i===" ";)i=n[++s+1];else if(i==="\r"&&n[s+1]===`
96
- `)for(i=n[++s+1];i===" "||i===" ";)i=n[++s+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=tS(n,s+1,a,e),s+=a}else{let a=n.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(r===" "||r===" "){let i=s,o=n[s+1];for(;o===" "||o===" ";)o=n[++s+1];o!==`
97
- `&&!(o==="\r"&&n[s+2]===`
98
- `)&&(t+=s>i?n.slice(i,s+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function Zw(n,e){let t="",s=n[e+1];for(;(s===" "||s===" "||s===`
99
- `||s==="\r")&&!(s==="\r"&&n[e+2]!==`
100
- `);)s===`
94
+ `){let{fold:o,offset:s}=yC(n,i);t+=o,i=s}else if(r==="\\"){let o=n[++i],s=vC[o];if(s)t+=s;else if(o===`
95
+ `)for(o=n[i+1];o===" "||o===" ";)o=n[++i+1];else if(o==="\r"&&n[i+1]===`
96
+ `)for(o=n[++i+1];o===" "||o===" ";)o=n[++i+1];else if(o==="x"||o==="u"||o==="U"){let a={x:2,u:4,U:8}[o];t+=_C(n,i+1,a,e),i+=a}else{let a=n.substr(i-1,2);e(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(r===" "||r===" "){let o=i,s=n[i+1];for(;s===" "||s===" ";)s=n[++i+1];s!==`
97
+ `&&!(s==="\r"&&n[i+2]===`
98
+ `)&&(t+=i>o?n.slice(o,i+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function yC(n,e){let t="",i=n[e+1];for(;(i===" "||i===" "||i===`
99
+ `||i==="\r")&&!(i==="\r"&&n[e+2]!==`
100
+ `);)i===`
101
101
  `&&(t+=`
102
- `),e+=1,s=n[e+1];return t||(t=" "),{fold:t,offset:e}}var eS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
- `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function tS(n,e,t,s){let r=n.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(o)){let a=n.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}eu.resolveFlowScalar=Jw});var nu=T(su=>{"use strict";var kt=U(),tu=Z(),sS=Yo(),nS=zo();function rS(n,e,t,s){let{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?sS.resolveBlockScalar(n,e,s):nS.resolveFlowScalar(e,n.options.strict,s),l=t?n.directives.tagName(t.source,u=>s(t,"TAG_RESOLVE_FAILED",u)):null,c;n.options.stringKeys&&n.atKey?c=n.schema[kt.SCALAR]:l?c=iS(n.schema,r,l,t,s):e.type==="scalar"?c=oS(n,r,e,s):c=n.schema[kt.SCALAR];let d;try{let u=c.resolve(r,h=>s(t??e,"TAG_RESOLVE_FAILED",h),n.options);d=kt.isScalar(u)?u:new tu.Scalar(u)}catch(u){let h=u instanceof Error?u.message:String(u);s(t??e,"TAG_RESOLVE_FAILED",h),d=new tu.Scalar(r)}return d.range=a,d.source=r,i&&(d.type=i),l&&(d.tag=l),c.format&&(d.format=c.format),o&&(d.comment=o),d}function iS(n,e,t,s,r){if(t==="!")return n[kt.SCALAR];let i=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[kt.SCALAR])}function oS({atKey:n,directives:e,schema:t},s,r,i){let o=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(s))||t[kt.SCALAR];if(t.compat){let a=t.compat.find(l=>l.default&&l.test?.test(s))??t[kt.SCALAR];if(o.tag!==a.tag){let l=e.tagString(o.tag),c=e.tagString(a.tag),d=`Value may be parsed as either ${l} or ${c}`;i(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}su.composeScalar=rS});var iu=T(ru=>{"use strict";function aS(n,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let r=e[s];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++s];r?.type==="space";)n+=r.source.length,r=e[++s];break}}return n}ru.emptyScalarPosition=aS});var cu=T(Xo=>{"use strict";var cS=ms(),lS=U(),dS=Qd(),ou=nu(),uS=Vt(),hS=iu(),fS={composeNode:au,composeEmptyNode:Qo};function au(n,e,t,s){let r=n.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t,c,d=!0;switch(e.type){case"alias":c=pS(n,e,s),(a||l)&&s(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=ou.composeScalar(n,e,l,s),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=dS.composeCollection(fS,n,e,t,s),a&&(c.anchor=a.source.substring(1))}catch(u){let h=u instanceof Error?u.message:String(u);s(e,"RESOURCE_EXHAUSTION",h)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",u),d=!1}}return c??(c=Qo(n,e.offset,void 0,null,t,s)),a&&c.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!lS.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&s(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(c.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?c.comment=o:c.commentBefore=o),n.options.keepSourceTokens&&d&&(c.srcToken=e),c}function Qo(n,e,t,s,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},c){let d={type:"scalar",offset:hS.emptyScalarPosition(e,t,s),indent:-1,source:""},u=ou.composeScalar(n,d,a,c);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=l),u}function pS({options:n},{offset:e,source:t,end:s},r){let i=new cS.Alias(t.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=uS.resolveEnd(s,o,n.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Xo.composeEmptyNode=Qo;Xo.composeNode=au});var uu=T(du=>{"use strict";var mS=Ms(),lu=cu(),gS=Vt(),yS=$s();function wS(n,e,{offset:t,start:s,value:r,end:i},o){let a=Object.assign({_directives:e},n),l=new mS.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=yS.resolveProps(s,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?lu.composeNode(c,r,d,o):lu.composeEmptyNode(c,d.end,s,null,d,o);let u=l.contents.range[2],h=gS.resolveEnd(i,u,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,u,h.offset],l}du.composeDoc=wS});var ea=T(pu=>{"use strict";var SS=H("process"),kS=Bi(),bS=Ms(),Rs=Ps(),hu=U(),_S=uu(),vS=Vt();function Bs(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function fu(n){let e="",t=!1,s=!1;for(let r=0;r<n.length;++r){let i=n[r];switch(i[0]){case"#":e+=(e===""?"":s?`
102
+ `),e+=1,i=n[e+1];return t||(t=" "),{fold:t,offset:e}}var vC={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function _C(n,e,t,i){let r=n.substr(e,t),s=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(s)){let a=n.substr(e-2,t+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(s)}Sw.resolveFlowScalar=pC});var Iw=N(xw=>{"use strict";var gn=Y(),$w=he(),wC=id(),bC=sd();function kC(n,e,t,i){let{value:r,type:o,comment:s,range:a}=e.type==="block-scalar"?wC.resolveBlockScalar(n,e,i):bC.resolveFlowScalar(e,n.options.strict,i),l=t?n.directives.tagName(t.source,d=>i(t,"TAG_RESOLVE_FAILED",d)):null,c;n.options.stringKeys&&n.atKey?c=n.schema[gn.SCALAR]:l?c=SC(n.schema,r,l,t,i):e.type==="scalar"?c=$C(n,r,e,i):c=n.schema[gn.SCALAR];let u;try{let d=c.resolve(r,f=>i(t??e,"TAG_RESOLVE_FAILED",f),n.options);u=gn.isScalar(d)?d:new $w.Scalar(d)}catch(d){let f=d instanceof Error?d.message:String(d);i(t??e,"TAG_RESOLVE_FAILED",f),u=new $w.Scalar(r)}return u.range=a,u.source=r,o&&(u.type=o),l&&(u.tag=l),c.format&&(u.format=c.format),s&&(u.comment=s),u}function SC(n,e,t,i,r){if(t==="!")return n[gn.SCALAR];let o=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(e))return a;let s=n.knownTags[t];return s&&!s.collection?(n.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[gn.SCALAR])}function $C({atKey:n,directives:e,schema:t},i,r,o){let s=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(i))||t[gn.SCALAR];if(t.compat){let a=t.compat.find(l=>l.default&&l.test?.test(i))??t[gn.SCALAR];if(s.tag!==a.tag){let l=e.tagString(s.tag),c=e.tagString(a.tag),u=`Value may be parsed as either ${l} or ${c}`;o(r,"TAG_RESOLVE_FAILED",u,!0)}}return s}xw.composeScalar=kC});var Ew=N(Tw=>{"use strict";function xC(n,e,t){if(e){t??(t=e.length);for(let i=t-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++i];r?.type==="space";)n+=r.source.length,r=e[++i];break}}return n}Tw.emptyScalarPosition=xC});var Cw=N(cd=>{"use strict";var IC=Qr(),TC=Y(),EC=ww(),Aw=Iw(),AC=er(),OC=Ew(),CC={composeNode:Ow,composeEmptyNode:ad};function Ow(n,e,t,i){let r=n.atKey,{spaceBefore:o,comment:s,anchor:a,tag:l}=t,c,u=!0;switch(e.type){case"alias":c=NC(n,e,i),(a||l)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Aw.composeScalar(n,e,l,i),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=EC.composeCollection(CC,n,e,t,i),a&&(c.anchor=a.source.substring(1))}catch(d){let f=d instanceof Error?d.message:String(d);i(e,"RESOURCE_EXHAUSTION",f)}break;default:{let d=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",d),u=!1}}return c??(c=ad(n,e.offset,void 0,null,t,i)),a&&c.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!TC.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(c.spaceBefore=!0),s&&(e.type==="scalar"&&e.source===""?c.comment=s:c.commentBefore=s),n.options.keepSourceTokens&&u&&(c.srcToken=e),c}function ad(n,e,t,i,{spaceBefore:r,comment:o,anchor:s,tag:a,end:l},c){let u={type:"scalar",offset:OC.emptyScalarPosition(e,t,i),indent:-1,source:""},d=Aw.composeScalar(n,u,a,c);return s&&(d.anchor=s.source.substring(1),d.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(d.spaceBefore=!0),o&&(d.comment=o,d.range[2]=l),d}function NC({options:n},{offset:e,source:t,end:i},r){let o=new IC.Alias(t.substring(1));o.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=e+t.length,a=AC.resolveEnd(i,s,n.strict,r);return o.range=[e,s,a.offset],a.comment&&(o.comment=a.comment),o}cd.composeEmptyNode=ad;cd.composeNode=Ow});var Pw=N(Dw=>{"use strict";var DC=gi(),Nw=Cw(),PC=er(),MC=wi();function LC(n,e,{offset:t,start:i,value:r,end:o},s){let a=Object.assign({_directives:e},n),l=new DC.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=MC.resolveProps(i,{indicator:"doc-start",next:r??o?.[0],offset:t,onError:s,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&s(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?Nw.composeNode(c,r,u,s):Nw.composeEmptyNode(c,u.end,i,null,u,s);let d=l.contents.range[2],f=PC.resolveEnd(o,d,!1,s);return f.comment&&(l.comment=f.comment),l.range=[t,d,f.offset],l}Dw.composeDoc=LC});var ud=N(zw=>{"use strict";var zC=ne("process"),jC=Jl(),UC=gi(),bi=_i(),Mw=Y(),RC=Pw(),BC=er();function ki(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function Lw(n){let e="",t=!1,i=!1;for(let r=0;r<n.length;++r){let o=n[r];switch(o[0]){case"#":e+=(e===""?"":i?`
104
104
 
105
105
  `:`
106
- `)+(i.substring(1)||" "),t=!0,s=!1;break;case"%":n[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}var Zo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,r,i)=>{let o=Bs(t);i?this.warnings.push(new Rs.YAMLWarning(o,s,r)):this.errors.push(new Rs.YAMLParseError(o,s,r))},this.directives=new kS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:s,afterEmptyLine:r}=fu(this.prelude);if(s){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
107
- ${s}`:s;else if(r||e.directives.docStart||!i)e.commentBefore=s;else if(hu.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];hu.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${s}
108
- ${a}`:s}else{let o=i.commentBefore;i.commentBefore=o?`${s}
109
- ${o}`:s}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:fu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(let r of e)yield*this.next(r);yield*this.end(t,s)}*next(e){switch(SS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,s,r)=>{let i=Bs(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",s,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=_S.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,s=new Rs.YAMLParseError(Bs(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){let s="Unexpected doc-end without preceding document";this.errors.push(new Rs.YAMLParseError(Bs(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;let t=vS.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let s=this.doc.comment;this.doc.comment=s?`${s}
110
- ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Rs.YAMLParseError(Bs(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let s=Object.assign({_directives:this.directives},this.options),r=new bS.Document(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};pu.Composer=Zo});var yu=T(ar=>{"use strict";var TS=Yo(),IS=zo(),AS=Ps(),mu=ks();function CS(n,e=!0,t){if(n){let s=(r,i,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,i,o);else throw new AS.YAMLParseError([a,a+1],i,o)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return IS.resolveFlowScalar(n,e,s);case"block-scalar":return TS.resolveBlockScalar({options:{strict:e}},n,s)}}return null}function ES(n,e){let{implicitKey:t=!1,indent:s,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=mu.stringifyString({type:o,value:n},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:s,source:`
106
+ `)+(o.substring(1)||" "),t=!0,i=!1;break;case"%":n[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(i=!0),t=!1}}return{comment:e,afterEmptyLine:i}}var ld=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,i,r,o)=>{let s=ki(t);o?this.warnings.push(new bi.YAMLWarning(s,i,r)):this.errors.push(new bi.YAMLParseError(s,i,r))},this.directives=new jC.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:i,afterEmptyLine:r}=Lw(this.prelude);if(i){let o=e.contents;if(t)e.comment=e.comment?`${e.comment}
107
+ ${i}`:i;else if(r||e.directives.docStart||!o)e.commentBefore=i;else if(Mw.isCollection(o)&&!o.flow&&o.items.length>0){let s=o.items[0];Mw.isPair(s)&&(s=s.key);let a=s.commentBefore;s.commentBefore=a?`${i}
108
+ ${a}`:i}else{let s=o.commentBefore;o.commentBefore=s?`${i}
109
+ ${s}`:i}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Lw(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,i=-1){for(let r of e)yield*this.next(r);yield*this.end(t,i)}*next(e){switch(zC.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,i,r)=>{let o=ki(e);o[0]+=t,this.onError(o,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=RC.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new bi.YAMLParseError(ki(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new bi.YAMLParseError(ki(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let t=BC.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
110
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new bi.YAMLParseError(ki(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new UC.Document(void 0,i);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};zw.Composer=ld});var Rw=N(Is=>{"use strict";var FC=id(),qC=sd(),ZC=_i(),jw=ii();function KC(n,e=!0,t){if(n){let i=(r,o,s)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,o,s);else throw new ZC.YAMLParseError([a,a+1],o,s)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return qC.resolveFlowScalar(n,e,i);case"block-scalar":return FC.resolveBlockScalar({options:{strict:e}},n,i)}}return null}function VC(n,e){let{implicitKey:t=!1,indent:i,inFlow:r=!1,offset:o=-1,type:s="PLAIN"}=e,a=jw.stringifyString({type:s,value:n},{implicitKey:t,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:i,source:`
111
111
  `}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
112
- `),d=a.substring(0,c),u=a.substring(c+1)+`
113
- `,h=[{type:"block-scalar-header",offset:i,indent:s,source:d}];return gu(h,l)||h.push({type:"newline",offset:-1,indent:s,source:`
114
- `}),{type:"block-scalar",offset:i,indent:s,props:h,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:s,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:s,source:a,end:l};default:return{type:"scalar",offset:i,indent:s,source:a,end:l}}}function NS(n,e,t={}){let{afterKey:s=!1,implicitKey:r=!1,inFlow:i=!1,type:o}=t,a="indent"in n?n.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(n.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=n.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=mu.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":xS(n,l);break;case'"':ta(n,l,"double-quoted-scalar");break;case"'":ta(n,l,"single-quoted-scalar");break;default:ta(n,l,"scalar")}}function xS(n,e){let t=e.indexOf(`
115
- `),s=e.substring(0,t),r=e.substring(t+1)+`
116
- `;if(n.type==="block-scalar"){let i=n.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=s,n.source=r}else{let{offset:i}=n,o="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:s}];gu(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
117
- `});for(let l of Object.keys(n))l!=="type"&&l!=="offset"&&delete n[l];Object.assign(n,{type:"block-scalar",indent:o,props:a,source:r})}}function gu(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function ta(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let s=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let i of s)i.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:s});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
118
- `};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let s="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(n))i!=="type"&&i!=="offset"&&delete n[i];Object.assign(n,{type:t,indent:s,source:e,end:r})}}}ar.createScalarToken=ES;ar.resolveAsScalar=CS;ar.setScalarValue=NS});var Su=T(wu=>{"use strict";var OS=n=>"type"in n?lr(n):cr(n);function lr(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=lr(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=cr(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=cr(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=cr(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function cr({start:n,key:e,sep:t,value:s}){let r="";for(let i of n)r+=i.source;if(e&&(r+=lr(e)),t)for(let i of t)r+=i.source;return s&&(r+=lr(s)),r}wu.stringify=OS});var vu=T(_u=>{"use strict";var sa=Symbol("break visit"),MS=Symbol("skip children"),ku=Symbol("remove item");function bt(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),bu(Object.freeze([]),n,e)}bt.BREAK=sa;bt.SKIP=MS;bt.REMOVE=ku;bt.itemAtPath=(n,e)=>{let t=n;for(let[s,r]of e){let i=t?.[s];if(i&&"items"in i)t=i.items[r];else return}return t};bt.parentCollection=(n,e)=>{let t=bt.itemAtPath(n,e.slice(0,-1)),s=e[e.length-1][0],r=t?.[s];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function bu(n,e,t){let s=t(e,n);if(typeof s=="symbol")return s;for(let r of["key","value"]){let i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=bu(Object.freeze(n.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===sa)return sa;a===ku&&(i.items.splice(o,1),o-=1)}}typeof s=="function"&&r==="key"&&(s=s(e,n))}}return typeof s=="function"?s(e,n):s}_u.visit=bt});var dr=T(fe=>{"use strict";var na=yu(),DS=Su(),LS=vu(),ra="\uFEFF",ia="",oa="",aa="",PS=n=>!!n&&"items"in n,$S=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function RS(n){switch(n){case ra:return"<BOM>";case ia:return"<DOC>";case oa:return"<FLOW_END>";case aa:return"<SCALAR>";default:return JSON.stringify(n)}}function BS(n){switch(n){case ra:return"byte-order-mark";case ia:return"doc-mode";case oa:return"flow-error-end";case aa:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
112
+ `),u=a.substring(0,c),d=a.substring(c+1)+`
113
+ `,f=[{type:"block-scalar-header",offset:o,indent:i,source:u}];return Uw(f,l)||f.push({type:"newline",offset:-1,indent:i,source:`
114
+ `}),{type:"block-scalar",offset:o,indent:i,props:f,source:d}}case'"':return{type:"double-quoted-scalar",offset:o,indent:i,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:o,indent:i,source:a,end:l};default:return{type:"scalar",offset:o,indent:i,source:a,end:l}}}function WC(n,e,t={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:o=!1,type:s}=t,a="indent"in n?n.indent:null;if(i&&typeof a=="number"&&(a+=2),!s)switch(n.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let c=n.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let l=jw.stringifyString({type:s,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":GC(n,l);break;case'"':dd(n,l,"double-quoted-scalar");break;case"'":dd(n,l,"single-quoted-scalar");break;default:dd(n,l,"scalar")}}function GC(n,e){let t=e.indexOf(`
115
+ `),i=e.substring(0,t),r=e.substring(t+1)+`
116
+ `;if(n.type==="block-scalar"){let o=n.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=i,n.source=r}else{let{offset:o}=n,s="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:s,source:i}];Uw(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:s,source:`
117
+ `});for(let l of Object.keys(n))l!=="type"&&l!=="offset"&&delete n[l];Object.assign(n,{type:"block-scalar",indent:s,props:a,source:r})}}function Uw(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function dd(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let i=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let o of i)o.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
118
+ `};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let i="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(n))o!=="type"&&o!=="offset"&&delete n[o];Object.assign(n,{type:t,indent:i,source:e,end:r})}}}Is.createScalarToken=VC;Is.resolveAsScalar=KC;Is.setScalarValue=WC});var Fw=N(Bw=>{"use strict";var JC=n=>"type"in n?Es(n):Ts(n);function Es(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=Es(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=Ts(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=Ts(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=Ts(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function Ts({start:n,key:e,sep:t,value:i}){let r="";for(let o of n)r+=o.source;if(e&&(r+=Es(e)),t)for(let o of t)r+=o.source;return i&&(r+=Es(i)),r}Bw.stringify=JC});var Vw=N(Kw=>{"use strict";var fd=Symbol("break visit"),HC=Symbol("skip children"),qw=Symbol("remove item");function yn(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),Zw(Object.freeze([]),n,e)}yn.BREAK=fd;yn.SKIP=HC;yn.REMOVE=qw;yn.itemAtPath=(n,e)=>{let t=n;for(let[i,r]of e){let o=t?.[i];if(o&&"items"in o)t=o.items[r];else return}return t};yn.parentCollection=(n,e)=>{let t=yn.itemAtPath(n,e.slice(0,-1)),i=e[e.length-1][0],r=t?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Zw(n,e,t){let i=t(e,n);if(typeof i=="symbol")return i;for(let r of["key","value"]){let o=e[r];if(o&&"items"in o){for(let s=0;s<o.items.length;++s){let a=Zw(Object.freeze(n.concat([[r,s]])),o.items[s],t);if(typeof a=="number")s=a-1;else{if(a===fd)return fd;a===qw&&(o.items.splice(s,1),s-=1)}}typeof i=="function"&&r==="key"&&(i=i(e,n))}}return typeof i=="function"?i(e,n):i}Kw.visit=yn});var As=N(ze=>{"use strict";var pd=Rw(),YC=Fw(),XC=Vw(),md="\uFEFF",hd="",gd="",yd="",QC=n=>!!n&&"items"in n,eN=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function tN(n){switch(n){case md:return"<BOM>";case hd:return"<DOC>";case gd:return"<FLOW_END>";case yd:return"<SCALAR>";default:return JSON.stringify(n)}}function nN(n){switch(n){case md:return"byte-order-mark";case hd:return"doc-mode";case gd:return"flow-error-end";case yd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
119
119
  `:case`\r
120
- `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}fe.createScalarToken=na.createScalarToken;fe.resolveAsScalar=na.resolveAsScalar;fe.setScalarValue=na.setScalarValue;fe.stringify=DS.stringify;fe.visit=LS.visit;fe.BOM=ra;fe.DOCUMENT=ia;fe.FLOW_END=oa;fe.SCALAR=aa;fe.isCollection=PS;fe.isScalar=$S;fe.prettyToken=RS;fe.tokenType=BS});var da=T(Iu=>{"use strict";var Us=dr();function Ee(n){switch(n){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var Tu=new Set("0123456789ABCDEFabcdef"),US=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ur=new Set(",[]{}"),jS=new Set(` ,[]{}
122
- \r `),ca=n=>!n||jS.has(n),la=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let s=this.next??"stream";for(;s&&(t||this.hasChars(1));)s=yield*this.parseNext(s)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
120
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}ze.createScalarToken=pd.createScalarToken;ze.resolveAsScalar=pd.resolveAsScalar;ze.setScalarValue=pd.setScalarValue;ze.stringify=YC.stringify;ze.visit=XC.visit;ze.BOM=md;ze.DOCUMENT=hd;ze.FLOW_END=gd;ze.SCALAR=yd;ze.isCollection=QC;ze.isScalar=eN;ze.prettyToken=tN;ze.tokenType=nN});var wd=N(Gw=>{"use strict";var Si=As();function it(n){switch(n){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var Ww=new Set("0123456789ABCDEFabcdef"),rN=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Os=new Set(",[]{}"),iN=new Set(` ,[]{}
122
+ \r `),vd=n=>!n||iN.has(n),_d=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let i=this.next??"stream";for(;i&&(t||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
123
123
  `?!0:t==="\r"?this.buffer[e+1]===`
124
- `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let s=0;for(;t===" ";)t=this.buffer[++s+e];if(t==="\r"){let r=this.buffer[s+e+1];if(r===`
125
- `||!r&&!this.atEnd)return e+s+1}return t===`
126
- `||s>=this.indentNext||!t&&!this.atEnd?e+s:-1}if(t==="-"||t==="."){let s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&Ee(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
127
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Us.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,s=e.indexOf("#");for(;s!==-1;){let i=e[s-1];if(i===" "||i===" "){t=s-1;break}else s=e.indexOf("#",s+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Us.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Ee(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ee(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ee(t)){let s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ca),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,s=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=s=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&r[0]!=="#"||s===0&&(r.startsWith("---")||r.startsWith("..."))&&Ee(r[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Us.FLOW_END,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(ca),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ee(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let s=this.buffer.substring(0,t),r=s.indexOf(`
128
- `,this.pos);if(r!==-1){for(;r!==-1;){let i=this.continueScalar(r+1);if(i===-1)break;r=s.indexOf(`
129
- `,i)}r!==-1&&(t=r-(s[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ee(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,s;e:for(let i=this.pos;s=this.buffer[i];++i)switch(s){case" ":t+=1;break;case`
130
- `:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
131
- `)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
132
- `,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(s=this.buffer[r];s===" ";)s=this.buffer[++r];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
133
- `;)s=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
134
- `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Us.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,s=this.pos-1,r;for(;r=this.buffer[++s];)if(r===":"){let i=this.buffer[s+1];if(Ee(i)||e&&ur.has(i))break;t=s}else if(Ee(r)){let i=this.buffer[s+1];if(r==="\r"&&(i===`
135
- `?(s+=1,r=`
136
- `,i=this.buffer[s+1]):t=s),i==="#"||e&&ur.has(i))break;if(r===`
137
- `){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&ur.has(r))break;t=s}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Us.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(ca))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Ee(t)||e&&ur.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Ee(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(US.has(t))t=this.buffer[++e];else if(t==="%"&&Tu.has(this.buffer[e+1])&&Tu.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
124
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let i=0;for(;t===" ";)t=this.buffer[++i+e];if(t==="\r"){let r=this.buffer[i+e+1];if(r===`
125
+ `||!r&&!this.atEnd)return e+i+1}return t===`
126
+ `||i>=this.indentNext||!t&&!this.atEnd?e+i:-1}if(t==="-"||t==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&it(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
127
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Si.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,i=e.indexOf("#");for(;i!==-1;){let o=e[i-1];if(o===" "||o===" "){t=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let o=e[t-1];if(o===" "||o===" ")t-=1;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Si.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&it(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!it(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&it(t)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(vd),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,i=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=i=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&r[0]!=="#"||i===0&&(r.startsWith("---")||r.startsWith("..."))&&it(r[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Si.FLOW_END,yield*this.parseLineStart();let o=0;for(;r[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),r[o]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(vd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||it(s)||s===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let o=0;for(;this.buffer[t-1-o]==="\\";)o+=1;if(o%2===0)break;t=this.buffer.indexOf('"',t+1)}let i=this.buffer.substring(0,t),r=i.indexOf(`
128
+ `,this.pos);if(r!==-1){for(;r!==-1;){let o=this.continueScalar(r+1);if(o===-1)break;r=i.indexOf(`
129
+ `,o)}r!==-1&&(t=r-(i[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>it(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,i;e:for(let o=this.pos;i=this.buffer[o];++o)switch(i){case" ":t+=1;break;case`
130
+ `:e=o,t=0;break;case"\r":{let s=this.buffer[o+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
131
+ `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(e+1);if(o===-1)break;e=this.buffer.indexOf(`
132
+ `,o)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(i=this.buffer[r];i===" ";)i=this.buffer[++r];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
133
+ `;)i=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let o=e-1,s=this.buffer[o];s==="\r"&&(s=this.buffer[--o]);let a=o;for(;s===" ";)s=this.buffer[--o];if(s===`
134
+ `&&o>=this.pos&&o+1+t>a)e=o;else break}while(!0);return yield Si.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let o=this.buffer[i+1];if(it(o)||e&&Os.has(o))break;t=i}else if(it(r)){let o=this.buffer[i+1];if(r==="\r"&&(o===`
135
+ `?(i+=1,r=`
136
+ `,o=this.buffer[i+1]):t=i),o==="#"||e&&Os.has(o))break;if(r===`
137
+ `){let s=this.continueScalar(i+1);if(s===-1)break;i=Math.max(i,s-2)}}else{if(e&&Os.has(r))break;t=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Si.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(vd))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(it(t)||e&&Os.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!it(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(rN.has(t))t=this.buffer[++e];else if(t==="%"&&Ww.has(this.buffer[e+1])&&Ww.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
138
138
  `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
139
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,s;do s=this.buffer[++t];while(s===" "||e&&s===" ");let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};Iu.Lexer=la});var ha=T(Au=>{"use strict";var ua=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,s=this.lineStarts.length;for(;t<s;){let i=t+s>>1;this.lineStarts[i]<e?t=i+1:s=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};Au.LineCounter=ua});var pa=T(Ou=>{"use strict";var qS=H("process"),Cu=dr(),FS=da();function at(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Eu(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function xu(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function hr(n){switch(n.type){case"document":return n.start;case"block-map":{let e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function Yt(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function Nu(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!at(e.start,"explicit-key-ind")&&!at(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,xu(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var fa=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new FS.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let s of this.lexer.lex(e,t))yield*this.next(s);t||(yield*this.end())}*next(e){if(this.source=e,qS.env.LOG_TOKENS&&console.log("|",Cu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Cu.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let s=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in s?s.indent:0:t.type==="flow-collection"&&s.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Nu(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{let r=s.items[s.items.length-1];if(r.value){s.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=s.items[s.items.length-1];r.value?s.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=s.items[s.items.length-1];!r||r.value?s.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((s.type==="document"||s.type==="block-map"||s.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Eu(r.start)===-1&&(t.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(s.type==="document"?s.end=r.start:s.items.push({start:r.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Eu(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=hr(this.peek(2)),s=Yt(t),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
139
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,i;do i=this.buffer[++t];while(i===" "||e&&i===" ");let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,i=this.buffer[t];for(;!e(i);)i=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};Gw.Lexer=_d});var kd=N(Jw=>{"use strict";var bd=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,i=this.lineStarts.length;for(;t<i;){let o=t+i>>1;this.lineStarts[o]<e?t=o+1:i=o}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};Jw.LineCounter=bd});var $d=N(eb=>{"use strict";var oN=ne("process"),Hw=As(),sN=wd();function Kt(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Yw(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Qw(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function Cs(n){switch(n.type){case"document":return n.start;case"block-map":{let e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function tr(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function Xw(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!Kt(e.start,"explicit-key-ind")&&!Kt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Qw(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var Sd=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new sN.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(e,t))yield*this.next(i);t||(yield*this.end())}*next(e){if(this.source=e,oN.env.LOG_TOKENS&&console.log("|",Hw.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Hw.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let i=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let i=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in i?i.indent:0:t.type==="flow-collection"&&i.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Xw(t),i.type){case"document":i.value=t;break;case"block-scalar":i.props.push(t);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Yw(r.start)===-1&&(t.indent===0||r.start.every(o=>o.type!=="comment"||o.indent<t.indent))&&(i.type==="document"?i.end=r.start:i.items.push({start:r.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Yw(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=Cs(this.peek(2)),i=tr(t),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
- `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,r=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(at(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(xu(t.key)&&!at(t.sep,"newline")){let o=Yt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(at(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Yt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):at(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!at(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||at(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{let s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){let r=hr(s),i=Yt(r);Nu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
141
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(r&&t.sep&&!t.value){let s=[];for(let a=0;a<t.sep.length;++a){let l=t.sep[a];switch(l.type){case"newline":s.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(o=t.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Kt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Qw(t.key)&&!Kt(t.sep,"newline")){let s=tr(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:a,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Kt(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let s=tr(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Kt(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);r||t.value?(e.items.push({start:o,key:s,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(s):(Object.assign(t,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(e);if(s){if(s.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Kt(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:o});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Kt(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=Cs(i),o=tr(r);Xw(e);let s=e.end.splice(1,e.end.length);s.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:o,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
142
142
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
143
- `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=hr(e),s=Yt(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=hr(e),s=Yt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ou.Parser=fa});var $u=T(qs=>{"use strict";var Mu=ea(),KS=Ms(),js=Ps(),HS=Qi(),WS=U(),GS=ha(),Du=pa();function Lu(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new GS.LineCounter||null,prettyErrors:e}}function VS(n,e={}){let{lineCounter:t,prettyErrors:s}=Lu(e),r=new Du.Parser(t?.addNewLine),i=new Mu.Composer(e),o=Array.from(i.compose(r.parse(n)));if(s&&t)for(let a of o)a.errors.forEach(js.prettifyError(n,t)),a.warnings.forEach(js.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Pu(n,e={}){let{lineCounter:t,prettyErrors:s}=Lu(e),r=new Du.Parser(t?.addNewLine),i=new Mu.Composer(e),o=null;for(let a of i.compose(r.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new js.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(js.prettifyError(n,t)),o.warnings.forEach(js.prettifyError(n,t))),o}function YS(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=Pu(n,t);if(!r)return null;if(r.warnings.forEach(i=>HS.warn(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},t))}function JS(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return WS.isDocument(n)&&!s?n.toString(t):new KS.Document(n,s,t).toString(t)}qs.parse=YS;qs.parseAllDocuments=VS;qs.parseDocument=Pu;qs.stringify=JS});var ga=T(F=>{"use strict";var zS=ea(),QS=Ms(),XS=Lo(),ma=Ps(),ZS=ms(),ct=U(),e0=nt(),t0=Z(),s0=it(),n0=ot(),r0=dr(),i0=da(),o0=ha(),a0=pa(),fr=$u(),Ru=us();F.Composer=zS.Composer;F.Document=QS.Document;F.Schema=XS.Schema;F.YAMLError=ma.YAMLError;F.YAMLParseError=ma.YAMLParseError;F.YAMLWarning=ma.YAMLWarning;F.Alias=ZS.Alias;F.isAlias=ct.isAlias;F.isCollection=ct.isCollection;F.isDocument=ct.isDocument;F.isMap=ct.isMap;F.isNode=ct.isNode;F.isPair=ct.isPair;F.isScalar=ct.isScalar;F.isSeq=ct.isSeq;F.Pair=e0.Pair;F.Scalar=t0.Scalar;F.YAMLMap=s0.YAMLMap;F.YAMLSeq=n0.YAMLSeq;F.CST=r0;F.Lexer=i0.Lexer;F.LineCounter=o0.LineCounter;F.Parser=a0.Parser;F.parse=fr.parse;F.parseAllDocuments=fr.parseAllDocuments;F.parseDocument=fr.parseDocument;F.stringify=fr.stringify;F.visit=Ru.visit;F.visitAsync=Ru.visitAsync});function Bu(n={},e){let t={};for(let s of Object.keys(Jt)){let r=n[s]??Jt[s];t[s]=r&&(e?.[s]??!0)}return t}var Jt,ya=j(()=>{"use strict";Jt={externalComms:!0,codeTask:!1,codeAccess:!1}});import{execFileSync as c0}from"node:child_process";function zt(n,e){if(process.platform!=="darwin")return"";try{return c0("security",["find-generic-password","-s",`hive/${n}/${e}`,"-w"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}var pr=j(()=>{"use strict"});import{readFileSync as l0,existsSync as Fu,readdirSync as d0,statSync as u0}from"node:fs";import{resolve as wa}from"node:path";import{randomUUID as Sa}from"node:crypto";function Uu(n){let e=process.env[n]||Hu(n);if(!e)throw new Error(`Missing required env var: ${n}`);return e}function b(n,e){return process.env[n]||Hu(n)||e}function f0(n){if(n?.length)return n.map(t=>wa(t.replace(/^~/,process.env.HOME??"/tmp")));let e=wa(cs,"plugins/claude-code");return Fu(e)?d0(e).map(t=>wa(e,t)).filter(t=>u0(t).isDirectory()):[]}var qu,Ku,h0,ju,C,gI,Fs,Hu,lt,_t,g,Ne=j(()=>{"use strict";qu=Ae(zc(),1),Ku=Ae(ga(),1);ya();pr();ls();h0=Ec(V);qu.default.config({path:h0});ju=Cc(V),C={};Fu(ju)&&(C=(0,Ku.parse)(l0(ju,"utf-8"))??{});gI=process.env.HOME??"/tmp",Fs=C.instance?.id??"hive",Hu=n=>zt(Fs,n),lt=C.instance?.portBase??3100,_t=C.instance?.ports??{},g={instance:{id:Fs,portBase:lt},business:{name:C.business?.name??b("BUSINESS_NAME",""),description:C.business?.description??"",location:C.business?.location??"",ownerName:C.business?.owner?.name??"",ownerRole:C.business?.owner?.role??""},slack:{appToken:Uu("SLACK_APP_TOKEN"),botToken:Uu("SLACK_BOT_TOKEN"),mcpToken:b("SLACK_MCP_TOKEN",""),auditChannel:b("SLACK_AUDIT_CHANNEL",C.slack?.auditChannel??""),localMcpServer:!!(C.slack?.localMcpServer??!1)},anthropic:{apiKey:b("ANTHROPIC_API_KEY","")},linear:{apiKey:b("LINEAR_API_KEY",""),teamId:b("LINEAR_TEAM_ID","")},clickup:{apiToken:b("CLICKUP_API_TOKEN","")},github:{repo:b("GITHUB_REPO",""),token:b("GH_TOKEN","")},brave:{apiKey:b("BRAVE_API_KEY","")},taskLedger:{apiUrl:b("TASK_LEDGER_API_URL","http://localhost:3002"),agentKeys:Object.fromEntries(Object.entries(process.env).filter(([n])=>n.startsWith("TASK_LEDGER_KEY_")).map(([n,e])=>[n.replace("TASK_LEDGER_KEY_","").toLowerCase().replace(/_/g,"-"),e])),apiKey:b("TASK_LEDGER_API_KEY","")},mongo:{uri:b("MONGODB_URI","mongodb://localhost:27017"),dbName:b("MONGODB_DB",`hive_${Fs}`)},defaultAgent:b("DEFAULT_AGENT","chief-of-staff"),google:{account:b("GOOGLE_ACCOUNT",C.google?.account??""),client:b("GOG_CLIENT",C.google?.client??""),accounts:C.google?.accounts??{},sharedFolder:b("DRIVE_SHARED_FOLDER",C.google?.sharedFolder??C.googleWorkspace?.sharedFolder??"")},googleWorkspace:{account:b("GWS_ACCOUNT",C.googleWorkspace?.account??""),gwsPath:b("GWS_PATH",""),sharedFolder:b("GWS_SHARED_FOLDER",C.googleWorkspace?.sharedFolder??"")},quo:{apiKey:b("QUO_API_KEY",""),phoneNumberId:b("QUO_PHONE_NUMBER_ID",""),lines:C.quo?.lines??{}},sms:{lines:C.sms?.lines??[]},imessage:{enabled:C.imessage?.enabled??!1,slackChannel:C.imessage?.slackChannel??"imessage",hotWindowMs:C.imessage?.hotWindowMs??3e5,coldIntervalMs:C.imessage?.coldIntervalMs??3e5,hotIntervalMs:C.imessage?.hotIntervalMs??1e4},resend:{apiKey:b("RESEND_API_KEY",""),fromAddress:b("RESEND_FROM_ADDRESS",""),defaultCc:b("RESEND_DEFAULT_CC",""),defaultBcc:b("RESEND_DEFAULT_BCC",""),emailDomain:b("RESEND_EMAIL_DOMAIN",C.resend?.emailDomain??""),businessName:b("RESEND_BUSINESS_NAME",C.resend?.businessName??"")},plugins:C.plugins??[],skillRegistries:C.skillRegistries??[{name:"keepur-default",url:"https://github.com/keepur/hive-skills",default:!0}],gemini:{apiKey:b("GEMINI_API_KEY",""),visionModel:b("GEMINI_VISION_MODEL","gemini-2.5-flash")},permits:{mongoUri:b("PERMITS_MONGO_URI","mongodb://localhost:27017/permits")},recall:{apiKey:b("RECALL_API_KEY",""),region:b("RECALL_API_REGION","us-west-2"),monitorPort:parseInt(b("MEETING_MONITOR_PORT",String(_t.recall??lt+1)),10),monitorPublicUrl:b("MEETING_MONITOR_PUBLIC_URL",""),webhookSecret:b("RECALL_WEBHOOK_SECRET","")},scheduler:{heartbeatIntervalMs:parseInt(b("HEARTBEAT_INTERVAL_MS","120000"),10)},background:{port:parseInt(b("BG_TASK_PORT",String(_t.background??lt)),10),authToken:b("BG_TASK_AUTH_TOKEN","")||Sa()},slackInternal:{port:parseInt(b("SLACK_INTERNAL_PORT",String(_t.slackInternal??lt+6)),10),authToken:b("SLACK_INTERNAL_TOKEN","")||Sa()},codeTask:{port:parseInt(b("CODE_TASK_PORT",String(_t.codeTask??lt+2)),10),authToken:b("CODE_TASK_AUTH_TOKEN","")||Sa(),pluginDirs:f0(C.codeTask?.pluginDirs),defaultModel:b("CODE_TASK_MODEL","claude-sonnet-4-6"),defaultMaxTurns:parseInt(b("CODE_TASK_MAX_TURNS","100"),10),defaultMaxBudget:parseFloat(b("CODE_TASK_MAX_BUDGET","5.00")),maxConcurrent:parseInt(b("CODE_TASK_MAX_CONCURRENT","2"),10),maxLifetimeMs:parseInt(b("CODE_TASK_MAX_LIFETIME_MS",String(480*60*1e3)),10),staleGraceMs:parseInt(b("CODE_TASK_STALE_GRACE_MS",String(1800*1e3)),10)},ws:{enabled:b("WS_ENABLED","false")==="true",port:parseInt(b("WS_PORT",String(_t.ws??lt+3)),10)},beekeeper:{port:parseInt(b("BEEKEEPER_PORT",String(C.beekeeper?.port??8420)),10)},workflow:{enabled:b("WORKFLOW_ENABLED","false")==="true"},adminApi:{port:parseInt(b("ADMIN_API_PORT",String(_t.adminApi??lt+4)),10),token:b("ADMIN_API_TOKEN","")},voice:{enabled:!!C.voice?.provider,provider:C.voice?.provider??"",publicUrl:C.voice?.publicUrl??"",phoneNumberId:C.voice?.phoneNumberId??"",assistants:C.voice?.assistants??{},apiKey:b("VAPI_API_KEY",""),serverSecret:b("VAPI_SERVER_SECRET",""),port:parseInt(b("VOICE_PORT",String(_t.voice??lt+5)),10)},autonomy:{externalComms:C.autonomy?.externalComms??Jt.externalComms,codeTask:C.autonomy?.codeTask??Jt.codeTask,codeAccess:C.autonomy?.codeAccess??Jt.codeAccess},modelRouter:{enabled:b("MODEL_ROUTER_ENABLED","true")==="true",model:b("MODEL_ROUTER_MODEL","claude-haiku-4-5-20251001"),timeoutMs:parseInt(b("MODEL_ROUTER_TIMEOUT_MS","8000"),10)},sweeper:{intervalMs:parseInt(b("SWEEPER_INTERVAL_MS","300000"),10),threadTtlMs:parseInt(b("SWEEPER_THREAD_TTL_MS","86400000"),10),taskFileTtlMs:parseInt(b("SWEEPER_TASK_FILE_TTL_MS","604800000"),10),meetingSessionTtlMs:parseInt(b("SWEEPER_MEETING_TTL_MS","3600000"),10),cacheTtlMs:parseInt(b("SWEEPER_CACHE_TTL_MS","3600000"),10),retryMaxAttempts:parseInt(b("SWEEPER_RETRY_MAX_ATTEMPTS","3"),10),retryBaseDelayMs:parseInt(b("SWEEPER_RETRY_BASE_DELAY_MS","30000"),10)},retention:(()=>{let n=C.retention?.paths??{data:7,"agents/*/scratch":7,"agents/*/feeds":7,"agents/*/playwright":3,"agents/*/reports":0,logs:30},e={};for(let[r,i]of Object.entries(n)){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new Error(`Invalid retention.paths.${r}: must be a non-negative integer (got ${i})`);e[r]={days:i}}let t=Number(C.retention?.defaults?.days??7);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid retention.defaults.days: ${t}`);let s=parseInt(b("RETENTION_INTERVAL_MS",String(C.retention?.intervalMs??168*36e5)),10);if(!Number.isFinite(s)||s<=0)throw new Error(`Invalid retention.intervalMs: must be a positive integer (got ${s})`);return{enabled:!!(C.retention?.enabled??!1),intervalMs:s,defaultDays:t,paths:e}})(),memory:{hotBudgetTokens:parseInt(b("MEMORY_HOT_BUDGET_TOKENS",String(C.memory?.hotBudgetTokens??3e3)),10),sweepIntervalHours:parseFloat(b("MEMORY_SWEEP_INTERVAL_HOURS",String(C.memory?.sweepIntervalHours??6))),hotThreshold:parseFloat(b("MEMORY_HOT_THRESHOLD",String(C.memory?.hotThreshold??.6))),warmThreshold:parseFloat(b("MEMORY_WARM_THRESHOLD",String(C.memory?.warmThreshold??.3))),recencyHalfLifeDays:parseFloat(b("MEMORY_RECENCY_HALF_LIFE_DAYS",String(C.memory?.recencyHalfLifeDays??7))),coldSummaryMinRecords:parseInt(b("MEMORY_COLD_SUMMARY_MIN",String(C.memory?.coldSummaryMinRecords??5)),10),coldRetentionDays:parseInt(b("MEMORY_COLD_RETENTION_DAYS",String(C.memory?.coldRetentionDays??90)),10),purgeRetentionDays:parseInt(b("MEMORY_PURGE_RETENTION_DAYS",String(C.memory?.purgeRetentionDays??7)),10),reflectionMinTurns:parseInt(b("MEMORY_REFLECTION_MIN_TURNS",String(C.memory?.reflectionMinTurns??3)),10)},codeIndex:{enabled:C.codeIndex?.enabled===!0||process.env.CODE_INDEX_ENABLED==="true",scoreThreshold:parseFloat(b("CODE_INDEX_SCORE_THRESHOLD",String(C.codeIndex?.scoreThreshold??.65))),prefetchLimit:parseInt(b("CODE_INDEX_PREFETCH_LIMIT",String(C.codeIndex?.prefetchLimit??8)),10),sessionKnowledge:{enabled:(C.codeIndex?.sessionKnowledge?.enabled??!0)&&process.env.CODE_INDEX_SESSION_KNOWLEDGE!=="false"},repos:C.codeIndex?.repos??{}},events:{retentionDays:parseInt(b("EVENT_RETENTION_DAYS",String(C.events?.retentionDays??30)),10)},activity:{enabled:(C.activity?.enabled??!0)&&process.env.ACTIVITY_LOG_ENABLED!=="false",bufferSize:parseInt(b("ACTIVITY_BUFFER_SIZE",String(C.activity?.bufferSize??200)),10),flushIntervalMs:parseInt(b("ACTIVITY_FLUSH_INTERVAL_MS",String(C.activity?.flushIntervalMs??3e4)),10),retentionDays:parseInt(b("ACTIVITY_RETENTION_DAYS",String(C.activity?.retentionDays??90)),10)},autoDream:{enabled:C.autoDream?.enabled??!0,idleThresholdMinutes:parseInt(b("AUTODREAM_IDLE_THRESHOLD_MINUTES",String(C.autoDream?.idleThresholdMinutes??30)),10),cooldownMinutes:parseInt(b("AUTODREAM_COOLDOWN_MINUTES",String(C.autoDream?.cooldownMinutes??60)),10),similarityThreshold:parseFloat(b("AUTODREAM_SIMILARITY_THRESHOLD",String(C.autoDream?.similarityThreshold??.85))),patternMinCount:parseInt(b("AUTODREAM_PATTERN_MIN_COUNT",String(C.autoDream?.patternMinCount??3)),10),maxClustersPerRun:parseInt(b("AUTODREAM_MAX_CLUSTERS",String(C.autoDream?.maxClustersPerRun??20)),10),maxContradictionPairsPerRun:parseInt(b("AUTODREAM_MAX_CONTRADICTIONS",String(C.autoDream?.maxContradictionPairsPerRun??30)),10),maxPromotionsPerRun:parseInt(b("AUTODREAM_MAX_PROMOTIONS",String(C.autoDream?.maxPromotionsPerRun??10)),10),maxBudgetUsd:parseFloat(b("AUTODREAM_MAX_BUDGET_USD",String(C.autoDream?.maxBudgetUsd??.1)))},browser:{cdpEndpoint:b("BROWSER_CDP_ENDPOINT","")},tasksDir:{code:b("CODE_TASKS_DIR",`/tmp/${Fs}-code-tasks`),background:b("BG_TASKS_DIR",`/tmp/${Fs}-bg-tasks`)}}});function Vu(n){ka.has(n.id)&&Gu.warn("Archetype already registered \u2014 overwriting",{id:n.id}),ka.set(n.id,n),Gu.info("Registered archetype",{id:n.id})}function mr(n){return ka.get(n)}var Gu,ka,gr=j(()=>{"use strict";M();Gu=k("archetypes"),ka=new Map});import{readFileSync as b0}from"node:fs";import{resolve as dh}from"node:path";function v0(){let n=[dh(import.meta.dirname,"..","..","package.json"),dh(import.meta.dirname,"..","package.json")];for(let e of n)try{let t=JSON.parse(b0(e,"utf-8"));if(t?.name==="@keepur/hive"&&typeof t.hiveApi=="string")return t.hiveApi}catch{continue}return null}var _0,uh,_a,hh=j(()=>{"use strict";M();_0=k("api-version");uh=v0();uh||_0.warn("Could not read hiveApi from package.json; falling back to 1.0.0");_a=uh??"1.0.0"});var gh={};Ue(gh,{isHiveApiCompatible:()=>ph,loadPlugins:()=>va,normalizeManifest:()=>mh,registerPluginCommands:()=>I0,rescanPluginBrokenServers:()=>Ta,resolvePluginServerPath:()=>Ks});import{readFileSync as T0,existsSync as Sr}from"node:fs";import{resolve as dt,join as wr}from"node:path";function Ks(n,e,t){let s=e.replace(/\.ts$/,".js"),r=e.replace(/\.ts$/,".min.js"),i=[];t.distDir&&i.push(dt(t.distDir,`plugins/${n}/${s}`)),i.push(dt(t.hiveHome,"plugins","node_modules",n,"dist",r),dt(t.hiveHome,"plugins","node_modules",n,"dist",s),dt(t.hiveHome,"plugins",n,"dist",r),dt(t.hiveHome,"plugins",n,"dist",s));for(let o of i)if(Sr(o))return{path:o};return{reason:"no compiled entry found (expected one of .min.js or .js under dist/)",pathsChecked:i}}function va(n,e,t){let s=[];for(let r of n){let i=dt(e,"plugins","node_modules",r),o=dt(e,"plugins",r),a=wr(i,"plugin.yaml"),l=wr(o,"plugin.yaml"),c;if(Sr(a))c=i;else if(Sr(l))c=o;else{ut.warn("Plugin manifest not found, skipping",{plugin:r,tried:[a,l]});continue}let d=wr(c,"plugin.yaml"),u=(0,fh.parse)(T0(d,"utf-8")),h=mh(u);if(h.hiveApi&&!ph(h.hiveApi,_a)){ut.warn("Plugin declares incompatible hiveApi range, skipping",{plugin:r,requires:h.hiveApi,running:_a});continue}let p={};for(let[f,y]of Object.entries(h.mcpServers)){let w=Ks(r,y.entry,{hiveHome:e,distDir:t?.distDir});"reason"in w&&(p[f]=w,ut.error("Plugin MCP server entry not resolvable",{plugin:r,server:f,entry:y.entry,reason:w.reason,pathsChecked:w.pathsChecked}))}for(let f of h.agentSeeds){let y=wr(c,"agent-seeds",f);Sr(y)||ut.warn("Plugin agent seed not found",{plugin:r,seed:f,path:y})}s.push({name:r,dir:c,manifest:h,brokenServers:p});let m=Object.keys(p);ut.info("Plugin loaded",{plugin:r,mcpServers:Object.keys(h.mcpServers),seeds:h.agentSeeds,...m.length?{brokenServers:m}:{}})}return s}function Ta(n,e,t){let s={},r={};for(let i of n){let o=Object.keys(i.brokenServers);if(o.length!==0)for(let a of o){let l=i.manifest.mcpServers[a];if(!l){delete i.brokenServers[a];continue}"path"in Ks(i.name,l.entry,{hiveHome:e,distDir:t?.distDir})?(delete i.brokenServers[a],(s[i.name]??=[]).push(a)):(r[i.name]??=[]).push(a)}}return{rescued:s,stillBroken:r}}function ph(n,e){let t=n.trim();if(t===e)return!0;if(t.startsWith("^")){let s=t.slice(1).split(".").map(Number),r=e.split(".").map(Number);return!(s.length<1||r.length<1||s[0]!==r[0]||(r[1]??0)<(s[1]??0)||(r[1]??0)===(s[1]??0)&&(r[2]??0)<(s[2]??0))}return ut.warn("Unrecognized hiveApi range syntax, accepting",{range:n}),!0}function mh(n){return{name:n.name??"",description:n.description??"",hiveApi:n.hiveApi??n["hive-api"]??void 0,mcpServers:Object.fromEntries(Object.entries(n["mcp-servers"]??{}).map(([e,t])=>[e,{entry:t.entry,description:t.description,usage:t.usage,notFor:t["not-for"],env:t.env??[],secretEnv:t["secret-env"]??[],envMap:t["env-map"]??{},agentEnv:t["agent-env"]??{}}])),agentSeeds:n["agent-seeds"]??n["agents-templates"]??[],registerCommands:n["register-commands"]??void 0}}async function I0(n,e){for(let t of n)if(t.manifest.registerCommands)try{let r=await import(dt(t.dir,"dist",t.manifest.registerCommands));typeof r.registerCommands=="function"&&(r.registerCommands(e),ut.info("Plugin commands registered",{plugin:t.name}))}catch(s){ut.warn("Failed to load plugin commands",{plugin:t.name,error:String(s)})}}var fh,ut,kr=j(()=>{"use strict";fh=Ae(ga(),1);M();hh();ut=k("plugin-loader")});import{readFileSync as A0,writeFileSync as C0}from"node:fs";function E0(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)throw new Error("No YAML frontmatter found");let t=e[1],s=e[2],r={name:"",description:"",agents:[]},i=t.split(`
144
- `),o=0;for(;o<i.length;){let a=i[o];if(a.trim()===""){o++;continue}let l=a.match(/^(\w[\w-]*):\s*(.*)/);if(!l){o++;continue}let c=l[1],d=l[2].trim();if(c==="name")r.name=vt(d);else if(c==="description")r.description=vt(d);else if(c==="workflow")r.workflow=vt(d);else if(c==="agents"){let u=d.match(/^\[([^\]]*)\]$/);if(u)r.agents=u[1].split(",").map(h=>vt(h.trim())).filter(h=>h.length>0);else if(d==="")for(r.agents=[];o+1<i.length&&i[o+1].match(/^\s+-\s+/);){o++;let h=i[o].replace(/^\s+-\s+/,"").trim();r.agents.push(vt(h))}else r.agents=[vt(d)]}else if(c==="origin")for(r.origin=yh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;else if(c==="author")for(r.author=yh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;o++}return{frontmatter:r,body:s}}function yh(n,e){let t={},s=e+1;for(;s<n.length&&n[s].match(/^\s+\S/);){let r=n[s].match(/^\s+([\w][\w-]*):\s*(.*)/);if(r){let i=r[2].trim();i==="true"?t[r[1]]=!0:i==="false"?t[r[1]]=!1:t[r[1]]=vt(i)}s++}return t}function vt(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):n}function N0(n,e){let t=[];t.push(`name: ${br(n.name)}`),t.push(`description: ${br(n.description)}`);let s=n.agents.join(", ");return t.push(`agents: [${s}]`),n.workflow&&t.push(`workflow: ${br(n.workflow)}`),n.origin&&(t.push("origin:"),wh(t,n.origin)),n.author&&(t.push("author:"),wh(t,n.author)),`---
143
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=Cs(e),i=tr(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=Cs(e),i=tr(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};eb.Parser=Sd});var ob=N(xi=>{"use strict";var tb=ud(),aN=gi(),$i=_i(),cN=cu(),lN=Y(),uN=kd(),nb=$d();function rb(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new uN.LineCounter||null,prettyErrors:e}}function dN(n,e={}){let{lineCounter:t,prettyErrors:i}=rb(e),r=new nb.Parser(t?.addNewLine),o=new tb.Composer(e),s=Array.from(o.compose(r.parse(n)));if(i&&t)for(let a of s)a.errors.forEach($i.prettifyError(n,t)),a.warnings.forEach($i.prettifyError(n,t));return s.length>0?s:Object.assign([],{empty:!0},o.streamInfo())}function ib(n,e={}){let{lineCounter:t,prettyErrors:i}=rb(e),r=new nb.Parser(t?.addNewLine),o=new tb.Composer(e),s=null;for(let a of o.compose(r.parse(n),!0,n.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new $i.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(s.errors.forEach($i.prettifyError(n,t)),s.warnings.forEach($i.prettifyError(n,t))),s}function fN(n,e,t){let i;typeof e=="function"?i=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=ib(n,t);if(!r)return null;if(r.warnings.forEach(o=>cN.warn(r.options.logLevel,o)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},t))}function pN(n,e,t){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return lN.isDocument(n)&&!i?n.toString(t):new aN.Document(n,i,t).toString(t)}xi.parse=fN;xi.parseAllDocuments=dN;xi.parseDocument=ib;xi.stringify=pN});var Id=N(Q=>{"use strict";var mN=ud(),hN=gi(),gN=Zu(),xd=_i(),yN=Qr(),Vt=Y(),vN=Bt(),_N=he(),wN=qt(),bN=Zt(),kN=As(),SN=wd(),$N=kd(),xN=$d(),Ns=ob(),sb=Jr();Q.Composer=mN.Composer;Q.Document=hN.Document;Q.Schema=gN.Schema;Q.YAMLError=xd.YAMLError;Q.YAMLParseError=xd.YAMLParseError;Q.YAMLWarning=xd.YAMLWarning;Q.Alias=yN.Alias;Q.isAlias=Vt.isAlias;Q.isCollection=Vt.isCollection;Q.isDocument=Vt.isDocument;Q.isMap=Vt.isMap;Q.isNode=Vt.isNode;Q.isPair=Vt.isPair;Q.isScalar=Vt.isScalar;Q.isSeq=Vt.isSeq;Q.Pair=vN.Pair;Q.Scalar=_N.Scalar;Q.YAMLMap=wN.YAMLMap;Q.YAMLSeq=bN.YAMLSeq;Q.CST=kN;Q.Lexer=SN.Lexer;Q.LineCounter=$N.LineCounter;Q.Parser=xN.Parser;Q.parse=Ns.parse;Q.parseAllDocuments=Ns.parseAllDocuments;Q.parseDocument=Ns.parseDocument;Q.stringify=Ns.stringify;Q.visit=sb.visit;Q.visitAsync=sb.visitAsync});function ab(n={},e){let t={};for(let i of Object.keys(nr)){let r=n[i]??nr[i];t[i]=r&&(e?.[i]??!0)}return t}var nr,Td=S(()=>{"use strict";nr={externalComms:!0,codeTask:!1,codeAccess:!1}});import{execFileSync as IN}from"node:child_process";function rr(n,e){if(process.platform!=="darwin")return"";try{return IN("security",["find-generic-password","-s",`hive/${n}/${e}`,"-w"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}var Ds=S(()=>{"use strict"});import{readFileSync as TN,existsSync as db,readdirSync as EN,statSync as AN}from"node:fs";import{resolve as Ed}from"node:path";import{randomUUID as Ad}from"node:crypto";function cb(n){let e=process.env[n]||pb(n);if(!e)throw new Error(`Missing required env var: ${n}`);return e}function I(n,e){return process.env[n]||pb(n)||e}function CN(n){if(n?.length)return n.map(t=>Ed(t.replace(/^~/,process.env.HOME??"/tmp")));let e=Ed(Vr,"plugins/claude-code");return db(e)?EN(e).map(t=>Ed(e,t)).filter(t=>AN(t).isDirectory()):[]}var ub,fb,ON,lb,M,kR,Ii,pb,Wt,vn,g,ot=S(()=>{"use strict";ub=nt(_v(),1),fb=nt(Id(),1);Td();Ds();Wr();ON=Yy(se);ub.default.config({path:ON});lb=Hy(se),M={};db(lb)&&(M=(0,fb.parse)(TN(lb,"utf-8"))??{});kR=process.env.HOME??"/tmp",Ii=M.instance?.id??"hive",pb=n=>rr(Ii,n),Wt=M.instance?.portBase??3100,vn=M.instance?.ports??{},g={instance:{id:Ii,portBase:Wt},business:{name:M.business?.name??I("BUSINESS_NAME",""),description:M.business?.description??"",location:M.business?.location??"",ownerName:M.business?.owner?.name??"",ownerRole:M.business?.owner?.role??""},slack:{appToken:cb("SLACK_APP_TOKEN"),botToken:cb("SLACK_BOT_TOKEN"),mcpToken:I("SLACK_MCP_TOKEN",""),auditChannel:I("SLACK_AUDIT_CHANNEL",M.slack?.auditChannel??""),localMcpServer:!!(M.slack?.localMcpServer??!1)},anthropic:{apiKey:I("ANTHROPIC_API_KEY","")},linear:{apiKey:I("LINEAR_API_KEY",""),teamId:I("LINEAR_TEAM_ID","")},clickup:{apiToken:I("CLICKUP_API_TOKEN","")},github:{repo:I("GITHUB_REPO",""),token:I("GH_TOKEN","")},brave:{apiKey:I("BRAVE_API_KEY","")},taskLedger:{apiUrl:I("TASK_LEDGER_API_URL","http://localhost:3002"),agentKeys:Object.fromEntries(Object.entries(process.env).filter(([n])=>n.startsWith("TASK_LEDGER_KEY_")).map(([n,e])=>[n.replace("TASK_LEDGER_KEY_","").toLowerCase().replace(/_/g,"-"),e])),apiKey:I("TASK_LEDGER_API_KEY","")},mongo:{uri:I("MONGODB_URI","mongodb://localhost:27017"),dbName:I("MONGODB_DB",`hive_${Ii}`)},defaultAgent:I("DEFAULT_AGENT","chief-of-staff"),google:{account:I("GOOGLE_ACCOUNT",M.google?.account??""),client:I("GOG_CLIENT",M.google?.client??""),accounts:M.google?.accounts??{},sharedFolder:I("DRIVE_SHARED_FOLDER",M.google?.sharedFolder??M.googleWorkspace?.sharedFolder??"")},googleWorkspace:{account:I("GWS_ACCOUNT",M.googleWorkspace?.account??""),gwsPath:I("GWS_PATH",""),sharedFolder:I("GWS_SHARED_FOLDER",M.googleWorkspace?.sharedFolder??"")},quo:{apiKey:I("QUO_API_KEY",""),phoneNumberId:I("QUO_PHONE_NUMBER_ID",""),lines:M.quo?.lines??{}},sms:{lines:M.sms?.lines??[]},imessage:{enabled:M.imessage?.enabled??!1,slackChannel:M.imessage?.slackChannel??"imessage",hotWindowMs:M.imessage?.hotWindowMs??3e5,coldIntervalMs:M.imessage?.coldIntervalMs??3e5,hotIntervalMs:M.imessage?.hotIntervalMs??1e4},resend:{apiKey:I("RESEND_API_KEY",""),fromAddress:I("RESEND_FROM_ADDRESS",""),defaultCc:I("RESEND_DEFAULT_CC",""),defaultBcc:I("RESEND_DEFAULT_BCC",""),emailDomain:I("RESEND_EMAIL_DOMAIN",M.resend?.emailDomain??""),businessName:I("RESEND_BUSINESS_NAME",M.resend?.businessName??"")},plugins:M.plugins??[],skillRegistries:M.skillRegistries??[{name:"keepur-default",url:"https://github.com/keepur/hive-skills",default:!0}],gemini:{apiKey:I("GEMINI_API_KEY",""),visionModel:I("GEMINI_VISION_MODEL","gemini-2.5-flash")},permits:{mongoUri:I("PERMITS_MONGO_URI","mongodb://localhost:27017/permits")},recall:{apiKey:I("RECALL_API_KEY",""),region:I("RECALL_API_REGION","us-west-2"),monitorPort:parseInt(I("MEETING_MONITOR_PORT",String(vn.recall??Wt+1)),10),monitorPublicUrl:I("MEETING_MONITOR_PUBLIC_URL",""),webhookSecret:I("RECALL_WEBHOOK_SECRET","")},scheduler:{heartbeatIntervalMs:parseInt(I("HEARTBEAT_INTERVAL_MS","120000"),10)},background:{port:parseInt(I("BG_TASK_PORT",String(vn.background??Wt)),10),authToken:I("BG_TASK_AUTH_TOKEN","")||Ad()},slackInternal:{port:parseInt(I("SLACK_INTERNAL_PORT",String(vn.slackInternal??Wt+6)),10),authToken:I("SLACK_INTERNAL_TOKEN","")||Ad()},codeTask:{port:parseInt(I("CODE_TASK_PORT",String(vn.codeTask??Wt+2)),10),authToken:I("CODE_TASK_AUTH_TOKEN","")||Ad(),pluginDirs:CN(M.codeTask?.pluginDirs),defaultModel:I("CODE_TASK_MODEL","claude-sonnet-4-6"),defaultMaxTurns:parseInt(I("CODE_TASK_MAX_TURNS","100"),10),defaultMaxBudget:parseFloat(I("CODE_TASK_MAX_BUDGET","5.00")),maxConcurrent:parseInt(I("CODE_TASK_MAX_CONCURRENT","2"),10),maxLifetimeMs:parseInt(I("CODE_TASK_MAX_LIFETIME_MS",String(480*60*1e3)),10),staleGraceMs:parseInt(I("CODE_TASK_STALE_GRACE_MS",String(1800*1e3)),10)},ws:{enabled:I("WS_ENABLED","false")==="true",port:parseInt(I("WS_PORT",String(vn.ws??Wt+3)),10)},beekeeper:{port:parseInt(I("BEEKEEPER_PORT",String(M.beekeeper?.port??8420)),10)},workflow:{enabled:I("WORKFLOW_ENABLED","false")==="true"},adminApi:{port:parseInt(I("ADMIN_API_PORT",String(vn.adminApi??Wt+4)),10),token:I("ADMIN_API_TOKEN","")},voice:{enabled:!!M.voice?.provider,provider:M.voice?.provider??"",publicUrl:M.voice?.publicUrl??"",phoneNumberId:M.voice?.phoneNumberId??"",assistants:M.voice?.assistants??{},apiKey:I("VAPI_API_KEY",""),serverSecret:I("VAPI_SERVER_SECRET",""),port:parseInt(I("VOICE_PORT",String(vn.voice??Wt+5)),10)},autonomy:{externalComms:M.autonomy?.externalComms??nr.externalComms,codeTask:M.autonomy?.codeTask??nr.codeTask,codeAccess:M.autonomy?.codeAccess??nr.codeAccess},modelRouter:{enabled:I("MODEL_ROUTER_ENABLED","true")==="true",model:I("MODEL_ROUTER_MODEL","claude-haiku-4-5-20251001"),timeoutMs:parseInt(I("MODEL_ROUTER_TIMEOUT_MS","8000"),10)},sweeper:{intervalMs:parseInt(I("SWEEPER_INTERVAL_MS","300000"),10),threadTtlMs:parseInt(I("SWEEPER_THREAD_TTL_MS","86400000"),10),taskFileTtlMs:parseInt(I("SWEEPER_TASK_FILE_TTL_MS","604800000"),10),meetingSessionTtlMs:parseInt(I("SWEEPER_MEETING_TTL_MS","3600000"),10),cacheTtlMs:parseInt(I("SWEEPER_CACHE_TTL_MS","3600000"),10),retryMaxAttempts:parseInt(I("SWEEPER_RETRY_MAX_ATTEMPTS","3"),10),retryBaseDelayMs:parseInt(I("SWEEPER_RETRY_BASE_DELAY_MS","30000"),10)},retention:(()=>{let n=M.retention?.paths??{data:7,"agents/*/scratch":7,"agents/*/feeds":7,"agents/*/playwright":3,"agents/*/reports":0,logs:30},e={};for(let[r,o]of Object.entries(n)){if(typeof o!="number"||!Number.isFinite(o)||o<0)throw new Error(`Invalid retention.paths.${r}: must be a non-negative integer (got ${o})`);e[r]={days:o}}let t=Number(M.retention?.defaults?.days??7);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid retention.defaults.days: ${t}`);let i=parseInt(I("RETENTION_INTERVAL_MS",String(M.retention?.intervalMs??168*36e5)),10);if(!Number.isFinite(i)||i<=0)throw new Error(`Invalid retention.intervalMs: must be a positive integer (got ${i})`);return{enabled:!!(M.retention?.enabled??!1),intervalMs:i,defaultDays:t,paths:e}})(),memory:{hotBudgetTokens:parseInt(I("MEMORY_HOT_BUDGET_TOKENS",String(M.memory?.hotBudgetTokens??3e3)),10),sweepIntervalHours:parseFloat(I("MEMORY_SWEEP_INTERVAL_HOURS",String(M.memory?.sweepIntervalHours??6))),hotThreshold:parseFloat(I("MEMORY_HOT_THRESHOLD",String(M.memory?.hotThreshold??.6))),warmThreshold:parseFloat(I("MEMORY_WARM_THRESHOLD",String(M.memory?.warmThreshold??.3))),recencyHalfLifeDays:parseFloat(I("MEMORY_RECENCY_HALF_LIFE_DAYS",String(M.memory?.recencyHalfLifeDays??7))),coldSummaryMinRecords:parseInt(I("MEMORY_COLD_SUMMARY_MIN",String(M.memory?.coldSummaryMinRecords??5)),10),coldRetentionDays:parseInt(I("MEMORY_COLD_RETENTION_DAYS",String(M.memory?.coldRetentionDays??90)),10),purgeRetentionDays:parseInt(I("MEMORY_PURGE_RETENTION_DAYS",String(M.memory?.purgeRetentionDays??7)),10),reflectionMinTurns:parseInt(I("MEMORY_REFLECTION_MIN_TURNS",String(M.memory?.reflectionMinTurns??3)),10)},codeIndex:{enabled:M.codeIndex?.enabled===!0||process.env.CODE_INDEX_ENABLED==="true",scoreThreshold:parseFloat(I("CODE_INDEX_SCORE_THRESHOLD",String(M.codeIndex?.scoreThreshold??.65))),prefetchLimit:parseInt(I("CODE_INDEX_PREFETCH_LIMIT",String(M.codeIndex?.prefetchLimit??8)),10),sessionKnowledge:{enabled:(M.codeIndex?.sessionKnowledge?.enabled??!0)&&process.env.CODE_INDEX_SESSION_KNOWLEDGE!=="false"},repos:M.codeIndex?.repos??{}},events:{retentionDays:parseInt(I("EVENT_RETENTION_DAYS",String(M.events?.retentionDays??30)),10)},activity:{enabled:(M.activity?.enabled??!0)&&process.env.ACTIVITY_LOG_ENABLED!=="false",bufferSize:parseInt(I("ACTIVITY_BUFFER_SIZE",String(M.activity?.bufferSize??200)),10),flushIntervalMs:parseInt(I("ACTIVITY_FLUSH_INTERVAL_MS",String(M.activity?.flushIntervalMs??3e4)),10),retentionDays:parseInt(I("ACTIVITY_RETENTION_DAYS",String(M.activity?.retentionDays??90)),10)},autoDream:{enabled:M.autoDream?.enabled??!0,idleThresholdMinutes:parseInt(I("AUTODREAM_IDLE_THRESHOLD_MINUTES",String(M.autoDream?.idleThresholdMinutes??30)),10),cooldownMinutes:parseInt(I("AUTODREAM_COOLDOWN_MINUTES",String(M.autoDream?.cooldownMinutes??60)),10),similarityThreshold:parseFloat(I("AUTODREAM_SIMILARITY_THRESHOLD",String(M.autoDream?.similarityThreshold??.85))),patternMinCount:parseInt(I("AUTODREAM_PATTERN_MIN_COUNT",String(M.autoDream?.patternMinCount??3)),10),maxClustersPerRun:parseInt(I("AUTODREAM_MAX_CLUSTERS",String(M.autoDream?.maxClustersPerRun??20)),10),maxContradictionPairsPerRun:parseInt(I("AUTODREAM_MAX_CONTRADICTIONS",String(M.autoDream?.maxContradictionPairsPerRun??30)),10),maxPromotionsPerRun:parseInt(I("AUTODREAM_MAX_PROMOTIONS",String(M.autoDream?.maxPromotionsPerRun??10)),10),maxBudgetUsd:parseFloat(I("AUTODREAM_MAX_BUDGET_USD",String(M.autoDream?.maxBudgetUsd??.1)))},browser:{cdpEndpoint:I("BROWSER_CDP_ENDPOINT","")},tasksDir:{code:I("CODE_TASKS_DIR",`/tmp/${Ii}-code-tasks`),background:I("BG_TASKS_DIR",`/tmp/${Ii}-bg-tasks`)}}});function gb(n){Od.has(n.id)&&hb.warn("Archetype already registered \u2014 overwriting",{id:n.id}),Od.set(n.id,n),hb.info("Registered archetype",{id:n.id})}function Ps(n){return Od.get(n)}var hb,Od,Ms=S(()=>{"use strict";R();hb=$("archetypes"),Od=new Map});import{readFileSync as UN}from"node:fs";import{resolve as Db}from"node:path";function BN(){let n=[Db(import.meta.dirname,"..","..","package.json"),Db(import.meta.dirname,"..","package.json")];for(let e of n)try{let t=JSON.parse(UN(e,"utf-8"));if(t?.name==="@keepur/hive"&&typeof t.hiveApi=="string")return t.hiveApi}catch{continue}return null}var RN,Pb,Nd,Mb=S(()=>{"use strict";R();RN=$("api-version");Pb=BN();Pb||RN.warn("Could not read hiveApi from package.json; falling back to 1.0.0");Nd=Pb??"1.0.0"});var Ub={};we(Ub,{isHiveApiCompatible:()=>zb,loadPlugins:()=>Dd,normalizeManifest:()=>jb,registerPluginCommands:()=>qN,rescanPluginBrokenServers:()=>Pd,resolvePluginServerPath:()=>Ti});import{readFileSync as FN,existsSync as js}from"node:fs";import{resolve as Gt,join as zs}from"node:path";function Ti(n,e,t){let i=e.replace(/\.ts$/,".js"),r=e.replace(/\.ts$/,".min.js"),o=[];t.distDir&&o.push(Gt(t.distDir,`plugins/${n}/${i}`)),o.push(Gt(t.hiveHome,"plugins","node_modules",n,"dist",r),Gt(t.hiveHome,"plugins","node_modules",n,"dist",i),Gt(t.hiveHome,"plugins",n,"dist",r),Gt(t.hiveHome,"plugins",n,"dist",i));for(let s of o)if(js(s))return{path:s};return{reason:"no compiled entry found (expected one of .min.js or .js under dist/)",pathsChecked:o}}function Dd(n,e,t){let i=[];for(let r of n){let o=Gt(e,"plugins","node_modules",r),s=Gt(e,"plugins",r),a=zs(o,"plugin.yaml"),l=zs(s,"plugin.yaml"),c;if(js(a))c=o;else if(js(l))c=s;else{Jt.warn("Plugin manifest not found, skipping",{plugin:r,tried:[a,l]});continue}let u=zs(c,"plugin.yaml"),d=(0,Lb.parse)(FN(u,"utf-8")),f=jb(d);if(f.hiveApi&&!zb(f.hiveApi,Nd)){Jt.warn("Plugin declares incompatible hiveApi range, skipping",{plugin:r,requires:f.hiveApi,running:Nd});continue}let p={};for(let[m,y]of Object.entries(f.mcpServers)){let _=Ti(r,y.entry,{hiveHome:e,distDir:t?.distDir});"reason"in _&&(p[m]=_,Jt.error("Plugin MCP server entry not resolvable",{plugin:r,server:m,entry:y.entry,reason:_.reason,pathsChecked:_.pathsChecked}))}for(let m of f.agentSeeds){let y=zs(c,"agent-seeds",m);js(y)||Jt.warn("Plugin agent seed not found",{plugin:r,seed:m,path:y})}i.push({name:r,dir:c,manifest:f,brokenServers:p});let h=Object.keys(p);Jt.info("Plugin loaded",{plugin:r,mcpServers:Object.keys(f.mcpServers),seeds:f.agentSeeds,...h.length?{brokenServers:h}:{}})}return i}function Pd(n,e,t){let i={},r={};for(let o of n){let s=Object.keys(o.brokenServers);if(s.length!==0)for(let a of s){let l=o.manifest.mcpServers[a];if(!l){delete o.brokenServers[a];continue}"path"in Ti(o.name,l.entry,{hiveHome:e,distDir:t?.distDir})?(delete o.brokenServers[a],(i[o.name]??=[]).push(a)):(r[o.name]??=[]).push(a)}}return{rescued:i,stillBroken:r}}function zb(n,e){let t=n.trim();if(t===e)return!0;if(t.startsWith("^")){let i=t.slice(1).split(".").map(Number),r=e.split(".").map(Number);return!(i.length<1||r.length<1||i[0]!==r[0]||(r[1]??0)<(i[1]??0)||(r[1]??0)===(i[1]??0)&&(r[2]??0)<(i[2]??0))}return Jt.warn("Unrecognized hiveApi range syntax, accepting",{range:n}),!0}function jb(n){return{name:n.name??"",description:n.description??"",hiveApi:n.hiveApi??n["hive-api"]??void 0,mcpServers:Object.fromEntries(Object.entries(n["mcp-servers"]??{}).map(([e,t])=>[e,{entry:t.entry,description:t.description,usage:t.usage,notFor:t["not-for"],env:t.env??[],secretEnv:t["secret-env"]??[],envMap:t["env-map"]??{},agentEnv:t["agent-env"]??{}}])),agentSeeds:n["agent-seeds"]??n["agents-templates"]??[],registerCommands:n["register-commands"]??void 0}}async function qN(n,e){for(let t of n)if(t.manifest.registerCommands)try{let r=await import(Gt(t.dir,"dist",t.manifest.registerCommands));typeof r.registerCommands=="function"&&(r.registerCommands(e),Jt.info("Plugin commands registered",{plugin:t.name}))}catch(i){Jt.warn("Failed to load plugin commands",{plugin:t.name,error:String(i)})}}var Lb,Jt,Us=S(()=>{"use strict";Lb=nt(Id(),1);R();Mb();Jt=$("plugin-loader")});import{readFileSync as ZN,writeFileSync as KN}from"node:fs";function VN(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)throw new Error("No YAML frontmatter found");let t=e[1],i=e[2],r={name:"",description:"",agents:[]},o=t.split(`
144
+ `),s=0;for(;s<o.length;){let a=o[s];if(a.trim()===""){s++;continue}let l=a.match(/^(\w[\w-]*):\s*(.*)/);if(!l){s++;continue}let c=l[1],u=l[2].trim();if(c==="name")r.name=_n(u);else if(c==="description")r.description=_n(u);else if(c==="workflow")r.workflow=_n(u);else if(c==="agents"){let d=u.match(/^\[([^\]]*)\]$/);if(d)r.agents=d[1].split(",").map(f=>_n(f.trim())).filter(f=>f.length>0);else if(u==="")for(r.agents=[];s+1<o.length&&o[s+1].match(/^\s+-\s+/);){s++;let f=o[s].replace(/^\s+-\s+/,"").trim();r.agents.push(_n(f))}else r.agents=[_n(u)]}else if(c==="origin")for(r.origin=Rb(o,s);s+1<o.length&&o[s+1].match(/^\s+\S/);)s++;else if(c==="author")for(r.author=Rb(o,s);s+1<o.length&&o[s+1].match(/^\s+\S/);)s++;s++}return{frontmatter:r,body:i}}function Rb(n,e){let t={},i=e+1;for(;i<n.length&&n[i].match(/^\s+\S/);){let r=n[i].match(/^\s+([\w][\w-]*):\s*(.*)/);if(r){let o=r[2].trim();o==="true"?t[r[1]]=!0:o==="false"?t[r[1]]=!1:t[r[1]]=_n(o)}i++}return t}function _n(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):n}function WN(n,e){let t=[];t.push(`name: ${Rs(n.name)}`),t.push(`description: ${Rs(n.description)}`);let i=n.agents.join(", ");return t.push(`agents: [${i}]`),n.workflow&&t.push(`workflow: ${Rs(n.workflow)}`),n.origin&&(t.push("origin:"),Bb(t,n.origin)),n.author&&(t.push("author:"),Bb(t,n.author)),`---
145
145
  ${t.join(`
146
146
  `)}
147
147
  ---
148
- ${e}`}function wh(n,e){for(let[t,s]of Object.entries(e))s!==void 0&&n.push(` ${t}: ${br(String(s))}`)}function br(n){return n.includes(":")||n.includes("#")||n.includes('"')?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:n}function Sh(n){let e=A0(n,"utf-8");return E0(e)}function kh(n,e,t){C0(n,N0(e,t),"utf-8")}function bh(n){let e=n.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);if(!e)return n;let t=e[1],s=e[2],r=e[3],i=e[4],o=s.split(`
149
- `),a=[],l=!1;for(let c of o){if(l){if(c.match(/^\s+\S/))continue;l=!1}if(c.match(/^origin:\s*$/)){l=!0;continue}c.match(/^origin:\s+\S/)||a.push(c)}return t+a.join(`
150
- `)+r+i}var Ia=j(()=>{"use strict"});import{createHash as x0}from"node:crypto";import{readdirSync as O0,readFileSync as M0,statSync as D0}from"node:fs";import{join as _h}from"node:path";function vh(n){let e=Th(n).sort(),t=x0("sha256");for(let s=0;s<e.length;s++){s>0&&t.update("\0");let r=_h(n,e[s]),i=M0(r,"utf-8");e[s]==="SKILL.md"?t.update(bh(i)):t.update(i)}return t.digest("hex")}function Th(n,e=""){let t=O0(n),s=[];for(let r of t){let i=_h(n,r),o=e?`${e}/${r}`:r;D0(i).isDirectory()?s.push(...Th(i,o)):s.push(o)}return s}var Ih=j(()=>{"use strict";Ia()});import{readdirSync as Ca,readFileSync as L0,statSync as Ea,existsSync as Tt}from"node:fs";import{join as xe,relative as P0,resolve as $0}from"node:path";function Na(n,e,t){let s=new Map,r=[],i=new Map;for(let o of t??[]){let a=xe(o,"skills");if(!Tt(a))continue;let l=o.split("/").pop()??"seed";Aa(a,`seed:${l}`,i,s,r,!1)}for(let o of e??[]){let a=xe(o.dir,"skills");Tt(a)&&Aa(a,o.name,i,s,r,!1)}if(Tt(n)?Aa(n,"customer",i,s,r,!0):be.debug("No customer skills directory found",{path:n}),r.length>0){for(let o of[...s.keys()])s.get(o).push(...r);s.set("__universal__",r)}return R0=B0(i,n),be.info("Skill index loaded",{workflows:i.size,agents:s.size-(s.has("__universal__")?1:0)}),s}function Ah(n,e,t){for(let[s,r]of e){let i=r.filter(o=>o.path!==n);i.length!==r.length&&(i.length===0?e.delete(s):e.set(s,i))}for(let s=t.length-1;s>=0;s--)t[s].path===n&&t.splice(s,1)}function Aa(n,e,t,s,r,i){let o;try{o=Ca(n).filter(a=>{try{return Ea(xe(n,a)).isDirectory()}catch{return!1}})}catch(a){be.warn("Failed to read skills directory",{source:e,path:n,error:String(a)});return}for(let a of o){let l=xe(n,a),c=xe(l,"skills");if(!Tt(c)){be.debug("Workflow missing skills/ subdirectory, skipping",{source:e,workflow:a});continue}let d=t.get(a);if(d)if(i&&d.source!=="customer")be.warn("Customer skill shadows plugin-bundled skill",{workflow:a,shadowed:d,customer:{source:e,path:l}}),Ah(d.path,s,r),t.set(a,{source:e,path:l});else if(i&&d.source==="customer"){be.error("Customer skill collision \u2014 both skipped",{workflow:a,first:d,second:{source:e,path:l}}),Ah(d.path,s,r),t.delete(a);continue}else{be.warn("Skill workflow collision \u2014 keeping first, skipping second",{workflow:a,kept:d,skipped:{source:e,path:l}});continue}else t.set(a,{source:e,path:l});let u={type:"local",path:l},h=new Set,p=!1,m;try{m=Ca(c).filter(f=>{try{return Ea(xe(c,f)).isDirectory()}catch{return!1}})}catch(f){be.warn("Failed to read workflow skills subdir",{source:e,workflow:a,error:String(f)});continue}for(let f of m){let y=xe(c,f,"SKILL.md");if(!Tt(y))continue;let w=U0(L0(y,"utf-8"));for(let S of w)S==="all"?p=!0:h.add(S)}if(p)r.push(u),be.debug("Workflow registered as universal",{source:e,workflow:a,skills:m.length});else if(h.size>0){for(let f of h){let y=s.get(f)??[];y.push(u),s.set(f,y)}be.debug("Workflow registered",{source:e,workflow:a,agents:[...h],skills:m.length})}}}function Ch(n,e){let t=n.get(e)??[],s=n.get("__universal__")??[];if(t.length>0&&s.length>0){let r=new Set(t.map(o=>o.path)),i=s.filter(o=>!r.has(o.path));return[...t,...i]}return t.length===0&&s.length>0?[...s]:t}function B0(n,e){let t=new Set,s=$0(e,"..");for(let[r,i]of n){if(i.source!=="customer")continue;let o=xe(i.path,"skills");if(!Tt(o))continue;let a;try{a=Ca(o).filter(l=>{try{return Ea(xe(o,l)).isDirectory()}catch{return!1}})}catch{continue}for(let l of a){let c=xe(o,l),d=xe(c,"SKILL.md");if(Tt(d))try{let{frontmatter:u,body:h}=Sh(d);if(!u.origin?.["base-content-hash"])continue;let p=vh(c);if(p!==u.origin["base-content-hash"]&&(t.add(c),be.warn("Registry-installed skill has been modified",{workflow:r,skill:l,source:u.origin.source,baseHash:u.origin["base-content-hash"],currentHash:p}),!u.origin.modified)){u.origin.modified=!0;try{kh(d,u,h),Rc(s,[P0(s,d)],`detect-modified: ${l} content hash changed`)}catch(m){be.error("Failed to persist modified flag to disk",{path:d,error:String(m)})}}}catch{}}}return t}function U0(n){let e=n.match(/^---\n([\s\S]*?)\n---/);if(!e)return[];let t=e[1],s=t.match(/^agents:\s*\n((?:\s+-\s+.+\n?)*)/m);if(s)return s[1].split(`
151
- `).map(i=>i.replace(/^\s+-\s+/,"").trim()).filter(Boolean);let r=t.match(/^agents:\s*\[([^\]]*)\]/m);return r?r[1].split(",").map(i=>i.trim()).filter(Boolean):[]}var be,R0,xa=j(()=>{"use strict";M();Ih();Ia();xi();be=k("skill-loader"),R0=new Set});var It,_r=j(()=>{"use strict";It={clickup:{description:"Task management \u2014 tasks, lists, spaces, comments, custom fields",usage:"Creating and managing project tasks"},google:{description:"Email (Gmail), calendar, Google Drive files",usage:"Sending email, checking calendar events, reading Drive documents"},resend:{description:"Send outbound email with file attachments",usage:"Sending transactional or outreach email from your agent address",notFor:"Reading email \u2014 use google for inbox access"},"brave-search":{description:"Web search, news, local business lookup",usage:"Finding current information from the public web",notFor:"Internal data \u2014 use crm-search, code-search, or memory instead"},contacts:{description:"Contact lookups by name, email, or phone",usage:"Quick lookups of people in the contact directory",notFor:"Messaging another hive agent (use team) or CRM deal/company data (use a CRM plugin)"},team:{description:"Direct agent-to-agent messaging \u2014 peer hive agents, not Slack DMs",usage:"Sending a message or task to another agent in this hive",notFor:"Looking up people in the contact directory \u2014 use contacts instead",toolkitBlurb:"Direct messaging to peer hive agents (not Slack DMs)"},linear:{description:"Issue tracking and project management",usage:"Creating, searching, and updating engineering issues"},"github-issues":{description:"GitHub issue tracking \u2014 create, search, update, comment on issues",usage:"Managing GitHub issues for engineering work"},quo:{description:"Send and receive SMS messages via OpenPhone",usage:"Texting customers or team members"},voice:{description:"Make outbound phone calls via Vapi",usage:"Calling customers, scheduling appointments, following up by phone"},tasks:{description:"Task management \u2014 create, update, and track agent tasks",usage:"Managing your own task queue"},"code-search":{description:"Semantic search over codebase file index \u2014 find where functionality lives, file roles, exports",usage:"Finding code by what it does, not just by filename",notFor:"Broad web search \u2014 use brave-search instead"},"code-task":{description:"Spawn Claude Code CLI sessions for coding tasks",usage:"Delegating implementation, debugging, or code analysis work"},memory:{description:"Read and write your personal agent memory",usage:"Storing and retrieving facts across conversations. Auto-managed \u2014 don't over-save"},"structured-memory":{description:"Semantic + temporal memory tiers \u2014 recall, save, pin, forget",usage:"Use memory_recall to find prior facts; memory_save/_pin for durable notes",toolkitBlurb:"Semantic + temporal memory tiers (recall, save, pin)"},schedule:{description:"Self-service schedule management \u2014 view, add, update, remove your schedules",usage:"Managing your recurring or one-time scheduled tasks",toolkitBlurb:"Manage your scheduled tasks (recurring or one-time)"},"event-bus":{description:"Publish events to the cross-agent event bus",usage:"Notifying other agents about state changes or completed work"},workflow:{description:"Plan and task management \u2014 create plans, assign tasks, track dependencies",usage:"Coordinating multi-step work across agents and humans"},callback:{description:"Schedule future self-invocations",usage:"Reminding yourself to follow up on something later"},background:{description:"Spawn detached background processes",usage:"Running long-lived commands that outlive your current turn"},"conversation-search":{description:"Semantic search over past conversations",usage:"Finding what was discussed previously across threads"},browser:{description:"Browser automation via Playwright \u2014 navigate, click, fill forms, screenshot",usage:"Accessing web UIs that don't have APIs"},slack:{description:"Slack API \u2014 read channels, post messages, manage threads",usage:"Interacting with Slack channels and threads",toolkitBlurb:"Slack channels, messages, and threads"},recall:{description:"Meeting bot \u2014 join calls, get transcripts",usage:"Participating in or getting transcripts from video meetings"},admin:{description:"Agent management \u2014 list, view, update agent definitions",usage:"Viewing or modifying agent configurations"},keychain:{description:"Read secrets from macOS Keychain",usage:"Retrieving API keys or credentials stored in the system keychain"}}});function Eh(n=[]){let e=[],t=[],s=[];for(let i of Object.keys(It)){if(q0.has(i)){e.push(i);continue}let o=j0[i];!o||o()?e.push(i):t.push(i)}let r=g.instance?.id??"unknown";for(let i of n)for(let[o,a]of Object.entries(i.manifest.mcpServers)){let l=i.brokenServers[o];if(l){s.push({name:o,reason:l.reason});continue}let c=a.env??[],d=a.secretEnv??[],u=c.every(p=>!!process.env[p]),h=d.every(p=>!!process.env[p]||!!zt(r,p));u&&h?e.push(o):t.push(o)}return{instanceId:g.instance?.id??"unknown",servers:{configured:e,unconfigured:t,broken:s}}}var j0,q0,Nh=j(()=>{"use strict";Ne();pr();_r();j0={google:()=>Object.keys(g.google?.accounts??{}).length>0||!!g.google?.account,resend:()=>!!g.resend?.apiKey,"brave-search":()=>!!g.brave?.apiKey,linear:()=>!!g.linear?.apiKey,clickup:()=>!!g.clickup?.apiToken,"github-issues":()=>!!g.github?.repo,quo:()=>!!g.quo?.apiKey,recall:()=>!!g.recall?.apiKey,"code-task":()=>!0,"code-search":()=>!!g.codeIndex?.enabled,browser:()=>!!g.browser?.cdpEndpoint,tasks:()=>(g.taskLedger?.apiUrl??"")!=="http://localhost:3002"},q0=new Set(["memory","slack","contacts","callback","background","schedule","event-bus","conversation-search","keychain","admin"])});function Oa(n,e){let t=It[n];if(t)return t;for(let s of e){let r=s.manifest.mcpServers[n];if(r?.description)return{description:r.description,usage:r.usage,notFor:r.notFor}}return{description:n}}function K0(n){return n.toolkitBlurb??n.description}function Ma(n,e){return`- ${n} \u2014 ${K0(e)}`}function xh(n){let{coreServerNames:e,delegateServerNames:t,plugins:s,autoInjectedServers:r}=n,i=[],o=[],a=new Set;for(let d of e)r.has(d)&&(i.push(d),a.add(d));for(let d of e)a.has(d)||o.push(d);let l=[];l.push(`## Your toolkit
148
+ ${e}`}function Bb(n,e){for(let[t,i]of Object.entries(e))i!==void 0&&n.push(` ${t}: ${Rs(String(i))}`)}function Rs(n){return n.includes(":")||n.includes("#")||n.includes('"')?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:n}function Fb(n){let e=ZN(n,"utf-8");return VN(e)}function qb(n,e,t){KN(n,WN(e,t),"utf-8")}function Zb(n){let e=n.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);if(!e)return n;let t=e[1],i=e[2],r=e[3],o=e[4],s=i.split(`
149
+ `),a=[],l=!1;for(let c of s){if(l){if(c.match(/^\s+\S/))continue;l=!1}if(c.match(/^origin:\s*$/)){l=!0;continue}c.match(/^origin:\s+\S/)||a.push(c)}return t+a.join(`
150
+ `)+r+o}var Md=S(()=>{"use strict"});import{createHash as GN}from"node:crypto";import{readdirSync as JN,readFileSync as HN,statSync as YN}from"node:fs";import{join as Kb}from"node:path";function Vb(n){let e=Wb(n).sort(),t=GN("sha256");for(let i=0;i<e.length;i++){i>0&&t.update("\0");let r=Kb(n,e[i]),o=HN(r,"utf-8");e[i]==="SKILL.md"?t.update(Zb(o)):t.update(o)}return t.digest("hex")}function Wb(n,e=""){let t=JN(n),i=[];for(let r of t){let o=Kb(n,r),s=e?`${e}/${r}`:r;YN(o).isDirectory()?i.push(...Wb(o,s)):i.push(s)}return i}var Gb=S(()=>{"use strict";Md()});import{readdirSync as zd,readFileSync as XN,statSync as jd,existsSync as wn}from"node:fs";import{join as st,relative as QN,resolve as eD}from"node:path";function Ud(n,e,t){let i=new Map,r=[],o=new Map;for(let s of t??[]){let a=st(s,"skills");if(!wn(a))continue;let l=s.split("/").pop()??"seed";Ld(a,`seed:${l}`,o,i,r,!1)}for(let s of e??[]){let a=st(s.dir,"skills");wn(a)&&Ld(a,s.name,o,i,r,!1)}if(wn(n)?Ld(n,"customer",o,i,r,!0):Je.debug("No customer skills directory found",{path:n}),r.length>0){for(let s of[...i.keys()])i.get(s).push(...r);i.set("__universal__",r)}return tD=nD(o,n),Je.info("Skill index loaded",{workflows:o.size,agents:i.size-(i.has("__universal__")?1:0)}),i}function Jb(n,e,t){for(let[i,r]of e){let o=r.filter(s=>s.path!==n);o.length!==r.length&&(o.length===0?e.delete(i):e.set(i,o))}for(let i=t.length-1;i>=0;i--)t[i].path===n&&t.splice(i,1)}function Ld(n,e,t,i,r,o){let s;try{s=zd(n).filter(a=>{try{return jd(st(n,a)).isDirectory()}catch{return!1}})}catch(a){Je.warn("Failed to read skills directory",{source:e,path:n,error:String(a)});return}for(let a of s){let l=st(n,a),c=st(l,"skills");if(!wn(c)){Je.debug("Workflow missing skills/ subdirectory, skipping",{source:e,workflow:a});continue}let u=t.get(a);if(u)if(o&&u.source!=="customer")Je.warn("Customer skill shadows plugin-bundled skill",{workflow:a,shadowed:u,customer:{source:e,path:l}}),Jb(u.path,i,r),t.set(a,{source:e,path:l});else if(o&&u.source==="customer"){Je.error("Customer skill collision \u2014 both skipped",{workflow:a,first:u,second:{source:e,path:l}}),Jb(u.path,i,r),t.delete(a);continue}else{Je.warn("Skill workflow collision \u2014 keeping first, skipping second",{workflow:a,kept:u,skipped:{source:e,path:l}});continue}else t.set(a,{source:e,path:l});let d={type:"local",path:l},f=new Set,p=!1,h;try{h=zd(c).filter(m=>{try{return jd(st(c,m)).isDirectory()}catch{return!1}})}catch(m){Je.warn("Failed to read workflow skills subdir",{source:e,workflow:a,error:String(m)});continue}for(let m of h){let y=st(c,m,"SKILL.md");if(!wn(y))continue;let _=rD(XN(y,"utf-8"));for(let b of _)b==="all"?p=!0:f.add(b)}if(p)r.push(d),Je.debug("Workflow registered as universal",{source:e,workflow:a,skills:h.length});else if(f.size>0){for(let m of f){let y=i.get(m)??[];y.push(d),i.set(m,y)}Je.debug("Workflow registered",{source:e,workflow:a,agents:[...f],skills:h.length})}}}function Hb(n,e){let t=n.get(e)??[],i=n.get("__universal__")??[];if(t.length>0&&i.length>0){let r=new Set(t.map(s=>s.path)),o=i.filter(s=>!r.has(s.path));return[...t,...o]}return t.length===0&&i.length>0?[...i]:t}function nD(n,e){let t=new Set,i=eD(e,"..");for(let[r,o]of n){if(o.source!=="customer")continue;let s=st(o.path,"skills");if(!wn(s))continue;let a;try{a=zd(s).filter(l=>{try{return jd(st(s,l)).isDirectory()}catch{return!1}})}catch{continue}for(let l of a){let c=st(s,l),u=st(c,"SKILL.md");if(wn(u))try{let{frontmatter:d,body:f}=Fb(u);if(!d.origin?.["base-content-hash"])continue;let p=Vb(c);if(p!==d.origin["base-content-hash"]&&(t.add(c),Je.warn("Registry-installed skill has been modified",{workflow:r,skill:l,source:d.origin.source,baseHash:d.origin["base-content-hash"],currentHash:p}),!d.origin.modified)){d.origin.modified=!0;try{qb(u,d,f),sv(i,[QN(i,u)],`detect-modified: ${l} content hash changed`)}catch(h){Je.error("Failed to persist modified flag to disk",{path:u,error:String(h)})}}}catch{}}}return t}function rD(n){let e=n.match(/^---\n([\s\S]*?)\n---/);if(!e)return[];let t=e[1],i=t.match(/^agents:\s*\n((?:\s+-\s+.+\n?)*)/m);if(i)return i[1].split(`
151
+ `).map(o=>o.replace(/^\s+-\s+/,"").trim()).filter(Boolean);let r=t.match(/^agents:\s*\[([^\]]*)\]/m);return r?r[1].split(",").map(o=>o.trim()).filter(Boolean):[]}var Je,tD,Rd=S(()=>{"use strict";R();Gb();Md();Bl();Je=$("skill-loader"),tD=new Set});var bn,Bs=S(()=>{"use strict";bn={clickup:{description:"Task management \u2014 tasks, lists, spaces, comments, custom fields",usage:"Creating and managing project tasks"},google:{description:"Email (Gmail), calendar, Google Drive files",usage:"Sending email, checking calendar events, reading Drive documents"},resend:{description:"Send outbound email with file attachments",usage:"Sending transactional or outreach email from your agent address",notFor:"Reading email \u2014 use google for inbox access"},"brave-search":{description:"Web search, news, local business lookup",usage:"Finding current information from the public web",notFor:"Internal data \u2014 use crm-search, code-search, or memory instead"},contacts:{description:"Contact lookups by name, email, or phone",usage:"Quick lookups of people in the contact directory",notFor:"Messaging another hive agent (use team) or CRM deal/company data (use a CRM plugin)"},team:{description:"Direct agent-to-agent messaging \u2014 peer hive agents, not Slack DMs",usage:"Sending a message or task to another agent in this hive",notFor:"Looking up people in the contact directory \u2014 use contacts instead",toolkitBlurb:"Direct messaging to peer hive agents (not Slack DMs)"},linear:{description:"Issue tracking and project management",usage:"Creating, searching, and updating engineering issues"},"github-issues":{description:"GitHub issue tracking \u2014 create, search, update, comment on issues",usage:"Managing GitHub issues for engineering work"},quo:{description:"Send and receive SMS messages via OpenPhone",usage:"Texting customers or team members"},voice:{description:"Make outbound phone calls via Vapi",usage:"Calling customers, scheduling appointments, following up by phone"},tasks:{description:"Task management \u2014 create, update, and track agent tasks",usage:"Managing your own task queue"},"code-search":{description:"Semantic search over codebase file index \u2014 find where functionality lives, file roles, exports",usage:"Finding code by what it does, not just by filename",notFor:"Broad web search \u2014 use brave-search instead"},"code-task":{description:"Spawn Claude Code CLI sessions for coding tasks",usage:"Delegating implementation, debugging, or code analysis work"},memory:{description:"Read and write your personal agent memory",usage:"Storing and retrieving facts across conversations. Auto-managed \u2014 don't over-save"},"structured-memory":{description:"Semantic + temporal memory tiers \u2014 recall, save, pin, forget",usage:"Use memory_recall to find prior facts; memory_save/_pin for durable notes",toolkitBlurb:"Semantic + temporal memory tiers (recall, save, pin)"},schedule:{description:"Self-service schedule management \u2014 view, add, update, remove your schedules",usage:"Managing your recurring or one-time scheduled tasks",toolkitBlurb:"Manage your scheduled tasks (recurring or one-time)"},"event-bus":{description:"Publish events to the cross-agent event bus",usage:"Notifying other agents about state changes or completed work"},workflow:{description:"Plan and task management \u2014 create plans, assign tasks, track dependencies",usage:"Coordinating multi-step work across agents and humans"},callback:{description:"Schedule future self-invocations",usage:"Reminding yourself to follow up on something later"},background:{description:"Spawn detached background processes",usage:"Running long-lived commands that outlive your current turn"},"conversation-search":{description:"Semantic search over past conversations",usage:"Finding what was discussed previously across threads"},browser:{description:"Browser automation via Playwright \u2014 navigate, click, fill forms, screenshot",usage:"Accessing web UIs that don't have APIs"},slack:{description:"Slack API \u2014 read channels, post messages, manage threads",usage:"Interacting with Slack channels and threads",toolkitBlurb:"Slack channels, messages, and threads"},recall:{description:"Meeting bot \u2014 join calls, get transcripts",usage:"Participating in or getting transcripts from video meetings"},admin:{description:"Agent management \u2014 list, view, update agent definitions",usage:"Viewing or modifying agent configurations"},keychain:{description:"Read secrets from macOS Keychain",usage:"Retrieving API keys or credentials stored in the system keychain"}}});function Yb(n=[]){let e=[],t=[],i=[];for(let o of Object.keys(bn)){if(oD.has(o)){e.push(o);continue}let s=iD[o];!s||s()?e.push(o):t.push(o)}let r=g.instance?.id??"unknown";for(let o of n)for(let[s,a]of Object.entries(o.manifest.mcpServers)){let l=o.brokenServers[s];if(l){i.push({name:s,reason:l.reason});continue}let c=a.env??[],u=a.secretEnv??[],d=c.every(p=>!!process.env[p]),f=u.every(p=>!!process.env[p]||!!rr(r,p));d&&f?e.push(s):t.push(s)}return{instanceId:g.instance?.id??"unknown",servers:{configured:e,unconfigured:t,broken:i}}}var iD,oD,Xb=S(()=>{"use strict";ot();Ds();Bs();iD={google:()=>Object.keys(g.google?.accounts??{}).length>0||!!g.google?.account,resend:()=>!!g.resend?.apiKey,"brave-search":()=>!!g.brave?.apiKey,linear:()=>!!g.linear?.apiKey,clickup:()=>!!g.clickup?.apiToken,"github-issues":()=>!!g.github?.repo,quo:()=>!!g.quo?.apiKey,recall:()=>!!g.recall?.apiKey,"code-task":()=>!0,"code-search":()=>!!g.codeIndex?.enabled,browser:()=>!!g.browser?.cdpEndpoint,tasks:()=>(g.taskLedger?.apiUrl??"")!=="http://localhost:3002"},oD=new Set(["memory","slack","contacts","callback","background","schedule","event-bus","conversation-search","keychain","admin"])});function Bd(n,e){let t=bn[n];if(t)return t;for(let i of e){let r=i.manifest.mcpServers[n];if(r?.description)return{description:r.description,usage:r.usage,notFor:r.notFor}}return{description:n}}function aD(n){return n.toolkitBlurb??n.description}function Fd(n,e){return`- ${n} \u2014 ${aD(e)}`}function Qb(n){let{coreServerNames:e,delegateServerNames:t,plugins:i,autoInjectedServers:r}=n,o=[],s=[],a=new Set;for(let u of e)r.has(u)&&(o.push(u),a.add(u));for(let u of e)a.has(u)||s.push(u);let l=[];l.push(`## Your toolkit
152
152
 
153
- You have access to the following tools this session. Try them; don't guess at availability.`);let c=F0.map(d=>`- ${d.name} \u2014 ${d.blurb}`).join(`
153
+ You have access to the following tools this session. Try them; don't guess at availability.`);let c=sD.map(u=>`- ${u.name} \u2014 ${u.blurb}`).join(`
154
154
  `);if(l.push(`### Built-in (always available)
155
- ${c}`),i.length>0){let d=i.map(u=>Ma(u,Oa(u,s))).join(`
155
+ ${c}`),o.length>0){let u=o.map(d=>Fd(d,Bd(d,i))).join(`
156
156
  `);l.push(`### Engine-provided (always available to every agent)
157
- `+d)}if(o.length>0){let d=o.map(u=>Ma(u,Oa(u,s))).join(`
157
+ `+u)}if(s.length>0){let u=s.map(d=>Fd(d,Bd(d,i))).join(`
158
158
  `);l.push(`### Capability MCPs (provisioned for your role)
159
- `+d)}if(t.length>0){let d=t.map(u=>Ma(u,Oa(u,s))).join(`
159
+ `+u)}if(t.length>0){let u=t.map(d=>Fd(d,Bd(d,i))).join(`
160
160
  `);l.push(`### Delegated capability MCPs (via Agent tool)
161
- `+d)}return l.join(`
162
-
163
- `)}var F0,Oh=j(()=>{"use strict";_r();F0=[{name:"Bash",blurb:"run shell commands"},{name:"Read / Write / Edit",blurb:"file I/O"},{name:"Glob / Grep",blurb:"file/content search"},{name:"WebFetch / WebSearch",blurb:"web access"},{name:"NotebookEdit",blurb:"Jupyter notebook editing"}]});var Lh={};Ue(Lh,{AgentRunner:()=>Ws,DIST_DIR:()=>Ke,ensurePluginNodeModulesLink:()=>Dh});import{query as H0}from"@anthropic-ai/claude-agent-sdk";import{resolve as Oe}from"node:path";import{existsSync as Hs,statSync as W0,mkdirSync as Mh,symlinkSync as G0,lstatSync as V0}from"node:fs";import{createRequire as Y0}from"node:module";import{readFile as J0}from"node:fs/promises";function z0(n){return JSON.stringify(Eh(n))}function Q0(n){let e=n;for(let t=0;t<15;t++){let s=Oe(e,"node_modules"),r=Oe(e,"package.json");if(Hs(s)&&Hs(r))return s;let i=Oe(e,"..");if(i===e)break;e=i}return null}function Dh(n){if(!Da)return;let e=Oe(n,"node_modules");try{V0(e);return}catch{}try{G0(Da,e,"dir"),R.info("Linked plugin node_modules to engine deps",{pluginDir:n,target:Da})}catch(t){R.warn("Failed to link plugin node_modules",{pluginDir:n,error:String(t)})}}function J(n){let e=X0[n];if(e){let t=Oe(Ke,"mcp",e);if(Hs(t))return t}return Oe(Ke,n)}var R,Ke,Da,X0,Ws,La=j(()=>{"use strict";gr();M();Ne();pr();ls();kr();xa();_r();Nh();Oh();R=k("agent-runner");Ke=Hs(Oe(import.meta.dirname,"mcp"))?import.meta.dirname:Oe(import.meta.dirname,"..");Da=Q0(Ke);X0={"memory/memory-mcp-server.js":"memory.min.js","memory/structured-memory-mcp-server.js":"structured-memory.min.js","keychain/keychain-mcp-server.js":"keychain.min.js","google/google-mcp-server.js":"google.min.js","quo/quo-mcp-server.js":"quo.min.js","voice/voice-mcp-server.js":"voice.min.js","contacts/contacts-mcp-server.js":"contacts.min.js","tasks/task-mcp-server.js":"task.min.js","resend/resend-mcp-server.js":"resend.min.js","linear/linear-mcp-server.js":"linear.min.js","github/github-issues-mcp-server.js":"github-issues.min.js","clickup/clickup-mcp-server.js":"clickup.min.js","recall/recall-mcp-server.js":"recall.min.js","background/background-task-mcp-server.js":"background-task.min.js","callback/callback-mcp-server.js":"callback.min.js","code-task/code-task-mcp-server.js":"code-task.min.js","search/conversation-search-mcp-server.js":"search-conversation.min.js","code-index/code-search-mcp-server.js":"code-search.min.js","events/event-bus-mcp-server.js":"event-bus.min.js","team/team-mcp-server.js":"team.min.js","workflow/workflow-mcp-server.js":"workflow.min.js","schedule/schedule-mcp-server.js":"schedule.min.js","admin/admin-mcp-server.js":"admin.min.js","slack/slack-mcp-server.js":"slack.min.js"};Ws=class n{static registryRef;agentConfig;memoryManager;plugins;skillIndex;activeQuery=null;eventSubscribersJson;prefetcher;_archetypeDef=void 0;constructor(e,t,s=[],r=new Map,i="{}",o){this.agentConfig=e,this.memoryManager=t,this.plugins=s,this.skillIndex=r,this.eventSubscribersJson=i,this.prefetcher=o}async buildSystemPrompt(e,t){let s=[];this.agentConfig.soul&&s.push(this.agentConfig.soul);let r=this.getArchetypeDef();if(r&&this.agentConfig.archetypeConfig)try{let c=r.systemPromptCard({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});c&&s.push(c)}catch(c){R.error("Archetype systemPromptCard threw \u2014 omitting card",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(c)})}s.push(this.agentConfig.systemPrompt);let i=await this.memoryManager.read("shared/constitution.md");i&&s.push(i),s.push(xh({coreServerNames:e,delegateServerNames:t??[],plugins:this.plugins,autoInjectedServers:n.autoInjectedServerNames()}));let o=await this.memoryManager.getHotTierPrompt(this.agentConfig.id,g.memory.hotBudgetTokens);if(o)s.push(o);else{let c=`agents/${this.agentConfig.id}`,d=await this.memoryManager.read(`${c}/memory.md`);d&&s.push(`## Your Memory
164
- ${d}`);let h=(await this.memoryManager.list(c)).filter(p=>p.endsWith(".md")&&p!=="memory.md");h.length>0&&s.push(`## Available Memory Files
165
- You have ${h.length} reference file(s) in your memory directory:
166
- `+h.map(p=>`- ${c}/${p}`).join(`
167
- `)+"\n\nRead relevant files via the memory MCP server (`memory_read`) before starting tasks that may relate to them.")}let l=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return s.push(`**Current date/time**: ${l} (Pacific Time)`),s.join(`
161
+ `+u)}return l.join(`
162
+
163
+ `)}var sD,ek=S(()=>{"use strict";Bs();sD=[{name:"Bash",blurb:"run shell commands"},{name:"Read / Write / Edit",blurb:"file I/O"},{name:"Glob / Grep",blurb:"file/content search"},{name:"WebFetch / WebSearch",blurb:"web access"},{name:"NotebookEdit",blurb:"Jupyter notebook editing"}]});function v(n,e,t){function i(a,l){if(a._zod||Object.defineProperty(a,"_zod",{value:{def:l,constr:s,traits:new Set},enumerable:!1}),a._zod.traits.has(n))return;a._zod.traits.add(n),e(a,l);let c=s.prototype,u=Object.keys(c);for(let d=0;d<u.length;d++){let f=u[d];f in a||(a[f]=c[f].bind(a))}}let r=t?.Parent??Object;class o extends r{}Object.defineProperty(o,"name",{value:n});function s(a){var l;let c=t?.Parent?new o:this;i(c,a),(l=c._zod).deferred??(l.deferred=[]);for(let u of c._zod.deferred)u();return c}return Object.defineProperty(s,"init",{value:i}),Object.defineProperty(s,Symbol.hasInstance,{value:a=>t?.Parent&&a instanceof t.Parent?!0:a?._zod?.traits?.has(n)}),Object.defineProperty(s,"name",{value:n}),s}function fe(n){return n&&Object.assign(Ei,n),Ei}var qd,Fs,at,Ht,Ei,ir=S(()=>{qd=Object.freeze({status:"aborted"});Fs=Symbol("zod_brand"),at=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Ht=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}},Ei={}});var E={};we(E,{BIGINT_FORMAT_RANGES:()=>Qd,Class:()=>Kd,NUMBER_FORMAT_RANGES:()=>Xd,aborted:()=>en,allowsEval:()=>Gd,assert:()=>fD,assertEqual:()=>cD,assertIs:()=>uD,assertNever:()=>dD,assertNotEqual:()=>lD,assignProp:()=>Xt,base64ToUint8Array:()=>nk,base64urlToUint8Array:()=>AD,cached:()=>sr,captureStackTrace:()=>Zs,cleanEnum:()=>ED,cleanRegex:()=>Ci,clone:()=>Ne,cloneDef:()=>mD,createTransparentProxy:()=>wD,defineLazy:()=>V,esc:()=>qs,escapeRegex:()=>He,extend:()=>SD,finalizeIssue:()=>je,floatSafeRemainder:()=>Vd,getElementAtPath:()=>hD,getEnumValues:()=>Oi,getLengthableOrigin:()=>Pi,getParsedType:()=>_D,getSizableOrigin:()=>Di,hexToUint8Array:()=>CD,isObject:()=>kn,isPlainObject:()=>Qt,issue:()=>ar,joinValues:()=>w,jsonStringifyReplacer:()=>or,merge:()=>xD,mergeDefs:()=>$t,normalizeParams:()=>C,nullish:()=>Yt,numKeys:()=>vD,objectClone:()=>pD,omit:()=>kD,optionalKeys:()=>Yd,parsedType:()=>T,partial:()=>ID,pick:()=>bD,prefixIssues:()=>qe,primitiveTypes:()=>Hd,promiseAllObject:()=>gD,propertyKeyTypes:()=>Ni,randomString:()=>yD,required:()=>TD,safeExtend:()=>$D,shallowClone:()=>Jd,slugify:()=>Wd,stringifyPrimitive:()=>x,uint8ArrayToBase64:()=>rk,uint8ArrayToBase64url:()=>OD,uint8ArrayToHex:()=>ND,unwrapMessage:()=>Ai});function cD(n){return n}function lD(n){return n}function uD(n){}function dD(n){throw new Error("Unexpected value in exhaustive check")}function fD(n){}function Oi(n){let e=Object.values(n).filter(i=>typeof i=="number");return Object.entries(n).filter(([i,r])=>e.indexOf(+i)===-1).map(([i,r])=>r)}function w(n,e="|"){return n.map(t=>x(t)).join(e)}function or(n,e){return typeof e=="bigint"?e.toString():e}function sr(n){return{get value(){{let t=n();return Object.defineProperty(this,"value",{value:t}),t}throw new Error("cached value already set")}}}function Yt(n){return n==null}function Ci(n){let e=n.startsWith("^")?1:0,t=n.endsWith("$")?n.length-1:n.length;return n.slice(e,t)}function Vd(n,e){let t=(n.toString().split(".")[1]||"").length,i=e.toString(),r=(i.split(".")[1]||"").length;if(r===0&&/\d?e-\d?/.test(i)){let l=i.match(/\d?e-(\d?)/);l?.[1]&&(r=Number.parseInt(l[1]))}let o=t>r?t:r,s=Number.parseInt(n.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function V(n,e,t){let i;Object.defineProperty(n,e,{get(){if(i!==tk)return i===void 0&&(i=tk,i=t()),i},set(r){Object.defineProperty(n,e,{value:r})},configurable:!0})}function pD(n){return Object.create(Object.getPrototypeOf(n),Object.getOwnPropertyDescriptors(n))}function Xt(n,e,t){Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0})}function $t(...n){let e={};for(let t of n){let i=Object.getOwnPropertyDescriptors(t);Object.assign(e,i)}return Object.defineProperties({},e)}function mD(n){return $t(n._zod.def)}function hD(n,e){return e?e.reduce((t,i)=>t?.[i],n):n}function gD(n){let e=Object.keys(n),t=e.map(i=>n[i]);return Promise.all(t).then(i=>{let r={};for(let o=0;o<e.length;o++)r[e[o]]=i[o];return r})}function yD(n=10){let e="abcdefghijklmnopqrstuvwxyz",t="";for(let i=0;i<n;i++)t+=e[Math.floor(Math.random()*e.length)];return t}function qs(n){return JSON.stringify(n)}function Wd(n){return n.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}function kn(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Qt(n){if(kn(n)===!1)return!1;let e=n.constructor;if(e===void 0||typeof e!="function")return!0;let t=e.prototype;return!(kn(t)===!1||Object.prototype.hasOwnProperty.call(t,"isPrototypeOf")===!1)}function Jd(n){return Qt(n)?{...n}:Array.isArray(n)?[...n]:n}function vD(n){let e=0;for(let t in n)Object.prototype.hasOwnProperty.call(n,t)&&e++;return e}function He(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ne(n,e,t){let i=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(i._zod.parent=n),i}function C(n){let e=n;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 wD(n){let e;return new Proxy({},{get(t,i,r){return e??(e=n()),Reflect.get(e,i,r)},set(t,i,r,o){return e??(e=n()),Reflect.set(e,i,r,o)},has(t,i){return e??(e=n()),Reflect.has(e,i)},deleteProperty(t,i){return e??(e=n()),Reflect.deleteProperty(e,i)},ownKeys(t){return e??(e=n()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(t,i){return e??(e=n()),Reflect.getOwnPropertyDescriptor(e,i)},defineProperty(t,i,r){return e??(e=n()),Reflect.defineProperty(e,i,r)}})}function x(n){return typeof n=="bigint"?n.toString()+"n":typeof n=="string"?`"${n}"`:`${n}`}function Yd(n){return Object.keys(n).filter(e=>n[e]._zod.optin==="optional"&&n[e]._zod.optout==="optional")}function bD(n,e){let t=n._zod.def,i=t.checks;if(i&&i.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");let o=$t(n._zod.def,{get shape(){let s={};for(let a in e){if(!(a in t.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&(s[a]=t.shape[a])}return Xt(this,"shape",s),s},checks:[]});return Ne(n,o)}function kD(n,e){let t=n._zod.def,i=t.checks;if(i&&i.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");let o=$t(n._zod.def,{get shape(){let s={...n._zod.def.shape};for(let a in e){if(!(a in t.shape))throw new Error(`Unrecognized key: "${a}"`);e[a]&&delete s[a]}return Xt(this,"shape",s),s},checks:[]});return Ne(n,o)}function SD(n,e){if(!Qt(e))throw new Error("Invalid input to extend: expected a plain object");let t=n._zod.def.checks;if(t&&t.length>0){let o=n._zod.def.shape;for(let s in e)if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}let r=$t(n._zod.def,{get shape(){let o={...n._zod.def.shape,...e};return Xt(this,"shape",o),o}});return Ne(n,r)}function $D(n,e){if(!Qt(e))throw new Error("Invalid input to safeExtend: expected a plain object");let t=$t(n._zod.def,{get shape(){let i={...n._zod.def.shape,...e};return Xt(this,"shape",i),i}});return Ne(n,t)}function xD(n,e){let t=$t(n._zod.def,{get shape(){let i={...n._zod.def.shape,...e._zod.def.shape};return Xt(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:[]});return Ne(n,t)}function ID(n,e,t){let r=e._zod.def.checks;if(r&&r.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");let s=$t(e._zod.def,{get shape(){let a=e._zod.def.shape,l={...a};if(t)for(let c in t){if(!(c in a))throw new Error(`Unrecognized key: "${c}"`);t[c]&&(l[c]=n?new n({type:"optional",innerType:a[c]}):a[c])}else for(let c in a)l[c]=n?new n({type:"optional",innerType:a[c]}):a[c];return Xt(this,"shape",l),l},checks:[]});return Ne(e,s)}function TD(n,e,t){let i=$t(e._zod.def,{get shape(){let r=e._zod.def.shape,o={...r};if(t)for(let s in t){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);t[s]&&(o[s]=new n({type:"nonoptional",innerType:r[s]}))}else for(let s in r)o[s]=new n({type:"nonoptional",innerType:r[s]});return Xt(this,"shape",o),o}});return Ne(e,i)}function en(n,e=0){if(n.aborted===!0)return!0;for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function qe(n,e){return e.map(t=>{var i;return(i=t).path??(i.path=[]),t.path.unshift(n),t})}function Ai(n){return typeof n=="string"?n:n?.message}function je(n,e,t){let i={...n,path:n.path??[]};if(!n.message){let r=Ai(n.inst?._zod.def?.error?.(n))??Ai(e?.error?.(n))??Ai(t.customError?.(n))??Ai(t.localeError?.(n))??"Invalid input";i.message=r}return delete i.inst,delete i.continue,e?.reportInput||delete i.input,i}function Di(n){return n instanceof Set?"set":n instanceof Map?"map":n instanceof File?"file":"unknown"}function Pi(n){return Array.isArray(n)?"array":typeof n=="string"?"string":"unknown"}function T(n){let e=typeof n;switch(e){case"number":return Number.isNaN(n)?"nan":"number";case"object":{if(n===null)return"null";if(Array.isArray(n))return"array";let t=n;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&"constructor"in t&&t.constructor)return t.constructor.name}}return e}function ar(...n){let[e,t,i]=n;return typeof e=="string"?{message:e,code:"custom",input:t,inst:i}:{...e}}function ED(n){return Object.entries(n).filter(([e,t])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}function nk(n){let e=atob(n),t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);return t}function rk(n){let e="";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return btoa(e)}function AD(n){let e=n.replace(/-/g,"+").replace(/_/g,"/"),t="=".repeat((4-e.length%4)%4);return nk(e+t)}function OD(n){return rk(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function CD(n){let e=n.replace(/^0x/,"");if(e.length%2!==0)throw new Error("Invalid hex string length");let t=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)t[i/2]=Number.parseInt(e.slice(i,i+2),16);return t}function ND(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}var tk,Zs,Gd,_D,Ni,Hd,Xd,Qd,Kd,U=S(()=>{tk=Symbol("evaluating");Zs="captureStackTrace"in Error?Error.captureStackTrace:(...n)=>{};Gd=sr(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let n=Function;return new n(""),!0}catch{return!1}});_D=n=>{let e=typeof n;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(n)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(n)?"array":n===null?"null":n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?"promise":typeof Map<"u"&&n instanceof Map?"map":typeof Set<"u"&&n instanceof Set?"set":typeof Date<"u"&&n instanceof Date?"date":typeof File<"u"&&n instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},Ni=new Set(["string","number","symbol"]),Hd=new Set(["string","number","bigint","boolean","symbol","undefined"]);Xd={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]},Qd={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Kd=class{constructor(...e){}}});function Li(n,e=t=>t.message){let t={},i=[];for(let r of n.issues)r.path.length>0?(t[r.path[0]]=t[r.path[0]]||[],t[r.path[0]].push(e(r))):i.push(e(r));return{formErrors:i,fieldErrors:t}}function zi(n,e=t=>t.message){let t={_errors:[]},i=r=>{for(let o of r.issues)if(o.code==="invalid_union"&&o.errors.length)o.errors.map(s=>i({issues:s}));else if(o.code==="invalid_key")i({issues:o.issues});else if(o.code==="invalid_element")i({issues:o.issues});else if(o.path.length===0)t._errors.push(e(o));else{let s=t,a=0;for(;a<o.path.length;){let l=o.path[a];a===o.path.length-1?(s[l]=s[l]||{_errors:[]},s[l]._errors.push(e(o))):s[l]=s[l]||{_errors:[]},s=s[l],a++}}};return i(n),t}function ef(n,e=t=>t.message){let t={errors:[]},i=(r,o=[])=>{var s,a;for(let l of r.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(c=>i({issues:c},l.path));else if(l.code==="invalid_key")i({issues:l.issues},l.path);else if(l.code==="invalid_element")i({issues:l.issues},l.path);else{let c=[...o,...l.path];if(c.length===0){t.errors.push(e(l));continue}let u=t,d=0;for(;d<c.length;){let f=c[d],p=d===c.length-1;typeof f=="string"?(u.properties??(u.properties={}),(s=u.properties)[f]??(s[f]={errors:[]}),u=u.properties[f]):(u.items??(u.items=[]),(a=u.items)[f]??(a[f]={errors:[]}),u=u.items[f]),p&&u.errors.push(e(l)),d++}}};return i(n),t}function ok(n){let e=[],t=n.map(i=>typeof i=="object"?i.key:i);for(let i of t)typeof i=="number"?e.push(`[${i}]`):typeof i=="symbol"?e.push(`[${JSON.stringify(String(i))}]`):/[^\w$]/.test(i)?e.push(`[${JSON.stringify(i)}]`):(e.length&&e.push("."),e.push(i));return e.join("")}function tf(n){let e=[],t=[...n.issues].sort((i,r)=>(i.path??[]).length-(r.path??[]).length);for(let i of t)e.push(`\u2716 ${i.message}`),i.path?.length&&e.push(` \u2192 at ${ok(i.path)}`);return e.join(`
164
+ `)}var ik,Mi,Ue,nf=S(()=>{ir();U();ik=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),n.message=JSON.stringify(e,or,2),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},Mi=v("$ZodError",ik),Ue=v("$ZodError",ik,{Parent:Error})});var cr,Ks,lr,Vs,ur,rf,dr,of,Ws,PD,Gs,MD,Js,LD,Hs,zD,Ys,jD,Xs,UD,Qs,RD,ea,BD,sf=S(()=>{ir();nf();U();cr=n=>(e,t,i,r)=>{let o=i?Object.assign(i,{async:!1}):{async:!1},s=e._zod.run({value:t,issues:[]},o);if(s instanceof Promise)throw new at;if(s.issues.length){let a=new(r?.Err??n)(s.issues.map(l=>je(l,o,fe())));throw Zs(a,r?.callee),a}return s.value},Ks=cr(Ue),lr=n=>async(e,t,i,r)=>{let o=i?Object.assign(i,{async:!0}):{async:!0},s=e._zod.run({value:t,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let a=new(r?.Err??n)(s.issues.map(l=>je(l,o,fe())));throw Zs(a,r?.callee),a}return s.value},Vs=lr(Ue),ur=n=>(e,t,i)=>{let r=i?{...i,async:!1}:{async:!1},o=e._zod.run({value:t,issues:[]},r);if(o instanceof Promise)throw new at;return o.issues.length?{success:!1,error:new(n??Mi)(o.issues.map(s=>je(s,r,fe())))}:{success:!0,data:o.value}},rf=ur(Ue),dr=n=>async(e,t,i)=>{let r=i?Object.assign(i,{async:!0}):{async:!0},o=e._zod.run({value:t,issues:[]},r);return o instanceof Promise&&(o=await o),o.issues.length?{success:!1,error:new n(o.issues.map(s=>je(s,r,fe())))}:{success:!0,data:o.value}},of=dr(Ue),Ws=n=>(e,t,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return cr(n)(e,t,r)},PD=Ws(Ue),Gs=n=>(e,t,i)=>cr(n)(e,t,i),MD=Gs(Ue),Js=n=>async(e,t,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return lr(n)(e,t,r)},LD=Js(Ue),Hs=n=>async(e,t,i)=>lr(n)(e,t,i),zD=Hs(Ue),Ys=n=>(e,t,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return ur(n)(e,t,r)},jD=Ys(Ue),Xs=n=>(e,t,i)=>ur(n)(e,t,i),UD=Xs(Ue),Qs=n=>async(e,t,i)=>{let r=i?Object.assign(i,{direction:"backward"}):{direction:"backward"};return dr(n)(e,t,r)},RD=Qs(Ue),ea=n=>async(e,t,i)=>dr(n)(e,t,i),BD=ea(Ue)});var Ye={};we(Ye,{base64:()=>kf,base64url:()=>ta,bigint:()=>Ef,boolean:()=>Of,browserEmail:()=>JD,cidrv4:()=>wf,cidrv6:()=>bf,cuid:()=>af,cuid2:()=>cf,date:()=>$f,datetime:()=>If,domain:()=>XD,duration:()=>pf,e164:()=>Sf,email:()=>hf,emoji:()=>gf,extendedDuration:()=>FD,guid:()=>mf,hex:()=>QD,hostname:()=>YD,html5Email:()=>VD,idnEmail:()=>GD,integer:()=>Af,ipv4:()=>yf,ipv6:()=>vf,ksuid:()=>df,lowercase:()=>Df,mac:()=>_f,md5_base64:()=>tP,md5_base64url:()=>nP,md5_hex:()=>eP,nanoid:()=>ff,null:()=>Cf,number:()=>na,rfc5322Email:()=>WD,sha1_base64:()=>iP,sha1_base64url:()=>oP,sha1_hex:()=>rP,sha256_base64:()=>aP,sha256_base64url:()=>cP,sha256_hex:()=>sP,sha384_base64:()=>uP,sha384_base64url:()=>dP,sha384_hex:()=>lP,sha512_base64:()=>pP,sha512_base64url:()=>mP,sha512_hex:()=>fP,string:()=>Tf,time:()=>xf,ulid:()=>lf,undefined:()=>Nf,unicodeEmail:()=>sk,uppercase:()=>Pf,uuid:()=>Sn,uuid4:()=>qD,uuid6:()=>ZD,uuid7:()=>KD,xid:()=>uf});function gf(){return new RegExp(HD,"u")}function ck(n){let e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof n.precision=="number"?n.precision===-1?`${e}`:n.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${n.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function xf(n){return new RegExp(`^${ck(n)}$`)}function If(n){let e=ck({precision:n.precision}),t=["Z"];n.local&&t.push(""),n.offset&&t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let i=`${e}(?:${t.join("|")})`;return new RegExp(`^${ak}T(?:${i})$`)}function ji(n,e){return new RegExp(`^[A-Za-z0-9+/]{${n}}${e}$`)}function Ui(n){return new RegExp(`^[A-Za-z0-9_-]{${n}}$`)}var af,cf,lf,uf,df,ff,pf,FD,mf,Sn,qD,ZD,KD,hf,VD,WD,sk,GD,JD,HD,yf,vf,_f,wf,bf,kf,ta,YD,XD,Sf,ak,$f,Tf,Ef,Af,na,Of,Cf,Nf,Df,Pf,QD,eP,tP,nP,rP,iP,oP,sP,aP,cP,lP,uP,dP,fP,pP,mP,ra=S(()=>{U();af=/^[cC][^\s-]{8,}$/,cf=/^[0-9a-z]+$/,lf=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,uf=/^[0-9a-vA-V]{20}$/,df=/^[A-Za-z0-9]{27}$/,ff=/^[a-zA-Z0-9_-]{21}$/,pf=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,FD=/^[-+]?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)?)??$/,mf=/^([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})$/,Sn=n=>n?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,qD=Sn(4),ZD=Sn(6),KD=Sn(7),hf=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,VD=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,WD=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,sk=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,GD=sk,JD=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,HD="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";yf=/^(?:(?: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])$/,vf=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,_f=n=>{let e=He(n??":");return new RegExp(`^(?:[0-9A-F]{2}${e}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${e}){5}[0-9a-f]{2}$`)},wf=/^((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])$/,bf=/^(([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])$/,kf=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,ta=/^[A-Za-z0-9_-]*$/,YD=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,XD=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,Sf=/^\+[1-9]\d{6,14}$/,ak="(?:(?:\\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])))",$f=new RegExp(`^${ak}$`);Tf=n=>{let e=n?`[\\s\\S]{${n?.minimum??0},${n?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Ef=/^-?\d+n?$/,Af=/^-?\d+$/,na=/^-?\d+(?:\.\d+)?$/,Of=/^(?:true|false)$/i,Cf=/^null$/i,Nf=/^undefined$/i,Df=/^[^A-Z]*$/,Pf=/^[^a-z]*$/,QD=/^[0-9a-fA-F]*$/;eP=/^[0-9a-fA-F]{32}$/,tP=ji(22,"=="),nP=Ui(22),rP=/^[0-9a-fA-F]{40}$/,iP=ji(27,"="),oP=Ui(27),sP=/^[0-9a-fA-F]{64}$/,aP=ji(43,"="),cP=Ui(43),lP=/^[0-9a-fA-F]{96}$/,uP=ji(64,""),dP=Ui(64),fP=/^[0-9a-fA-F]{128}$/,pP=ji(86,"=="),mP=Ui(86)});function lk(n,e,t){n.issues.length&&e.issues.push(...qe(t,n.issues))}var oe,uk,ia,oa,Mf,Lf,zf,jf,Uf,Rf,Bf,Ff,qf,fr,Zf,Kf,Vf,Wf,Gf,Jf,Hf,Yf,Xf,sa=S(()=>{ir();ra();U();oe=v("$ZodCheck",(n,e)=>{var t;n._zod??(n._zod={}),n._zod.def=e,(t=n._zod).onattach??(t.onattach=[])}),uk={number:"number",bigint:"bigint",object:"date"},ia=v("$ZodCheckLessThan",(n,e)=>{oe.init(n,e);let t=uk[typeof e.value];n._zod.onattach.push(i=>{let r=i._zod.bag,o=(e.inclusive?r.maximum:r.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<o&&(e.inclusive?r.maximum=e.value:r.exclusiveMaximum=e.value)}),n._zod.check=i=>{(e.inclusive?i.value<=e.value:i.value<e.value)||i.issues.push({origin:t,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:i.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),oa=v("$ZodCheckGreaterThan",(n,e)=>{oe.init(n,e);let t=uk[typeof e.value];n._zod.onattach.push(i=>{let r=i._zod.bag,o=(e.inclusive?r.minimum:r.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>o&&(e.inclusive?r.minimum=e.value:r.exclusiveMinimum=e.value)}),n._zod.check=i=>{(e.inclusive?i.value>=e.value:i.value>e.value)||i.issues.push({origin:t,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:i.value,inclusive:e.inclusive,inst:n,continue:!e.abort})}}),Mf=v("$ZodCheckMultipleOf",(n,e)=>{oe.init(n,e),n._zod.onattach.push(t=>{var i;(i=t._zod.bag).multipleOf??(i.multipleOf=e.value)}),n._zod.check=t=>{if(typeof t.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof t.value=="bigint"?t.value%e.value===BigInt(0):Vd(t.value,e.value)===0)||t.issues.push({origin:typeof t.value,code:"not_multiple_of",divisor:e.value,input:t.value,inst:n,continue:!e.abort})}}),Lf=v("$ZodCheckNumberFormat",(n,e)=>{oe.init(n,e),e.format=e.format||"float64";let t=e.format?.includes("int"),i=t?"int":"number",[r,o]=Xd[e.format];n._zod.onattach.push(s=>{let a=s._zod.bag;a.format=e.format,a.minimum=r,a.maximum=o,t&&(a.pattern=Af)}),n._zod.check=s=>{let a=s.value;if(t){if(!Number.isInteger(a)){s.issues.push({expected:i,format:e.format,code:"invalid_type",continue:!1,input:a,inst:n});return}if(!Number.isSafeInteger(a)){a>0?s.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:i,inclusive:!0,continue:!e.abort}):s.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:n,origin:i,inclusive:!0,continue:!e.abort});return}}a<r&&s.issues.push({origin:"number",input:a,code:"too_small",minimum:r,inclusive:!0,inst:n,continue:!e.abort}),a>o&&s.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inclusive:!0,inst:n,continue:!e.abort})}}),zf=v("$ZodCheckBigIntFormat",(n,e)=>{oe.init(n,e);let[t,i]=Qd[e.format];n._zod.onattach.push(r=>{let o=r._zod.bag;o.format=e.format,o.minimum=t,o.maximum=i}),n._zod.check=r=>{let o=r.value;o<t&&r.issues.push({origin:"bigint",input:o,code:"too_small",minimum:t,inclusive:!0,inst:n,continue:!e.abort}),o>i&&r.issues.push({origin:"bigint",input:o,code:"too_big",maximum:i,inclusive:!0,inst:n,continue:!e.abort})}}),jf=v("$ZodCheckMaxSize",(n,e)=>{var t;oe.init(n,e),(t=n._zod.def).when??(t.when=i=>{let r=i.value;return!Yt(r)&&r.size!==void 0}),n._zod.onattach.push(i=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(i._zod.bag.maximum=e.maximum)}),n._zod.check=i=>{let r=i.value;r.size<=e.maximum||i.issues.push({origin:Di(r),code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:n,continue:!e.abort})}}),Uf=v("$ZodCheckMinSize",(n,e)=>{var t;oe.init(n,e),(t=n._zod.def).when??(t.when=i=>{let r=i.value;return!Yt(r)&&r.size!==void 0}),n._zod.onattach.push(i=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(i._zod.bag.minimum=e.minimum)}),n._zod.check=i=>{let r=i.value;r.size>=e.minimum||i.issues.push({origin:Di(r),code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:n,continue:!e.abort})}}),Rf=v("$ZodCheckSizeEquals",(n,e)=>{var t;oe.init(n,e),(t=n._zod.def).when??(t.when=i=>{let r=i.value;return!Yt(r)&&r.size!==void 0}),n._zod.onattach.push(i=>{let r=i._zod.bag;r.minimum=e.size,r.maximum=e.size,r.size=e.size}),n._zod.check=i=>{let r=i.value,o=r.size;if(o===e.size)return;let s=o>e.size;i.issues.push({origin:Di(r),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},inclusive:!0,exact:!0,input:i.value,inst:n,continue:!e.abort})}}),Bf=v("$ZodCheckMaxLength",(n,e)=>{var t;oe.init(n,e),(t=n._zod.def).when??(t.when=i=>{let r=i.value;return!Yt(r)&&r.length!==void 0}),n._zod.onattach.push(i=>{let r=i._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<r&&(i._zod.bag.maximum=e.maximum)}),n._zod.check=i=>{let r=i.value;if(r.length<=e.maximum)return;let s=Pi(r);i.issues.push({origin:s,code:"too_big",maximum:e.maximum,inclusive:!0,input:r,inst:n,continue:!e.abort})}}),Ff=v("$ZodCheckMinLength",(n,e)=>{var t;oe.init(n,e),(t=n._zod.def).when??(t.when=i=>{let r=i.value;return!Yt(r)&&r.length!==void 0}),n._zod.onattach.push(i=>{let r=i._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>r&&(i._zod.bag.minimum=e.minimum)}),n._zod.check=i=>{let r=i.value;if(r.length>=e.minimum)return;let s=Pi(r);i.issues.push({origin:s,code:"too_small",minimum:e.minimum,inclusive:!0,input:r,inst:n,continue:!e.abort})}}),qf=v("$ZodCheckLengthEquals",(n,e)=>{var t;oe.init(n,e),(t=n._zod.def).when??(t.when=i=>{let r=i.value;return!Yt(r)&&r.length!==void 0}),n._zod.onattach.push(i=>{let r=i._zod.bag;r.minimum=e.length,r.maximum=e.length,r.length=e.length}),n._zod.check=i=>{let r=i.value,o=r.length;if(o===e.length)return;let s=Pi(r),a=o>e.length;i.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:i.value,inst:n,continue:!e.abort})}}),fr=v("$ZodCheckStringFormat",(n,e)=>{var t,i;oe.init(n,e),n._zod.onattach.push(r=>{let o=r._zod.bag;o.format=e.format,e.pattern&&(o.patterns??(o.patterns=new Set),o.patterns.add(e.pattern))}),e.pattern?(t=n._zod).check??(t.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:e.format,input:r.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:n,continue:!e.abort})}):(i=n._zod).check??(i.check=()=>{})}),Zf=v("$ZodCheckRegex",(n,e)=>{fr.init(n,e),n._zod.check=t=>{e.pattern.lastIndex=0,!e.pattern.test(t.value)&&t.issues.push({origin:"string",code:"invalid_format",format:"regex",input:t.value,pattern:e.pattern.toString(),inst:n,continue:!e.abort})}}),Kf=v("$ZodCheckLowerCase",(n,e)=>{e.pattern??(e.pattern=Df),fr.init(n,e)}),Vf=v("$ZodCheckUpperCase",(n,e)=>{e.pattern??(e.pattern=Pf),fr.init(n,e)}),Wf=v("$ZodCheckIncludes",(n,e)=>{oe.init(n,e);let t=He(e.includes),i=new RegExp(typeof e.position=="number"?`^.{${e.position}}${t}`:t);e.pattern=i,n._zod.onattach.push(r=>{let o=r._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(i)}),n._zod.check=r=>{r.value.includes(e.includes,e.position)||r.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:r.value,inst:n,continue:!e.abort})}}),Gf=v("$ZodCheckStartsWith",(n,e)=>{oe.init(n,e);let t=new RegExp(`^${He(e.prefix)}.*`);e.pattern??(e.pattern=t),n._zod.onattach.push(i=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(t)}),n._zod.check=i=>{i.value.startsWith(e.prefix)||i.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:i.value,inst:n,continue:!e.abort})}}),Jf=v("$ZodCheckEndsWith",(n,e)=>{oe.init(n,e);let t=new RegExp(`.*${He(e.suffix)}$`);e.pattern??(e.pattern=t),n._zod.onattach.push(i=>{let r=i._zod.bag;r.patterns??(r.patterns=new Set),r.patterns.add(t)}),n._zod.check=i=>{i.value.endsWith(e.suffix)||i.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:i.value,inst:n,continue:!e.abort})}});Hf=v("$ZodCheckProperty",(n,e)=>{oe.init(n,e),n._zod.check=t=>{let i=e.schema._zod.run({value:t.value[e.property],issues:[]},{});if(i instanceof Promise)return i.then(r=>lk(r,t,e.property));lk(i,t,e.property)}}),Yf=v("$ZodCheckMimeType",(n,e)=>{oe.init(n,e);let t=new Set(e.mime);n._zod.onattach.push(i=>{i._zod.bag.mime=e.mime}),n._zod.check=i=>{t.has(i.value.type)||i.issues.push({code:"invalid_value",values:e.mime,input:i.value.type,inst:n,continue:!e.abort})}}),Xf=v("$ZodCheckOverwrite",(n,e)=>{oe.init(n,e),n._zod.check=t=>{t.value=e.tx(t.value)}})});var Ri,Qf=S(()=>{Ri=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 i=e.split(`
165
+ `).filter(s=>s),r=Math.min(...i.map(s=>s.length-s.trimStart().length)),o=i.map(s=>s.slice(r)).map(s=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.args,r=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...t,r.join(`
166
+ `))}}});var ep,tp=S(()=>{ep={major:4,minor:3,patch:6}});function Sp(n){if(n==="")return!0;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}function Sk(n){if(!ta.test(n))return!1;let e=n.replace(/[-_]/g,i=>i==="-"?"+":"/"),t=e.padEnd(Math.ceil(e.length/4)*4,"=");return Sp(t)}function $k(n,e=null){try{let t=n.split(".");if(t.length!==3)return!1;let[i]=t;if(!i)return!1;let r=JSON.parse(atob(i));return!("typ"in r&&r?.typ!=="JWT"||!r.alg||e&&(!("alg"in r)||r.alg!==e))}catch{return!1}}function fk(n,e,t){n.issues.length&&e.issues.push(...qe(t,n.issues)),e.value[t]=n.value}function da(n,e,t,i,r){if(n.issues.length){if(r&&!(t in i))return;e.issues.push(...qe(t,n.issues))}n.value===void 0?t in i&&(e.value[t]=void 0):e.value[t]=n.value}function xk(n){let e=Object.keys(n.shape);for(let i of e)if(!n.shape?.[i]?._zod?.traits?.has("$ZodType"))throw new Error(`Invalid element at key "${i}": expected a Zod schema`);let t=Yd(n.shape);return{...n,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(t)}}function Ik(n,e,t,i,r,o){let s=[],a=r.keySet,l=r.catchall._zod,c=l.def.type,u=l.optout==="optional";for(let d in e){if(a.has(d))continue;if(c==="never"){s.push(d);continue}let f=l.run({value:e[d],issues:[]},i);f instanceof Promise?n.push(f.then(p=>da(p,t,d,e,u))):da(f,t,d,e,u)}return s.length&&t.issues.push({code:"unrecognized_keys",keys:s,input:e,inst:o}),n.length?Promise.all(n).then(()=>t):t}function pk(n,e,t,i){for(let o of n)if(o.issues.length===0)return e.value=o.value,e;let r=n.filter(o=>!en(o));return r.length===1?(e.value=r[0].value,r[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(o=>o.issues.map(s=>je(s,i,fe())))}),e)}function mk(n,e,t,i){let r=n.filter(o=>o.issues.length===0);return r.length===1?(e.value=r[0].value,e):(r.length===0?e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:n.map(o=>o.issues.map(s=>je(s,i,fe())))}):e.issues.push({code:"invalid_union",input:e.value,inst:t,errors:[],inclusive:!1}),e)}function np(n,e){if(n===e)return{valid:!0,data:n};if(n instanceof Date&&e instanceof Date&&+n==+e)return{valid:!0,data:n};if(Qt(n)&&Qt(e)){let t=Object.keys(e),i=Object.keys(n).filter(o=>t.indexOf(o)!==-1),r={...n,...e};for(let o of i){let s=np(n[o],e[o]);if(!s.valid)return{valid:!1,mergeErrorPath:[o,...s.mergeErrorPath]};r[o]=s.data}return{valid:!0,data:r}}if(Array.isArray(n)&&Array.isArray(e)){if(n.length!==e.length)return{valid:!1,mergeErrorPath:[]};let t=[];for(let i=0;i<n.length;i++){let r=n[i],o=e[i],s=np(r,o);if(!s.valid)return{valid:!1,mergeErrorPath:[i,...s.mergeErrorPath]};t.push(s.data)}return{valid:!0,data:t}}return{valid:!1,mergeErrorPath:[]}}function hk(n,e,t){let i=new Map,r;for(let a of e.issues)if(a.code==="unrecognized_keys"){r??(r=a);for(let l of a.keys)i.has(l)||i.set(l,{}),i.get(l).l=!0}else n.issues.push(a);for(let a of t.issues)if(a.code==="unrecognized_keys")for(let l of a.keys)i.has(l)||i.set(l,{}),i.get(l).r=!0;else n.issues.push(a);let o=[...i].filter(([,a])=>a.l&&a.r).map(([a])=>a);if(o.length&&r&&n.issues.push({...r,keys:o}),en(n))return n;let s=np(e.value,t.value);if(!s.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(s.mergeErrorPath)}`);return n.value=s.data,n}function aa(n,e,t){n.issues.length&&e.issues.push(...qe(t,n.issues)),e.value[t]=n.value}function gk(n,e,t,i,r,o,s){n.issues.length&&(Ni.has(typeof i)?t.issues.push(...qe(i,n.issues)):t.issues.push({code:"invalid_key",origin:"map",input:r,inst:o,issues:n.issues.map(a=>je(a,s,fe()))})),e.issues.length&&(Ni.has(typeof i)?t.issues.push(...qe(i,e.issues)):t.issues.push({origin:"map",code:"invalid_element",input:r,inst:o,key:i,issues:e.issues.map(a=>je(a,s,fe()))})),t.value.set(n.value,e.value)}function yk(n,e){n.issues.length&&e.issues.push(...n.issues),e.value.add(n.value)}function vk(n,e){return n.issues.length&&e===void 0?{issues:[],value:void 0}:n}function _k(n,e){return n.value===void 0&&(n.value=e.defaultValue),n}function wk(n,e){return!n.issues.length&&n.value===void 0&&n.issues.push({code:"invalid_type",expected:"nonoptional",input:n.value,inst:e}),n}function ca(n,e,t){return n.issues.length?(n.aborted=!0,n):e._zod.run({value:n.value,issues:n.issues},t)}function la(n,e,t){if(n.issues.length)return n.aborted=!0,n;if((t.direction||"forward")==="forward"){let r=e.transform(n.value,n);return r instanceof Promise?r.then(o=>ua(n,o,e.out,t)):ua(n,r,e.out,t)}else{let r=e.reverseTransform(n.value,n);return r instanceof Promise?r.then(o=>ua(n,o,e.in,t)):ua(n,r,e.in,t)}}function ua(n,e,t,i){return n.issues.length?(n.aborted=!0,n):t._zod.run({value:e,issues:n.issues},i)}function bk(n){return n.value=Object.freeze(n.value),n}function kk(n,e,t,i){if(!n){let r={code:"custom",input:t,inst:i,path:[...i._zod.def.path??[]],continue:!i._zod.def.abort};i._zod.def.params&&(r.params=i._zod.def.params),e.issues.push(ar(r))}}var q,$n,re,rp,ip,op,sp,ap,cp,lp,up,dp,fp,pp,mp,hp,gp,yp,vp,_p,wp,bp,kp,$p,xp,Ip,Tp,Ep,fa,Ap,Bi,pa,Op,Cp,Np,Dp,Pp,Mp,Lp,zp,jp,Up,Tk,Rp,Fi,Bp,Fp,qp,ma,Zp,Kp,Vp,Wp,Gp,Jp,Hp,ha,Yp,Xp,Qp,em,tm,nm,rm,im,om,qi,sm,am,cm,lm,um,dm,fm=S(()=>{sa();ir();Qf();sf();ra();U();tp();U();q=v("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=ep;let i=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&i.unshift(n);for(let r of i)for(let o of r._zod.onattach)o(n);if(i.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let r=(s,a,l)=>{let c=en(s),u;for(let d of a){if(d._zod.def.when){if(!d._zod.def.when(s))continue}else if(c)continue;let f=s.issues.length,p=d._zod.check(s);if(p instanceof Promise&&l?.async===!1)throw new at;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==f&&(c||(c=en(s,f)))});else{if(s.issues.length===f)continue;c||(c=en(s,f))}}return u?u.then(()=>s):s},o=(s,a,l)=>{if(en(s))return s.aborted=!0,s;let c=r(a,i,l);if(c instanceof Promise){if(l.async===!1)throw new at;return c.then(u=>n._zod.parse(u,l))}return n._zod.parse(c,l)};n._zod.run=(s,a)=>{if(a.skipChecks)return n._zod.parse(s,a);if(a.direction==="backward"){let c=n._zod.parse({value:s.value,issues:[]},{...a,skipChecks:!0});return c instanceof Promise?c.then(u=>o(u,s,a)):o(c,s,a)}let l=n._zod.parse(s,a);if(l instanceof Promise){if(a.async===!1)throw new at;return l.then(c=>r(c,i,a))}return r(l,i,a)}}V(n,"~standard",()=>({validate:r=>{try{let o=rf(n,r);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return of(n,r).then(s=>s.success?{value:s.data}:{issues:s.error?.issues})}},vendor:"zod",version:1}))}),$n=v("$ZodString",(n,e)=>{q.init(n,e),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??Tf(n._zod.bag),n._zod.parse=(t,i)=>{if(e.coerce)try{t.value=String(t.value)}catch{}return typeof t.value=="string"||t.issues.push({expected:"string",code:"invalid_type",input:t.value,inst:n}),t}}),re=v("$ZodStringFormat",(n,e)=>{fr.init(n,e),$n.init(n,e)}),rp=v("$ZodGUID",(n,e)=>{e.pattern??(e.pattern=mf),re.init(n,e)}),ip=v("$ZodUUID",(n,e)=>{if(e.version){let i={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(i===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=Sn(i))}else e.pattern??(e.pattern=Sn());re.init(n,e)}),op=v("$ZodEmail",(n,e)=>{e.pattern??(e.pattern=hf),re.init(n,e)}),sp=v("$ZodURL",(n,e)=>{re.init(n,e),n._zod.check=t=>{try{let i=t.value.trim(),r=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(r.hostname)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:t.value,inst:n,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(r.protocol.endsWith(":")?r.protocol.slice(0,-1):r.protocol)||t.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:t.value,inst:n,continue:!e.abort})),e.normalize?t.value=r.href:t.value=i;return}catch{t.issues.push({code:"invalid_format",format:"url",input:t.value,inst:n,continue:!e.abort})}}}),ap=v("$ZodEmoji",(n,e)=>{e.pattern??(e.pattern=gf()),re.init(n,e)}),cp=v("$ZodNanoID",(n,e)=>{e.pattern??(e.pattern=ff),re.init(n,e)}),lp=v("$ZodCUID",(n,e)=>{e.pattern??(e.pattern=af),re.init(n,e)}),up=v("$ZodCUID2",(n,e)=>{e.pattern??(e.pattern=cf),re.init(n,e)}),dp=v("$ZodULID",(n,e)=>{e.pattern??(e.pattern=lf),re.init(n,e)}),fp=v("$ZodXID",(n,e)=>{e.pattern??(e.pattern=uf),re.init(n,e)}),pp=v("$ZodKSUID",(n,e)=>{e.pattern??(e.pattern=df),re.init(n,e)}),mp=v("$ZodISODateTime",(n,e)=>{e.pattern??(e.pattern=If(e)),re.init(n,e)}),hp=v("$ZodISODate",(n,e)=>{e.pattern??(e.pattern=$f),re.init(n,e)}),gp=v("$ZodISOTime",(n,e)=>{e.pattern??(e.pattern=xf(e)),re.init(n,e)}),yp=v("$ZodISODuration",(n,e)=>{e.pattern??(e.pattern=pf),re.init(n,e)}),vp=v("$ZodIPv4",(n,e)=>{e.pattern??(e.pattern=yf),re.init(n,e),n._zod.bag.format="ipv4"}),_p=v("$ZodIPv6",(n,e)=>{e.pattern??(e.pattern=vf),re.init(n,e),n._zod.bag.format="ipv6",n._zod.check=t=>{try{new URL(`http://[${t.value}]`)}catch{t.issues.push({code:"invalid_format",format:"ipv6",input:t.value,inst:n,continue:!e.abort})}}}),wp=v("$ZodMAC",(n,e)=>{e.pattern??(e.pattern=_f(e.delimiter)),re.init(n,e),n._zod.bag.format="mac"}),bp=v("$ZodCIDRv4",(n,e)=>{e.pattern??(e.pattern=wf),re.init(n,e)}),kp=v("$ZodCIDRv6",(n,e)=>{e.pattern??(e.pattern=bf),re.init(n,e),n._zod.check=t=>{let i=t.value.split("/");try{if(i.length!==2)throw new Error;let[r,o]=i;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://[${r}]`)}catch{t.issues.push({code:"invalid_format",format:"cidrv6",input:t.value,inst:n,continue:!e.abort})}}});$p=v("$ZodBase64",(n,e)=>{e.pattern??(e.pattern=kf),re.init(n,e),n._zod.bag.contentEncoding="base64",n._zod.check=t=>{Sp(t.value)||t.issues.push({code:"invalid_format",format:"base64",input:t.value,inst:n,continue:!e.abort})}});xp=v("$ZodBase64URL",(n,e)=>{e.pattern??(e.pattern=ta),re.init(n,e),n._zod.bag.contentEncoding="base64url",n._zod.check=t=>{Sk(t.value)||t.issues.push({code:"invalid_format",format:"base64url",input:t.value,inst:n,continue:!e.abort})}}),Ip=v("$ZodE164",(n,e)=>{e.pattern??(e.pattern=Sf),re.init(n,e)});Tp=v("$ZodJWT",(n,e)=>{re.init(n,e),n._zod.check=t=>{$k(t.value,e.alg)||t.issues.push({code:"invalid_format",format:"jwt",input:t.value,inst:n,continue:!e.abort})}}),Ep=v("$ZodCustomStringFormat",(n,e)=>{re.init(n,e),n._zod.check=t=>{e.fn(t.value)||t.issues.push({code:"invalid_format",format:e.format,input:t.value,inst:n,continue:!e.abort})}}),fa=v("$ZodNumber",(n,e)=>{q.init(n,e),n._zod.pattern=n._zod.bag.pattern??na,n._zod.parse=(t,i)=>{if(e.coerce)try{t.value=Number(t.value)}catch{}let r=t.value;if(typeof r=="number"&&!Number.isNaN(r)&&Number.isFinite(r))return t;let o=typeof r=="number"?Number.isNaN(r)?"NaN":Number.isFinite(r)?void 0:"Infinity":void 0;return t.issues.push({expected:"number",code:"invalid_type",input:r,inst:n,...o?{received:o}:{}}),t}}),Ap=v("$ZodNumberFormat",(n,e)=>{Lf.init(n,e),fa.init(n,e)}),Bi=v("$ZodBoolean",(n,e)=>{q.init(n,e),n._zod.pattern=Of,n._zod.parse=(t,i)=>{if(e.coerce)try{t.value=!!t.value}catch{}let r=t.value;return typeof r=="boolean"||t.issues.push({expected:"boolean",code:"invalid_type",input:r,inst:n}),t}}),pa=v("$ZodBigInt",(n,e)=>{q.init(n,e),n._zod.pattern=Ef,n._zod.parse=(t,i)=>{if(e.coerce)try{t.value=BigInt(t.value)}catch{}return typeof t.value=="bigint"||t.issues.push({expected:"bigint",code:"invalid_type",input:t.value,inst:n}),t}}),Op=v("$ZodBigIntFormat",(n,e)=>{zf.init(n,e),pa.init(n,e)}),Cp=v("$ZodSymbol",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;return typeof r=="symbol"||t.issues.push({expected:"symbol",code:"invalid_type",input:r,inst:n}),t}}),Np=v("$ZodUndefined",(n,e)=>{q.init(n,e),n._zod.pattern=Nf,n._zod.values=new Set([void 0]),n._zod.optin="optional",n._zod.optout="optional",n._zod.parse=(t,i)=>{let r=t.value;return typeof r>"u"||t.issues.push({expected:"undefined",code:"invalid_type",input:r,inst:n}),t}}),Dp=v("$ZodNull",(n,e)=>{q.init(n,e),n._zod.pattern=Cf,n._zod.values=new Set([null]),n._zod.parse=(t,i)=>{let r=t.value;return r===null||t.issues.push({expected:"null",code:"invalid_type",input:r,inst:n}),t}}),Pp=v("$ZodAny",(n,e)=>{q.init(n,e),n._zod.parse=t=>t}),Mp=v("$ZodUnknown",(n,e)=>{q.init(n,e),n._zod.parse=t=>t}),Lp=v("$ZodNever",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)}),zp=v("$ZodVoid",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;return typeof r>"u"||t.issues.push({expected:"void",code:"invalid_type",input:r,inst:n}),t}}),jp=v("$ZodDate",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{if(e.coerce)try{t.value=new Date(t.value)}catch{}let r=t.value,o=r instanceof Date;return o&&!Number.isNaN(r.getTime())||t.issues.push({expected:"date",code:"invalid_type",input:r,...o?{received:"Invalid Date"}:{},inst:n}),t}});Up=v("$ZodArray",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;if(!Array.isArray(r))return t.issues.push({expected:"array",code:"invalid_type",input:r,inst:n}),t;t.value=Array(r.length);let o=[];for(let s=0;s<r.length;s++){let a=r[s],l=e.element._zod.run({value:a,issues:[]},i);l instanceof Promise?o.push(l.then(c=>fk(c,t,s))):fk(l,t,s)}return o.length?Promise.all(o).then(()=>t):t}});Tk=v("$ZodObject",(n,e)=>{if(q.init(n,e),!Object.getOwnPropertyDescriptor(e,"shape")?.get){let a=e.shape;Object.defineProperty(e,"shape",{get:()=>{let l={...a};return Object.defineProperty(e,"shape",{value:l}),l}})}let i=sr(()=>xk(e));V(n._zod,"propValues",()=>{let a=e.shape,l={};for(let c in a){let u=a[c]._zod;if(u.values){l[c]??(l[c]=new Set);for(let d of u.values)l[c].add(d)}}return l});let r=kn,o=e.catchall,s;n._zod.parse=(a,l)=>{s??(s=i.value);let c=a.value;if(!r(c))return a.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),a;a.value={};let u=[],d=s.shape;for(let f of s.keys){let p=d[f],h=p._zod.optout==="optional",m=p._zod.run({value:c[f],issues:[]},l);m instanceof Promise?u.push(m.then(y=>da(y,a,f,c,h))):da(m,a,f,c,h)}return o?Ik(u,c,a,l,i.value,n):u.length?Promise.all(u).then(()=>a):a}}),Rp=v("$ZodObjectJIT",(n,e)=>{Tk.init(n,e);let t=n._zod.parse,i=sr(()=>xk(e)),r=f=>{let p=new Ri(["shape","payload","ctx"]),h=i.value,m=k=>{let O=qs(k);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};p.write("const input = payload.value;");let y=Object.create(null),_=0;for(let k of h.keys)y[k]=`key_${_++}`;p.write("const newResult = {};");for(let k of h.keys){let O=y[k],A=qs(k),L=f[k]?._zod?.optout==="optional";p.write(`const ${O} = ${m(k)};`),L?p.write(`
167
+ if (${O}.issues.length) {
168
+ if (${A} in input) {
169
+ payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
170
+ ...iss,
171
+ path: iss.path ? [${A}, ...iss.path] : [${A}]
172
+ })));
173
+ }
174
+ }
175
+
176
+ if (${O}.value === undefined) {
177
+ if (${A} in input) {
178
+ newResult[${A}] = undefined;
179
+ }
180
+ } else {
181
+ newResult[${A}] = ${O}.value;
182
+ }
183
+
184
+ `):p.write(`
185
+ if (${O}.issues.length) {
186
+ payload.issues = payload.issues.concat(${O}.issues.map(iss => ({
187
+ ...iss,
188
+ path: iss.path ? [${A}, ...iss.path] : [${A}]
189
+ })));
190
+ }
191
+
192
+ if (${O}.value === undefined) {
193
+ if (${A} in input) {
194
+ newResult[${A}] = undefined;
195
+ }
196
+ } else {
197
+ newResult[${A}] = ${O}.value;
198
+ }
199
+
200
+ `)}p.write("payload.value = newResult;"),p.write("return payload;");let b=p.compile();return(k,O)=>b(f,k,O)},o,s=kn,a=!Ei.jitless,c=a&&Gd.value,u=e.catchall,d;n._zod.parse=(f,p)=>{d??(d=i.value);let h=f.value;return s(h)?a&&c&&p?.async===!1&&p.jitless!==!0?(o||(o=r(e.shape)),f=o(f,p),u?Ik([],h,f,p,d,n):f):t(f,p):(f.issues.push({expected:"object",code:"invalid_type",input:h,inst:n}),f)}});Fi=v("$ZodUnion",(n,e)=>{q.init(n,e),V(n._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),V(n._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),V(n._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),V(n._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(o=>o._zod.pattern);return new RegExp(`^(${r.map(o=>Ci(o.source)).join("|")})$`)}});let t=e.options.length===1,i=e.options[0]._zod.run;n._zod.parse=(r,o)=>{if(t)return i(r,o);let s=!1,a=[];for(let l of e.options){let c=l._zod.run({value:r.value,issues:[]},o);if(c instanceof Promise)a.push(c),s=!0;else{if(c.issues.length===0)return c;a.push(c)}}return s?Promise.all(a).then(l=>pk(l,r,n,o)):pk(a,r,n,o)}});Bp=v("$ZodXor",(n,e)=>{Fi.init(n,e),e.inclusive=!1;let t=e.options.length===1,i=e.options[0]._zod.run;n._zod.parse=(r,o)=>{if(t)return i(r,o);let s=!1,a=[];for(let l of e.options){let c=l._zod.run({value:r.value,issues:[]},o);c instanceof Promise?(a.push(c),s=!0):a.push(c)}return s?Promise.all(a).then(l=>mk(l,r,n,o)):mk(a,r,n,o)}}),Fp=v("$ZodDiscriminatedUnion",(n,e)=>{e.inclusive=!1,Fi.init(n,e);let t=n._zod.parse;V(n._zod,"propValues",()=>{let r={};for(let o of e.options){let s=o._zod.propValues;if(!s||Object.keys(s).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,l]of Object.entries(s)){r[a]||(r[a]=new Set);for(let c of l)r[a].add(c)}}return r});let i=sr(()=>{let r=e.options,o=new Map;for(let s of r){let a=s._zod.propValues?.[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let l of a){if(o.has(l))throw new Error(`Duplicate discriminator value "${String(l)}"`);o.set(l,s)}}return o});n._zod.parse=(r,o)=>{let s=r.value;if(!kn(s))return r.issues.push({code:"invalid_type",expected:"object",input:s,inst:n}),r;let a=i.value.get(s?.[e.discriminator]);return a?a._zod.run(r,o):e.unionFallback?t(r,o):(r.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:e.discriminator,input:s,path:[e.discriminator],inst:n}),r)}}),qp=v("$ZodIntersection",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value,o=e.left._zod.run({value:r,issues:[]},i),s=e.right._zod.run({value:r,issues:[]},i);return o instanceof Promise||s instanceof Promise?Promise.all([o,s]).then(([l,c])=>hk(t,l,c)):hk(t,o,s)}});ma=v("$ZodTuple",(n,e)=>{q.init(n,e);let t=e.items;n._zod.parse=(i,r)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:n,expected:"tuple",code:"invalid_type"}),i;i.value=[];let s=[],a=[...t].reverse().findIndex(u=>u._zod.optin!=="optional"),l=a===-1?0:t.length-a;if(!e.rest){let u=o.length>t.length,d=o.length<l-1;if(u||d)return i.issues.push({...u?{code:"too_big",maximum:t.length,inclusive:!0}:{code:"too_small",minimum:t.length},input:o,inst:n,origin:"array"}),i}let c=-1;for(let u of t){if(c++,c>=o.length&&c>=l)continue;let d=u._zod.run({value:o[c],issues:[]},r);d instanceof Promise?s.push(d.then(f=>aa(f,i,c))):aa(d,i,c)}if(e.rest){let u=o.slice(t.length);for(let d of u){c++;let f=e.rest._zod.run({value:d,issues:[]},r);f instanceof Promise?s.push(f.then(p=>aa(p,i,c))):aa(f,i,c)}}return s.length?Promise.all(s).then(()=>i):i}});Zp=v("$ZodRecord",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;if(!Qt(r))return t.issues.push({expected:"record",code:"invalid_type",input:r,inst:n}),t;let o=[],s=e.keyType._zod.values;if(s){t.value={};let a=new Set;for(let c of s)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){a.add(typeof c=="number"?c.toString():c);let u=e.valueType._zod.run({value:r[c],issues:[]},i);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&t.issues.push(...qe(c,d.issues)),t.value[c]=d.value})):(u.issues.length&&t.issues.push(...qe(c,u.issues)),t.value[c]=u.value)}let l;for(let c in r)a.has(c)||(l=l??[],l.push(c));l&&l.length>0&&t.issues.push({code:"unrecognized_keys",input:r,inst:n,keys:l})}else{t.value={};for(let a of Reflect.ownKeys(r)){if(a==="__proto__")continue;let l=e.keyType._zod.run({value:a,issues:[]},i);if(l instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof a=="string"&&na.test(a)&&l.issues.length){let d=e.keyType._zod.run({value:Number(a),issues:[]},i);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(l=d)}if(l.issues.length){e.mode==="loose"?t.value[a]=r[a]:t.issues.push({code:"invalid_key",origin:"record",issues:l.issues.map(d=>je(d,i,fe())),input:a,path:[a],inst:n});continue}let u=e.valueType._zod.run({value:r[a],issues:[]},i);u instanceof Promise?o.push(u.then(d=>{d.issues.length&&t.issues.push(...qe(a,d.issues)),t.value[l.value]=d.value})):(u.issues.length&&t.issues.push(...qe(a,u.issues)),t.value[l.value]=u.value)}}return o.length?Promise.all(o).then(()=>t):t}}),Kp=v("$ZodMap",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;if(!(r instanceof Map))return t.issues.push({expected:"map",code:"invalid_type",input:r,inst:n}),t;let o=[];t.value=new Map;for(let[s,a]of r){let l=e.keyType._zod.run({value:s,issues:[]},i),c=e.valueType._zod.run({value:a,issues:[]},i);l instanceof Promise||c instanceof Promise?o.push(Promise.all([l,c]).then(([u,d])=>{gk(u,d,t,s,r,n,i)})):gk(l,c,t,s,r,n,i)}return o.length?Promise.all(o).then(()=>t):t}});Vp=v("$ZodSet",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;if(!(r instanceof Set))return t.issues.push({input:r,inst:n,expected:"set",code:"invalid_type"}),t;let o=[];t.value=new Set;for(let s of r){let a=e.valueType._zod.run({value:s,issues:[]},i);a instanceof Promise?o.push(a.then(l=>yk(l,t))):yk(a,t)}return o.length?Promise.all(o).then(()=>t):t}});Wp=v("$ZodEnum",(n,e)=>{q.init(n,e);let t=Oi(e.entries),i=new Set(t);n._zod.values=i,n._zod.pattern=new RegExp(`^(${t.filter(r=>Ni.has(typeof r)).map(r=>typeof r=="string"?He(r):r.toString()).join("|")})$`),n._zod.parse=(r,o)=>{let s=r.value;return i.has(s)||r.issues.push({code:"invalid_value",values:t,input:s,inst:n}),r}}),Gp=v("$ZodLiteral",(n,e)=>{if(q.init(n,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");let t=new Set(e.values);n._zod.values=t,n._zod.pattern=new RegExp(`^(${e.values.map(i=>typeof i=="string"?He(i):i?He(i.toString()):String(i)).join("|")})$`),n._zod.parse=(i,r)=>{let o=i.value;return t.has(o)||i.issues.push({code:"invalid_value",values:e.values,input:o,inst:n}),i}}),Jp=v("$ZodFile",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{let r=t.value;return r instanceof File||t.issues.push({expected:"file",code:"invalid_type",input:r,inst:n}),t}}),Hp=v("$ZodTransform",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{if(i.direction==="backward")throw new Ht(n.constructor.name);let r=e.transform(t.value,t);if(i.async)return(r instanceof Promise?r:Promise.resolve(r)).then(s=>(t.value=s,t));if(r instanceof Promise)throw new at;return t.value=r,t}});ha=v("$ZodOptional",(n,e)=>{q.init(n,e),n._zod.optin="optional",n._zod.optout="optional",V(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),V(n._zod,"pattern",()=>{let t=e.innerType._zod.pattern;return t?new RegExp(`^(${Ci(t.source)})?$`):void 0}),n._zod.parse=(t,i)=>{if(e.innerType._zod.optin==="optional"){let r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(o=>vk(o,t.value)):vk(r,t.value)}return t.value===void 0?t:e.innerType._zod.run(t,i)}}),Yp=v("$ZodExactOptional",(n,e)=>{ha.init(n,e),V(n._zod,"values",()=>e.innerType._zod.values),V(n._zod,"pattern",()=>e.innerType._zod.pattern),n._zod.parse=(t,i)=>e.innerType._zod.run(t,i)}),Xp=v("$ZodNullable",(n,e)=>{q.init(n,e),V(n._zod,"optin",()=>e.innerType._zod.optin),V(n._zod,"optout",()=>e.innerType._zod.optout),V(n._zod,"pattern",()=>{let t=e.innerType._zod.pattern;return t?new RegExp(`^(${Ci(t.source)}|null)$`):void 0}),V(n._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),n._zod.parse=(t,i)=>t.value===null?t:e.innerType._zod.run(t,i)}),Qp=v("$ZodDefault",(n,e)=>{q.init(n,e),n._zod.optin="optional",V(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,i)=>{if(i.direction==="backward")return e.innerType._zod.run(t,i);if(t.value===void 0)return t.value=e.defaultValue,t;let r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(o=>_k(o,e)):_k(r,e)}});em=v("$ZodPrefault",(n,e)=>{q.init(n,e),n._zod.optin="optional",V(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,i)=>(i.direction==="backward"||t.value===void 0&&(t.value=e.defaultValue),e.innerType._zod.run(t,i))}),tm=v("$ZodNonOptional",(n,e)=>{q.init(n,e),V(n._zod,"values",()=>{let t=e.innerType._zod.values;return t?new Set([...t].filter(i=>i!==void 0)):void 0}),n._zod.parse=(t,i)=>{let r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(o=>wk(o,n)):wk(r,n)}});nm=v("$ZodSuccess",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>{if(i.direction==="backward")throw new Ht("ZodSuccess");let r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(o=>(t.value=o.issues.length===0,t)):(t.value=r.issues.length===0,t)}}),rm=v("$ZodCatch",(n,e)=>{q.init(n,e),V(n._zod,"optin",()=>e.innerType._zod.optin),V(n._zod,"optout",()=>e.innerType._zod.optout),V(n._zod,"values",()=>e.innerType._zod.values),n._zod.parse=(t,i)=>{if(i.direction==="backward")return e.innerType._zod.run(t,i);let r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(o=>(t.value=o.value,o.issues.length&&(t.value=e.catchValue({...t,error:{issues:o.issues.map(s=>je(s,i,fe()))},input:t.value}),t.issues=[]),t)):(t.value=r.value,r.issues.length&&(t.value=e.catchValue({...t,error:{issues:r.issues.map(o=>je(o,i,fe()))},input:t.value}),t.issues=[]),t)}}),im=v("$ZodNaN",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>((typeof t.value!="number"||!Number.isNaN(t.value))&&t.issues.push({input:t.value,inst:n,expected:"nan",code:"invalid_type"}),t)}),om=v("$ZodPipe",(n,e)=>{q.init(n,e),V(n._zod,"values",()=>e.in._zod.values),V(n._zod,"optin",()=>e.in._zod.optin),V(n._zod,"optout",()=>e.out._zod.optout),V(n._zod,"propValues",()=>e.in._zod.propValues),n._zod.parse=(t,i)=>{if(i.direction==="backward"){let o=e.out._zod.run(t,i);return o instanceof Promise?o.then(s=>ca(s,e.in,i)):ca(o,e.in,i)}let r=e.in._zod.run(t,i);return r instanceof Promise?r.then(o=>ca(o,e.out,i)):ca(r,e.out,i)}});qi=v("$ZodCodec",(n,e)=>{q.init(n,e),V(n._zod,"values",()=>e.in._zod.values),V(n._zod,"optin",()=>e.in._zod.optin),V(n._zod,"optout",()=>e.out._zod.optout),V(n._zod,"propValues",()=>e.in._zod.propValues),n._zod.parse=(t,i)=>{if((i.direction||"forward")==="forward"){let o=e.in._zod.run(t,i);return o instanceof Promise?o.then(s=>la(s,e,i)):la(o,e,i)}else{let o=e.out._zod.run(t,i);return o instanceof Promise?o.then(s=>la(s,e,i)):la(o,e,i)}}});sm=v("$ZodReadonly",(n,e)=>{q.init(n,e),V(n._zod,"propValues",()=>e.innerType._zod.propValues),V(n._zod,"values",()=>e.innerType._zod.values),V(n._zod,"optin",()=>e.innerType?._zod?.optin),V(n._zod,"optout",()=>e.innerType?._zod?.optout),n._zod.parse=(t,i)=>{if(i.direction==="backward")return e.innerType._zod.run(t,i);let r=e.innerType._zod.run(t,i);return r instanceof Promise?r.then(bk):bk(r)}});am=v("$ZodTemplateLiteral",(n,e)=>{q.init(n,e);let t=[];for(let i of e.parts)if(typeof i=="object"&&i!==null){if(!i._zod.pattern)throw new Error(`Invalid template literal part, no pattern found: ${[...i._zod.traits].shift()}`);let r=i._zod.pattern instanceof RegExp?i._zod.pattern.source:i._zod.pattern;if(!r)throw new Error(`Invalid template literal part: ${i._zod.traits}`);let o=r.startsWith("^")?1:0,s=r.endsWith("$")?r.length-1:r.length;t.push(r.slice(o,s))}else if(i===null||Hd.has(typeof i))t.push(He(`${i}`));else throw new Error(`Invalid template literal part: ${i}`);n._zod.pattern=new RegExp(`^${t.join("")}$`),n._zod.parse=(i,r)=>typeof i.value!="string"?(i.issues.push({input:i.value,inst:n,expected:"string",code:"invalid_type"}),i):(n._zod.pattern.lastIndex=0,n._zod.pattern.test(i.value)||i.issues.push({input:i.value,inst:n,code:"invalid_format",format:e.format??"template_literal",pattern:n._zod.pattern.source}),i)}),cm=v("$ZodFunction",(n,e)=>(q.init(n,e),n._def=e,n._zod.def=e,n.implement=t=>{if(typeof t!="function")throw new Error("implement() must be called with a function");return function(...i){let r=n._def.input?Ks(n._def.input,i):i,o=Reflect.apply(t,this,r);return n._def.output?Ks(n._def.output,o):o}},n.implementAsync=t=>{if(typeof t!="function")throw new Error("implementAsync() must be called with a function");return async function(...i){let r=n._def.input?await Vs(n._def.input,i):i,o=await Reflect.apply(t,this,r);return n._def.output?await Vs(n._def.output,o):o}},n._zod.parse=(t,i)=>typeof t.value!="function"?(t.issues.push({code:"invalid_type",expected:"function",input:t.value,inst:n}),t):(n._def.output&&n._def.output._zod.def.type==="promise"?t.value=n.implementAsync(t.value):t.value=n.implement(t.value),t),n.input=(...t)=>{let i=n.constructor;return Array.isArray(t[0])?new i({type:"function",input:new ma({type:"tuple",items:t[0],rest:t[1]}),output:n._def.output}):new i({type:"function",input:t[0],output:n._def.output})},n.output=t=>{let i=n.constructor;return new i({type:"function",input:n._def.input,output:t})},n)),lm=v("$ZodPromise",(n,e)=>{q.init(n,e),n._zod.parse=(t,i)=>Promise.resolve(t.value).then(r=>e.innerType._zod.run({value:r,issues:[]},i))}),um=v("$ZodLazy",(n,e)=>{q.init(n,e),V(n._zod,"innerType",()=>e.getter()),V(n._zod,"pattern",()=>n._zod.innerType?._zod?.pattern),V(n._zod,"propValues",()=>n._zod.innerType?._zod?.propValues),V(n._zod,"optin",()=>n._zod.innerType?._zod?.optin??void 0),V(n._zod,"optout",()=>n._zod.innerType?._zod?.optout??void 0),n._zod.parse=(t,i)=>n._zod.innerType._zod.run(t,i)}),dm=v("$ZodCustom",(n,e)=>{oe.init(n,e),q.init(n,e),n._zod.parse=(t,i)=>t,n._zod.check=t=>{let i=t.value,r=e.fn(i);if(r instanceof Promise)return r.then(o=>kk(o,t,i,n));kk(r,t,i,n)}})});function Ek(){return{localeError:gP()}}var gP,Ak=S(()=>{U();gP=()=>{let n={string:{unit:"\u062D\u0631\u0641",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},file:{unit:"\u0628\u0627\u064A\u062A",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},array:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"},set:{unit:"\u0639\u0646\u0635\u0631",verb:"\u0623\u0646 \u064A\u062D\u0648\u064A"}};function e(r){return n[r]??null}let t={regex:"\u0645\u062F\u062E\u0644",email:"\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",url:"\u0631\u0627\u0628\u0637",emoji:"\u0625\u064A\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",date:"\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",time:"\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",duration:"\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",ipv4:"\u0639\u0646\u0648\u0627\u0646 IPv4",ipv6:"\u0639\u0646\u0648\u0627\u0646 IPv6",cidrv4:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",cidrv6:"\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",base64:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",base64url:"\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",json_string:"\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",e164:"\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",jwt:"JWT",template_literal:"\u0645\u062F\u062E\u0644"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${r.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`:`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${o}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${a}`}case"invalid_value":return r.values.length===1?`\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${x(r.values[0])}`:`\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${r.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"}`:`\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${r.origin??"\u0627\u0644\u0642\u064A\u0645\u0629"} ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${r.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${r.minimum.toString()} ${s.unit}`:`\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${r.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${r.prefix}"`:o.format==="ends_with"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${o.suffix}"`:o.format==="includes"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${o.includes}"`:o.format==="regex"?`\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${o.pattern}`:`${t[o.format]??r.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`}case"not_multiple_of":return`\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${r.divisor}`;case"unrecognized_keys":return`\u0645\u0639\u0631\u0641${r.keys.length>1?"\u0627\u062A":""} \u063A\u0631\u064A\u0628${r.keys.length>1?"\u0629":""}: ${w(r.keys,"\u060C ")}`;case"invalid_key":return`\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${r.origin}`;case"invalid_union":return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";case"invalid_element":return`\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${r.origin}`;default:return"\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644"}}}});function Ok(){return{localeError:yP()}}var yP,Ck=S(()=>{U();yP=()=>{let n={string:{unit:"simvol",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"element",verb:"olmal\u0131d\u0131r"},set:{unit:"element",verb:"olmal\u0131d\u0131r"}};function e(r){return n[r]??null}let t={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"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${r.expected}, daxil olan ${a}`:`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${o}, daxil olan ${a}`}case"invalid_value":return r.values.length===1?`Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${x(r.values[0])}`:`Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${r.origin??"d\u0259y\u0259r"} ${o}${r.maximum.toString()} ${s.unit??"element"}`:`\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${r.origin??"d\u0259y\u0259r"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${r.origin} ${o}${r.minimum.toString()} ${s.unit}`:`\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Yanl\u0131\u015F m\u0259tn: "${o.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`:o.format==="ends_with"?`Yanl\u0131\u015F m\u0259tn: "${o.suffix}" il\u0259 bitm\u0259lidir`:o.format==="includes"?`Yanl\u0131\u015F m\u0259tn: "${o.includes}" daxil olmal\u0131d\u0131r`:o.format==="regex"?`Yanl\u0131\u015F m\u0259tn: ${o.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`:`Yanl\u0131\u015F ${t[o.format]??r.format}`}case"not_multiple_of":return`Yanl\u0131\u015F \u0259d\u0259d: ${r.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;case"unrecognized_keys":return`Tan\u0131nmayan a\xE7ar${r.keys.length>1?"lar":""}: ${w(r.keys,", ")}`;case"invalid_key":return`${r.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;case"invalid_union":return"Yanl\u0131\u015F d\u0259y\u0259r";case"invalid_element":return`${r.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;default:return"Yanl\u0131\u015F d\u0259y\u0259r"}}}});function Nk(n,e,t,i){let r=Math.abs(n),o=r%10,s=r%100;return s>=11&&s<=19?i:o===1?e:o>=2&&o<=4?t:i}function Dk(){return{localeError:vP()}}var vP,Pk=S(()=>{U();vP=()=>{let n={string:{unit:{one:"\u0441\u0456\u043C\u0432\u0430\u043B",few:"\u0441\u0456\u043C\u0432\u0430\u043B\u044B",many:"\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u044B",many:"\u0431\u0430\u0439\u0442\u0430\u045E"},verb:"\u043C\u0435\u0446\u044C"}};function e(r){return n[r]??null}let t={regex:"\u0443\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0430\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0447\u0430\u0441",duration:"ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0430\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0430\u0441",cidrv4:"IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",base64:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",base64url:"\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",json_string:"JSON \u0440\u0430\u0434\u043E\u043A",e164:"\u043D\u0443\u043C\u0430\u0440 E.164",jwt:"JWT",template_literal:"\u0443\u0432\u043E\u0434"},i={nan:"NaN",number:"\u043B\u0456\u043A",array:"\u043C\u0430\u0441\u0456\u045E"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${r.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${o}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${x(r.values[0])}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);if(s){let a=Number(r.maximum),l=Nk(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${o}${r.maximum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);if(s){let a=Number(r.minimum),l=Nk(a,s.unit.one,s.unit.few,s.unit.many);return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${s.verb} ${o}${r.minimum.toString()} ${l}`}return`\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${r.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${t[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${r.keys.length>1?"\u043A\u043B\u044E\u0447\u044B":"\u043A\u043B\u044E\u0447"}: ${w(r.keys,", ")}`;case"invalid_key":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${r.origin}`;case"invalid_union":return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";case"invalid_element":return`\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${r.origin}`;default:return"\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434"}}}});function Mk(){return{localeError:_P()}}var _P,Lk=S(()=>{U();_P=()=>{let n={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},file:{unit:"\u0431\u0430\u0439\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430",verb:"\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430"}};function e(r){return n[r]??null}let t={regex:"\u0432\u0445\u043E\u0434",email:"\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0436\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",base64url:"base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",json_string:"JSON \u043D\u0438\u0437",e164:"E.164 \u043D\u043E\u043C\u0435\u0440",jwt:"JWT",template_literal:"\u0432\u0445\u043E\u0434"},i={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${r.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${o}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${x(r.values[0])}`:`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${o}${r.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin??"\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${o}${r.minimum.toString()} ${s.unit}`:`\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${r.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;if(o.format==="starts_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${o.prefix}"`;if(o.format==="ends_with")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${o.suffix}"`;if(o.format==="includes")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${o.includes}"`;if(o.format==="regex")return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${o.pattern}`;let s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";return o.format==="emoji"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),o.format==="datetime"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),o.format==="date"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),o.format==="time"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E"),o.format==="duration"&&(s="\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430"),`${s} ${t[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${r.keys.length>1?"\u0438":""} \u043A\u043B\u044E\u0447${r.keys.length>1?"\u043E\u0432\u0435":""}: ${w(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";case"invalid_element":return`\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${r.origin}`;default:return"\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434"}}}});function zk(){return{localeError:wP()}}var wP,jk=S(()=>{U();wP=()=>{let n={string:{unit:"car\xE0cters",verb:"contenir"},file:{unit:"bytes",verb:"contenir"},array:{unit:"elements",verb:"contenir"},set:{unit:"elements",verb:"contenir"}};function e(r){return n[r]??null}let t={regex:"entrada",email:"adre\xE7a electr\xF2nica",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:"data i hora ISO",date:"data ISO",time:"hora ISO",duration:"durada ISO",ipv4:"adre\xE7a IPv4",ipv6:"adre\xE7a IPv6",cidrv4:"rang IPv4",cidrv6:"rang IPv6",base64:"cadena codificada en base64",base64url:"cadena codificada en base64url",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Tipus inv\xE0lid: s'esperava instanceof ${r.expected}, s'ha rebut ${a}`:`Tipus inv\xE0lid: s'esperava ${o}, s'ha rebut ${a}`}case"invalid_value":return r.values.length===1?`Valor inv\xE0lid: s'esperava ${x(r.values[0])}`:`Opci\xF3 inv\xE0lida: s'esperava una de ${w(r.values," o ")}`;case"too_big":{let o=r.inclusive?"com a m\xE0xim":"menys de",s=e(r.origin);return s?`Massa gran: s'esperava que ${r.origin??"el valor"} contingu\xE9s ${o} ${r.maximum.toString()} ${s.unit??"elements"}`:`Massa gran: s'esperava que ${r.origin??"el valor"} fos ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?"com a m\xEDnim":"m\xE9s de",s=e(r.origin);return s?`Massa petit: s'esperava que ${r.origin} contingu\xE9s ${o} ${r.minimum.toString()} ${s.unit}`:`Massa petit: s'esperava que ${r.origin} fos ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Format inv\xE0lid: ha de comen\xE7ar amb "${o.prefix}"`:o.format==="ends_with"?`Format inv\xE0lid: ha d'acabar amb "${o.suffix}"`:o.format==="includes"?`Format inv\xE0lid: ha d'incloure "${o.includes}"`:o.format==="regex"?`Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${o.pattern}`:`Format inv\xE0lid per a ${t[o.format]??r.format}`}case"not_multiple_of":return`N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${r.divisor}`;case"unrecognized_keys":return`Clau${r.keys.length>1?"s":""} no reconeguda${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Clau inv\xE0lida a ${r.origin}`;case"invalid_union":return"Entrada inv\xE0lida";case"invalid_element":return`Element inv\xE0lid a ${r.origin}`;default:return"Entrada inv\xE0lida"}}}});function Uk(){return{localeError:bP()}}var bP,Rk=S(()=>{U();bP=()=>{let n={string:{unit:"znak\u016F",verb:"m\xEDt"},file:{unit:"bajt\u016F",verb:"m\xEDt"},array:{unit:"prvk\u016F",verb:"m\xEDt"},set:{unit:"prvk\u016F",verb:"m\xEDt"}};function e(r){return n[r]??null}let t={regex:"regul\xE1rn\xED v\xFDraz",email:"e-mailov\xE1 adresa",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:"datum a \u010Das ve form\xE1tu ISO",date:"datum ve form\xE1tu ISO",time:"\u010Das ve form\xE1tu ISO",duration:"doba trv\xE1n\xED ISO",ipv4:"IPv4 adresa",ipv6:"IPv6 adresa",cidrv4:"rozsah IPv4",cidrv6:"rozsah IPv6",base64:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",base64url:"\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",json_string:"\u0159et\u011Bzec ve form\xE1tu JSON",e164:"\u010D\xEDslo E.164",jwt:"JWT",template_literal:"vstup"},i={nan:"NaN",number:"\u010D\xEDslo",string:"\u0159et\u011Bzec",function:"funkce",array:"pole"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${r.expected}, obdr\u017Eeno ${a}`:`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${o}, obdr\u017Eeno ${a}`}case"invalid_value":return r.values.length===1?`Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${x(r.values[0])}`:`Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${r.origin??"hodnota"} mus\xED m\xEDt ${o}${r.maximum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${r.origin??"hodnota"} mus\xED b\xFDt ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${r.origin??"hodnota"} mus\xED m\xEDt ${o}${r.minimum.toString()} ${s.unit??"prvk\u016F"}`:`Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${r.origin??"hodnota"} mus\xED b\xFDt ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${o.prefix}"`:o.format==="ends_with"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${o.suffix}"`:o.format==="includes"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${o.includes}"`:o.format==="regex"?`Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${o.pattern}`:`Neplatn\xFD form\xE1t ${t[o.format]??r.format}`}case"not_multiple_of":return`Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${r.divisor}`;case"unrecognized_keys":return`Nezn\xE1m\xE9 kl\xED\u010De: ${w(r.keys,", ")}`;case"invalid_key":return`Neplatn\xFD kl\xED\u010D v ${r.origin}`;case"invalid_union":return"Neplatn\xFD vstup";case"invalid_element":return`Neplatn\xE1 hodnota v ${r.origin}`;default:return"Neplatn\xFD vstup"}}}});function Bk(){return{localeError:kP()}}var kP,Fk=S(()=>{U();kP=()=>{let n={string:{unit:"tegn",verb:"havde"},file:{unit:"bytes",verb:"havde"},array:{unit:"elementer",verb:"indeholdt"},set:{unit:"elementer",verb:"indeholdt"}};function e(r){return n[r]??null}let t={regex:"input",email:"e-mailadresse",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 dato- og klokkesl\xE6t",date:"ISO-dato",time:"ISO-klokkesl\xE6t",duration:"ISO-varighed",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodet streng",base64url:"base64url-kodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},i={nan:"NaN",string:"streng",number:"tal",boolean:"boolean",array:"liste",object:"objekt",set:"s\xE6t",file:"fil"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Ugyldigt input: forventede instanceof ${r.expected}, fik ${a}`:`Ugyldigt input: forventede ${o}, fik ${a}`}case"invalid_value":return r.values.length===1?`Ugyldig v\xE6rdi: forventede ${x(r.values[0])}`:`Ugyldigt valg: forventede en af f\xF8lgende ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin),a=i[r.origin]??r.origin;return s?`For stor: forventede ${a??"value"} ${s.verb} ${o} ${r.maximum.toString()} ${s.unit??"elementer"}`:`For stor: forventede ${a??"value"} havde ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin),a=i[r.origin]??r.origin;return s?`For lille: forventede ${a} ${s.verb} ${o} ${r.minimum.toString()} ${s.unit}`:`For lille: forventede ${a} havde ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ugyldig streng: skal starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: skal ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: skal indeholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: skal matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${t[o.format]??r.format}`}case"not_multiple_of":return`Ugyldigt tal: skal v\xE6re deleligt med ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukendte n\xF8gler":"Ukendt n\xF8gle"}: ${w(r.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8gle i ${r.origin}`;case"invalid_union":return"Ugyldigt input: matcher ingen af de tilladte typer";case"invalid_element":return`Ugyldig v\xE6rdi i ${r.origin}`;default:return"Ugyldigt input"}}}});function qk(){return{localeError:SP()}}var SP,Zk=S(()=>{U();SP=()=>{let n={string:{unit:"Zeichen",verb:"zu haben"},file:{unit:"Bytes",verb:"zu haben"},array:{unit:"Elemente",verb:"zu haben"},set:{unit:"Elemente",verb:"zu haben"}};function e(r){return n[r]??null}let t={regex:"Eingabe",email:"E-Mail-Adresse",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-Datum und -Uhrzeit",date:"ISO-Datum",time:"ISO-Uhrzeit",duration:"ISO-Dauer",ipv4:"IPv4-Adresse",ipv6:"IPv6-Adresse",cidrv4:"IPv4-Bereich",cidrv6:"IPv6-Bereich",base64:"Base64-codierter String",base64url:"Base64-URL-codierter String",json_string:"JSON-String",e164:"E.164-Nummer",jwt:"JWT",template_literal:"Eingabe"},i={nan:"NaN",number:"Zahl",array:"Array"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Ung\xFCltige Eingabe: erwartet instanceof ${r.expected}, erhalten ${a}`:`Ung\xFCltige Eingabe: erwartet ${o}, erhalten ${a}`}case"invalid_value":return r.values.length===1?`Ung\xFCltige Eingabe: erwartet ${x(r.values[0])}`:`Ung\xFCltige Option: erwartet eine von ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Zu gro\xDF: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ${s.unit??"Elemente"} hat`:`Zu gro\xDF: erwartet, dass ${r.origin??"Wert"} ${o}${r.maximum.toString()} ist`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ${s.unit} hat`:`Zu klein: erwartet, dass ${r.origin} ${o}${r.minimum.toString()} ist`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ung\xFCltiger String: muss mit "${o.prefix}" beginnen`:o.format==="ends_with"?`Ung\xFCltiger String: muss mit "${o.suffix}" enden`:o.format==="includes"?`Ung\xFCltiger String: muss "${o.includes}" enthalten`:o.format==="regex"?`Ung\xFCltiger String: muss dem Muster ${o.pattern} entsprechen`:`Ung\xFCltig: ${t[o.format]??r.format}`}case"not_multiple_of":return`Ung\xFCltige Zahl: muss ein Vielfaches von ${r.divisor} sein`;case"unrecognized_keys":return`${r.keys.length>1?"Unbekannte Schl\xFCssel":"Unbekannter Schl\xFCssel"}: ${w(r.keys,", ")}`;case"invalid_key":return`Ung\xFCltiger Schl\xFCssel in ${r.origin}`;case"invalid_union":return"Ung\xFCltige Eingabe";case"invalid_element":return`Ung\xFCltiger Wert in ${r.origin}`;default:return"Ung\xFCltige Eingabe"}}}});function ga(){return{localeError:$P()}}var $P,pm=S(()=>{U();$P=()=>{let n={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(r){return n[r]??null}let t={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",mac:"MAC 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"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return`Invalid input: expected ${o}, received ${a}`}case"invalid_value":return r.values.length===1?`Invalid input: expected ${x(r.values[0])}`:`Invalid option: expected one of ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Too big: expected ${r.origin??"value"} to have ${o}${r.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${r.origin??"value"} to be ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Too small: expected ${r.origin} to have ${o}${r.minimum.toString()} ${s.unit}`:`Too small: expected ${r.origin} to be ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;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 ${t[o.format]??r.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${r.divisor}`;case"unrecognized_keys":return`Unrecognized key${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Invalid key in ${r.origin}`;case"invalid_union":return"Invalid input";case"invalid_element":return`Invalid value in ${r.origin}`;default:return"Invalid input"}}}});function Kk(){return{localeError:xP()}}var xP,Vk=S(()=>{U();xP=()=>{let n={string:{unit:"karaktrojn",verb:"havi"},file:{unit:"bajtojn",verb:"havi"},array:{unit:"elementojn",verb:"havi"},set:{unit:"elementojn",verb:"havi"}};function e(r){return n[r]??null}let t={regex:"enigo",email:"retadreso",url:"URL",emoji:"emo\u011Dio",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-datotempo",date:"ISO-dato",time:"ISO-tempo",duration:"ISO-da\u016Dro",ipv4:"IPv4-adreso",ipv6:"IPv6-adreso",cidrv4:"IPv4-rango",cidrv6:"IPv6-rango",base64:"64-ume kodita karaktraro",base64url:"URL-64-ume kodita karaktraro",json_string:"JSON-karaktraro",e164:"E.164-nombro",jwt:"JWT",template_literal:"enigo"},i={nan:"NaN",number:"nombro",array:"tabelo",null:"senvalora"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Nevalida enigo: atendi\u011Dis instanceof ${r.expected}, ricevi\u011Dis ${a}`:`Nevalida enigo: atendi\u011Dis ${o}, ricevi\u011Dis ${a}`}case"invalid_value":return r.values.length===1?`Nevalida enigo: atendi\u011Dis ${x(r.values[0])}`:`Nevalida opcio: atendi\u011Dis unu el ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${o}${r.maximum.toString()} ${s.unit??"elementojn"}`:`Tro granda: atendi\u011Dis ke ${r.origin??"valoro"} havu ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Tro malgranda: atendi\u011Dis ke ${r.origin} havu ${o}${r.minimum.toString()} ${s.unit}`:`Tro malgranda: atendi\u011Dis ke ${r.origin} estu ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Nevalida karaktraro: devas komenci\u011Di per "${o.prefix}"`:o.format==="ends_with"?`Nevalida karaktraro: devas fini\u011Di per "${o.suffix}"`:o.format==="includes"?`Nevalida karaktraro: devas inkluzivi "${o.includes}"`:o.format==="regex"?`Nevalida karaktraro: devas kongrui kun la modelo ${o.pattern}`:`Nevalida ${t[o.format]??r.format}`}case"not_multiple_of":return`Nevalida nombro: devas esti oblo de ${r.divisor}`;case"unrecognized_keys":return`Nekonata${r.keys.length>1?"j":""} \u015Dlosilo${r.keys.length>1?"j":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Nevalida \u015Dlosilo en ${r.origin}`;case"invalid_union":return"Nevalida enigo";case"invalid_element":return`Nevalida valoro en ${r.origin}`;default:return"Nevalida enigo"}}}});function Wk(){return{localeError:IP()}}var IP,Gk=S(()=>{U();IP=()=>{let n={string:{unit:"caracteres",verb:"tener"},file:{unit:"bytes",verb:"tener"},array:{unit:"elementos",verb:"tener"},set:{unit:"elementos",verb:"tener"}};function e(r){return n[r]??null}let t={regex:"entrada",email:"direcci\xF3n de correo electr\xF3nico",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:"fecha y hora ISO",date:"fecha ISO",time:"hora ISO",duration:"duraci\xF3n ISO",ipv4:"direcci\xF3n IPv4",ipv6:"direcci\xF3n IPv6",cidrv4:"rango IPv4",cidrv6:"rango IPv6",base64:"cadena codificada en base64",base64url:"URL codificada en base64",json_string:"cadena JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},i={nan:"NaN",string:"texto",number:"n\xFAmero",boolean:"booleano",array:"arreglo",object:"objeto",set:"conjunto",file:"archivo",date:"fecha",bigint:"n\xFAmero grande",symbol:"s\xEDmbolo",undefined:"indefinido",null:"nulo",function:"funci\xF3n",map:"mapa",record:"registro",tuple:"tupla",enum:"enumeraci\xF3n",union:"uni\xF3n",literal:"literal",promise:"promesa",void:"vac\xEDo",never:"nunca",unknown:"desconocido",any:"cualquiera"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Entrada inv\xE1lida: se esperaba instanceof ${r.expected}, recibido ${a}`:`Entrada inv\xE1lida: se esperaba ${o}, recibido ${a}`}case"invalid_value":return r.values.length===1?`Entrada inv\xE1lida: se esperaba ${x(r.values[0])}`:`Opci\xF3n inv\xE1lida: se esperaba una de ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin),a=i[r.origin]??r.origin;return s?`Demasiado grande: se esperaba que ${a??"valor"} tuviera ${o}${r.maximum.toString()} ${s.unit??"elementos"}`:`Demasiado grande: se esperaba que ${a??"valor"} fuera ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin),a=i[r.origin]??r.origin;return s?`Demasiado peque\xF1o: se esperaba que ${a} tuviera ${o}${r.minimum.toString()} ${s.unit}`:`Demasiado peque\xF1o: se esperaba que ${a} fuera ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Cadena inv\xE1lida: debe comenzar con "${o.prefix}"`:o.format==="ends_with"?`Cadena inv\xE1lida: debe terminar en "${o.suffix}"`:o.format==="includes"?`Cadena inv\xE1lida: debe incluir "${o.includes}"`:o.format==="regex"?`Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${o.pattern}`:`Inv\xE1lido ${t[o.format]??r.format}`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${r.divisor}`;case"unrecognized_keys":return`Llave${r.keys.length>1?"s":""} desconocida${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Llave inv\xE1lida en ${i[r.origin]??r.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido en ${i[r.origin]??r.origin}`;default:return"Entrada inv\xE1lida"}}}});function Jk(){return{localeError:TP()}}var TP,Hk=S(()=>{U();TP=()=>{let n={string:{unit:"\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},file:{unit:"\u0628\u0627\u06CC\u062A",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},array:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"},set:{unit:"\u0622\u06CC\u062A\u0645",verb:"\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F"}};function e(r){return n[r]??null}let t={regex:"\u0648\u0631\u0648\u062F\u06CC",email:"\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",url:"URL",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",date:"\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",time:"\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",duration:"\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",ipv4:"IPv4 \u0622\u062F\u0631\u0633",ipv6:"IPv6 \u0622\u062F\u0631\u0633",cidrv4:"IPv4 \u062F\u0627\u0645\u0646\u0647",cidrv6:"IPv6 \u062F\u0627\u0645\u0646\u0647",base64:"base64-encoded \u0631\u0634\u062A\u0647",base64url:"base64url-encoded \u0631\u0634\u062A\u0647",json_string:"JSON \u0631\u0634\u062A\u0647",e164:"E.164 \u0639\u062F\u062F",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u06CC"},i={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0622\u0631\u0627\u06CC\u0647"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${r.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`:`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${o} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${a} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`}case"invalid_value":return r.values.length===1?`\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${x(r.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`:`\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${w(r.values,"|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${r.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${r.origin??"\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} \u0628\u0627\u0634\u062F`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} ${s.unit} \u0628\u0627\u0634\u062F`:`\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} \u0628\u0627\u0634\u062F`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`:o.format==="ends_with"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${o.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`:o.format==="includes"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${o.includes}" \u0628\u0627\u0634\u062F`:o.format==="regex"?`\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${o.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`:`${t[o.format]??r.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`}case"not_multiple_of":return`\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${r.divisor} \u0628\u0627\u0634\u062F`;case"unrecognized_keys":return`\u06A9\u0644\u06CC\u062F${r.keys.length>1?"\u0647\u0627\u06CC":""} \u0646\u0627\u0634\u0646\u0627\u0633: ${w(r.keys,", ")}`;case"invalid_key":return`\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${r.origin}`;case"invalid_union":return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";case"invalid_element":return`\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${r.origin}`;default:return"\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631"}}}});function Yk(){return{localeError:EP()}}var EP,Xk=S(()=>{U();EP=()=>{let n={string:{unit:"merkki\xE4",subject:"merkkijonon"},file:{unit:"tavua",subject:"tiedoston"},array:{unit:"alkiota",subject:"listan"},set:{unit:"alkiota",subject:"joukon"},number:{unit:"",subject:"luvun"},bigint:{unit:"",subject:"suuren kokonaisluvun"},int:{unit:"",subject:"kokonaisluvun"},date:{unit:"",subject:"p\xE4iv\xE4m\xE4\xE4r\xE4n"}};function e(r){return n[r]??null}let t={regex:"s\xE4\xE4nn\xF6llinen lauseke",email:"s\xE4hk\xF6postiosoite",url:"URL-osoite",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO-aikaleima",date:"ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",time:"ISO-aika",duration:"ISO-kesto",ipv4:"IPv4-osoite",ipv6:"IPv6-osoite",cidrv4:"IPv4-alue",cidrv6:"IPv6-alue",base64:"base64-koodattu merkkijono",base64url:"base64url-koodattu merkkijono",json_string:"JSON-merkkijono",e164:"E.164-luku",jwt:"JWT",template_literal:"templaattimerkkijono"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Virheellinen tyyppi: odotettiin instanceof ${r.expected}, oli ${a}`:`Virheellinen tyyppi: odotettiin ${o}, oli ${a}`}case"invalid_value":return r.values.length===1?`Virheellinen sy\xF6te: t\xE4ytyy olla ${x(r.values[0])}`:`Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Liian suuri: ${s.subject} t\xE4ytyy olla ${o}${r.maximum.toString()} ${s.unit}`.trim():`Liian suuri: arvon t\xE4ytyy olla ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Liian pieni: ${s.subject} t\xE4ytyy olla ${o}${r.minimum.toString()} ${s.unit}`.trim():`Liian pieni: arvon t\xE4ytyy olla ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Virheellinen sy\xF6te: t\xE4ytyy alkaa "${o.prefix}"`:o.format==="ends_with"?`Virheellinen sy\xF6te: t\xE4ytyy loppua "${o.suffix}"`:o.format==="includes"?`Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${o.includes}"`:o.format==="regex"?`Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${o.pattern}`:`Virheellinen ${t[o.format]??r.format}`}case"not_multiple_of":return`Virheellinen luku: t\xE4ytyy olla luvun ${r.divisor} monikerta`;case"unrecognized_keys":return`${r.keys.length>1?"Tuntemattomat avaimet":"Tuntematon avain"}: ${w(r.keys,", ")}`;case"invalid_key":return"Virheellinen avain tietueessa";case"invalid_union":return"Virheellinen unioni";case"invalid_element":return"Virheellinen arvo joukossa";default:return"Virheellinen sy\xF6te"}}}});function Qk(){return{localeError:AP()}}var AP,eS=S(()=>{U();AP=()=>{let n={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(r){return n[r]??null}let t={regex:"entr\xE9e",email:"adresse e-mail",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:"date et heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},i={nan:"NaN",number:"nombre",array:"tableau"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Entr\xE9e invalide : instanceof ${r.expected} attendu, ${a} re\xE7u`:`Entr\xE9e invalide : ${o} attendu, ${a} re\xE7u`}case"invalid_value":return r.values.length===1?`Entr\xE9e invalide : ${x(r.values[0])} attendu`:`Option invalide : une valeur parmi ${w(r.values,"|")} attendue`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Trop grand : ${r.origin??"valeur"} doit ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"\xE9l\xE9ment(s)"}`:`Trop grand : ${r.origin??"valeur"} doit \xEAtre ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Trop petit : ${r.origin} doit ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Trop petit : ${r.origin} doit \xEAtre ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au mod\xE8le ${o.pattern}`:`${t[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${r.divisor}`;case"unrecognized_keys":return`Cl\xE9${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${w(r.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${r.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entr\xE9e invalide"}}}});function tS(){return{localeError:OP()}}var OP,nS=S(()=>{U();OP=()=>{let n={string:{unit:"caract\xE8res",verb:"avoir"},file:{unit:"octets",verb:"avoir"},array:{unit:"\xE9l\xE9ments",verb:"avoir"},set:{unit:"\xE9l\xE9ments",verb:"avoir"}};function e(r){return n[r]??null}let t={regex:"entr\xE9e",email:"adresse courriel",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:"date-heure ISO",date:"date ISO",time:"heure ISO",duration:"dur\xE9e ISO",ipv4:"adresse IPv4",ipv6:"adresse IPv6",cidrv4:"plage IPv4",cidrv6:"plage IPv6",base64:"cha\xEEne encod\xE9e en base64",base64url:"cha\xEEne encod\xE9e en base64url",json_string:"cha\xEEne JSON",e164:"num\xE9ro E.164",jwt:"JWT",template_literal:"entr\xE9e"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Entr\xE9e invalide : attendu instanceof ${r.expected}, re\xE7u ${a}`:`Entr\xE9e invalide : attendu ${o}, re\xE7u ${a}`}case"invalid_value":return r.values.length===1?`Entr\xE9e invalide : attendu ${x(r.values[0])}`:`Option invalide : attendu l'une des valeurs suivantes ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"\u2264":"<",s=e(r.origin);return s?`Trop grand : attendu que ${r.origin??"la valeur"} ait ${o}${r.maximum.toString()} ${s.unit}`:`Trop grand : attendu que ${r.origin??"la valeur"} soit ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?"\u2265":">",s=e(r.origin);return s?`Trop petit : attendu que ${r.origin} ait ${o}${r.minimum.toString()} ${s.unit}`:`Trop petit : attendu que ${r.origin} soit ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Cha\xEEne invalide : doit commencer par "${o.prefix}"`:o.format==="ends_with"?`Cha\xEEne invalide : doit se terminer par "${o.suffix}"`:o.format==="includes"?`Cha\xEEne invalide : doit inclure "${o.includes}"`:o.format==="regex"?`Cha\xEEne invalide : doit correspondre au motif ${o.pattern}`:`${t[o.format]??r.format} invalide`}case"not_multiple_of":return`Nombre invalide : doit \xEAtre un multiple de ${r.divisor}`;case"unrecognized_keys":return`Cl\xE9${r.keys.length>1?"s":""} non reconnue${r.keys.length>1?"s":""} : ${w(r.keys,", ")}`;case"invalid_key":return`Cl\xE9 invalide dans ${r.origin}`;case"invalid_union":return"Entr\xE9e invalide";case"invalid_element":return`Valeur invalide dans ${r.origin}`;default:return"Entr\xE9e invalide"}}}});function rS(){return{localeError:CP()}}var CP,iS=S(()=>{U();CP=()=>{let n={string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA",gender:"f"},number:{label:"\u05DE\u05E1\u05E4\u05E8",gender:"m"},boolean:{label:"\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9",gender:"m"},bigint:{label:"BigInt",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA",gender:"m"},array:{label:"\u05DE\u05E2\u05E8\u05DA",gender:"m"},object:{label:"\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8",gender:"m"},null:{label:"\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)",gender:"m"},undefined:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)",gender:"m"},symbol:{label:"\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)",gender:"m"},function:{label:"\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4",gender:"f"},map:{label:"\u05DE\u05E4\u05D4 (Map)",gender:"f"},set:{label:"\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)",gender:"f"},file:{label:"\u05E7\u05D5\u05D1\u05E5",gender:"m"},promise:{label:"Promise",gender:"m"},NaN:{label:"NaN",gender:"m"},unknown:{label:"\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2",gender:"m"},value:{label:"\u05E2\u05E8\u05DA",gender:"m"}},e={string:{unit:"\u05EA\u05D5\u05D5\u05D9\u05DD",shortLabel:"\u05E7\u05E6\u05E8",longLabel:"\u05D0\u05E8\u05D5\u05DA"},file:{unit:"\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},array:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},set:{unit:"\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"},number:{unit:"",shortLabel:"\u05E7\u05D8\u05DF",longLabel:"\u05D2\u05D3\u05D5\u05DC"}},t=c=>c?n[c]:void 0,i=c=>{let u=t(c);return u?u.label:c??n.unknown.label},r=c=>`\u05D4${i(c)}`,o=c=>(t(c)?.gender??"m")==="f"?"\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA":"\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA",s=c=>c?e[c]??null:null,a={regex:{label:"\u05E7\u05DC\u05D8",gender:"m"},email:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC",gender:"f"},url:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA",gender:"f"},emoji:{label:"\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9",gender:"m"},uuid:{label:"UUID",gender:"m"},nanoid:{label:"nanoid",gender:"m"},guid:{label:"GUID",gender:"m"},cuid:{label:"cuid",gender:"m"},cuid2:{label:"cuid2",gender:"m"},ulid:{label:"ULID",gender:"m"},xid:{label:"XID",gender:"m"},ksuid:{label:"KSUID",gender:"m"},datetime:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO",gender:"m"},date:{label:"\u05EA\u05D0\u05E8\u05D9\u05DA ISO",gender:"m"},time:{label:"\u05D6\u05DE\u05DF ISO",gender:"m"},duration:{label:"\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO",gender:"m"},ipv4:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv4",gender:"f"},ipv6:{label:"\u05DB\u05EA\u05D5\u05D1\u05EA IPv6",gender:"f"},cidrv4:{label:"\u05D8\u05D5\u05D5\u05D7 IPv4",gender:"m"},cidrv6:{label:"\u05D8\u05D5\u05D5\u05D7 IPv6",gender:"m"},base64:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64",gender:"f"},base64url:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA",gender:"f"},json_string:{label:"\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON",gender:"f"},e164:{label:"\u05DE\u05E1\u05E4\u05E8 E.164",gender:"m"},jwt:{label:"JWT",gender:"m"},ends_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},includes:{label:"\u05E7\u05DC\u05D8",gender:"m"},lowercase:{label:"\u05E7\u05DC\u05D8",gender:"m"},starts_with:{label:"\u05E7\u05DC\u05D8",gender:"m"},uppercase:{label:"\u05E7\u05DC\u05D8",gender:"m"}},l={nan:"NaN"};return c=>{switch(c.code){case"invalid_type":{let u=c.expected,d=l[u??""]??i(u),f=T(c.input),p=l[f]??n[f]?.label??f;return/^[A-Z]/.test(c.expected)?`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${c.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${p}`:`\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${d}, \u05D4\u05EA\u05E7\u05D1\u05DC ${p}`}case"invalid_value":{if(c.values.length===1)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${x(c.values[0])}`;let u=c.values.map(p=>x(p));if(c.values.length===2)return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u[0]} \u05D0\u05D5 ${u[1]}`;let d=u[u.length-1];return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${u.slice(0,-1).join(", ")} \u05D0\u05D5 ${d}`}case"too_big":{let u=s(c.origin),d=r(c.origin??"value");if(c.origin==="string")return`${u?.longLabel??"\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.maximum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA":"\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();if(c.origin==="number"){let h=c.inclusive?`\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.maximum}`:`\u05E7\u05D8\u05DF \u05DE-${c.maximum}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${h}`}if(c.origin==="array"||c.origin==="set"){let h=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA",m=c.inclusive?`${c.maximum} ${u?.unit??""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA`:`\u05E4\u05D7\u05D5\u05EA \u05DE-${c.maximum} ${u?.unit??""}`;return`\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${d} ${h} \u05DC\u05D4\u05DB\u05D9\u05DC ${m}`.trim()}let f=c.inclusive?"<=":"<",p=o(c.origin??"value");return u?.unit?`${u.longLabel} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.maximum.toString()} ${u.unit}`:`${u?.longLabel??"\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.maximum.toString()}`}case"too_small":{let u=s(c.origin),d=r(c.origin??"value");if(c.origin==="string")return`${u?.shortLabel??"\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${c.minimum.toString()} ${u?.unit??""} ${c.inclusive?"\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8":"\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();if(c.origin==="number"){let h=c.inclusive?`\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${c.minimum}`:`\u05D2\u05D3\u05D5\u05DC \u05DE-${c.minimum}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${h}`}if(c.origin==="array"||c.origin==="set"){let h=c.origin==="set"?"\u05E6\u05E8\u05D9\u05DB\u05D4":"\u05E6\u05E8\u05D9\u05DA";if(c.minimum===1&&c.inclusive){let y=(c.origin==="set","\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3");return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${h} \u05DC\u05D4\u05DB\u05D9\u05DC ${y}`}let m=c.inclusive?`${c.minimum} ${u?.unit??""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8`:`\u05D9\u05D5\u05EA\u05E8 \u05DE-${c.minimum} ${u?.unit??""}`;return`\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${d} ${h} \u05DC\u05D4\u05DB\u05D9\u05DC ${m}`.trim()}let f=c.inclusive?">=":">",p=o(c.origin??"value");return u?.unit?`${u.shortLabel} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.minimum.toString()} ${u.unit}`:`${u?.shortLabel??"\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${d} ${p} ${f}${c.minimum.toString()}`}case"invalid_format":{let u=c;if(u.format==="starts_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${u.prefix}"`;if(u.format==="ends_with")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${u.suffix}"`;if(u.format==="includes")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${u.includes}"`;if(u.format==="regex")return`\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${u.pattern}`;let d=a[u.format],f=d?.label??u.format,h=(d?.gender??"m")==="f"?"\u05EA\u05E7\u05D9\u05E0\u05D4":"\u05EA\u05E7\u05D9\u05DF";return`${f} \u05DC\u05D0 ${h}`}case"not_multiple_of":return`\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${c.divisor}`;case"unrecognized_keys":return`\u05DE\u05E4\u05EA\u05D7${c.keys.length>1?"\u05D5\u05EA":""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${c.keys.length>1?"\u05D9\u05DD":"\u05D4"}: ${w(c.keys,", ")}`;case"invalid_key":return"\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8";case"invalid_union":return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";case"invalid_element":return`\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${r(c.origin??"array")}`;default:return"\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF"}}}});function oS(){return{localeError:NP()}}var NP,sS=S(()=>{U();NP=()=>{let n={string:{unit:"karakter",verb:"legyen"},file:{unit:"byte",verb:"legyen"},array:{unit:"elem",verb:"legyen"},set:{unit:"elem",verb:"legyen"}};function e(r){return n[r]??null}let t={regex:"bemenet",email:"email c\xEDm",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 id\u0151b\xE9lyeg",date:"ISO d\xE1tum",time:"ISO id\u0151",duration:"ISO id\u0151intervallum",ipv4:"IPv4 c\xEDm",ipv6:"IPv6 c\xEDm",cidrv4:"IPv4 tartom\xE1ny",cidrv6:"IPv6 tartom\xE1ny",base64:"base64-k\xF3dolt string",base64url:"base64url-k\xF3dolt string",json_string:"JSON string",e164:"E.164 sz\xE1m",jwt:"JWT",template_literal:"bemenet"},i={nan:"NaN",number:"sz\xE1m",array:"t\xF6mb"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${r.expected}, a kapott \xE9rt\xE9k ${a}`:`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${o}, a kapott \xE9rt\xE9k ${a}`}case"invalid_value":return r.values.length===1?`\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${x(r.values[0])}`:`\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`T\xFAl nagy: ${r.origin??"\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${o}${r.maximum.toString()} ${s.unit??"elem"}`:`T\xFAl nagy: a bemeneti \xE9rt\xE9k ${r.origin??"\xE9rt\xE9k"} t\xFAl nagy: ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${r.origin} m\xE9rete t\xFAl kicsi ${o}${r.minimum.toString()} ${s.unit}`:`T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${r.origin} t\xFAl kicsi ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\xC9rv\xE9nytelen string: "${o.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`:o.format==="ends_with"?`\xC9rv\xE9nytelen string: "${o.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`:o.format==="includes"?`\xC9rv\xE9nytelen string: "${o.includes}" \xE9rt\xE9ket kell tartalmaznia`:o.format==="regex"?`\xC9rv\xE9nytelen string: ${o.pattern} mint\xE1nak kell megfelelnie`:`\xC9rv\xE9nytelen ${t[o.format]??r.format}`}case"not_multiple_of":return`\xC9rv\xE9nytelen sz\xE1m: ${r.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;case"unrecognized_keys":return`Ismeretlen kulcs${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`\xC9rv\xE9nytelen kulcs ${r.origin}`;case"invalid_union":return"\xC9rv\xE9nytelen bemenet";case"invalid_element":return`\xC9rv\xE9nytelen \xE9rt\xE9k: ${r.origin}`;default:return"\xC9rv\xE9nytelen bemenet"}}}});function aS(n,e,t){return Math.abs(n)===1?e:t}function pr(n){if(!n)return"";let e=["\u0561","\u0565","\u0568","\u056B","\u0578","\u0578\u0582","\u0585"],t=n[n.length-1];return n+(e.includes(t)?"\u0576":"\u0568")}function cS(){return{localeError:DP()}}var DP,lS=S(()=>{U();DP=()=>{let n={string:{unit:{one:"\u0576\u0577\u0561\u0576",many:"\u0576\u0577\u0561\u0576\u0576\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},file:{unit:{one:"\u0562\u0561\u0575\u0569",many:"\u0562\u0561\u0575\u0569\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},array:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"},set:{unit:{one:"\u057F\u0561\u0580\u0580",many:"\u057F\u0561\u0580\u0580\u0565\u0580"},verb:"\u0578\u0582\u0576\u0565\u0576\u0561\u056C"}};function e(r){return n[r]??null}let t={regex:"\u0574\u0578\u0582\u057F\u0584",email:"\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",url:"URL",emoji:"\u0567\u0574\u0578\u057B\u056B",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",date:"ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",time:"ISO \u056A\u0561\u0574",duration:"ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",ipv4:"IPv4 \u0570\u0561\u057D\u0581\u0565",ipv6:"IPv6 \u0570\u0561\u057D\u0581\u0565",cidrv4:"IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",cidrv6:"IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",base64:"base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",base64url:"base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",json_string:"JSON \u057F\u0578\u0572",e164:"E.164 \u0570\u0561\u0574\u0561\u0580",jwt:"JWT",template_literal:"\u0574\u0578\u0582\u057F\u0584"},i={nan:"NaN",number:"\u0569\u056B\u057E",array:"\u0566\u0561\u0576\u0563\u057E\u0561\u056E"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${r.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`:`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${o}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${a}`}case"invalid_value":return r.values.length===1?`\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${x(r.values[1])}`:`\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);if(s){let a=Number(r.maximum),l=aS(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pr(r.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${o}${r.maximum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pr(r.origin??"\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);if(s){let a=Number(r.minimum),l=aS(a,s.unit.one,s.unit.many);return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pr(r.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${o}${r.minimum.toString()} ${l}`}return`\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${pr(r.origin)} \u056C\u056B\u0576\u056B ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${o.prefix}"-\u0578\u057E`:o.format==="ends_with"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${o.suffix}"-\u0578\u057E`:o.format==="includes"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${o.includes}"`:o.format==="regex"?`\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${o.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`:`\u054D\u056D\u0561\u056C ${t[o.format]??r.format}`}case"not_multiple_of":return`\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${r.divisor}-\u056B`;case"unrecognized_keys":return`\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${r.keys.length>1?"\u0576\u0565\u0580":""}. ${w(r.keys,", ")}`;case"invalid_key":return`\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${pr(r.origin)}-\u0578\u0582\u0574`;case"invalid_union":return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";case"invalid_element":return`\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${pr(r.origin)}-\u0578\u0582\u0574`;default:return"\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574"}}}});function uS(){return{localeError:PP()}}var PP,dS=S(()=>{U();PP=()=>{let n={string:{unit:"karakter",verb:"memiliki"},file:{unit:"byte",verb:"memiliki"},array:{unit:"item",verb:"memiliki"},set:{unit:"item",verb:"memiliki"}};function e(r){return n[r]??null}let t={regex:"input",email:"alamat email",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:"tanggal dan waktu format ISO",date:"tanggal format ISO",time:"jam format ISO",duration:"durasi format ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"rentang alamat IPv4",cidrv6:"rentang alamat IPv6",base64:"string dengan enkode base64",base64url:"string dengan enkode base64url",json_string:"string JSON",e164:"angka E.164",jwt:"JWT",template_literal:"input"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Input tidak valid: diharapkan instanceof ${r.expected}, diterima ${a}`:`Input tidak valid: diharapkan ${o}, diterima ${a}`}case"invalid_value":return r.values.length===1?`Input tidak valid: diharapkan ${x(r.values[0])}`:`Pilihan tidak valid: diharapkan salah satu dari ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Terlalu besar: diharapkan ${r.origin??"value"} memiliki ${o}${r.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: diharapkan ${r.origin??"value"} menjadi ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Terlalu kecil: diharapkan ${r.origin} memiliki ${o}${r.minimum.toString()} ${s.unit}`:`Terlalu kecil: diharapkan ${r.origin} menjadi ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`String tidak valid: harus dimulai dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak valid: harus berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak valid: harus menyertakan "${o.includes}"`:o.format==="regex"?`String tidak valid: harus sesuai pola ${o.pattern}`:`${t[o.format]??r.format} tidak valid`}case"not_multiple_of":return`Angka tidak valid: harus kelipatan dari ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali ${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Kunci tidak valid di ${r.origin}`;case"invalid_union":return"Input tidak valid";case"invalid_element":return`Nilai tidak valid di ${r.origin}`;default:return"Input tidak valid"}}}});function fS(){return{localeError:MP()}}var MP,pS=S(()=>{U();MP=()=>{let n={string:{unit:"stafi",verb:"a\xF0 hafa"},file:{unit:"b\xE6ti",verb:"a\xF0 hafa"},array:{unit:"hluti",verb:"a\xF0 hafa"},set:{unit:"hluti",verb:"a\xF0 hafa"}};function e(r){return n[r]??null}let t={regex:"gildi",email:"netfang",url:"vefsl\xF3\xF0",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO dagsetning og t\xEDmi",date:"ISO dagsetning",time:"ISO t\xEDmi",duration:"ISO t\xEDmalengd",ipv4:"IPv4 address",ipv6:"IPv6 address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded strengur",base64url:"base64url-encoded strengur",json_string:"JSON strengur",e164:"E.164 t\xF6lugildi",jwt:"JWT",template_literal:"gildi"},i={nan:"NaN",number:"n\xFAmer",array:"fylki"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera instanceof ${r.expected}`:`Rangt gildi: \xDE\xFA sl\xF3st inn ${a} \xFEar sem \xE1 a\xF0 vera ${o}`}case"invalid_value":return r.values.length===1?`Rangt gildi: gert r\xE1\xF0 fyrir ${x(r.values[0])}`:`\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin??"gildi"} hafi ${o}${r.maximum.toString()} ${s.unit??"hluti"}`:`Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin??"gildi"} s\xE9 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin} hafi ${o}${r.minimum.toString()} ${s.unit}`:`Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${r.origin} s\xE9 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${o.prefix}"`:o.format==="ends_with"?`\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${o.suffix}"`:o.format==="includes"?`\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${o.includes}"`:o.format==="regex"?`\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${o.pattern}`:`Rangt ${t[o.format]??r.format}`}case"not_multiple_of":return`R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${r.divisor}`;case"unrecognized_keys":return`\xD3\xFEekkt ${r.keys.length>1?"ir lyklar":"ur lykill"}: ${w(r.keys,", ")}`;case"invalid_key":return`Rangur lykill \xED ${r.origin}`;case"invalid_union":return"Rangt gildi";case"invalid_element":return`Rangt gildi \xED ${r.origin}`;default:return"Rangt gildi"}}}});function mS(){return{localeError:LP()}}var LP,hS=S(()=>{U();LP=()=>{let n={string:{unit:"caratteri",verb:"avere"},file:{unit:"byte",verb:"avere"},array:{unit:"elementi",verb:"avere"},set:{unit:"elementi",verb:"avere"}};function e(r){return n[r]??null}let t={regex:"input",email:"indirizzo email",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:"data e ora ISO",date:"data ISO",time:"ora ISO",duration:"durata ISO",ipv4:"indirizzo IPv4",ipv6:"indirizzo IPv6",cidrv4:"intervallo IPv4",cidrv6:"intervallo IPv6",base64:"stringa codificata in base64",base64url:"URL codificata in base64",json_string:"stringa JSON",e164:"numero E.164",jwt:"JWT",template_literal:"input"},i={nan:"NaN",number:"numero",array:"vettore"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Input non valido: atteso instanceof ${r.expected}, ricevuto ${a}`:`Input non valido: atteso ${o}, ricevuto ${a}`}case"invalid_value":return r.values.length===1?`Input non valido: atteso ${x(r.values[0])}`:`Opzione non valida: atteso uno tra ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Troppo grande: ${r.origin??"valore"} deve avere ${o}${r.maximum.toString()} ${s.unit??"elementi"}`:`Troppo grande: ${r.origin??"valore"} deve essere ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Troppo piccolo: ${r.origin} deve avere ${o}${r.minimum.toString()} ${s.unit}`:`Troppo piccolo: ${r.origin} deve essere ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Stringa non valida: deve iniziare con "${o.prefix}"`:o.format==="ends_with"?`Stringa non valida: deve terminare con "${o.suffix}"`:o.format==="includes"?`Stringa non valida: deve includere "${o.includes}"`:o.format==="regex"?`Stringa non valida: deve corrispondere al pattern ${o.pattern}`:`Invalid ${t[o.format]??r.format}`}case"not_multiple_of":return`Numero non valido: deve essere un multiplo di ${r.divisor}`;case"unrecognized_keys":return`Chiav${r.keys.length>1?"i":"e"} non riconosciut${r.keys.length>1?"e":"a"}: ${w(r.keys,", ")}`;case"invalid_key":return`Chiave non valida in ${r.origin}`;case"invalid_union":return"Input non valido";case"invalid_element":return`Valore non valido in ${r.origin}`;default:return"Input non valido"}}}});function gS(){return{localeError:zP()}}var zP,yS=S(()=>{U();zP=()=>{let n={string:{unit:"\u6587\u5B57",verb:"\u3067\u3042\u308B"},file:{unit:"\u30D0\u30A4\u30C8",verb:"\u3067\u3042\u308B"},array:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"},set:{unit:"\u8981\u7D20",verb:"\u3067\u3042\u308B"}};function e(r){return n[r]??null}let t={regex:"\u5165\u529B\u5024",email:"\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",url:"URL",emoji:"\u7D75\u6587\u5B57",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u6642",date:"ISO\u65E5\u4ED8",time:"ISO\u6642\u523B",duration:"ISO\u671F\u9593",ipv4:"IPv4\u30A2\u30C9\u30EC\u30B9",ipv6:"IPv6\u30A2\u30C9\u30EC\u30B9",cidrv4:"IPv4\u7BC4\u56F2",cidrv6:"IPv6\u7BC4\u56F2",base64:"base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",base64url:"base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",json_string:"JSON\u6587\u5B57\u5217",e164:"E.164\u756A\u53F7",jwt:"JWT",template_literal:"\u5165\u529B\u5024"},i={nan:"NaN",number:"\u6570\u5024",array:"\u914D\u5217"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u7121\u52B9\u306A\u5165\u529B: instanceof ${r.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u5165\u529B: ${o}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${a}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`}case"invalid_value":return r.values.length===1?`\u7121\u52B9\u306A\u5165\u529B: ${x(r.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`:`\u7121\u52B9\u306A\u9078\u629E: ${w(r.values,"\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"too_big":{let o=r.inclusive?"\u4EE5\u4E0B\u3067\u3042\u308B":"\u3088\u308A\u5C0F\u3055\u3044",s=e(r.origin);return s?`\u5927\u304D\u3059\u304E\u308B\u5024: ${r.origin??"\u5024"}\u306F${r.maximum.toString()}${s.unit??"\u8981\u7D20"}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5927\u304D\u3059\u304E\u308B\u5024: ${r.origin??"\u5024"}\u306F${r.maximum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"too_small":{let o=r.inclusive?"\u4EE5\u4E0A\u3067\u3042\u308B":"\u3088\u308A\u5927\u304D\u3044",s=e(r.origin);return s?`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${r.origin}\u306F${r.minimum.toString()}${s.unit}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u5C0F\u3055\u3059\u304E\u308B\u5024: ${r.origin}\u306F${r.minimum.toString()}${o}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="ends_with"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="includes"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: "${o.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:o.format==="regex"?`\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${o.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`:`\u7121\u52B9\u306A${t[o.format]??r.format}`}case"not_multiple_of":return`\u7121\u52B9\u306A\u6570\u5024: ${r.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;case"unrecognized_keys":return`\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${r.keys.length>1?"\u7FA4":""}: ${w(r.keys,"\u3001")}`;case"invalid_key":return`${r.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;case"invalid_union":return"\u7121\u52B9\u306A\u5165\u529B";case"invalid_element":return`${r.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;default:return"\u7121\u52B9\u306A\u5165\u529B"}}}});function vS(){return{localeError:jP()}}var jP,_S=S(()=>{U();jP=()=>{let n={string:{unit:"\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},file:{unit:"\u10D1\u10D0\u10D8\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},array:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"},set:{unit:"\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8",verb:"\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1"}};function e(r){return n[r]??null}let t={regex:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",email:"\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",url:"URL",emoji:"\u10D4\u10DB\u10DD\u10EF\u10D8",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",date:"\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",time:"\u10D3\u10E0\u10DD",duration:"\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",ipv4:"IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",ipv6:"IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",cidrv4:"IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",cidrv6:"IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",base64:"base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",base64url:"base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",json_string:"JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",e164:"E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",jwt:"JWT",template_literal:"\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"},i={nan:"NaN",number:"\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",string:"\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",boolean:"\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",function:"\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",array:"\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${r.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${o}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${a}`}case"invalid_value":return r.values.length===1?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${x(r.values[0])}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${w(r.values,"|")}-\u10D3\u10D0\u10DC`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin??"\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${r.origin} \u10D8\u10E7\u10DD\u10E1 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${o.prefix}"-\u10D8\u10D7`:o.format==="ends_with"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${o.suffix}"-\u10D8\u10D7`:o.format==="includes"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${o.includes}"-\u10E1`:o.format==="regex"?`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${o.pattern}`:`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${r.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;case"unrecognized_keys":return`\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${r.keys.length>1?"\u10D4\u10D1\u10D8":"\u10D8"}: ${w(r.keys,", ")}`;case"invalid_key":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${r.origin}-\u10E8\u10D8`;case"invalid_union":return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";case"invalid_element":return`\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${r.origin}-\u10E8\u10D8`;default:return"\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"}}}});function ya(){return{localeError:UP()}}var UP,mm=S(()=>{U();UP=()=>{let n={string:{unit:"\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},file:{unit:"\u1794\u17C3",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},array:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"},set:{unit:"\u1792\u17B6\u178F\u17BB",verb:"\u1782\u17BD\u179A\u1798\u17B6\u1793"}};function e(r){return n[r]??null}let t={regex:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",email:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",url:"URL",emoji:"\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",date:"\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",time:"\u1798\u17C9\u17C4\u1784 ISO",duration:"\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",ipv4:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",ipv6:"\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",cidrv4:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",cidrv6:"\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",base64:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",base64url:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",json_string:"\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",e164:"\u179B\u17C1\u1781 E.164",jwt:"JWT",template_literal:"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"},i={nan:"NaN",number:"\u179B\u17C1\u1781",array:"\u17A2\u17B6\u179A\u17C1 (Array)",null:"\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${r.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`:`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${o} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${a}`}case"invalid_value":return r.values.length===1?`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${x(r.values[0])}`:`\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${r.maximum.toString()} ${s.unit??"\u1792\u17B6\u178F\u17BB"}`:`\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin??"\u178F\u1798\u17D2\u179B\u17C3"} ${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin} ${o} ${r.minimum.toString()} ${s.unit}`:`\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${r.origin} ${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${o.prefix}"`:o.format==="ends_with"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${o.suffix}"`:o.format==="includes"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${o.includes}"`:o.format==="regex"?`\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${o.pattern}`:`\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${r.divisor}`;case"unrecognized_keys":return`\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${w(r.keys,", ")}`;case"invalid_key":return`\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${r.origin}`;case"invalid_union":return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";case"invalid_element":return`\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${r.origin}`;default:return"\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C"}}}});function wS(){return ya()}var bS=S(()=>{mm()});function kS(){return{localeError:RP()}}var RP,SS=S(()=>{U();RP=()=>{let n={string:{unit:"\uBB38\uC790",verb:"to have"},file:{unit:"\uBC14\uC774\uD2B8",verb:"to have"},array:{unit:"\uAC1C",verb:"to have"},set:{unit:"\uAC1C",verb:"to have"}};function e(r){return n[r]??null}let t={regex:"\uC785\uB825",email:"\uC774\uBA54\uC77C \uC8FC\uC18C",url:"URL",emoji:"\uC774\uBAA8\uC9C0",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \uB0A0\uC9DC\uC2DC\uAC04",date:"ISO \uB0A0\uC9DC",time:"ISO \uC2DC\uAC04",duration:"ISO \uAE30\uAC04",ipv4:"IPv4 \uC8FC\uC18C",ipv6:"IPv6 \uC8FC\uC18C",cidrv4:"IPv4 \uBC94\uC704",cidrv6:"IPv6 \uBC94\uC704",base64:"base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",base64url:"base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",json_string:"JSON \uBB38\uC790\uC5F4",e164:"E.164 \uBC88\uD638",jwt:"JWT",template_literal:"\uC785\uB825"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${r.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${o}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${a}\uC785\uB2C8\uB2E4`}case"invalid_value":return r.values.length===1?`\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${x(r.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C \uC635\uC158: ${w(r.values,"\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"too_big":{let o=r.inclusive?"\uC774\uD558":"\uBBF8\uB9CC",s=o==="\uBBF8\uB9CC"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(r.origin),l=a?.unit??"\uC694\uC18C";return a?`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${r.maximum.toString()}${l} ${o}${s}`:`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${r.maximum.toString()} ${o}${s}`}case"too_small":{let o=r.inclusive?"\uC774\uC0C1":"\uCD08\uACFC",s=o==="\uC774\uC0C1"?"\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4":"\uC5EC\uC57C \uD569\uB2C8\uB2E4",a=e(r.origin),l=a?.unit??"\uC694\uC18C";return a?`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${r.minimum.toString()}${l} ${o}${s}`:`${r.origin??"\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${r.minimum.toString()} ${o}${s}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="ends_with"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`:o.format==="includes"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${o.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`:o.format==="regex"?`\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${o.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`:`\uC798\uBABB\uB41C ${t[o.format]??r.format}`}case"not_multiple_of":return`\uC798\uBABB\uB41C \uC22B\uC790: ${r.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;case"unrecognized_keys":return`\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${w(r.keys,", ")}`;case"invalid_key":return`\uC798\uBABB\uB41C \uD0A4: ${r.origin}`;case"invalid_union":return"\uC798\uBABB\uB41C \uC785\uB825";case"invalid_element":return`\uC798\uBABB\uB41C \uAC12: ${r.origin}`;default:return"\uC798\uBABB\uB41C \uC785\uB825"}}}});function $S(n){let e=Math.abs(n),t=e%10,i=e%100;return i>=11&&i<=19||t===0?"many":t===1?"one":"few"}function xS(){return{localeError:BP()}}var Zi,BP,IS=S(()=>{U();Zi=n=>n.charAt(0).toUpperCase()+n.slice(1);BP=()=>{let n={string:{unit:{one:"simbolis",few:"simboliai",many:"simboli\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne ilgesn\u0117 kaip",notInclusive:"turi b\u016Bti trumpesn\u0117 kaip"},bigger:{inclusive:"turi b\u016Bti ne trumpesn\u0117 kaip",notInclusive:"turi b\u016Bti ilgesn\u0117 kaip"}}},file:{unit:{one:"baitas",few:"baitai",many:"bait\u0173"},verb:{smaller:{inclusive:"turi b\u016Bti ne didesnis kaip",notInclusive:"turi b\u016Bti ma\u017Eesnis kaip"},bigger:{inclusive:"turi b\u016Bti ne ma\u017Eesnis kaip",notInclusive:"turi b\u016Bti didesnis kaip"}}},array:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}},set:{unit:{one:"element\u0105",few:"elementus",many:"element\u0173"},verb:{smaller:{inclusive:"turi tur\u0117ti ne daugiau kaip",notInclusive:"turi tur\u0117ti ma\u017Eiau kaip"},bigger:{inclusive:"turi tur\u0117ti ne ma\u017Eiau kaip",notInclusive:"turi tur\u0117ti daugiau kaip"}}}};function e(r,o,s,a){let l=n[r]??null;return l===null?l:{unit:l.unit[o],verb:l.verb[a][s?"inclusive":"notInclusive"]}}let t={regex:"\u012Fvestis",email:"el. pa\u0161to adresas",url:"URL",emoji:"jaustukas",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO data ir laikas",date:"ISO data",time:"ISO laikas",duration:"ISO trukm\u0117",ipv4:"IPv4 adresas",ipv6:"IPv6 adresas",cidrv4:"IPv4 tinklo prefiksas (CIDR)",cidrv6:"IPv6 tinklo prefiksas (CIDR)",base64:"base64 u\u017Ekoduota eilut\u0117",base64url:"base64url u\u017Ekoduota eilut\u0117",json_string:"JSON eilut\u0117",e164:"E.164 numeris",jwt:"JWT",template_literal:"\u012Fvestis"},i={nan:"NaN",number:"skai\u010Dius",bigint:"sveikasis skai\u010Dius",string:"eilut\u0117",boolean:"login\u0117 reik\u0161m\u0117",undefined:"neapibr\u0117\u017Eta reik\u0161m\u0117",function:"funkcija",symbol:"simbolis",array:"masyvas",object:"objektas",null:"nulin\u0117 reik\u0161m\u0117"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Gautas tipas ${a}, o tik\u0117tasi - instanceof ${r.expected}`:`Gautas tipas ${a}, o tik\u0117tasi - ${o}`}case"invalid_value":return r.values.length===1?`Privalo b\u016Bti ${x(r.values[0])}`:`Privalo b\u016Bti vienas i\u0161 ${w(r.values,"|")} pasirinkim\u0173`;case"too_big":{let o=i[r.origin]??r.origin,s=e(r.origin,$S(Number(r.maximum)),r.inclusive??!1,"smaller");if(s?.verb)return`${Zi(o??r.origin??"reik\u0161m\u0117")} ${s.verb} ${r.maximum.toString()} ${s.unit??"element\u0173"}`;let a=r.inclusive?"ne didesnis kaip":"ma\u017Eesnis kaip";return`${Zi(o??r.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${r.maximum.toString()} ${s?.unit}`}case"too_small":{let o=i[r.origin]??r.origin,s=e(r.origin,$S(Number(r.minimum)),r.inclusive??!1,"bigger");if(s?.verb)return`${Zi(o??r.origin??"reik\u0161m\u0117")} ${s.verb} ${r.minimum.toString()} ${s.unit??"element\u0173"}`;let a=r.inclusive?"ne ma\u017Eesnis kaip":"didesnis kaip";return`${Zi(o??r.origin??"reik\u0161m\u0117")} turi b\u016Bti ${a} ${r.minimum.toString()} ${s?.unit}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Eilut\u0117 privalo prasid\u0117ti "${o.prefix}"`:o.format==="ends_with"?`Eilut\u0117 privalo pasibaigti "${o.suffix}"`:o.format==="includes"?`Eilut\u0117 privalo \u012Ftraukti "${o.includes}"`:o.format==="regex"?`Eilut\u0117 privalo atitikti ${o.pattern}`:`Neteisingas ${t[o.format]??r.format}`}case"not_multiple_of":return`Skai\u010Dius privalo b\u016Bti ${r.divisor} kartotinis.`;case"unrecognized_keys":return`Neatpa\u017Eint${r.keys.length>1?"i":"as"} rakt${r.keys.length>1?"ai":"as"}: ${w(r.keys,", ")}`;case"invalid_key":return"Rastas klaidingas raktas";case"invalid_union":return"Klaidinga \u012Fvestis";case"invalid_element":{let o=i[r.origin]??r.origin;return`${Zi(o??r.origin??"reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`}default:return"Klaidinga \u012Fvestis"}}}});function TS(){return{localeError:FP()}}var FP,ES=S(()=>{U();FP=()=>{let n={string:{unit:"\u0437\u043D\u0430\u0446\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},file:{unit:"\u0431\u0430\u0458\u0442\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},array:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"},set:{unit:"\u0441\u0442\u0430\u0432\u043A\u0438",verb:"\u0434\u0430 \u0438\u043C\u0430\u0430\u0442"}};function e(r){return n[r]??null}let t={regex:"\u0432\u043D\u0435\u0441",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",url:"URL",emoji:"\u0435\u043C\u043E\u045F\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",date:"ISO \u0434\u0430\u0442\u0443\u043C",time:"ISO \u0432\u0440\u0435\u043C\u0435",duration:"ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",cidrv4:"IPv4 \u043E\u043F\u0441\u0435\u0433",cidrv6:"IPv6 \u043E\u043F\u0441\u0435\u0433",base64:"base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",base64url:"base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",json_string:"JSON \u043D\u0438\u0437\u0430",e164:"E.164 \u0431\u0440\u043E\u0458",jwt:"JWT",template_literal:"\u0432\u043D\u0435\u0441"},i={nan:"NaN",number:"\u0431\u0440\u043E\u0458",array:"\u043D\u0438\u0437\u0430"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${r.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`:`\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${o}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${a}`}case"invalid_value":return r.values.length===1?`Invalid input: expected ${x(r.values[0])}`:`\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${o}${r.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin??"\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin} \u0434\u0430 \u0438\u043C\u0430 ${o}${r.minimum.toString()} ${s.unit}`:`\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${r.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${o.pattern}`:`Invalid ${t[o.format]??r.format}`}case"not_multiple_of":return`\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438":"\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${w(r.keys,", ")}`;case"invalid_key":return`\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${r.origin}`;case"invalid_union":return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";case"invalid_element":return`\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${r.origin}`;default:return"\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441"}}}});function AS(){return{localeError:qP()}}var qP,OS=S(()=>{U();qP=()=>{let n={string:{unit:"aksara",verb:"mempunyai"},file:{unit:"bait",verb:"mempunyai"},array:{unit:"elemen",verb:"mempunyai"},set:{unit:"elemen",verb:"mempunyai"}};function e(r){return n[r]??null}let t={regex:"input",email:"alamat e-mel",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:"tarikh masa ISO",date:"tarikh ISO",time:"masa ISO",duration:"tempoh ISO",ipv4:"alamat IPv4",ipv6:"alamat IPv6",cidrv4:"julat IPv4",cidrv6:"julat IPv6",base64:"string dikodkan base64",base64url:"string dikodkan base64url",json_string:"string JSON",e164:"nombor E.164",jwt:"JWT",template_literal:"input"},i={nan:"NaN",number:"nombor"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Input tidak sah: dijangka instanceof ${r.expected}, diterima ${a}`:`Input tidak sah: dijangka ${o}, diterima ${a}`}case"invalid_value":return r.values.length===1?`Input tidak sah: dijangka ${x(r.values[0])}`:`Pilihan tidak sah: dijangka salah satu daripada ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Terlalu besar: dijangka ${r.origin??"nilai"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"elemen"}`:`Terlalu besar: dijangka ${r.origin??"nilai"} adalah ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Terlalu kecil: dijangka ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Terlalu kecil: dijangka ${r.origin} adalah ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`String tidak sah: mesti bermula dengan "${o.prefix}"`:o.format==="ends_with"?`String tidak sah: mesti berakhir dengan "${o.suffix}"`:o.format==="includes"?`String tidak sah: mesti mengandungi "${o.includes}"`:o.format==="regex"?`String tidak sah: mesti sepadan dengan corak ${o.pattern}`:`${t[o.format]??r.format} tidak sah`}case"not_multiple_of":return`Nombor tidak sah: perlu gandaan ${r.divisor}`;case"unrecognized_keys":return`Kunci tidak dikenali: ${w(r.keys,", ")}`;case"invalid_key":return`Kunci tidak sah dalam ${r.origin}`;case"invalid_union":return"Input tidak sah";case"invalid_element":return`Nilai tidak sah dalam ${r.origin}`;default:return"Input tidak sah"}}}});function CS(){return{localeError:ZP()}}var ZP,NS=S(()=>{U();ZP=()=>{let n={string:{unit:"tekens",verb:"heeft"},file:{unit:"bytes",verb:"heeft"},array:{unit:"elementen",verb:"heeft"},set:{unit:"elementen",verb:"heeft"}};function e(r){return n[r]??null}let t={regex:"invoer",email:"emailadres",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 datum en tijd",date:"ISO datum",time:"ISO tijd",duration:"ISO duur",ipv4:"IPv4-adres",ipv6:"IPv6-adres",cidrv4:"IPv4-bereik",cidrv6:"IPv6-bereik",base64:"base64-gecodeerde tekst",base64url:"base64 URL-gecodeerde tekst",json_string:"JSON string",e164:"E.164-nummer",jwt:"JWT",template_literal:"invoer"},i={nan:"NaN",number:"getal"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Ongeldige invoer: verwacht instanceof ${r.expected}, ontving ${a}`:`Ongeldige invoer: verwacht ${o}, ontving ${a}`}case"invalid_value":return r.values.length===1?`Ongeldige invoer: verwacht ${x(r.values[0])}`:`Ongeldige optie: verwacht \xE9\xE9n van ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin),a=r.origin==="date"?"laat":r.origin==="string"?"lang":"groot";return s?`Te ${a}: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} ${s.unit??"elementen"} ${s.verb}`:`Te ${a}: verwacht dat ${r.origin??"waarde"} ${o}${r.maximum.toString()} is`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin),a=r.origin==="date"?"vroeg":r.origin==="string"?"kort":"klein";return s?`Te ${a}: verwacht dat ${r.origin} ${o}${r.minimum.toString()} ${s.unit} ${s.verb}`:`Te ${a}: verwacht dat ${r.origin} ${o}${r.minimum.toString()} is`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ongeldige tekst: moet met "${o.prefix}" beginnen`:o.format==="ends_with"?`Ongeldige tekst: moet op "${o.suffix}" eindigen`:o.format==="includes"?`Ongeldige tekst: moet "${o.includes}" bevatten`:o.format==="regex"?`Ongeldige tekst: moet overeenkomen met patroon ${o.pattern}`:`Ongeldig: ${t[o.format]??r.format}`}case"not_multiple_of":return`Ongeldig getal: moet een veelvoud van ${r.divisor} zijn`;case"unrecognized_keys":return`Onbekende key${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Ongeldige key in ${r.origin}`;case"invalid_union":return"Ongeldige invoer";case"invalid_element":return`Ongeldige waarde in ${r.origin}`;default:return"Ongeldige invoer"}}}});function DS(){return{localeError:KP()}}var KP,PS=S(()=>{U();KP=()=>{let n={string:{unit:"tegn",verb:"\xE5 ha"},file:{unit:"bytes",verb:"\xE5 ha"},array:{unit:"elementer",verb:"\xE5 inneholde"},set:{unit:"elementer",verb:"\xE5 inneholde"}};function e(r){return n[r]??null}let t={regex:"input",email:"e-postadresse",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 dato- og klokkeslett",date:"ISO-dato",time:"ISO-klokkeslett",duration:"ISO-varighet",ipv4:"IPv4-omr\xE5de",ipv6:"IPv6-omr\xE5de",cidrv4:"IPv4-spekter",cidrv6:"IPv6-spekter",base64:"base64-enkodet streng",base64url:"base64url-enkodet streng",json_string:"JSON-streng",e164:"E.164-nummer",jwt:"JWT",template_literal:"input"},i={nan:"NaN",number:"tall",array:"liste"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Ugyldig input: forventet instanceof ${r.expected}, fikk ${a}`:`Ugyldig input: forventet ${o}, fikk ${a}`}case"invalid_value":return r.values.length===1?`Ugyldig verdi: forventet ${x(r.values[0])}`:`Ugyldig valg: forventet en av ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`For stor(t): forventet ${r.origin??"value"} til \xE5 ha ${o}${r.maximum.toString()} ${s.unit??"elementer"}`:`For stor(t): forventet ${r.origin??"value"} til \xE5 ha ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`For lite(n): forventet ${r.origin} til \xE5 ha ${o}${r.minimum.toString()} ${s.unit}`:`For lite(n): forventet ${r.origin} til \xE5 ha ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ugyldig streng: m\xE5 starte med "${o.prefix}"`:o.format==="ends_with"?`Ugyldig streng: m\xE5 ende med "${o.suffix}"`:o.format==="includes"?`Ugyldig streng: m\xE5 inneholde "${o.includes}"`:o.format==="regex"?`Ugyldig streng: m\xE5 matche m\xF8nsteret ${o.pattern}`:`Ugyldig ${t[o.format]??r.format}`}case"not_multiple_of":return`Ugyldig tall: m\xE5 v\xE6re et multiplum av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ukjente n\xF8kler":"Ukjent n\xF8kkel"}: ${w(r.keys,", ")}`;case"invalid_key":return`Ugyldig n\xF8kkel i ${r.origin}`;case"invalid_union":return"Ugyldig input";case"invalid_element":return`Ugyldig verdi i ${r.origin}`;default:return"Ugyldig input"}}}});function MS(){return{localeError:VP()}}var VP,LS=S(()=>{U();VP=()=>{let n={string:{unit:"harf",verb:"olmal\u0131d\u0131r"},file:{unit:"bayt",verb:"olmal\u0131d\u0131r"},array:{unit:"unsur",verb:"olmal\u0131d\u0131r"},set:{unit:"unsur",verb:"olmal\u0131d\u0131r"}};function e(r){return n[r]??null}let t={regex:"giren",email:"epostag\xE2h",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 heng\xE2m\u0131",date:"ISO tarihi",time:"ISO zaman\u0131",duration:"ISO m\xFCddeti",ipv4:"IPv4 ni\u015F\xE2n\u0131",ipv6:"IPv6 ni\u015F\xE2n\u0131",cidrv4:"IPv4 menzili",cidrv6:"IPv6 menzili",base64:"base64-\u015Fifreli metin",base64url:"base64url-\u015Fifreli metin",json_string:"JSON metin",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"giren"},i={nan:"NaN",number:"numara",array:"saf",null:"gayb"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`F\xE2sit giren: umulan instanceof ${r.expected}, al\u0131nan ${a}`:`F\xE2sit giren: umulan ${o}, al\u0131nan ${a}`}case"invalid_value":return r.values.length===1?`F\xE2sit giren: umulan ${x(r.values[0])}`:`F\xE2sit tercih: m\xFBteberler ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Fazla b\xFCy\xFCk: ${r.origin??"value"}, ${o}${r.maximum.toString()} ${s.unit??"elements"} sahip olmal\u0131yd\u0131.`:`Fazla b\xFCy\xFCk: ${r.origin??"value"}, ${o}${r.maximum.toString()} olmal\u0131yd\u0131.`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Fazla k\xFC\xE7\xFCk: ${r.origin}, ${o}${r.minimum.toString()} ${s.unit} sahip olmal\u0131yd\u0131.`:`Fazla k\xFC\xE7\xFCk: ${r.origin}, ${o}${r.minimum.toString()} olmal\u0131yd\u0131.`}case"invalid_format":{let o=r;return o.format==="starts_with"?`F\xE2sit metin: "${o.prefix}" ile ba\u015Flamal\u0131.`:o.format==="ends_with"?`F\xE2sit metin: "${o.suffix}" ile bitmeli.`:o.format==="includes"?`F\xE2sit metin: "${o.includes}" ihtiv\xE2 etmeli.`:o.format==="regex"?`F\xE2sit metin: ${o.pattern} nak\u015F\u0131na uymal\u0131.`:`F\xE2sit ${t[o.format]??r.format}`}case"not_multiple_of":return`F\xE2sit say\u0131: ${r.divisor} kat\u0131 olmal\u0131yd\u0131.`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar ${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7in tan\u0131nmayan anahtar var.`;case"invalid_union":return"Giren tan\u0131namad\u0131.";case"invalid_element":return`${r.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;default:return"K\u0131ymet tan\u0131namad\u0131."}}}});function zS(){return{localeError:WP()}}var WP,jS=S(()=>{U();WP=()=>{let n={string:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},file:{unit:"\u0628\u0627\u06CC\u067C\u0633",verb:"\u0648\u0644\u0631\u064A"},array:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"},set:{unit:"\u062A\u0648\u06A9\u064A",verb:"\u0648\u0644\u0631\u064A"}};function e(r){return n[r]??null}let t={regex:"\u0648\u0631\u0648\u062F\u064A",email:"\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",url:"\u06CC\u0648 \u0622\u0631 \u0627\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u064A",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",date:"\u0646\u06D0\u067C\u0647",time:"\u0648\u062E\u062A",duration:"\u0645\u0648\u062F\u0647",ipv4:"\u062F IPv4 \u067E\u062A\u0647",ipv6:"\u062F IPv6 \u067E\u062A\u0647",cidrv4:"\u062F IPv4 \u0633\u0627\u062D\u0647",cidrv6:"\u062F IPv6 \u0633\u0627\u062D\u0647",base64:"base64-encoded \u0645\u062A\u0646",base64url:"base64url-encoded \u0645\u062A\u0646",json_string:"JSON \u0645\u062A\u0646",e164:"\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",jwt:"JWT",template_literal:"\u0648\u0631\u0648\u062F\u064A"},i={nan:"NaN",number:"\u0639\u062F\u062F",array:"\u0627\u0631\u06D0"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${r.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`:`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${o} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${a} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`}case"invalid_value":return r.values.length===1?`\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${x(r.values[0])} \u0648\u0627\u06CC`:`\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${w(r.values,"|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${r.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${r.origin??"\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${o}${r.maximum.toString()} \u0648\u064A`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} ${s.unit} \u0648\u0644\u0631\u064A`:`\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${r.origin} \u0628\u0627\u06CC\u062F ${o}${r.minimum.toString()} \u0648\u064A`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`:o.format==="ends_with"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${o.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`:o.format==="includes"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${o.includes}" \u0648\u0644\u0631\u064A`:o.format==="regex"?`\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${o.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`:`${t[o.format]??r.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`}case"not_multiple_of":return`\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${r.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;case"unrecognized_keys":return`\u0646\u0627\u0633\u0645 ${r.keys.length>1?"\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647":"\u06A9\u0644\u06CC\u0689"}: ${w(r.keys,", ")}`;case"invalid_key":return`\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${r.origin} \u06A9\u06D0`;case"invalid_union":return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";case"invalid_element":return`\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${r.origin} \u06A9\u06D0`;default:return"\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A"}}}});function US(){return{localeError:GP()}}var GP,RS=S(()=>{U();GP=()=>{let n={string:{unit:"znak\xF3w",verb:"mie\u0107"},file:{unit:"bajt\xF3w",verb:"mie\u0107"},array:{unit:"element\xF3w",verb:"mie\u0107"},set:{unit:"element\xF3w",verb:"mie\u0107"}};function e(r){return n[r]??null}let t={regex:"wyra\u017Cenie",email:"adres email",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:"data i godzina w formacie ISO",date:"data w formacie ISO",time:"godzina w formacie ISO",duration:"czas trwania ISO",ipv4:"adres IPv4",ipv6:"adres IPv6",cidrv4:"zakres IPv4",cidrv6:"zakres IPv6",base64:"ci\u0105g znak\xF3w zakodowany w formacie base64",base64url:"ci\u0105g znak\xF3w zakodowany w formacie base64url",json_string:"ci\u0105g znak\xF3w w formacie JSON",e164:"liczba E.164",jwt:"JWT",template_literal:"wej\u015Bcie"},i={nan:"NaN",number:"liczba",array:"tablica"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${r.expected}, otrzymano ${a}`:`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${o}, otrzymano ${a}`}case"invalid_value":return r.values.length===1?`Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${x(r.values[0])}`:`Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${r.maximum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie mie\u0107 ${o}${r.minimum.toString()} ${s.unit??"element\xF3w"}`:`Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${r.origin??"warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${o.prefix}"`:o.format==="ends_with"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${o.suffix}"`:o.format==="includes"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${o.includes}"`:o.format==="regex"?`Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${o.pattern}`:`Nieprawid\u0142ow(y/a/e) ${t[o.format]??r.format}`}case"not_multiple_of":return`Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${r.divisor}`;case"unrecognized_keys":return`Nierozpoznane klucze${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Nieprawid\u0142owy klucz w ${r.origin}`;case"invalid_union":return"Nieprawid\u0142owe dane wej\u015Bciowe";case"invalid_element":return`Nieprawid\u0142owa warto\u015B\u0107 w ${r.origin}`;default:return"Nieprawid\u0142owe dane wej\u015Bciowe"}}}});function BS(){return{localeError:JP()}}var JP,FS=S(()=>{U();JP=()=>{let n={string:{unit:"caracteres",verb:"ter"},file:{unit:"bytes",verb:"ter"},array:{unit:"itens",verb:"ter"},set:{unit:"itens",verb:"ter"}};function e(r){return n[r]??null}let t={regex:"padr\xE3o",email:"endere\xE7o de e-mail",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:"data e hora ISO",date:"data ISO",time:"hora ISO",duration:"dura\xE7\xE3o ISO",ipv4:"endere\xE7o IPv4",ipv6:"endere\xE7o IPv6",cidrv4:"faixa de IPv4",cidrv6:"faixa de IPv6",base64:"texto codificado em base64",base64url:"URL codificada em base64",json_string:"texto JSON",e164:"n\xFAmero E.164",jwt:"JWT",template_literal:"entrada"},i={nan:"NaN",number:"n\xFAmero",null:"nulo"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Tipo inv\xE1lido: esperado instanceof ${r.expected}, recebido ${a}`:`Tipo inv\xE1lido: esperado ${o}, recebido ${a}`}case"invalid_value":return r.values.length===1?`Entrada inv\xE1lida: esperado ${x(r.values[0])}`:`Op\xE7\xE3o inv\xE1lida: esperada uma das ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Muito grande: esperado que ${r.origin??"valor"} tivesse ${o}${r.maximum.toString()} ${s.unit??"elementos"}`:`Muito grande: esperado que ${r.origin??"valor"} fosse ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Muito pequeno: esperado que ${r.origin} tivesse ${o}${r.minimum.toString()} ${s.unit}`:`Muito pequeno: esperado que ${r.origin} fosse ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Texto inv\xE1lido: deve come\xE7ar com "${o.prefix}"`:o.format==="ends_with"?`Texto inv\xE1lido: deve terminar com "${o.suffix}"`:o.format==="includes"?`Texto inv\xE1lido: deve incluir "${o.includes}"`:o.format==="regex"?`Texto inv\xE1lido: deve corresponder ao padr\xE3o ${o.pattern}`:`${t[o.format]??r.format} inv\xE1lido`}case"not_multiple_of":return`N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${r.divisor}`;case"unrecognized_keys":return`Chave${r.keys.length>1?"s":""} desconhecida${r.keys.length>1?"s":""}: ${w(r.keys,", ")}`;case"invalid_key":return`Chave inv\xE1lida em ${r.origin}`;case"invalid_union":return"Entrada inv\xE1lida";case"invalid_element":return`Valor inv\xE1lido em ${r.origin}`;default:return"Campo inv\xE1lido"}}}});function qS(n,e,t,i){let r=Math.abs(n),o=r%10,s=r%100;return s>=11&&s<=19?i:o===1?e:o>=2&&o<=4?t:i}function ZS(){return{localeError:HP()}}var HP,KS=S(()=>{U();HP=()=>{let n={string:{unit:{one:"\u0441\u0438\u043C\u0432\u043E\u043B",few:"\u0441\u0438\u043C\u0432\u043E\u043B\u0430",many:"\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},file:{unit:{one:"\u0431\u0430\u0439\u0442",few:"\u0431\u0430\u0439\u0442\u0430",many:"\u0431\u0430\u0439\u0442"},verb:"\u0438\u043C\u0435\u0442\u044C"},array:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"},set:{unit:{one:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442",few:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",many:"\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"},verb:"\u0438\u043C\u0435\u0442\u044C"}};function e(r){return n[r]??null}let t={regex:"\u0432\u0432\u043E\u0434",email:"email \u0430\u0434\u0440\u0435\u0441",url:"URL",emoji:"\u044D\u043C\u043E\u0434\u0437\u0438",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",date:"ISO \u0434\u0430\u0442\u0430",time:"ISO \u0432\u0440\u0435\u043C\u044F",duration:"ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",ipv4:"IPv4 \u0430\u0434\u0440\u0435\u0441",ipv6:"IPv6 \u0430\u0434\u0440\u0435\u0441",cidrv4:"IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",cidrv6:"IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",base64:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",base64url:"\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",json_string:"JSON \u0441\u0442\u0440\u043E\u043A\u0430",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0432\u043E\u0434"},i={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0441\u0438\u0432"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${r.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${o}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${x(r.values[0])}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);if(s){let a=Number(r.maximum),l=qS(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${r.maximum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);if(s){let a=Number(r.minimum),l=qS(a,s.unit.one,s.unit.few,s.unit.many);return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${o}${r.minimum.toString()} ${l}`}return`\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${r.origin} \u0431\u0443\u0434\u0435\u0442 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${r.keys.length>1?"\u044B\u0435":"\u044B\u0439"} \u043A\u043B\u044E\u0447${r.keys.length>1?"\u0438":""}: ${w(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";case"invalid_element":return`\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${r.origin}`;default:return"\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435"}}}});function VS(){return{localeError:YP()}}var YP,WS=S(()=>{U();YP=()=>{let n={string:{unit:"znakov",verb:"imeti"},file:{unit:"bajtov",verb:"imeti"},array:{unit:"elementov",verb:"imeti"},set:{unit:"elementov",verb:"imeti"}};function e(r){return n[r]??null}let t={regex:"vnos",email:"e-po\u0161tni naslov",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 datum in \u010Das",date:"ISO datum",time:"ISO \u010Das",duration:"ISO trajanje",ipv4:"IPv4 naslov",ipv6:"IPv6 naslov",cidrv4:"obseg IPv4",cidrv6:"obseg IPv6",base64:"base64 kodiran niz",base64url:"base64url kodiran niz",json_string:"JSON niz",e164:"E.164 \u0161tevilka",jwt:"JWT",template_literal:"vnos"},i={nan:"NaN",number:"\u0161tevilo",array:"tabela"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Neveljaven vnos: pri\u010Dakovano instanceof ${r.expected}, prejeto ${a}`:`Neveljaven vnos: pri\u010Dakovano ${o}, prejeto ${a}`}case"invalid_value":return r.values.length===1?`Neveljaven vnos: pri\u010Dakovano ${x(r.values[0])}`:`Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Preveliko: pri\u010Dakovano, da bo ${r.origin??"vrednost"} imelo ${o}${r.maximum.toString()} ${s.unit??"elementov"}`:`Preveliko: pri\u010Dakovano, da bo ${r.origin??"vrednost"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Premajhno: pri\u010Dakovano, da bo ${r.origin} imelo ${o}${r.minimum.toString()} ${s.unit}`:`Premajhno: pri\u010Dakovano, da bo ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Neveljaven niz: mora se za\u010Deti z "${o.prefix}"`:o.format==="ends_with"?`Neveljaven niz: mora se kon\u010Dati z "${o.suffix}"`:o.format==="includes"?`Neveljaven niz: mora vsebovati "${o.includes}"`:o.format==="regex"?`Neveljaven niz: mora ustrezati vzorcu ${o.pattern}`:`Neveljaven ${t[o.format]??r.format}`}case"not_multiple_of":return`Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${r.divisor}`;case"unrecognized_keys":return`Neprepoznan${r.keys.length>1?"i klju\u010Di":" klju\u010D"}: ${w(r.keys,", ")}`;case"invalid_key":return`Neveljaven klju\u010D v ${r.origin}`;case"invalid_union":return"Neveljaven vnos";case"invalid_element":return`Neveljavna vrednost v ${r.origin}`;default:return"Neveljaven vnos"}}}});function GS(){return{localeError:XP()}}var XP,JS=S(()=>{U();XP=()=>{let n={string:{unit:"tecken",verb:"att ha"},file:{unit:"bytes",verb:"att ha"},array:{unit:"objekt",verb:"att inneh\xE5lla"},set:{unit:"objekt",verb:"att inneh\xE5lla"}};function e(r){return n[r]??null}let t={regex:"regulj\xE4rt uttryck",email:"e-postadress",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-datum och tid",date:"ISO-datum",time:"ISO-tid",duration:"ISO-varaktighet",ipv4:"IPv4-intervall",ipv6:"IPv6-intervall",cidrv4:"IPv4-spektrum",cidrv6:"IPv6-spektrum",base64:"base64-kodad str\xE4ng",base64url:"base64url-kodad str\xE4ng",json_string:"JSON-str\xE4ng",e164:"E.164-nummer",jwt:"JWT",template_literal:"mall-literal"},i={nan:"NaN",number:"antal",array:"lista"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${r.expected}, fick ${a}`:`Ogiltig inmatning: f\xF6rv\xE4ntat ${o}, fick ${a}`}case"invalid_value":return r.values.length===1?`Ogiltig inmatning: f\xF6rv\xE4ntat ${x(r.values[0])}`:`Ogiltigt val: f\xF6rv\xE4ntade en av ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`F\xF6r stor(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${o}${r.maximum.toString()} ${s.unit??"element"}`:`F\xF6r stor(t): f\xF6rv\xE4ntat ${r.origin??"v\xE4rdet"} att ha ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`F\xF6r lite(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${o}${r.minimum.toString()} ${s.unit}`:`F\xF6r lite(t): f\xF6rv\xE4ntade ${r.origin??"v\xE4rdet"} att ha ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${o.prefix}"`:o.format==="ends_with"?`Ogiltig str\xE4ng: m\xE5ste sluta med "${o.suffix}"`:o.format==="includes"?`Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${o.includes}"`:o.format==="regex"?`Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${o.pattern}"`:`Ogiltig(t) ${t[o.format]??r.format}`}case"not_multiple_of":return`Ogiltigt tal: m\xE5ste vara en multipel av ${r.divisor}`;case"unrecognized_keys":return`${r.keys.length>1?"Ok\xE4nda nycklar":"Ok\xE4nd nyckel"}: ${w(r.keys,", ")}`;case"invalid_key":return`Ogiltig nyckel i ${r.origin??"v\xE4rdet"}`;case"invalid_union":return"Ogiltig input";case"invalid_element":return`Ogiltigt v\xE4rde i ${r.origin??"v\xE4rdet"}`;default:return"Ogiltig input"}}}});function HS(){return{localeError:QP()}}var QP,YS=S(()=>{U();QP=()=>{let n={string:{unit:"\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},file:{unit:"\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},array:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"},set:{unit:"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD",verb:"\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD"}};function e(r){return n[r]??null}let t={regex:"\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",email:"\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",date:"ISO \u0BA4\u0BC7\u0BA4\u0BBF",time:"ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",duration:"ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",ipv4:"IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",ipv6:"IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",cidrv4:"IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",cidrv6:"IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",base64:"base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",base64url:"base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",json_string:"JSON \u0B9A\u0BB0\u0BAE\u0BCD",e164:"E.164 \u0B8E\u0BA3\u0BCD",jwt:"JWT",template_literal:"input"},i={nan:"NaN",number:"\u0B8E\u0BA3\u0BCD",array:"\u0B85\u0BA3\u0BBF",null:"\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${r.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${o}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${a}`}case"invalid_value":return r.values.length===1?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${x(r.values[0])}`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${w(r.values,"|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${r.maximum.toString()} ${s.unit??"\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin??"\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${o}${r.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin} ${o}${r.minimum.toString()} ${s.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${r.origin} ${o}${r.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="ends_with"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="includes"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${o.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:o.format==="regex"?`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${o.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`:`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${r.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;case"unrecognized_keys":return`\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${r.keys.length>1?"\u0B95\u0BB3\u0BCD":""}: ${w(r.keys,", ")}`;case"invalid_key":return`${r.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;case"invalid_union":return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";case"invalid_element":return`${r.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;default:return"\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1"}}}});function XS(){return{localeError:e1()}}var e1,QS=S(()=>{U();e1=()=>{let n={string:{unit:"\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},file:{unit:"\u0E44\u0E1A\u0E15\u0E4C",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},array:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"},set:{unit:"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23",verb:"\u0E04\u0E27\u0E23\u0E21\u0E35"}};function e(r){return n[r]??null}let t={regex:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",email:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",url:"URL",emoji:"\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",date:"\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",time:"\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",duration:"\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",ipv4:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",ipv6:"\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",cidrv4:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",cidrv6:"\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",base64:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",base64url:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",json_string:"\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",e164:"\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",jwt:"\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",template_literal:"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"},i={nan:"NaN",number:"\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",array:"\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",null:"\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${r.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`:`\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${o} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${a}`}case"invalid_value":return r.values.length===1?`\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${x(r.values[0])}`:`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19":"\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32",s=e(r.origin);return s?`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.maximum.toString()} ${s.unit??"\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`:`\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin??"\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?"\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22":"\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32",s=e(r.origin);return s?`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.minimum.toString()} ${s.unit}`:`\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${r.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${o} ${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${o.prefix}"`:o.format==="ends_with"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${o.suffix}"`:o.format==="includes"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${o.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`:o.format==="regex"?`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${o.pattern}`:`\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${t[o.format]??r.format}`}case"not_multiple_of":return`\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${r.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;case"unrecognized_keys":return`\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${w(r.keys,", ")}`;case"invalid_key":return`\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${r.origin}`;case"invalid_union":return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";case"invalid_element":return`\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${r.origin}`;default:return"\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07"}}}});function e$(){return{localeError:t1()}}var t1,t$=S(()=>{U();t1=()=>{let n={string:{unit:"karakter",verb:"olmal\u0131"},file:{unit:"bayt",verb:"olmal\u0131"},array:{unit:"\xF6\u011Fe",verb:"olmal\u0131"},set:{unit:"\xF6\u011Fe",verb:"olmal\u0131"}};function e(r){return n[r]??null}let t={regex:"girdi",email:"e-posta adresi",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 tarih ve saat",date:"ISO tarih",time:"ISO saat",duration:"ISO s\xFCre",ipv4:"IPv4 adresi",ipv6:"IPv6 adresi",cidrv4:"IPv4 aral\u0131\u011F\u0131",cidrv6:"IPv6 aral\u0131\u011F\u0131",base64:"base64 ile \u015Fifrelenmi\u015F metin",base64url:"base64url ile \u015Fifrelenmi\u015F metin",json_string:"JSON dizesi",e164:"E.164 say\u0131s\u0131",jwt:"JWT",template_literal:"\u015Eablon dizesi"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Ge\xE7ersiz de\u011Fer: beklenen instanceof ${r.expected}, al\u0131nan ${a}`:`Ge\xE7ersiz de\u011Fer: beklenen ${o}, al\u0131nan ${a}`}case"invalid_value":return r.values.length===1?`Ge\xE7ersiz de\u011Fer: beklenen ${x(r.values[0])}`:`Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${o}${r.maximum.toString()} ${s.unit??"\xF6\u011Fe"}`:`\xC7ok b\xFCy\xFCk: beklenen ${r.origin??"de\u011Fer"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${o}${r.minimum.toString()} ${s.unit}`:`\xC7ok k\xFC\xE7\xFCk: beklenen ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Ge\xE7ersiz metin: "${o.prefix}" ile ba\u015Flamal\u0131`:o.format==="ends_with"?`Ge\xE7ersiz metin: "${o.suffix}" ile bitmeli`:o.format==="includes"?`Ge\xE7ersiz metin: "${o.includes}" i\xE7ermeli`:o.format==="regex"?`Ge\xE7ersiz metin: ${o.pattern} desenine uymal\u0131`:`Ge\xE7ersiz ${t[o.format]??r.format}`}case"not_multiple_of":return`Ge\xE7ersiz say\u0131: ${r.divisor} ile tam b\xF6l\xFCnebilmeli`;case"unrecognized_keys":return`Tan\u0131nmayan anahtar${r.keys.length>1?"lar":""}: ${w(r.keys,", ")}`;case"invalid_key":return`${r.origin} i\xE7inde ge\xE7ersiz anahtar`;case"invalid_union":return"Ge\xE7ersiz de\u011Fer";case"invalid_element":return`${r.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;default:return"Ge\xE7ersiz de\u011Fer"}}}});function va(){return{localeError:n1()}}var n1,hm=S(()=>{U();n1=()=>{let n={string:{unit:"\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},file:{unit:"\u0431\u0430\u0439\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},array:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"},set:{unit:"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432",verb:"\u043C\u0430\u0442\u0438\u043C\u0435"}};function e(r){return n[r]??null}let t={regex:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",email:"\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",url:"URL",emoji:"\u0435\u043C\u043E\u0434\u0437\u0456",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",date:"\u0434\u0430\u0442\u0430 ISO",time:"\u0447\u0430\u0441 ISO",duration:"\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",ipv4:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",ipv6:"\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",cidrv4:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",cidrv6:"\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",base64:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",base64url:"\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",json_string:"\u0440\u044F\u0434\u043E\u043A JSON",e164:"\u043D\u043E\u043C\u0435\u0440 E.164",jwt:"JWT",template_literal:"\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"},i={nan:"NaN",number:"\u0447\u0438\u0441\u043B\u043E",array:"\u043C\u0430\u0441\u0438\u0432"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${r.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${o}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${a}`}case"invalid_value":return r.values.length===1?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${x(r.values[0])}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin??"\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${r.origin} \u0431\u0443\u0434\u0435 ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${o.prefix}"`:o.format==="ends_with"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${o.suffix}"`:o.format==="includes"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${o.includes}"`:o.format==="regex"?`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${o.pattern}`:`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${r.divisor}`;case"unrecognized_keys":return`\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${r.keys.length>1?"\u0456":""}: ${w(r.keys,", ")}`;case"invalid_key":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${r.origin}`;case"invalid_union":return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";case"invalid_element":return`\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${r.origin}`;default:return"\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"}}}});function n$(){return va()}var r$=S(()=>{hm()});function i$(){return{localeError:r1()}}var r1,o$=S(()=>{U();r1=()=>{let n={string:{unit:"\u062D\u0631\u0648\u0641",verb:"\u06C1\u0648\u0646\u0627"},file:{unit:"\u0628\u0627\u0626\u0679\u0633",verb:"\u06C1\u0648\u0646\u0627"},array:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"},set:{unit:"\u0622\u0626\u0679\u0645\u0632",verb:"\u06C1\u0648\u0646\u0627"}};function e(r){return n[r]??null}let t={regex:"\u0627\u0646 \u067E\u0679",email:"\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",url:"\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",emoji:"\u0627\u06CC\u0645\u0648\u062C\u06CC",uuid:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",uuidv4:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",uuidv6:"\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",nanoid:"\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",guid:"\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",cuid2:"\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",ulid:"\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",xid:"\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",ksuid:"\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",datetime:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",date:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",time:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",duration:"\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",ipv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",ipv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",cidrv4:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",cidrv6:"\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",base64:"\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",base64url:"\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",json_string:"\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",e164:"\u0627\u06CC 164 \u0646\u0645\u0628\u0631",jwt:"\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",template_literal:"\u0627\u0646 \u067E\u0679"},i={nan:"NaN",number:"\u0646\u0645\u0628\u0631",array:"\u0622\u0631\u06D2",null:"\u0646\u0644"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${r.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`:`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${o} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${a} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`}case"invalid_value":return r.values.length===1?`\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${x(r.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`:`\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${w(r.values,"|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u0628\u06C1\u062A \u0628\u0691\u0627: ${r.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${o}${r.maximum.toString()} ${s.unit??"\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0628\u0691\u0627: ${r.origin??"\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${o}${r.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${r.origin} \u06A9\u06D2 ${o}${r.minimum.toString()} ${s.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`:`\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${r.origin} \u06A9\u0627 ${o}${r.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="ends_with"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="includes"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${o.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:o.format==="regex"?`\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${o.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`:`\u063A\u0644\u0637 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${r.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;case"unrecognized_keys":return`\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${r.keys.length>1?"\u0632":""}: ${w(r.keys,"\u060C ")}`;case"invalid_key":return`${r.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;case"invalid_union":return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";case"invalid_element":return`${r.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;default:return"\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679"}}}});function s$(){return{localeError:i1()}}var i1,a$=S(()=>{U();i1=()=>{let n={string:{unit:"belgi",verb:"bo\u2018lishi kerak"},file:{unit:"bayt",verb:"bo\u2018lishi kerak"},array:{unit:"element",verb:"bo\u2018lishi kerak"},set:{unit:"element",verb:"bo\u2018lishi kerak"}};function e(r){return n[r]??null}let t={regex:"kirish",email:"elektron pochta manzili",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 sana va vaqti",date:"ISO sana",time:"ISO vaqt",duration:"ISO davomiylik",ipv4:"IPv4 manzil",ipv6:"IPv6 manzil",mac:"MAC manzil",cidrv4:"IPv4 diapazon",cidrv6:"IPv6 diapazon",base64:"base64 kodlangan satr",base64url:"base64url kodlangan satr",json_string:"JSON satr",e164:"E.164 raqam",jwt:"JWT",template_literal:"kirish"},i={nan:"NaN",number:"raqam",array:"massiv"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`Noto\u2018g\u2018ri kirish: kutilgan instanceof ${r.expected}, qabul qilingan ${a}`:`Noto\u2018g\u2018ri kirish: kutilgan ${o}, qabul qilingan ${a}`}case"invalid_value":return r.values.length===1?`Noto\u2018g\u2018ri kirish: kutilgan ${x(r.values[0])}`:`Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Juda katta: kutilgan ${r.origin??"qiymat"} ${o}${r.maximum.toString()} ${s.unit} ${s.verb}`:`Juda katta: kutilgan ${r.origin??"qiymat"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Juda kichik: kutilgan ${r.origin} ${o}${r.minimum.toString()} ${s.unit} ${s.verb}`:`Juda kichik: kutilgan ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Noto\u2018g\u2018ri satr: "${o.prefix}" bilan boshlanishi kerak`:o.format==="ends_with"?`Noto\u2018g\u2018ri satr: "${o.suffix}" bilan tugashi kerak`:o.format==="includes"?`Noto\u2018g\u2018ri satr: "${o.includes}" ni o\u2018z ichiga olishi kerak`:o.format==="regex"?`Noto\u2018g\u2018ri satr: ${o.pattern} shabloniga mos kelishi kerak`:`Noto\u2018g\u2018ri ${t[o.format]??r.format}`}case"not_multiple_of":return`Noto\u2018g\u2018ri raqam: ${r.divisor} ning karralisi bo\u2018lishi kerak`;case"unrecognized_keys":return`Noma\u2019lum kalit${r.keys.length>1?"lar":""}: ${w(r.keys,", ")}`;case"invalid_key":return`${r.origin} dagi kalit noto\u2018g\u2018ri`;case"invalid_union":return"Noto\u2018g\u2018ri kirish";case"invalid_element":return`${r.origin} da noto\u2018g\u2018ri qiymat`;default:return"Noto\u2018g\u2018ri kirish"}}}});function c$(){return{localeError:o1()}}var o1,l$=S(()=>{U();o1=()=>{let n={string:{unit:"k\xFD t\u1EF1",verb:"c\xF3"},file:{unit:"byte",verb:"c\xF3"},array:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"},set:{unit:"ph\u1EA7n t\u1EED",verb:"c\xF3"}};function e(r){return n[r]??null}let t={regex:"\u0111\u1EA7u v\xE0o",email:"\u0111\u1ECBa ch\u1EC9 email",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:"ng\xE0y gi\u1EDD ISO",date:"ng\xE0y ISO",time:"gi\u1EDD ISO",duration:"kho\u1EA3ng th\u1EDDi gian ISO",ipv4:"\u0111\u1ECBa ch\u1EC9 IPv4",ipv6:"\u0111\u1ECBa ch\u1EC9 IPv6",cidrv4:"d\u1EA3i IPv4",cidrv6:"d\u1EA3i IPv6",base64:"chu\u1ED7i m\xE3 h\xF3a base64",base64url:"chu\u1ED7i m\xE3 h\xF3a base64url",json_string:"chu\u1ED7i JSON",e164:"s\u1ED1 E.164",jwt:"JWT",template_literal:"\u0111\u1EA7u v\xE0o"},i={nan:"NaN",number:"s\u1ED1",array:"m\u1EA3ng"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${r.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`:`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${o}, nh\u1EADn \u0111\u01B0\u1EE3c ${a}`}case"invalid_value":return r.values.length===1?`\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${x(r.values[0])}`:`T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${r.origin??"gi\xE1 tr\u1ECB"} ${s.verb} ${o}${r.maximum.toString()} ${s.unit??"ph\u1EA7n t\u1EED"}`:`Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${r.origin??"gi\xE1 tr\u1ECB"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${r.origin} ${s.verb} ${o}${r.minimum.toString()} ${s.unit}`:`Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${o.prefix}"`:o.format==="ends_with"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${o.suffix}"`:o.format==="includes"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${o.includes}"`:o.format==="regex"?`Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${o.pattern}`:`${t[o.format]??r.format} kh\xF4ng h\u1EE3p l\u1EC7`}case"not_multiple_of":return`S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${r.divisor}`;case"unrecognized_keys":return`Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${w(r.keys,", ")}`;case"invalid_key":return`Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${r.origin}`;case"invalid_union":return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";case"invalid_element":return`Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${r.origin}`;default:return"\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7"}}}});function u$(){return{localeError:s1()}}var s1,d$=S(()=>{U();s1=()=>{let n={string:{unit:"\u5B57\u7B26",verb:"\u5305\u542B"},file:{unit:"\u5B57\u8282",verb:"\u5305\u542B"},array:{unit:"\u9879",verb:"\u5305\u542B"},set:{unit:"\u9879",verb:"\u5305\u542B"}};function e(r){return n[r]??null}let t={regex:"\u8F93\u5165",email:"\u7535\u5B50\u90AE\u4EF6",url:"URL",emoji:"\u8868\u60C5\u7B26\u53F7",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO\u65E5\u671F\u65F6\u95F4",date:"ISO\u65E5\u671F",time:"ISO\u65F6\u95F4",duration:"ISO\u65F6\u957F",ipv4:"IPv4\u5730\u5740",ipv6:"IPv6\u5730\u5740",cidrv4:"IPv4\u7F51\u6BB5",cidrv6:"IPv6\u7F51\u6BB5",base64:"base64\u7F16\u7801\u5B57\u7B26\u4E32",base64url:"base64url\u7F16\u7801\u5B57\u7B26\u4E32",json_string:"JSON\u5B57\u7B26\u4E32",e164:"E.164\u53F7\u7801",jwt:"JWT",template_literal:"\u8F93\u5165"},i={nan:"NaN",number:"\u6570\u5B57",array:"\u6570\u7EC4",null:"\u7A7A\u503C(null)"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${r.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`:`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${o}\uFF0C\u5B9E\u9645\u63A5\u6536 ${a}`}case"invalid_value":return r.values.length===1?`\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${x(r.values[0])}`:`\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${r.origin??"\u503C"} ${o}${r.maximum.toString()} ${s.unit??"\u4E2A\u5143\u7D20"}`:`\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${r.origin??"\u503C"} ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${r.origin} ${o}${r.minimum.toString()} ${s.unit}`:`\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${r.origin} ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.prefix}" \u5F00\u5934`:o.format==="ends_with"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${o.suffix}" \u7ED3\u5C3E`:o.format==="includes"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${o.pattern}`:`\u65E0\u6548${t[o.format]??r.format}`}case"not_multiple_of":return`\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${r.divisor} \u7684\u500D\u6570`;case"unrecognized_keys":return`\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${w(r.keys,", ")}`;case"invalid_key":return`${r.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;case"invalid_union":return"\u65E0\u6548\u8F93\u5165";case"invalid_element":return`${r.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;default:return"\u65E0\u6548\u8F93\u5165"}}}});function f$(){return{localeError:a1()}}var a1,p$=S(()=>{U();a1=()=>{let n={string:{unit:"\u5B57\u5143",verb:"\u64C1\u6709"},file:{unit:"\u4F4D\u5143\u7D44",verb:"\u64C1\u6709"},array:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"},set:{unit:"\u9805\u76EE",verb:"\u64C1\u6709"}};function e(r){return n[r]??null}let t={regex:"\u8F38\u5165",email:"\u90F5\u4EF6\u5730\u5740",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 \u65E5\u671F\u6642\u9593",date:"ISO \u65E5\u671F",time:"ISO \u6642\u9593",duration:"ISO \u671F\u9593",ipv4:"IPv4 \u4F4D\u5740",ipv6:"IPv6 \u4F4D\u5740",cidrv4:"IPv4 \u7BC4\u570D",cidrv6:"IPv6 \u7BC4\u570D",base64:"base64 \u7DE8\u78BC\u5B57\u4E32",base64url:"base64url \u7DE8\u78BC\u5B57\u4E32",json_string:"JSON \u5B57\u4E32",e164:"E.164 \u6578\u503C",jwt:"JWT",template_literal:"\u8F38\u5165"},i={nan:"NaN"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${r.expected}\uFF0C\u4F46\u6536\u5230 ${a}`:`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${o}\uFF0C\u4F46\u6536\u5230 ${a}`}case"invalid_value":return r.values.length===1?`\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${x(r.values[0])}`:`\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${r.origin??"\u503C"} \u61C9\u70BA ${o}${r.maximum.toString()} ${s.unit??"\u500B\u5143\u7D20"}`:`\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${r.origin??"\u503C"} \u61C9\u70BA ${o}${r.maximum.toString()}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${r.origin} \u61C9\u70BA ${o}${r.minimum.toString()} ${s.unit}`:`\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${r.origin} \u61C9\u70BA ${o}${r.minimum.toString()}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.prefix}" \u958B\u982D`:o.format==="ends_with"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${o.suffix}" \u7D50\u5C3E`:o.format==="includes"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${o.includes}"`:o.format==="regex"?`\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${o.pattern}`:`\u7121\u6548\u7684 ${t[o.format]??r.format}`}case"not_multiple_of":return`\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${r.divisor} \u7684\u500D\u6578`;case"unrecognized_keys":return`\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${r.keys.length>1?"\u5011":""}\uFF1A${w(r.keys,"\u3001")}`;case"invalid_key":return`${r.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;case"invalid_union":return"\u7121\u6548\u7684\u8F38\u5165\u503C";case"invalid_element":return`${r.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;default:return"\u7121\u6548\u7684\u8F38\u5165\u503C"}}}});function m$(){return{localeError:c1()}}var c1,h$=S(()=>{U();c1=()=>{let n={string:{unit:"\xE0mi",verb:"n\xED"},file:{unit:"bytes",verb:"n\xED"},array:{unit:"nkan",verb:"n\xED"},set:{unit:"nkan",verb:"n\xED"}};function e(r){return n[r]??null}let t={regex:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",email:"\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",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:"\xE0k\xF3k\xF2 ISO",date:"\u1ECDj\u1ECD\u0301 ISO",time:"\xE0k\xF3k\xF2 ISO",duration:"\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",ipv4:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",ipv6:"\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",cidrv4:"\xE0gb\xE8gb\xE8 IPv4",cidrv6:"\xE0gb\xE8gb\xE8 IPv6",base64:"\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",base64url:"\u1ECD\u0300r\u1ECD\u0300 base64url",json_string:"\u1ECD\u0300r\u1ECD\u0300 JSON",e164:"n\u1ECD\u0301mb\xE0 E.164",jwt:"JWT",template_literal:"\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"},i={nan:"NaN",number:"n\u1ECD\u0301mb\xE0",array:"akop\u1ECD"};return r=>{switch(r.code){case"invalid_type":{let o=i[r.expected]??r.expected,s=T(r.input),a=i[s]??s;return/^[A-Z]/.test(r.expected)?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${r.expected}, \xE0m\u1ECD\u0300 a r\xED ${a}`:`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${o}, \xE0m\u1ECD\u0300 a r\xED ${a}`}case"invalid_value":return r.values.length===1?`\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${x(r.values[0])}`:`\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${w(r.values,"|")}`;case"too_big":{let o=r.inclusive?"<=":"<",s=e(r.origin);return s?`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${r.origin??"iye"} ${s.verb} ${o}${r.maximum} ${s.unit}`:`T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${o}${r.maximum}`}case"too_small":{let o=r.inclusive?">=":">",s=e(r.origin);return s?`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${r.origin} ${s.verb} ${o}${r.minimum} ${s.unit}`:`K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${o}${r.minimum}`}case"invalid_format":{let o=r;return o.format==="starts_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${o.prefix}"`:o.format==="ends_with"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${o.suffix}"`:o.format==="includes"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${o.includes}"`:o.format==="regex"?`\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${o.pattern}`:`A\u1E63\xEC\u1E63e: ${t[o.format]??r.format}`}case"not_multiple_of":return`N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${r.divisor}`;case"unrecognized_keys":return`B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${w(r.keys,", ")}`;case"invalid_key":return`B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${r.origin}`;case"invalid_union":return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";case"invalid_element":return`Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${r.origin}`;default:return"\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e"}}}});var Ki={};we(Ki,{ar:()=>Ek,az:()=>Ok,be:()=>Dk,bg:()=>Mk,ca:()=>zk,cs:()=>Uk,da:()=>Bk,de:()=>qk,en:()=>ga,eo:()=>Kk,es:()=>Wk,fa:()=>Jk,fi:()=>Yk,fr:()=>Qk,frCA:()=>tS,he:()=>rS,hu:()=>oS,hy:()=>cS,id:()=>uS,is:()=>fS,it:()=>mS,ja:()=>gS,ka:()=>vS,kh:()=>wS,km:()=>ya,ko:()=>kS,lt:()=>xS,mk:()=>TS,ms:()=>AS,nl:()=>CS,no:()=>DS,ota:()=>MS,pl:()=>US,ps:()=>zS,pt:()=>BS,ru:()=>ZS,sl:()=>VS,sv:()=>GS,ta:()=>HS,th:()=>XS,tr:()=>e$,ua:()=>n$,uk:()=>va,ur:()=>i$,uz:()=>s$,vi:()=>c$,yo:()=>m$,zhCN:()=>u$,zhTW:()=>f$});var gm=S(()=>{Ak();Ck();Pk();Lk();jk();Rk();Fk();Zk();pm();Vk();Gk();Hk();Xk();eS();nS();iS();sS();lS();dS();pS();hS();yS();_S();bS();mm();SS();IS();ES();OS();NS();PS();LS();jS();RS();FS();KS();WS();JS();YS();QS();t$();r$();hm();o$();a$();l$();d$();p$();h$()});function wa(){return new _a}var g$,ym,vm,_a,xe,Vi=S(()=>{ym=Symbol("ZodOutput"),vm=Symbol("ZodInput"),_a=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let i=t[0];return this._map.set(e,i),i&&typeof i=="object"&&"id"in i&&this._idmap.set(i.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let i={...this.get(t)??{}};delete i.id;let r={...i,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};(g$=globalThis).__zod_globalRegistry??(g$.__zod_globalRegistry=wa());xe=globalThis.__zod_globalRegistry});function _m(n,e){return new n({type:"string",...C(e)})}function wm(n,e){return new n({type:"string",coerce:!0,...C(e)})}function ba(n,e){return new n({type:"string",format:"email",check:"string_format",abort:!1,...C(e)})}function Wi(n,e){return new n({type:"string",format:"guid",check:"string_format",abort:!1,...C(e)})}function ka(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,...C(e)})}function Sa(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(e)})}function $a(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(e)})}function xa(n,e){return new n({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(e)})}function Gi(n,e){return new n({type:"string",format:"url",check:"string_format",abort:!1,...C(e)})}function Ia(n,e){return new n({type:"string",format:"emoji",check:"string_format",abort:!1,...C(e)})}function Ta(n,e){return new n({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(e)})}function Ea(n,e){return new n({type:"string",format:"cuid",check:"string_format",abort:!1,...C(e)})}function Aa(n,e){return new n({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(e)})}function Oa(n,e){return new n({type:"string",format:"ulid",check:"string_format",abort:!1,...C(e)})}function Ca(n,e){return new n({type:"string",format:"xid",check:"string_format",abort:!1,...C(e)})}function Na(n,e){return new n({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(e)})}function Da(n,e){return new n({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(e)})}function Pa(n,e){return new n({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(e)})}function bm(n,e){return new n({type:"string",format:"mac",check:"string_format",abort:!1,...C(e)})}function Ma(n,e){return new n({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(e)})}function La(n,e){return new n({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(e)})}function za(n,e){return new n({type:"string",format:"base64",check:"string_format",abort:!1,...C(e)})}function ja(n,e){return new n({type:"string",format:"base64url",check:"string_format",abort:!1,...C(e)})}function Ua(n,e){return new n({type:"string",format:"e164",check:"string_format",abort:!1,...C(e)})}function Ra(n,e){return new n({type:"string",format:"jwt",check:"string_format",abort:!1,...C(e)})}function Sm(n,e){return new n({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(e)})}function $m(n,e){return new n({type:"string",format:"date",check:"string_format",...C(e)})}function xm(n,e){return new n({type:"string",format:"time",check:"string_format",precision:null,...C(e)})}function Im(n,e){return new n({type:"string",format:"duration",check:"string_format",...C(e)})}function Tm(n,e){return new n({type:"number",checks:[],...C(e)})}function Em(n,e){return new n({type:"number",coerce:!0,checks:[],...C(e)})}function Am(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"safeint",...C(e)})}function Om(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"float32",...C(e)})}function Cm(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"float64",...C(e)})}function Nm(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"int32",...C(e)})}function Dm(n,e){return new n({type:"number",check:"number_format",abort:!1,format:"uint32",...C(e)})}function Pm(n,e){return new n({type:"boolean",...C(e)})}function Mm(n,e){return new n({type:"boolean",coerce:!0,...C(e)})}function Lm(n,e){return new n({type:"bigint",...C(e)})}function zm(n,e){return new n({type:"bigint",coerce:!0,...C(e)})}function jm(n,e){return new n({type:"bigint",check:"bigint_format",abort:!1,format:"int64",...C(e)})}function Um(n,e){return new n({type:"bigint",check:"bigint_format",abort:!1,format:"uint64",...C(e)})}function Rm(n,e){return new n({type:"symbol",...C(e)})}function Bm(n,e){return new n({type:"undefined",...C(e)})}function Fm(n,e){return new n({type:"null",...C(e)})}function qm(n){return new n({type:"any"})}function Zm(n){return new n({type:"unknown"})}function Km(n,e){return new n({type:"never",...C(e)})}function Vm(n,e){return new n({type:"void",...C(e)})}function Wm(n,e){return new n({type:"date",...C(e)})}function Gm(n,e){return new n({type:"date",coerce:!0,...C(e)})}function Jm(n,e){return new n({type:"nan",...C(e)})}function mt(n,e){return new ia({check:"less_than",...C(e),value:n,inclusive:!1})}function Ze(n,e){return new ia({check:"less_than",...C(e),value:n,inclusive:!0})}function ht(n,e){return new oa({check:"greater_than",...C(e),value:n,inclusive:!1})}function De(n,e){return new oa({check:"greater_than",...C(e),value:n,inclusive:!0})}function Ba(n){return ht(0,n)}function Fa(n){return mt(0,n)}function qa(n){return Ze(0,n)}function Za(n){return De(0,n)}function tn(n,e){return new Mf({check:"multiple_of",...C(e),value:n})}function nn(n,e){return new jf({check:"max_size",...C(e),maximum:n})}function gt(n,e){return new Uf({check:"min_size",...C(e),minimum:n})}function xn(n,e){return new Rf({check:"size_equals",...C(e),size:n})}function In(n,e){return new Bf({check:"max_length",...C(e),maximum:n})}function xt(n,e){return new Ff({check:"min_length",...C(e),minimum:n})}function Tn(n,e){return new qf({check:"length_equals",...C(e),length:n})}function mr(n,e){return new Zf({check:"string_format",format:"regex",...C(e),pattern:n})}function hr(n){return new Kf({check:"string_format",format:"lowercase",...C(n)})}function gr(n){return new Vf({check:"string_format",format:"uppercase",...C(n)})}function yr(n,e){return new Wf({check:"string_format",format:"includes",...C(e),includes:n})}function vr(n,e){return new Gf({check:"string_format",format:"starts_with",...C(e),prefix:n})}function _r(n,e){return new Jf({check:"string_format",format:"ends_with",...C(e),suffix:n})}function Ka(n,e,t){return new Hf({check:"property",property:n,schema:e,...C(t)})}function wr(n,e){return new Yf({check:"mime_type",mime:n,...C(e)})}function ct(n){return new Xf({check:"overwrite",tx:n})}function br(n){return ct(e=>e.normalize(n))}function kr(){return ct(n=>n.trim())}function Sr(){return ct(n=>n.toLowerCase())}function $r(){return ct(n=>n.toUpperCase())}function xr(){return ct(n=>Wd(n))}function Hm(n,e,t){return new n({type:"array",element:e,...C(t)})}function u1(n,e,t){return new n({type:"union",options:e,...C(t)})}function d1(n,e,t){return new n({type:"union",options:e,inclusive:!1,...C(t)})}function f1(n,e,t,i){return new n({type:"union",options:t,discriminator:e,...C(i)})}function p1(n,e,t){return new n({type:"intersection",left:e,right:t})}function m1(n,e,t,i){let r=t instanceof q,o=r?i:t,s=r?t:null;return new n({type:"tuple",items:e,rest:s,...C(o)})}function h1(n,e,t,i){return new n({type:"record",keyType:e,valueType:t,...C(i)})}function g1(n,e,t,i){return new n({type:"map",keyType:e,valueType:t,...C(i)})}function y1(n,e,t){return new n({type:"set",valueType:e,...C(t)})}function v1(n,e,t){let i=Array.isArray(e)?Object.fromEntries(e.map(r=>[r,r])):e;return new n({type:"enum",entries:i,...C(t)})}function _1(n,e,t){return new n({type:"enum",entries:e,...C(t)})}function w1(n,e,t){return new n({type:"literal",values:Array.isArray(e)?e:[e],...C(t)})}function Ym(n,e){return new n({type:"file",...C(e)})}function b1(n,e){return new n({type:"transform",transform:e})}function k1(n,e){return new n({type:"optional",innerType:e})}function S1(n,e){return new n({type:"nullable",innerType:e})}function $1(n,e,t){return new n({type:"default",innerType:e,get defaultValue(){return typeof t=="function"?t():Jd(t)}})}function x1(n,e,t){return new n({type:"nonoptional",innerType:e,...C(t)})}function I1(n,e){return new n({type:"success",innerType:e})}function T1(n,e,t){return new n({type:"catch",innerType:e,catchValue:typeof t=="function"?t:()=>t})}function E1(n,e,t){return new n({type:"pipe",in:e,out:t})}function A1(n,e){return new n({type:"readonly",innerType:e})}function O1(n,e,t){return new n({type:"template_literal",parts:e,...C(t)})}function C1(n,e){return new n({type:"lazy",getter:e})}function N1(n,e){return new n({type:"promise",innerType:e})}function Xm(n,e,t){let i=C(t);return i.abort??(i.abort=!0),new n({type:"custom",check:"custom",fn:e,...i})}function Qm(n,e,t){return new n({type:"custom",check:"custom",fn:e,...C(t)})}function eh(n){let e=y$(t=>(t.addIssue=i=>{if(typeof i=="string")t.issues.push(ar(i,t.value,e._zod.def));else{let r=i;r.fatal&&(r.continue=!1),r.code??(r.code="custom"),r.input??(r.input=t.value),r.inst??(r.inst=e),r.continue??(r.continue=!e._zod.def.abort),t.issues.push(ar(r))}},n(t.value,t)));return e}function y$(n,e){let t=new oe({check:"custom",...C(e)});return t._zod.check=n,t}function th(n){let e=new oe({check:"describe"});return e._zod.onattach=[t=>{let i=xe.get(t)??{};xe.add(t,{...i,description:n})}],e._zod.check=()=>{},e}function nh(n){let e=new oe({check:"meta"});return e._zod.onattach=[t=>{let i=xe.get(t)??{};xe.add(t,{...i,...n})}],e._zod.check=()=>{},e}function rh(n,e){let t=C(e),i=t.truthy??["true","1","yes","on","y","enabled"],r=t.falsy??["false","0","no","off","n","disabled"];t.case!=="sensitive"&&(i=i.map(p=>typeof p=="string"?p.toLowerCase():p),r=r.map(p=>typeof p=="string"?p.toLowerCase():p));let o=new Set(i),s=new Set(r),a=n.Codec??qi,l=n.Boolean??Bi,c=n.String??$n,u=new c({type:"string",error:t.error}),d=new l({type:"boolean",error:t.error}),f=new a({type:"pipe",in:u,out:d,transform:((p,h)=>{let m=p;return t.case!=="sensitive"&&(m=m.toLowerCase()),o.has(m)?!0:s.has(m)?!1:(h.issues.push({code:"invalid_value",expected:"stringbool",values:[...o,...s],input:h.value,inst:f,continue:!1}),{})}),reverseTransform:((p,h)=>p===!0?i[0]||"true":r[0]||"false"),error:t.error});return f}function Ir(n,e,t,i={}){let r=C(i),o={...C(i),check:"string_format",type:"string",format:e,fn:typeof t=="function"?t:a=>t.test(a),...r};return t instanceof RegExp&&(o.pattern=t),new n(o)}var km,v$=S(()=>{sa();Vi();fm();U();km={Any:null,Minute:-1,Second:0,Millisecond:3,Microsecond:6}});function rn(n){let e=n?.target??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:n.processors??{},metadataRegistry:n?.metadata??xe,target:e,unrepresentable:n?.unrepresentable??"throw",override:n?.override??(()=>{}),io:n?.io??"output",counter:0,seen:new Map,cycles:n?.cycles??"ref",reused:n?.reused??"inline",external:n?.external??void 0}}function ee(n,e,t={path:[],schemaPath:[]}){var i;let r=n._zod.def,o=e.seen.get(n);if(o)return o.count++,t.schemaPath.includes(n)&&(o.cycle=t.path),o.schema;let s={schema:{},count:1,cycle:void 0,path:t.path};e.seen.set(n,s);let a=n._zod.toJSONSchema?.();if(a)s.schema=a;else{let u={...t,schemaPath:[...t.schemaPath,n],path:t.path};if(n._zod.processJSONSchema)n._zod.processJSONSchema(e,s.schema,u);else{let f=s.schema,p=e.processors[r.type];if(!p)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${r.type}`);p(n,e,f,u)}let d=n._zod.parent;d&&(s.ref||(s.ref=d),ee(d,e,u),e.seen.get(d).isParent=!0)}let l=e.metadataRegistry.get(n);return l&&Object.assign(s.schema,l),e.io==="input"&&Pe(n)&&(delete s.schema.examples,delete s.schema.default),e.io==="input"&&s.schema._prefault&&((i=s.schema).default??(i.default=s.schema._prefault)),delete s.schema._prefault,e.seen.get(n).schema}function on(n,e){let t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=new Map;for(let s of n.seen.entries()){let a=n.metadataRegistry.get(s[0])?.id;if(a){let l=i.get(a);if(l&&l!==s[0])throw new Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);i.set(a,s[0])}}let r=s=>{let a=n.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let d=n.external.registry.get(s[0])?.id,f=n.external.uri??(h=>h);if(d)return{ref:f(d)};let p=s[1].defId??s[1].schema.id??`schema${n.counter++}`;return s[1].defId=p,{defId:p,ref:`${f("__shared")}#/${a}/${p}`}}if(s[1]===t)return{ref:"#"};let c=`#/${a}/`,u=s[1].schema.id??`__schema${n.counter++}`;return{defId:u,ref:c+u}},o=s=>{if(s[1].schema.$ref)return;let a=s[1],{ref:l,defId:c}=r(s);a.def={...a.schema},c&&(a.defId=c);let u=a.schema;for(let d in u)delete u[d];u.$ref=l};if(n.cycles==="throw")for(let s of n.seen.entries()){let a=s[1];if(a.cycle)throw new Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
201
+
202
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let s of n.seen.entries()){let a=s[1];if(e===s[0]){o(s);continue}if(n.external){let c=n.external.registry.get(s[0])?.id;if(e!==s[0]&&c){o(s);continue}}if(n.metadataRegistry.get(s[0])?.id){o(s);continue}if(a.cycle){o(s);continue}if(a.count>1&&n.reused==="ref"){o(s);continue}}}function sn(n,e){let t=n.seen.get(e);if(!t)throw new Error("Unprocessed schema. This is a bug in Zod.");let i=s=>{let a=n.seen.get(s);if(a.ref===null)return;let l=a.def??a.schema,c={...l},u=a.ref;if(a.ref=null,u){i(u);let f=n.seen.get(u),p=f.schema;if(p.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0")?(l.allOf=l.allOf??[],l.allOf.push(p)):Object.assign(l,p),Object.assign(l,c),s._zod.parent===u)for(let m in l)m==="$ref"||m==="allOf"||m in c||delete l[m];if(p.$ref&&f.def)for(let m in l)m==="$ref"||m==="allOf"||m in f.def&&JSON.stringify(l[m])===JSON.stringify(f.def[m])&&delete l[m]}let d=s._zod.parent;if(d&&d!==u){i(d);let f=n.seen.get(d);if(f?.schema.$ref&&(l.$ref=f.schema.$ref,f.def))for(let p in l)p==="$ref"||p==="allOf"||p in f.def&&JSON.stringify(l[p])===JSON.stringify(f.def[p])&&delete l[p]}n.override({zodSchema:s,jsonSchema:l,path:a.path??[]})};for(let s of[...n.seen.entries()].reverse())i(s[0]);let r={};if(n.target==="draft-2020-12"?r.$schema="https://json-schema.org/draft/2020-12/schema":n.target==="draft-07"?r.$schema="http://json-schema.org/draft-07/schema#":n.target==="draft-04"?r.$schema="http://json-schema.org/draft-04/schema#":n.target,n.external?.uri){let s=n.external.registry.get(e)?.id;if(!s)throw new Error("Schema is missing an `id` property");r.$id=n.external.uri(s)}Object.assign(r,t.def??t.schema);let o=n.external?.defs??{};for(let s of n.seen.entries()){let a=s[1];a.def&&a.defId&&(o[a.defId]=a.def)}n.external||Object.keys(o).length>0&&(n.target==="draft-2020-12"?r.$defs=o:r.definitions=o);try{let s=JSON.parse(JSON.stringify(r));return Object.defineProperty(s,"~standard",{value:{...e["~standard"],jsonSchema:{input:Tr(e,"input",n.processors),output:Tr(e,"output",n.processors)}},enumerable:!1,writable:!1}),s}catch{throw new Error("Error converting schema to JSON.")}}function Pe(n,e){let t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);let i=n._zod.def;if(i.type==="transform")return!0;if(i.type==="array")return Pe(i.element,t);if(i.type==="set")return Pe(i.valueType,t);if(i.type==="lazy")return Pe(i.getter(),t);if(i.type==="promise"||i.type==="optional"||i.type==="nonoptional"||i.type==="nullable"||i.type==="readonly"||i.type==="default"||i.type==="prefault")return Pe(i.innerType,t);if(i.type==="intersection")return Pe(i.left,t)||Pe(i.right,t);if(i.type==="record"||i.type==="map")return Pe(i.keyType,t)||Pe(i.valueType,t);if(i.type==="pipe")return Pe(i.in,t)||Pe(i.out,t);if(i.type==="object"){for(let r in i.shape)if(Pe(i.shape[r],t))return!0;return!1}if(i.type==="union"){for(let r of i.options)if(Pe(r,t))return!0;return!1}if(i.type==="tuple"){for(let r of i.items)if(Pe(r,t))return!0;return!!(i.rest&&Pe(i.rest,t))}return!1}var ih,Tr,Ji=S(()=>{Vi();ih=(n,e={})=>t=>{let i=rn({...t,processors:e});return ee(n,i),on(i,n),sn(i,n)},Tr=(n,e,t={})=>i=>{let{libraryOptions:r,target:o}=i??{},s=rn({...r??{},target:o,io:e,processors:t});return ee(n,s),on(s,n),sn(s,n)}});function Ja(n,e){if("_idmap"in n){let i=n,r=rn({...e,processors:Va}),o={};for(let l of i._idmap.entries()){let[c,u]=l;ee(u,r)}let s={},a={registry:i,uri:e?.uri,defs:o};r.external=a;for(let l of i._idmap.entries()){let[c,u]=l;on(r,u),s[c]=sn(r,u)}if(Object.keys(o).length>0){let l=r.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[l]:o}}return{schemas:s}}let t=rn({...e,processors:Va});return ee(n,t),on(t,n),sn(t,n)}var D1,oh,sh,ah,ch,lh,uh,dh,fh,ph,mh,hh,gh,yh,vh,_h,wh,bh,kh,Sh,$h,xh,Ih,Th,Eh,Ah,Wa,Oh,Ch,Nh,Dh,Ph,Mh,Lh,zh,jh,Uh,Rh,Ga,Bh,Va,Hi=S(()=>{Ji();U();D1={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},oh=(n,e,t,i)=>{let r=t;r.type="string";let{minimum:o,maximum:s,format:a,patterns:l,contentEncoding:c}=n._zod.bag;if(typeof o=="number"&&(r.minLength=o),typeof s=="number"&&(r.maxLength=s),a&&(r.format=D1[a]??a,r.format===""&&delete r.format,a==="time"&&delete r.format),c&&(r.contentEncoding=c),l&&l.size>0){let u=[...l];u.length===1?r.pattern=u[0].source:u.length>1&&(r.allOf=[...u.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},sh=(n,e,t,i)=>{let r=t,{minimum:o,maximum:s,format:a,multipleOf:l,exclusiveMaximum:c,exclusiveMinimum:u}=n._zod.bag;typeof a=="string"&&a.includes("int")?r.type="integer":r.type="number",typeof u=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(r.minimum=u,r.exclusiveMinimum=!0):r.exclusiveMinimum=u),typeof o=="number"&&(r.minimum=o,typeof u=="number"&&e.target!=="draft-04"&&(u>=o?delete r.minimum:delete r.exclusiveMinimum)),typeof c=="number"&&(e.target==="draft-04"||e.target==="openapi-3.0"?(r.maximum=c,r.exclusiveMaximum=!0):r.exclusiveMaximum=c),typeof s=="number"&&(r.maximum=s,typeof c=="number"&&e.target!=="draft-04"&&(c<=s?delete r.maximum:delete r.exclusiveMaximum)),typeof l=="number"&&(r.multipleOf=l)},ah=(n,e,t,i)=>{t.type="boolean"},ch=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},lh=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},uh=(n,e,t,i)=>{e.target==="openapi-3.0"?(t.type="string",t.nullable=!0,t.enum=[null]):t.type="null"},dh=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},fh=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},ph=(n,e,t,i)=>{t.not={}},mh=(n,e,t,i)=>{},hh=(n,e,t,i)=>{},gh=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},yh=(n,e,t,i)=>{let r=n._zod.def,o=Oi(r.entries);o.every(s=>typeof s=="number")&&(t.type="number"),o.every(s=>typeof s=="string")&&(t.type="string"),t.enum=o},vh=(n,e,t,i)=>{let r=n._zod.def,o=[];for(let s of r.values)if(s===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof s=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");o.push(Number(s))}else o.push(s);if(o.length!==0)if(o.length===1){let s=o[0];t.type=s===null?"null":typeof s,e.target==="draft-04"||e.target==="openapi-3.0"?t.enum=[s]:t.const=s}else o.every(s=>typeof s=="number")&&(t.type="number"),o.every(s=>typeof s=="string")&&(t.type="string"),o.every(s=>typeof s=="boolean")&&(t.type="boolean"),o.every(s=>s===null)&&(t.type="null"),t.enum=o},_h=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},wh=(n,e,t,i)=>{let r=t,o=n._zod.pattern;if(!o)throw new Error("Pattern not found in template literal");r.type="string",r.pattern=o.source},bh=(n,e,t,i)=>{let r=t,o={type:"string",format:"binary",contentEncoding:"binary"},{minimum:s,maximum:a,mime:l}=n._zod.bag;s!==void 0&&(o.minLength=s),a!==void 0&&(o.maxLength=a),l?l.length===1?(o.contentMediaType=l[0],Object.assign(r,o)):(Object.assign(r,o),r.anyOf=l.map(c=>({contentMediaType:c}))):Object.assign(r,o)},kh=(n,e,t,i)=>{t.type="boolean"},Sh=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},$h=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},xh=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Ih=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},Th=(n,e,t,i)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},Eh=(n,e,t,i)=>{let r=t,o=n._zod.def,{minimum:s,maximum:a}=n._zod.bag;typeof s=="number"&&(r.minItems=s),typeof a=="number"&&(r.maxItems=a),r.type="array",r.items=ee(o.element,e,{...i,path:[...i.path,"items"]})},Ah=(n,e,t,i)=>{let r=t,o=n._zod.def;r.type="object",r.properties={};let s=o.shape;for(let c in s)r.properties[c]=ee(s[c],e,{...i,path:[...i.path,"properties",c]});let a=new Set(Object.keys(s)),l=new Set([...a].filter(c=>{let u=o.shape[c]._zod;return e.io==="input"?u.optin===void 0:u.optout===void 0}));l.size>0&&(r.required=Array.from(l)),o.catchall?._zod.def.type==="never"?r.additionalProperties=!1:o.catchall?o.catchall&&(r.additionalProperties=ee(o.catchall,e,{...i,path:[...i.path,"additionalProperties"]})):e.io==="output"&&(r.additionalProperties=!1)},Wa=(n,e,t,i)=>{let r=n._zod.def,o=r.inclusive===!1,s=r.options.map((a,l)=>ee(a,e,{...i,path:[...i.path,o?"oneOf":"anyOf",l]}));o?t.oneOf=s:t.anyOf=s},Oh=(n,e,t,i)=>{let r=n._zod.def,o=ee(r.left,e,{...i,path:[...i.path,"allOf",0]}),s=ee(r.right,e,{...i,path:[...i.path,"allOf",1]}),a=c=>"allOf"in c&&Object.keys(c).length===1,l=[...a(o)?o.allOf:[o],...a(s)?s.allOf:[s]];t.allOf=l},Ch=(n,e,t,i)=>{let r=t,o=n._zod.def;r.type="array";let s=e.target==="draft-2020-12"?"prefixItems":"items",a=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",l=o.items.map((f,p)=>ee(f,e,{...i,path:[...i.path,s,p]})),c=o.rest?ee(o.rest,e,{...i,path:[...i.path,a,...e.target==="openapi-3.0"?[o.items.length]:[]]}):null;e.target==="draft-2020-12"?(r.prefixItems=l,c&&(r.items=c)):e.target==="openapi-3.0"?(r.items={anyOf:l},c&&r.items.anyOf.push(c),r.minItems=l.length,c||(r.maxItems=l.length)):(r.items=l,c&&(r.additionalItems=c));let{minimum:u,maximum:d}=n._zod.bag;typeof u=="number"&&(r.minItems=u),typeof d=="number"&&(r.maxItems=d)},Nh=(n,e,t,i)=>{let r=t,o=n._zod.def;r.type="object";let s=o.keyType,l=s._zod.bag?.patterns;if(o.mode==="loose"&&l&&l.size>0){let u=ee(o.valueType,e,{...i,path:[...i.path,"patternProperties","*"]});r.patternProperties={};for(let d of l)r.patternProperties[d.source]=u}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(r.propertyNames=ee(o.keyType,e,{...i,path:[...i.path,"propertyNames"]})),r.additionalProperties=ee(o.valueType,e,{...i,path:[...i.path,"additionalProperties"]});let c=s._zod.values;if(c){let u=[...c].filter(d=>typeof d=="string"||typeof d=="number");u.length>0&&(r.required=u)}},Dh=(n,e,t,i)=>{let r=n._zod.def,o=ee(r.innerType,e,i),s=e.seen.get(n);e.target==="openapi-3.0"?(s.ref=r.innerType,t.nullable=!0):t.anyOf=[o,{type:"null"}]},Ph=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType},Mh=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType,t.default=JSON.parse(JSON.stringify(r.defaultValue))},Lh=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType,e.io==="input"&&(t._prefault=JSON.parse(JSON.stringify(r.defaultValue)))},zh=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType;let s;try{s=r.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}t.default=s},jh=(n,e,t,i)=>{let r=n._zod.def,o=e.io==="input"?r.in._zod.def.type==="transform"?r.out:r.in:r.out;ee(o,e,i);let s=e.seen.get(n);s.ref=o},Uh=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType,t.readOnly=!0},Rh=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType},Ga=(n,e,t,i)=>{let r=n._zod.def;ee(r.innerType,e,i);let o=e.seen.get(n);o.ref=r.innerType},Bh=(n,e,t,i)=>{let r=n._zod.innerType;ee(r,e,i);let o=e.seen.get(n);o.ref=r},Va={string:oh,number:sh,boolean:ah,bigint:ch,symbol:lh,null:uh,undefined:dh,void:fh,never:ph,any:mh,unknown:hh,date:gh,enum:yh,literal:vh,nan:_h,template_literal:wh,file:bh,success:kh,custom:Sh,function:$h,transform:xh,map:Ih,set:Th,array:Eh,object:Ah,union:Wa,intersection:Oh,tuple:Ch,record:Nh,nullable:Dh,nonoptional:Ph,default:Mh,prefault:Lh,catch:zh,pipe:jh,readonly:Uh,promise:Rh,optional:Ga,lazy:Bh}});var Ha,_$=S(()=>{Hi();Ji();Ha=class{get metadataRegistry(){return this.ctx.metadataRegistry}get target(){return this.ctx.target}get unrepresentable(){return this.ctx.unrepresentable}get override(){return this.ctx.override}get io(){return this.ctx.io}get counter(){return this.ctx.counter}set counter(e){this.ctx.counter=e}get seen(){return this.ctx.seen}constructor(e){let t=e?.target??"draft-2020-12";t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),this.ctx=rn({processors:Va,target:t,...e?.metadata&&{metadata:e.metadata},...e?.unrepresentable&&{unrepresentable:e.unrepresentable},...e?.override&&{override:e.override},...e?.io&&{io:e.io}})}process(e,t={path:[],schemaPath:[]}){return ee(e,this.ctx,t)}emit(e,t){t&&(t.cycles&&(this.ctx.cycles=t.cycles),t.reused&&(this.ctx.reused=t.reused),t.external&&(this.ctx.external=t.external)),on(this.ctx,e);let i=sn(this.ctx,e),{"~standard":r,...o}=i;return o}}});var w$={};var b$=S(()=>{});var It={};we(It,{$ZodAny:()=>Pp,$ZodArray:()=>Up,$ZodAsyncError:()=>at,$ZodBase64:()=>$p,$ZodBase64URL:()=>xp,$ZodBigInt:()=>pa,$ZodBigIntFormat:()=>Op,$ZodBoolean:()=>Bi,$ZodCIDRv4:()=>bp,$ZodCIDRv6:()=>kp,$ZodCUID:()=>lp,$ZodCUID2:()=>up,$ZodCatch:()=>rm,$ZodCheck:()=>oe,$ZodCheckBigIntFormat:()=>zf,$ZodCheckEndsWith:()=>Jf,$ZodCheckGreaterThan:()=>oa,$ZodCheckIncludes:()=>Wf,$ZodCheckLengthEquals:()=>qf,$ZodCheckLessThan:()=>ia,$ZodCheckLowerCase:()=>Kf,$ZodCheckMaxLength:()=>Bf,$ZodCheckMaxSize:()=>jf,$ZodCheckMimeType:()=>Yf,$ZodCheckMinLength:()=>Ff,$ZodCheckMinSize:()=>Uf,$ZodCheckMultipleOf:()=>Mf,$ZodCheckNumberFormat:()=>Lf,$ZodCheckOverwrite:()=>Xf,$ZodCheckProperty:()=>Hf,$ZodCheckRegex:()=>Zf,$ZodCheckSizeEquals:()=>Rf,$ZodCheckStartsWith:()=>Gf,$ZodCheckStringFormat:()=>fr,$ZodCheckUpperCase:()=>Vf,$ZodCodec:()=>qi,$ZodCustom:()=>dm,$ZodCustomStringFormat:()=>Ep,$ZodDate:()=>jp,$ZodDefault:()=>Qp,$ZodDiscriminatedUnion:()=>Fp,$ZodE164:()=>Ip,$ZodEmail:()=>op,$ZodEmoji:()=>ap,$ZodEncodeError:()=>Ht,$ZodEnum:()=>Wp,$ZodError:()=>Mi,$ZodExactOptional:()=>Yp,$ZodFile:()=>Jp,$ZodFunction:()=>cm,$ZodGUID:()=>rp,$ZodIPv4:()=>vp,$ZodIPv6:()=>_p,$ZodISODate:()=>hp,$ZodISODateTime:()=>mp,$ZodISODuration:()=>yp,$ZodISOTime:()=>gp,$ZodIntersection:()=>qp,$ZodJWT:()=>Tp,$ZodKSUID:()=>pp,$ZodLazy:()=>um,$ZodLiteral:()=>Gp,$ZodMAC:()=>wp,$ZodMap:()=>Kp,$ZodNaN:()=>im,$ZodNanoID:()=>cp,$ZodNever:()=>Lp,$ZodNonOptional:()=>tm,$ZodNull:()=>Dp,$ZodNullable:()=>Xp,$ZodNumber:()=>fa,$ZodNumberFormat:()=>Ap,$ZodObject:()=>Tk,$ZodObjectJIT:()=>Rp,$ZodOptional:()=>ha,$ZodPipe:()=>om,$ZodPrefault:()=>em,$ZodPromise:()=>lm,$ZodReadonly:()=>sm,$ZodRealError:()=>Ue,$ZodRecord:()=>Zp,$ZodRegistry:()=>_a,$ZodSet:()=>Vp,$ZodString:()=>$n,$ZodStringFormat:()=>re,$ZodSuccess:()=>nm,$ZodSymbol:()=>Cp,$ZodTemplateLiteral:()=>am,$ZodTransform:()=>Hp,$ZodTuple:()=>ma,$ZodType:()=>q,$ZodULID:()=>dp,$ZodURL:()=>sp,$ZodUUID:()=>ip,$ZodUndefined:()=>Np,$ZodUnion:()=>Fi,$ZodUnknown:()=>Mp,$ZodVoid:()=>zp,$ZodXID:()=>fp,$ZodXor:()=>Bp,$brand:()=>Fs,$constructor:()=>v,$input:()=>vm,$output:()=>ym,Doc:()=>Ri,JSONSchema:()=>w$,JSONSchemaGenerator:()=>Ha,NEVER:()=>qd,TimePrecision:()=>km,_any:()=>qm,_array:()=>Hm,_base64:()=>za,_base64url:()=>ja,_bigint:()=>Lm,_boolean:()=>Pm,_catch:()=>T1,_check:()=>y$,_cidrv4:()=>Ma,_cidrv6:()=>La,_coercedBigint:()=>zm,_coercedBoolean:()=>Mm,_coercedDate:()=>Gm,_coercedNumber:()=>Em,_coercedString:()=>wm,_cuid:()=>Ea,_cuid2:()=>Aa,_custom:()=>Xm,_date:()=>Wm,_decode:()=>Gs,_decodeAsync:()=>Hs,_default:()=>$1,_discriminatedUnion:()=>f1,_e164:()=>Ua,_email:()=>ba,_emoji:()=>Ia,_encode:()=>Ws,_encodeAsync:()=>Js,_endsWith:()=>_r,_enum:()=>v1,_file:()=>Ym,_float32:()=>Om,_float64:()=>Cm,_gt:()=>ht,_gte:()=>De,_guid:()=>Wi,_includes:()=>yr,_int:()=>Am,_int32:()=>Nm,_int64:()=>jm,_intersection:()=>p1,_ipv4:()=>Da,_ipv6:()=>Pa,_isoDate:()=>$m,_isoDateTime:()=>Sm,_isoDuration:()=>Im,_isoTime:()=>xm,_jwt:()=>Ra,_ksuid:()=>Na,_lazy:()=>C1,_length:()=>Tn,_literal:()=>w1,_lowercase:()=>hr,_lt:()=>mt,_lte:()=>Ze,_mac:()=>bm,_map:()=>g1,_max:()=>Ze,_maxLength:()=>In,_maxSize:()=>nn,_mime:()=>wr,_min:()=>De,_minLength:()=>xt,_minSize:()=>gt,_multipleOf:()=>tn,_nan:()=>Jm,_nanoid:()=>Ta,_nativeEnum:()=>_1,_negative:()=>Fa,_never:()=>Km,_nonnegative:()=>Za,_nonoptional:()=>x1,_nonpositive:()=>qa,_normalize:()=>br,_null:()=>Fm,_nullable:()=>S1,_number:()=>Tm,_optional:()=>k1,_overwrite:()=>ct,_parse:()=>cr,_parseAsync:()=>lr,_pipe:()=>E1,_positive:()=>Ba,_promise:()=>N1,_property:()=>Ka,_readonly:()=>A1,_record:()=>h1,_refine:()=>Qm,_regex:()=>mr,_safeDecode:()=>Xs,_safeDecodeAsync:()=>ea,_safeEncode:()=>Ys,_safeEncodeAsync:()=>Qs,_safeParse:()=>ur,_safeParseAsync:()=>dr,_set:()=>y1,_size:()=>xn,_slugify:()=>xr,_startsWith:()=>vr,_string:()=>_m,_stringFormat:()=>Ir,_stringbool:()=>rh,_success:()=>I1,_superRefine:()=>eh,_symbol:()=>Rm,_templateLiteral:()=>O1,_toLowerCase:()=>Sr,_toUpperCase:()=>$r,_transform:()=>b1,_trim:()=>kr,_tuple:()=>m1,_uint32:()=>Dm,_uint64:()=>Um,_ulid:()=>Oa,_undefined:()=>Bm,_union:()=>u1,_unknown:()=>Zm,_uppercase:()=>gr,_url:()=>Gi,_uuid:()=>ka,_uuidv4:()=>Sa,_uuidv6:()=>$a,_uuidv7:()=>xa,_void:()=>Vm,_xid:()=>Ca,_xor:()=>d1,clone:()=>Ne,config:()=>fe,createStandardJSONSchemaMethod:()=>Tr,createToJSONSchemaMethod:()=>ih,decode:()=>MD,decodeAsync:()=>zD,describe:()=>th,encode:()=>PD,encodeAsync:()=>LD,extractDefs:()=>on,finalize:()=>sn,flattenError:()=>Li,formatError:()=>zi,globalConfig:()=>Ei,globalRegistry:()=>xe,initializeContext:()=>rn,isValidBase64:()=>Sp,isValidBase64URL:()=>Sk,isValidJWT:()=>$k,locales:()=>Ki,meta:()=>nh,parse:()=>Ks,parseAsync:()=>Vs,prettifyError:()=>tf,process:()=>ee,regexes:()=>Ye,registry:()=>wa,safeDecode:()=>UD,safeDecodeAsync:()=>BD,safeEncode:()=>jD,safeEncodeAsync:()=>RD,safeParse:()=>rf,safeParseAsync:()=>of,toDotPath:()=>ok,toJSONSchema:()=>Ja,treeifyError:()=>ef,util:()=>E,version:()=>ep});var Re=S(()=>{ir();sf();nf();fm();sa();tp();U();ra();gm();Vi();Qf();v$();Ji();Hi();_$();b$()});var Ya={};we(Ya,{endsWith:()=>_r,gt:()=>ht,gte:()=>De,includes:()=>yr,length:()=>Tn,lowercase:()=>hr,lt:()=>mt,lte:()=>Ze,maxLength:()=>In,maxSize:()=>nn,mime:()=>wr,minLength:()=>xt,minSize:()=>gt,multipleOf:()=>tn,negative:()=>Fa,nonnegative:()=>Za,nonpositive:()=>qa,normalize:()=>br,overwrite:()=>ct,positive:()=>Ba,property:()=>Ka,regex:()=>mr,size:()=>xn,slugify:()=>xr,startsWith:()=>vr,toLowerCase:()=>Sr,toUpperCase:()=>$r,trim:()=>kr,uppercase:()=>gr});var Xa=S(()=>{Re()});var Er={};we(Er,{ZodISODate:()=>ec,ZodISODateTime:()=>Qa,ZodISODuration:()=>nc,ZodISOTime:()=>tc,date:()=>qh,datetime:()=>Fh,duration:()=>Kh,time:()=>Zh});function Fh(n){return Sm(Qa,n)}function qh(n){return $m(ec,n)}function Zh(n){return xm(tc,n)}function Kh(n){return Im(nc,n)}var Qa,ec,tc,nc,Yi=S(()=>{Re();Qi();Qa=v("ZodISODateTime",(n,e)=>{mp.init(n,e),ie.init(n,e)});ec=v("ZodISODate",(n,e)=>{hp.init(n,e),ie.init(n,e)});tc=v("ZodISOTime",(n,e)=>{gp.init(n,e),ie.init(n,e)});nc=v("ZodISODuration",(n,e)=>{yp.init(n,e),ie.init(n,e)})});var k$,M1,Be,Vh=S(()=>{Re();Re();U();k$=(n,e)=>{Mi.init(n,e),n.name="ZodError",Object.defineProperties(n,{format:{value:t=>zi(n,t)},flatten:{value:t=>Li(n,t)},addIssue:{value:t=>{n.issues.push(t),n.message=JSON.stringify(n.issues,or,2)}},addIssues:{value:t=>{n.issues.push(...t),n.message=JSON.stringify(n.issues,or,2)}},isEmpty:{get(){return n.issues.length===0}}})},M1=v("ZodError",k$),Be=v("ZodError",k$,{Parent:Error})});var Wh,Gh,Jh,Hh,Yh,Xh,Qh,eg,tg,ng,rg,ig,og=S(()=>{Re();Vh();Wh=cr(Be),Gh=lr(Be),Jh=ur(Be),Hh=dr(Be),Yh=Ws(Be),Xh=Gs(Be),Qh=Js(Be),eg=Hs(Be),tg=Ys(Be),ng=Xs(Be),rg=Qs(Be),ig=ea(Be)});var Xi={};we(Xi,{ZodAny:()=>pg,ZodArray:()=>yg,ZodBase64:()=>vc,ZodBase64URL:()=>_c,ZodBigInt:()=>Pr,ZodBigIntFormat:()=>kc,ZodBoolean:()=>Dr,ZodCIDRv4:()=>gc,ZodCIDRv6:()=>yc,ZodCUID:()=>lc,ZodCUID2:()=>uc,ZodCatch:()=>Ug,ZodCodec:()=>Oc,ZodCustom:()=>uo,ZodCustomStringFormat:()=>Cr,ZodDate:()=>oo,ZodDefault:()=>Dg,ZodDiscriminatedUnion:()=>_g,ZodE164:()=>wc,ZodEmail:()=>sc,ZodEmoji:()=>ac,ZodEnum:()=>Ar,ZodExactOptional:()=>Og,ZodFile:()=>Eg,ZodFunction:()=>Gg,ZodGUID:()=>eo,ZodIPv4:()=>mc,ZodIPv6:()=>hc,ZodIntersection:()=>wg,ZodJWT:()=>bc,ZodKSUID:()=>pc,ZodLazy:()=>Kg,ZodLiteral:()=>Tg,ZodMAC:()=>sg,ZodMap:()=>xg,ZodNaN:()=>Bg,ZodNanoID:()=>cc,ZodNever:()=>hg,ZodNonOptional:()=>Ec,ZodNull:()=>dg,ZodNullable:()=>Ng,ZodNumber:()=>Nr,ZodNumberFormat:()=>An,ZodObject:()=>ao,ZodOptional:()=>Tc,ZodPipe:()=>Ac,ZodPrefault:()=>Mg,ZodPromise:()=>Wg,ZodReadonly:()=>Fg,ZodRecord:()=>lo,ZodSet:()=>Ig,ZodString:()=>Or,ZodStringFormat:()=>ie,ZodSuccess:()=>jg,ZodSymbol:()=>lg,ZodTemplateLiteral:()=>Zg,ZodTransform:()=>Ag,ZodTuple:()=>kg,ZodType:()=>K,ZodULID:()=>dc,ZodURL:()=>io,ZodUUID:()=>yt,ZodUndefined:()=>ug,ZodUnion:()=>co,ZodUnknown:()=>mg,ZodVoid:()=>gg,ZodXID:()=>fc,ZodXor:()=>vg,_ZodString:()=>oc,_default:()=>Pg,_function:()=>Ex,any:()=>sx,array:()=>so,base64:()=>q$,base64url:()=>Z$,bigint:()=>tx,boolean:()=>cg,catch:()=>Rg,check:()=>Ax,cidrv4:()=>B$,cidrv6:()=>F$,codec:()=>xx,cuid:()=>D$,cuid2:()=>P$,custom:()=>Ox,date:()=>cx,describe:()=>Cx,discriminatedUnion:()=>mx,e164:()=>K$,email:()=>S$,emoji:()=>C$,enum:()=>xc,exactOptional:()=>Cg,file:()=>bx,float32:()=>Y$,float64:()=>X$,function:()=>Ex,guid:()=>$$,hash:()=>H$,hex:()=>J$,hostname:()=>G$,httpUrl:()=>O$,instanceof:()=>Dx,int:()=>ic,int32:()=>Q$,int64:()=>nx,intersection:()=>bg,ipv4:()=>j$,ipv6:()=>R$,json:()=>Mx,jwt:()=>V$,keyof:()=>lx,ksuid:()=>z$,lazy:()=>Vg,literal:()=>wx,looseObject:()=>fx,looseRecord:()=>gx,mac:()=>U$,map:()=>yx,meta:()=>Nx,nan:()=>$x,nanoid:()=>N$,nativeEnum:()=>_x,never:()=>Sc,nonoptional:()=>zg,null:()=>fg,nullable:()=>no,nullish:()=>kx,number:()=>ag,object:()=>ux,optional:()=>to,partialRecord:()=>hx,pipe:()=>ro,prefault:()=>Lg,preprocess:()=>Lx,promise:()=>Tx,readonly:()=>qg,record:()=>$g,refine:()=>Jg,set:()=>vx,strictObject:()=>dx,string:()=>rc,stringFormat:()=>W$,stringbool:()=>Px,success:()=>Sx,superRefine:()=>Hg,symbol:()=>ix,templateLiteral:()=>Ix,transform:()=>Ic,tuple:()=>Sg,uint32:()=>ex,uint64:()=>rx,ulid:()=>M$,undefined:()=>ox,union:()=>$c,unknown:()=>En,url:()=>A$,uuid:()=>x$,uuidv4:()=>I$,uuidv6:()=>T$,uuidv7:()=>E$,void:()=>ax,xid:()=>L$,xor:()=>px});function rc(n){return _m(Or,n)}function S$(n){return ba(sc,n)}function $$(n){return Wi(eo,n)}function x$(n){return ka(yt,n)}function I$(n){return Sa(yt,n)}function T$(n){return $a(yt,n)}function E$(n){return xa(yt,n)}function A$(n){return Gi(io,n)}function O$(n){return Gi(io,{protocol:/^https?$/,hostname:Ye.domain,...E.normalizeParams(n)})}function C$(n){return Ia(ac,n)}function N$(n){return Ta(cc,n)}function D$(n){return Ea(lc,n)}function P$(n){return Aa(uc,n)}function M$(n){return Oa(dc,n)}function L$(n){return Ca(fc,n)}function z$(n){return Na(pc,n)}function j$(n){return Da(mc,n)}function U$(n){return bm(sg,n)}function R$(n){return Pa(hc,n)}function B$(n){return Ma(gc,n)}function F$(n){return La(yc,n)}function q$(n){return za(vc,n)}function Z$(n){return ja(_c,n)}function K$(n){return Ua(wc,n)}function V$(n){return Ra(bc,n)}function W$(n,e,t={}){return Ir(Cr,n,e,t)}function G$(n){return Ir(Cr,"hostname",Ye.hostname,n)}function J$(n){return Ir(Cr,"hex",Ye.hex,n)}function H$(n,e){let t=e?.enc??"hex",i=`${n}_${t}`,r=Ye[i];if(!r)throw new Error(`Unrecognized hash format: ${i}`);return Ir(Cr,i,r,e)}function ag(n){return Tm(Nr,n)}function ic(n){return Am(An,n)}function Y$(n){return Om(An,n)}function X$(n){return Cm(An,n)}function Q$(n){return Nm(An,n)}function ex(n){return Dm(An,n)}function cg(n){return Pm(Dr,n)}function tx(n){return Lm(Pr,n)}function nx(n){return jm(kc,n)}function rx(n){return Um(kc,n)}function ix(n){return Rm(lg,n)}function ox(n){return Bm(ug,n)}function fg(n){return Fm(dg,n)}function sx(){return qm(pg)}function En(){return Zm(mg)}function Sc(n){return Km(hg,n)}function ax(n){return Vm(gg,n)}function cx(n){return Wm(oo,n)}function so(n,e){return Hm(yg,n,e)}function lx(n){let e=n._zod.def.shape;return xc(Object.keys(e))}function ux(n,e){let t={type:"object",shape:n??{},...E.normalizeParams(e)};return new ao(t)}function dx(n,e){return new ao({type:"object",shape:n,catchall:Sc(),...E.normalizeParams(e)})}function fx(n,e){return new ao({type:"object",shape:n,catchall:En(),...E.normalizeParams(e)})}function $c(n,e){return new co({type:"union",options:n,...E.normalizeParams(e)})}function px(n,e){return new vg({type:"union",options:n,inclusive:!1,...E.normalizeParams(e)})}function mx(n,e,t){return new _g({type:"union",options:e,discriminator:n,...E.normalizeParams(t)})}function bg(n,e){return new wg({type:"intersection",left:n,right:e})}function Sg(n,e,t){let i=e instanceof q,r=i?t:e,o=i?e:null;return new kg({type:"tuple",items:n,rest:o,...E.normalizeParams(r)})}function $g(n,e,t){return new lo({type:"record",keyType:n,valueType:e,...E.normalizeParams(t)})}function hx(n,e,t){let i=Ne(n);return i._zod.values=void 0,new lo({type:"record",keyType:i,valueType:e,...E.normalizeParams(t)})}function gx(n,e,t){return new lo({type:"record",keyType:n,valueType:e,mode:"loose",...E.normalizeParams(t)})}function yx(n,e,t){return new xg({type:"map",keyType:n,valueType:e,...E.normalizeParams(t)})}function vx(n,e){return new Ig({type:"set",valueType:n,...E.normalizeParams(e)})}function xc(n,e){let t=Array.isArray(n)?Object.fromEntries(n.map(i=>[i,i])):n;return new Ar({type:"enum",entries:t,...E.normalizeParams(e)})}function _x(n,e){return new Ar({type:"enum",entries:n,...E.normalizeParams(e)})}function wx(n,e){return new Tg({type:"literal",values:Array.isArray(n)?n:[n],...E.normalizeParams(e)})}function bx(n){return Ym(Eg,n)}function Ic(n){return new Ag({type:"transform",transform:n})}function to(n){return new Tc({type:"optional",innerType:n})}function Cg(n){return new Og({type:"optional",innerType:n})}function no(n){return new Ng({type:"nullable",innerType:n})}function kx(n){return to(no(n))}function Pg(n,e){return new Dg({type:"default",innerType:n,get defaultValue(){return typeof e=="function"?e():E.shallowClone(e)}})}function Lg(n,e){return new Mg({type:"prefault",innerType:n,get defaultValue(){return typeof e=="function"?e():E.shallowClone(e)}})}function zg(n,e){return new Ec({type:"nonoptional",innerType:n,...E.normalizeParams(e)})}function Sx(n){return new jg({type:"success",innerType:n})}function Rg(n,e){return new Ug({type:"catch",innerType:n,catchValue:typeof e=="function"?e:()=>e})}function $x(n){return Jm(Bg,n)}function ro(n,e){return new Ac({type:"pipe",in:n,out:e})}function xx(n,e,t){return new Oc({type:"pipe",in:n,out:e,transform:t.decode,reverseTransform:t.encode})}function qg(n){return new Fg({type:"readonly",innerType:n})}function Ix(n,e){return new Zg({type:"template_literal",parts:n,...E.normalizeParams(e)})}function Vg(n){return new Kg({type:"lazy",getter:n})}function Tx(n){return new Wg({type:"promise",innerType:n})}function Ex(n){return new Gg({type:"function",input:Array.isArray(n?.input)?Sg(n?.input):n?.input??so(En()),output:n?.output??En()})}function Ax(n){let e=new oe({check:"custom"});return e._zod.check=n,e}function Ox(n,e){return Xm(uo,n??(()=>!0),e)}function Jg(n,e={}){return Qm(uo,n,e)}function Hg(n){return eh(n)}function Dx(n,e={}){let t=new uo({type:"custom",check:"custom",fn:i=>i instanceof n,abort:!0,...E.normalizeParams(e)});return t._zod.bag.Class=n,t._zod.check=i=>{i.value instanceof n||i.issues.push({code:"invalid_type",expected:n.name,input:i.value,inst:t,path:[...t._zod.def.path??[]]})},t}function Mx(n){let e=Vg(()=>$c([rc(n),ag(),cg(),fg(),so(e),$g(rc(),e)]));return e}function Lx(n,e){return ro(Ic(n),e)}var K,oc,Or,ie,sc,eo,yt,io,ac,cc,lc,uc,dc,fc,pc,mc,sg,hc,gc,yc,vc,_c,wc,bc,Cr,Nr,An,Dr,Pr,kc,lg,ug,dg,pg,mg,hg,gg,oo,yg,ao,co,vg,_g,wg,kg,lo,xg,Ig,Ar,Tg,Eg,Ag,Tc,Og,Ng,Dg,Mg,Ec,jg,Ug,Bg,Ac,Oc,Fg,Zg,Kg,Wg,Gg,uo,Cx,Nx,Px,Qi=S(()=>{Re();Re();Hi();Ji();Xa();Yi();og();K=v("ZodType",(n,e)=>(q.init(n,e),Object.assign(n["~standard"],{jsonSchema:{input:Tr(n,"input"),output:Tr(n,"output")}}),n.toJSONSchema=ih(n,{}),n.def=e,n.type=e.type,Object.defineProperty(n,"_def",{value:e}),n.check=(...t)=>n.clone(E.mergeDefs(e,{checks:[...e.checks??[],...t.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0}),n.with=n.check,n.clone=(t,i)=>Ne(n,t,i),n.brand=()=>n,n.register=((t,i)=>(t.add(n,i),n)),n.parse=(t,i)=>Wh(n,t,i,{callee:n.parse}),n.safeParse=(t,i)=>Jh(n,t,i),n.parseAsync=async(t,i)=>Gh(n,t,i,{callee:n.parseAsync}),n.safeParseAsync=async(t,i)=>Hh(n,t,i),n.spa=n.safeParseAsync,n.encode=(t,i)=>Yh(n,t,i),n.decode=(t,i)=>Xh(n,t,i),n.encodeAsync=async(t,i)=>Qh(n,t,i),n.decodeAsync=async(t,i)=>eg(n,t,i),n.safeEncode=(t,i)=>tg(n,t,i),n.safeDecode=(t,i)=>ng(n,t,i),n.safeEncodeAsync=async(t,i)=>rg(n,t,i),n.safeDecodeAsync=async(t,i)=>ig(n,t,i),n.refine=(t,i)=>n.check(Jg(t,i)),n.superRefine=t=>n.check(Hg(t)),n.overwrite=t=>n.check(ct(t)),n.optional=()=>to(n),n.exactOptional=()=>Cg(n),n.nullable=()=>no(n),n.nullish=()=>to(no(n)),n.nonoptional=t=>zg(n,t),n.array=()=>so(n),n.or=t=>$c([n,t]),n.and=t=>bg(n,t),n.transform=t=>ro(n,Ic(t)),n.default=t=>Pg(n,t),n.prefault=t=>Lg(n,t),n.catch=t=>Rg(n,t),n.pipe=t=>ro(n,t),n.readonly=()=>qg(n),n.describe=t=>{let i=n.clone();return xe.add(i,{description:t}),i},Object.defineProperty(n,"description",{get(){return xe.get(n)?.description},configurable:!0}),n.meta=(...t)=>{if(t.length===0)return xe.get(n);let i=n.clone();return xe.add(i,t[0]),i},n.isOptional=()=>n.safeParse(void 0).success,n.isNullable=()=>n.safeParse(null).success,n.apply=t=>t(n),n)),oc=v("_ZodString",(n,e)=>{$n.init(n,e),K.init(n,e),n._zod.processJSONSchema=(i,r,o)=>oh(n,i,r,o);let t=n._zod.bag;n.format=t.format??null,n.minLength=t.minimum??null,n.maxLength=t.maximum??null,n.regex=(...i)=>n.check(mr(...i)),n.includes=(...i)=>n.check(yr(...i)),n.startsWith=(...i)=>n.check(vr(...i)),n.endsWith=(...i)=>n.check(_r(...i)),n.min=(...i)=>n.check(xt(...i)),n.max=(...i)=>n.check(In(...i)),n.length=(...i)=>n.check(Tn(...i)),n.nonempty=(...i)=>n.check(xt(1,...i)),n.lowercase=i=>n.check(hr(i)),n.uppercase=i=>n.check(gr(i)),n.trim=()=>n.check(kr()),n.normalize=(...i)=>n.check(br(...i)),n.toLowerCase=()=>n.check(Sr()),n.toUpperCase=()=>n.check($r()),n.slugify=()=>n.check(xr())}),Or=v("ZodString",(n,e)=>{$n.init(n,e),oc.init(n,e),n.email=t=>n.check(ba(sc,t)),n.url=t=>n.check(Gi(io,t)),n.jwt=t=>n.check(Ra(bc,t)),n.emoji=t=>n.check(Ia(ac,t)),n.guid=t=>n.check(Wi(eo,t)),n.uuid=t=>n.check(ka(yt,t)),n.uuidv4=t=>n.check(Sa(yt,t)),n.uuidv6=t=>n.check($a(yt,t)),n.uuidv7=t=>n.check(xa(yt,t)),n.nanoid=t=>n.check(Ta(cc,t)),n.guid=t=>n.check(Wi(eo,t)),n.cuid=t=>n.check(Ea(lc,t)),n.cuid2=t=>n.check(Aa(uc,t)),n.ulid=t=>n.check(Oa(dc,t)),n.base64=t=>n.check(za(vc,t)),n.base64url=t=>n.check(ja(_c,t)),n.xid=t=>n.check(Ca(fc,t)),n.ksuid=t=>n.check(Na(pc,t)),n.ipv4=t=>n.check(Da(mc,t)),n.ipv6=t=>n.check(Pa(hc,t)),n.cidrv4=t=>n.check(Ma(gc,t)),n.cidrv6=t=>n.check(La(yc,t)),n.e164=t=>n.check(Ua(wc,t)),n.datetime=t=>n.check(Fh(t)),n.date=t=>n.check(qh(t)),n.time=t=>n.check(Zh(t)),n.duration=t=>n.check(Kh(t))});ie=v("ZodStringFormat",(n,e)=>{re.init(n,e),oc.init(n,e)}),sc=v("ZodEmail",(n,e)=>{op.init(n,e),ie.init(n,e)});eo=v("ZodGUID",(n,e)=>{rp.init(n,e),ie.init(n,e)});yt=v("ZodUUID",(n,e)=>{ip.init(n,e),ie.init(n,e)});io=v("ZodURL",(n,e)=>{sp.init(n,e),ie.init(n,e)});ac=v("ZodEmoji",(n,e)=>{ap.init(n,e),ie.init(n,e)});cc=v("ZodNanoID",(n,e)=>{cp.init(n,e),ie.init(n,e)});lc=v("ZodCUID",(n,e)=>{lp.init(n,e),ie.init(n,e)});uc=v("ZodCUID2",(n,e)=>{up.init(n,e),ie.init(n,e)});dc=v("ZodULID",(n,e)=>{dp.init(n,e),ie.init(n,e)});fc=v("ZodXID",(n,e)=>{fp.init(n,e),ie.init(n,e)});pc=v("ZodKSUID",(n,e)=>{pp.init(n,e),ie.init(n,e)});mc=v("ZodIPv4",(n,e)=>{vp.init(n,e),ie.init(n,e)});sg=v("ZodMAC",(n,e)=>{wp.init(n,e),ie.init(n,e)});hc=v("ZodIPv6",(n,e)=>{_p.init(n,e),ie.init(n,e)});gc=v("ZodCIDRv4",(n,e)=>{bp.init(n,e),ie.init(n,e)});yc=v("ZodCIDRv6",(n,e)=>{kp.init(n,e),ie.init(n,e)});vc=v("ZodBase64",(n,e)=>{$p.init(n,e),ie.init(n,e)});_c=v("ZodBase64URL",(n,e)=>{xp.init(n,e),ie.init(n,e)});wc=v("ZodE164",(n,e)=>{Ip.init(n,e),ie.init(n,e)});bc=v("ZodJWT",(n,e)=>{Tp.init(n,e),ie.init(n,e)});Cr=v("ZodCustomStringFormat",(n,e)=>{Ep.init(n,e),ie.init(n,e)});Nr=v("ZodNumber",(n,e)=>{fa.init(n,e),K.init(n,e),n._zod.processJSONSchema=(i,r,o)=>sh(n,i,r,o),n.gt=(i,r)=>n.check(ht(i,r)),n.gte=(i,r)=>n.check(De(i,r)),n.min=(i,r)=>n.check(De(i,r)),n.lt=(i,r)=>n.check(mt(i,r)),n.lte=(i,r)=>n.check(Ze(i,r)),n.max=(i,r)=>n.check(Ze(i,r)),n.int=i=>n.check(ic(i)),n.safe=i=>n.check(ic(i)),n.positive=i=>n.check(ht(0,i)),n.nonnegative=i=>n.check(De(0,i)),n.negative=i=>n.check(mt(0,i)),n.nonpositive=i=>n.check(Ze(0,i)),n.multipleOf=(i,r)=>n.check(tn(i,r)),n.step=(i,r)=>n.check(tn(i,r)),n.finite=()=>n;let t=n._zod.bag;n.minValue=Math.max(t.minimum??Number.NEGATIVE_INFINITY,t.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,n.maxValue=Math.min(t.maximum??Number.POSITIVE_INFINITY,t.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,n.isInt=(t.format??"").includes("int")||Number.isSafeInteger(t.multipleOf??.5),n.isFinite=!0,n.format=t.format??null});An=v("ZodNumberFormat",(n,e)=>{Ap.init(n,e),Nr.init(n,e)});Dr=v("ZodBoolean",(n,e)=>{Bi.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>ah(n,t,i,r)});Pr=v("ZodBigInt",(n,e)=>{pa.init(n,e),K.init(n,e),n._zod.processJSONSchema=(i,r,o)=>ch(n,i,r,o),n.gte=(i,r)=>n.check(De(i,r)),n.min=(i,r)=>n.check(De(i,r)),n.gt=(i,r)=>n.check(ht(i,r)),n.gte=(i,r)=>n.check(De(i,r)),n.min=(i,r)=>n.check(De(i,r)),n.lt=(i,r)=>n.check(mt(i,r)),n.lte=(i,r)=>n.check(Ze(i,r)),n.max=(i,r)=>n.check(Ze(i,r)),n.positive=i=>n.check(ht(BigInt(0),i)),n.negative=i=>n.check(mt(BigInt(0),i)),n.nonpositive=i=>n.check(Ze(BigInt(0),i)),n.nonnegative=i=>n.check(De(BigInt(0),i)),n.multipleOf=(i,r)=>n.check(tn(i,r));let t=n._zod.bag;n.minValue=t.minimum??null,n.maxValue=t.maximum??null,n.format=t.format??null});kc=v("ZodBigIntFormat",(n,e)=>{Op.init(n,e),Pr.init(n,e)});lg=v("ZodSymbol",(n,e)=>{Cp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>lh(n,t,i,r)});ug=v("ZodUndefined",(n,e)=>{Np.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>dh(n,t,i,r)});dg=v("ZodNull",(n,e)=>{Dp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>uh(n,t,i,r)});pg=v("ZodAny",(n,e)=>{Pp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>mh(n,t,i,r)});mg=v("ZodUnknown",(n,e)=>{Mp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>hh(n,t,i,r)});hg=v("ZodNever",(n,e)=>{Lp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>ph(n,t,i,r)});gg=v("ZodVoid",(n,e)=>{zp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>fh(n,t,i,r)});oo=v("ZodDate",(n,e)=>{jp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(i,r,o)=>gh(n,i,r,o),n.min=(i,r)=>n.check(De(i,r)),n.max=(i,r)=>n.check(Ze(i,r));let t=n._zod.bag;n.minDate=t.minimum?new Date(t.minimum):null,n.maxDate=t.maximum?new Date(t.maximum):null});yg=v("ZodArray",(n,e)=>{Up.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Eh(n,t,i,r),n.element=e.element,n.min=(t,i)=>n.check(xt(t,i)),n.nonempty=t=>n.check(xt(1,t)),n.max=(t,i)=>n.check(In(t,i)),n.length=(t,i)=>n.check(Tn(t,i)),n.unwrap=()=>n.element});ao=v("ZodObject",(n,e)=>{Rp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Ah(n,t,i,r),E.defineLazy(n,"shape",()=>e.shape),n.keyof=()=>xc(Object.keys(n._zod.def.shape)),n.catchall=t=>n.clone({...n._zod.def,catchall:t}),n.passthrough=()=>n.clone({...n._zod.def,catchall:En()}),n.loose=()=>n.clone({...n._zod.def,catchall:En()}),n.strict=()=>n.clone({...n._zod.def,catchall:Sc()}),n.strip=()=>n.clone({...n._zod.def,catchall:void 0}),n.extend=t=>E.extend(n,t),n.safeExtend=t=>E.safeExtend(n,t),n.merge=t=>E.merge(n,t),n.pick=t=>E.pick(n,t),n.omit=t=>E.omit(n,t),n.partial=(...t)=>E.partial(Tc,n,t[0]),n.required=(...t)=>E.required(Ec,n,t[0])});co=v("ZodUnion",(n,e)=>{Fi.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Wa(n,t,i,r),n.options=e.options});vg=v("ZodXor",(n,e)=>{co.init(n,e),Bp.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Wa(n,t,i,r),n.options=e.options});_g=v("ZodDiscriminatedUnion",(n,e)=>{co.init(n,e),Fp.init(n,e)});wg=v("ZodIntersection",(n,e)=>{qp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Oh(n,t,i,r)});kg=v("ZodTuple",(n,e)=>{ma.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Ch(n,t,i,r),n.rest=t=>n.clone({...n._zod.def,rest:t})});lo=v("ZodRecord",(n,e)=>{Zp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Nh(n,t,i,r),n.keyType=e.keyType,n.valueType=e.valueType});xg=v("ZodMap",(n,e)=>{Kp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Ih(n,t,i,r),n.keyType=e.keyType,n.valueType=e.valueType,n.min=(...t)=>n.check(gt(...t)),n.nonempty=t=>n.check(gt(1,t)),n.max=(...t)=>n.check(nn(...t)),n.size=(...t)=>n.check(xn(...t))});Ig=v("ZodSet",(n,e)=>{Vp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Th(n,t,i,r),n.min=(...t)=>n.check(gt(...t)),n.nonempty=t=>n.check(gt(1,t)),n.max=(...t)=>n.check(nn(...t)),n.size=(...t)=>n.check(xn(...t))});Ar=v("ZodEnum",(n,e)=>{Wp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(i,r,o)=>yh(n,i,r,o),n.enum=e.entries,n.options=Object.values(e.entries);let t=new Set(Object.keys(e.entries));n.extract=(i,r)=>{let o={};for(let s of i)if(t.has(s))o[s]=e.entries[s];else throw new Error(`Key ${s} not found in enum`);return new Ar({...e,checks:[],...E.normalizeParams(r),entries:o})},n.exclude=(i,r)=>{let o={...e.entries};for(let s of i)if(t.has(s))delete o[s];else throw new Error(`Key ${s} not found in enum`);return new Ar({...e,checks:[],...E.normalizeParams(r),entries:o})}});Tg=v("ZodLiteral",(n,e)=>{Gp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>vh(n,t,i,r),n.values=new Set(e.values),Object.defineProperty(n,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});Eg=v("ZodFile",(n,e)=>{Jp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>bh(n,t,i,r),n.min=(t,i)=>n.check(gt(t,i)),n.max=(t,i)=>n.check(nn(t,i)),n.mime=(t,i)=>n.check(wr(Array.isArray(t)?t:[t],i))});Ag=v("ZodTransform",(n,e)=>{Hp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>xh(n,t,i,r),n._zod.parse=(t,i)=>{if(i.direction==="backward")throw new Ht(n.constructor.name);t.addIssue=o=>{if(typeof o=="string")t.issues.push(E.issue(o,t.value,e));else{let s=o;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=t.value),s.inst??(s.inst=n),t.issues.push(E.issue(s))}};let r=e.transform(t.value,t);return r instanceof Promise?r.then(o=>(t.value=o,t)):(t.value=r,t)}});Tc=v("ZodOptional",(n,e)=>{ha.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Ga(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Og=v("ZodExactOptional",(n,e)=>{Yp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Ga(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Ng=v("ZodNullable",(n,e)=>{Xp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Dh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Dg=v("ZodDefault",(n,e)=>{Qp.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Mh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType,n.removeDefault=n.unwrap});Mg=v("ZodPrefault",(n,e)=>{em.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Lh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Ec=v("ZodNonOptional",(n,e)=>{tm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Ph(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});jg=v("ZodSuccess",(n,e)=>{nm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>kh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Ug=v("ZodCatch",(n,e)=>{rm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>zh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType,n.removeCatch=n.unwrap});Bg=v("ZodNaN",(n,e)=>{im.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>_h(n,t,i,r)});Ac=v("ZodPipe",(n,e)=>{om.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>jh(n,t,i,r),n.in=e.in,n.out=e.out});Oc=v("ZodCodec",(n,e)=>{Ac.init(n,e),qi.init(n,e)});Fg=v("ZodReadonly",(n,e)=>{sm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Uh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Zg=v("ZodTemplateLiteral",(n,e)=>{am.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>wh(n,t,i,r)});Kg=v("ZodLazy",(n,e)=>{um.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Bh(n,t,i,r),n.unwrap=()=>n._zod.def.getter()});Wg=v("ZodPromise",(n,e)=>{lm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Rh(n,t,i,r),n.unwrap=()=>n._zod.def.innerType});Gg=v("ZodFunction",(n,e)=>{cm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>$h(n,t,i,r)});uo=v("ZodCustom",(n,e)=>{dm.init(n,e),K.init(n,e),n._zod.processJSONSchema=(t,i,r)=>Sh(n,t,i,r)});Cx=th,Nx=nh;Px=(...n)=>rh({Codec:Oc,Boolean:Dr,String:Or},...n)});function j1(n){fe({customError:n})}function U1(){return fe().customError}var z1,Yg,zx=S(()=>{Re();Re();z1={invalid_type:"invalid_type",too_big:"too_big",too_small:"too_small",invalid_format:"invalid_format",not_multiple_of:"not_multiple_of",unrecognized_keys:"unrecognized_keys",invalid_union:"invalid_union",invalid_key:"invalid_key",invalid_element:"invalid_element",invalid_value:"invalid_value",custom:"custom"};Yg||(Yg={})});function B1(n,e){let t=n.$schema;return t==="https://json-schema.org/draft/2020-12/schema"?"draft-2020-12":t==="http://json-schema.org/draft-07/schema#"?"draft-7":t==="http://json-schema.org/draft-04/schema#"?"draft-4":e??"draft-2020-12"}function F1(n,e){if(!n.startsWith("#"))throw new Error("External $ref is not supported, only local refs (#/...) are allowed");let t=n.slice(1).split("/").filter(Boolean);if(t.length===0)return e.rootSchema;let i=e.version==="draft-2020-12"?"$defs":"definitions";if(t[0]===i){let r=t[1];if(!r||!e.defs[r])throw new Error(`Reference not found: ${n}`);return e.defs[r]}throw new Error(`Reference not found: ${n}`)}function jx(n,e){if(n.not!==void 0){if(typeof n.not=="object"&&Object.keys(n.not).length===0)return D.never();throw new Error("not is not supported in Zod (except { not: {} } for never)")}if(n.unevaluatedItems!==void 0)throw new Error("unevaluatedItems is not supported");if(n.unevaluatedProperties!==void 0)throw new Error("unevaluatedProperties is not supported");if(n.if!==void 0||n.then!==void 0||n.else!==void 0)throw new Error("Conditional schemas (if/then/else) are not supported");if(n.dependentSchemas!==void 0||n.dependentRequired!==void 0)throw new Error("dependentSchemas and dependentRequired are not supported");if(n.$ref){let r=n.$ref;if(e.refs.has(r))return e.refs.get(r);if(e.processing.has(r))return D.lazy(()=>{if(!e.refs.has(r))throw new Error(`Circular reference not resolved: ${r}`);return e.refs.get(r)});e.processing.add(r);let o=F1(r,e),s=Ee(o,e);return e.refs.set(r,s),e.processing.delete(r),s}if(n.enum!==void 0){let r=n.enum;if(e.version==="openapi-3.0"&&n.nullable===!0&&r.length===1&&r[0]===null)return D.null();if(r.length===0)return D.never();if(r.length===1)return D.literal(r[0]);if(r.every(s=>typeof s=="string"))return D.enum(r);let o=r.map(s=>D.literal(s));return o.length<2?o[0]:D.union([o[0],o[1],...o.slice(2)])}if(n.const!==void 0)return D.literal(n.const);let t=n.type;if(Array.isArray(t)){let r=t.map(o=>{let s={...n,type:o};return jx(s,e)});return r.length===0?D.never():r.length===1?r[0]:D.union(r)}if(!t)return D.any();let i;switch(t){case"string":{let r=D.string();if(n.format){let o=n.format;o==="email"?r=r.check(D.email()):o==="uri"||o==="uri-reference"?r=r.check(D.url()):o==="uuid"||o==="guid"?r=r.check(D.uuid()):o==="date-time"?r=r.check(D.iso.datetime()):o==="date"?r=r.check(D.iso.date()):o==="time"?r=r.check(D.iso.time()):o==="duration"?r=r.check(D.iso.duration()):o==="ipv4"?r=r.check(D.ipv4()):o==="ipv6"?r=r.check(D.ipv6()):o==="mac"?r=r.check(D.mac()):o==="cidr"?r=r.check(D.cidrv4()):o==="cidr-v6"?r=r.check(D.cidrv6()):o==="base64"?r=r.check(D.base64()):o==="base64url"?r=r.check(D.base64url()):o==="e164"?r=r.check(D.e164()):o==="jwt"?r=r.check(D.jwt()):o==="emoji"?r=r.check(D.emoji()):o==="nanoid"?r=r.check(D.nanoid()):o==="cuid"?r=r.check(D.cuid()):o==="cuid2"?r=r.check(D.cuid2()):o==="ulid"?r=r.check(D.ulid()):o==="xid"?r=r.check(D.xid()):o==="ksuid"&&(r=r.check(D.ksuid()))}typeof n.minLength=="number"&&(r=r.min(n.minLength)),typeof n.maxLength=="number"&&(r=r.max(n.maxLength)),n.pattern&&(r=r.regex(new RegExp(n.pattern))),i=r;break}case"number":case"integer":{let r=t==="integer"?D.number().int():D.number();typeof n.minimum=="number"&&(r=r.min(n.minimum)),typeof n.maximum=="number"&&(r=r.max(n.maximum)),typeof n.exclusiveMinimum=="number"?r=r.gt(n.exclusiveMinimum):n.exclusiveMinimum===!0&&typeof n.minimum=="number"&&(r=r.gt(n.minimum)),typeof n.exclusiveMaximum=="number"?r=r.lt(n.exclusiveMaximum):n.exclusiveMaximum===!0&&typeof n.maximum=="number"&&(r=r.lt(n.maximum)),typeof n.multipleOf=="number"&&(r=r.multipleOf(n.multipleOf)),i=r;break}case"boolean":{i=D.boolean();break}case"null":{i=D.null();break}case"object":{let r={},o=n.properties||{},s=new Set(n.required||[]);for(let[l,c]of Object.entries(o)){let u=Ee(c,e);r[l]=s.has(l)?u:u.optional()}if(n.propertyNames){let l=Ee(n.propertyNames,e),c=n.additionalProperties&&typeof n.additionalProperties=="object"?Ee(n.additionalProperties,e):D.any();if(Object.keys(r).length===0){i=D.record(l,c);break}let u=D.object(r).passthrough(),d=D.looseRecord(l,c);i=D.intersection(u,d);break}if(n.patternProperties){let l=n.patternProperties,c=Object.keys(l),u=[];for(let f of c){let p=Ee(l[f],e),h=D.string().regex(new RegExp(f));u.push(D.looseRecord(h,p))}let d=[];if(Object.keys(r).length>0&&d.push(D.object(r).passthrough()),d.push(...u),d.length===0)i=D.object({}).passthrough();else if(d.length===1)i=d[0];else{let f=D.intersection(d[0],d[1]);for(let p=2;p<d.length;p++)f=D.intersection(f,d[p]);i=f}break}let a=D.object(r);n.additionalProperties===!1?i=a.strict():typeof n.additionalProperties=="object"?i=a.catchall(Ee(n.additionalProperties,e)):i=a.passthrough();break}case"array":{let r=n.prefixItems,o=n.items;if(r&&Array.isArray(r)){let s=r.map(l=>Ee(l,e)),a=o&&typeof o=="object"&&!Array.isArray(o)?Ee(o,e):void 0;a?i=D.tuple(s).rest(a):i=D.tuple(s),typeof n.minItems=="number"&&(i=i.check(D.minLength(n.minItems))),typeof n.maxItems=="number"&&(i=i.check(D.maxLength(n.maxItems)))}else if(Array.isArray(o)){let s=o.map(l=>Ee(l,e)),a=n.additionalItems&&typeof n.additionalItems=="object"?Ee(n.additionalItems,e):void 0;a?i=D.tuple(s).rest(a):i=D.tuple(s),typeof n.minItems=="number"&&(i=i.check(D.minLength(n.minItems))),typeof n.maxItems=="number"&&(i=i.check(D.maxLength(n.maxItems)))}else if(o!==void 0){let s=Ee(o,e),a=D.array(s);typeof n.minItems=="number"&&(a=a.min(n.minItems)),typeof n.maxItems=="number"&&(a=a.max(n.maxItems)),i=a}else i=D.array(D.any());break}default:throw new Error(`Unsupported type: ${t}`)}return n.description&&(i=i.describe(n.description)),n.default!==void 0&&(i=i.default(n.default)),i}function Ee(n,e){if(typeof n=="boolean")return n?D.any():D.never();let t=jx(n,e),i=n.type||n.enum!==void 0||n.const!==void 0;if(n.anyOf&&Array.isArray(n.anyOf)){let a=n.anyOf.map(c=>Ee(c,e)),l=D.union(a);t=i?D.intersection(t,l):l}if(n.oneOf&&Array.isArray(n.oneOf)){let a=n.oneOf.map(c=>Ee(c,e)),l=D.xor(a);t=i?D.intersection(t,l):l}if(n.allOf&&Array.isArray(n.allOf))if(n.allOf.length===0)t=i?t:D.any();else{let a=i?t:Ee(n.allOf[0],e),l=i?0:1;for(let c=l;c<n.allOf.length;c++)a=D.intersection(a,Ee(n.allOf[c],e));t=a}n.nullable===!0&&e.version==="openapi-3.0"&&(t=D.nullable(t)),n.readOnly===!0&&(t=D.readonly(t));let r={},o=["$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor"];for(let a of o)a in n&&(r[a]=n[a]);let s=["contentEncoding","contentMediaType","contentSchema"];for(let a of s)a in n&&(r[a]=n[a]);for(let a of Object.keys(n))R1.has(a)||(r[a]=n[a]);return Object.keys(r).length>0&&e.registry.add(t,r),t}function Ux(n,e){if(typeof n=="boolean")return n?D.any():D.never();let t=B1(n,e?.defaultTarget),i=n.$defs||n.definitions||{},r={version:t,defs:i,refs:new Map,processing:new Set,rootSchema:n,registry:e?.registry??xe};return Ee(n,r)}var D,R1,Rx=S(()=>{Vi();Xa();Yi();Qi();D={...Xi,...Ya,iso:Er},R1=new Set(["$schema","$ref","$defs","definitions","$id","id","$comment","$anchor","$vocabulary","$dynamicRef","$dynamicAnchor","type","enum","const","anyOf","oneOf","allOf","not","properties","required","additionalProperties","patternProperties","propertyNames","minProperties","maxProperties","items","prefixItems","additionalItems","minItems","maxItems","uniqueItems","contains","minContains","maxContains","minLength","maxLength","pattern","format","minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","description","default","contentEncoding","contentMediaType","contentSchema","unevaluatedItems","unevaluatedProperties","if","then","else","dependentSchemas","dependentRequired","nullable","readOnly"])});var Xg={};we(Xg,{bigint:()=>V1,boolean:()=>K1,date:()=>W1,number:()=>Z1,string:()=>q1});function q1(n){return wm(Or,n)}function Z1(n){return Em(Nr,n)}function K1(n){return Mm(Dr,n)}function V1(n){return zm(Pr,n)}function W1(n){return Gm(oo,n)}var Bx=S(()=>{Re();Qi()});var Tt={};we(Tt,{$brand:()=>Fs,$input:()=>vm,$output:()=>ym,NEVER:()=>qd,TimePrecision:()=>km,ZodAny:()=>pg,ZodArray:()=>yg,ZodBase64:()=>vc,ZodBase64URL:()=>_c,ZodBigInt:()=>Pr,ZodBigIntFormat:()=>kc,ZodBoolean:()=>Dr,ZodCIDRv4:()=>gc,ZodCIDRv6:()=>yc,ZodCUID:()=>lc,ZodCUID2:()=>uc,ZodCatch:()=>Ug,ZodCodec:()=>Oc,ZodCustom:()=>uo,ZodCustomStringFormat:()=>Cr,ZodDate:()=>oo,ZodDefault:()=>Dg,ZodDiscriminatedUnion:()=>_g,ZodE164:()=>wc,ZodEmail:()=>sc,ZodEmoji:()=>ac,ZodEnum:()=>Ar,ZodError:()=>M1,ZodExactOptional:()=>Og,ZodFile:()=>Eg,ZodFirstPartyTypeKind:()=>Yg,ZodFunction:()=>Gg,ZodGUID:()=>eo,ZodIPv4:()=>mc,ZodIPv6:()=>hc,ZodISODate:()=>ec,ZodISODateTime:()=>Qa,ZodISODuration:()=>nc,ZodISOTime:()=>tc,ZodIntersection:()=>wg,ZodIssueCode:()=>z1,ZodJWT:()=>bc,ZodKSUID:()=>pc,ZodLazy:()=>Kg,ZodLiteral:()=>Tg,ZodMAC:()=>sg,ZodMap:()=>xg,ZodNaN:()=>Bg,ZodNanoID:()=>cc,ZodNever:()=>hg,ZodNonOptional:()=>Ec,ZodNull:()=>dg,ZodNullable:()=>Ng,ZodNumber:()=>Nr,ZodNumberFormat:()=>An,ZodObject:()=>ao,ZodOptional:()=>Tc,ZodPipe:()=>Ac,ZodPrefault:()=>Mg,ZodPromise:()=>Wg,ZodReadonly:()=>Fg,ZodRealError:()=>Be,ZodRecord:()=>lo,ZodSet:()=>Ig,ZodString:()=>Or,ZodStringFormat:()=>ie,ZodSuccess:()=>jg,ZodSymbol:()=>lg,ZodTemplateLiteral:()=>Zg,ZodTransform:()=>Ag,ZodTuple:()=>kg,ZodType:()=>K,ZodULID:()=>dc,ZodURL:()=>io,ZodUUID:()=>yt,ZodUndefined:()=>ug,ZodUnion:()=>co,ZodUnknown:()=>mg,ZodVoid:()=>gg,ZodXID:()=>fc,ZodXor:()=>vg,_ZodString:()=>oc,_default:()=>Pg,_function:()=>Ex,any:()=>sx,array:()=>so,base64:()=>q$,base64url:()=>Z$,bigint:()=>tx,boolean:()=>cg,catch:()=>Rg,check:()=>Ax,cidrv4:()=>B$,cidrv6:()=>F$,clone:()=>Ne,codec:()=>xx,coerce:()=>Xg,config:()=>fe,core:()=>It,cuid:()=>D$,cuid2:()=>P$,custom:()=>Ox,date:()=>cx,decode:()=>Xh,decodeAsync:()=>eg,describe:()=>Cx,discriminatedUnion:()=>mx,e164:()=>K$,email:()=>S$,emoji:()=>C$,encode:()=>Yh,encodeAsync:()=>Qh,endsWith:()=>_r,enum:()=>xc,exactOptional:()=>Cg,file:()=>bx,flattenError:()=>Li,float32:()=>Y$,float64:()=>X$,formatError:()=>zi,fromJSONSchema:()=>Ux,function:()=>Ex,getErrorMap:()=>U1,globalRegistry:()=>xe,gt:()=>ht,gte:()=>De,guid:()=>$$,hash:()=>H$,hex:()=>J$,hostname:()=>G$,httpUrl:()=>O$,includes:()=>yr,instanceof:()=>Dx,int:()=>ic,int32:()=>Q$,int64:()=>nx,intersection:()=>bg,ipv4:()=>j$,ipv6:()=>R$,iso:()=>Er,json:()=>Mx,jwt:()=>V$,keyof:()=>lx,ksuid:()=>z$,lazy:()=>Vg,length:()=>Tn,literal:()=>wx,locales:()=>Ki,looseObject:()=>fx,looseRecord:()=>gx,lowercase:()=>hr,lt:()=>mt,lte:()=>Ze,mac:()=>U$,map:()=>yx,maxLength:()=>In,maxSize:()=>nn,meta:()=>Nx,mime:()=>wr,minLength:()=>xt,minSize:()=>gt,multipleOf:()=>tn,nan:()=>$x,nanoid:()=>N$,nativeEnum:()=>_x,negative:()=>Fa,never:()=>Sc,nonnegative:()=>Za,nonoptional:()=>zg,nonpositive:()=>qa,normalize:()=>br,null:()=>fg,nullable:()=>no,nullish:()=>kx,number:()=>ag,object:()=>ux,optional:()=>to,overwrite:()=>ct,parse:()=>Wh,parseAsync:()=>Gh,partialRecord:()=>hx,pipe:()=>ro,positive:()=>Ba,prefault:()=>Lg,preprocess:()=>Lx,prettifyError:()=>tf,promise:()=>Tx,property:()=>Ka,readonly:()=>qg,record:()=>$g,refine:()=>Jg,regex:()=>mr,regexes:()=>Ye,registry:()=>wa,safeDecode:()=>ng,safeDecodeAsync:()=>ig,safeEncode:()=>tg,safeEncodeAsync:()=>rg,safeParse:()=>Jh,safeParseAsync:()=>Hh,set:()=>vx,setErrorMap:()=>j1,size:()=>xn,slugify:()=>xr,startsWith:()=>vr,strictObject:()=>dx,string:()=>rc,stringFormat:()=>W$,stringbool:()=>Px,success:()=>Sx,superRefine:()=>Hg,symbol:()=>ix,templateLiteral:()=>Ix,toJSONSchema:()=>Ja,toLowerCase:()=>Sr,toUpperCase:()=>$r,transform:()=>Ic,treeifyError:()=>ef,trim:()=>kr,tuple:()=>Sg,uint32:()=>ex,uint64:()=>rx,ulid:()=>M$,undefined:()=>ox,union:()=>$c,unknown:()=>En,uppercase:()=>gr,url:()=>A$,util:()=>E,uuid:()=>x$,uuidv4:()=>I$,uuidv6:()=>T$,uuidv7:()=>E$,void:()=>ax,xid:()=>L$,xor:()=>px});var Qg=S(()=>{Re();Qi();Xa();Vh();og();zx();Re();pm();Re();Hi();Rx();gm();Yi();Yi();Bx();fe(ga())});var Fx=S(()=>{Qg();Qg()});import{createSdkMcpServer as G1,tool as ey}from"@anthropic-ai/claude-agent-sdk";function J1(n){return[ey("team_list","List the team. Defaults: active humans + active agents, sorted by category then name. Set includeArchived=true to include archived members. Set includeAgents=false to filter to humans only.",{includeArchived:Tt.boolean().optional(),includeAgents:Tt.boolean().optional()},async e=>{let t=await n.getTeam({includeArchived:e.includeArchived,includeAgents:e.includeAgents});return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}),ey("team_lookup_human","Look up a team-human by name or email. Provide exactly one. Returns full contact card or null if no match. Match is case-insensitive exact (no fuzzy/partial).",{name:Tt.string().optional(),email:Tt.string().optional()},async e=>{if((e.name?1:0)+(e.email?1:0)!=1)return{isError:!0,content:[{type:"text",text:"team_lookup_human: provide exactly one of name|email"}]};let t=await n.lookupHuman(e);return{content:[{type:"text",text:t?JSON.stringify(t,null,2):"null"}]}}),ey("team_lookup_agent","Look up a team-agent by agentId or name (aliases supported). Provide exactly one. agentId match is case-sensitive; name/alias match is case-insensitive. Returns full agent card or null if no match.",{agentId:Tt.string().optional(),name:Tt.string().optional()},async e=>{if((e.agentId?1:0)+(e.name?1:0)!=1)return{isError:!0,content:[{type:"text",text:"team_lookup_agent: provide exactly one of agentId|name"}]};let t=await n.lookupAgent(e);return{content:[{type:"text",text:t?JSON.stringify(t,null,2):"null"}]}})]}function qx(n){return G1({name:"team-roster",version:"0.1.0",tools:J1(n)})}var Zx=S(()=>{"use strict";Fx()});var Wx={};we(Wx,{AgentRunner:()=>po,DIST_DIR:()=>Et,ensurePluginNodeModulesLink:()=>Vx});import{query as H1}from"@anthropic-ai/claude-agent-sdk";import{resolve as lt}from"node:path";import{existsSync as fo,statSync as Y1,mkdirSync as Kx,symlinkSync as X1,lstatSync as Q1}from"node:fs";import{createRequire as eM}from"node:module";import{readFile as tM}from"node:fs/promises";function nM(n){return JSON.stringify(Yb(n))}function rM(n){let e=n;for(let t=0;t<15;t++){let i=lt(e,"node_modules"),r=lt(e,"package.json");if(fo(i)&&fo(r))return i;let o=lt(e,"..");if(o===e)break;e=o}return null}function Vx(n){if(!ty)return;let e=lt(n,"node_modules");try{Q1(e);return}catch{}try{X1(ty,e,"dir"),J.info("Linked plugin node_modules to engine deps",{pluginDir:n,target:ty})}catch(t){J.warn("Failed to link plugin node_modules",{pluginDir:n,error:String(t)})}}function ce(n){let e=iM[n];if(e){let t=lt(Et,"mcp",e);if(fo(t))return t}return lt(Et,n)}var J,Et,ty,iM,po,ny=S(()=>{"use strict";Ms();R();ot();Ds();Wr();Us();Rd();Bs();Xb();ek();Zx();J=$("agent-runner");Et=fo(lt(import.meta.dirname,"mcp"))?import.meta.dirname:lt(import.meta.dirname,"..");ty=rM(Et);iM={"memory/memory-mcp-server.js":"memory.min.js","memory/structured-memory-mcp-server.js":"structured-memory.min.js","keychain/keychain-mcp-server.js":"keychain.min.js","google/google-mcp-server.js":"google.min.js","quo/quo-mcp-server.js":"quo.min.js","voice/voice-mcp-server.js":"voice.min.js","contacts/contacts-mcp-server.js":"contacts.min.js","tasks/task-mcp-server.js":"task.min.js","resend/resend-mcp-server.js":"resend.min.js","linear/linear-mcp-server.js":"linear.min.js","github/github-issues-mcp-server.js":"github-issues.min.js","clickup/clickup-mcp-server.js":"clickup.min.js","recall/recall-mcp-server.js":"recall.min.js","background/background-task-mcp-server.js":"background-task.min.js","callback/callback-mcp-server.js":"callback.min.js","code-task/code-task-mcp-server.js":"code-task.min.js","search/conversation-search-mcp-server.js":"search-conversation.min.js","code-index/code-search-mcp-server.js":"code-search.min.js","events/event-bus-mcp-server.js":"event-bus.min.js","team/team-mcp-server.js":"team.min.js","workflow/workflow-mcp-server.js":"workflow.min.js","schedule/schedule-mcp-server.js":"schedule.min.js","admin/admin-mcp-server.js":"admin.min.js","slack/slack-mcp-server.js":"slack.min.js"};po=class n{static registryRef;agentConfig;memoryManager;plugins;skillIndex;activeQuery=null;eventSubscribersJson;prefetcher;teamRoster;teamRosterMcpServer;_archetypeDef=void 0;constructor(e,t,i=[],r=new Map,o="{}",s,a){this.agentConfig=e,this.memoryManager=t,this.plugins=i,this.skillIndex=r,this.eventSubscribersJson=o,this.prefetcher=s,this.teamRoster=a}async buildSystemPrompt(e,t){let i=[];this.agentConfig.soul&&i.push(this.agentConfig.soul);let r=this.getArchetypeDef();if(r&&this.agentConfig.archetypeConfig)try{let c=r.systemPromptCard({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});c&&i.push(c)}catch(c){J.error("Archetype systemPromptCard threw \u2014 omitting card",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(c)})}i.push(this.agentConfig.systemPrompt);let o=await this.memoryManager.read("shared/constitution.md");if(o&&i.push(o),this.teamRoster)try{let c=await this.teamRoster.teamSummary();c&&i.push(c)}catch(c){J.warn("teamSummary failed; omitting from prompt",{agent:this.agentConfig.id,error:String(c)})}i.push(Qb({coreServerNames:e,delegateServerNames:t??[],plugins:this.plugins,autoInjectedServers:n.autoInjectedServerNames()}));let s=await this.memoryManager.getHotTierPrompt(this.agentConfig.id,g.memory.hotBudgetTokens);if(s)i.push(s);else{let c=`agents/${this.agentConfig.id}`,u=await this.memoryManager.read(`${c}/memory.md`);u&&i.push(`## Your Memory
203
+ ${u}`);let f=(await this.memoryManager.list(c)).filter(p=>p.endsWith(".md")&&p!=="memory.md");f.length>0&&i.push(`## Available Memory Files
204
+ You have ${f.length} reference file(s) in your memory directory:
205
+ `+f.map(p=>`- ${c}/${p}`).join(`
206
+ `)+"\n\nRead relevant files via the memory MCP server (`memory_read`) before starting tasks that may relate to them.")}let l=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return i.push(`**Current date/time**: ${l} (Pacific Time)`),i.join(`
168
207
 
169
208
  ---
170
209
 
171
- `)}buildServerConfig(e,t){return this.buildAllServerConfigs(t)[e]}buildAllServerConfigs(e){let t={};if(g.slack.localMcpServer)t.slack={type:"stdio",command:"node",args:[J("slack/slack-mcp-server.js")],env:{HIVE_INTERNAL_URL:`http://127.0.0.1:${g.slackInternal.port}`,HIVE_INTERNAL_TOKEN:g.slackInternal.authToken,HIVE_AGENT_ID:this.agentConfig.id}};else{let c=g.slack.mcpToken;c&&(t.slack={type:"http",url:"https://mcp.slack.com/mcp",headers:{Authorization:`Bearer ${c}`}})}let s=[{id:"self",backing:"mongo"}],r=this.getArchetypeDef();if(r&&this.agentConfig.archetypeConfig)try{let c=r.memoryScopes({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});for(let d of c)d.id!=="self"&&s.push(d)}catch(c){R.error("Archetype memoryScopes threw \u2014 using self-only",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(c)})}t.memory={type:"stdio",command:"node",args:[J("memory/memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,MEMORY_SCOPES_JSON:JSON.stringify(s)}},t["structured-memory"]={type:"stdio",command:"node",args:[J("memory/structured-memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,CHANNEL_ID:e?.channelId??"",THREAD_ID:e?.threadId??"",QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333",OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434"}},t.keychain={type:"stdio",command:"node",args:[J("keychain/keychain-mcp-server.js")],env:{KEYCHAIN_SERVICE:`hive/${g.instance.id}`}};let i=g.google.accounts[this.agentConfig.id]||g.google.account,o=g.google.client;if(t.google={type:"stdio",command:"node",args:[J("google/google-mcp-server.js")],env:{...i?{GOG_ACCOUNT:i}:{},...o?{GOG_CLIENT:o}:{},DRIVE_SHARED_FOLDER:g.google.sharedFolder,INSTANCE_ID:g.instance.id,PATH:process.env.PATH??""}},g.quo.apiKey&&(t.quo={type:"stdio",command:"node",args:[J("quo/quo-mcp-server.js")],env:{QUO_API_KEY:g.quo.apiKey,...g.quo.phoneNumberId?{QUO_PHONE_NUMBER_ID:g.quo.phoneNumberId}:{},QUO_LINES_JSON:JSON.stringify(g.quo.lines)}}),g.voice.enabled&&g.voice.apiKey){let c=Object.entries(g.voice.assistants).find(([d,u])=>u===this.agentConfig.id)?.[0]??"";t.voice={type:"stdio",command:"node",args:[J("voice/voice-mcp-server.js")],env:{VAPI_API_KEY:g.voice.apiKey,VAPI_PHONE_NUMBER_ID:g.voice.phoneNumberId,VAPI_ASSISTANT_ID:c,AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name}}}t.contacts={type:"stdio",command:"node",args:[J("contacts/contacts-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}};let a=g.taskLedger.agentKeys[this.agentConfig.id]??g.taskLedger.apiKey;if(a&&(t.tasks={type:"stdio",command:"node",args:[J("tasks/task-mcp-server.js")],env:{TASK_LEDGER_API_URL:g.taskLedger.apiUrl,TASK_LEDGER_API_KEY:a}}),g.brave.apiKey&&(t["brave-search"]={type:"stdio",command:"node",args:[Y0(import.meta.url).resolve("brave-search-mcp/dist/index.js")],env:{BRAVE_API_KEY:g.brave.apiKey}}),g.resend.apiKey){let c=this.agentConfig.name.toLowerCase(),d=g.resend.emailDomain,u=g.resend.businessName?` (${g.resend.businessName})`:"",h=d?`${this.agentConfig.name}${u} <${c}@${d}>`:g.resend.fromAddress;t.resend={type:"stdio",command:"node",args:[J("resend/resend-mcp-server.js")],env:{RESEND_API_KEY:g.resend.apiKey,RESEND_FROM_ADDRESS:h,RESEND_DEFAULT_CC:g.resend.defaultCc,RESEND_DEFAULT_BCC:g.resend.defaultBcc}}}if(g.linear.apiKey){let c={LINEAR_API_KEY:g.linear.apiKey};g.linear.teamId&&(c.LINEAR_TEAM_ID=g.linear.teamId),t.linear={type:"stdio",command:"node",args:[J("linear/linear-mcp-server.js")],env:c}}if(g.github.repo){let c={GITHUB_REPO:g.github.repo,PATH:process.env.PATH??""};g.github.token&&(c.GH_TOKEN=g.github.token),t["github-issues"]={type:"stdio",command:"node",args:[J("github/github-issues-mcp-server.js")],env:c}}if(g.clickup.apiToken&&(t.clickup={type:"stdio",command:"node",args:[J("clickup/clickup-mcp-server.js")],env:{CLICKUP_API_TOKEN:g.clickup.apiToken}}),g.recall.apiKey&&(t.recall={type:"stdio",command:"node",args:[J("recall/recall-mcp-server.js")],env:{RECALL_API_KEY:g.recall.apiKey,RECALL_API_REGION:g.recall.region,RECALL_WEBHOOK_SECRET:g.recall.webhookSecret,MEETING_MONITOR_API:`http://127.0.0.1:${g.recall.monitorPort}`,MEETING_MONITOR_PUBLIC_URL:g.recall.monitorPublicUrl,RECALL_AGENT_ID:this.agentConfig.id,RECALL_ADAPTER_ID:e?.adapterId??"",RECALL_CHANNEL_ID:e?.channelId??"",RECALL_CHANNEL_KIND:e?.channelKind??"internal",RECALL_CHANNEL_LABEL:e?.channelLabel??"",RECALL_THREAD_ID:e?.threadId??"",RECALL_SLACK_TS:e?.slackTs??"",RECALL_SLACK_THREAD_TS:e?.slackThreadTs??""}}),g.browser.cdpEndpoint){let c=xc(this.agentConfig.id,V);Mh(c,{recursive:!0}),t.browser={type:"stdio",command:"npx",args:["@playwright/mcp@latest","--cdp-endpoint",g.browser.cdpEndpoint,"--output-dir",c,"--user-data-dir",Oe(c,"user-data")],env:{PATH:process.env.PATH??"",HOME:process.env.HOME??""}}}t.background={type:"stdio",command:"node",args:[J("background/background-task-mcp-server.js")],env:{BG_TASK_API:`http://127.0.0.1:${g.background.port}`,BG_AUTH_TOKEN:g.background.authToken,BG_AGENT_ID:this.agentConfig.id,BG_ADAPTER_ID:e?.adapterId??"",BG_CHANNEL_ID:e?.channelId??"",BG_CHANNEL_KIND:e?.channelKind??"internal",BG_CHANNEL_LABEL:e?.channelLabel??"",BG_THREAD_ID:e?.threadId??"",BG_SLACK_TS:e?.slackTs??"",BG_SLACK_THREAD_TS:e?.slackThreadTs??""}},t.callback={type:"stdio",command:"node",args:[J("callback/callback-mcp-server.js")],env:{CB_AGENT_ID:this.agentConfig.id,CB_ADAPTER_ID:e?.adapterId??"",CB_CHANNEL_ID:e?.channelId??"",CB_CHANNEL_KIND:e?.channelKind??"internal",CB_CHANNEL_LABEL:e?.channelLabel??"",CB_THREAD_ID:e?.threadId??"",CB_SLACK_TS:e?.slackTs??"",CB_SLACK_THREAD_TS:e?.slackThreadTs??"",MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}},t["code-task"]={type:"stdio",command:"node",args:[J("code-task/code-task-mcp-server.js")],env:{CT_TASK_API:`http://127.0.0.1:${g.codeTask.port}`,CT_AUTH_TOKEN:g.codeTask.authToken,CT_AGENT_ID:this.agentConfig.id,CT_ADAPTER_ID:e?.adapterId??"",CT_CHANNEL_ID:e?.channelId??"",CT_CHANNEL_KIND:e?.channelKind??"internal",CT_CHANNEL_LABEL:e?.channelLabel??"",CT_THREAD_ID:e?.threadId??"",CT_SLACK_TS:e?.slackTs??"",CT_SLACK_THREAD_TS:e?.slackThreadTs??""}};let l={OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434",QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333"};process.env.KB_EMBED_MODEL&&(l.KB_EMBED_MODEL=process.env.KB_EMBED_MODEL),t["conversation-search"]={type:"stdio",command:"node",args:[J("search/conversation-search-mcp-server.js")],env:{...l,AGENT_ID:this.agentConfig.id,DEFAULT_AGENT:g.defaultAgent}},t["code-search"]={type:"stdio",command:"node",args:[J("code-index/code-search-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333",OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434"}};for(let c of this.plugins)for(let[d,u]of Object.entries(c.manifest.mcpServers)){if(t[d]){R.warn("Plugin server name conflicts with core server, skipping",{plugin:c.name,server:d});continue}if(c.brokenServers[d])continue;let h=Ks(c.name,u.entry,{hiveHome:V,distDir:Ke});if("reason"in h){R.error("Plugin MCP server unresolvable at spawn time",{plugin:c.name,server:d,reason:h.reason,pathsChecked:h.pathsChecked});continue}let p=h.path;Dh(c.dir);let m=g.taskLedger.agentKeys[this.agentConfig.id]??g.taskLedger.apiKey,f={AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,TASK_LEDGER_API_URL:g.taskLedger.apiUrl,...m?{TASK_LEDGER_API_KEY:m}:{},PATH:process.env.PATH??"",HOME:process.env.HOME??""};for(let y of u.env??[])process.env[y]&&(f[y]=process.env[y]);for(let y of u.secretEnv??[]){let w=process.env[y]||zt(g.instance.id,y);w&&(f[y]=w)}for(let[y,w]of Object.entries(u.envMap??{}))f[w]&&(f[y]=f[w]);for(let[y,w]of Object.entries(u.agentEnv??{}))f[y]=n.resolveAgentEnvPath(this.agentConfig,w);t[d]={type:"stdio",command:"node",args:[p],env:f}}return t["event-bus"]={type:"stdio",command:"node",args:[J("events/event-bus-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}},n.registryRef||R.warn("registryRef not set \u2014 agents will get empty AGENT_IDS for team server"),t.team={type:"stdio",command:"node",args:[J("team/team-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,AGENT_IDS:JSON.stringify(n.registryRef?.getAll().map(c=>c.id)??[])}},g.workflow.enabled&&(t.workflow={type:"stdio",command:"node",args:[J("workflow/workflow-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}}),t.schedule={type:"stdio",command:"node",args:[J("schedule/schedule-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}},t.admin={type:"stdio",command:"node",args:[J("admin/admin-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,AGENT_ID:this.agentConfig.id,INSTANCE_CAPABILITIES:z0(this.plugins)}},t}filterCoreServers(e){let t={...e},s=new Set(this.agentConfig.coreServers);s.has("memory")&&s.add("structured-memory"),s.add("schedule"),s.add("team"),s.add("slack"),g.workflow.enabled&&s.add("workflow");for(let r of Object.keys(t))s.has(r)||delete t[r];if(!this.agentConfig.autonomy.externalComms)for(let r of["resend","quo"])t[r]&&(R.debug("Autonomy: externalComms disabled \u2014 removing server",{server:r,agent:this.agentConfig.id}),delete t[r]);return this.agentConfig.autonomy.codeTask||t["code-task"]&&(R.debug("Autonomy: codeTask disabled \u2014 removing server",{server:"code-task",agent:this.agentConfig.id}),delete t["code-task"]),this.agentConfig.autonomy.codeAccess||t["code-search"]&&(R.debug("Autonomy: codeAccess disabled \u2014 removing server",{server:"code-search",agent:this.agentConfig.id}),delete t["code-search"]),t}static resolveAgentEnvPath(e,t){let s=t.split("."),r=e;for(let i of s){if(r==null||typeof r!="object")return"";r=r[i]}return r==null?"":String(r)}static autoInjectedServerNames(){let e=new Set(["schedule","team","slack"]);return g.workflow.enabled&&e.add("workflow"),e}static CONTEXT_DEPENDENT_SERVERS=new Set(["callback","background","code-task","recall","structured-memory","memory"]);buildDelegateAgents(e){let t=this.agentConfig.delegateServers;if(t.length===0)return{};let s={},r=new Set;this.agentConfig.autonomy.externalComms||(r.add("resend"),r.add("quo")),this.agentConfig.autonomy.codeTask||r.add("code-task"),this.agentConfig.autonomy.codeAccess||r.add("code-search");for(let i of t){if(r.has(i)){R.debug("Autonomy gate \u2014 skipping delegate server",{server:i,agent:this.agentConfig.id});continue}n.CONTEXT_DEPENDENT_SERVERS.has(i)&&R.warn("Context-dependent server in delegateServers \u2014 subagent won't have channel context",{agent:this.agentConfig.id,server:i});let o=e[i];if(!o){R.warn("Delegate server not found in configs, skipping",{agent:this.agentConfig.id,server:i});continue}let a=this.getServerCatalogEntry(i).description,l=this.agentConfig.delegatePrompts?.[i],c=l||`You are a tool specialist for ${i}. Execute the requested task using your available tools. Return results concisely. Do not add commentary or explanation beyond what was asked.`;s[i]={description:a,prompt:c,mcpServers:[{[i]:o}],model:"inherit",maxTurns:l?7:10,disallowedTools:["Agent"]},l&&R.info("Intent-aware delegate prompt loaded",{agent:this.agentConfig.id,server:i,promptLength:l.length})}return s}getServerCatalogEntry(e){if(It[e])return It[e];for(let t of this.plugins){let s=t.manifest.mcpServers[e];if(s?.description)return{description:s.description,usage:s.usage,notFor:s.notFor}}return{description:e}}buildSdkPlugins(){let e=this.agentConfig.plugins;if(!e?.length)return[];let t=[],s=Oe(Ke,"..","plugins","claude-code");for(let r of e){if(r.includes("/")||r.includes("\\")||r===".."||r.startsWith(".")){R.warn("Invalid plugin name, skipping",{plugin:r,agent:this.agentConfig.id});continue}let i=Oe(s,r);if(!Hs(i)){R.warn("Plugin not found, skipping",{plugin:r,expected:i,agent:this.agentConfig.id});continue}t.push({type:"local",path:i})}return t.length>0&&R.debug("Loaded plugins for agent",{agent:this.agentConfig.id,plugins:t.map(r=>r.path)}),t}buildNativeSkills(){return Ch(this.skillIndex,this.agentConfig.id)}getArchetypeDef(){return this._archetypeDef===void 0&&(this._archetypeDef=this.agentConfig.archetype?mr(this.agentConfig.archetype)??null:null,this.agentConfig.archetype&&!this._archetypeDef&&R.warn("Archetype referenced by agent not registered \u2014 running unstructured",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype})),this._archetypeDef}buildHooks(e){let t={PreCompact:this.buildPreCompactMatcher()},s=this.getArchetypeDef();if(s&&this.agentConfig.archetypeConfig)try{let r=s.preToolUseHooks({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:e});r.length>0&&(t.PreToolUse=r)}catch(r){R.error("Archetype preToolUseHooks threw \u2014 installing deny-all PreToolUse hook",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(r)}),t.PreToolUse=[{hooks:[async()=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Archetype hook initialization failed (${String(r)}). All tool calls blocked until the archetype is fixed.`}})]}]}return t}buildPreCompactMatcher(){let e=this.agentConfig.name,t=this.agentConfig.id,s=this.prefetcher;return[{hooks:[async(r,i,o)=>{R.info("PreCompact hook fired",{agent:t});let a=[`You are ${e} (agent ID: ${t}). When summarizing this conversation for compaction:`,"- Preserve your identity, role, and any behavioral instructions from your system prompt","- Keep all customer/contact names, deal details, and reference numbers","- Retain every decision made and commitment given \u2014 who decided what, and why","- Preserve active workflows: what's in progress, what's pending, next steps","- Keep tool call results that informed decisions (not raw API responses)","- Discard pleasantries, thinking-out-loud, and intermediate failed attempts"].join(`
172
- `),l="";if(s&&r?.transcript_path)try{let d=await J0(r.transcript_path,"utf-8");if(d.length>0){let h=d.length>2e5?d.slice(-2e5):d;l=await s.getCompactionContext(h,t)}}catch(d){R.warn("Code context extraction failed during compaction \u2014 proceeding without",{agent:t,error:String(d)})}return{continue:!0,systemMessage:l?`${a}
210
+ `)}buildServerConfig(e,t){return this.buildAllServerConfigs(t)[e]}buildAllServerConfigs(e){let t={};if(g.slack.localMcpServer)t.slack={type:"stdio",command:"node",args:[ce("slack/slack-mcp-server.js")],env:{HIVE_INTERNAL_URL:`http://127.0.0.1:${g.slackInternal.port}`,HIVE_INTERNAL_TOKEN:g.slackInternal.authToken,HIVE_AGENT_ID:this.agentConfig.id}};else{let c=g.slack.mcpToken;c&&(t.slack={type:"http",url:"https://mcp.slack.com/mcp",headers:{Authorization:`Bearer ${c}`}})}let i=[{id:"self",backing:"mongo"}],r=this.getArchetypeDef();if(r&&this.agentConfig.archetypeConfig)try{let c=r.memoryScopes({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});for(let u of c)u.id!=="self"&&i.push(u)}catch(c){J.error("Archetype memoryScopes threw \u2014 using self-only",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(c)})}t.memory={type:"stdio",command:"node",args:[ce("memory/memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,MEMORY_SCOPES_JSON:JSON.stringify(i)}},t["structured-memory"]={type:"stdio",command:"node",args:[ce("memory/structured-memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,CHANNEL_ID:e?.channelId??"",THREAD_ID:e?.threadId??"",QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333",OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434"}},t.keychain={type:"stdio",command:"node",args:[ce("keychain/keychain-mcp-server.js")],env:{KEYCHAIN_SERVICE:`hive/${g.instance.id}`}};let o=g.google.accounts[this.agentConfig.id]||g.google.account,s=g.google.client;if(t.google={type:"stdio",command:"node",args:[ce("google/google-mcp-server.js")],env:{...o?{GOG_ACCOUNT:o}:{},...s?{GOG_CLIENT:s}:{},DRIVE_SHARED_FOLDER:g.google.sharedFolder,INSTANCE_ID:g.instance.id,PATH:process.env.PATH??""}},g.quo.apiKey&&(t.quo={type:"stdio",command:"node",args:[ce("quo/quo-mcp-server.js")],env:{QUO_API_KEY:g.quo.apiKey,...g.quo.phoneNumberId?{QUO_PHONE_NUMBER_ID:g.quo.phoneNumberId}:{},QUO_LINES_JSON:JSON.stringify(g.quo.lines)}}),g.voice.enabled&&g.voice.apiKey){let c=Object.entries(g.voice.assistants).find(([u,d])=>d===this.agentConfig.id)?.[0]??"";t.voice={type:"stdio",command:"node",args:[ce("voice/voice-mcp-server.js")],env:{VAPI_API_KEY:g.voice.apiKey,VAPI_PHONE_NUMBER_ID:g.voice.phoneNumberId,VAPI_ASSISTANT_ID:c,AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name}}}t.contacts={type:"stdio",command:"node",args:[ce("contacts/contacts-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}};let a=g.taskLedger.agentKeys[this.agentConfig.id]??g.taskLedger.apiKey;if(a&&(t.tasks={type:"stdio",command:"node",args:[ce("tasks/task-mcp-server.js")],env:{TASK_LEDGER_API_URL:g.taskLedger.apiUrl,TASK_LEDGER_API_KEY:a}}),g.brave.apiKey&&(t["brave-search"]={type:"stdio",command:"node",args:[eM(import.meta.url).resolve("brave-search-mcp/dist/index.js")],env:{BRAVE_API_KEY:g.brave.apiKey}}),g.resend.apiKey){let c=this.agentConfig.name.toLowerCase(),u=g.resend.emailDomain,d=g.resend.businessName?` (${g.resend.businessName})`:"",f=u?`${this.agentConfig.name}${d} <${c}@${u}>`:g.resend.fromAddress;t.resend={type:"stdio",command:"node",args:[ce("resend/resend-mcp-server.js")],env:{RESEND_API_KEY:g.resend.apiKey,RESEND_FROM_ADDRESS:f,RESEND_DEFAULT_CC:g.resend.defaultCc,RESEND_DEFAULT_BCC:g.resend.defaultBcc}}}if(g.linear.apiKey){let c={LINEAR_API_KEY:g.linear.apiKey};g.linear.teamId&&(c.LINEAR_TEAM_ID=g.linear.teamId),t.linear={type:"stdio",command:"node",args:[ce("linear/linear-mcp-server.js")],env:c}}if(g.github.repo){let c={GITHUB_REPO:g.github.repo,PATH:process.env.PATH??""};g.github.token&&(c.GH_TOKEN=g.github.token),t["github-issues"]={type:"stdio",command:"node",args:[ce("github/github-issues-mcp-server.js")],env:c}}if(g.clickup.apiToken&&(t.clickup={type:"stdio",command:"node",args:[ce("clickup/clickup-mcp-server.js")],env:{CLICKUP_API_TOKEN:g.clickup.apiToken}}),g.recall.apiKey&&(t.recall={type:"stdio",command:"node",args:[ce("recall/recall-mcp-server.js")],env:{RECALL_API_KEY:g.recall.apiKey,RECALL_API_REGION:g.recall.region,RECALL_WEBHOOK_SECRET:g.recall.webhookSecret,MEETING_MONITOR_API:`http://127.0.0.1:${g.recall.monitorPort}`,MEETING_MONITOR_PUBLIC_URL:g.recall.monitorPublicUrl,RECALL_AGENT_ID:this.agentConfig.id,RECALL_ADAPTER_ID:e?.adapterId??"",RECALL_CHANNEL_ID:e?.channelId??"",RECALL_CHANNEL_KIND:e?.channelKind??"internal",RECALL_CHANNEL_LABEL:e?.channelLabel??"",RECALL_THREAD_ID:e?.threadId??"",RECALL_SLACK_TS:e?.slackTs??"",RECALL_SLACK_THREAD_TS:e?.slackThreadTs??""}}),g.browser.cdpEndpoint){let c=Qy(this.agentConfig.id,se);Kx(c,{recursive:!0}),t.browser={type:"stdio",command:"npx",args:["@playwright/mcp@latest","--cdp-endpoint",g.browser.cdpEndpoint,"--output-dir",c,"--user-data-dir",lt(c,"user-data")],env:{PATH:process.env.PATH??"",HOME:process.env.HOME??""}}}t.background={type:"stdio",command:"node",args:[ce("background/background-task-mcp-server.js")],env:{BG_TASK_API:`http://127.0.0.1:${g.background.port}`,BG_AUTH_TOKEN:g.background.authToken,BG_AGENT_ID:this.agentConfig.id,BG_ADAPTER_ID:e?.adapterId??"",BG_CHANNEL_ID:e?.channelId??"",BG_CHANNEL_KIND:e?.channelKind??"internal",BG_CHANNEL_LABEL:e?.channelLabel??"",BG_THREAD_ID:e?.threadId??"",BG_SLACK_TS:e?.slackTs??"",BG_SLACK_THREAD_TS:e?.slackThreadTs??""}},t.callback={type:"stdio",command:"node",args:[ce("callback/callback-mcp-server.js")],env:{CB_AGENT_ID:this.agentConfig.id,CB_ADAPTER_ID:e?.adapterId??"",CB_CHANNEL_ID:e?.channelId??"",CB_CHANNEL_KIND:e?.channelKind??"internal",CB_CHANNEL_LABEL:e?.channelLabel??"",CB_THREAD_ID:e?.threadId??"",CB_SLACK_TS:e?.slackTs??"",CB_SLACK_THREAD_TS:e?.slackThreadTs??"",MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}},t["code-task"]={type:"stdio",command:"node",args:[ce("code-task/code-task-mcp-server.js")],env:{CT_TASK_API:`http://127.0.0.1:${g.codeTask.port}`,CT_AUTH_TOKEN:g.codeTask.authToken,CT_AGENT_ID:this.agentConfig.id,CT_ADAPTER_ID:e?.adapterId??"",CT_CHANNEL_ID:e?.channelId??"",CT_CHANNEL_KIND:e?.channelKind??"internal",CT_CHANNEL_LABEL:e?.channelLabel??"",CT_THREAD_ID:e?.threadId??"",CT_SLACK_TS:e?.slackTs??"",CT_SLACK_THREAD_TS:e?.slackThreadTs??""}};let l={OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434",QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333"};process.env.KB_EMBED_MODEL&&(l.KB_EMBED_MODEL=process.env.KB_EMBED_MODEL),t["conversation-search"]={type:"stdio",command:"node",args:[ce("search/conversation-search-mcp-server.js")],env:{...l,AGENT_ID:this.agentConfig.id,DEFAULT_AGENT:g.defaultAgent}},t["code-search"]={type:"stdio",command:"node",args:[ce("code-index/code-search-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333",OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434"}};for(let c of this.plugins)for(let[u,d]of Object.entries(c.manifest.mcpServers)){if(t[u]){J.warn("Plugin server name conflicts with core server, skipping",{plugin:c.name,server:u});continue}if(c.brokenServers[u])continue;let f=Ti(c.name,d.entry,{hiveHome:se,distDir:Et});if("reason"in f){J.error("Plugin MCP server unresolvable at spawn time",{plugin:c.name,server:u,reason:f.reason,pathsChecked:f.pathsChecked});continue}let p=f.path;Vx(c.dir);let h=g.taskLedger.agentKeys[this.agentConfig.id]??g.taskLedger.apiKey,m={AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,TASK_LEDGER_API_URL:g.taskLedger.apiUrl,...h?{TASK_LEDGER_API_KEY:h}:{},PATH:process.env.PATH??"",HOME:process.env.HOME??""};for(let y of d.env??[])process.env[y]&&(m[y]=process.env[y]);for(let y of d.secretEnv??[]){let _=process.env[y]||rr(g.instance.id,y);_&&(m[y]=_)}for(let[y,_]of Object.entries(d.envMap??{}))m[_]&&(m[y]=m[_]);for(let[y,_]of Object.entries(d.agentEnv??{}))m[y]=n.resolveAgentEnvPath(this.agentConfig,_);t[u]={type:"stdio",command:"node",args:[p],env:m}}return t["event-bus"]={type:"stdio",command:"node",args:[ce("events/event-bus-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}},n.registryRef||J.warn("registryRef not set \u2014 agents will get empty AGENT_IDS for team server"),t.team={type:"stdio",command:"node",args:[ce("team/team-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,AGENT_IDS:JSON.stringify(n.registryRef?.getAll().map(c=>c.id)??[])}},g.workflow.enabled&&(t.workflow={type:"stdio",command:"node",args:[ce("workflow/workflow-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}}),t.schedule={type:"stdio",command:"node",args:[ce("schedule/schedule-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}},t.admin={type:"stdio",command:"node",args:[ce("admin/admin-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,AGENT_ID:this.agentConfig.id,INSTANCE_CAPABILITIES:nM(this.plugins)}},t}filterCoreServers(e){let t={...e},i=new Set(this.agentConfig.coreServers);i.has("memory")&&i.add("structured-memory"),i.add("schedule"),i.add("team"),i.add("team-roster"),i.add("slack"),g.workflow.enabled&&i.add("workflow");for(let r of Object.keys(t))i.has(r)||delete t[r];if(!this.agentConfig.autonomy.externalComms)for(let r of["resend","quo"])t[r]&&(J.debug("Autonomy: externalComms disabled \u2014 removing server",{server:r,agent:this.agentConfig.id}),delete t[r]);return this.agentConfig.autonomy.codeTask||t["code-task"]&&(J.debug("Autonomy: codeTask disabled \u2014 removing server",{server:"code-task",agent:this.agentConfig.id}),delete t["code-task"]),this.agentConfig.autonomy.codeAccess||t["code-search"]&&(J.debug("Autonomy: codeAccess disabled \u2014 removing server",{server:"code-search",agent:this.agentConfig.id}),delete t["code-search"]),t}static resolveAgentEnvPath(e,t){let i=t.split("."),r=e;for(let o of i){if(r==null||typeof r!="object")return"";r=r[o]}return r==null?"":String(r)}static autoInjectedServerNames(){let e=new Set(["schedule","team","team-roster","slack"]);return g.workflow.enabled&&e.add("workflow"),e}static CONTEXT_DEPENDENT_SERVERS=new Set(["callback","background","code-task","recall","structured-memory","memory"]);buildDelegateAgents(e){let t=this.agentConfig.delegateServers;if(t.length===0)return{};let i={},r=new Set;this.agentConfig.autonomy.externalComms||(r.add("resend"),r.add("quo")),this.agentConfig.autonomy.codeTask||r.add("code-task"),this.agentConfig.autonomy.codeAccess||r.add("code-search");for(let o of t){if(r.has(o)){J.debug("Autonomy gate \u2014 skipping delegate server",{server:o,agent:this.agentConfig.id});continue}n.CONTEXT_DEPENDENT_SERVERS.has(o)&&J.warn("Context-dependent server in delegateServers \u2014 subagent won't have channel context",{agent:this.agentConfig.id,server:o});let s=e[o];if(!s){J.warn("Delegate server not found in configs, skipping",{agent:this.agentConfig.id,server:o});continue}let a=this.getServerCatalogEntry(o).description,l=this.agentConfig.delegatePrompts?.[o],c=l||`You are a tool specialist for ${o}. Execute the requested task using your available tools. Return results concisely. Do not add commentary or explanation beyond what was asked.`;i[o]={description:a,prompt:c,mcpServers:[{[o]:s}],model:"inherit",maxTurns:l?7:10,disallowedTools:["Agent"]},l&&J.info("Intent-aware delegate prompt loaded",{agent:this.agentConfig.id,server:o,promptLength:l.length})}return i}getServerCatalogEntry(e){if(bn[e])return bn[e];for(let t of this.plugins){let i=t.manifest.mcpServers[e];if(i?.description)return{description:i.description,usage:i.usage,notFor:i.notFor}}return{description:e}}buildSdkPlugins(){let e=this.agentConfig.plugins;if(!e?.length)return[];let t=[],i=lt(Et,"..","plugins","claude-code");for(let r of e){if(r.includes("/")||r.includes("\\")||r===".."||r.startsWith(".")){J.warn("Invalid plugin name, skipping",{plugin:r,agent:this.agentConfig.id});continue}let o=lt(i,r);if(!fo(o)){J.warn("Plugin not found, skipping",{plugin:r,expected:o,agent:this.agentConfig.id});continue}t.push({type:"local",path:o})}return t.length>0&&J.debug("Loaded plugins for agent",{agent:this.agentConfig.id,plugins:t.map(r=>r.path)}),t}buildNativeSkills(){return Hb(this.skillIndex,this.agentConfig.id)}getArchetypeDef(){return this._archetypeDef===void 0&&(this._archetypeDef=this.agentConfig.archetype?Ps(this.agentConfig.archetype)??null:null,this.agentConfig.archetype&&!this._archetypeDef&&J.warn("Archetype referenced by agent not registered \u2014 running unstructured",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype})),this._archetypeDef}buildHooks(e){let t={PreCompact:this.buildPreCompactMatcher()},i=this.getArchetypeDef();if(i&&this.agentConfig.archetypeConfig)try{let r=i.preToolUseHooks({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:e});r.length>0&&(t.PreToolUse=r)}catch(r){J.error("Archetype preToolUseHooks threw \u2014 installing deny-all PreToolUse hook",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(r)}),t.PreToolUse=[{hooks:[async()=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Archetype hook initialization failed (${String(r)}). All tool calls blocked until the archetype is fixed.`}})]}]}return t}buildPreCompactMatcher(){let e=this.agentConfig.name,t=this.agentConfig.id,i=this.prefetcher;return[{hooks:[async(r,o,s)=>{J.info("PreCompact hook fired",{agent:t});let a=[`You are ${e} (agent ID: ${t}). When summarizing this conversation for compaction:`,"- Preserve your identity, role, and any behavioral instructions from your system prompt","- Keep all customer/contact names, deal details, and reference numbers","- Retain every decision made and commitment given \u2014 who decided what, and why","- Preserve active workflows: what's in progress, what's pending, next steps","- Keep tool call results that informed decisions (not raw API responses)","- Discard pleasantries, thinking-out-loud, and intermediate failed attempts"].join(`
211
+ `),l="";if(i&&r?.transcript_path)try{let u=await tM(r.transcript_path,"utf-8");if(u.length>0){let f=u.length>2e5?u.slice(-2e5):u;l=await i.getCompactionContext(f,t)}}catch(u){J.warn("Code context extraction failed during compaction \u2014 proceeding without",{agent:t,error:String(u)})}return{continue:!0,systemMessage:l?`${a}
173
212
 
174
- ${l}`:a}}]}]}async send(e,t,s,r,i,o){let a=i??this.agentConfig.model;R.info("Sending prompt to agent",{agent:this.agentConfig.id,model:a,modelOverride:!!i,resumeSession:t??"new",promptLength:e.length,streaming:!!s});let l=this.buildAllServerConfigs(r),c=this.filterCoreServers(l),d=this.buildDelegateAgents(l),u=await this.buildSystemPrompt(Object.keys(c),Object.keys(d)),h=[...this.buildSdkPlugins(),...this.buildNativeSkills()];Object.keys(d).length>0&&R.info("Delegate subagents configured",{agent:this.agentConfig.id,delegates:Object.keys(d)});let p={},m=this.getArchetypeDef();if(m&&this.agentConfig.archetypeConfig)try{p=m.sessionOptions({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:r})}catch(Y){R.error("Archetype sessionOptions threw \u2014 ignoring",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(Y)})}let f=typeof p.cwd=="string"?"archetype":"default",y=f==="archetype"?p.cwd:pn(this.agentConfig.id,V);if(f==="default")Mh(y,{recursive:!0});else{let Y;try{Y=W0(y)}catch(L){let P=`Archetype cwd unavailable at session start \u2014 refusing to run: ${y} (${String(L)})`;throw R.error(P,{agent:this.agentConfig.id}),new Error(P)}if(!Y.isDirectory()){let L=`Archetype cwd is not a directory: ${y}`;throw R.error(L,{agent:this.agentConfig.id}),new Error(L)}}let w=H0({prompt:e,options:{model:a,systemPrompt:u,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:o?.maxTurns??this.agentConfig.maxTurns,maxBudgetUsd:o?.budgetUsd??this.agentConfig.budgetUsd,cwd:y,settingSources:p.settingSources??[],includePartialMessages:!!s,...t?{resume:t}:{},...Object.keys(c).length>0?{mcpServers:c}:{},...Object.keys(d).length>0?{agents:d}:{},...h.length>0?{plugins:h}:{},hooks:this.buildHooks(r),...this.agentConfig.betas?.length?{betas:this.agentConfig.betas}:{},env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});this.activeQuery=w;let S="",_=t??"",v=0,I=0,N=!1,D;this._aborted=!1;let A=0,E=0,G=0,W=0,$=0,le=0,Ie,ge=[],ln=null,os=null,mt=o?.timeoutMs??this.agentConfig.timeoutMs??3e5,Ti=setTimeout(()=>{R.warn("Agent query timed out, aborting",{agent:this.agentConfig.id,timeoutMs:mt}),this.abort()},mt);try{for await(let Y of w){let L=Y;if(L.type==="system"&&L.subtype==="init"&&(_=L.session_id,R.debug("Session initialized",{sessionId:_})),L.type==="system"&&L.subtype==="compact_boundary"){let P=L.compact_metadata;le++,Ie=P?.pre_tokens,R.info("Context compacted",{agent:this.agentConfig.id,trigger:P?.trigger,preTokens:P?.pre_tokens,compactionNumber:le})}if(L.type==="system"&&L.subtype==="status"&&L.status==="compacting"&&R.info("Compaction in progress",{agent:this.agentConfig.id}),L.type==="stream_event"&&s){let P=L.event;P?.type==="content_block_delta"&&P?.delta?.type==="text_delta"&&(s(P.delta.text),N=!0)}if(L.type==="tool_progress"){let P=L;R.info("Tool in progress",{agent:this.agentConfig.id,tool:P.tool_name,elapsed:P.elapsed_time_seconds})}if(L.type==="assistant"){let P=L.message?.content;if(Array.isArray(P))for(let de of P)de.type==="text"?S=de.text:de.type==="tool_use"&&(os&&ge.length>0&&(ge[ge.length-1].endMs=Date.now()),os=de.name,ln=Date.now(),ge.push({tool:de.name,startMs:ln}),R.info("Tool call started",{agent:this.agentConfig.id,tool:de.name}));L.session_id&&(_=L.session_id)}if(L.type==="result"){let P=L;v=P.total_cost_usd,I=P.duration_ms,_=P.session_id;let de=P.usage;de&&(A=de.input_tokens??0,E=de.output_tokens??0,G=de.cache_read_input_tokens??0,W=de.cache_creation_input_tokens??0);let un=P.modelUsage;if(un)for(let Pt of Object.values(un))Pt.contextWindow&&Pt.contextWindow>$&&($=Pt.contextWindow);P.subtype==="success"?S=P.result||S:(D=P.subtype,"errors"in P&&Array.isArray(P.errors)&&(D=P.errors.join("; ")))}}}catch(Y){let L=String(Y);S&&v>0?R.warn("Agent process crashed after producing response \u2014 using response anyway",{agent:this.agentConfig.id,error:L,resultPreview:S.slice(0,200),costUsd:v,durationMs:I}):(D=L,R.error("Agent query failed",{agent:this.agentConfig.id,error:L,costUsd:v,durationMs:I}))}finally{clearTimeout(Ti),this.activeQuery=null}os&&ge.length>0&&(ge[ge.length-1].endMs=Date.now());let Qe={};for(let Y of ge){let L=(Y.endMs??Date.now())-Y.startMs,P=Y.tool.includes("__")?Y.tool.split("__")[1]:Y.tool;Qe[P]||(Qe[P]={count:0,totalMs:0}),Qe[P].count++,Qe[P].totalMs+=L}let dn=Object.entries(Qe).sort((Y,L)=>L[1].totalMs-Y[1].totalMs).map(([Y,L])=>`${Y}:${L.count}x/${(L.totalMs/1e3).toFixed(1)}s`).join(", "),Be=ge.reduce((Y,L)=>Y+((L.endMs??Date.now())-L.startMs),0),as=I-Be;return R.info("Agent response complete",{agent:this.agentConfig.id,sessionId:_,costUsd:v,durationMs:I,llmMs:as,toolMs:Be,toolCalls:ge.length,toolSummary:dn||"none",inputTokens:A,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:le,preCompactTokens:Ie,streamed:N,hasError:!!D}),{text:S,sessionId:_,costUsd:v,durationMs:I,llmMs:as,toolMs:Be,toolCalls:ge.length,toolSummary:dn||"none",streamed:N,inputTokens:A,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:le,preCompactTokens:Ie,error:D,aborted:this._aborted}}_aborted=!1;get wasAborted(){return this._aborted}abort(){this.activeQuery&&(R.info("Aborting active query",{agent:this.agentConfig.id}),this._aborted=!0,this.activeQuery.close(),this.activeQuery=null)}}});import{writeFileSync as $a,mkdirSync as Z0}from"node:fs";import{join as Tr,extname as Ra}from"node:path";import{tmpdir as ek}from"node:os";function Rh(n){Pa=n}async function Bh(n,e){if(!Pa)return null;try{let t=n.toString("base64"),s=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Ph}:generateContent?key=${Pa}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{parts:[{inline_data:{mime_type:e,data:t}},{text:"Describe this image in detail. If it contains text, extract all of it. If it's a diagram, architecture drawing, or technical image, describe all labels, relationships, and structure. If it's a screenshot of messages or a conversation, transcribe everything. Be thorough."}]}]})});if(!s.ok){let o=await s.text();return ye.warn("Gemini vision error",{status:s.status,error:o.slice(0,200)}),null}let i=(await s.json()).candidates?.[0]?.content?.parts?.[0]?.text;return i&&ye.info("Image described via Gemini",{model:Ph,chars:i.length}),i||null}catch(t){return ye.warn("Gemini vision failed",{error:t.message}),null}}async function Uh(n,e,t){let s=Ra(e).slice(1).toLowerCase();if(tk.has(s)||t.startsWith("text/"))return{textContent:vr(n.toString("utf-8")),isImage:!1};if(s==="pdf"||t==="application/pdf")try{let r=await import("pdf-parse"),o=await(r.default??r)(n);return{textContent:vr(o.text),isImage:!1}}catch(r){return ye.warn("PDF parse failed",{name:e,error:r.message}),{textContent:"[PDF \u2014 could not extract text]",isImage:!1}}if(s==="docx"||t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document")try{let i=await(await import("mammoth")).extractRawText({buffer:n});return{textContent:vr(i.value),isImage:!1}}catch(r){return ye.warn("DOCX parse failed",{name:e,error:r.message}),{textContent:"[DOCX \u2014 could not extract text]",isImage:!1}}if(s==="xlsx"||s==="xls"||t.includes("spreadsheet"))try{let r=await import("xlsx"),i=r.read(n,{type:"buffer"}),o=i.SheetNames.map(a=>{let l=r.utils.sheet_to_csv(i.Sheets[a]);return`--- Sheet: ${a} ---
175
- ${l}`});return{textContent:vr(o.join(`
213
+ ${l}`:a}}]}]}async send(e,t,i,r,o,s){let a=o??this.agentConfig.model;J.info("Sending prompt to agent",{agent:this.agentConfig.id,model:a,modelOverride:!!o,resumeSession:t??"new",promptLength:e.length,streaming:!!i});let l=this.buildAllServerConfigs(r),c=this.filterCoreServers(l);this.teamRoster&&(this.teamRosterMcpServer||(this.teamRosterMcpServer=qx(this.teamRoster)),c["team-roster"]=this.teamRosterMcpServer);let u=this.buildDelegateAgents(l),d=await this.buildSystemPrompt(Object.keys(c),Object.keys(u)),f=[...this.buildSdkPlugins(),...this.buildNativeSkills()];Object.keys(u).length>0&&J.info("Delegate subagents configured",{agent:this.agentConfig.id,delegates:Object.keys(u)});let p={},h=this.getArchetypeDef();if(h&&this.agentConfig.archetypeConfig)try{p=h.sessionOptions({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:r})}catch(de){J.error("Archetype sessionOptions threw \u2014 ignoring",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(de)})}let m=typeof p.cwd=="string"?"archetype":"default",y=m==="archetype"?p.cwd:Do(this.agentConfig.id,se);if(m==="default")Kx(y,{recursive:!0});else{let de;try{de=Y1(y)}catch(Z){let G=`Archetype cwd unavailable at session start \u2014 refusing to run: ${y} (${String(Z)})`;throw J.error(G,{agent:this.agentConfig.id}),new Error(G)}if(!de.isDirectory()){let Z=`Archetype cwd is not a directory: ${y}`;throw J.error(Z,{agent:this.agentConfig.id}),new Error(Z)}}let _=H1({prompt:e,options:{model:a,systemPrompt:d,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:s?.maxTurns??this.agentConfig.maxTurns,maxBudgetUsd:s?.budgetUsd??this.agentConfig.budgetUsd,cwd:y,settingSources:p.settingSources??[],includePartialMessages:!!i,...t?{resume:t}:{},...Object.keys(c).length>0?{mcpServers:c}:{},...Object.keys(u).length>0?{agents:u}:{},...f.length>0?{plugins:f}:{},hooks:this.buildHooks(r),...this.agentConfig.betas?.length?{betas:this.agentConfig.betas}:{},env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});this.activeQuery=_;let b="",k=t??"",O=0,A=0,j=!1,L;this._aborted=!1;let P=0,z=0,ae=0,ue=0,W=0,Se=0,tt,Ie=[],Rn=null,wt=null,Oo=s?.timeoutMs??this.agentConfig.timeoutMs??3e5,Ml=setTimeout(()=>{J.warn("Agent query timed out, aborting",{agent:this.agentConfig.id,timeoutMs:Oo}),this.abort()},Oo);try{for await(let de of _){let Z=de;if(Z.type==="system"&&Z.subtype==="init"&&(k=Z.session_id,J.debug("Session initialized",{sessionId:k})),Z.type==="system"&&Z.subtype==="compact_boundary"){let G=Z.compact_metadata;Se++,tt=G?.pre_tokens,J.info("Context compacted",{agent:this.agentConfig.id,trigger:G?.trigger,preTokens:G?.pre_tokens,compactionNumber:Se})}if(Z.type==="system"&&Z.subtype==="status"&&Z.status==="compacting"&&J.info("Compaction in progress",{agent:this.agentConfig.id}),Z.type==="stream_event"&&i){let G=Z.event;G?.type==="content_block_delta"&&G?.delta?.type==="text_delta"&&(i(G.delta.text),j=!0)}if(Z.type==="tool_progress"){let G=Z;J.info("Tool in progress",{agent:this.agentConfig.id,tool:G.tool_name,elapsed:G.elapsed_time_seconds})}if(Z.type==="assistant"){let G=Z.message?.content;if(Array.isArray(G))for(let Te of G)Te.type==="text"?b=Te.text:Te.type==="tool_use"&&(wt&&Ie.length>0&&(Ie[Ie.length-1].endMs=Date.now()),wt=Te.name,Rn=Date.now(),Ie.push({tool:Te.name,startMs:Rn}),J.info("Tool call started",{agent:this.agentConfig.id,tool:Te.name}));Z.session_id&&(k=Z.session_id)}if(Z.type==="result"){let G=Z;O=G.total_cost_usd,A=G.duration_ms,k=G.session_id;let Te=G.usage;Te&&(P=Te.input_tokens??0,z=Te.output_tokens??0,ae=Te.cache_read_input_tokens??0,ue=Te.cache_creation_input_tokens??0);let Bn=G.modelUsage;if(Bn)for(let Fn of Object.values(Bn))Fn.contextWindow&&Fn.contextWindow>W&&(W=Fn.contextWindow);G.subtype==="success"?b=G.result||b:(L=G.subtype,"errors"in G&&Array.isArray(G.errors)&&(L=G.errors.join("; ")))}}}catch(de){let Z=String(de);b&&O>0?J.warn("Agent process crashed after producing response \u2014 using response anyway",{agent:this.agentConfig.id,error:Z,resultPreview:b.slice(0,200),costUsd:O,durationMs:A}):(L=Z,J.error("Agent query failed",{agent:this.agentConfig.id,error:Z,costUsd:O,durationMs:A}))}finally{clearTimeout(Ml),this.activeQuery=null}wt&&Ie.length>0&&(Ie[Ie.length-1].endMs=Date.now());let un={};for(let de of Ie){let Z=(de.endMs??Date.now())-de.startMs,G=de.tool.includes("__")?de.tool.split("__")[1]:de.tool;un[G]||(un[G]={count:0,totalMs:0}),un[G].count++,un[G].totalMs+=Z}let dn=Object.entries(un).sort((de,Z)=>Z[1].totalMs-de[1].totalMs).map(([de,Z])=>`${de}:${Z.count}x/${(Z.totalMs/1e3).toFixed(1)}s`).join(", "),Zr=Ie.reduce((de,Z)=>de+((Z.endMs??Date.now())-Z.startMs),0),Kr=A-Zr;return J.info("Agent response complete",{agent:this.agentConfig.id,sessionId:k,costUsd:O,durationMs:A,llmMs:Kr,toolMs:Zr,toolCalls:Ie.length,toolSummary:dn||"none",inputTokens:P,outputTokens:z,cacheReadTokens:ae,cacheCreationTokens:ue,contextWindow:W,compactions:Se,preCompactTokens:tt,streamed:j,hasError:!!L}),{text:b,sessionId:k,costUsd:O,durationMs:A,llmMs:Kr,toolMs:Zr,toolCalls:Ie.length,toolSummary:dn||"none",streamed:j,inputTokens:P,outputTokens:z,cacheReadTokens:ae,cacheCreationTokens:ue,contextWindow:W,compactions:Se,preCompactTokens:tt,error:L,aborted:this._aborted}}_aborted=!1;get wasAborted(){return this._aborted}abort(){this.activeQuery&&(J.info("Aborting active query",{agent:this.agentConfig.id}),this._aborted=!0,this.activeQuery.close(),this.activeQuery=null)}}});import{writeFileSync as iy,mkdirSync as oM}from"node:fs";import{join as Nc,extname as oy}from"node:path";import{tmpdir as sM}from"node:os";function Hx(n){ry=n}async function Yx(n,e){if(!ry)return null;try{let t=n.toString("base64"),i=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Gx}:generateContent?key=${ry}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{parts:[{inline_data:{mime_type:e,data:t}},{text:"Describe this image in detail. If it contains text, extract all of it. If it's a diagram, architecture drawing, or technical image, describe all labels, relationships, and structure. If it's a screenshot of messages or a conversation, transcribe everything. Be thorough."}]}]})});if(!i.ok){let s=await i.text();return Ke.warn("Gemini vision error",{status:i.status,error:s.slice(0,200)}),null}let o=(await i.json()).candidates?.[0]?.content?.parts?.[0]?.text;return o&&Ke.info("Image described via Gemini",{model:Gx,chars:o.length}),o||null}catch(t){return Ke.warn("Gemini vision failed",{error:t.message}),null}}async function Xx(n,e,t){let i=oy(e).slice(1).toLowerCase();if(aM.has(i)||t.startsWith("text/"))return{textContent:Cc(n.toString("utf-8")),isImage:!1};if(i==="pdf"||t==="application/pdf")try{let r=await import("pdf-parse"),s=await(r.default??r)(n);return{textContent:Cc(s.text),isImage:!1}}catch(r){return Ke.warn("PDF parse failed",{name:e,error:r.message}),{textContent:"[PDF \u2014 could not extract text]",isImage:!1}}if(i==="docx"||t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document")try{let o=await(await import("mammoth")).extractRawText({buffer:n});return{textContent:Cc(o.value),isImage:!1}}catch(r){return Ke.warn("DOCX parse failed",{name:e,error:r.message}),{textContent:"[DOCX \u2014 could not extract text]",isImage:!1}}if(i==="xlsx"||i==="xls"||t.includes("spreadsheet"))try{let r=await import("xlsx"),o=r.read(n,{type:"buffer"}),s=o.SheetNames.map(a=>{let l=r.utils.sheet_to_csv(o.Sheets[a]);return`--- Sheet: ${a} ---
214
+ ${l}`});return{textContent:Cc(s.join(`
176
215
 
177
- `)),isImage:!1}}catch(r){return ye.warn("XLSX parse failed",{name:e,error:r.message}),{textContent:"[Spreadsheet \u2014 could not extract content]",isImage:!1}}return null}async function jh(n,e){let t=n.url_private_download||n.url_private;if(!t)return ye.warn("No download URL for file",{id:n.id,name:n.name}),null;try{ye.info("Downloading file",{id:n.id,url:t.slice(0,80),mimetype:n.mimetype});let s=await fetch(t,{headers:{Authorization:`Bearer ${e}`},redirect:"manual"});if(s.status===302||s.status===301){let d=s.headers.get("location");d&&(ye.info("Following redirect",{id:n.id}),s=await fetch(d))}if(!s.ok)return ye.error("Failed to download file",{id:n.id,status:s.status}),null;let r=Buffer.from(await s.arrayBuffer());if(r.length<100&&r.length>0){let d=r.toString("utf-8").trim();if(d.includes("requested")&&d.includes("file")&&d.includes("not found"))return ye.error("Slack file error response",{id:n.id,name:n.name,errorText:d,bufferSize:r.length}),null}let i=n.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=Tr(Ir,`${n.id}-${i}`);$a(o,r);let a=Ra(n.name).slice(1).toLowerCase();if($h.has(a)||n.mimetype.startsWith("image/")){let d=await Bh(r,n.mimetype);return{name:n.name,mimetype:n.mimetype,size:n.size,localPath:o,textContent:d??"[Image \u2014 could not extract description]",isImage:!0}}let c=await Uh(r,n.name,n.mimetype);return c?{name:n.name,mimetype:n.mimetype,size:n.size,localPath:o,...c}:(ye.info("Unsupported file type",{name:n.name,ext:a,mimetype:n.mimetype}),{name:n.name,mimetype:n.mimetype,size:n.size,localPath:o,textContent:null,isImage:!1})}catch(s){return ye.error("File processing failed",{id:n.id,name:n.name,error:s.message}),null}}async function Gs(n,e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_"),r=Tr(Ir,`ws-${Date.now()}-${s}`);$a(r,n);let i=await Bh(n,t);return{name:e,mimetype:t,size:n.length,localPath:r,textContent:i??"[Image \u2014 could not extract description]",isImage:!0}}async function qh(n,e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_"),r=Tr(Ir,`team-${Date.now()}-${s}`);$a(r,n);let i=Ra(e).slice(1).toLowerCase();if($h.has(i)||t.startsWith("image/"))return Gs(n,e,t);let a=await Uh(n,e,t);return a?{name:e,mimetype:t,size:n.length,localPath:r,...a}:{name:e,mimetype:t,size:n.length,localPath:r,textContent:null,isImage:!1}}function Fh(n){return n.length===0?"":`
216
+ `)),isImage:!1}}catch(r){return Ke.warn("XLSX parse failed",{name:e,error:r.message}),{textContent:"[Spreadsheet \u2014 could not extract content]",isImage:!1}}return null}async function Qx(n,e){let t=n.url_private_download||n.url_private;if(!t)return Ke.warn("No download URL for file",{id:n.id,name:n.name}),null;try{Ke.info("Downloading file",{id:n.id,url:t.slice(0,80),mimetype:n.mimetype});let i=await fetch(t,{headers:{Authorization:`Bearer ${e}`},redirect:"manual"});if(i.status===302||i.status===301){let u=i.headers.get("location");u&&(Ke.info("Following redirect",{id:n.id}),i=await fetch(u))}if(!i.ok)return Ke.error("Failed to download file",{id:n.id,status:i.status}),null;let r=Buffer.from(await i.arrayBuffer());if(r.length<100&&r.length>0){let u=r.toString("utf-8").trim();if(u.includes("requested")&&u.includes("file")&&u.includes("not found"))return Ke.error("Slack file error response",{id:n.id,name:n.name,errorText:u,bufferSize:r.length}),null}let o=n.name.replace(/[^a-zA-Z0-9._-]/g,"_"),s=Nc(Dc,`${n.id}-${o}`);iy(s,r);let a=oy(n.name).slice(1).toLowerCase();if(Jx.has(a)||n.mimetype.startsWith("image/")){let u=await Yx(r,n.mimetype);return{name:n.name,mimetype:n.mimetype,size:n.size,localPath:s,textContent:u??"[Image \u2014 could not extract description]",isImage:!0}}let c=await Xx(r,n.name,n.mimetype);return c?{name:n.name,mimetype:n.mimetype,size:n.size,localPath:s,...c}:(Ke.info("Unsupported file type",{name:n.name,ext:a,mimetype:n.mimetype}),{name:n.name,mimetype:n.mimetype,size:n.size,localPath:s,textContent:null,isImage:!1})}catch(i){return Ke.error("File processing failed",{id:n.id,name:n.name,error:i.message}),null}}async function mo(n,e,t){let i=e.replace(/[^a-zA-Z0-9._-]/g,"_"),r=Nc(Dc,`ws-${Date.now()}-${i}`);iy(r,n);let o=await Yx(n,t);return{name:e,mimetype:t,size:n.length,localPath:r,textContent:o??"[Image \u2014 could not extract description]",isImage:!0}}async function eI(n,e,t){let i=e.replace(/[^a-zA-Z0-9._-]/g,"_"),r=Nc(Dc,`team-${Date.now()}-${i}`);iy(r,n);let o=oy(e).slice(1).toLowerCase();if(Jx.has(o)||t.startsWith("image/"))return mo(n,e,t);let a=await Xx(n,e,t);return a?{name:e,mimetype:t,size:n.length,localPath:r,...a}:{name:e,mimetype:t,size:n.length,localPath:r,textContent:null,isImage:!1}}function tI(n){return n.length===0?"":`
178
217
 
179
- `+n.map(t=>{let s=`\u{1F4CE} File: ${t.name} (${Kh(t.size)}, ${t.mimetype})`;return t.isImage?t.textContent?`${s}
218
+ `+n.map(t=>{let i=`\u{1F4CE} File: ${t.name} (${nI(t.size)}, ${t.mimetype})`;return t.isImage?t.textContent?`${i}
180
219
  --- image description ---
181
220
  ${t.textContent}
182
- --- end image description ---`:`${s}
183
- [Image received but could not be processed]`:t.textContent?`${s}
221
+ --- end image description ---`:`${i}
222
+ [Image received but could not be processed]`:t.textContent?`${i}
184
223
  --- file content ---
185
224
  ${t.textContent}
186
- --- end file content ---`:`${s}
225
+ --- end file content ---`:`${i}
187
226
  Saved at: ${t.localPath}
188
227
  (Content could not be extracted \u2014 file available for download)`}).join(`
189
228
 
190
- `)}function Kh(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function vr(n,e=5e4){return n.length<=e?n:n.slice(0,e)+`
229
+ `)}function nI(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function Cc(n,e=5e4){return n.length<=e?n:n.slice(0,e)+`
191
230
 
192
- [... truncated at ${Kh(e)} \u2014 full file at local path]`}var ye,Ir,$h,Pa,Ph,tk,Vs=j(()=>{"use strict";M();ye=k("file-processor"),Ir=Tr(ek(),"hive-slack-files");Z0(Ir,{recursive:!0});$h=new Set(["png","jpg","jpeg","gif","webp","bmp","heic"]),Pa="",Ph=process.env.GEMINI_VISION_MODEL||"gemini-2.5-flash";tk=new Set(["csv","tsv","txt","text","md","markdown","json","xml","html","yaml","yml","log"])});async function He(n,e){let t=await fetch(`${n}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:ak,input:e})});if(!t.ok)throw new Error(`Ollama embed ${t.status}: ${await t.text()}`);return(await t.json()).embeddings[0]}var ak,Er=j(()=>{"use strict";ak=process.env.KB_EMBED_MODEL??"bge-large"});var Wa,aN,bf=j(()=>{"use strict";Wa="code_index",aN=Buffer.from("6ba7b8109dad11d180b400c04fd430c8","hex")});var _f={};Ue(_f,{CodeIndexPrefetcher:()=>Ga});import{QdrantClient as Mb}from"@qdrant/js-client-rest";var Ga,vf=j(()=>{"use strict";Er();bf();Ga=class{options;qdrant;connected=!1;scoreThreshold;prefetchLimit;constructor(e){this.options=e,this.scoreThreshold=e.scoreThreshold??.65,this.prefetchLimit=e.prefetchLimit??8}async ensureConnected(){this.connected||(this.qdrant=new Mb({url:this.options.qdrantUrl}),this.connected=!0)}async getContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],r;try{r=await He(this.options.ollamaUrl,e)}catch{return""}try{let o=(await this.qdrant.search(Wa,{vector:r,limit:this.prefetchLimit,with_payload:!0})).filter(a=>a.score>=this.scoreThreshold);if(o.length>0){let a=o.map(l=>{let c=l.payload;return`- **${c.repo}:${c.filePath}** \u2014 ${c.summary} (${c.role})`});s.push(`**Relevant files:**
231
+ [... truncated at ${nI(e)} \u2014 full file at local path]`}var Ke,Dc,Jx,ry,Gx,aM,ho=S(()=>{"use strict";R();Ke=$("file-processor"),Dc=Nc(sM(),"hive-slack-files");oM(Dc,{recursive:!0});Jx=new Set(["png","jpg","jpeg","gif","webp","bmp","heic"]),ry="",Gx=process.env.GEMINI_VISION_MODEL||"gemini-2.5-flash";aM=new Set(["csv","tsv","txt","text","md","markdown","json","xml","html","yaml","yml","log"])});async function At(n,e){let t=await fetch(`${n}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:pM,input:e})});if(!t.ok)throw new Error(`Ollama embed ${t.status}: ${await t.text()}`);return(await t.json()).embeddings[0]}var pM,Lc=S(()=>{"use strict";pM=process.env.KB_EMBED_MODEL??"bge-large"});var py,dZ,zI=S(()=>{"use strict";py="code_index",dZ=Buffer.from("6ba7b8109dad11d180b400c04fd430c8","hex")});var jI={};we(jI,{CodeIndexPrefetcher:()=>my});import{QdrantClient as jL}from"@qdrant/js-client-rest";var my,UI=S(()=>{"use strict";Lc();zI();my=class{options;qdrant;connected=!1;scoreThreshold;prefetchLimit;constructor(e){this.options=e,this.scoreThreshold=e.scoreThreshold??.65,this.prefetchLimit=e.prefetchLimit??8}async ensureConnected(){this.connected||(this.qdrant=new jL({url:this.options.qdrantUrl}),this.connected=!0)}async getContext(e,t){try{await this.ensureConnected()}catch{return""}let i=[],r;try{r=await At(this.options.ollamaUrl,e)}catch{return""}try{let s=(await this.qdrant.search(py,{vector:r,limit:this.prefetchLimit,with_payload:!0})).filter(a=>a.score>=this.scoreThreshold);if(s.length>0){let a=s.map(l=>{let c=l.payload;return`- **${c.repo}:${c.filePath}** \u2014 ${c.summary} (${c.role})`});i.push(`**Relevant files:**
193
232
  `+a.join(`
194
- `))}}catch{}if(t)try{let o=(await this.qdrant.search("agent_memory",{vector:r,limit:15,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(a=>a.score>=this.scoreThreshold).filter(a=>typeof a.payload?.topic=="string"&&a.payload.topic.startsWith("code:"));if(o.length>0){let a=o.map(l=>l.payload?.mongoId).filter(Boolean);if(a.length>0){let l=this.options.db.collection("agent_memory"),{ObjectId:c}=await import("mongodb"),d=await l.find({_id:{$in:a.map(u=>new c(u))}}).toArray();if(d.length>0){let u=d.map(h=>`- ${String(h.topic??"").replace(/^code:/,"")}: ${String(h.content??"")}`);s.push(`**Previous session insights:**
195
- `+u.join(`
196
- `))}}}}catch{}return s.length===0?"":["## Codebase Context (auto-retrieved)",...s,"","_Results may be stale \u2014 verify by reading files._"].join(`
197
- `)}extractFilePaths(e){let t=/(?:^|\s|`|"|')((src|plugins|dist|docs|scripts|setup|skills|service|agents-templates|test)\/.{1,200}\.(ts|tsx|js|jsx|json|yaml|yml|md))\b/gm,s=new Set,r;for(;(r=t.exec(e))!==null;)s.add(r[1]);return[...s]}async getCompactionContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],r=[],i=new Set;try{let c=this.extractFilePaths(e);if(c.length>0){let u=await this.options.db.collection("code_index").find({filePath:{$in:c}}).project({repo:1,filePath:1,summary:1,role:1}).toArray();for(let h of u){let p=`${h.repo}:${h.filePath}`;i.has(p)||(i.add(p),s.push(`- ${p} \u2014 ${h.summary} [${h.role}]`))}}}catch{}try{let c=e.slice(-2e3),d=await He(this.options.ollamaUrl,c),u=await this.qdrant.search(Wa,{vector:d,limit:this.prefetchLimit,with_payload:!0});for(let h of u){if(h.score<this.scoreThreshold)continue;let p=h.payload,m=`${p.repo}:${p.filePath}`;i.has(m)||(i.add(m),s.push(`- ${m} \u2014 ${p.summary} [${p.role}]`))}if(t){let p=(await this.qdrant.search("agent_memory",{vector:d,limit:10,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(m=>m.score>=this.scoreThreshold).filter(m=>typeof m.payload?.topic=="string"&&m.payload.topic.startsWith("code:"));if(p.length>0){let m=p.map(f=>f.payload?.mongoId).filter(Boolean);if(m.length>0){let{ObjectId:f}=await import("mongodb"),w=await this.options.db.collection("agent_memory").find({_id:{$in:m.map(S=>new f(S))}}).toArray();for(let S of w){let _=String(S.topic??"").replace(/^code:/,""),v=String(S.content??"");r.push(`- ${_}: ${v}`)}}}}}catch{}if(s.length===0&&r.length===0)return"";let o=s.slice(0,10),a=[];o.length>0&&a.push("Files actively referenced in this conversation:",...o,"Preserve references to these files and any decisions made about them.");let l=r.slice(0,10);return l.length>0&&a.push("","Code insights from prior sessions:",...l,"Preserve these insights if relevant to the conversation."),a.join(`
198
- `)}async close(){}}});var Tf={};Ue(Tf,{KnowledgeExtractor:()=>Va});import Db from"@anthropic-ai/sdk";var Lb,Va,If=j(()=>{"use strict";M();Lb=k("knowledge-extractor"),Va=class{memoryStore;memoryEmbedder;anthropic;constructor(e,t){this.memoryStore=e,this.memoryEmbedder=t,this.anthropic=new Db}async extract(e,t){if(!t?.result)return 0;let s=t.result.length>3e4?t.result.slice(0,3e4)+`
233
+ `))}}catch{}if(t)try{let s=(await this.qdrant.search("agent_memory",{vector:r,limit:15,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(a=>a.score>=this.scoreThreshold).filter(a=>typeof a.payload?.topic=="string"&&a.payload.topic.startsWith("code:"));if(s.length>0){let a=s.map(l=>l.payload?.mongoId).filter(Boolean);if(a.length>0){let l=this.options.db.collection("agent_memory"),{ObjectId:c}=await import("mongodb"),u=await l.find({_id:{$in:a.map(d=>new c(d))}}).toArray();if(u.length>0){let d=u.map(f=>`- ${String(f.topic??"").replace(/^code:/,"")}: ${String(f.content??"")}`);i.push(`**Previous session insights:**
234
+ `+d.join(`
235
+ `))}}}}catch{}return i.length===0?"":["## Codebase Context (auto-retrieved)",...i,"","_Results may be stale \u2014 verify by reading files._"].join(`
236
+ `)}extractFilePaths(e){let t=/(?:^|\s|`|"|')((src|plugins|dist|docs|scripts|setup|skills|service|agents-templates|test)\/.{1,200}\.(ts|tsx|js|jsx|json|yaml|yml|md))\b/gm,i=new Set,r;for(;(r=t.exec(e))!==null;)i.add(r[1]);return[...i]}async getCompactionContext(e,t){try{await this.ensureConnected()}catch{return""}let i=[],r=[],o=new Set;try{let c=this.extractFilePaths(e);if(c.length>0){let d=await this.options.db.collection("code_index").find({filePath:{$in:c}}).project({repo:1,filePath:1,summary:1,role:1}).toArray();for(let f of d){let p=`${f.repo}:${f.filePath}`;o.has(p)||(o.add(p),i.push(`- ${p} \u2014 ${f.summary} [${f.role}]`))}}}catch{}try{let c=e.slice(-2e3),u=await At(this.options.ollamaUrl,c),d=await this.qdrant.search(py,{vector:u,limit:this.prefetchLimit,with_payload:!0});for(let f of d){if(f.score<this.scoreThreshold)continue;let p=f.payload,h=`${p.repo}:${p.filePath}`;o.has(h)||(o.add(h),i.push(`- ${h} \u2014 ${p.summary} [${p.role}]`))}if(t){let p=(await this.qdrant.search("agent_memory",{vector:u,limit:10,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(h=>h.score>=this.scoreThreshold).filter(h=>typeof h.payload?.topic=="string"&&h.payload.topic.startsWith("code:"));if(p.length>0){let h=p.map(m=>m.payload?.mongoId).filter(Boolean);if(h.length>0){let{ObjectId:m}=await import("mongodb"),_=await this.options.db.collection("agent_memory").find({_id:{$in:h.map(b=>new m(b))}}).toArray();for(let b of _){let k=String(b.topic??"").replace(/^code:/,""),O=String(b.content??"");r.push(`- ${k}: ${O}`)}}}}}catch{}if(i.length===0&&r.length===0)return"";let s=i.slice(0,10),a=[];s.length>0&&a.push("Files actively referenced in this conversation:",...s,"Preserve references to these files and any decisions made about them.");let l=r.slice(0,10);return l.length>0&&a.push("","Code insights from prior sessions:",...l,"Preserve these insights if relevant to the conversation."),a.join(`
237
+ `)}async close(){}}});var RI={};we(RI,{KnowledgeExtractor:()=>hy});import UL from"@anthropic-ai/sdk";var RL,hy,BI=S(()=>{"use strict";R();RL=$("knowledge-extractor"),hy=class{memoryStore;memoryEmbedder;anthropic;constructor(e,t){this.memoryStore=e,this.memoryEmbedder=t,this.anthropic=new UL}async extract(e,t){if(!t?.result)return 0;let i=t.result.length>3e4?t.result.slice(0,3e4)+`
199
238
  [...truncated]`:t.result,r=await this.anthropic.messages.create({model:"claude-haiku-4-5-20251001",max_tokens:4096,messages:[{role:"user",content:`Extract code insights from this completed coding session. For each source file the session read or modified, note:
200
239
  - filePath: the relative file path
201
240
  - repo: which repository this file belongs to, inferred from the working directory or file paths
@@ -205,74 +244,74 @@ ${t.textContent}
205
244
  Return a JSON array. Only include files where the session gained meaningful understanding \u2014 skip trivial reads (package.json, tsconfig, etc). Only JSON, no other text.
206
245
 
207
246
  Session output:
208
- ${s}`}]}),o=(r.content[0].type==="text"?r.content[0].text:"").match(/\[[\s\S]*\]/);if(!o)return 0;let a;try{a=JSON.parse(o[0])}catch{return 0}let l=0;for(let c of a){if(!c.filePath||!c.insight)continue;let d=`code:${c.repo??"unknown"}:${c.filePath}`;try{let u=this.memoryStore.getCollection(),h=await u.find({agentId:e,topic:d,pinned:{$ne:!0}}).toArray();for(let y of h)y.qdrantPointId&&await this.memoryEmbedder.remove(y.qdrantPointId).catch(()=>{});h.length>0&&await u.deleteMany({_id:{$in:h.map(y=>y._id)}});let p={content:c.insight,type:"fact",topic:d,importance:c.wasModified?"high":"medium"},m=crypto.randomUUID(),f=await this.memoryStore.save(e,p,m);await this.memoryEmbedder.upsert(m,c.insight,{agentId:e,mongoId:f._id.toString(),type:"fact",topic:d,tier:"hot",importance:p.importance,createdAt:Date.now()}),l++}catch(u){Lb.error("Failed to save insight",{topic:d,error:String(u)})}}return l}}});function Af(n,e){let t=[n,e].sort();return`dm:${t[0]}:${t[1]}`}var Cf=j(()=>{"use strict"});var Ef={};Ue(Ef,{TeamStore:()=>Ja});import{ObjectId as Pb}from"mongodb";var Ya,Ja,Nf=j(()=>{"use strict";M();Cf();Ya=k("team-store"),Ja=class{db;channels;messages;constructor(e){this.db=e}async init(){this.channels=this.db.collection("team_channels"),this.messages=this.db.collection("team_messages"),await this.channels.createIndex({type:1}),await this.channels.createIndex({members:1}),await this.messages.createIndex({channelId:1,createdAt:-1}),await this.messages.createIndex({threadId:1}),await this.messages.createIndex({createdAt:-1}),Ya.info("Team store connected",{db:this.db.databaseName})}async getChannel(e){return this.channels.findOne({_id:e,archived:{$ne:!0}})}async listChannels(e){let t={archived:{$ne:!0}};return e&&(t.members=e),this.channels.find(t).sort({updatedAt:-1}).toArray()}async createChannel(e){return await this.channels.insertOne(e),Ya.info("Channel created",{id:e._id,type:e.type}),e}async getOrCreateDm(e,t,s){let r=Af(e,t),i=await this.channels.findOne({_id:r});if(i)return i;let o={_id:r,type:"dm",name:s?`DM with ${s}`:`DM: ${e} & ${t}`,members:[e,t].sort(),createdBy:e,createdAt:new Date,updatedAt:new Date,archived:!1};return await this.channels.insertOne(o),Ya.info("DM created",{id:r,members:o.members}),o}async joinChannel(e,t){return(await this.channels.updateOne({_id:e,archived:{$ne:!0}},{$addToSet:{members:t},$set:{updatedAt:new Date}})).modifiedCount>0}async leaveChannel(e,t){return(await this.channels.updateOne({_id:e},{$pull:{members:t},$set:{updatedAt:new Date}})).modifiedCount>0}async archiveChannel(e){return(await this.channels.updateOne({_id:e},{$set:{archived:!0,updatedAt:new Date}})).modifiedCount>0}async renameChannel(e,t){return(await this.channels.updateOne({_id:e},{$set:{name:t,updatedAt:new Date}})).modifiedCount>0}async saveMessage(e){let t={...e,_id:new Pb().toHexString()};return await this.messages.insertOne(t),await this.channels.updateOne({_id:e.channelId},{$set:{updatedAt:new Date}}),t}async getHistory(e,t){let s=Math.min(t?.limit??50,100),r={channelId:e};t?.before&&(r._id={$lt:t.before}),t?.threadId&&(r.threadId=t.threadId);let i=await this.messages.find(r).sort({createdAt:-1}).limit(s+1).toArray(),o=i.length>s;return o&&i.pop(),{messages:i.reverse(),hasMore:o}}}});var xf={};Ue(xf,{CommandRegistry:()=>Qa});var za,Qa,Of=j(()=>{"use strict";M();za=k("command-registry"),Qa=class{teamStore;resolveAgent;commands=new Map;constructor(e,t){this.teamStore=e,this.resolveAgent=t,this.registerCoreCommands()}register(e){this.commands.has(e.def.name)&&za.warn("Command already registered, overwriting",{name:e.def.name}),this.commands.set(e.def.name,e),za.info("Command registered",{name:e.def.name,source:e.def.source})}get(e){return this.commands.get(e)}has(e){return this.commands.has(e)}list(){return[...this.commands.values()].map(e=>e.def)}async execute(e,t){let s=this.commands.get(e);if(!s)return{found:!1};try{return{found:!0,result:await s.execute(t)}}catch(r){return za.error("Command execution failed",{name:e,error:String(r)}),{found:!0,result:`Command failed: ${String(r)}`}}}registerCoreCommands(){this.register({def:{name:"help",source:"core",description:"List available commands"},execute:async()=>`Available commands:
209
- ${this.list().map(s=>` /${s.name} \u2014 ${s.description}`).join(`
210
- `)}`}),this.register({def:{name:"dm",source:"core",description:"Open or create a DM with an agent",args:[{name:"agent",required:!0,description:"Agent id or display name"}]},execute:async e=>{let t=e.args[0];if(!t)return"Usage: /dm <agent-id-or-name>";let s=this.resolveAgent(t);return s?`DM ready: ${(await this.teamStore.getOrCreateDm(e.senderId,s.id,e.senderName))._id}`:`Unknown agent: ${t}`}}),this.register({def:{name:"rename",source:"core",description:"Rename the current channel or thread",args:[{name:"name",required:!0,description:"New name"}]},execute:async e=>{let t=e.args.join(" ");return t?await this.teamStore.renameChannel(e.channelId,t)?`Renamed to "${t}"`:"Channel not found":"Usage: /rename <new name>"}}),this.register({def:{name:"members",source:"core",description:"List members of the current channel"},execute:async e=>{let t=await this.teamStore.getChannel(e.channelId);return t?`Members of ${t.name}:
211
- ${t.members.map(s=>` - ${s}`).join(`
212
- `)}`:"Channel not found"}})}}});var Ve=T((SN,Lf)=>{"use strict";var Mf=["nodebuffer","arraybuffer","fragments"],Df=typeof Blob<"u";Df&&Mf.push("blob");Lf.exports={BINARY_TYPES:Mf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Df,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Zs=T((kN,di)=>{"use strict";var{EMPTY_BUFFER:$b}=Ve(),Xa=Buffer[Symbol.species];function Rb(n,e){if(n.length===0)return $b;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),s=0;for(let r=0;r<n.length;r++){let i=n[r];t.set(i,s),s+=i.length}return s<e?new Xa(t.buffer,t.byteOffset,s):t}function Pf(n,e,t,s,r){for(let i=0;i<r;i++)t[s+i]=n[i]^e[i&3]}function $f(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Bb(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Za(n){if(Za.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Xa(n):ArrayBuffer.isView(n)?e=new Xa(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Za.readOnly=!1),e}di.exports={concat:Rb,mask:Pf,toArrayBuffer:Bb,toBuffer:Za,unmask:$f};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=H("bufferutil");di.exports.mask=function(e,t,s,r,i){i<48?Pf(e,t,s,r,i):n.mask(e,t,s,r,i)},di.exports.unmask=function(e,t){e.length<32?$f(e,t):n.unmask(e,t)}}catch{}});var Uf=T((bN,Bf)=>{"use strict";var Rf=Symbol("kDone"),ec=Symbol("kRun"),tc=class{constructor(e){this[Rf]=()=>{this.pending--,this[ec]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ec]()}[ec](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Rf])}}};Bf.exports=tc});var es=T((_N,Kf)=>{"use strict";var en=H("zlib"),jf=Zs(),Ub=Uf(),{kStatusCode:qf}=Ve(),jb=Buffer[Symbol.species],qb=Buffer.from([0,0,255,255]),hi=Symbol("permessage-deflate"),Ye=Symbol("total-length"),Xt=Symbol("callback"),ft=Symbol("buffers"),Zt=Symbol("error"),ui,sc=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ui){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ui=new Ub(t)}}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[Xt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,s=e.find(r=>!(t.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>r.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(s=>{let r=t[s];if(r.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(r=r[0],s==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else if(s==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else throw new Error(`Unknown parameter "${s}"`);t[s]=r})}),e}decompress(e,t,s){ui.add(r=>{this._decompress(e,t,(i,o)=>{r(),s(i,o)})})}compress(e,t,s){ui.add(r=>{this._compress(e,t,(i,o)=>{r(),s(i,o)})})}_decompress(e,t,s){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=en.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[hi]=this,this._inflate[Ye]=0,this._inflate[ft]=[],this._inflate.on("error",Kb),this._inflate.on("data",Ff)}this._inflate[Xt]=s,this._inflate.write(e),t&&this._inflate.write(qb),this._inflate.flush(()=>{let i=this._inflate[Zt];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=jf.concat(this._inflate[ft],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[ft]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,t,s){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=en.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ye]=0,this._deflate[ft]=[],this._deflate.on("data",Fb)}this._deflate[Xt]=s,this._deflate.write(e),this._deflate.flush(en.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=jf.concat(this._deflate[ft],this._deflate[Ye]);t&&(i=new jb(i.buffer,i.byteOffset,i.length-4)),this._deflate[Xt]=null,this._deflate[Ye]=0,this._deflate[ft]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Kf.exports=sc;function Fb(n){this[ft].push(n),this[Ye]+=n.length}function Ff(n){if(this[Ye]+=n.length,this[hi]._maxPayload<1||this[Ye]<=this[hi]._maxPayload){this[ft].push(n);return}this[Zt]=new RangeError("Max payload size exceeded"),this[Zt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zt][qf]=1009,this.removeListener("data",Ff),this.reset()}function Kb(n){if(this[hi]._inflate=null,this[Zt]){this[Xt](this[Zt]);return}n[qf]=1007,this[Xt](n)}});var ts=T((vN,fi)=>{"use strict";var{isUtf8:Hf}=H("buffer"),{hasBlob:Hb}=Ve(),Wb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Gb(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function nc(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function Vb(n){return Hb&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}fi.exports={isBlob:Vb,isValidStatusCode:Gb,isValidUTF8:nc,tokenChars:Wb};if(Hf)fi.exports.isValidUTF8=function(n){return n.length<24?nc(n):Hf(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=H("utf-8-validate");fi.exports.isValidUTF8=function(e){return e.length<32?nc(e):n(e)}}catch{}});var cc=T((TN,Qf)=>{"use strict";var{Writable:Yb}=H("stream"),Wf=es(),{BINARY_TYPES:Jb,EMPTY_BUFFER:Gf,kStatusCode:zb,kWebSocket:Qb}=Ve(),{concat:rc,toArrayBuffer:Xb,unmask:Zb}=Zs(),{isValidStatusCode:e_,isValidUTF8:Vf}=ts(),pi=Buffer[Symbol.species],_e=0,Yf=1,Jf=2,zf=3,ic=4,oc=5,mi=6,ac=class extends Yb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Jb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Qb]=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=_e}_write(e,t,s){if(this._opcode===8&&this._state==_e)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new pi(s.buffer,s.byteOffset+e,s.length-e),new pi(s.buffer,s.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=t.length-e;e>=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new pi(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case _e:this.getInfo(e);break;case Yf:this.getPayloadLength16(e);break;case Jf:this.getPayloadLength64(e);break;case zf:this.getMask();break;case ic:this.getData(e);break;case oc:case mi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let s=(t[0]&64)===64;if(s&&!this._extensions[Wf.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=Yf:this._payloadLength===127?this._state=Jf: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 t=this.consume(8),s=t.readUInt32BE(0);if(s>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=s*Math.pow(2,32)+t.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 t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=zf:this._state=ic}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ic}getData(e){let t=Gf;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Zb(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=oc,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Wf.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return t(r);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===_e&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=_e;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=rc(s,t):this._binaryType==="arraybuffer"?r=Xb(rc(s,t)):this._binaryType==="blob"?r=new Blob(s):r=s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=_e):(this._state=mi,setImmediate(()=>{this.emit("message",r,!0),this._state=_e,this.startLoop(e)}))}else{let r=rc(s,t);if(!this._skipUTF8Validation&&!Vf(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===oc||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=_e):(this._state=mi,setImmediate(()=>{this.emit("message",r,!1),this._state=_e,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gf),this.end();else{let s=e.readUInt16BE(0);if(!e_(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let r=new pi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Vf(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=_e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_e):(this._state=mi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_e,this.startLoop(t)}))}createError(e,t,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[zb]=r,o}};Qf.exports=ac});var uc=T((AN,ep)=>{"use strict";var{Duplex:IN}=H("stream"),{randomFillSync:t_}=H("crypto"),Xf=es(),{EMPTY_BUFFER:s_,kWebSocket:n_,NOOP:r_}=Ve(),{isBlob:ss,isValidStatusCode:i_}=ts(),{mask:Zf,toBuffer:xt}=Zs(),ve=Symbol("kByteLength"),o_=Buffer.alloc(4),gi=8*1024,Ot,ns=gi,De=0,a_=1,c_=2,lc=class n{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=De,this.onerror=r_,this[n_]=void 0}static frame(e,t){let s,r=!1,i=2,o=!1;t.mask&&(s=t.maskBuffer||o_,t.generateMask?t.generateMask(s):(ns===gi&&(Ot===void 0&&(Ot=Buffer.alloc(gi)),t_(Ot,0,gi),ns=0),s[0]=Ot[ns++],s[1]=Ot[ns++],s[2]=Ot[ns++],s[3]=Ot[ns++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[ve]!==void 0?a=t[ve]:(e=Buffer.from(e),a=e.length):(a=e.length,r=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(r?a+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[i-4]=s[0],c[i-3]=s[1],c[i-2]=s[2],c[i-1]=s[3],o?[c,e]:r?(Zf(e,s,c,i,a),[c]):(Zf(e,s,e,0,a),[c,e])):[c,e]}close(e,t,s,r){let i;if(e===void 0)i=s_;else{if(typeof e!="number"||!i_(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[ve]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==De?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(n.frame(i,o),r)}ping(e,t,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):ss(e)?(r=e.size,i=!1):(e=xt(e),r=e.length,i=xt.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ss(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==De?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(n.frame(e,o),s)}pong(e,t,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):ss(e)?(r=e.size,i=!1):(e=xt(e),r=e.length,i=xt.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ss(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==De?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(n.frame(e,o),s)}send(e,t,s){let r=this._extensions[Xf.extensionName],i=t.binary?2:1,o=t.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ss(e)?(a=e.size,l=!1):(e=xt(e),a=e.length,l=xt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[ve]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};ss(e)?this._state!==De?this.enqueue([this.getBlobData,e,this._compress,c,s]):this.getBlobData(e,this._compress,c,s):this._state!==De?this.enqueue([this.dispatch,e,this._compress,c,s]):this.dispatch(e,this._compress,c,s)}getBlobData(e,t,s,r){this._bufferedBytes+=s[ve],this._state=c_,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(dc,this,a,r);return}this._bufferedBytes-=s[ve];let o=xt(i);t?this.dispatch(o,t,s,r):(this._state=De,this.sendFrame(n.frame(o,s),r),this.dequeue())}).catch(i=>{process.nextTick(l_,this,i,r)})}dispatch(e,t,s,r){if(!t){this.sendFrame(n.frame(e,s),r);return}let i=this._extensions[Xf.extensionName];this._bufferedBytes+=s[ve],this._state=a_,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");dc(this,l,r);return}this._bufferedBytes-=s[ve],this._state=De,s.readOnly=!1,this.sendFrame(n.frame(a,s),r),this.dequeue()})}dequeue(){for(;this._state===De&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ve],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ve],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};ep.exports=lc;function dc(n,e,t){typeof t=="function"&&t(e);for(let s=0;s<n._queue.length;s++){let r=n._queue[s],i=r[r.length-1];typeof i=="function"&&i(e)}}function l_(n,e,t){dc(n,e,t),n.onerror(e)}});var lp=T((CN,cp)=>{"use strict";var{kForOnEventAttribute:tn,kListener:hc}=Ve(),tp=Symbol("kCode"),sp=Symbol("kData"),np=Symbol("kError"),rp=Symbol("kMessage"),ip=Symbol("kReason"),rs=Symbol("kTarget"),op=Symbol("kType"),ap=Symbol("kWasClean"),Je=class{constructor(e){this[rs]=null,this[op]=e}get target(){return this[rs]}get type(){return this[op]}};Object.defineProperty(Je.prototype,"target",{enumerable:!0});Object.defineProperty(Je.prototype,"type",{enumerable:!0});var Mt=class extends Je{constructor(e,t={}){super(e),this[tp]=t.code===void 0?0:t.code,this[ip]=t.reason===void 0?"":t.reason,this[ap]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[tp]}get reason(){return this[ip]}get wasClean(){return this[ap]}};Object.defineProperty(Mt.prototype,"code",{enumerable:!0});Object.defineProperty(Mt.prototype,"reason",{enumerable:!0});Object.defineProperty(Mt.prototype,"wasClean",{enumerable:!0});var is=class extends Je{constructor(e,t={}){super(e),this[np]=t.error===void 0?null:t.error,this[rp]=t.message===void 0?"":t.message}get error(){return this[np]}get message(){return this[rp]}};Object.defineProperty(is.prototype,"error",{enumerable:!0});Object.defineProperty(is.prototype,"message",{enumerable:!0});var sn=class extends Je{constructor(e,t={}){super(e),this[sp]=t.data===void 0?null:t.data}get data(){return this[sp]}};Object.defineProperty(sn.prototype,"data",{enumerable:!0});var d_={addEventListener(n,e,t={}){for(let r of this.listeners(n))if(!t[tn]&&r[hc]===e&&!r[tn])return;let s;if(n==="message")s=function(i,o){let a=new sn("message",{data:o?i:i.toString()});a[rs]=this,yi(e,this,a)};else if(n==="close")s=function(i,o){let a=new Mt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[rs]=this,yi(e,this,a)};else if(n==="error")s=function(i){let o=new is("error",{error:i,message:i.message});o[rs]=this,yi(e,this,o)};else if(n==="open")s=function(){let i=new Je("open");i[rs]=this,yi(e,this,i)};else return;s[tn]=!!t[tn],s[hc]=e,t.once?this.once(n,s):this.on(n,s)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[hc]===e&&!t[tn]){this.removeListener(n,t);break}}};cp.exports={CloseEvent:Mt,ErrorEvent:is,Event:Je,EventTarget:d_,MessageEvent:sn};function yi(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var wi=T((EN,dp)=>{"use strict";var{tokenChars:nn}=ts();function $e(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function u_(n){let e=Object.create(null),t=Object.create(null),s=!1,r=!1,i=!1,o,a,l=-1,c=-1,d=-1,u=0;for(;u<n.length;u++)if(c=n.charCodeAt(u),o===void 0)if(d===-1&&nn[c]===1)l===-1&&(l=u);else if(u!==0&&(c===32||c===9))d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(l,d);c===44?($e(e,p,t),t=Object.create(null)):o=p,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&nn[c]===1)l===-1&&(l=u);else if(c===32||c===9)d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),$e(t,n.slice(l,d),!0),c===44&&($e(e,o,t),t=Object.create(null),o=void 0),l=d=-1}else if(c===61&&l!==-1&&d===-1)a=n.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(r){if(nn[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:s||(s=!0),r=!1}else if(i)if(nn[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)i=!1,d=u;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&n.charCodeAt(u-1)===61)i=!0;else if(d===-1&&nn[c]===1)l===-1&&(l=u);else if(l!==-1&&(c===32||c===9))d===-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(l,d);s&&(p=p.replace(/\\/g,""),s=!1),$e(t,a,p),c===44&&($e(e,o,t),t=Object.create(null),o=void 0),a=void 0,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let h=n.slice(l,d);return o===void 0?$e(e,h,t):(a===void 0?$e(t,h,!0):s?$e(t,a,h.replace(/\\/g,"")):$e(t,a,h),$e(e,o,t)),e}function h_(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(s=>[e].concat(Object.keys(s).map(r=>{let i=s[r];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?r:`${r}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}dp.exports={format:h_,parse:u_}});var _i=T((ON,_p)=>{"use strict";var f_=H("events"),p_=H("https"),m_=H("http"),fp=H("net"),g_=H("tls"),{randomBytes:y_,createHash:w_}=H("crypto"),{Duplex:NN,Readable:xN}=H("stream"),{URL:fc}=H("url"),pt=es(),S_=cc(),k_=uc(),{isBlob:b_}=ts(),{BINARY_TYPES:up,CLOSE_TIMEOUT:__,EMPTY_BUFFER:Si,GUID:v_,kForOnEventAttribute:pc,kListener:T_,kStatusCode:I_,kWebSocket:ie,NOOP:pp}=Ve(),{EventTarget:{addEventListener:A_,removeEventListener:C_}}=lp(),{format:E_,parse:N_}=wi(),{toBuffer:x_}=Zs(),mp=Symbol("kAborted"),mc=[8,13],ze=["CONNECTING","OPEN","CLOSING","CLOSED"],O_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,z=class n extends f_{constructor(e,t,s){super(),this._binaryType=up[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Si,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(s=t,t=[]):t=[t]),gp(this,e,t,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){up.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,t,s){let r=new S_({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new k_(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[ie]=this,i[ie]=this,e[ie]=this,r.on("conclude",L_),r.on("drain",P_),r.on("error",$_),r.on("message",R_),r.on("ping",B_),r.on("pong",U_),i.onerror=j_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Sp),e.on("data",bi),e.on("end",kp),e.on("error",bp),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),wp(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=t=void 0):typeof t=="function"&&(s=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){gc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Si,t,s)}pong(e,t,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=t=void 0):typeof t=="function"&&(s=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){gc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Si,t,s)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(s=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){gc(this,e,s);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(r.compress=!1),this._sender.send(e||Si,r,s)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(z,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(z.prototype,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(z,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(z.prototype,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(z,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(z.prototype,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(z,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});Object.defineProperty(z.prototype,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(z.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(z.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[pc])return e[T_];return null},set(e){for(let t of this.listeners(n))if(t[pc]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[pc]:!0})}})});z.prototype.addEventListener=A_;z.prototype.removeEventListener=C_;_p.exports=z;function gp(n,e,t,s){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:__,protocolVersion:mc[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=r.autoPong,n._closeTimeout=r.closeTimeout,!mc.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${mc.join(", ")})`);let i;if(e instanceof fc)i=e;else try{i=new fc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let f=new SyntaxError(l);if(n._redirects===0)throw f;ki(n,f);return}let c=o?443:80,d=y_(16).toString("base64"),u=o?p_.request:m_.request,h=new Set,p;if(r.createConnection=r.createConnection||(o?D_:M_),r.defaultPort=r.defaultPort||c,r.port=i.port||c,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(p=new pt({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=E_({[pt.extensionName]:p.offer()})),t.length){for(let f of t){if(typeof f!="string"||!O_.test(f)||h.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(f)}r.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let f=r.path.split(":");r.socketPath=f[0],r.path=f[1]}let m;if(r.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?r.socketPath:i.host;let f=s&&s.headers;if(s={...s,headers:{}},f)for(let[y,w]of Object.entries(f))s.headers[y.toLowerCase()]=w}else if(n.listenerCount("redirect")===0){let f=a?n._originalIpc?r.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!f||n._originalSecure&&!o)&&(delete r.headers.authorization,delete r.headers.cookie,f||delete r.headers.host,r.auth=void 0)}r.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),m=n._req=u(r),n._redirects&&n.emit("redirect",n.url,m)}else m=n._req=u(r);r.timeout&&m.on("timeout",()=>{Se(n,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[mp]||(m=n._req=null,ki(n,f))}),m.on("response",f=>{let y=f.headers.location,w=f.statusCode;if(y&&r.followRedirects&&w>=300&&w<400){if(++n._redirects>r.maxRedirects){Se(n,m,"Maximum redirects exceeded");return}m.abort();let S;try{S=new fc(y,e)}catch{let v=new SyntaxError(`Invalid URL: ${y}`);ki(n,v);return}gp(n,S,t,s)}else n.emit("unexpected-response",m,f)||Se(n,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,y,w)=>{if(n.emit("upgrade",f),n.readyState!==z.CONNECTING)return;m=n._req=null;let S=f.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){Se(n,y,"Invalid Upgrade header");return}let _=w_("sha1").update(d+v_).digest("base64");if(f.headers["sec-websocket-accept"]!==_){Se(n,y,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],I;if(v!==void 0?h.size?h.has(v)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":h.size&&(I="Server sent no subprotocol"),I){Se(n,y,I);return}v&&(n._protocol=v);let N=f.headers["sec-websocket-extensions"];if(N!==void 0){if(!p){Se(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let D;try{D=N_(N)}catch{Se(n,y,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(D);if(A.length!==1||A[0]!==pt.extensionName){Se(n,y,"Server indicated an extension that was not requested");return}try{p.accept(D[pt.extensionName])}catch{Se(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[pt.extensionName]=p}n.setSocket(y,w,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(m,n):m.end()}function ki(n,e){n._readyState=z.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function M_(n){return n.path=n.socketPath,fp.connect(n)}function D_(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=fp.isIP(n.host)?"":n.host),g_.connect(n)}function Se(n,e,t){n._readyState=z.CLOSING;let s=new Error(t);Error.captureStackTrace(s,Se),e.setHeader?(e[mp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ki,n,s)):(e.destroy(s),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function gc(n,e,t){if(e){let s=b_(e)?e.size:x_(e).length;n._socket?n._sender._bufferedBytes+=s:n._bufferedAmount+=s}if(t){let s=new Error(`WebSocket is not open: readyState ${n.readyState} (${ze[n.readyState]})`);process.nextTick(t,s)}}function L_(n,e){let t=this[ie];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ie]!==void 0&&(t._socket.removeListener("data",bi),process.nextTick(yp,t._socket),n===1005?t.close():t.close(n,e))}function P_(){let n=this[ie];n.isPaused||n._socket.resume()}function $_(n){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",bi),process.nextTick(yp,e._socket),e.close(n[I_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function hp(){this[ie].emitClose()}function R_(n,e){this[ie].emit("message",n,e)}function B_(n){let e=this[ie];e._autoPong&&e.pong(n,!this._isServer,pp),e.emit("ping",n)}function U_(n){this[ie].emit("pong",n)}function yp(n){n.resume()}function j_(n){let e=this[ie];e.readyState!==z.CLOSED&&(e.readyState===z.OPEN&&(e._readyState=z.CLOSING,wp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function wp(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Sp(){let n=this[ie];if(this.removeListener("close",Sp),this.removeListener("data",bi),this.removeListener("end",kp),n._readyState=z.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ie]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",hp),n._receiver.on("finish",hp))}function bi(n){this[ie]._receiver.write(n)||this.pause()}function kp(){let n=this[ie];n._readyState=z.CLOSING,n._receiver.end(),this.end()}function bp(){let n=this[ie];this.removeListener("error",bp),this.on("error",pp),n&&(n._readyState=z.CLOSING,this.destroy())}});var Ap=T((DN,Ip)=>{"use strict";var MN=_i(),{Duplex:q_}=H("stream");function vp(n){n.emit("close")}function F_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Tp(n){this.removeListener("error",Tp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function K_(n,e){let t=!0,s=new q_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||n.pause()}),n.once("error",function(i){s.destroyed||(t=!1,s.destroy(i))}),n.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(r,i){if(n.readyState===n.CLOSED){i(r),process.nextTick(vp,s);return}let o=!1;n.once("error",function(l){o=!0,i(l)}),n.once("close",function(){o||i(r),process.nextTick(vp,s)}),t&&n.terminate()},s._final=function(r){if(n.readyState===n.CONNECTING){n.once("open",function(){s._final(r)});return}n._socket!==null&&(n._socket._writableState.finished?(r(),s._readableState.endEmitted&&s.destroy()):(n._socket.once("finish",function(){r()}),n.close()))},s._read=function(){n.isPaused&&n.resume()},s._write=function(r,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){s._write(r,i,o)});return}n.send(r,o)},s.on("end",F_),s.on("error",Tp),s}Ip.exports=K_});var yc=T((LN,Cp)=>{"use strict";var{tokenChars:H_}=ts();function W_(n){let e=new Set,t=-1,s=-1,r=0;for(r;r<n.length;r++){let o=n.charCodeAt(r);if(s===-1&&H_[o]===1)t===-1&&(t=r);else if(r!==0&&(o===32||o===9))s===-1&&t!==-1&&(s=r);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${r}`);s===-1&&(s=r);let a=n.slice(t,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=s=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(t===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Cp.exports={parse:W_}});var Lp=T(($N,Dp)=>{"use strict";var G_=H("events"),vi=H("http"),{Duplex:PN}=H("stream"),{createHash:V_}=H("crypto"),Ep=wi(),Dt=es(),Y_=yc(),J_=_i(),{CLOSE_TIMEOUT:z_,GUID:Q_,kWebSocket:X_}=Ve(),Z_=/^[+/0-9A-Za-z]{22}==$/,Np=0,xp=1,Mp=2,wc=class extends G_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:z_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:J_,...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=vi.createServer((s,r)=>{let i=vi.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=ev(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,o)=>{this.handleUpgrade(r,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Np}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===Mp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(rn,this);return}if(e&&this.once("close",e),this._state!==xp)if(this._state=xp,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(rn,this):process.nextTick(rn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{rn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,r){t.on("error",Op);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Lt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Lt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Z_.test(i)){Lt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Lt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){on(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Y_.parse(l)}catch{Lt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let h=new Dt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Ep.parse(d);p[Dt.extensionName]&&(h.accept(p[Dt.extensionName]),u[Dt.extensionName]=h)}catch{Lt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={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(h,(p,m,f,y)=>{if(!p)return on(t,m||401,f,y);this.completeUpgrade(u,i,c,e,t,s,r)});return}if(!this.options.verifyClient(h))return on(t,401)}this.completeUpgrade(u,i,c,e,t,s,r)}completeUpgrade(e,t,s,r,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[X_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Np)return on(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${V_("sha1").update(t+Q_).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(s.size){let u=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Dt.extensionName]){let u=e[Dt.extensionName].params,h=Ep.format({[Dt.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",c,r),i.write(c.concat(`\r
247
+ ${i}`}]}),s=(r.content[0].type==="text"?r.content[0].text:"").match(/\[[\s\S]*\]/);if(!s)return 0;let a;try{a=JSON.parse(s[0])}catch{return 0}let l=0;for(let c of a){if(!c.filePath||!c.insight)continue;let u=`code:${c.repo??"unknown"}:${c.filePath}`;try{let d=this.memoryStore.getCollection(),f=await d.find({agentId:e,topic:u,pinned:{$ne:!0}}).toArray();for(let y of f)y.qdrantPointId&&await this.memoryEmbedder.remove(y.qdrantPointId).catch(()=>{});f.length>0&&await d.deleteMany({_id:{$in:f.map(y=>y._id)}});let p={content:c.insight,type:"fact",topic:u,importance:c.wasModified?"high":"medium"},h=crypto.randomUUID(),m=await this.memoryStore.save(e,p,h);await this.memoryEmbedder.upsert(h,c.insight,{agentId:e,mongoId:m._id.toString(),type:"fact",topic:u,tier:"hot",importance:p.importance,createdAt:Date.now()}),l++}catch(d){RL.error("Failed to save insight",{topic:u,error:String(d)})}}return l}}});function FI(n,e){let t=[n,e].sort();return`dm:${t[0]}:${t[1]}`}var qI=S(()=>{"use strict"});var ZI={};we(ZI,{TeamStore:()=>yy});import{ObjectId as BL}from"mongodb";var gy,yy,KI=S(()=>{"use strict";R();qI();gy=$("team-store"),yy=class{db;channels;messages;constructor(e){this.db=e}async init(){this.channels=this.db.collection("team_channels"),this.messages=this.db.collection("team_messages"),await this.channels.createIndex({type:1}),await this.channels.createIndex({members:1}),await this.messages.createIndex({channelId:1,createdAt:-1}),await this.messages.createIndex({threadId:1}),await this.messages.createIndex({createdAt:-1}),gy.info("Team store connected",{db:this.db.databaseName})}async getChannel(e){return this.channels.findOne({_id:e,archived:{$ne:!0}})}async listChannels(e){let t={archived:{$ne:!0}};return e&&(t.members=e),this.channels.find(t).sort({updatedAt:-1}).toArray()}async createChannel(e){return await this.channels.insertOne(e),gy.info("Channel created",{id:e._id,type:e.type}),e}async getOrCreateDm(e,t,i){let r=FI(e,t),o=await this.channels.findOne({_id:r});if(o)return o;let s={_id:r,type:"dm",name:i?`DM with ${i}`:`DM: ${e} & ${t}`,members:[e,t].sort(),createdBy:e,createdAt:new Date,updatedAt:new Date,archived:!1};return await this.channels.insertOne(s),gy.info("DM created",{id:r,members:s.members}),s}async joinChannel(e,t){return(await this.channels.updateOne({_id:e,archived:{$ne:!0}},{$addToSet:{members:t},$set:{updatedAt:new Date}})).modifiedCount>0}async leaveChannel(e,t){return(await this.channels.updateOne({_id:e},{$pull:{members:t},$set:{updatedAt:new Date}})).modifiedCount>0}async archiveChannel(e){return(await this.channels.updateOne({_id:e},{$set:{archived:!0,updatedAt:new Date}})).modifiedCount>0}async renameChannel(e,t){return(await this.channels.updateOne({_id:e},{$set:{name:t,updatedAt:new Date}})).modifiedCount>0}async saveMessage(e){let t={...e,_id:new BL().toHexString()};return await this.messages.insertOne(t),await this.channels.updateOne({_id:e.channelId},{$set:{updatedAt:new Date}}),t}async getHistory(e,t){let i=Math.min(t?.limit??50,100),r={channelId:e};t?.before&&(r._id={$lt:t.before}),t?.threadId&&(r.threadId=t.threadId);let o=await this.messages.find(r).sort({createdAt:-1}).limit(i+1).toArray(),s=o.length>i;return s&&o.pop(),{messages:o.reverse(),hasMore:s}}}});var VI={};we(VI,{CommandRegistry:()=>_y});var vy,_y,WI=S(()=>{"use strict";R();vy=$("command-registry"),_y=class{teamStore;resolveAgent;commands=new Map;constructor(e,t){this.teamStore=e,this.resolveAgent=t,this.registerCoreCommands()}register(e){this.commands.has(e.def.name)&&vy.warn("Command already registered, overwriting",{name:e.def.name}),this.commands.set(e.def.name,e),vy.info("Command registered",{name:e.def.name,source:e.def.source})}get(e){return this.commands.get(e)}has(e){return this.commands.has(e)}list(){return[...this.commands.values()].map(e=>e.def)}async execute(e,t){let i=this.commands.get(e);if(!i)return{found:!1};try{return{found:!0,result:await i.execute(t)}}catch(r){return vy.error("Command execution failed",{name:e,error:String(r)}),{found:!0,result:`Command failed: ${String(r)}`}}}registerCoreCommands(){this.register({def:{name:"help",source:"core",description:"List available commands"},execute:async()=>`Available commands:
248
+ ${this.list().map(i=>` /${i.name} \u2014 ${i.description}`).join(`
249
+ `)}`}),this.register({def:{name:"dm",source:"core",description:"Open or create a DM with an agent",args:[{name:"agent",required:!0,description:"Agent id or display name"}]},execute:async e=>{let t=e.args[0];if(!t)return"Usage: /dm <agent-id-or-name>";let i=this.resolveAgent(t);return i?`DM ready: ${(await this.teamStore.getOrCreateDm(e.senderId,i.id,e.senderName))._id}`:`Unknown agent: ${t}`}}),this.register({def:{name:"rename",source:"core",description:"Rename the current channel or thread",args:[{name:"name",required:!0,description:"New name"}]},execute:async e=>{let t=e.args.join(" ");return t?await this.teamStore.renameChannel(e.channelId,t)?`Renamed to "${t}"`:"Channel not found":"Usage: /rename <new name>"}}),this.register({def:{name:"members",source:"core",description:"List members of the current channel"},execute:async e=>{let t=await this.teamStore.getChannel(e.channelId);return t?`Members of ${t.name}:
250
+ ${t.members.map(i=>` - ${i}`).join(`
251
+ `)}`:"Channel not found"}})}}});var Nt=N((SZ,HI)=>{"use strict";var GI=["nodebuffer","arraybuffer","fragments"],JI=typeof Blob<"u";JI&&GI.push("blob");HI.exports={BINARY_TYPES:GI,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:JI,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var bo=N(($Z,bl)=>{"use strict";var{EMPTY_BUFFER:FL}=Nt(),wy=Buffer[Symbol.species];function qL(n,e){if(n.length===0)return FL;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),i=0;for(let r=0;r<n.length;r++){let o=n[r];t.set(o,i),i+=o.length}return i<e?new wy(t.buffer,t.byteOffset,i):t}function YI(n,e,t,i,r){for(let o=0;o<r;o++)t[i+o]=n[o]^e[o&3]}function XI(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function ZL(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function by(n){if(by.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new wy(n):ArrayBuffer.isView(n)?e=new wy(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),by.readOnly=!1),e}bl.exports={concat:qL,mask:YI,toArrayBuffer:ZL,toBuffer:by,unmask:XI};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=ne("bufferutil");bl.exports.mask=function(e,t,i,r,o){o<48?YI(e,t,i,r,o):n.mask(e,t,i,r,o)},bl.exports.unmask=function(e,t){e.length<32?XI(e,t):n.unmask(e,t)}}catch{}});var t0=N((xZ,e0)=>{"use strict";var QI=Symbol("kDone"),ky=Symbol("kRun"),Sy=class{constructor(e){this[QI]=()=>{this.pending--,this[ky]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ky]()}[ky](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[QI])}}};e0.exports=Sy});var jr=N((IZ,o0)=>{"use strict";var ko=ne("zlib"),n0=bo(),KL=t0(),{kStatusCode:r0}=Nt(),VL=Buffer[Symbol.species],WL=Buffer.from([0,0,255,255]),Sl=Symbol("permessage-deflate"),Dt=Symbol("total-length"),Lr=Symbol("callback"),cn=Symbol("buffers"),zr=Symbol("error"),kl,$y=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!kl){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;kl=new KL(t)}}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[Lr];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,i=e.find(r=>!(t.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>r.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!i)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(i.server_no_context_takeover=!0),t.clientNoContextTakeover&&(i.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(i.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?i.client_max_window_bits=t.clientMaxWindowBits:(i.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete i.client_max_window_bits,i}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(i=>{let r=t[i];if(r.length>1)throw new Error(`Parameter "${i}" must have only a single value`);if(r=r[0],i==="client_max_window_bits"){if(r!==!0){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else if(i==="server_max_window_bits"){let o=+r;if(!Number.isInteger(o)||o<8||o>15)throw new TypeError(`Invalid value for parameter "${i}": ${r}`);r=o}else if(i==="client_no_context_takeover"||i==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${i}": ${r}`)}else throw new Error(`Unknown parameter "${i}"`);t[i]=r})}),e}decompress(e,t,i){kl.add(r=>{this._decompress(e,t,(o,s)=>{r(),i(o,s)})})}compress(e,t,i){kl.add(r=>{this._compress(e,t,(o,s)=>{r(),i(o,s)})})}_decompress(e,t,i){let r=this._isServer?"client":"server";if(!this._inflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?ko.Z_DEFAULT_WINDOWBITS:this.params[o];this._inflate=ko.createInflateRaw({...this._options.zlibInflateOptions,windowBits:s}),this._inflate[Sl]=this,this._inflate[Dt]=0,this._inflate[cn]=[],this._inflate.on("error",JL),this._inflate.on("data",i0)}this._inflate[Lr]=i,this._inflate.write(e),t&&this._inflate.write(WL),this._inflate.flush(()=>{let o=this._inflate[zr];if(o){this._inflate.close(),this._inflate=null,i(o);return}let s=n0.concat(this._inflate[cn],this._inflate[Dt]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Dt]=0,this._inflate[cn]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),i(null,s)})}_compress(e,t,i){let r=this._isServer?"server":"client";if(!this._deflate){let o=`${r}_max_window_bits`,s=typeof this.params[o]!="number"?ko.Z_DEFAULT_WINDOWBITS:this.params[o];this._deflate=ko.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:s}),this._deflate[Dt]=0,this._deflate[cn]=[],this._deflate.on("data",GL)}this._deflate[Lr]=i,this._deflate.write(e),this._deflate.flush(ko.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let o=n0.concat(this._deflate[cn],this._deflate[Dt]);t&&(o=new VL(o.buffer,o.byteOffset,o.length-4)),this._deflate[Lr]=null,this._deflate[Dt]=0,this._deflate[cn]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),i(null,o)})}};o0.exports=$y;function GL(n){this[cn].push(n),this[Dt]+=n.length}function i0(n){if(this[Dt]+=n.length,this[Sl]._maxPayload<1||this[Dt]<=this[Sl]._maxPayload){this[cn].push(n);return}this[zr]=new RangeError("Max payload size exceeded"),this[zr].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[zr][r0]=1009,this.removeListener("data",i0),this.reset()}function JL(n){if(this[Sl]._inflate=null,this[zr]){this[Lr](this[zr]);return}n[r0]=1007,this[Lr](n)}});var Ur=N((TZ,$l)=>{"use strict";var{isUtf8:s0}=ne("buffer"),{hasBlob:HL}=Nt(),YL=[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 XL(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function xy(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function QL(n){return HL&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}$l.exports={isBlob:QL,isValidStatusCode:XL,isValidUTF8:xy,tokenChars:YL};if(s0)$l.exports.isValidUTF8=function(n){return n.length<24?xy(n):s0(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=ne("utf-8-validate");$l.exports.isValidUTF8=function(e){return e.length<32?xy(e):n(e)}}catch{}});var Oy=N((EZ,p0)=>{"use strict";var{Writable:ez}=ne("stream"),a0=jr(),{BINARY_TYPES:tz,EMPTY_BUFFER:c0,kStatusCode:nz,kWebSocket:rz}=Nt(),{concat:Iy,toArrayBuffer:iz,unmask:oz}=bo(),{isValidStatusCode:sz,isValidUTF8:l0}=Ur(),xl=Buffer[Symbol.species],Xe=0,u0=1,d0=2,f0=3,Ty=4,Ey=5,Il=6,Ay=class extends ez{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||tz[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[rz]=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=Xe}_write(e,t,i){if(this._opcode===8&&this._state==Xe)return i();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(i)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let i=this._buffers[0];return this._buffers[0]=new xl(i.buffer,i.byteOffset+e,i.length-e),new xl(i.buffer,i.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let i=this._buffers[0],r=t.length-e;e>=i.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(i.buffer,i.byteOffset,e),r),this._buffers[0]=new xl(i.buffer,i.byteOffset+e,i.length-e)),e-=i.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case Xe:this.getInfo(e);break;case u0:this.getPayloadLength16(e);break;case d0:this.getPayloadLength64(e);break;case f0:this.getMask();break;case Ty:this.getData(e);break;case Ey:case Il:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let i=(t[0]&64)===64;if(i&&!this._extensions[a0.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=i}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(i){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=u0:this._payloadLength===127?this._state=d0: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 t=this.consume(8),i=t.readUInt32BE(0);if(i>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=i*Math.pow(2,32)+t.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 t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=f0:this._state=Ty}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=Ty}getData(e){let t=c0;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&oz(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=Ey,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[a0.extensionName].decompress(e,this._fin,(r,o)=>{if(r)return t(r);if(o.length){if(this._messageLength+=o.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(s);return}this._fragments.push(o)}this.dataMessage(t),this._state===Xe&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=Xe;return}let t=this._messageLength,i=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=Iy(i,t):this._binaryType==="arraybuffer"?r=iz(Iy(i,t)):this._binaryType==="blob"?r=new Blob(i):r=i,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=Xe):(this._state=Il,setImmediate(()=>{this.emit("message",r,!0),this._state=Xe,this.startLoop(e)}))}else{let r=Iy(i,t);if(!this._skipUTF8Validation&&!l0(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(o);return}this._state===Ey||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=Xe):(this._state=Il,setImmediate(()=>{this.emit("message",r,!1),this._state=Xe,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,c0),this.end();else{let i=e.readUInt16BE(0);if(!sz(i)){let o=this.createError(RangeError,`invalid status code ${i}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(o);return}let r=new xl(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!l0(r)){let o=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(o);return}this._loop=!1,this.emit("conclude",i,r),this.end()}this._state=Xe;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=Xe):(this._state=Il,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=Xe,this.startLoop(t)}))}createError(e,t,i,r,o){this._loop=!1,this._errored=!0;let s=new e(i?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(s,this.createError),s.code=o,s[nz]=r,s}};p0.exports=Ay});var Dy=N((OZ,g0)=>{"use strict";var{Duplex:AZ}=ne("stream"),{randomFillSync:az}=ne("crypto"),m0=jr(),{EMPTY_BUFFER:cz,kWebSocket:lz,NOOP:uz}=Nt(),{isBlob:Rr,isValidStatusCode:dz}=Ur(),{mask:h0,toBuffer:Mn}=bo(),Qe=Symbol("kByteLength"),fz=Buffer.alloc(4),Tl=8*1024,Ln,Br=Tl,dt=0,pz=1,mz=2,Cy=class n{constructor(e,t,i){this._extensions=t||{},i&&(this._generateMask=i,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=dt,this.onerror=uz,this[lz]=void 0}static frame(e,t){let i,r=!1,o=2,s=!1;t.mask&&(i=t.maskBuffer||fz,t.generateMask?t.generateMask(i):(Br===Tl&&(Ln===void 0&&(Ln=Buffer.alloc(Tl)),az(Ln,0,Tl),Br=0),i[0]=Ln[Br++],i[1]=Ln[Br++],i[2]=Ln[Br++],i[3]=Ln[Br++]),s=(i[0]|i[1]|i[2]|i[3])===0,o=6);let a;typeof e=="string"?(!t.mask||s)&&t[Qe]!==void 0?a=t[Qe]:(e=Buffer.from(e),a=e.length):(a=e.length,r=t.mask&&t.readOnly&&!s);let l=a;a>=65536?(o+=8,l=127):a>125&&(o+=2,l=126);let c=Buffer.allocUnsafe(r?a+o:o);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[o-4]=i[0],c[o-3]=i[1],c[o-2]=i[2],c[o-1]=i[3],s?[c,e]:r?(h0(e,i,c,o,a),[c]):(h0(e,i,e,0,a),[c,e])):[c,e]}close(e,t,i,r){let o;if(e===void 0)o=cz;else{if(typeof e!="number"||!dz(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)o=Buffer.allocUnsafe(2),o.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");o=Buffer.allocUnsafe(2+a),o.writeUInt16BE(e,0),typeof t=="string"?o.write(t,2):o.set(t,2)}}let s={[Qe]:o.length,fin:!0,generateMask:this._generateMask,mask:i,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==dt?this.enqueue([this.dispatch,o,!1,s,r]):this.sendFrame(n.frame(o,s),r)}ping(e,t,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):Rr(e)?(r=e.size,o=!1):(e=Mn(e),r=e.length,o=Mn.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Qe]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:o,rsv1:!1};Rr(e)?this._state!==dt?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==dt?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(n.frame(e,s),i)}pong(e,t,i){let r,o;if(typeof e=="string"?(r=Buffer.byteLength(e),o=!1):Rr(e)?(r=e.size,o=!1):(e=Mn(e),r=e.length,o=Mn.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let s={[Qe]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:o,rsv1:!1};Rr(e)?this._state!==dt?this.enqueue([this.getBlobData,e,!1,s,i]):this.getBlobData(e,!1,s,i):this._state!==dt?this.enqueue([this.dispatch,e,!1,s,i]):this.sendFrame(n.frame(e,s),i)}send(e,t,i){let r=this._extensions[m0.extensionName],o=t.binary?2:1,s=t.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):Rr(e)?(a=e.size,l=!1):(e=Mn(e),a=e.length,l=Mn.readOnly),this._firstFragment?(this._firstFragment=!1,s&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(s=a>=r._threshold),this._compress=s):(s=!1,o=0),t.fin&&(this._firstFragment=!0);let c={[Qe]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:o,readOnly:l,rsv1:s};Rr(e)?this._state!==dt?this.enqueue([this.getBlobData,e,this._compress,c,i]):this.getBlobData(e,this._compress,c,i):this._state!==dt?this.enqueue([this.dispatch,e,this._compress,c,i]):this.dispatch(e,this._compress,c,i)}getBlobData(e,t,i,r){this._bufferedBytes+=i[Qe],this._state=mz,e.arrayBuffer().then(o=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(Ny,this,a,r);return}this._bufferedBytes-=i[Qe];let s=Mn(o);t?this.dispatch(s,t,i,r):(this._state=dt,this.sendFrame(n.frame(s,i),r),this.dequeue())}).catch(o=>{process.nextTick(hz,this,o,r)})}dispatch(e,t,i,r){if(!t){this.sendFrame(n.frame(e,i),r);return}let o=this._extensions[m0.extensionName];this._bufferedBytes+=i[Qe],this._state=pz,o.compress(e,i.fin,(s,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");Ny(this,l,r);return}this._bufferedBytes-=i[Qe],this._state=dt,i.readOnly=!1,this.sendFrame(n.frame(a,i),r),this.dequeue()})}dequeue(){for(;this._state===dt&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][Qe],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][Qe],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};g0.exports=Cy;function Ny(n,e,t){typeof t=="function"&&t(e);for(let i=0;i<n._queue.length;i++){let r=n._queue[i],o=r[r.length-1];typeof o=="function"&&o(e)}}function hz(n,e,t){Ny(n,e,t),n.onerror(e)}});var x0=N((CZ,$0)=>{"use strict";var{kForOnEventAttribute:So,kListener:Py}=Nt(),y0=Symbol("kCode"),v0=Symbol("kData"),_0=Symbol("kError"),w0=Symbol("kMessage"),b0=Symbol("kReason"),Fr=Symbol("kTarget"),k0=Symbol("kType"),S0=Symbol("kWasClean"),Pt=class{constructor(e){this[Fr]=null,this[k0]=e}get target(){return this[Fr]}get type(){return this[k0]}};Object.defineProperty(Pt.prototype,"target",{enumerable:!0});Object.defineProperty(Pt.prototype,"type",{enumerable:!0});var zn=class extends Pt{constructor(e,t={}){super(e),this[y0]=t.code===void 0?0:t.code,this[b0]=t.reason===void 0?"":t.reason,this[S0]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[y0]}get reason(){return this[b0]}get wasClean(){return this[S0]}};Object.defineProperty(zn.prototype,"code",{enumerable:!0});Object.defineProperty(zn.prototype,"reason",{enumerable:!0});Object.defineProperty(zn.prototype,"wasClean",{enumerable:!0});var qr=class extends Pt{constructor(e,t={}){super(e),this[_0]=t.error===void 0?null:t.error,this[w0]=t.message===void 0?"":t.message}get error(){return this[_0]}get message(){return this[w0]}};Object.defineProperty(qr.prototype,"error",{enumerable:!0});Object.defineProperty(qr.prototype,"message",{enumerable:!0});var $o=class extends Pt{constructor(e,t={}){super(e),this[v0]=t.data===void 0?null:t.data}get data(){return this[v0]}};Object.defineProperty($o.prototype,"data",{enumerable:!0});var gz={addEventListener(n,e,t={}){for(let r of this.listeners(n))if(!t[So]&&r[Py]===e&&!r[So])return;let i;if(n==="message")i=function(o,s){let a=new $o("message",{data:s?o:o.toString()});a[Fr]=this,El(e,this,a)};else if(n==="close")i=function(o,s){let a=new zn("close",{code:o,reason:s.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[Fr]=this,El(e,this,a)};else if(n==="error")i=function(o){let s=new qr("error",{error:o,message:o.message});s[Fr]=this,El(e,this,s)};else if(n==="open")i=function(){let o=new Pt("open");o[Fr]=this,El(e,this,o)};else return;i[So]=!!t[So],i[Py]=e,t.once?this.once(n,i):this.on(n,i)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[Py]===e&&!t[So]){this.removeListener(n,t);break}}};$0.exports={CloseEvent:zn,ErrorEvent:qr,Event:Pt,EventTarget:gz,MessageEvent:$o};function El(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var Al=N((NZ,I0)=>{"use strict";var{tokenChars:xo}=Ur();function vt(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function yz(n){let e=Object.create(null),t=Object.create(null),i=!1,r=!1,o=!1,s,a,l=-1,c=-1,u=-1,d=0;for(;d<n.length;d++)if(c=n.charCodeAt(d),s===void 0)if(u===-1&&xo[c]===1)l===-1&&(l=d);else if(d!==0&&(c===32||c===9))u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=n.slice(l,u);c===44?(vt(e,p,t),t=Object.create(null)):s=p,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);else if(a===void 0)if(u===-1&&xo[c]===1)l===-1&&(l=d);else if(c===32||c===9)u===-1&&l!==-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d),vt(t,n.slice(l,u),!0),c===44&&(vt(e,s,t),t=Object.create(null),s=void 0),l=u=-1}else if(c===61&&l!==-1&&u===-1)a=n.slice(l,d),l=u=-1;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(r){if(xo[c]!==1)throw new SyntaxError(`Unexpected character at index ${d}`);l===-1?l=d:i||(i=!0),r=!1}else if(o)if(xo[c]===1)l===-1&&(l=d);else if(c===34&&l!==-1)o=!1,u=d;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${d}`);else if(c===34&&n.charCodeAt(d-1)===61)o=!0;else if(u===-1&&xo[c]===1)l===-1&&(l=d);else if(l!==-1&&(c===32||c===9))u===-1&&(u=d);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${d}`);u===-1&&(u=d);let p=n.slice(l,u);i&&(p=p.replace(/\\/g,""),i=!1),vt(t,a,p),c===44&&(vt(e,s,t),t=Object.create(null),s=void 0),a=void 0,l=u=-1}else throw new SyntaxError(`Unexpected character at index ${d}`);if(l===-1||o||c===32||c===9)throw new SyntaxError("Unexpected end of input");u===-1&&(u=d);let f=n.slice(l,u);return s===void 0?vt(e,f,t):(a===void 0?vt(t,f,!0):i?vt(t,a,f.replace(/\\/g,"")):vt(t,a,f),vt(e,s,t)),e}function vz(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(i=>[e].concat(Object.keys(i).map(r=>{let o=i[r];return Array.isArray(o)||(o=[o]),o.map(s=>s===!0?r:`${r}=${s}`).join("; ")})).join("; ")).join(", ")}).join(", ")}I0.exports={format:vz,parse:yz}});var Dl=N((MZ,j0)=>{"use strict";var _z=ne("events"),wz=ne("https"),bz=ne("http"),A0=ne("net"),kz=ne("tls"),{randomBytes:Sz,createHash:$z}=ne("crypto"),{Duplex:DZ,Readable:PZ}=ne("stream"),{URL:My}=ne("url"),ln=jr(),xz=Oy(),Iz=Dy(),{isBlob:Tz}=Ur(),{BINARY_TYPES:T0,CLOSE_TIMEOUT:Ez,EMPTY_BUFFER:Ol,GUID:Az,kForOnEventAttribute:Ly,kListener:Oz,kStatusCode:Cz,kWebSocket:ke,NOOP:O0}=Nt(),{EventTarget:{addEventListener:Nz,removeEventListener:Dz}}=x0(),{format:Pz,parse:Mz}=Al(),{toBuffer:Lz}=bo(),C0=Symbol("kAborted"),zy=[8,13],Mt=["CONNECTING","OPEN","CLOSING","CLOSED"],zz=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,le=class n extends _z{constructor(e,t,i){super(),this._binaryType=T0[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Ol,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(i=t,t=[]):t=[t]),N0(this,e,t,i)):(this._autoPong=i.autoPong,this._closeTimeout=i.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){T0.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,t,i){let r=new xz({allowSynchronousEvents:i.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:i.maxPayload,skipUTF8Validation:i.skipUTF8Validation}),o=new Iz(e,this._extensions,i.generateMask);this._receiver=r,this._sender=o,this._socket=e,r[ke]=this,o[ke]=this,e[ke]=this,r.on("conclude",Rz),r.on("drain",Bz),r.on("error",Fz),r.on("message",qz),r.on("ping",Zz),r.on("pong",Kz),o.onerror=Vz,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",M0),e.on("data",Nl),e.on("end",L0),e.on("error",z0),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[ln.extensionName]&&this._extensions[ln.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,i=>{i||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),P0(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){jy(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Ol,t,i)}pong(e,t,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(i=e,e=t=void 0):typeof t=="function"&&(i=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){jy(this,e,i);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Ol,t,i)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,i){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(i=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){jy(this,e,i);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[ln.extensionName]||(r.compress=!1),this._sender.send(e||Ol,r,i)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){We(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(le,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")});Object.defineProperty(le.prototype,"CONNECTING",{enumerable:!0,value:Mt.indexOf("CONNECTING")});Object.defineProperty(le,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")});Object.defineProperty(le.prototype,"OPEN",{enumerable:!0,value:Mt.indexOf("OPEN")});Object.defineProperty(le,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")});Object.defineProperty(le.prototype,"CLOSING",{enumerable:!0,value:Mt.indexOf("CLOSING")});Object.defineProperty(le,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")});Object.defineProperty(le.prototype,"CLOSED",{enumerable:!0,value:Mt.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(le.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(le.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[Ly])return e[Oz];return null},set(e){for(let t of this.listeners(n))if(t[Ly]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[Ly]:!0})}})});le.prototype.addEventListener=Nz;le.prototype.removeEventListener=Dz;j0.exports=le;function N0(n,e,t,i){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:Ez,protocolVersion:zy[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=r.autoPong,n._closeTimeout=r.closeTimeout,!zy.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${zy.join(", ")})`);let o;if(e instanceof My)o=e;else try{o=new My(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}o.protocol==="http:"?o.protocol="ws:":o.protocol==="https:"&&(o.protocol="wss:"),n._url=o.href;let s=o.protocol==="wss:",a=o.protocol==="ws+unix:",l;if(o.protocol!=="ws:"&&!s&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!o.pathname?l="The URL's pathname is empty":o.hash&&(l="The URL contains a fragment identifier"),l){let m=new SyntaxError(l);if(n._redirects===0)throw m;Cl(n,m);return}let c=s?443:80,u=Sz(16).toString("base64"),d=s?wz.request:bz.request,f=new Set,p;if(r.createConnection=r.createConnection||(s?Uz:jz),r.defaultPort=r.defaultPort||c,r.port=o.port||c,r.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":u,Connection:"Upgrade",Upgrade:"websocket"},r.path=o.pathname+o.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(p=new ln({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=Pz({[ln.extensionName]:p.offer()})),t.length){for(let m of t){if(typeof m!="string"||!zz.test(m)||f.has(m))throw new SyntaxError("An invalid or duplicated subprotocol was specified");f.add(m)}r.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(o.username||o.password)&&(r.auth=`${o.username}:${o.password}`),a){let m=r.path.split(":");r.socketPath=m[0],r.path=m[1]}let h;if(r.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=s,n._originalHostOrSocketPath=a?r.socketPath:o.host;let m=i&&i.headers;if(i={...i,headers:{}},m)for(let[y,_]of Object.entries(m))i.headers[y.toLowerCase()]=_}else if(n.listenerCount("redirect")===0){let m=a?n._originalIpc?r.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:o.host===n._originalHostOrSocketPath;(!m||n._originalSecure&&!s)&&(delete r.headers.authorization,delete r.headers.cookie,m||delete r.headers.host,r.auth=void 0)}r.auth&&!i.headers.authorization&&(i.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),h=n._req=d(r),n._redirects&&n.emit("redirect",n.url,h)}else h=n._req=d(r);r.timeout&&h.on("timeout",()=>{We(n,h,"Opening handshake has timed out")}),h.on("error",m=>{h===null||h[C0]||(h=n._req=null,Cl(n,m))}),h.on("response",m=>{let y=m.headers.location,_=m.statusCode;if(y&&r.followRedirects&&_>=300&&_<400){if(++n._redirects>r.maxRedirects){We(n,h,"Maximum redirects exceeded");return}h.abort();let b;try{b=new My(y,e)}catch{let O=new SyntaxError(`Invalid URL: ${y}`);Cl(n,O);return}N0(n,b,t,i)}else n.emit("unexpected-response",h,m)||We(n,h,`Unexpected server response: ${m.statusCode}`)}),h.on("upgrade",(m,y,_)=>{if(n.emit("upgrade",m),n.readyState!==le.CONNECTING)return;h=n._req=null;let b=m.headers.upgrade;if(b===void 0||b.toLowerCase()!=="websocket"){We(n,y,"Invalid Upgrade header");return}let k=$z("sha1").update(u+Az).digest("base64");if(m.headers["sec-websocket-accept"]!==k){We(n,y,"Invalid Sec-WebSocket-Accept header");return}let O=m.headers["sec-websocket-protocol"],A;if(O!==void 0?f.size?f.has(O)||(A="Server sent an invalid subprotocol"):A="Server sent a subprotocol but none was requested":f.size&&(A="Server sent no subprotocol"),A){We(n,y,A);return}O&&(n._protocol=O);let j=m.headers["sec-websocket-extensions"];if(j!==void 0){if(!p){We(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let L;try{L=Mz(j)}catch{We(n,y,"Invalid Sec-WebSocket-Extensions header");return}let P=Object.keys(L);if(P.length!==1||P[0]!==ln.extensionName){We(n,y,"Server indicated an extension that was not requested");return}try{p.accept(L[ln.extensionName])}catch{We(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[ln.extensionName]=p}n.setSocket(y,_,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(h,n):h.end()}function Cl(n,e){n._readyState=le.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function jz(n){return n.path=n.socketPath,A0.connect(n)}function Uz(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=A0.isIP(n.host)?"":n.host),kz.connect(n)}function We(n,e,t){n._readyState=le.CLOSING;let i=new Error(t);Error.captureStackTrace(i,We),e.setHeader?(e[C0]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(Cl,n,i)):(e.destroy(i),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function jy(n,e,t){if(e){let i=Tz(e)?e.size:Lz(e).length;n._socket?n._sender._bufferedBytes+=i:n._bufferedAmount+=i}if(t){let i=new Error(`WebSocket is not open: readyState ${n.readyState} (${Mt[n.readyState]})`);process.nextTick(t,i)}}function Rz(n,e){let t=this[ke];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ke]!==void 0&&(t._socket.removeListener("data",Nl),process.nextTick(D0,t._socket),n===1005?t.close():t.close(n,e))}function Bz(){let n=this[ke];n.isPaused||n._socket.resume()}function Fz(n){let e=this[ke];e._socket[ke]!==void 0&&(e._socket.removeListener("data",Nl),process.nextTick(D0,e._socket),e.close(n[Cz])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function E0(){this[ke].emitClose()}function qz(n,e){this[ke].emit("message",n,e)}function Zz(n){let e=this[ke];e._autoPong&&e.pong(n,!this._isServer,O0),e.emit("ping",n)}function Kz(n){this[ke].emit("pong",n)}function D0(n){n.resume()}function Vz(n){let e=this[ke];e.readyState!==le.CLOSED&&(e.readyState===le.OPEN&&(e._readyState=le.CLOSING,P0(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function P0(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function M0(){let n=this[ke];if(this.removeListener("close",M0),this.removeListener("data",Nl),this.removeListener("end",L0),n._readyState=le.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ke]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",E0),n._receiver.on("finish",E0))}function Nl(n){this[ke]._receiver.write(n)||this.pause()}function L0(){let n=this[ke];n._readyState=le.CLOSING,n._receiver.end(),this.end()}function z0(){let n=this[ke];this.removeListener("error",z0),this.on("error",O0),n&&(n._readyState=le.CLOSING,this.destroy())}});var F0=N((zZ,B0)=>{"use strict";var LZ=Dl(),{Duplex:Wz}=ne("stream");function U0(n){n.emit("close")}function Gz(){!this.destroyed&&this._writableState.finished&&this.destroy()}function R0(n){this.removeListener("error",R0),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function Jz(n,e){let t=!0,i=new Wz({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(o,s){let a=!s&&i._readableState.objectMode?o.toString():o;i.push(a)||n.pause()}),n.once("error",function(o){i.destroyed||(t=!1,i.destroy(o))}),n.once("close",function(){i.destroyed||i.push(null)}),i._destroy=function(r,o){if(n.readyState===n.CLOSED){o(r),process.nextTick(U0,i);return}let s=!1;n.once("error",function(l){s=!0,o(l)}),n.once("close",function(){s||o(r),process.nextTick(U0,i)}),t&&n.terminate()},i._final=function(r){if(n.readyState===n.CONNECTING){n.once("open",function(){i._final(r)});return}n._socket!==null&&(n._socket._writableState.finished?(r(),i._readableState.endEmitted&&i.destroy()):(n._socket.once("finish",function(){r()}),n.close()))},i._read=function(){n.isPaused&&n.resume()},i._write=function(r,o,s){if(n.readyState===n.CONNECTING){n.once("open",function(){i._write(r,o,s)});return}n.send(r,s)},i.on("end",Gz),i.on("error",R0),i}B0.exports=Jz});var Uy=N((jZ,q0)=>{"use strict";var{tokenChars:Hz}=Ur();function Yz(n){let e=new Set,t=-1,i=-1,r=0;for(r;r<n.length;r++){let s=n.charCodeAt(r);if(i===-1&&Hz[s]===1)t===-1&&(t=r);else if(r!==0&&(s===32||s===9))i===-1&&t!==-1&&(i=r);else if(s===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${r}`);i===-1&&(i=r);let a=n.slice(t,i);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=i=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(t===-1||i!==-1)throw new SyntaxError("Unexpected end of input");let o=n.slice(t,r);if(e.has(o))throw new SyntaxError(`The "${o}" subprotocol is duplicated`);return e.add(o),e}q0.exports={parse:Yz}});var H0=N((RZ,J0)=>{"use strict";var Xz=ne("events"),Pl=ne("http"),{Duplex:UZ}=ne("stream"),{createHash:Qz}=ne("crypto"),Z0=Al(),jn=jr(),ej=Uy(),tj=Dl(),{CLOSE_TIMEOUT:nj,GUID:rj,kWebSocket:ij}=Nt(),oj=/^[+/0-9A-Za-z]{22}==$/,K0=0,V0=1,G0=2,Ry=class extends Xz{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:nj,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:tj,...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=Pl.createServer((i,r)=>{let o=Pl.STATUS_CODES[426];r.writeHead(426,{"Content-Length":o.length,"Content-Type":"text/plain"}),r.end(o)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let i=this.emit.bind(this,"connection");this._removeListeners=sj(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,o,s)=>{this.handleUpgrade(r,o,s,i)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=K0}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===G0){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(Io,this);return}if(e&&this.once("close",e),this._state!==V0)if(this._state=V0,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(Io,this):process.nextTick(Io,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{Io(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,i,r){t.on("error",W0);let o=e.headers["sec-websocket-key"],s=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Un(this,e,t,405,"Invalid HTTP method");return}if(s===void 0||s.toLowerCase()!=="websocket"){Un(this,e,t,400,"Invalid Upgrade header");return}if(o===void 0||!oj.test(o)){Un(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Un(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){To(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=ej.parse(l)}catch{Un(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let u=e.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&u!==void 0){let f=new jn({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Z0.parse(u);p[jn.extensionName]&&(f.accept(p[jn.extensionName]),d[jn.extensionName]=f)}catch{Un(this,e,t,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,(p,h,m,y)=>{if(!p)return To(t,h||401,m,y);this.completeUpgrade(d,o,c,e,t,i,r)});return}if(!this.options.verifyClient(f))return To(t,401)}this.completeUpgrade(d,o,c,e,t,i,r)}completeUpgrade(e,t,i,r,o,s,a){if(!o.readable||!o.writable)return o.destroy();if(o[ij])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>K0)return To(o,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Qz("sha1").update(t+rj).digest("base64")}`],u=new this.options.WebSocket(null,void 0,this.options);if(i.size){let d=this.options.handleProtocols?this.options.handleProtocols(i,r):i.values().next().value;d&&(c.push(`Sec-WebSocket-Protocol: ${d}`),u._protocol=d)}if(e[jn.extensionName]){let d=e[jn.extensionName].params,f=Z0.format({[jn.extensionName]:[d]});c.push(`Sec-WebSocket-Extensions: ${f}`),u._extensions=e}this.emit("headers",c,r),o.write(c.concat(`\r
213
252
  `).join(`\r
214
- `)),i.removeListener("error",Op),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(rn,this)})),a(d,r)}};Dp.exports=wc;function ev(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let s of Object.keys(e))n.removeListener(s,e[s])}}function rn(n){n._state=Mp,n.emit("close")}function Op(){this.destroy()}function on(n,e,t,s){t=t||vi.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...s},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${vi.STATUS_CODES[e]}\r
215
- `+Object.keys(s).map(r=>`${r}: ${s[r]}`).join(`\r
253
+ `)),o.removeListener("error",W0),u.setSocket(o,s,{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(Io,this)})),a(u,r)}};J0.exports=Ry;function sj(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let i of Object.keys(e))n.removeListener(i,e[i])}}function Io(n){n._state=G0,n.emit("close")}function W0(){this.destroy()}function To(n,e,t,i){t=t||Pl.STATUS_CODES[e],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...i},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${Pl.STATUS_CODES[e]}\r
254
+ `+Object.keys(i).map(r=>`${r}: ${i[r]}`).join(`\r
216
255
  `)+`\r
217
256
  \r
218
- `+t)}function Lt(n,e,t,s,r,i){if(n.listenerCount("wsClientError")){let o=new Error(r);Error.captureStackTrace(o,Lt),n.emit("wsClientError",o,t,e)}else on(t,s,r,i)}});var tv,sv,nv,rv,iv,ov,an,Sc,Pp=j(()=>{tv=Ae(Ap(),1),sv=Ae(wi(),1),nv=Ae(es(),1),rv=Ae(cc(),1),iv=Ae(uc(),1),ov=Ae(yc(),1),an=Ae(_i(),1),Sc=Ae(Lp(),1)});function $p(n){let e;try{e=JSON.parse(n)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"message":return typeof t.text!="string"||typeof t.id!="string"?null:typeof t.channelId=="string"?{type:"message",channelId:t.channelId,text:t.text,threadId:typeof t.threadId=="string"?t.threadId:void 0,id:t.id}:{type:"message",text:t.text,id:t.id};case"image":return typeof t.data!="string"||typeof t.filename!="string"||typeof t.id!="string"?null:typeof t.channelId=="string"?{type:"image",channelId:t.channelId,data:t.data,filename:t.filename,id:t.id}:{type:"image",data:t.data,filename:t.filename,id:t.id};case"file":return typeof t.channelId=="string"&&typeof t.data=="string"&&typeof t.filename=="string"&&typeof t.mimetype=="string"&&typeof t.id=="string"?{type:"file",channelId:t.channelId,data:t.data,filename:t.filename,mimetype:t.mimetype,id:t.id}:null;case"ping":return{type:"ping"};case"join":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"join",channelId:t.channelId,id:t.id}:null;case"leave":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"leave",channelId:t.channelId,id:t.id}:null;case"command":return typeof t.channelId=="string"&&typeof t.name=="string"&&Array.isArray(t.args)&&typeof t.id=="string"?{type:"command",channelId:t.channelId,name:t.name,args:t.args.map(String),id:t.id}:null;case"command_list":return typeof t.id=="string"?{type:"command_list",id:t.id}:null;case"channel_list":return typeof t.id=="string"?{type:"channel_list",id:t.id}:null;case"history":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"history",channelId:t.channelId,before:typeof t.before=="string"?t.before:void 0,limit:typeof t.limit=="number"?t.limit:void 0,id:t.id}:null;case"agent_list":return typeof t.id=="string"?{type:"agent_list",id:t.id}:null;default:return null}}function Rp(n){return(n.type==="message"||n.type==="image"||n.type==="file")&&"channelId"in n}var Bp=j(()=>{"use strict"});var jp={};Ue(jp,{WsAdapter:()=>kc});import{createServer as av}from"node:http";import{randomUUID as cn}from"node:crypto";function Up(n){let e=n.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",heic:"image/heic"}[e??""]??"image/jpeg"}var Te,kc,qp=j(()=>{"use strict";Pp();M();Bp();Vs();Te=k("ws-adapter"),kc=class{id="ws";kind="app";port;server;wss;connections=new Map;pendingMessages=new Map;onWorkItem;teamStore;commandRegistry;agentRegistry;agentManager;constructor(e,t){this.port=e,this.teamStore=t.teamStore,this.commandRegistry=t.commandRegistry,this.agentRegistry=t.agentRegistry,this.agentManager=t.agentManager}async start(e){this.onWorkItem=e,this.server=av(async(t,s)=>{if(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS"){s.writeHead(204),s.end();return}let r=new URL(t.url??"/",`http://localhost:${this.port}`);if(t.method==="GET"&&r.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",connections:this.connections.size}));return}s.writeHead(404),s.end("Not found")}),this.wss=new Sc.default({noServer:!0,maxPayload:10*1024*1024}),this.server.on("upgrade",(t,s,r)=>{let i=new URL(t.url??"/",`http://localhost:${this.port}`);if(i.searchParams.get("internal")!=="1"){s.write(`HTTP/1.1 404 Not Found\r
257
+ `+t)}function Un(n,e,t,i,r,o){if(n.listenerCount("wsClientError")){let s=new Error(r);Error.captureStackTrace(s,Un),n.emit("wsClientError",s,t,e)}else To(t,i,r,o)}});var aj,cj,lj,uj,dj,fj,Eo,By,Y0=S(()=>{aj=nt(F0(),1),cj=nt(Al(),1),lj=nt(jr(),1),uj=nt(Oy(),1),dj=nt(Dy(),1),fj=nt(Uy(),1),Eo=nt(Dl(),1),By=nt(H0(),1)});function X0(n){let e;try{e=JSON.parse(n)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"message":return typeof t.text!="string"||typeof t.id!="string"?null:typeof t.channelId=="string"?{type:"message",channelId:t.channelId,text:t.text,threadId:typeof t.threadId=="string"?t.threadId:void 0,id:t.id}:{type:"message",text:t.text,id:t.id};case"image":return typeof t.data!="string"||typeof t.filename!="string"||typeof t.id!="string"?null:typeof t.channelId=="string"?{type:"image",channelId:t.channelId,data:t.data,filename:t.filename,id:t.id}:{type:"image",data:t.data,filename:t.filename,id:t.id};case"file":return typeof t.channelId=="string"&&typeof t.data=="string"&&typeof t.filename=="string"&&typeof t.mimetype=="string"&&typeof t.id=="string"?{type:"file",channelId:t.channelId,data:t.data,filename:t.filename,mimetype:t.mimetype,id:t.id}:null;case"ping":return{type:"ping"};case"join":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"join",channelId:t.channelId,id:t.id}:null;case"leave":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"leave",channelId:t.channelId,id:t.id}:null;case"command":return typeof t.channelId=="string"&&typeof t.name=="string"&&Array.isArray(t.args)&&typeof t.id=="string"?{type:"command",channelId:t.channelId,name:t.name,args:t.args.map(String),id:t.id}:null;case"command_list":return typeof t.id=="string"?{type:"command_list",id:t.id}:null;case"channel_list":return typeof t.id=="string"?{type:"channel_list",id:t.id}:null;case"history":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"history",channelId:t.channelId,before:typeof t.before=="string"?t.before:void 0,limit:typeof t.limit=="number"?t.limit:void 0,id:t.id}:null;case"agent_list":return typeof t.id=="string"?{type:"agent_list",id:t.id}:null;default:return null}}function Q0(n){return(n.type==="message"||n.type==="image"||n.type==="file")&&"channelId"in n}var eT=S(()=>{"use strict"});var nT={};we(nT,{WsAdapter:()=>Fy});import{createServer as pj}from"node:http";import{randomUUID as Ao}from"node:crypto";function tT(n){let e=n.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",heic:"image/heic"}[e??""]??"image/jpeg"}var et,Fy,rT=S(()=>{"use strict";Y0();R();eT();ho();et=$("ws-adapter"),Fy=class{id="ws";kind="app";port;server;wss;connections=new Map;pendingMessages=new Map;onWorkItem;teamStore;commandRegistry;agentRegistry;agentManager;constructor(e,t){this.port=e,this.teamStore=t.teamStore,this.commandRegistry=t.commandRegistry,this.agentRegistry=t.agentRegistry,this.agentManager=t.agentManager}async start(e){this.onWorkItem=e,this.server=pj(async(t,i)=>{if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS"){i.writeHead(204),i.end();return}let r=new URL(t.url??"/",`http://localhost:${this.port}`);if(t.method==="GET"&&r.pathname==="/health"){i.writeHead(200,{"Content-Type":"application/json"}),i.end(JSON.stringify({status:"ok",connections:this.connections.size}));return}i.writeHead(404),i.end("Not found")}),this.wss=new By.default({noServer:!0,maxPayload:10*1024*1024}),this.server.on("upgrade",(t,i,r)=>{let o=new URL(t.url??"/",`http://localhost:${this.port}`);if(o.searchParams.get("internal")!=="1"){i.write(`HTTP/1.1 404 Not Found\r
219
258
  \r
220
- `),s.destroy();return}let o=t.socket.remoteAddress??"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1")){s.write(`HTTP/1.1 403 Forbidden\r
259
+ `),i.destroy();return}let s=t.socket.remoteAddress??"";if(!(s==="127.0.0.1"||s==="::1"||s==="::ffff:127.0.0.1")){i.write(`HTTP/1.1 403 Forbidden\r
221
260
  \r
222
- `),s.destroy();return}let l=i.searchParams.get("deviceId"),c=i.searchParams.get("label")??i.searchParams.get("name"),d=i.searchParams.get("user")??void 0;if(!l||!c){s.write(`HTTP/1.1 400 Bad Request\r
261
+ `),i.destroy();return}let l=o.searchParams.get("deviceId"),c=o.searchParams.get("label")??o.searchParams.get("name"),u=o.searchParams.get("user")??void 0;if(!l||!c){i.write(`HTTP/1.1 400 Bad Request\r
223
262
  \r
224
- `),s.destroy();return}let u=i.searchParams.get("origin")??void 0,h={_id:l,label:c,user:d,defaultAgentId:"",origin:u};this.wss.handleUpgrade(t,s,r,p=>{this.wss.emit("connection",p,t,h)})}),this.wss.on("connection",(t,s,r)=>{let i=r._id;Te.info("Device connected",{deviceId:i,label:r.label});let o=this.pendingMessages.get(i);if(o?.length){Te.info("Draining pending messages",{deviceId:i,count:o.length});for(let l of o)this.send(t,l);this.pendingMessages.delete(i)}let a=this.connections.get(i);a&&a.close(1e3,"Replaced by new connection"),this.connections.set(i,t),t.on("message",async l=>{try{let c=$p(l.toString());if(!c){this.send(t,{type:"error",message:"Invalid message format"});return}if(c.type==="ping")return;if(c.type==="command"){await this.handleCommand(t,c,r,i);return}if(c.type==="command_list"){await this.handleCommandList(t,c);return}if(c.type==="channel_list"){await this.handleChannelList(t,c,i);return}if(c.type==="history"){await this.handleHistory(t,c,i);return}if(c.type==="join"){await this.handleJoin(t,c,i);return}if(c.type==="leave"){await this.handleLeave(t,c,i);return}if(c.type==="agent_list"){let d=this.buildAgentList();this.send(t,{type:"agent_list",agents:d,id:c.id});return}if(Rp(c)){c.type==="message"?await this.handleTeamMessage(t,c,r,i):c.type==="image"?await this.handleTeamImage(t,c,r,i):c.type==="file"&&await this.handleTeamFile(t,c,r,i);return}if(c.type==="message"){this.send(t,{type:"ack",id:c.id});let d={id:c.id||cn(),text:c.text,source:{kind:"app",id:i,label:`app:${r.label}`,adapterId:"ws"},sender:i,senderName:r.label,threadId:`app:${i}`,timestamp:new Date,meta:{deviceId:i,defaultAgentId:r.defaultAgentId,origin:r.origin}};this.onWorkItem(d)}if(c.type==="image"){this.send(t,{type:"ack",id:c.id});let d=Buffer.from(c.data,"base64"),u=Up(c.filename);try{let h=await Gs(d,c.filename,u),p={id:c.id||cn(),text:`[Photo: ${c.filename}]`,source:{kind:"app",id:i,label:`app:${r.label}`,adapterId:"ws"},sender:i,senderName:r.label,threadId:`app:${i}`,timestamp:new Date,files:[h],meta:{deviceId:i,defaultAgentId:r.defaultAgentId,origin:r.origin}};this.onWorkItem(p)}catch(h){Te.error("Image processing failed",{deviceId:i,filename:c.filename,error:String(h)}),this.send(t,{type:"error",message:"Failed to process image"})}}}catch(c){Te.error("Message handling error",{deviceId:i,error:String(c)}),this.send(t,{type:"error",message:"Internal error"})}}),t.on("close",()=>{Te.info("Device disconnected",{deviceId:i}),this.connections.delete(i)}),t.on("error",l=>{Te.error("WebSocket error",{deviceId:i,error:String(l)})})}),await new Promise(t=>{this.server.listen(this.port,"127.0.0.1",()=>{Te.info("WebSocket server listening",{port:this.port,host:"127.0.0.1"}),t()})})}async deliver(e){let t=e.workItem.meta?.deviceId;if(!t){Te.warn("No deviceId in WorkResult, cannot deliver");return}let s=e.error?`Error: ${e.error}`:e.text,r=e.workItem.meta?.channelId,i=this.agentRegistry.get(e.agentId)?.name??e.agentId;r&&await this.teamStore.saveMessage({channelId:r,senderId:e.agentId,senderType:"agent",senderName:i,text:s,createdAt:new Date});let o={type:"message",text:s,agentId:e.agentId,agentName:i,replyTo:e.workItem.id,...r?{channelId:r}:{}},a=this.connections.get(t);if(a&&a.readyState===an.default.OPEN)this.send(a,o);else{Te.info("Device not connected, buffering message",{deviceId:t});let l=this.pendingMessages.get(t)??[];l.push(o),this.pendingMessages.set(t,l)}}async onProcessingStart(e,t){let s=e.meta?.deviceId;if(!s)return;let r=this.connections.get(s);r&&r.readyState===an.default.OPEN&&this.send(r,{type:"typing",agentId:t})}async onProcessingEnd(e,t){}async stop(){for(let[e,t]of this.connections)t.close(1001,"Server shutting down");this.connections.clear(),await new Promise(e=>{this.wss&&this.wss.close(()=>{}),this.server?this.server.close(()=>e()):e()}),Te.info("WebSocket adapter stopped")}get connectionCount(){return this.connections.size}async verifyChannelMembership(e,t,s){let r=await this.teamStore.getChannel(t);return r?r.members.includes(s)?r:(this.send(e,{type:"error",message:"Not a member of this channel"}),null):(this.send(e,{type:"error",message:"Channel not found"}),null)}buildAgentList(){return this.agentRegistry.getAll().map(e=>{let t=this.agentManager.getState(e.id);return{id:e.id,name:e.name,icon:e.icon,title:e.title??null,model:e.model,status:t?.status??"idle",tools:[...new Set([...e.coreServers,...e.delegateServers])].sort(),schedule:e.schedule.map(s=>({cron:s.cron,task:s.task})),channels:e.channels,messagesProcessed:t?.messagesProcessed??0,lastActivity:t?t.lastActivity.toISOString():null}})}async handleTeamMessage(e,t,s,r){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,r);if(!i)return;await this.teamStore.saveMessage({channelId:t.channelId,threadId:t.threadId,senderId:r,senderType:"person",senderName:s.label,text:t.text,createdAt:new Date});let o=i.type==="dm"?i.members.find(l=>l!==r):void 0,a={id:t.id||cn(),text:t.text,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:s.label,threadId:t.threadId??`team:${t.channelId}`,timestamp:new Date,meta:{deviceId:r,channelId:t.channelId,...s.user?{user:s.user}:{},...o?{targetAgentId:o}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(a)}async handleTeamImage(e,t,s,r){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,r);if(!i)return;let o=Buffer.from(t.data,"base64"),a=Up(t.filename);try{let l=await Gs(o,t.filename,a);await this.teamStore.saveMessage({channelId:t.channelId,senderId:r,senderType:"person",senderName:s.label,text:`[Photo: ${t.filename}]`,files:[{name:l.name,mimetype:l.mimetype,size:l.size,storageKey:l.localPath,isImage:!0}],createdAt:new Date});let c=i.type==="dm"?i.members.find(u=>u!==r):void 0,d={id:t.id||cn(),text:`[Photo: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[l],meta:{deviceId:r,channelId:t.channelId,...s.user?{user:s.user}:{},...c?{targetAgentId:c}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(d)}catch(l){Te.error("Team image processing failed",{deviceId:r,filename:t.filename,error:String(l)}),this.send(e,{type:"error",message:"Failed to process image"})}}async handleTeamFile(e,t,s,r){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,r);if(!i)return;let o=Buffer.from(t.data,"base64");try{let a=t.mimetype.startsWith("image/")?await Gs(o,t.filename,t.mimetype):await qh(o,t.filename,t.mimetype);await this.teamStore.saveMessage({channelId:t.channelId,senderId:r,senderType:"person",senderName:s.label,text:`[File: ${t.filename}]`,files:[{name:a.name,mimetype:a.mimetype,size:a.size,storageKey:a.localPath,isImage:a.isImage}],createdAt:new Date});let l=i.type==="dm"?i.members.find(d=>d!==r):void 0,c={id:t.id||cn(),text:`[File: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[a],meta:{deviceId:r,channelId:t.channelId,...s.user?{user:s.user}:{},...l?{targetAgentId:l}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(c)}catch(a){Te.error("Team file processing failed",{deviceId:r,filename:t.filename,error:String(a)}),this.send(e,{type:"error",message:"Failed to process file"})}}async handleCommand(e,t,s,r){if(this.send(e,{type:"ack",id:t.id}),!this.commandRegistry.has(t.name)){this.send(e,{type:"error",message:`Unknown command: /${t.name}`});return}let{result:i}=await this.commandRegistry.execute(t.name,{channelId:t.channelId,senderId:r,senderName:s.label,args:t.args});i&&await this.teamStore.saveMessage({channelId:t.channelId,senderId:"system",senderType:"agent",senderName:"system",text:i,command:{name:t.name,args:t.args,result:i},createdAt:new Date}),this.send(e,{type:"message",text:i??"Done.",agentId:"system",agentName:"system",replyTo:t.id})}async handleCommandList(e,t){let s=this.commandRegistry.list();this.send(e,{type:"command_list",commands:s.map(r=>({name:r.name,description:r.description,args:r.args})),id:t.id})}async handleChannelList(e,t,s){let r=await this.teamStore.listChannels(s);this.send(e,{type:"channel_list",channels:r.map(i=>({id:i._id,type:i.type,name:i.name,members:i.members})),id:t.id})}async handleHistory(e,t,s){if(!await this.verifyChannelMembership(e,t.channelId,s))return;let{messages:r,hasMore:i}=await this.teamStore.getHistory(t.channelId,{before:t.before,limit:t.limit});this.send(e,{type:"history",channelId:t.channelId,messages:r.map(o=>({id:o._id??"",senderId:o.senderId,senderType:o.senderType,senderName:o.senderName,text:o.text,threadId:o.threadId,createdAt:o.createdAt.toISOString()})),hasMore:i,id:t.id})}async handleJoin(e,t,s){if(t.channelId.startsWith("dm:")){let i=await this.teamStore.getChannel(t.channelId);if(!i||!i.members.includes(s)){this.send(e,{type:"error",message:"Cannot join a DM you are not part of"});return}}await this.teamStore.joinChannel(t.channelId,s)?this.send(e,{type:"channel_event",channelId:t.channelId,event:"joined",detail:{memberId:s},id:t.id}):this.send(e,{type:"error",message:"Failed to join channel"})}async handleLeave(e,t,s){await this.teamStore.leaveChannel(t.channelId,s)?this.send(e,{type:"channel_event",channelId:t.channelId,event:"left",detail:{memberId:s},id:t.id}):this.send(e,{type:"error",message:"Failed to leave channel"})}send(e,t){e.readyState===an.default.OPEN&&e.send(JSON.stringify(t))}}});var Fp={};Ue(Fp,{startBeekeeperRegistration:()=>cv});function cv(n){let{beekeeperPort:e,wsPort:t}=n,s=n.intervalMs??3e4,r=`http://127.0.0.1:${e}/internal/register-capability`,i={name:n.capabilityName??"hive",localWsUrl:`ws://127.0.0.1:${t}`,healthUrl:`http://127.0.0.1:${t}/health`},o=JSON.stringify(i),a=async()=>{try{let c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:o});if(c.ok)bc.debug("Registered with beekeeper",{beekeeperPort:e,wsPort:t});else{let d=await c.text().catch(()=>"");bc.warn("Beekeeper registration failed",{status:c.status,body:d})}}catch(c){bc.warn("Beekeeper registration error",{error:String(c)})}};a();let l=setInterval(()=>{a()},s);return{stop:()=>clearInterval(l)}}var bc,Kp=j(()=>{"use strict";M();bc=k("beekeeper-client")});async function Hp(n,e,t){let s=[];n.soul&&s.push(n.soul),s.push(n.systemPrompt);let r=await e.read("shared/constitution.md");r&&s.push(r),s.push(`## Voice Call Mode
263
+ `),i.destroy();return}let d=o.searchParams.get("origin")??void 0,f={_id:l,label:c,user:u,defaultAgentId:"",origin:d};this.wss.handleUpgrade(t,i,r,p=>{this.wss.emit("connection",p,t,f)})}),this.wss.on("connection",(t,i,r)=>{let o=r._id;et.info("Device connected",{deviceId:o,label:r.label});let s=this.pendingMessages.get(o);if(s?.length){et.info("Draining pending messages",{deviceId:o,count:s.length});for(let l of s)this.send(t,l);this.pendingMessages.delete(o)}let a=this.connections.get(o);a&&a.close(1e3,"Replaced by new connection"),this.connections.set(o,t),t.on("message",async l=>{try{let c=X0(l.toString());if(!c){this.send(t,{type:"error",message:"Invalid message format"});return}if(c.type==="ping")return;if(c.type==="command"){await this.handleCommand(t,c,r,o);return}if(c.type==="command_list"){await this.handleCommandList(t,c);return}if(c.type==="channel_list"){await this.handleChannelList(t,c,o);return}if(c.type==="history"){await this.handleHistory(t,c,o);return}if(c.type==="join"){await this.handleJoin(t,c,o);return}if(c.type==="leave"){await this.handleLeave(t,c,o);return}if(c.type==="agent_list"){let u=this.buildAgentList();this.send(t,{type:"agent_list",agents:u,id:c.id});return}if(Q0(c)){c.type==="message"?await this.handleTeamMessage(t,c,r,o):c.type==="image"?await this.handleTeamImage(t,c,r,o):c.type==="file"&&await this.handleTeamFile(t,c,r,o);return}if(c.type==="message"){this.send(t,{type:"ack",id:c.id});let u={id:c.id||Ao(),text:c.text,source:{kind:"app",id:o,label:`app:${r.label}`,adapterId:"ws"},sender:o,senderName:r.label,threadId:`app:${o}`,timestamp:new Date,meta:{deviceId:o,defaultAgentId:r.defaultAgentId,origin:r.origin}};this.onWorkItem(u)}if(c.type==="image"){this.send(t,{type:"ack",id:c.id});let u=Buffer.from(c.data,"base64"),d=tT(c.filename);try{let f=await mo(u,c.filename,d),p={id:c.id||Ao(),text:`[Photo: ${c.filename}]`,source:{kind:"app",id:o,label:`app:${r.label}`,adapterId:"ws"},sender:o,senderName:r.label,threadId:`app:${o}`,timestamp:new Date,files:[f],meta:{deviceId:o,defaultAgentId:r.defaultAgentId,origin:r.origin}};this.onWorkItem(p)}catch(f){et.error("Image processing failed",{deviceId:o,filename:c.filename,error:String(f)}),this.send(t,{type:"error",message:"Failed to process image"})}}}catch(c){et.error("Message handling error",{deviceId:o,error:String(c)}),this.send(t,{type:"error",message:"Internal error"})}}),t.on("close",()=>{et.info("Device disconnected",{deviceId:o}),this.connections.delete(o)}),t.on("error",l=>{et.error("WebSocket error",{deviceId:o,error:String(l)})})}),await new Promise(t=>{this.server.listen(this.port,"127.0.0.1",()=>{et.info("WebSocket server listening",{port:this.port,host:"127.0.0.1"}),t()})})}async deliver(e){let t=e.workItem.meta?.deviceId;if(!t){et.warn("No deviceId in WorkResult, cannot deliver");return}let i=e.error?`Error: ${e.error}`:e.text,r=e.workItem.meta?.channelId,o=this.agentRegistry.get(e.agentId)?.name??e.agentId;r&&await this.teamStore.saveMessage({channelId:r,senderId:e.agentId,senderType:"agent",senderName:o,text:i,createdAt:new Date});let s={type:"message",text:i,agentId:e.agentId,agentName:o,replyTo:e.workItem.id,...r?{channelId:r}:{}},a=this.connections.get(t);if(a&&a.readyState===Eo.default.OPEN)this.send(a,s);else{et.info("Device not connected, buffering message",{deviceId:t});let l=this.pendingMessages.get(t)??[];l.push(s),this.pendingMessages.set(t,l)}}async onProcessingStart(e,t){let i=e.meta?.deviceId;if(!i)return;let r=this.connections.get(i);r&&r.readyState===Eo.default.OPEN&&this.send(r,{type:"typing",agentId:t})}async onProcessingEnd(e,t){}async stop(){for(let[e,t]of this.connections)t.close(1001,"Server shutting down");this.connections.clear(),await new Promise(e=>{this.wss&&this.wss.close(()=>{}),this.server?this.server.close(()=>e()):e()}),et.info("WebSocket adapter stopped")}get connectionCount(){return this.connections.size}async verifyChannelMembership(e,t,i){let r=await this.teamStore.getChannel(t);return r?r.members.includes(i)?r:(this.send(e,{type:"error",message:"Not a member of this channel"}),null):(this.send(e,{type:"error",message:"Channel not found"}),null)}buildAgentList(){return this.agentRegistry.getAll().map(e=>{let t=this.agentManager.getState(e.id);return{id:e.id,name:e.name,icon:e.icon,title:e.title??null,model:e.model,status:t?.status??"idle",tools:[...new Set([...e.coreServers,...e.delegateServers])].sort(),schedule:e.schedule.map(i=>({cron:i.cron,task:i.task})),channels:e.channels,messagesProcessed:t?.messagesProcessed??0,lastActivity:t?t.lastActivity.toISOString():null}})}async handleTeamMessage(e,t,i,r){this.send(e,{type:"ack",id:t.id});let o=await this.verifyChannelMembership(e,t.channelId,r);if(!o)return;await this.teamStore.saveMessage({channelId:t.channelId,threadId:t.threadId,senderId:r,senderType:"person",senderName:i.label,text:t.text,createdAt:new Date});let s=o.type==="dm"?o.members.find(l=>l!==r):void 0,a={id:t.id||Ao(),text:t.text,source:{kind:"team",id:t.channelId,label:`team:${o?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:i.label,threadId:t.threadId??`team:${t.channelId}`,timestamp:new Date,meta:{deviceId:r,channelId:t.channelId,...i.user?{user:i.user}:{},...s?{targetAgentId:s}:{defaultAgentId:i.defaultAgentId}}};this.onWorkItem(a)}async handleTeamImage(e,t,i,r){this.send(e,{type:"ack",id:t.id});let o=await this.verifyChannelMembership(e,t.channelId,r);if(!o)return;let s=Buffer.from(t.data,"base64"),a=tT(t.filename);try{let l=await mo(s,t.filename,a);await this.teamStore.saveMessage({channelId:t.channelId,senderId:r,senderType:"person",senderName:i.label,text:`[Photo: ${t.filename}]`,files:[{name:l.name,mimetype:l.mimetype,size:l.size,storageKey:l.localPath,isImage:!0}],createdAt:new Date});let c=o.type==="dm"?o.members.find(d=>d!==r):void 0,u={id:t.id||Ao(),text:`[Photo: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${o?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:i.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[l],meta:{deviceId:r,channelId:t.channelId,...i.user?{user:i.user}:{},...c?{targetAgentId:c}:{defaultAgentId:i.defaultAgentId}}};this.onWorkItem(u)}catch(l){et.error("Team image processing failed",{deviceId:r,filename:t.filename,error:String(l)}),this.send(e,{type:"error",message:"Failed to process image"})}}async handleTeamFile(e,t,i,r){this.send(e,{type:"ack",id:t.id});let o=await this.verifyChannelMembership(e,t.channelId,r);if(!o)return;let s=Buffer.from(t.data,"base64");try{let a=t.mimetype.startsWith("image/")?await mo(s,t.filename,t.mimetype):await eI(s,t.filename,t.mimetype);await this.teamStore.saveMessage({channelId:t.channelId,senderId:r,senderType:"person",senderName:i.label,text:`[File: ${t.filename}]`,files:[{name:a.name,mimetype:a.mimetype,size:a.size,storageKey:a.localPath,isImage:a.isImage}],createdAt:new Date});let l=o.type==="dm"?o.members.find(u=>u!==r):void 0,c={id:t.id||Ao(),text:`[File: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${o?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:i.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[a],meta:{deviceId:r,channelId:t.channelId,...i.user?{user:i.user}:{},...l?{targetAgentId:l}:{defaultAgentId:i.defaultAgentId}}};this.onWorkItem(c)}catch(a){et.error("Team file processing failed",{deviceId:r,filename:t.filename,error:String(a)}),this.send(e,{type:"error",message:"Failed to process file"})}}async handleCommand(e,t,i,r){if(this.send(e,{type:"ack",id:t.id}),!this.commandRegistry.has(t.name)){this.send(e,{type:"error",message:`Unknown command: /${t.name}`});return}let{result:o}=await this.commandRegistry.execute(t.name,{channelId:t.channelId,senderId:r,senderName:i.label,args:t.args});o&&await this.teamStore.saveMessage({channelId:t.channelId,senderId:"system",senderType:"agent",senderName:"system",text:o,command:{name:t.name,args:t.args,result:o},createdAt:new Date}),this.send(e,{type:"message",text:o??"Done.",agentId:"system",agentName:"system",replyTo:t.id})}async handleCommandList(e,t){let i=this.commandRegistry.list();this.send(e,{type:"command_list",commands:i.map(r=>({name:r.name,description:r.description,args:r.args})),id:t.id})}async handleChannelList(e,t,i){let r=await this.teamStore.listChannels(i);this.send(e,{type:"channel_list",channels:r.map(o=>({id:o._id,type:o.type,name:o.name,members:o.members})),id:t.id})}async handleHistory(e,t,i){if(!await this.verifyChannelMembership(e,t.channelId,i))return;let{messages:r,hasMore:o}=await this.teamStore.getHistory(t.channelId,{before:t.before,limit:t.limit});this.send(e,{type:"history",channelId:t.channelId,messages:r.map(s=>({id:s._id??"",senderId:s.senderId,senderType:s.senderType,senderName:s.senderName,text:s.text,threadId:s.threadId,createdAt:s.createdAt.toISOString()})),hasMore:o,id:t.id})}async handleJoin(e,t,i){if(t.channelId.startsWith("dm:")){let o=await this.teamStore.getChannel(t.channelId);if(!o||!o.members.includes(i)){this.send(e,{type:"error",message:"Cannot join a DM you are not part of"});return}}await this.teamStore.joinChannel(t.channelId,i)?this.send(e,{type:"channel_event",channelId:t.channelId,event:"joined",detail:{memberId:i},id:t.id}):this.send(e,{type:"error",message:"Failed to join channel"})}async handleLeave(e,t,i){await this.teamStore.leaveChannel(t.channelId,i)?this.send(e,{type:"channel_event",channelId:t.channelId,event:"left",detail:{memberId:i},id:t.id}):this.send(e,{type:"error",message:"Failed to leave channel"})}send(e,t){e.readyState===Eo.default.OPEN&&e.send(JSON.stringify(t))}}});var iT={};we(iT,{startBeekeeperRegistration:()=>mj});function mj(n){let{beekeeperPort:e,wsPort:t}=n,i=n.intervalMs??3e4,r=`http://127.0.0.1:${e}/internal/register-capability`,o={name:n.capabilityName??"hive",localWsUrl:`ws://127.0.0.1:${t}`,healthUrl:`http://127.0.0.1:${t}/health`},s=JSON.stringify(o),a=async()=>{try{let c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:s});if(c.ok)qy.debug("Registered with beekeeper",{beekeeperPort:e,wsPort:t});else{let u=await c.text().catch(()=>"");qy.warn("Beekeeper registration failed",{status:c.status,body:u})}}catch(c){qy.warn("Beekeeper registration error",{error:String(c)})}};a();let l=setInterval(()=>{a()},i);return{stop:()=>clearInterval(l)}}var qy,oT=S(()=>{"use strict";R();qy=$("beekeeper-client")});async function sT(n,e,t){let i=[];n.soul&&i.push(n.soul),i.push(n.systemPrompt);let r=await e.read("shared/constitution.md");r&&i.push(r),i.push(`## Voice Call Mode
225
264
 
226
- You are currently on a live phone call. Keep responses conversational and concise \u2014 you are speaking out loud, not writing text. Avoid markdown, bullet points, or long lists. Speak naturally as a human would on the phone. Identify yourself at the start of the call.`),t?.goal&&s.push(`## Call Goal
265
+ You are currently on a live phone call. Keep responses conversational and concise \u2014 you are speaking out loud, not writing text. Avoid markdown, bullet points, or long lists. Speak naturally as a human would on the phone. Identify yourself at the start of the call.`),t?.goal&&i.push(`## Call Goal
227
266
 
228
- ${t.goal}`),t?.context&&s.push(`## Call Context
267
+ ${t.goal}`),t?.context&&i.push(`## Call Context
229
268
 
230
- ${t.context}`);let i=await e.getHotTierPrompt(n.id,g.memory.hotBudgetTokens);if(i)s.push(i);else{let l=`agents/${n.id}`,c=await e.read(`${l}/memory.md`);c&&s.push(`## Your Memory
231
- ${c}`)}let a=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return s.push(`**Current date/time**: ${a} (Pacific Time)`),s.join(`
269
+ ${t.context}`);let o=await e.getHotTierPrompt(n.id,g.memory.hotBudgetTokens);if(o)i.push(o);else{let l=`agents/${n.id}`,c=await e.read(`${l}/memory.md`);c&&i.push(`## Your Memory
270
+ ${c}`)}let a=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return i.push(`**Current date/time**: ${a} (Pacific Time)`),i.join(`
232
271
 
233
272
  ---
234
273
 
235
- `)}var Wp=j(()=>{"use strict";Ne()});function Gp(n,e){let t=[];for(let s of n)if(s.role!=="system")if(s.role==="user")t.push({role:"user",content:s.content??""});else if(s.role==="assistant")if(s.tool_calls&&s.tool_calls.length>0){let r=[];s.content&&r.push({type:"text",text:s.content});for(let i of s.tool_calls)r.push({type:"tool_use",id:i.id,name:i.function.name,input:lv(i.function.arguments)});t.push({role:"assistant",content:r})}else t.push({role:"assistant",content:s.content??""});else s.role==="tool"&&t.push({role:"user",content:[{type:"tool_result",tool_use_id:s.tool_call_id??"",content:s.content??""}]});return(t.length===0||t[0].role!=="user")&&t.unshift({role:"user",content:"[Call connected]"}),{system:e,messages:t}}function Vp(n){if(!(!n||n.length===0))return n.map(e=>({name:e.function.name,description:e.function.description??"",input_schema:e.function.parameters??{type:"object",properties:{}}}))}function Yp(n,e,t){let s={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,delta:{content:e},finish_reason:null}]};return`data: ${JSON.stringify(s)}
274
+ `)}var aT=S(()=>{"use strict";ot()});function cT(n,e){let t=[];for(let i of n)if(i.role!=="system")if(i.role==="user")t.push({role:"user",content:i.content??""});else if(i.role==="assistant")if(i.tool_calls&&i.tool_calls.length>0){let r=[];i.content&&r.push({type:"text",text:i.content});for(let o of i.tool_calls)r.push({type:"tool_use",id:o.id,name:o.function.name,input:hj(o.function.arguments)});t.push({role:"assistant",content:r})}else t.push({role:"assistant",content:i.content??""});else i.role==="tool"&&t.push({role:"user",content:[{type:"tool_result",tool_use_id:i.tool_call_id??"",content:i.content??""}]});return(t.length===0||t[0].role!=="user")&&t.unshift({role:"user",content:"[Call connected]"}),{system:e,messages:t}}function lT(n){if(!(!n||n.length===0))return n.map(e=>({name:e.function.name,description:e.function.description??"",input_schema:e.function.parameters??{type:"object",properties:{}}}))}function uT(n,e,t){let i={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,delta:{content:e},finish_reason:null}]};return`data: ${JSON.stringify(i)}
236
275
 
237
- `}function _c(n,e,t="stop"){let s={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:{},finish_reason:t}]};return`data: ${JSON.stringify(s)}
276
+ `}function Zy(n,e,t="stop"){let i={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:{},finish_reason:t}]};return`data: ${JSON.stringify(i)}
238
277
 
239
278
  data: [DONE]
240
279
 
241
- `}function Jp(n,e,t){return{id:n,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}]}}function lv(n){if(!n)return{};try{return JSON.parse(n)}catch{return{}}}var zp=j(()=>{"use strict"});var Xp={};Ue(Xp,{VoiceAdapter:()=>vc});import{createServer as dv}from"node:http";import uv from"@anthropic-ai/sdk";import{randomUUID as Qp}from"node:crypto";function fv(n){return new Promise((e,t)=>{let s=[];n.on("data",r=>s.push(r)),n.on("end",()=>e(Buffer.concat(s).toString("utf-8"))),n.on("error",t)})}var Re,hv,vc,Zp=j(()=>{"use strict";M();Wp();zp();Ne();Re=k("voice-adapter"),hv=7200*1e3,vc=class{port;serverSecret;registry;memoryManager;httpServer;anthropic;sessions=new Map;sweepTimer;constructor(e,t,s,r){this.port=e,this.serverSecret=t,this.registry=s,this.memoryManager=r,this.anthropic=new uv}async start(){this.httpServer=dv((e,t)=>{this.handleRequest(e,t).catch(s=>{Re.error("Voice request handler error",{error:String(s)}),t.headersSent||(t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"})))})}),await new Promise(e=>{this.httpServer.listen(this.port,()=>e())}),this.sweepTimer=setInterval(()=>this.sweepStaleSessions(),1800*1e3),Re.info("Voice adapter started",{port:this.port})}stop(){this.sweepTimer&&clearInterval(this.sweepTimer),this.httpServer?.close(),Re.info("Voice adapter stopped")}sweepStaleSessions(){let e=Date.now(),t=0;for(let[s,r]of this.sessions)e-r.startedAt.getTime()>hv&&(this.sessions.delete(s),t++);t>0&&Re.info("Swept stale voice sessions",{count:t})}async handleRequest(e,t){if(!this.serverSecret){Re.error("Voice endpoint called but VAPI_SERVER_SECRET not configured \u2014 rejecting"),t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Server secret not configured"}));return}if((e.headers["x-vapi-secret"]??e.headers["server-secret"]??"")!==this.serverSecret){Re.warn("Voice request rejected \u2014 invalid server secret"),t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="GET"&&e.url==="/health"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"ok",activeCalls:this.sessions.size}));return}if(e.method!=="POST"||e.url!=="/v1/chat/completions"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}));return}let r=await fv(e),i;try{i=JSON.parse(r)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}let o=this.resolveAgentId(i);if(!o){Re.error("Could not resolve agent ID from Vapi request"),t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Cannot determine agent identity"}));return}let a=this.registry.get(o);if(!a){Re.error("Agent not found",{agentId:o}),t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:`Agent not found: ${o}`}));return}let l=i.call?.id??Qp();this.sessions.has(l)||(this.sessions.set(l,{callId:l,agentId:o,startedAt:new Date}),Re.info("Voice call session started",{callId:l,agentId:o}));let c=i.call?.metadata,d=await Hp(a,this.memoryManager,{goal:c?.goal,context:c?.context}),{system:u,messages:h}=Gp(i.messages,d),p=Vp(i.tools),m=a.model,f=`chatcmpl-${Qp()}`;if(i.stream===!1){let S=(await this.anthropic.messages.create({model:m,max_tokens:1024,system:u,messages:h,...p?{tools:p}:{}})).content.filter(_=>_.type==="text").map(_=>_.text).join("");t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(Jp(f,S,m)));return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{let y=this.anthropic.messages.stream({model:m,max_tokens:1024,system:u,messages:h,...p?{tools:p}:{}});for await(let w of y)if(w.type==="content_block_delta"){let S=w.delta;S.type==="text_delta"&&t.write(Yp(f,S.text??"",m))}t.writableEnded||t.write(_c(f,m))}catch(y){Re.error("Claude streaming error",{error:String(y),callId:l,agentId:o}),t.writableEnded||t.write(_c(f,m,"error"))}t.end()}resolveAgentId(e){let t=e.assistant?.metadata;if(t?.hive_agent_id)return t.hive_agent_id;let s=e.assistant?.id;if(s&&g.voice.assistants[s])return g.voice.assistants[s];let r=e.call?.metadata;if(r?.hive_agent_id)return r.hive_agent_id}}});ls();xi();import{existsSync as Tc,mkdirSync as pv,watch as mv}from"node:fs";import{resolve as em}from"node:path";import{MongoClient as gv}from"mongodb";M();import{existsSync as Bc,readFileSync as Uc,readdirSync as mm,statSync as xv,writeFileSync as Ov,mkdirSync as Mv}from"node:fs";import{resolve as jc,join as Lv}from"node:path";import{createHash as gm}from"node:crypto";var Oi=k("integrity");function qc(n,e){let t=jc(e,"installed-snapshot.json");if(!Bc(t))return Oi.warn("No installed-snapshot.json \u2014 skipping integrity check (first install?)"),{ok:!0,warnings:[]};let s=JSON.parse(Uc(t,"utf-8"));if(!Array.isArray(s))return{ok:!1,warnings:[`installed-snapshot.json is malformed (expected array, got ${typeof s})`]};let r=s,i=[];for(let o of r){let a=jc(n,o.path);if(!Bc(a)){i.push(`missing: ${o.path}`);continue}let l=Uc(a);gm("sha256").update(l).digest("hex")!==o.hash&&i.push(`modified: ${o.path}`)}if(i.length>0)throw Oi.error("Package integrity check FAILED \u2014 refusing to start",{drift:i}),new Error(`Package integrity check failed. ${i.length} file(s) have been modified or are missing:
242
- `+i.map(o=>` - ${o}`).join(`
280
+ `}function dT(n,e,t){return{id:n,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}]}}function hj(n){if(!n)return{};try{return JSON.parse(n)}catch{return{}}}var fT=S(()=>{"use strict"});var mT={};we(mT,{VoiceAdapter:()=>Ky});import{createServer as gj}from"node:http";import yj from"@anthropic-ai/sdk";import{randomUUID as pT}from"node:crypto";function _j(n){return new Promise((e,t)=>{let i=[];n.on("data",r=>i.push(r)),n.on("end",()=>e(Buffer.concat(i).toString("utf-8"))),n.on("error",t)})}var _t,vj,Ky,hT=S(()=>{"use strict";R();aT();fT();ot();_t=$("voice-adapter"),vj=7200*1e3,Ky=class{port;serverSecret;registry;memoryManager;httpServer;anthropic;sessions=new Map;sweepTimer;constructor(e,t,i,r){this.port=e,this.serverSecret=t,this.registry=i,this.memoryManager=r,this.anthropic=new yj}async start(){this.httpServer=gj((e,t)=>{this.handleRequest(e,t).catch(i=>{_t.error("Voice request handler error",{error:String(i)}),t.headersSent||(t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"})))})}),await new Promise(e=>{this.httpServer.listen(this.port,()=>e())}),this.sweepTimer=setInterval(()=>this.sweepStaleSessions(),1800*1e3),_t.info("Voice adapter started",{port:this.port})}stop(){this.sweepTimer&&clearInterval(this.sweepTimer),this.httpServer?.close(),_t.info("Voice adapter stopped")}sweepStaleSessions(){let e=Date.now(),t=0;for(let[i,r]of this.sessions)e-r.startedAt.getTime()>vj&&(this.sessions.delete(i),t++);t>0&&_t.info("Swept stale voice sessions",{count:t})}async handleRequest(e,t){if(!this.serverSecret){_t.error("Voice endpoint called but VAPI_SERVER_SECRET not configured \u2014 rejecting"),t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Server secret not configured"}));return}if((e.headers["x-vapi-secret"]??e.headers["server-secret"]??"")!==this.serverSecret){_t.warn("Voice request rejected \u2014 invalid server secret"),t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="GET"&&e.url==="/health"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"ok",activeCalls:this.sessions.size}));return}if(e.method!=="POST"||e.url!=="/v1/chat/completions"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}));return}let r=await _j(e),o;try{o=JSON.parse(r)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}let s=this.resolveAgentId(o);if(!s){_t.error("Could not resolve agent ID from Vapi request"),t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Cannot determine agent identity"}));return}let a=this.registry.get(s);if(!a){_t.error("Agent not found",{agentId:s}),t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:`Agent not found: ${s}`}));return}let l=o.call?.id??pT();this.sessions.has(l)||(this.sessions.set(l,{callId:l,agentId:s,startedAt:new Date}),_t.info("Voice call session started",{callId:l,agentId:s}));let c=o.call?.metadata,u=await sT(a,this.memoryManager,{goal:c?.goal,context:c?.context}),{system:d,messages:f}=cT(o.messages,u),p=lT(o.tools),h=a.model,m=`chatcmpl-${pT()}`;if(o.stream===!1){let b=(await this.anthropic.messages.create({model:h,max_tokens:1024,system:d,messages:f,...p?{tools:p}:{}})).content.filter(k=>k.type==="text").map(k=>k.text).join("");t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(dT(m,b,h)));return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{let y=this.anthropic.messages.stream({model:h,max_tokens:1024,system:d,messages:f,...p?{tools:p}:{}});for await(let _ of y)if(_.type==="content_block_delta"){let b=_.delta;b.type==="text_delta"&&t.write(uT(m,b.text??"",h))}t.writableEnded||t.write(Zy(m,h))}catch(y){_t.error("Claude streaming error",{error:String(y),callId:l,agentId:s}),t.writableEnded||t.write(Zy(m,h,"error"))}t.end()}resolveAgentId(e){let t=e.assistant?.metadata;if(t?.hive_agent_id)return t.hive_agent_id;let i=e.assistant?.id;if(i&&g.voice.assistants[i])return g.voice.assistants[i];let r=e.call?.metadata;if(r?.hive_agent_id)return r.hive_agent_id}}});Wr();Bl();import{existsSync as Vy,mkdirSync as wj,watch as bj}from"node:fs";import{resolve as gT}from"node:path";import{MongoClient as kj}from"mongodb";R();import{existsSync as av,readFileSync as cv,readdirSync as DT,statSync as Lj,writeFileSync as zj,mkdirSync as jj}from"node:fs";import{resolve as lv,join as Rj}from"node:path";import{createHash as PT}from"node:crypto";var Fl=$("integrity");function uv(n,e){let t=lv(e,"installed-snapshot.json");if(!av(t))return Fl.warn("No installed-snapshot.json \u2014 skipping integrity check (first install?)"),{ok:!0,warnings:[]};let i=JSON.parse(cv(t,"utf-8"));if(!Array.isArray(i))return{ok:!1,warnings:[`installed-snapshot.json is malformed (expected array, got ${typeof i})`]};let r=i,o=[];for(let s of r){let a=lv(n,s.path);if(!av(a)){o.push(`missing: ${s.path}`);continue}let l=cv(a);PT("sha256").update(l).digest("hex")!==s.hash&&o.push(`modified: ${s.path}`)}if(o.length>0)throw Fl.error("Package integrity check FAILED \u2014 refusing to start",{drift:o}),new Error(`Package integrity check failed. ${o.length} file(s) have been modified or are missing:
281
+ `+o.map(s=>` - ${s}`).join(`
243
282
  `)+`
244
- Reinstall with: npm install @keepur/hive@<version>`);return{ok:!0,warnings:[]}}function Fc(n){let e=["skills","plugins","workflow","data","agents","logs",".hive",".hive-state",".env","hive.yaml","hive-","beekeeper.yaml",".hive-generated.json"];try{let t=mm(n),s=[];for(let r of t)e.some(i=>r.startsWith(i))||s.push(r);s.length>0&&Oi.warn("Unexpected files in instance directory",{files:s})}catch{}}M();import{existsSync as Mi,readFileSync as ym,writeFileSync as wm,mkdirSync as Sm}from"node:fs";import{resolve as Di}from"node:path";var Kc=k("upgrade-notice");function Hc(n,e){let t=Di(n,"upgrade-notice-emitted");if(Mi(t))return;let s=Di(n,"previous-snapshot.json");if(Mi(s))try{let r=JSON.parse(ym(s,"utf-8")),i=[];for(let l of r)if(typeof l.path=="string"&&l.path.startsWith("skills/")&&l.path.endsWith("SKILL.md")){let c=l.path.match(/^skills\/([^/]+)\//);c&&!Mi(Di(e,c[1]))&&i.push(c[1])}if(i.length===0)return;let o=[...new Set(i)],a=["","=".repeat(72),"Your previous version of hive shipped the following skills in its tarball:",...o.map(l=>` - ${l}`),"","These are no longer part of the hive core package. You can re-install any of","them from the default Keepur registry with:",""," hive skill add <name>","","Agent-authored skills you or your agents wrote on this hive are unaffected and","continue to work. This notice only appears once.","=".repeat(72),""].join(`
245
- `);Kc.info(a),Sm(n,{recursive:!0}),wm(t,new Date().toISOString())}catch(r){Kc.warn("Failed to check upgrade notice",{error:String(r)})}}Ne();M();M();ya();var X={maxConcurrent:3,timeoutMs:3e5,budgetUsd:10,maxTurns:200,icon:"",keywords:[],passiveChannels:[],delegatePrompts:{},schedule:[],coreServers:["memory","structured-memory","keychain","event-bus","contacts"],delegateServers:[]};function Wu(n,e){return{id:n._id,name:n.name,aliases:n.aliases??[],model:n.model,channels:n.channels??[],homeBase:n.homeBase,catches:n.catches,passiveChannels:n.passiveChannels??X.passiveChannels,keywords:n.keywords??X.keywords,isDefault:n.isDefault??!1,schedule:n.schedule??X.schedule,budgetUsd:n.budgetUsd??X.budgetUsd,maxTurns:n.maxTurns??X.maxTurns,icon:n.icon??X.icon,slackBot:n.slackBot,coreServers:n.coreServers??[...X.coreServers],delegateServers:n.delegateServers??[...X.delegateServers],plugins:n.plugins,maxConcurrent:n.maxConcurrent??X.maxConcurrent,timeoutMs:n.timeoutMs??X.timeoutMs,betas:n.betas,metadata:n.metadata,disabled:n.disabled??!1,subscribe:n.subscribe??[],resourceTiers:n.resourceTiers,delegatePrompts:n.delegatePrompts??X.delegatePrompts,soul:n.soul??"",systemPrompt:n.systemPrompt??"",archetype:n.archetype,title:n.title,archetypeConfig:n.archetypeConfig,autonomy:Bu(e,n.autonomy)}}Ne();gr();gr();import{statSync as p0}from"node:fs";import{normalize as Yu,resolve as Ju}from"node:path";var zu=new Set(["linear","github","clickup"]);function Xu(n){if(!n||typeof n!="object")throw new Error("software-engineer archetypeConfig must be an object");let e=n;if(typeof e.workshop!="string"||!e.workshop.startsWith("/"))throw new Error("workshop must be an absolute path");let t=Yu(e.workshop);Qu(t,"workshop");let s=e.workspaces??[];if(!Array.isArray(s))throw new Error("workspaces must be an array");let r=new Set,i=s.map((o,a)=>{if(!o||typeof o!="object")throw new Error(`workspaces[${a}]: must be an object`);let l=o;if(typeof l.name!="string"||l.name.length===0)throw new Error(`workspaces[${a}]: name is required`);if(r.has(l.name))throw new Error(`workspaces[${a}]: duplicate workspace name "${l.name}"`);if(r.add(l.name),typeof l.path!="string"||!l.path.startsWith("/"))throw new Error(`workspaces[${a}] (${l.name}): path must be an absolute path`);let c=Yu(l.path);Qu(c,`workspaces[${a}] (${l.name})`);let d=Ju(c),u=Ju(t);if(!d.startsWith(u+"/"))throw new Error(`workspaces[${a}] (${l.name}): path must be inside workshop (${t}), got ${c}`);if(!l.tracker||typeof l.tracker!="object")throw new Error(`workspaces[${a}] (${l.name}): tracker is required`);let h=l.tracker;if(typeof h.type!="string"||!zu.has(h.type))throw new Error(`workspaces[${a}] (${l.name}): tracker.type must be one of: ${[...zu].join(", ")}`);return m0(h,a,l.name),{name:l.name,path:c,tracker:h,...l.primary===!0?{primary:!0}:{}}});return{workshop:t,workspaces:i}}function Qu(n,e){let t;try{t=p0(n)}catch{throw new Error(`${e}: path does not exist: ${n}`)}if(!t.isDirectory())throw new Error(`${e}: path is not a directory: ${n}`)}function m0(n,e,t){switch(n.type){case"linear":if(typeof n.project!="string"||n.project.length===0)throw new Error(`workspaces[${e}] (${t}): linear tracker requires project`);break;case"github":if(typeof n.repo!="string"||n.repo.length===0)throw new Error(`workspaces[${e}] (${t}): github tracker requires repo`);break;case"clickup":if(typeof n.list!="string"||n.list.length===0)throw new Error(`workspaces[${e}] (${t}): clickup tracker requires list`);break}}function Zu(n){let e=n.archetypeConfig,t=n.agentConfig.title||n.agentConfig.name,s=[];s.push(`# Software Engineer
283
+ Reinstall with: npm install @keepur/hive@<version>`);return{ok:!0,warnings:[]}}function dv(n){let e=["skills","plugins","workflow","data","agents","logs",".hive",".hive-state",".env","hive.yaml","hive-","beekeeper.yaml",".hive-generated.json"];try{let t=DT(n),i=[];for(let r of t)e.some(o=>r.startsWith(o))||i.push(r);i.length>0&&Fl.warn("Unexpected files in instance directory",{files:i})}catch{}}R();import{existsSync as ql,readFileSync as MT,writeFileSync as LT,mkdirSync as zT}from"node:fs";import{resolve as Zl}from"node:path";var fv=$("upgrade-notice");function pv(n,e){let t=Zl(n,"upgrade-notice-emitted");if(ql(t))return;let i=Zl(n,"previous-snapshot.json");if(ql(i))try{let r=JSON.parse(MT(i,"utf-8")),o=[];for(let l of r)if(typeof l.path=="string"&&l.path.startsWith("skills/")&&l.path.endsWith("SKILL.md")){let c=l.path.match(/^skills\/([^/]+)\//);c&&!ql(Zl(e,c[1]))&&o.push(c[1])}if(o.length===0)return;let s=[...new Set(o)],a=["","=".repeat(72),"Your previous version of hive shipped the following skills in its tarball:",...s.map(l=>` - ${l}`),"","These are no longer part of the hive core package. You can re-install any of","them from the default Keepur registry with:",""," hive skill add <name>","","Agent-authored skills you or your agents wrote on this hive are unaffected and","continue to work. This notice only appears once.","=".repeat(72),""].join(`
284
+ `);fv.info(a),zT(n,{recursive:!0}),LT(t,new Date().toISOString())}catch(r){fv.warn("Failed to check upgrade notice",{error:String(r)})}}ot();R();R();Td();var me={maxConcurrent:3,timeoutMs:3e5,budgetUsd:10,maxTurns:200,icon:"",keywords:[],passiveChannels:[],delegatePrompts:{},schedule:[],coreServers:["memory","structured-memory","keychain","event-bus","contacts"],delegateServers:[]};function mb(n,e){return{id:n._id,name:n.name,aliases:n.aliases??[],model:n.model,channels:n.channels??[],homeBase:n.homeBase,catches:n.catches,passiveChannels:n.passiveChannels??me.passiveChannels,keywords:n.keywords??me.keywords,isDefault:n.isDefault??!1,schedule:n.schedule??me.schedule,budgetUsd:n.budgetUsd??me.budgetUsd,maxTurns:n.maxTurns??me.maxTurns,icon:n.icon??me.icon,slackBot:n.slackBot,coreServers:n.coreServers??[...me.coreServers],delegateServers:n.delegateServers??[...me.delegateServers],plugins:n.plugins,maxConcurrent:n.maxConcurrent??me.maxConcurrent,timeoutMs:n.timeoutMs??me.timeoutMs,betas:n.betas,metadata:n.metadata,disabled:n.disabled??!1,subscribe:n.subscribe??[],resourceTiers:n.resourceTiers,delegatePrompts:n.delegatePrompts??me.delegatePrompts,soul:n.soul??"",systemPrompt:n.systemPrompt??"",archetype:n.archetype,title:n.title,archetypeConfig:n.archetypeConfig,autonomy:ab(e,n.autonomy)}}ot();Ms();Ms();import{statSync as NN}from"node:fs";import{normalize as yb,resolve as vb}from"node:path";var _b=new Set(["linear","github","clickup"]);function bb(n){if(!n||typeof n!="object")throw new Error("software-engineer archetypeConfig must be an object");let e=n;if(typeof e.workshop!="string"||!e.workshop.startsWith("/"))throw new Error("workshop must be an absolute path");let t=yb(e.workshop);wb(t,"workshop");let i=e.workspaces??[];if(!Array.isArray(i))throw new Error("workspaces must be an array");let r=new Set,o=i.map((s,a)=>{if(!s||typeof s!="object")throw new Error(`workspaces[${a}]: must be an object`);let l=s;if(typeof l.name!="string"||l.name.length===0)throw new Error(`workspaces[${a}]: name is required`);if(r.has(l.name))throw new Error(`workspaces[${a}]: duplicate workspace name "${l.name}"`);if(r.add(l.name),typeof l.path!="string"||!l.path.startsWith("/"))throw new Error(`workspaces[${a}] (${l.name}): path must be an absolute path`);let c=yb(l.path);wb(c,`workspaces[${a}] (${l.name})`);let u=vb(c),d=vb(t);if(!u.startsWith(d+"/"))throw new Error(`workspaces[${a}] (${l.name}): path must be inside workshop (${t}), got ${c}`);if(!l.tracker||typeof l.tracker!="object")throw new Error(`workspaces[${a}] (${l.name}): tracker is required`);let f=l.tracker;if(typeof f.type!="string"||!_b.has(f.type))throw new Error(`workspaces[${a}] (${l.name}): tracker.type must be one of: ${[..._b].join(", ")}`);return DN(f,a,l.name),{name:l.name,path:c,tracker:f,...l.primary===!0?{primary:!0}:{}}});return{workshop:t,workspaces:o}}function wb(n,e){let t;try{t=NN(n)}catch{throw new Error(`${e}: path does not exist: ${n}`)}if(!t.isDirectory())throw new Error(`${e}: path is not a directory: ${n}`)}function DN(n,e,t){switch(n.type){case"linear":if(typeof n.project!="string"||n.project.length===0)throw new Error(`workspaces[${e}] (${t}): linear tracker requires project`);break;case"github":if(typeof n.repo!="string"||n.repo.length===0)throw new Error(`workspaces[${e}] (${t}): github tracker requires repo`);break;case"clickup":if(typeof n.list!="string"||n.list.length===0)throw new Error(`workspaces[${e}] (${t}): clickup tracker requires list`);break}}function kb(n){let e=n.archetypeConfig,t=n.agentConfig.title||n.agentConfig.name,i=[];i.push(`# Software Engineer
246
285
 
247
286
  You are a software engineer. Your title is ${t}. Your discipline is owning codebases and shipping production code through disciplined delivery.`);let r=[`Your workshop is \`${e.workshop}\`. This is your working directory.`];if(e.workspaces.length>0){r.push(`
248
- Workspaces:`);for(let i of e.workspaces){let o=g0(i.tracker),a=i.primary?" (primary)":"";r.push(`- **${i.name}**${a}: \`${i.path}\` \u2014 tracker: ${o}`)}}else r.push(`
249
- No workspaces configured yet. You have full agency over your entire workshop.`);return s.push(r.join(`
250
- `)),e.workspaces.length>0&&s.push("## Workshop vs Workspace Policy\n\n**Workshop** (outside workspaces): You have full agency. Read, write, create, edit freely. This is your prototyping space, scratch area, and coordination point.\n\n**Workspaces**: Delegate-only. You MUST NOT directly edit, write, or create files inside a workspace. All code changes inside workspaces flow through `code_task`. This preserves the spec \u2192 plan \u2192 PR \u2192 CI discipline.\n\nIf you attempt to Edit or Write inside a workspace, the tool will be blocked with an error. This is intentional. Use `code_task` instead.\n\nInside workspaces, ALL execution \u2014 including git, npm, builds, test runs \u2014 flows through `code_task`. Your working directory is your workshop; treat all relative file paths accordingly. Reference workspace source only via absolute paths or through `code_task`."),s.push(`## Workflow: Ticket as Spec
287
+ Workspaces:`);for(let o of e.workspaces){let s=PN(o.tracker),a=o.primary?" (primary)":"";r.push(`- **${o.name}**${a}: \`${o.path}\` \u2014 tracker: ${s}`)}}else r.push(`
288
+ No workspaces configured yet. You have full agency over your entire workshop.`);return i.push(r.join(`
289
+ `)),e.workspaces.length>0&&i.push("## Workshop vs Workspace Policy\n\n**Workshop** (outside workspaces): You have full agency. Read, write, create, edit freely. This is your prototyping space, scratch area, and coordination point.\n\n**Workspaces**: Delegate-only. You MUST NOT directly edit, write, or create files inside a workspace. All code changes inside workspaces flow through `code_task`. This preserves the spec \u2192 plan \u2192 PR \u2192 CI discipline.\n\nIf you attempt to Edit or Write inside a workspace, the tool will be blocked with an error. This is intentional. Use `code_task` instead.\n\nInside workspaces, ALL execution \u2014 including git, npm, builds, test runs \u2014 flows through `code_task`. Your working directory is your workshop; treat all relative file paths accordingly. Reference workspace source only via absolute paths or through `code_task`."),i.push(`## Workflow: Ticket as Spec
251
290
 
252
291
  Every piece of work starts with a ticket. The ticket description IS the spec. Write ticket descriptions that a developer can implement from \u2014 problem statement, approach, and acceptance criteria.
253
292
 
254
- Never start coding without a filed ticket. Never delegate to \`code_task\` without a ticket reference.`),s.push(`## Delivery Primitives
293
+ Never start coding without a filed ticket. Never delegate to \`code_task\` without a ticket reference.`),i.push(`## Delivery Primitives
255
294
 
256
295
  You have four delivery primitives that compose into your workflow:
257
296
 
258
297
  1. **Brainstorm** \u2014 Explore intent, constraints, and approaches with the requester. Ask clarifying questions. Reach alignment before filing a ticket.
259
298
  2. **File Ticket** \u2014 Create a ticket in the workspace's tracker with a complete spec (problem, approach, acceptance criteria). The description must be implementable by someone who wasn't in the brainstorm.
260
299
  3. **Code Task** \u2014 Delegate implementation to \`code_task\` with the ticket context. Paste the ticket body into the prompt so the inner session has the full spec inline. Use \`code_status\` to check progress. If the session reports NEEDS_CONTEXT or BLOCKED, respond via \`code_respond\` with your answer and context.
261
- 4. **Review** \u2014 Verify the work meets the spec. Check the PR and CI status, then comment on the tracker ticket with the result.`),s.push("## Review Recipe\n\nWhen reviewing completed work:\n1. Check PR state: `gh pr view <number>`\n2. Check CI status: `gh pr checks <number>`\n3. Comment on the tracker ticket with the PR URL and status summary (use the workspace's tracker MCP \u2014 e.g., `linear:create_comment`).\n\nFor workspaces using Linear for tickets and GitHub for code (split-tracker), use `gh` for PR/CI reads and the Linear MCP for ticket comments."),s.push(`## Definition of Done
300
+ 4. **Review** \u2014 Verify the work meets the spec. Check the PR and CI status, then comment on the tracker ticket with the result.`),i.push("## Review Recipe\n\nWhen reviewing completed work:\n1. Check PR state: `gh pr view <number>`\n2. Check CI status: `gh pr checks <number>`\n3. Comment on the tracker ticket with the PR URL and status summary (use the workspace's tracker MCP \u2014 e.g., `linear:create_comment`).\n\nFor workspaces using Linear for tickets and GitHub for code (split-tracker), use `gh` for PR/CI reads and the Linear MCP for ticket comments."),i.push(`## Definition of Done
262
301
 
263
302
  A task is done when ALL of these are true:
264
303
  - Ticket filed with complete spec
265
304
  - \`code_task\` completed successfully
266
305
  - PR merged and CI green
267
- - Ticket closed in the tracker`),s.push(`## Guardrails
306
+ - Ticket closed in the tracker`),i.push(`## Guardrails
268
307
 
269
308
  - **Never** directly edit files inside a workspace \u2014 always via \`code_task\`
270
309
  - **Never** start implementation without a filed ticket
271
310
  - **Never** delegate to \`code_task\` without the ticket context in the prompt
272
311
  - **Always** verify PR + CI status before closing a ticket
273
- - **Always** file a ticket before delegating work`),s.join(`
312
+ - **Always** file a ticket before delegating work`),i.join(`
274
313
 
275
- `)}function g0(n){switch(n.type){case"linear":return`Linear (project: ${n.project})`;case"github":return`GitHub Issues (repo: ${n.repo})`;case"clickup":return`ClickUp (list: ${n.list})`;default:return n.type}}import{resolve as y0}from"node:path";import{normalize as eh,resolve as th}from"node:path";function ba(n){if(typeof n!="string"||!n.startsWith("/"))throw new Error(`claudeProjectSlug: path must be absolute, got ${String(n)}`);return n.replace(/\/+$/,"").replace(/[/_.]/g,"-").replace(/-+/g,"-")}function sh(n,e){let t=eh(th(n));return e.workspaces.find(s=>{let r=eh(th(s.path));return t===r||t.startsWith(r+"/")})}function nh(n){return ba(n.workshop)}function rh(n){return ba(n.path)}var w0=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function S0(n,e){return n==="NotebookEdit"?e.notebook_path??e.file_path:e.file_path}function ih(n){let e=n.archetypeConfig;return e.workspaces.length===0?[]:[{hooks:[async t=>{try{let s=t,r=s.tool_name??"";if(!w0.has(r))return{continue:!0};let i=S0(r,s.tool_input??{});if(typeof i!="string"||i.length===0)return{continue:!0};let o=y0(e.workshop,i),a=sh(o,e);return a?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${r} blocked: \`${o}\` is inside workspace \`${a.name}\`. Code changes inside workspaces flow through \`code_task\`, not direct edits \u2014 this preserves the spec \u2192 plan \u2192 PR \u2192 CI discipline. If you're drafting a prototype, work inside the workshop outside any workspace. If you're ready to implement against a ticket, use \`code_task\` with the ticket ID.`}}:{continue:!0}}catch(s){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Software-engineer hook internal error: ${String(s)}. All file mutations blocked until the archetype is fixed.`}}}}]}]}import{homedir as k0}from"node:os";import{join as oh}from"node:path";function ah(n){let e=n.archetypeConfig,t=k0(),s=[];s.push({id:"workshop",backing:"filesystem",dir:oh(t,".claude/projects",nh(e),"memory")});for(let r of e.workspaces)s.push({id:`workspace:${r.name}`,backing:"filesystem",dir:oh(t,".claude/projects",rh(r),"memory")});return s}function ch(n){return{cwd:n.archetypeConfig.workshop,settingSources:["project"]}}Vu({id:"software-engineer",description:"Owns codebases and ships production code through disciplined delivery (ticket \u2192 spec \u2192 PR \u2192 CI \u2192 close).",whenToUse:"Pick this when the agent's core job is writing, reviewing, or shipping production code. For product strategists, marketers, or anyone where code is incidental, use a plain agent.",configSchema:{workshop:{type:"string",required:!0,description:"Absolute filesystem path \u2014 the engineer's bounded root directory (e.g. /Users/you/dev)."},workspaces:{type:"array",required:!1,description:"Registered codebases inside the workshop. Do NOT prompt for these at creation time \u2014 workspace registration is a separate admin flow. Start with an empty array."}},validateConfig:Xu,systemPromptCard:Zu,preToolUseHooks:ih,memoryScopes:ah,sessionOptions:ch});var pe=k("agent-registry"),lh=3e4,yr=class{agents=new Map;originToAgent=new Map;disabledAgents=[];agentDefs;changeStream=null;pollTimer=null;lastPollTime=new Date(0);onReload;constructor(e,t){this.agentDefs=e,this.onReload=t}async load(){let e=await this.agentDefs.find().toArray(),t=new Set(this.agents.keys()),s=new Set,r=[],i=[],o=[],a=[];for(let l of e){let c=Wu(l,g.autonomy);if(s.add(c.id),c.disabled){a.push(c),this.agents.has(c.id)&&(this.agents.delete(c.id),o.push(c.id),pe.info("Disabled agent removed from active map",{id:c.id}));continue}if(c.archetype){let d=mr(c.archetype);if(!d)pe.warn("Unknown archetype \u2014 loading agent as unstructured",{id:c.id,archetype:c.archetype}),c.archetype=void 0,c.archetypeConfig=void 0;else try{c.archetypeConfig=d.validateConfig(c.archetypeConfig)}catch(u){pe.error("Archetype config validation failed \u2014 agent will not load",{id:c.id,archetype:c.archetype,error:String(u)}),this.agents.has(c.id)&&(this.agents.delete(c.id),o.push(c.id),pe.warn("Evicted previously-loaded agent due to archetype validation failure",{id:c.id}));continue}}t.has(c.id)?i.push(c.id):r.push(c.id),this.agents.set(c.id,c),pe.info("Loaded agent",{id:c.id,name:c.name})}this.disabledAgents=a;for(let l of t)s.has(l)||(this.agents.delete(l),o.push(l),pe.info("Removed agent",{id:l}));return this.lastPollTime=new Date,this.rebuildOriginIndex(),{added:r,updated:i,removed:o}}async startWatching(){try{this.changeStream=this.agentDefs.watch([],{fullDocument:"updateLookup"}),this.changeStream.on("change",()=>{pe.info("Agent definition changed (change stream), triggering reload"),this.onReload?.()}),this.changeStream.on("error",e=>{pe.warn("Change stream error, falling back to polling",{error:String(e)}),this.changeStream=null,this.startPolling()}),pe.info("Agent registry watching via change stream")}catch{pe.info("Change stream not available, using polling fallback"),this.startPolling()}}startPolling(){this.pollTimer=setInterval(async()=>{try{let e=await this.agentDefs.countDocuments({updatedAt:{$gt:this.lastPollTime}});e>0&&(pe.info("Agent definitions changed (poll), triggering reload",{changed:e}),this.onReload?.())}catch(e){pe.error("Poll check failed",{error:String(e)})}},lh),pe.info("Agent registry watching via polling",{intervalMs:lh})}rebuildOriginIndex(){this.originToAgent.clear();let e=[...this.agents.values()].sort((t,s)=>t.id.localeCompare(s.id));for(let t of e)for(let s of t.catches??[]){if(this.originToAgent.has(s)){pe.error("Origin conflict \u2014 first sorted agent wins",{origin:s,winner:this.originToAgent.get(s),loser:t.id});continue}this.originToAgent.set(s,t.id)}}stopWatching(){this.changeStream&&(this.changeStream.close().catch(()=>{}),this.changeStream=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}get(e){return this.agents.get(e)}getAll(){return Array.from(this.agents.values())}async getAllDefinitions(){return this.agentDefs.find().toArray()}listIds(){return Array.from(this.agents.keys())}findByChannel(e){return this.getAll().find(t=>!t.disabled&&t.channels.includes(e))}findByOrigin(e){let t=this.originToAgent.get(e);return t?this.agents.get(t):void 0}isPassiveChannel(e){return this.getAll().some(t=>!t.disabled&&t.passiveChannels.includes(e))}findByKeyword(e){let t=e.toLowerCase();return this.getAll().find(s=>!s.disabled&&s.keywords.some(r=>{let i=r.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${i}\\b`).test(t)}))}findByName(e){return this.findAllByName(e)[0]}findAllByName(e){return this.getAll().filter(t=>{if(t.disabled)return!1;if(this.matchesName(t.name,e))return!0;if(t.name.includes(" ")){let s=t.name.split(" ")[0];if(this.matchesName(s,e))return!0}for(let s of t.aliases)if(this.matchesName(s,e))return!0;return!1})}matchesName(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|hey\\s+|@)${s}\\b|\\b${s}[,:]`,"i").test(t)}getDefault(){return this.getAll().find(e=>!e.disabled&&e.isDefault)}getDisabled(){return this.disabledAgents}getSubscriberMap(){let e={};for(let t of this.getAll())if(!t.disabled)for(let s of t.subscribe??[]){let r=s.includes(":")?s.split(":")[0]:s;e[r]||(e[r]=[]),e[r].includes(t.id)||e[r].push(t.id)}return e}};M();La();Vs();M();Ne();import{query as sk}from"@anthropic-ai/claude-agent-sdk";var Ys=k("model-router"),nk={haiku:{timeoutMs:12e4,maxTurns:20,budgetUsd:1},sonnet:{timeoutMs:3e5,maxTurns:50,budgetUsd:5},opus:{timeoutMs:6e5,maxTurns:200,budgetUsd:50}};function Ar(n,e){let t=nk[n],s=e?.[n];return s?{timeoutMs:s.timeoutMs??t.timeoutMs,maxTurns:s.maxTurns??t.maxTurns,budgetUsd:s.budgetUsd??t.budgetUsd}:{...t}}var ht={haiku:0,sonnet:1,opus:2},Cr={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-7"};function rk(n){return n.includes("opus")?"opus":n.includes("haiku")?"haiku":"sonnet"}var ik=`You are a model router. Your job is to classify the complexity of a user message and decide which AI model tier should handle it.
314
+ `)}function PN(n){switch(n.type){case"linear":return`Linear (project: ${n.project})`;case"github":return`GitHub Issues (repo: ${n.repo})`;case"clickup":return`ClickUp (list: ${n.list})`;default:return n.type}}import{resolve as MN}from"node:path";import{normalize as Sb,resolve as $b}from"node:path";function Cd(n){if(typeof n!="string"||!n.startsWith("/"))throw new Error(`claudeProjectSlug: path must be absolute, got ${String(n)}`);return n.replace(/\/+$/,"").replace(/[/_.]/g,"-").replace(/-+/g,"-")}function xb(n,e){let t=Sb($b(n));return e.workspaces.find(i=>{let r=Sb($b(i.path));return t===r||t.startsWith(r+"/")})}function Ib(n){return Cd(n.workshop)}function Tb(n){return Cd(n.path)}var LN=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function zN(n,e){return n==="NotebookEdit"?e.notebook_path??e.file_path:e.file_path}function Eb(n){let e=n.archetypeConfig;return e.workspaces.length===0?[]:[{hooks:[async t=>{try{let i=t,r=i.tool_name??"";if(!LN.has(r))return{continue:!0};let o=zN(r,i.tool_input??{});if(typeof o!="string"||o.length===0)return{continue:!0};let s=MN(e.workshop,o),a=xb(s,e);return a?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${r} blocked: \`${s}\` is inside workspace \`${a.name}\`. Code changes inside workspaces flow through \`code_task\`, not direct edits \u2014 this preserves the spec \u2192 plan \u2192 PR \u2192 CI discipline. If you're drafting a prototype, work inside the workshop outside any workspace. If you're ready to implement against a ticket, use \`code_task\` with the ticket ID.`}}:{continue:!0}}catch(i){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Software-engineer hook internal error: ${String(i)}. All file mutations blocked until the archetype is fixed.`}}}}]}]}import{homedir as jN}from"node:os";import{join as Ab}from"node:path";function Ob(n){let e=n.archetypeConfig,t=jN(),i=[];i.push({id:"workshop",backing:"filesystem",dir:Ab(t,".claude/projects",Ib(e),"memory")});for(let r of e.workspaces)i.push({id:`workspace:${r.name}`,backing:"filesystem",dir:Ab(t,".claude/projects",Tb(r),"memory")});return i}function Cb(n){return{cwd:n.archetypeConfig.workshop,settingSources:["project"]}}gb({id:"software-engineer",description:"Owns codebases and ships production code through disciplined delivery (ticket \u2192 spec \u2192 PR \u2192 CI \u2192 close).",whenToUse:"Pick this when the agent's core job is writing, reviewing, or shipping production code. For product strategists, marketers, or anyone where code is incidental, use a plain agent.",configSchema:{workshop:{type:"string",required:!0,description:"Absolute filesystem path \u2014 the engineer's bounded root directory (e.g. /Users/you/dev)."},workspaces:{type:"array",required:!1,description:"Registered codebases inside the workshop. Do NOT prompt for these at creation time \u2014 workspace registration is a separate admin flow. Start with an empty array."}},validateConfig:bb,systemPromptCard:kb,preToolUseHooks:Eb,memoryScopes:Ob,sessionOptions:Cb});var Ce=$("agent-registry"),Nb=3e4,Ls=class{agents=new Map;originToAgent=new Map;disabledAgents=[];agentDefs;changeStream=null;pollTimer=null;lastPollTime=new Date(0);onChangeDetected;postReloadHandlers=[];constructor(e,t){this.agentDefs=e,this.onChangeDetected=t}onPostReload(e){return this.postReloadHandlers.push(e),()=>{let t=this.postReloadHandlers.indexOf(e);t>=0&&this.postReloadHandlers.splice(t,1)}}firePostReload(){for(let e of this.postReloadHandlers)try{e()}catch(t){Ce.warn("onPostReload handler threw",{error:String(t)})}}async load(){let e=await this.agentDefs.find().toArray(),t=new Set(this.agents.keys()),i=new Set,r=[],o=[],s=[],a=[];for(let l of e){let c=mb(l,g.autonomy);if(i.add(c.id),c.disabled){a.push(c),this.agents.has(c.id)&&(this.agents.delete(c.id),s.push(c.id),Ce.info("Disabled agent removed from active map",{id:c.id}));continue}if(c.archetype){let u=Ps(c.archetype);if(!u)Ce.warn("Unknown archetype \u2014 loading agent as unstructured",{id:c.id,archetype:c.archetype}),c.archetype=void 0,c.archetypeConfig=void 0;else try{c.archetypeConfig=u.validateConfig(c.archetypeConfig)}catch(d){Ce.error("Archetype config validation failed \u2014 agent will not load",{id:c.id,archetype:c.archetype,error:String(d)}),this.agents.has(c.id)&&(this.agents.delete(c.id),s.push(c.id),Ce.warn("Evicted previously-loaded agent due to archetype validation failure",{id:c.id}));continue}}t.has(c.id)?o.push(c.id):r.push(c.id),this.agents.set(c.id,c),Ce.info("Loaded agent",{id:c.id,name:c.name})}this.disabledAgents=a;for(let l of t)i.has(l)||(this.agents.delete(l),s.push(l),Ce.info("Removed agent",{id:l}));return this.lastPollTime=new Date,this.rebuildOriginIndex(),this.firePostReload(),{added:r,updated:o,removed:s}}async startWatching(){try{this.changeStream=this.agentDefs.watch([],{fullDocument:"updateLookup"}),this.changeStream.on("change",()=>{Ce.info("Agent definition changed (change stream), triggering reload"),this.onChangeDetected?.()}),this.changeStream.on("error",e=>{Ce.warn("Change stream error, falling back to polling",{error:String(e)}),this.changeStream=null,this.startPolling()}),Ce.info("Agent registry watching via change stream")}catch{Ce.info("Change stream not available, using polling fallback"),this.startPolling()}}startPolling(){this.pollTimer=setInterval(async()=>{try{let e=await this.agentDefs.countDocuments({updatedAt:{$gt:this.lastPollTime}});e>0&&(Ce.info("Agent definitions changed (poll), triggering reload",{changed:e}),this.onChangeDetected?.())}catch(e){Ce.error("Poll check failed",{error:String(e)})}},Nb),Ce.info("Agent registry watching via polling",{intervalMs:Nb})}rebuildOriginIndex(){this.originToAgent.clear();let e=[...this.agents.values()].sort((t,i)=>t.id.localeCompare(i.id));for(let t of e)for(let i of t.catches??[]){if(this.originToAgent.has(i)){Ce.error("Origin conflict \u2014 first sorted agent wins",{origin:i,winner:this.originToAgent.get(i),loser:t.id});continue}this.originToAgent.set(i,t.id)}}stopWatching(){this.changeStream&&(this.changeStream.close().catch(()=>{}),this.changeStream=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}get(e){return this.agents.get(e)}getAll(){return Array.from(this.agents.values())}async getAllDefinitions(){return this.agentDefs.find().toArray()}listIds(){return Array.from(this.agents.keys())}findByChannel(e){return this.getAll().find(t=>!t.disabled&&t.channels.includes(e))}findByOrigin(e){let t=this.originToAgent.get(e);return t?this.agents.get(t):void 0}isPassiveChannel(e){return this.getAll().some(t=>!t.disabled&&t.passiveChannels.includes(e))}findByKeyword(e){let t=e.toLowerCase();return this.getAll().find(i=>!i.disabled&&i.keywords.some(r=>{let o=r.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${o}\\b`).test(t)}))}findByName(e){return this.findAllByName(e)[0]}findAllByName(e){return this.getAll().filter(t=>{if(t.disabled)return!1;if(this.matchesName(t.name,e))return!0;if(t.name.includes(" ")){let i=t.name.split(" ")[0];if(this.matchesName(i,e))return!0}for(let i of t.aliases)if(this.matchesName(i,e))return!0;return!1})}matchesName(e,t){let i=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|hey\\s+|@)${i}\\b|\\b${i}[,:]`,"i").test(t)}getDefault(){return this.getAll().find(e=>!e.disabled&&e.isDefault)}getDisabled(){return this.disabledAgents}getSubscriberMap(){let e={};for(let t of this.getAll())if(!t.disabled)for(let i of t.subscribe??[]){let r=i.includes(":")?i.split(":")[0]:i;e[r]||(e[r]=[]),e[r].includes(t.id)||e[r].push(t.id)}return e}};R();ny();ho();R();ot();import{query as cM}from"@anthropic-ai/claude-agent-sdk";var go=$("model-router"),lM={haiku:{timeoutMs:12e4,maxTurns:20,budgetUsd:1},sonnet:{timeoutMs:3e5,maxTurns:50,budgetUsd:5},opus:{timeoutMs:6e5,maxTurns:200,budgetUsd:50}};function Pc(n,e){let t=lM[n],i=e?.[n];return i?{timeoutMs:i.timeoutMs??t.timeoutMs,maxTurns:i.maxTurns??t.maxTurns,budgetUsd:i.budgetUsd??t.budgetUsd}:{...t}}var an={haiku:0,sonnet:1,opus:2},Mc={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-7"};function uM(n){return n.includes("opus")?"opus":n.includes("haiku")?"haiku":"sonnet"}var dM=`You are a model router. Your job is to classify the complexity of a user message and decide which AI model tier should handle it.
276
315
 
277
316
  Tiers:
278
317
  - **haiku**: Greetings, simple factual questions, acknowledgments, status checks, yes/no answers, brief lookups, routine updates. Fast and cheap.
@@ -285,33 +324,34 @@ Rules:
285
324
  - Look at the TASK complexity, not the message length.
286
325
  - Scheduled/cron tasks that say "execute your scheduled X task" are routine \u2192 haiku unless the task itself is complex.
287
326
 
288
- Respond with ONLY a JSON object: { "tier": "haiku" | "sonnet" | "opus" }`;function ok(n){try{let s=JSON.parse(n);if(s.tier&&ht[s.tier]!==void 0)return s.tier}catch{}let e=n.indexOf("{"),t=n.lastIndexOf("}");if(e!==-1&&t>e)try{let s=JSON.parse(n.slice(e,t+1));if(s.tier&&ht[s.tier]!==void 0)return s.tier}catch{}return null}async function Hh(n,e,t){let s=rk(e),r=g.modelRouter.model;if(s==="haiku")return{tier:"haiku",model:Cr.haiku,costUsd:0,durationMs:0,resourceLimits:Ar("haiku",t)};let i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Ys.warn("Model router timed out",{timeoutMs:g.modelRouter.timeoutMs}),i.close())},g.modelRouter.timeoutMs);try{i=sk({prompt:n,options:{model:r,systemPrompt:ik,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let p=h;if(p.type==="assistant"){let m=p.message?.content;if(Array.isArray(m))for(let f of m)f.type==="text"&&(o=f.text)}if(p.type==="result"){let m=p;a=m.total_cost_usd,l=m.duration_ms,m.subtype==="success"&&m.result&&(o=m.result)}}}catch(h){Ys.warn("Model router query failed, defaulting to sonnet",{error:String(h)});let p=ht[s]>=ht.sonnet?"sonnet":s;return{tier:p,model:Cr[p],costUsd:0,durationMs:0,resourceLimits:Ar(p,t)}}finally{clearTimeout(c),i=null}let d=ok(o);if(!d){Ys.warn("Model router parse failed, defaulting to sonnet",{rawText:o.slice(0,200)});let h=ht[s]>=ht.sonnet?"sonnet":s;return{tier:h,model:Cr[h],costUsd:0,durationMs:0,resourceLimits:Ar(h,t)}}let u=d;return ht[d]>ht[s]&&(u=s,Ys.debug("Model router capped by ceiling",{requested:d,ceiling:s})),Ys.info("Model router decision",{tier:u,requested:d,ceiling:s,costUsd:a,durationMs:l,textPreview:n.slice(0,100)}),{tier:u,model:Cr[u],costUsd:a,durationMs:l,resourceLimits:Ar(u,t)}}Ne();kr();xa();ls();import{existsSync as Wh,readdirSync as lk,statSync as dk}from"node:fs";import{join as Gh}from"node:path";Er();import{QdrantClient as ck}from"@qdrant/js-client-rest";var Nr="conversations",xr=class{qdrantUrl;ollamaUrl;qdrant=null;collectionReady=!1;constructor(e,t){this.qdrantUrl=e??process.env.QDRANT_URL??"http://localhost:6333",this.ollamaUrl=t??process.env.OLLAMA_URL??"http://localhost:11434"}getClient(){return this.qdrant||(this.qdrant=new ck({url:this.qdrantUrl})),this.qdrant}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(r=>r.name===Nr)){let i=(await He(this.ollamaUrl,"test")).length;await e.createCollection(Nr,{vectors:{size:i,distance:"Cosine"}})}this.collectionReady=!0}async index(e){await this.ensureCollection();let t=this.getClient(),s=e.inbound+`
327
+ Respond with ONLY a JSON object: { "tier": "haiku" | "sonnet" | "opus" }`;function fM(n){try{let i=JSON.parse(n);if(i.tier&&an[i.tier]!==void 0)return i.tier}catch{}let e=n.indexOf("{"),t=n.lastIndexOf("}");if(e!==-1&&t>e)try{let i=JSON.parse(n.slice(e,t+1));if(i.tier&&an[i.tier]!==void 0)return i.tier}catch{}return null}async function rI(n,e,t){let i=uM(e),r=g.modelRouter.model;if(i==="haiku")return{tier:"haiku",model:Mc.haiku,costUsd:0,durationMs:0,resourceLimits:Pc("haiku",t)};let o=null,s="",a=0,l=0,c=setTimeout(()=>{o&&(go.warn("Model router timed out",{timeoutMs:g.modelRouter.timeoutMs}),o.close())},g.modelRouter.timeoutMs);try{o=cM({prompt:n,options:{model:r,systemPrompt:dM,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let f of o){let p=f;if(p.type==="assistant"){let h=p.message?.content;if(Array.isArray(h))for(let m of h)m.type==="text"&&(s=m.text)}if(p.type==="result"){let h=p;a=h.total_cost_usd,l=h.duration_ms,h.subtype==="success"&&h.result&&(s=h.result)}}}catch(f){go.warn("Model router query failed, defaulting to sonnet",{error:String(f)});let p=an[i]>=an.sonnet?"sonnet":i;return{tier:p,model:Mc[p],costUsd:0,durationMs:0,resourceLimits:Pc(p,t)}}finally{clearTimeout(c),o=null}let u=fM(s);if(!u){go.warn("Model router parse failed, defaulting to sonnet",{rawText:s.slice(0,200)});let f=an[i]>=an.sonnet?"sonnet":i;return{tier:f,model:Mc[f],costUsd:0,durationMs:0,resourceLimits:Pc(f,t)}}let d=u;return an[u]>an[i]&&(d=i,go.debug("Model router capped by ceiling",{requested:u,ceiling:i})),go.info("Model router decision",{tier:d,requested:u,ceiling:i,costUsd:a,durationMs:l,textPreview:n.slice(0,100)}),{tier:d,model:Mc[d],costUsd:a,durationMs:l,resourceLimits:Pc(d,t)}}ot();Us();Rd();Wr();import{existsSync as iI,readdirSync as hM,statSync as gM}from"node:fs";import{join as oI}from"node:path";Lc();import{QdrantClient as mM}from"@qdrant/js-client-rest";var zc="conversations",jc=class{qdrantUrl;ollamaUrl;qdrant=null;collectionReady=!1;constructor(e,t){this.qdrantUrl=e??process.env.QDRANT_URL??"http://localhost:6333",this.ollamaUrl=t??process.env.OLLAMA_URL??"http://localhost:11434"}getClient(){return this.qdrant||(this.qdrant=new mM({url:this.qdrantUrl})),this.qdrant}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(r=>r.name===zc)){let o=(await At(this.ollamaUrl,"test")).length;await e.createCollection(zc,{vectors:{size:o,distance:"Cosine"}})}this.collectionReady=!0}async index(e){await this.ensureCollection();let t=this.getClient(),i=e.inbound+`
289
328
 
290
- `+e.response,r=await He(this.ollamaUrl,s),i=crypto.randomUUID();await t.upsert(Nr,{points:[{id:i,vector:r,payload:{agentId:e.agentId,threadId:e.threadId,channelId:e.channelId,source:e.source,senderName:e.senderName,timestampUnix:e.timestampUnix,timestamp:e.timestamp,inbound:e.inbound,response:e.response}}]})}async search(e,t,s,r){await this.ensureCollection();let i=this.getClient(),o=await He(this.ollamaUrl,e),a=[{key:"agentId",match:{value:t}}];return r!==void 0&&a.push({key:"timestampUnix",range:{gte:r}}),(await i.search(Nr,{vector:o,limit:s,with_payload:!0,filter:{must:a}})).map(c=>({agentId:c.payload?.agentId,threadId:c.payload?.threadId,channelId:c.payload?.channelId,source:c.payload?.source,senderName:c.payload?.senderName,timestampUnix:c.payload?.timestampUnix,timestamp:c.payload?.timestamp,inbound:c.payload?.inbound,response:c.payload?.response,score:c.score}))}};var ae=k("agent-manager"),uk=new xr;function hk(n){if(!Wh(n))return[];try{return lk(n).map(e=>Gh(n,e)).filter(e=>{try{return dk(e).isDirectory()&&Wh(Gh(e,"skills"))}catch{return!1}})}catch{return[]}}var Or=class{states=new Map;queues=new Map;processing=new Set;activeRunners=new Map;activeThreads=new Map;registry;memoryManager;sessionStore;plugins;seedDirs;skillIndex;activityLogger;prefetcher;activeWorkItems=new Map;spawnWindow=new Map;constructor(e,t,s,r,i){this.registry=e,this.memoryManager=t,this.sessionStore=s,this.activityLogger=r,this.prefetcher=i,this.plugins=va(g.plugins,V,{distDir:Ke}),this.seedDirs=hk(Nc),this.skillIndex=Na(Xe,this.plugins,this.seedDirs)}getPlugins(){return this.plugins}getActiveWorkItems(e){return this.activeWorkItems.get(e)??[]}createRunner(e){let t=this.registry.get(e);if(!t)throw new Error(`Unknown agent: ${e}`);let s=JSON.stringify(this.registry.getSubscriberMap());return new Ws(t,this.memoryManager,this.plugins,this.skillIndex,s,this.prefetcher)}reloadSkills(){try{this.skillIndex=Na(Xe,this.plugins,this.seedDirs)}catch(e){ae.warn("Skill reload failed, retaining previous index",{error:String(e)})}}rescanPlugins(){let{rescued:e,stillBroken:t}=Ta(this.plugins,V,{distDir:Ke});Object.values(e).reduce((i,o)=>i+o.length,0)>0&&ae.info("Plugin MCP servers rescued after rescan",{rescued:e}),Object.values(t).reduce((i,o)=>i+o.length,0)>0&&ae.warn("Plugin MCP servers still unresolvable after rescan",{stillBroken:t})}recordSpawn(e){let t=Date.now(),s=6e4,r=(this.spawnWindow.get(e)??[]).filter(i=>t-i<s);if(r.push(t),this.spawnWindow.set(e,r),r.length>3&&ae.warn("Session spawn rate exceeded",{channelId:e,count:r.length,windowSec:60}),this.spawnWindow.size>200){let i=this.spawnWindow.keys().next().value;i&&this.spawnWindow.delete(i)}}ensureState(e){this.states.has(e)||this.states.set(e,{id:e,status:"idle",lastActivity:new Date,messagesProcessed:0,errorCount:0,activeThreadCount:0})}async sendMessage(e,t,s){this.ensureState(e);let r=t.threadId??t.id,i=`${e}:${r}`;return new Promise((o,a)=>{let l=this.queues.get(i)??[];l.push({message:t,onStream:s,resolve:o,reject:a}),this.queues.set(i,l),this.processThreadQueue(e,i).catch(c=>{ae.error("processThreadQueue failed unexpectedly",{agentId:e,threadKey:i,error:String(c)}),this.processing.delete(i);let d=this.activeThreads.get(e);d&&(d.delete(i),this.updateThreadCount(e),d.size===0&&this.updateStatus(e,"idle"));let u=this.queues.get(i);if(u){for(let h of u)h.reject(c instanceof Error?c:new Error(String(c)));this.queues.delete(i)}this.retryDeferredThreads(e)})})}async processThreadQueue(e,t){if(this.processing.has(t))return;let s=this.queues.get(t);if(!s||s.length===0)return;let r=this.registry.get(e),i=r?.maxConcurrent??3,o=this.activeThreads.get(e)??new Set;if(o.size>=i){ae.debug("Agent at concurrency limit, deferring",{agentId:e,threadKey:t,active:o.size,limit:i});return}this.processing.add(t),o.add(t),this.activeThreads.set(e,o),this.updateStatus(e,"processing"),this.updateThreadCount(e);let a=this.createRunner(e),l=this.activeRunners.get(e)??new Set;l.add(a),this.activeRunners.set(e,l);let c=0,d,u;for(;s.length>0;){let m=s.shift(),f=this.activeWorkItems.get(e)??[];f.push(m.message),this.activeWorkItems.set(e,f);try{let y=m.message.threadId??m.message.id,w=await this.sessionStore.get(e,y);w||this.recordSpawn(m.message.source.id);let S={adapterId:m.message.source.adapterId??m.message.source.kind,channelId:m.message.source.id,channelKind:m.message.source.kind,channelLabel:m.message.source.label,threadId:m.message.threadId??m.message.id,slackTs:m.message.meta?.slackTs??"",slackThreadTs:m.message.meta?.slackThreadTs??""},_=m.message.senderName??m.message.sender,v=m.message.source.kind==="team"?m.message.meta?.user:void 0,I;if(v)I=`[user:${v} via ${_} in #${m.message.source.label}]: ${m.message.text}`;else if(m.message.senderName){let W=m.message.meta?.slackThreadTs,$=m.message.meta?.slackTs,le=W??$,Ie=le?`, thread=${le}`:"";I=`[${_} in #${m.message.source.label}${Ie}]: ${m.message.text}`}else I=m.message.text;m.message.files?.length&&(I+=Fh(m.message.files));let N,D=0,A;if(g.modelRouter.enabled&&m.message.sender!=="system")try{let W=this.registry.get(e);if(W){let $=await Hh(m.message.text,W.model,W.resourceTiers);N=$.model!==W.model?$.model:void 0,D=$.costUsd,A=$.resourceLimits}}catch(W){ae.warn("Model router failed, using default",{agentId:e,error:String(W)})}let E=await a.send(I,w,m.onStream,S,N,A);E.costUsd+=D,E.sessionId&&!E.aborted&&this.sessionStore.set(e,y,E.sessionId,{inputTokens:E.inputTokens,outputTokens:E.outputTokens,cacheReadTokens:E.cacheReadTokens,cacheCreationTokens:E.cacheCreationTokens,contextWindow:E.contextWindow,compactions:E.compactions,preCompactTokens:E.preCompactTokens});let G=this.states.get(e);G.messagesProcessed++,G.lastActivity=new Date,G.currentSessionId=E.sessionId,E.error&&(G.errorCount++,w&&this.sessionStore.delete(e,y)),m.resolve(E),c++,d=m,u=E,E.text&&!E.error&&uk.index({agentId:e,threadId:y,channelId:m.message.source.id,source:m.message.source.kind,senderName:m.message.senderName??"unknown",timestampUnix:Math.floor(Date.now()/1e3),timestamp:new Date().toISOString(),inbound:I,response:E.text}).catch(W=>ae.warn("Conversation indexing failed",{agentId:e,error:String(W)})),this.activityLogger?.record({agentId:e,threadId:y,timestamp:new Date,sender:m.message.sender,senderName:m.message.senderName,channel:m.message.source.label,channelKind:m.message.source.kind,model:N??r?.model??"unknown",modelTier:void 0,costUsd:E.costUsd,durationMs:E.durationMs,inputTokens:E.inputTokens,outputTokens:E.outputTokens,contextWindow:E.contextWindow,toolCalls:E.toolCalls,toolSummary:E.toolSummary,compactions:E.compactions,streamed:E.streamed,error:E.error})}catch(y){let w=this.states.get(e);w&&(w.errorCount++,w.lastActivity=new Date),this.activityLogger?.record({agentId:e,threadId:m.message.threadId??m.message.id,timestamp:new Date,sender:m.message.sender,senderName:m.message.senderName,channel:m.message.source.label,channelKind:m.message.source.kind,model:r?.model??"unknown",costUsd:0,durationMs:0,inputTokens:0,outputTokens:0,contextWindow:0,toolCalls:0,toolSummary:"none",compactions:0,streamed:!1,error:String(y)}),m.reject(y instanceof Error?y:new Error(String(y)))}finally{let y=(this.activeWorkItems.get(e)??[]).filter(w=>w.id!==m.message.id);y.length===0?this.activeWorkItems.delete(e):this.activeWorkItems.set(e,y)}}let h=[...r?.coreServers??[],...r?.delegateServers??[]];if((h.includes("memory")||h.includes("structured-memory"))&&u&&d&&!u.error&&!u.aborted&&c>=g.memory.reflectionMinTurns&&d.message.sender!=="system")try{let m=["[System \u2014 end of conversation reflection]","This conversation is wrapping up. Review what was discussed:","- Were any new facts, decisions, or commitments made?","- Did anything contradict or update what you previously knew?","- Should any existing memories be updated or forgotten?","","If yes, use memory_save, memory_update, or memory_forget now.","If nothing worth saving, do nothing."].join(`
291
- `),f=await a.send(m,u.sessionId);if(ae.info("Reflection completed",{agentId:e,threadKey:t,turnCount:c,costUsd:f.costUsd,toolCalls:f.toolCalls,toolSummary:f.toolSummary||void 0}),f.sessionId&&!f.aborted){let y=d.message.threadId??d.message.id;this.sessionStore.set(e,y,f.sessionId,{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheCreationTokens:f.cacheCreationTokens,contextWindow:f.contextWindow,compactions:f.compactions,preCompactTokens:f.preCompactTokens})}}catch(m){ae.warn("Reflection failed, non-critical",{agentId:e,threadKey:t,error:String(m)})}l.delete(a),this.processing.delete(t),o.delete(t),this.queues.delete(t),this.updateThreadCount(e),o.size===0&&this.updateStatus(e,"idle"),this.retryDeferredThreads(e)}updateThreadCount(e){let t=this.states.get(e);t&&(t.activeThreadCount=this.activeThreads.get(e)?.size??0)}retryDeferredThreads(e){let t=`${e}:`;for(let[s,r]of this.queues)if(s.startsWith(t)&&r.length>0&&!this.processing.has(s)){this.processThreadQueue(e,s);break}}updateStatus(e,t){let s=this.states.get(e);s&&(s.status=t,ae.debug("Agent status changed",{agentId:e,status:t}))}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}stopAgent(e){let t=this.activeRunners.get(e);if(t){for(let s of t)s.abort();t.clear()}this.activeRunners.delete(e),this.activeThreads.delete(e),this.updateStatus(e,"stopped")}stopAll(){for(let e of this.states.keys())this.stopAgent(e);ae.info("All agents stopped")}async findAgentForThread(e){return this.sessionStore.findAgentByThread(e)}async findAgentsForThread(e){return this.sessionStore.findAgentsByThread(e)}restartAgent(e){this.stopAgent(e),this.sessionStore.clearAgent(e),this.states.set(e,{id:e,status:"idle",lastActivity:new Date,messagesProcessed:0,errorCount:0,activeThreadCount:0}),ae.info("Agent restarted",{agentId:e})}sweep(){let e=0,t=[];for(let[r,i]of this.states)!this.registry.get(r)&&(i.status==="stopped"||i.status==="idle")&&(this.states.delete(r),this.activeRunners.delete(r),this.activeThreads.delete(r),e++,ae.info("Zombie agent state removed",{agentId:r}));for(let r of this.processing){let i=r.split(":")[0],o=this.activeRunners.get(i);if(!o||o.size===0){this.processing.delete(r);let a=this.activeThreads.get(i);a&&(a.delete(r),this.updateThreadCount(i),a.size===0&&this.updateStatus(i,"idle")),e++,ae.warn("Stuck processing flag cleared",{threadKey:r,agentId:i});let l=this.queues.get(r);l&&l.length>0&&this.processThreadQueue(i,r).catch(c=>{ae.error("Failed to restart stuck queue",{threadKey:r,error:String(c)})})}}let s=new Set;for(let r of this.queues.keys())s.add(r.split(":")[0]);for(let r of s)this.retryDeferredThreads(r);return{component:"agent-manager",pruned:e,retried:0,bytesFreed:0,errors:t}}};M();Vs();import{SocketModeClient as pk}from"@slack/socket-mode";import{WebClient as mk}from"@slack/web-api";M();var fk=k("outbound-ts-cache"),Mr=class{entries=new Map;ttlMs;maxSize;constructor(e={}){this.ttlMs=e.ttlMs??12e4,this.maxSize=e.maxSize??1e4}register(e,t){if(this.evictExpired(),this.entries.size>=this.maxSize){let s=this.entries.keys().next().value;s&&this.entries.delete(s)}this.entries.set(this.key(e,t),Date.now()+this.ttlMs)}has(e,t){let s=this.entries.get(this.key(e,t));return s===void 0?!1:s<=Date.now()?(this.entries.delete(this.key(e,t)),!1):!0}size(){return this.entries.size}key(e,t){return`${e}:${t}`}evictExpired(){let e=Date.now(),t=0;for(let[s,r]of this.entries)r<=e&&(this.entries.delete(s),t++);t>0&&fk.debug(`evicted ${t} expired entries`,{evicted:t})}};var K=k("slack-gateway"),Dr=class n{socket;web;messageHandler=null;threadStartedHandler=null;threadContextHandler=null;botUserId=null;botId=null;peerBotUserIds=new Set;peerBotIds=new Set;channelNameCache=new Map;channelIdCache=new Map;userNameCache=new Map;outboundTsCache=new Mr;integrationChannels=new Set;botToken;constructor(e,t){this.socket=new pk({appToken:e}),this.web=new mk(t),this.botToken=t}addIntegrationChannels(e){for(let t of e)this.integrationChannels.add(t)}addPeerBotIds(e,t){e&&this.peerBotUserIds.add(e),t&&this.peerBotIds.add(t),K.info("Peer bot IDs registered",{peerBotUserIds:[...this.peerBotUserIds],peerBotIds:[...this.peerBotIds]})}get resolvedBotUserId(){return this.botUserId}get resolvedBotId(){return this.botId}onMessage(e){this.messageHandler=e}onThreadStarted(e){this.threadStartedHandler=e}onThreadContextChanged(e){this.threadContextHandler=e}async start(){let e=await this.web.auth.test();this.botUserId=e.user_id,this.botId=e.bot_id??null,K.info("Bot identity resolved",{botUserId:this.botUserId,botId:this.botId}),this.socket.on("message",async({event:t,ack:s})=>{if(await s(),!t||(K.debug("Raw message event",{subtype:t.subtype,bot_id:t.bot_id,user:t.user,channel:t.channel,hasText:!!t.text,hasAttachments:!!t.attachments?.length,hasBlocks:!!t.blocks?.length}),t.user===this.botUserId)||this.peerBotUserIds.has(t.user)||t.bot_id&&t.bot_id===this.botId||t.bot_id&&this.peerBotIds.has(t.bot_id))return;if(t.ts&&t.channel&&this.outboundTsCache.has(t.channel,t.ts)){K.info("Outbound echo suppressed",{channel:t.channel,ts:t.ts});return}if(t.bot_id||t.subtype){let l=await this.resolveChannelName(t.channel);if(!this.integrationChannels.has(l)){K.info("Message filtered (subtype/bot in non-integration channel)",{channel:t.channel,channelName:l,user:t.user,subtype:t.subtype,bot_id:t.bot_id,hasText:!!t.text});return}K.info("Integration message accepted",{channelName:l,subtype:t.subtype,bot_id:t.bot_id})}let r=await this.resolveChannelName(t.channel),i=t.text??"";if(!i){let l=[...t.blocks??[]];for(let c of t.attachments??[])c.blocks&&l.push(...c.blocks),c.text&&(i+=c.text+`
292
- `);i||(i=l.filter(c=>c.type==="section"||c.type==="rich_text").map(c=>c.text?.text?c.text.text:c.elements?c.elements.map(d=>d.elements?.map(u=>u.text||"").join("")??"").join(`
329
+ `+e.response,r=await At(this.ollamaUrl,i),o=crypto.randomUUID();await t.upsert(zc,{points:[{id:o,vector:r,payload:{agentId:e.agentId,threadId:e.threadId,channelId:e.channelId,source:e.source,senderName:e.senderName,timestampUnix:e.timestampUnix,timestamp:e.timestamp,inbound:e.inbound,response:e.response}}]})}async search(e,t,i,r){await this.ensureCollection();let o=this.getClient(),s=await At(this.ollamaUrl,e),a=[{key:"agentId",match:{value:t}}];return r!==void 0&&a.push({key:"timestampUnix",range:{gte:r}}),(await o.search(zc,{vector:s,limit:i,with_payload:!0,filter:{must:a}})).map(c=>({agentId:c.payload?.agentId,threadId:c.payload?.threadId,channelId:c.payload?.channelId,source:c.payload?.source,senderName:c.payload?.senderName,timestampUnix:c.payload?.timestampUnix,timestamp:c.payload?.timestamp,inbound:c.payload?.inbound,response:c.payload?.response,score:c.score}))}};var Ae=$("agent-manager"),yM=new jc;function vM(n){if(!iI(n))return[];try{return hM(n).map(e=>oI(n,e)).filter(e=>{try{return gM(e).isDirectory()&&iI(oI(e,"skills"))}catch{return!1}})}catch{return[]}}var Uc=class{states=new Map;queues=new Map;processing=new Set;activeRunners=new Map;activeThreads=new Map;registry;memoryManager;sessionStore;plugins;seedDirs;skillIndex;activityLogger;prefetcher;teamRoster;activeWorkItems=new Map;spawnWindow=new Map;constructor(e,t,i,r,o,s){this.registry=e,this.memoryManager=t,this.sessionStore=i,this.activityLogger=r,this.prefetcher=o,this.teamRoster=s,this.plugins=Dd(g.plugins,se,{distDir:Et}),this.seedDirs=vM(Xy),this.skillIndex=Ud(Lt,this.plugins,this.seedDirs)}getPlugins(){return this.plugins}getActiveWorkItems(e){return this.activeWorkItems.get(e)??[]}createRunner(e){let t=this.registry.get(e);if(!t)throw new Error(`Unknown agent: ${e}`);let i=JSON.stringify(this.registry.getSubscriberMap());return new po(t,this.memoryManager,this.plugins,this.skillIndex,i,this.prefetcher,this.teamRoster)}reloadSkills(){try{this.skillIndex=Ud(Lt,this.plugins,this.seedDirs)}catch(e){Ae.warn("Skill reload failed, retaining previous index",{error:String(e)})}}rescanPlugins(){let{rescued:e,stillBroken:t}=Pd(this.plugins,se,{distDir:Et});Object.values(e).reduce((o,s)=>o+s.length,0)>0&&Ae.info("Plugin MCP servers rescued after rescan",{rescued:e}),Object.values(t).reduce((o,s)=>o+s.length,0)>0&&Ae.warn("Plugin MCP servers still unresolvable after rescan",{stillBroken:t})}recordSpawn(e){let t=Date.now(),i=6e4,r=(this.spawnWindow.get(e)??[]).filter(o=>t-o<i);if(r.push(t),this.spawnWindow.set(e,r),r.length>3&&Ae.warn("Session spawn rate exceeded",{channelId:e,count:r.length,windowSec:60}),this.spawnWindow.size>200){let o=this.spawnWindow.keys().next().value;o&&this.spawnWindow.delete(o)}}ensureState(e){this.states.has(e)||this.states.set(e,{id:e,status:"idle",lastActivity:new Date,messagesProcessed:0,errorCount:0,activeThreadCount:0})}async sendMessage(e,t,i){this.ensureState(e);let r=t.threadId??t.id,o=`${e}:${r}`;return new Promise((s,a)=>{let l=this.queues.get(o)??[];l.push({message:t,onStream:i,resolve:s,reject:a}),this.queues.set(o,l),this.processThreadQueue(e,o).catch(c=>{Ae.error("processThreadQueue failed unexpectedly",{agentId:e,threadKey:o,error:String(c)}),this.processing.delete(o);let u=this.activeThreads.get(e);u&&(u.delete(o),this.updateThreadCount(e),u.size===0&&this.updateStatus(e,"idle"));let d=this.queues.get(o);if(d){for(let f of d)f.reject(c instanceof Error?c:new Error(String(c)));this.queues.delete(o)}this.retryDeferredThreads(e)})})}async processThreadQueue(e,t){if(this.processing.has(t))return;let i=this.queues.get(t);if(!i||i.length===0)return;let r=this.registry.get(e),o=r?.maxConcurrent??3,s=this.activeThreads.get(e)??new Set;if(s.size>=o){Ae.debug("Agent at concurrency limit, deferring",{agentId:e,threadKey:t,active:s.size,limit:o});return}this.processing.add(t),s.add(t),this.activeThreads.set(e,s),this.updateStatus(e,"processing"),this.updateThreadCount(e);let a=this.createRunner(e),l=this.activeRunners.get(e)??new Set;l.add(a),this.activeRunners.set(e,l);let c=0,u,d;for(;i.length>0;){let h=i.shift(),m=this.activeWorkItems.get(e)??[];m.push(h.message),this.activeWorkItems.set(e,m);try{let y=h.message.threadId??h.message.id,_=await this.sessionStore.get(e,y);_||this.recordSpawn(h.message.source.id);let b={adapterId:h.message.source.adapterId??h.message.source.kind,channelId:h.message.source.id,channelKind:h.message.source.kind,channelLabel:h.message.source.label,threadId:h.message.threadId??h.message.id,slackTs:h.message.meta?.slackTs??"",slackThreadTs:h.message.meta?.slackThreadTs??""},k=h.message.senderName??h.message.sender,O=h.message.source.kind==="team"?h.message.meta?.user:void 0,A;if(O)A=`[user:${O} via ${k} in #${h.message.source.label}]: ${h.message.text}`;else if(h.message.senderName){let ue=h.message.meta?.slackThreadTs,W=h.message.meta?.slackTs,Se=ue??W,tt=Se?`, thread=${Se}`:"";A=`[${k} in #${h.message.source.label}${tt}]: ${h.message.text}`}else A=h.message.text;h.message.files?.length&&(A+=tI(h.message.files));let j,L=0,P;if(g.modelRouter.enabled&&h.message.sender!=="system")try{let ue=this.registry.get(e);if(ue){let W=await rI(h.message.text,ue.model,ue.resourceTiers);j=W.model!==ue.model?W.model:void 0,L=W.costUsd,P=W.resourceLimits}}catch(ue){Ae.warn("Model router failed, using default",{agentId:e,error:String(ue)})}let z=await a.send(A,_,h.onStream,b,j,P);z.costUsd+=L,z.sessionId&&!z.aborted&&this.sessionStore.set(e,y,z.sessionId,{inputTokens:z.inputTokens,outputTokens:z.outputTokens,cacheReadTokens:z.cacheReadTokens,cacheCreationTokens:z.cacheCreationTokens,contextWindow:z.contextWindow,compactions:z.compactions,preCompactTokens:z.preCompactTokens});let ae=this.states.get(e);ae.messagesProcessed++,ae.lastActivity=new Date,ae.currentSessionId=z.sessionId,z.error&&(ae.errorCount++,_&&this.sessionStore.delete(e,y)),h.resolve(z),c++,u=h,d=z,z.text&&!z.error&&yM.index({agentId:e,threadId:y,channelId:h.message.source.id,source:h.message.source.kind,senderName:h.message.senderName??"unknown",timestampUnix:Math.floor(Date.now()/1e3),timestamp:new Date().toISOString(),inbound:A,response:z.text}).catch(ue=>Ae.warn("Conversation indexing failed",{agentId:e,error:String(ue)})),this.activityLogger?.record({agentId:e,threadId:y,timestamp:new Date,sender:h.message.sender,senderName:h.message.senderName,channel:h.message.source.label,channelKind:h.message.source.kind,model:j??r?.model??"unknown",modelTier:void 0,costUsd:z.costUsd,durationMs:z.durationMs,inputTokens:z.inputTokens,outputTokens:z.outputTokens,contextWindow:z.contextWindow,toolCalls:z.toolCalls,toolSummary:z.toolSummary,compactions:z.compactions,streamed:z.streamed,error:z.error})}catch(y){let _=this.states.get(e);_&&(_.errorCount++,_.lastActivity=new Date),this.activityLogger?.record({agentId:e,threadId:h.message.threadId??h.message.id,timestamp:new Date,sender:h.message.sender,senderName:h.message.senderName,channel:h.message.source.label,channelKind:h.message.source.kind,model:r?.model??"unknown",costUsd:0,durationMs:0,inputTokens:0,outputTokens:0,contextWindow:0,toolCalls:0,toolSummary:"none",compactions:0,streamed:!1,error:String(y)}),h.reject(y instanceof Error?y:new Error(String(y)))}finally{let y=(this.activeWorkItems.get(e)??[]).filter(_=>_.id!==h.message.id);y.length===0?this.activeWorkItems.delete(e):this.activeWorkItems.set(e,y)}}let f=[...r?.coreServers??[],...r?.delegateServers??[]];if((f.includes("memory")||f.includes("structured-memory"))&&d&&u&&!d.error&&!d.aborted&&c>=g.memory.reflectionMinTurns&&u.message.sender!=="system")try{let h=["[System \u2014 end of conversation reflection]","This conversation is wrapping up. Review what was discussed:","- Were any new facts, decisions, or commitments made?","- Did anything contradict or update what you previously knew?","- Should any existing memories be updated or forgotten?","","If yes, use memory_save, memory_update, or memory_forget now.","If nothing worth saving, do nothing."].join(`
330
+ `),m=await a.send(h,d.sessionId);if(Ae.info("Reflection completed",{agentId:e,threadKey:t,turnCount:c,costUsd:m.costUsd,toolCalls:m.toolCalls,toolSummary:m.toolSummary||void 0}),m.sessionId&&!m.aborted){let y=u.message.threadId??u.message.id;this.sessionStore.set(e,y,m.sessionId,{inputTokens:m.inputTokens,outputTokens:m.outputTokens,cacheReadTokens:m.cacheReadTokens,cacheCreationTokens:m.cacheCreationTokens,contextWindow:m.contextWindow,compactions:m.compactions,preCompactTokens:m.preCompactTokens})}}catch(h){Ae.warn("Reflection failed, non-critical",{agentId:e,threadKey:t,error:String(h)})}l.delete(a),this.processing.delete(t),s.delete(t),this.queues.delete(t),this.updateThreadCount(e),s.size===0&&this.updateStatus(e,"idle"),this.retryDeferredThreads(e)}updateThreadCount(e){let t=this.states.get(e);t&&(t.activeThreadCount=this.activeThreads.get(e)?.size??0)}retryDeferredThreads(e){let t=`${e}:`;for(let[i,r]of this.queues)if(i.startsWith(t)&&r.length>0&&!this.processing.has(i)){this.processThreadQueue(e,i);break}}updateStatus(e,t){let i=this.states.get(e);i&&(i.status=t,Ae.debug("Agent status changed",{agentId:e,status:t}))}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}stopAgent(e){let t=this.activeRunners.get(e);if(t){for(let i of t)i.abort();t.clear()}this.activeRunners.delete(e),this.activeThreads.delete(e),this.updateStatus(e,"stopped")}stopAll(){for(let e of this.states.keys())this.stopAgent(e);Ae.info("All agents stopped")}async findAgentForThread(e){return this.sessionStore.findAgentByThread(e)}async findAgentsForThread(e){return this.sessionStore.findAgentsByThread(e)}restartAgent(e){this.stopAgent(e),this.sessionStore.clearAgent(e),this.states.set(e,{id:e,status:"idle",lastActivity:new Date,messagesProcessed:0,errorCount:0,activeThreadCount:0}),Ae.info("Agent restarted",{agentId:e})}sweep(){let e=0,t=[];for(let[r,o]of this.states)!this.registry.get(r)&&(o.status==="stopped"||o.status==="idle")&&(this.states.delete(r),this.activeRunners.delete(r),this.activeThreads.delete(r),e++,Ae.info("Zombie agent state removed",{agentId:r}));for(let r of this.processing){let o=r.split(":")[0],s=this.activeRunners.get(o);if(!s||s.size===0){this.processing.delete(r);let a=this.activeThreads.get(o);a&&(a.delete(r),this.updateThreadCount(o),a.size===0&&this.updateStatus(o,"idle")),e++,Ae.warn("Stuck processing flag cleared",{threadKey:r,agentId:o});let l=this.queues.get(r);l&&l.length>0&&this.processThreadQueue(o,r).catch(c=>{Ae.error("Failed to restart stuck queue",{threadKey:r,error:String(c)})})}}let i=new Set;for(let r of this.queues.keys())i.add(r.split(":")[0]);for(let r of i)this.retryDeferredThreads(r);return{component:"agent-manager",pruned:e,retried:0,bytesFreed:0,errors:t}}};R();var sI=$("team-cache"),aI=6e4,Rc=class{db;humans={data:null,loadedAt:0};agents={data:null,loadedAt:0};constructor(e){this.db=e}invalidateHumans(){sI.debug("humans slice invalidated"),this.humans={data:null,loadedAt:0}}invalidateAgents(){sI.debug("agents slice invalidated"),this.agents={data:null,loadedAt:0}}async getHumans(){if(this.humans.data&&Date.now()-this.humans.loadedAt<aI)return this.humans.data;let t=(await this.db.collection("contacts").find({category:{$in:["team-human","archived"]}}).toArray()).map(i=>({kind:"human",id:i._id.toHexString(),name:i.name||`${i.firstName??""} ${i.lastName??""}`.trim(),email:i.email??void 0,role:i.role,pronouns:i.pronouns,category:i.category==="archived"?"archived":"team-human",updatedAt:i.updatedAt}));return this.humans={data:t,loadedAt:Date.now()},t}async getAgents(){if(this.agents.data&&Date.now()-this.agents.loadedAt<aI)return this.agents.data;let t=(await this.db.collection("agent_definitions").find({}).toArray()).map(i=>({kind:"agent",id:i._id,name:i.name,role:i.role,category:i.disabled?"archived":"team-agent",agentId:i._id,slackChannel:i.homeBase??i.channels?.[0],model:i.model,aliases:i.aliases,active:!i.disabled}));return this.agents={data:t,loadedAt:Date.now()},t}};var Bc=class{cache;constructor(e){this.cache=e}async getTeam(e={}){let t=e.includeArchived??!1,i=e.includeAgents??!0,r=await this.cache.getHumans(),o=i?await this.cache.getAgents():[],s=[...r,...o];return(t?s:s.filter(l=>l.category!=="archived")).sort((l,c)=>l.category!==c.category?l.category.localeCompare(c.category):l.name.localeCompare(c.name))}async lookupHuman(e){let t=typeof e.name=="string"&&e.name.length>0,i=typeof e.email=="string"&&e.email.length>0;if(t===i)throw new Error("lookupHuman: exactly one of name|email required");let r=(await this.cache.getHumans()).filter(a=>a.category==="team-human");if(i){let a=e.email.toLowerCase(),l=r.filter(c=>c.email&&c.email.toLowerCase()===a);return cI(l)}let o=e.name.toLowerCase(),s=r.filter(a=>a.name.toLowerCase()===o);return cI(s)}async lookupAgent(e){let t=typeof e.agentId=="string"&&e.agentId.length>0,i=typeof e.name=="string"&&e.name.length>0;if(t===i)throw new Error("lookupAgent: exactly one of agentId|name required");let r=(await this.cache.getAgents()).filter(a=>a.category==="team-agent");if(t)return r.find(a=>a.agentId===e.agentId)??null;let o=e.name.toLowerCase(),s=r.find(a=>a.name.toLowerCase()===o);return s||(r.find(a=>(a.aliases??[]).some(l=>l.toLowerCase()===o))??null)}async teamSummary(){let e=await this.getTeam({includeArchived:!1,includeAgents:!0}),t=e.filter(o=>o.kind==="human"),i=e.filter(o=>o.kind==="agent"),r=["## Team"];if(t.length>0){r.push("","### Humans");for(let o of t){let s=o.role?` \u2014 ${o.role}`:"";r.push(`- **${o.name}**${s}`)}}if(i.length>0){r.push("","### AI Agents");for(let o of i){let s=o.role?` \u2014 ${o.role}`:"",a=o.slackChannel?` (\`#${o.slackChannel}\`)`:"";r.push(`- **${o.name}**${a}${s}`)}}return t.length===0&&i.length===0?"":(r.push("","Use `team_lookup_human` / `team_lookup_agent` for full contact details."),r.join(`
331
+ `))}};function cI(n){return n.length===0?null:n.length===1?n[0]:[...n].sort((t,i)=>{let r=t.updatedAt?t.updatedAt.getTime():0;return(i.updatedAt?i.updatedAt.getTime():0)-r})[0]}R();var On=$("contacts-watcher"),lI=3e4,Fc=class{db;cache;changeStream=null;pollTimer=null;lastPollTime=new Date;constructor(e,t){this.db=e,this.cache=t}async start(){try{this.changeStream=this.db.collection("contacts").watch([]),this.changeStream.on("change",()=>{On.debug("contacts changed (change stream), invalidating humans cache"),this.cache.invalidateHumans()}),this.changeStream.on("error",e=>{On.warn("contacts change stream error, falling back to polling",{error:String(e)}),this.changeStream?.close().catch(()=>{}),this.changeStream=null,this.startPolling()}),On.info("contacts change stream started")}catch(e){On.info("contacts change stream not available, using polling fallback",{error:String(e)}),this.startPolling()}}startPolling(){this.pollTimer||(this.pollTimer=setInterval(async()=>{try{let e=await this.db.collection("contacts").countDocuments({updatedAt:{$gt:this.lastPollTime}});e>0&&(On.debug("contacts changed (poll), invalidating humans cache",{changed:e}),this.cache.invalidateHumans(),this.lastPollTime=new Date)}catch(e){On.warn("contacts poll failed",{error:String(e)})}},lI),On.info("contacts watcher running via polling",{intervalMs:lI}))}stop(){this.changeStream&&(this.changeStream.close().catch(()=>{}),this.changeStream=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}};R();ho();import{SocketModeClient as wM}from"@slack/socket-mode";import{WebClient as bM}from"@slack/web-api";R();var _M=$("outbound-ts-cache"),qc=class{entries=new Map;ttlMs;maxSize;constructor(e={}){this.ttlMs=e.ttlMs??12e4,this.maxSize=e.maxSize??1e4}register(e,t){if(this.evictExpired(),this.entries.size>=this.maxSize){let i=this.entries.keys().next().value;i&&this.entries.delete(i)}this.entries.set(this.key(e,t),Date.now()+this.ttlMs)}has(e,t){let i=this.entries.get(this.key(e,t));return i===void 0?!1:i<=Date.now()?(this.entries.delete(this.key(e,t)),!1):!0}size(){return this.entries.size}key(e,t){return`${e}:${t}`}evictExpired(){let e=Date.now(),t=0;for(let[i,r]of this.entries)r<=e&&(this.entries.delete(i),t++);t>0&&_M.debug(`evicted ${t} expired entries`,{evicted:t})}};var te=$("slack-gateway"),Zc=class n{socket;web;messageHandler=null;threadStartedHandler=null;threadContextHandler=null;botUserId=null;botId=null;peerBotUserIds=new Set;peerBotIds=new Set;channelNameCache=new Map;channelIdCache=new Map;userNameCache=new Map;outboundTsCache=new qc;integrationChannels=new Set;botToken;constructor(e,t){this.socket=new wM({appToken:e}),this.web=new bM(t),this.botToken=t}addIntegrationChannels(e){for(let t of e)this.integrationChannels.add(t)}addPeerBotIds(e,t){e&&this.peerBotUserIds.add(e),t&&this.peerBotIds.add(t),te.info("Peer bot IDs registered",{peerBotUserIds:[...this.peerBotUserIds],peerBotIds:[...this.peerBotIds]})}get resolvedBotUserId(){return this.botUserId}get resolvedBotId(){return this.botId}onMessage(e){this.messageHandler=e}onThreadStarted(e){this.threadStartedHandler=e}onThreadContextChanged(e){this.threadContextHandler=e}async start(){let e=await this.web.auth.test();this.botUserId=e.user_id,this.botId=e.bot_id??null,te.info("Bot identity resolved",{botUserId:this.botUserId,botId:this.botId}),this.socket.on("message",async({event:t,ack:i})=>{if(await i(),!t||(te.debug("Raw message event",{subtype:t.subtype,bot_id:t.bot_id,user:t.user,channel:t.channel,hasText:!!t.text,hasAttachments:!!t.attachments?.length,hasBlocks:!!t.blocks?.length}),t.user===this.botUserId)||this.peerBotUserIds.has(t.user)||t.bot_id&&t.bot_id===this.botId||t.bot_id&&this.peerBotIds.has(t.bot_id))return;if(t.ts&&t.channel&&this.outboundTsCache.has(t.channel,t.ts)){te.info("Outbound echo suppressed",{channel:t.channel,ts:t.ts});return}if(t.bot_id||t.subtype){let l=await this.resolveChannelName(t.channel);if(!this.integrationChannels.has(l)){te.info("Message filtered (subtype/bot in non-integration channel)",{channel:t.channel,channelName:l,user:t.user,subtype:t.subtype,bot_id:t.bot_id,hasText:!!t.text});return}te.info("Integration message accepted",{channelName:l,subtype:t.subtype,bot_id:t.bot_id})}let r=await this.resolveChannelName(t.channel),o=t.text??"";if(!o){let l=[...t.blocks??[]];for(let c of t.attachments??[])c.blocks&&l.push(...c.blocks),c.text&&(o+=c.text+`
332
+ `);o||(o=l.filter(c=>c.type==="section"||c.type==="rich_text").map(c=>c.text?.text?c.text.text:c.elements?c.elements.map(u=>u.elements?.map(d=>d.text||"").join("")??"").join(`
293
333
  `):"").filter(Boolean).join(`
294
- `)),i=i.trim()}let o=[];if(t.files?.length&&(K.info("Processing file attachments",{count:t.files.length,names:t.files.map(c=>c.name)}),o=(await Promise.all(t.files.map(c=>jh(c,this.botToken)))).filter(Boolean)),!i&&o.length===0){K.info("Skipping message with no extractable text or files",{channel:t.channel,channelName:r,user:t.user,subtype:t.subtype,hasBlocks:!!t.blocks?.length,hasAttachments:!!t.attachments?.length,blockTypes:t.blocks?.map(l=>l.type)});return}!i&&o.length>0&&(i=`[shared ${o.length} file${o.length>1?"s":""}]`),i=await this.resolveUserMentions(i);let a={text:i,channel:t.channel,channelName:r,user:t.user??t.bot_id??"unknown",ts:t.ts,threadTs:t.thread_ts,files:o.length>0?o:void 0};K.info("Message received",{channel:a.channel,channelName:r,user:a.user,textLength:a.text.length,fileCount:o.length}),this.messageHandler?.(a)}),this.socket.on("assistant_thread_started",async({event:t,ack:s})=>{await s(),K.info("Assistant thread started",{channel:t?.assistant_thread?.channel_id});let r=t?.assistant_thread;r&&this.threadStartedHandler?.({channel:r.channel_id,threadTs:r.thread_ts,context:r.context??{}})}),this.socket.on("assistant_thread_context_changed",async({event:t,ack:s})=>{await s(),K.info("Assistant thread context changed",{channel:t?.assistant_thread?.channel_id});let r=t?.assistant_thread;r&&this.threadContextHandler?.({channel:r.channel_id,threadTs:r.thread_ts,context:r.context??{}})}),this.socket.on("slack_event",async({ack:t,body:s})=>{await t();let r=s?.event;r&&K.debug("slack_event",{type:r.type,subtype:r.subtype,channel:r.channel})}),await this.socket.start(),K.info("Socket Mode connected")}async stop(){await this.socket.disconnect(),K.info("Socket Mode disconnected")}async setThreadStatus(e,t,s){try{await this.web.assistant.threads.setStatus({channel_id:e,thread_ts:t,status:s})}catch(r){K.warn("Failed to set thread status",{error:String(r)})}}async setSuggestedPrompts(e,t,s){try{await this.web.assistant.threads.setSuggestedPrompts({channel_id:e,thread_ts:t,prompts:s})}catch(r){K.warn("Failed to set suggested prompts",{error:String(r)})}}async setThreadTitle(e,t,s){try{await this.web.assistant.threads.setTitle({channel_id:e,thread_ts:t,title:s})}catch(r){K.warn("Failed to set thread title",{error:String(r)})}}async startStream(e,t){try{let s=await this.web.chat.startStream({channel:e,thread_ts:t});return s.channel&&s.ts?{channel:s.channel,ts:s.ts}:void 0}catch(s){K.warn("Failed to start stream",{error:String(s)});return}}async appendStream(e,t,s){try{await this.web.chat.appendStream({channel:e,ts:t,markdown_text:s})}catch(r){K.warn("Failed to append stream",{error:String(r)})}}async stopStream(e,t){try{await this.web.chat.stopStream({channel:e,ts:t})}catch(s){K.warn("Failed to stop stream",{error:String(s)})}}static SLACK_MAX_CHARS=3900;static SPLIT_MAX_CHARS=8e3;static SUMMARY_LENGTH=200;async postMessage(e,t,s,r){return t.length<=n.SLACK_MAX_CHARS?this.postSingle(e,t,s,r):t.length<=n.SPLIT_MAX_CHARS?this.postSplit(e,t,s,r):this.postAsFile(e,t,s,r)}async postSingle(e,t,s,r){if(r)try{let i={};r.icon&&(r.icon.startsWith(":")&&r.icon.endsWith(":")?i.icon_emoji=r.icon:i.icon_url=r.icon);let o=await this.web.chat.postMessage({channel:e,text:t,thread_ts:s,unfurl_links:!1,username:r.name,...i});return o.ok&&o.ts&&o.channel&&this.outboundTsCache.register(o.channel,o.ts),o.ts}catch(i){K.warn("Failed to post with identity, falling back to plain post",{error:String(i)})}try{let i=await this.web.chat.postMessage({channel:e,text:t,thread_ts:s,unfurl_links:!1});return i.ok&&i.ts&&i.channel&&this.outboundTsCache.register(i.channel,i.ts),i.ts}catch(i){K.error("Failed to post message",{channel:e,error:String(i)});return}}splitText(e){let t=n.SLACK_MAX_CHARS,s=[],r=e;for(;r.length>t;){let i=-1,o=r.lastIndexOf(`
295
-
296
- `,t);if(o>0&&(i=o+2),i===-1){let a=r.lastIndexOf(`
297
- `,t);a>0&&(i=a+1)}if(i===-1){let a=r.lastIndexOf(" ",t);a>0&&(i=a+1)}i===-1&&(i=t),s.push(r.slice(0,i).trimEnd()),r=r.slice(i).trimStart()}return r.length>0&&s.push(r),s}async postSplit(e,t,s,r){let i=this.splitText(t);K.info("Splitting oversized message",{channel:e,totalLength:t.length,chunks:i.length});let o;for(let a=0;a<i.length;a++){let l=a===0?i[a]:`_(cont.)_ ${i[a]}`,c=await this.postSingle(e,l,s,r);a===0&&(o=c)}return o}async postAsFile(e,t,s,r){let i=t.slice(0,n.SUMMARY_LENGTH),o=i,a=Math.max(i.lastIndexOf(". "),i.lastIndexOf(`.
298
- `),i.lastIndexOf(`?
299
- `),i.lastIndexOf("? "),i.lastIndexOf(`!
300
- `),i.lastIndexOf("! "));if(a>0)o=i.slice(0,a+1);else{let h=i.lastIndexOf(`
301
- `);h>0&&(o=i.slice(0,h))}o=`${o.trimEnd()}
302
-
303
- _(full response attached)_`;let l=r?.name??"hive",c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=`${l.toLowerCase()}-${c}.md`,u=await this.postSingle(e,o,s,r);try{let h={content:t,filename:d,title:`${l} response`},p=s?{channel_id:e,thread_ts:s}:{channel_id:e};return await this.web.files.uploadV2({...h,...p}),K.info("Uploaded oversized message as file",{channel:e,filename:d,length:t.length}),u}catch(h){return K.warn("File upload failed, falling back to split",{channel:e,error:String(h)}),this.postSplit(e,t,s,r)}}async addReaction(e,t,s){try{await this.web.reactions.add({channel:e,name:s,timestamp:t})}catch(r){let i=String(r);i.includes("already_reacted")||K.warn("Failed to add reaction",{channel:e,ts:t,emoji:s,error:i})}}async removeReaction(e,t,s){try{await this.web.reactions.remove({channel:e,name:s,timestamp:t})}catch{}}async resolveUserName(e){let t=this.userNameCache.get(e);if(t)return t;try{let s=await this.web.users.info({user:e});return t=s.user?.profile?.display_name||s.user?.real_name||s.user?.name||e,this.userNameCache.set(e,t),t}catch{return this.userNameCache.set(e,e),e}}async resolveUserMentions(e){let t=/<@(U[A-Z0-9]+)>/g,s=[...e.matchAll(t)];if(s.length===0)return e;let r=e;for(let i of s){let o=i[1],a=this.userNameCache.get(o);if(!a)try{let l=await this.web.users.info({user:o});a=l.user?.profile?.display_name||l.user?.real_name||l.user?.name||o,this.userNameCache.set(o,a)}catch{this.userNameCache.set(o,o);continue}r=r.replace(i[0],`@${a}`)}return r}registerOutboundTs(e,t){this.outboundTsCache.register(e,t)}isOutboundEcho(e,t){return this.outboundTsCache.has(e,t)}async postAndRegister(e,t,s){try{let r=await this.postMessage(e,t,s);return r?{ok:!0,ts:r}:{ok:!1,error:"postMessage returned no ts"}}catch(r){return{ok:!1,error:r.message}}}async resolveChannelId(e){if(e.startsWith("C")||e.startsWith("D")||e.startsWith("G"))return e;let t=e.replace(/^#/,""),s=this.channelIdCache.get(t);if(s)return s;try{let r;do{let i=await this.web.conversations.list({limit:1e3,cursor:r,exclude_archived:!0,types:"public_channel,private_channel"});for(let o of i.channels??[])o.id&&o.name&&(this.channelNameCache.set(o.id,o.name),this.channelIdCache.set(o.name,o.id));r=i.response_metadata?.next_cursor||void 0}while(r)}catch(r){return K.warn("channel id resolve failed",{name:t,error:r.message}),null}return this.channelIdCache.get(t)??null}async resolveChannelName(e){let t=this.channelNameCache.get(e);if(t)return t;try{let r=(await this.web.conversations.info({channel:e})).channel?.name??e;return this.channelNameCache.set(e,r),r}catch{return this.channelNameCache.set(e,e),e}}async readChannel(e,t=50){try{return(await this.web.conversations.history({channel:e,limit:t})).messages}catch(s){K.warn("readChannel failed",{channel:e,error:s.message});return}}async listChannels(e){let t=[];try{let s;do{let r=await this.web.conversations.list({limit:1e3,cursor:s,exclude_archived:!0,types:"public_channel,private_channel"});for(let i of r.channels??[])i.id&&i.name&&(this.channelNameCache.set(i.id,i.name),this.channelIdCache.set(i.name,i.id),(!e||i.name.includes(e))&&t.push({id:i.id,name:i.name}));s=r.response_metadata?.next_cursor||void 0}while(s)}catch(s){K.warn("listChannels failed",{query:e,error:s.message})}return t}async readUser(e){try{return(await this.web.users.info({user:e})).user}catch(t){K.warn("readUser failed",{user:e,error:t.message});return}}sweep(){let e=this.channelNameCache.size+this.channelIdCache.size+this.userNameCache.size;return this.channelNameCache.clear(),this.channelIdCache.clear(),this.userNameCache.clear(),{component:"slack-gateway",pruned:e,retried:0,bytesFreed:0,errors:[]}}get client(){return this.web}};M();var gk=k("memory-manager"),Lr=class{db;collection;versions;_memoryStore;set memoryStore(e){this._memoryStore=e}constructor(e){this.db=e}async init(){this.collection=this.db.collection("memory"),this.versions=this.db.collection("memory_versions"),await this.collection.createIndex({path:1},{unique:!0}),await this.versions.createIndex({path:1,savedAt:-1}),gk.info("Memory manager connected to MongoDB",{db:this.db.databaseName})}async read(e){return(await this.collection.findOne({path:e}))?.content??null}async list(e){let t=e.endsWith("/")?e:e+"/";return(await this.collection.find({path:{$regex:`^${yk(t)}[^/]+$`}}).project({path:1}).toArray()).map(r=>r.path.slice(t.length))}async getHotTierPrompt(e,t){if(!this._memoryStore)return null;let s=await this._memoryStore.getHotTier(e);if(s.length===0)return null;let r={task:"Active Tasks",fact:"Key Facts",decision:"Recent Decisions",preference:"Preferences",interaction:"Recent Interactions",summary:"Summaries"},i={},o=[],a=0;for(let d of s){let h=`- [${d.updatedAt.toISOString().split("T")[0]}] ${d.content} (${d.importance})`,p=Math.ceil(h.length/4);if(a+p>t&&!d.pinned)break;if(a+=p,d.pinned)o.push(`- ${d.content} (${d.importance}, pinned)`);else{let m=d.type;i[m]||(i[m]=[]),i[m].push(h)}}let l=["## Your Memory"];for(let[d,u]of Object.entries(r))i[d]?.length&&l.push(`### ${u}
304
- ${i[d].join(`
305
- `)}`);o.length>0&&l.push(`### Pinned
306
- ${o.join(`
334
+ `)),o=o.trim()}let s=[];if(t.files?.length&&(te.info("Processing file attachments",{count:t.files.length,names:t.files.map(c=>c.name)}),s=(await Promise.all(t.files.map(c=>Qx(c,this.botToken)))).filter(Boolean)),!o&&s.length===0){te.info("Skipping message with no extractable text or files",{channel:t.channel,channelName:r,user:t.user,subtype:t.subtype,hasBlocks:!!t.blocks?.length,hasAttachments:!!t.attachments?.length,blockTypes:t.blocks?.map(l=>l.type)});return}!o&&s.length>0&&(o=`[shared ${s.length} file${s.length>1?"s":""}]`),o=await this.resolveUserMentions(o);let a={text:o,channel:t.channel,channelName:r,user:t.user??t.bot_id??"unknown",ts:t.ts,threadTs:t.thread_ts,files:s.length>0?s:void 0};te.info("Message received",{channel:a.channel,channelName:r,user:a.user,textLength:a.text.length,fileCount:s.length}),this.messageHandler?.(a)}),this.socket.on("assistant_thread_started",async({event:t,ack:i})=>{await i(),te.info("Assistant thread started",{channel:t?.assistant_thread?.channel_id});let r=t?.assistant_thread;r&&this.threadStartedHandler?.({channel:r.channel_id,threadTs:r.thread_ts,context:r.context??{}})}),this.socket.on("assistant_thread_context_changed",async({event:t,ack:i})=>{await i(),te.info("Assistant thread context changed",{channel:t?.assistant_thread?.channel_id});let r=t?.assistant_thread;r&&this.threadContextHandler?.({channel:r.channel_id,threadTs:r.thread_ts,context:r.context??{}})}),this.socket.on("slack_event",async({ack:t,body:i})=>{await t();let r=i?.event;r&&te.debug("slack_event",{type:r.type,subtype:r.subtype,channel:r.channel})}),await this.socket.start(),te.info("Socket Mode connected")}async stop(){await this.socket.disconnect(),te.info("Socket Mode disconnected")}async setThreadStatus(e,t,i){try{await this.web.assistant.threads.setStatus({channel_id:e,thread_ts:t,status:i})}catch(r){te.warn("Failed to set thread status",{error:String(r)})}}async setSuggestedPrompts(e,t,i){try{await this.web.assistant.threads.setSuggestedPrompts({channel_id:e,thread_ts:t,prompts:i})}catch(r){te.warn("Failed to set suggested prompts",{error:String(r)})}}async setThreadTitle(e,t,i){try{await this.web.assistant.threads.setTitle({channel_id:e,thread_ts:t,title:i})}catch(r){te.warn("Failed to set thread title",{error:String(r)})}}async startStream(e,t){try{let i=await this.web.chat.startStream({channel:e,thread_ts:t});return i.channel&&i.ts?{channel:i.channel,ts:i.ts}:void 0}catch(i){te.warn("Failed to start stream",{error:String(i)});return}}async appendStream(e,t,i){try{await this.web.chat.appendStream({channel:e,ts:t,markdown_text:i})}catch(r){te.warn("Failed to append stream",{error:String(r)})}}async stopStream(e,t){try{await this.web.chat.stopStream({channel:e,ts:t})}catch(i){te.warn("Failed to stop stream",{error:String(i)})}}static SLACK_MAX_CHARS=3900;static SPLIT_MAX_CHARS=8e3;static SUMMARY_LENGTH=200;async postMessage(e,t,i,r){return t.length<=n.SLACK_MAX_CHARS?this.postSingle(e,t,i,r):t.length<=n.SPLIT_MAX_CHARS?this.postSplit(e,t,i,r):this.postAsFile(e,t,i,r)}async postSingle(e,t,i,r){if(r)try{let o={};r.icon&&(r.icon.startsWith(":")&&r.icon.endsWith(":")?o.icon_emoji=r.icon:o.icon_url=r.icon);let s=await this.web.chat.postMessage({channel:e,text:t,thread_ts:i,unfurl_links:!1,username:r.name,...o});return s.ok&&s.ts&&s.channel&&this.outboundTsCache.register(s.channel,s.ts),s.ts}catch(o){te.warn("Failed to post with identity, falling back to plain post",{error:String(o)})}try{let o=await this.web.chat.postMessage({channel:e,text:t,thread_ts:i,unfurl_links:!1});return o.ok&&o.ts&&o.channel&&this.outboundTsCache.register(o.channel,o.ts),o.ts}catch(o){te.error("Failed to post message",{channel:e,error:String(o)});return}}splitText(e){let t=n.SLACK_MAX_CHARS,i=[],r=e;for(;r.length>t;){let o=-1,s=r.lastIndexOf(`
335
+
336
+ `,t);if(s>0&&(o=s+2),o===-1){let a=r.lastIndexOf(`
337
+ `,t);a>0&&(o=a+1)}if(o===-1){let a=r.lastIndexOf(" ",t);a>0&&(o=a+1)}o===-1&&(o=t),i.push(r.slice(0,o).trimEnd()),r=r.slice(o).trimStart()}return r.length>0&&i.push(r),i}async postSplit(e,t,i,r){let o=this.splitText(t);te.info("Splitting oversized message",{channel:e,totalLength:t.length,chunks:o.length});let s;for(let a=0;a<o.length;a++){let l=a===0?o[a]:`_(cont.)_ ${o[a]}`,c=await this.postSingle(e,l,i,r);a===0&&(s=c)}return s}async postAsFile(e,t,i,r){let o=t.slice(0,n.SUMMARY_LENGTH),s=o,a=Math.max(o.lastIndexOf(". "),o.lastIndexOf(`.
338
+ `),o.lastIndexOf(`?
339
+ `),o.lastIndexOf("? "),o.lastIndexOf(`!
340
+ `),o.lastIndexOf("! "));if(a>0)s=o.slice(0,a+1);else{let f=o.lastIndexOf(`
341
+ `);f>0&&(s=o.slice(0,f))}s=`${s.trimEnd()}
342
+
343
+ _(full response attached)_`;let l=r?.name??"hive",c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),u=`${l.toLowerCase()}-${c}.md`,d=await this.postSingle(e,s,i,r);try{let f={content:t,filename:u,title:`${l} response`},p=i?{channel_id:e,thread_ts:i}:{channel_id:e};return await this.web.files.uploadV2({...f,...p}),te.info("Uploaded oversized message as file",{channel:e,filename:u,length:t.length}),d}catch(f){return te.warn("File upload failed, falling back to split",{channel:e,error:String(f)}),this.postSplit(e,t,i,r)}}async addReaction(e,t,i){try{await this.web.reactions.add({channel:e,name:i,timestamp:t})}catch(r){let o=String(r);o.includes("already_reacted")||te.warn("Failed to add reaction",{channel:e,ts:t,emoji:i,error:o})}}async removeReaction(e,t,i){try{await this.web.reactions.remove({channel:e,name:i,timestamp:t})}catch{}}async resolveUserName(e){let t=this.userNameCache.get(e);if(t)return t;try{let i=await this.web.users.info({user:e});return t=i.user?.profile?.display_name||i.user?.real_name||i.user?.name||e,this.userNameCache.set(e,t),t}catch{return this.userNameCache.set(e,e),e}}async resolveUserMentions(e){let t=/<@(U[A-Z0-9]+)>/g,i=[...e.matchAll(t)];if(i.length===0)return e;let r=e;for(let o of i){let s=o[1],a=this.userNameCache.get(s);if(!a)try{let l=await this.web.users.info({user:s});a=l.user?.profile?.display_name||l.user?.real_name||l.user?.name||s,this.userNameCache.set(s,a)}catch{this.userNameCache.set(s,s);continue}r=r.replace(o[0],`@${a}`)}return r}registerOutboundTs(e,t){this.outboundTsCache.register(e,t)}isOutboundEcho(e,t){return this.outboundTsCache.has(e,t)}async postAndRegister(e,t,i){try{let r=await this.postMessage(e,t,i);return r?{ok:!0,ts:r}:{ok:!1,error:"postMessage returned no ts"}}catch(r){return{ok:!1,error:r.message}}}async resolveChannelId(e){if(e.startsWith("C")||e.startsWith("D")||e.startsWith("G"))return e;let t=e.replace(/^#/,""),i=this.channelIdCache.get(t);if(i)return i;try{let r;do{let o=await this.web.conversations.list({limit:1e3,cursor:r,exclude_archived:!0,types:"public_channel,private_channel"});for(let s of o.channels??[])s.id&&s.name&&(this.channelNameCache.set(s.id,s.name),this.channelIdCache.set(s.name,s.id));r=o.response_metadata?.next_cursor||void 0}while(r)}catch(r){return te.warn("channel id resolve failed",{name:t,error:r.message}),null}return this.channelIdCache.get(t)??null}async resolveChannelName(e){let t=this.channelNameCache.get(e);if(t)return t;try{let r=(await this.web.conversations.info({channel:e})).channel?.name??e;return this.channelNameCache.set(e,r),r}catch{return this.channelNameCache.set(e,e),e}}async readChannel(e,t=50){try{return(await this.web.conversations.history({channel:e,limit:t})).messages}catch(i){te.warn("readChannel failed",{channel:e,error:i.message});return}}async listChannels(e){let t=[];try{let i;do{let r=await this.web.conversations.list({limit:1e3,cursor:i,exclude_archived:!0,types:"public_channel,private_channel"});for(let o of r.channels??[])o.id&&o.name&&(this.channelNameCache.set(o.id,o.name),this.channelIdCache.set(o.name,o.id),(!e||o.name.includes(e))&&t.push({id:o.id,name:o.name}));i=r.response_metadata?.next_cursor||void 0}while(i)}catch(i){te.warn("listChannels failed",{query:e,error:i.message})}return t}async readUser(e){try{return(await this.web.users.info({user:e})).user}catch(t){te.warn("readUser failed",{user:e,error:t.message});return}}sweep(){let e=this.channelNameCache.size+this.channelIdCache.size+this.userNameCache.size;return this.channelNameCache.clear(),this.channelIdCache.clear(),this.userNameCache.clear(),{component:"slack-gateway",pruned:e,retried:0,bytesFreed:0,errors:[]}}get client(){return this.web}};R();var kM=$("memory-manager"),Kc=class{db;collection;versions;_memoryStore;set memoryStore(e){this._memoryStore=e}constructor(e){this.db=e}async init(){this.collection=this.db.collection("memory"),this.versions=this.db.collection("memory_versions"),await this.collection.createIndex({path:1},{unique:!0}),await this.versions.createIndex({path:1,savedAt:-1}),kM.info("Memory manager connected to MongoDB",{db:this.db.databaseName})}async read(e){return(await this.collection.findOne({path:e}))?.content??null}async list(e){let t=e.endsWith("/")?e:e+"/";return(await this.collection.find({path:{$regex:`^${SM(t)}[^/]+$`}}).project({path:1}).toArray()).map(r=>r.path.slice(t.length))}async getHotTierPrompt(e,t){if(!this._memoryStore)return null;let i=await this._memoryStore.getHotTier(e);if(i.length===0)return null;let r={task:"Active Tasks",fact:"Key Facts",decision:"Recent Decisions",preference:"Preferences",interaction:"Recent Interactions",summary:"Summaries"},o={},s=[],a=0;for(let u of i){let f=`- [${u.updatedAt.toISOString().split("T")[0]}] ${u.content} (${u.importance})`,p=Math.ceil(f.length/4);if(a+p>t&&!u.pinned)break;if(a+=p,u.pinned)s.push(`- ${u.content} (${u.importance}, pinned)`);else{let h=u.type;o[h]||(o[h]=[]),o[h].push(f)}}let l=["## Your Memory"];for(let[u,d]of Object.entries(r))o[u]?.length&&l.push(`### ${d}
344
+ ${o[u].join(`
345
+ `)}`);s.length>0&&l.push(`### Pinned
346
+ ${s.join(`
307
347
  `)}`);let c=await this._memoryStore.countNonHot(e);return c>0&&l.push(`---
308
348
  You have ${c} additional memories available via \`memory_recall\`. Use it to search for context before starting tasks.`),l.join(`
309
349
 
310
- `)}async write(e,t,s){let r=await this.collection.findOne({path:e});r&&await this.versions.insertOne({path:e,content:r.content,savedAt:r.updatedAt,savedBy:r.updatedBy}),await this.collection.updateOne({path:e},{$set:{content:t,updatedAt:new Date,...s?{updatedBy:s}:{}}},{upsert:!0})}async commitAndPush(e){}async pull(){}async close(){}};function yk(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}M();Ne();var Q=k("scheduler"),Pr=class{heartbeatTimer=null;cronTimer=null;callbackTimer=null;eventTimer=null;teamTimer=null;agentManager;memoryManager;healthReporter;registry;cronJobs=[];db=null;callbackCollection=null;eventsCollection=null;onDispatch;constructor(e,t,s,r,i){this.agentManager=e,this.memoryManager=t,this.healthReporter=s,this.registry=r,this.onDispatch=i;for(let o of r.getAll())for(let a of o.schedule)this.cronJobs.push({agentId:o.id,cron:a.cron,task:a.task,lastRun:null})}async connectDb(e){this.db=e,this.callbackCollection=this.db.collection("agent_callbacks"),this.eventsCollection=this.db.collection("agent_events"),await this.callbackCollection.createIndex({status:1,dueAt:1}),await this.eventsCollection.createIndex({hasPending:1,createdAt:1}),await this.eventsCollection.createIndex({sourceAgentId:1,createdAt:-1}),await this.eventsCollection.createIndex({domain:1,createdAt:-1}),await this.eventsCollection.createIndex({createdAt:1},{expireAfterSeconds:g.events.retentionDays*86400}),await this.db.collection("team_pending_requests").createIndex({status:1,createdAt:-1}),await this.db.collection("team_pending_requests").createIndex({createdAt:1},{expireAfterSeconds:3600}),Q.info("Callback store connected",{db:e.databaseName})}async reloadSchedules(){this.cronJobs=[];for(let e of this.registry.getAll())for(let t of e.schedule)this.cronJobs.push({agentId:e.id,cron:t.cron,task:t.task,lastRun:null});Q.info("Schedules reloaded",{jobs:this.cronJobs.length})}start(){this.heartbeatTimer=setInterval(async()=>{try{await this.memoryManager.pull(),await this.healthReporter.writeToMemory()}catch(e){Q.error("Heartbeat failed",{error:String(e)})}},g.scheduler.heartbeatIntervalMs),this.cronTimer=setInterval(()=>{this.checkCronJobs()},6e4),this.callbackCollection&&(this.callbackTimer=setInterval(()=>{this.checkCallbacks().catch(e=>{Q.error("Callback check failed",{error:String(e)})})},3e4)),this.eventsCollection&&(this.eventTimer=setInterval(()=>{this.checkEvents().catch(e=>{Q.error("Event check failed",{error:String(e)})})},3e4)),this.db&&(this.teamTimer=setInterval(()=>{this.fireTeamRequests().catch(e=>Q.error("Team request check failed",{error:String(e)}))},5e3)),Q.info("Scheduler started",{heartbeatMs:g.scheduler.heartbeatIntervalMs,cronJobs:this.cronJobs.length,callbacksEnabled:!!this.callbackCollection,eventsEnabled:!!this.eventsCollection})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.cronTimer&&(clearInterval(this.cronTimer),this.cronTimer=null),this.callbackTimer&&(clearInterval(this.callbackTimer),this.callbackTimer=null),this.eventTimer&&(clearInterval(this.eventTimer),this.eventTimer=null),this.teamTimer&&(clearInterval(this.teamTimer),this.teamTimer=null),Q.info("Scheduler stopped")}checkCronJobs(){let e=new Date;for(let t of this.cronJobs)if(wk(t.cron,e)){if(t.lastRun&&Sk(t.lastRun,e))continue;t.lastRun=e;let s=this.registry.get(t.agentId);if(s?.disabled){Q.debug("Skipping scheduled task \u2014 agent disabled",{agentId:t.agentId,task:t.task});continue}Q.info("Triggering scheduled task",{agentId:t.agentId,task:t.task});let r=s?.homeBase??s?.channels?.[0];if(!r){Q.error("Cannot dispatch scheduled task \u2014 agent has no homeBase or channels",{agentId:t.agentId,task:t.task});continue}let i={id:`sched:${t.agentId}:${t.task}:${Date.now()}`,text:`[Scheduled task: ${t.task}] Execute your scheduled "${t.task}" task now.`,source:{kind:"slack",id:r,label:r},sender:"system",threadId:`scheduler:${t.agentId}:${t.task}:${Date.now()}`,timestamp:e,meta:{targetAgentId:t.agentId}};this.onDispatch?this.onDispatch(i):this.agentManager.sendMessage(t.agentId,i).catch(o=>{Q.error("Scheduled task failed",{agentId:t.agentId,task:t.task,error:String(o)})})}}async checkCallbacks(){if(!this.callbackCollection)return;let e=new Date,t=this.callbackCollection.find({status:"pending",dueAt:{$lte:e}});for await(let s of t){if((await this.callbackCollection.updateOne({_id:s._id,status:"pending"},{$set:{status:"fired",firedAt:e}})).modifiedCount===0)continue;Q.info("Firing callback",{agentId:s.agentId,callbackId:s._id.toString(),contextPreview:s.context.slice(0,80)});let i=this.registry.get(s.agentId);if(!i){Q.warn("Callback agent not found, skipping",{agentId:s.agentId});continue}if(i.disabled){Q.info("Callback agent disabled, skipping",{agentId:s.agentId});continue}let o={id:`callback:${s._id.toString()}`,text:`[Scheduled callback] ${s.context}`,source:{kind:s.source.channelKind||"slack",id:s.source.channelId,label:s.source.channelLabel,adapterId:s.source.adapterId},sender:"system",threadId:s.source.threadId||void 0,timestamp:e,meta:{slackTs:s.source.slackTs,slackThreadTs:s.source.slackThreadTs,targetAgentId:s.agentId}};this.onDispatch?this.onDispatch(o):this.agentManager.sendMessage(s.agentId,o).catch(a=>{Q.error("Callback dispatch failed",{agentId:s.agentId,callbackId:s._id.toString(),error:String(a)})})}}async checkEvents(){if(!this.eventsCollection)return;let e=this.eventsCollection.find({hasPending:!0});for await(let t of e){let s=t.deliveries.filter(r=>r.status==="pending");for(let r of s){let i=new Date;if((await this.eventsCollection.updateOne({_id:t._id,deliveries:{$elemMatch:{agentId:r.agentId,status:"pending"}}},{$set:{"deliveries.$.status":"fired","deliveries.$.firedAt":i}})).modifiedCount===0)continue;await this.eventsCollection.updateOne({_id:t._id,"deliveries.status":{$ne:"pending"}},{$set:{hasPending:!1}});let a=this.registry.get(r.agentId);if(!a){Q.warn("Event target agent not found, skipping",{agentId:r.agentId,eventType:t.type});continue}if(a.disabled){Q.info("Event target agent disabled, skipping",{agentId:r.agentId,eventType:t.type});continue}let l=t._id.toHexString(),d=this.registry.get(t.sourceAgentId)?.name??t.sourceAgentId;Q.info("Dispatching event",{eventType:t.type,eventId:l,targetAgent:r.agentId,sourceAgent:t.sourceAgentId});let u=a.homeBase??`agent-${r.agentId}`,h={id:`event:${l}:${r.agentId}`,text:`[Event: ${t.type} from ${d}]
350
+ `)}async write(e,t,i){let r=await this.collection.findOne({path:e});r&&await this.versions.insertOne({path:e,content:r.content,savedAt:r.updatedAt,savedBy:r.updatedBy}),await this.collection.updateOne({path:e},{$set:{content:t,updatedAt:new Date,...i?{updatedBy:i}:{}}},{upsert:!0})}async commitAndPush(e){}async pull(){}async close(){}};function SM(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}R();ot();var pe=$("scheduler"),Vc=class{heartbeatTimer=null;cronTimer=null;callbackTimer=null;eventTimer=null;teamTimer=null;agentManager;memoryManager;healthReporter;registry;cronJobs=[];db=null;callbackCollection=null;eventsCollection=null;onDispatch;constructor(e,t,i,r,o){this.agentManager=e,this.memoryManager=t,this.healthReporter=i,this.registry=r,this.onDispatch=o;for(let s of r.getAll())for(let a of s.schedule)this.cronJobs.push({agentId:s.id,cron:a.cron,task:a.task,lastRun:null})}async connectDb(e){this.db=e,this.callbackCollection=this.db.collection("agent_callbacks"),this.eventsCollection=this.db.collection("agent_events"),await this.callbackCollection.createIndex({status:1,dueAt:1}),await this.eventsCollection.createIndex({hasPending:1,createdAt:1}),await this.eventsCollection.createIndex({sourceAgentId:1,createdAt:-1}),await this.eventsCollection.createIndex({domain:1,createdAt:-1}),await this.eventsCollection.createIndex({createdAt:1},{expireAfterSeconds:g.events.retentionDays*86400}),await this.db.collection("team_pending_requests").createIndex({status:1,createdAt:-1}),await this.db.collection("team_pending_requests").createIndex({createdAt:1},{expireAfterSeconds:3600}),pe.info("Callback store connected",{db:e.databaseName})}async reloadSchedules(){this.cronJobs=[];for(let e of this.registry.getAll())for(let t of e.schedule)this.cronJobs.push({agentId:e.id,cron:t.cron,task:t.task,lastRun:null});pe.info("Schedules reloaded",{jobs:this.cronJobs.length})}start(){this.heartbeatTimer=setInterval(async()=>{try{await this.memoryManager.pull(),await this.healthReporter.writeToMemory()}catch(e){pe.error("Heartbeat failed",{error:String(e)})}},g.scheduler.heartbeatIntervalMs),this.cronTimer=setInterval(()=>{this.checkCronJobs()},6e4),this.callbackCollection&&(this.callbackTimer=setInterval(()=>{this.checkCallbacks().catch(e=>{pe.error("Callback check failed",{error:String(e)})})},3e4)),this.eventsCollection&&(this.eventTimer=setInterval(()=>{this.checkEvents().catch(e=>{pe.error("Event check failed",{error:String(e)})})},3e4)),this.db&&(this.teamTimer=setInterval(()=>{this.fireTeamRequests().catch(e=>pe.error("Team request check failed",{error:String(e)}))},5e3)),pe.info("Scheduler started",{heartbeatMs:g.scheduler.heartbeatIntervalMs,cronJobs:this.cronJobs.length,callbacksEnabled:!!this.callbackCollection,eventsEnabled:!!this.eventsCollection})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.cronTimer&&(clearInterval(this.cronTimer),this.cronTimer=null),this.callbackTimer&&(clearInterval(this.callbackTimer),this.callbackTimer=null),this.eventTimer&&(clearInterval(this.eventTimer),this.eventTimer=null),this.teamTimer&&(clearInterval(this.teamTimer),this.teamTimer=null),pe.info("Scheduler stopped")}checkCronJobs(){let e=new Date;for(let t of this.cronJobs)if($M(t.cron,e)){if(t.lastRun&&xM(t.lastRun,e))continue;t.lastRun=e;let i=this.registry.get(t.agentId);if(i?.disabled){pe.debug("Skipping scheduled task \u2014 agent disabled",{agentId:t.agentId,task:t.task});continue}pe.info("Triggering scheduled task",{agentId:t.agentId,task:t.task});let r=i?.homeBase??i?.channels?.[0];if(!r){pe.error("Cannot dispatch scheduled task \u2014 agent has no homeBase or channels",{agentId:t.agentId,task:t.task});continue}let o={id:`sched:${t.agentId}:${t.task}:${Date.now()}`,text:`[Scheduled task: ${t.task}] Execute your scheduled "${t.task}" task now.`,source:{kind:"slack",id:r,label:r},sender:"system",threadId:`scheduler:${t.agentId}:${t.task}:${Date.now()}`,timestamp:e,meta:{targetAgentId:t.agentId}};this.onDispatch?this.onDispatch(o):this.agentManager.sendMessage(t.agentId,o).catch(s=>{pe.error("Scheduled task failed",{agentId:t.agentId,task:t.task,error:String(s)})})}}async checkCallbacks(){if(!this.callbackCollection)return;let e=new Date,t=this.callbackCollection.find({status:"pending",dueAt:{$lte:e}});for await(let i of t){if((await this.callbackCollection.updateOne({_id:i._id,status:"pending"},{$set:{status:"fired",firedAt:e}})).modifiedCount===0)continue;pe.info("Firing callback",{agentId:i.agentId,callbackId:i._id.toString(),contextPreview:i.context.slice(0,80)});let o=this.registry.get(i.agentId);if(!o){pe.warn("Callback agent not found, skipping",{agentId:i.agentId});continue}if(o.disabled){pe.info("Callback agent disabled, skipping",{agentId:i.agentId});continue}let s={id:`callback:${i._id.toString()}`,text:`[Scheduled callback] ${i.context}`,source:{kind:i.source.channelKind||"slack",id:i.source.channelId,label:i.source.channelLabel,adapterId:i.source.adapterId},sender:"system",threadId:i.source.threadId||void 0,timestamp:e,meta:{slackTs:i.source.slackTs,slackThreadTs:i.source.slackThreadTs,targetAgentId:i.agentId}};this.onDispatch?this.onDispatch(s):this.agentManager.sendMessage(i.agentId,s).catch(a=>{pe.error("Callback dispatch failed",{agentId:i.agentId,callbackId:i._id.toString(),error:String(a)})})}}async checkEvents(){if(!this.eventsCollection)return;let e=this.eventsCollection.find({hasPending:!0});for await(let t of e){let i=t.deliveries.filter(r=>r.status==="pending");for(let r of i){let o=new Date;if((await this.eventsCollection.updateOne({_id:t._id,deliveries:{$elemMatch:{agentId:r.agentId,status:"pending"}}},{$set:{"deliveries.$.status":"fired","deliveries.$.firedAt":o}})).modifiedCount===0)continue;await this.eventsCollection.updateOne({_id:t._id,"deliveries.status":{$ne:"pending"}},{$set:{hasPending:!1}});let a=this.registry.get(r.agentId);if(!a){pe.warn("Event target agent not found, skipping",{agentId:r.agentId,eventType:t.type});continue}if(a.disabled){pe.info("Event target agent disabled, skipping",{agentId:r.agentId,eventType:t.type});continue}let l=t._id.toHexString(),u=this.registry.get(t.sourceAgentId)?.name??t.sourceAgentId;pe.info("Dispatching event",{eventType:t.type,eventId:l,targetAgent:r.agentId,sourceAgent:t.sourceAgentId});let d=a.homeBase??`agent-${r.agentId}`,f={id:`event:${l}:${r.agentId}`,text:`[Event: ${t.type} from ${u}]
311
351
 
312
- ${JSON.stringify(t.payload)}`,source:{kind:"internal",id:u,label:u},sender:"system",threadId:`event:${l}:${r.agentId}:${i.getTime()}`,timestamp:i,meta:{targetAgentId:r.agentId,eventType:t.type,eventDomain:t.domain,eventId:l}};this.onDispatch?this.onDispatch(h):this.agentManager.sendMessage(r.agentId,h).catch(p=>{Q.error("Event dispatch failed",{agentId:r.agentId,eventType:t.type,eventId:l,error:String(p)})})}}}async fireTeamRequests(){if(!this.db)return;let e=await this.db.collection("team_pending_requests").find({status:"pending"}).toArray();for(let t of e){if(!await this.db.collection("team_pending_requests").findOneAndUpdate({_id:t._id,status:"pending"},{$set:{status:"fired",firedAt:new Date}}))continue;let r={id:`team-${String(t._id)}`,text:t.text,source:{kind:"internal",id:t.channelId,label:`internal:${t.fromAgentId}\u2192${t.targetAgentId}`},sender:t.fromAgentId,senderName:t.fromAgentId,threadId:`internal:${t.channelId}:${t.threadId}`,timestamp:new Date,meta:{targetAgentId:t.targetAgentId,teamRequestId:String(t._id),teamRequestType:t.type}};try{if(t.type==="fire_and_forget")this.onDispatch?this.onDispatch(r):this.agentManager.sendMessage(t.targetAgentId,r).catch(i=>Q.error("Fire-and-forget team message failed",{target:t.targetAgentId,error:String(i)}));else if(t.type==="request_response"){let i=await this.agentManager.sendMessage(t.targetAgentId,r);await this.db.collection("team_messages").insertOne({channelId:t.channelId,threadId:t.threadId,senderId:t.targetAgentId,senderType:"agent",senderName:t.targetAgentId,text:i.text,createdAt:new Date}),await this.db.collection("team_pending_requests").updateOne({_id:t._id},{$set:{status:"completed",response:i.text}})}}catch(i){Q.error("Team request dispatch failed",{requestId:String(t._id),target:t.targetAgentId,error:String(i)}),await this.db.collection("team_pending_requests").updateOne({_id:t._id},{$set:{status:"failed",error:String(i)}})}}}};function wk(n,e){let t=n.split(/\s+/);if(t.length!==5)return!1;let[s,r,i,o,a]=t,l=e.getMinutes(),c=e.getHours(),d=e.getDate(),u=e.getMonth()+1,h=e.getDay();return Js(s,l)&&Js(r,c)&&Js(i,d)&&Js(o,u)&&Js(a,h)}function Js(n,e){if(n==="*")return!0;if(n.includes("-")){let[t,s]=n.split("-").map(Number);return e>=t&&e<=s}if(n.includes(","))return n.split(",").map(Number).includes(e);if(n.startsWith("*/")){let t=Number(n.slice(2));return e%t===0}return Number(n)===e}function Sk(n,e){return n.getFullYear()===e.getFullYear()&&n.getMonth()===e.getMonth()&&n.getDate()===e.getDate()&&n.getHours()===e.getHours()&&n.getMinutes()===e.getMinutes()}M();var kk=k("health-reporter"),$r=class{agentManager;memoryManager;registry;constructor(e,t,s){this.agentManager=e,this.memoryManager=t,this.registry=s}generateReport(){let e={};for(let t of this.agentManager.getAllStates())e[t.id]={status:t.status,lastActivity:t.lastActivity.toISOString(),messagesProcessed:t.messagesProcessed,errorCount:t.errorCount,sessionId:t.currentSessionId,activeThreads:t.activeThreadCount??0};return{lastUpdated:new Date().toISOString(),agents:e}}formatForSlack(){let e=this.generateReport();if(Object.keys(e.agents).length===0)return"No agents are currently registered.";let s=[`*Hive Status* \u2014 ${new Date().toLocaleString()}
313
- `];for(let[r,i]of Object.entries(e.agents)){let l=this.registry?.get(r)?.disabled?":no_entry_sign:":i.status==="idle"?":white_circle:":i.status==="processing"?":large_blue_circle:":i.status==="error"?":red_circle:":":black_circle:",c=i.activeThreads>0?` (${i.activeThreads} threads)`:"";s.push(`${l} *${r}*${c}`),s.push(` Messages: ${i.messagesProcessed} | Errors: ${i.errorCount}`),s.push(` Last active: ${new Date(i.lastActivity).toLocaleString()}`)}return s.join(`
314
- `)}async writeToMemory(){let e=this.generateReport();await this.memoryManager.write("status/health.json",JSON.stringify(e,null,2)),await this.memoryManager.commitAndPush("heartbeat: update agent status"),kk.info("Health report written to memory")}};M();import{LinearClient as bk}from"@linear/sdk";var me=k("linear-client"),Rr=class{client;defaultTeamId;constructor(e,t){this.client=new bk({apiKey:e}),this.defaultTeamId=t}async listTeams(){try{return(await this.client.teams()).nodes.map(t=>({id:t.id,name:t.name,key:t.key}))}catch(e){return me.error("Failed to list teams",{error:String(e)}),[]}}async createIssue(e,t){try{let s=t?.teamId??this.defaultTeamId;if(!s)return me.error("Cannot create issue: no teamId provided and no default set"),null;let i=await(await this.client.createIssue({teamId:s,title:e,description:t?.description,priority:t?.priority,stateId:t?.stateId,labelIds:t?.labelIds})).issue;return i?(me.info("Issue created",{identifier:i.identifier,title:e}),{identifier:i.identifier,id:i.id,url:i.url}):(me.error("Issue creation returned no issue",{title:e}),null)}catch(s){return me.error("Failed to create issue",{error:String(s),title:e}),null}}async updateIssue(e,t){try{return await this.client.updateIssue(e,t),me.info("Issue updated",{issueId:e,...t}),!0}catch(s){return me.error("Failed to update issue",{error:String(s),issueId:e}),!1}}async addComment(e,t){try{let r=await(await this.client.createComment({issueId:e,body:t})).comment;return me.info("Comment added",{issueId:e,commentId:r?.id}),r?.id??null}catch(s){return me.error("Failed to add comment",{error:String(s),issueId:e}),null}}async listIssues(e){try{let t=e?.teamId??this.defaultTeamId,s={};t&&(s.team={id:{eq:t}}),e?.stateType&&(s.state={type:{eq:e.stateType}}),e?.assigneeEmail&&(s.assignee={email:{eq:e.assigneeEmail}});let r=await this.client.issues({filter:s,first:e?.limit??50,orderBy:"updatedAt"}),i=[];for(let o of r.nodes){let a=await o.state,l=await o.assignee;i.push({identifier:o.identifier,id:o.id,title:o.title,state:a?.name??"Unknown",priority:o.priority,url:o.url,assignee:l?{id:l.id,name:l.name,email:l.email}:void 0})}return i}catch(t){return me.error("Failed to list issues",{error:String(t)}),[]}}async searchIssues(e,t,s){try{let r=s??this.defaultTeamId,o=(await this.client.searchIssues(e,{first:t??10})).nodes,a=[];for(let l of o){if(r&&(await l.team)?.id!==r)continue;let c=await l.state,d=await l.assignee;a.push({identifier:l.identifier,id:l.id,title:l.title,state:c?.name??"Unknown",priority:l.priority,url:l.url,assignee:d?{id:d.id,name:d.name,email:d.email}:void 0})}return a}catch(r){return me.error("Failed to search issues",{error:String(r),term:e}),[]}}async getWorkflowStates(e){try{let t=e??this.defaultTeamId,s={};return t&&(s.team={id:{eq:t}}),(await this.client.workflowStates({filter:s})).nodes.map(i=>({id:i.id,name:i.name,type:i.type}))}catch(t){return me.error("Failed to get workflow states",{error:String(t)}),[]}}async searchUsers(e,t){try{return(await this.client.users({filter:{or:[{name:{containsIgnoreCase:e}},{displayName:{containsIgnoreCase:e}},{email:{containsIgnoreCase:e}}]},first:t??10})).nodes.map(r=>({id:r.id,name:r.name,displayName:r.displayName,email:r.email,active:r.active}))}catch(s){return me.error("Failed to search users",{error:String(s),query:e}),[]}}async findIssueByIdentifier(e){try{let t=await this.client.issue(e),s=await t.state,r=await t.assignee;return{identifier:t.identifier,id:t.id,title:t.title,state:s?.name??"Unknown",priority:t.priority,url:t.url,description:t.description??void 0,assignee:r?{id:r.id,name:r.name,email:r.email}:void 0}}catch(t){return me.error("Failed to find issue",{error:String(t),identifier:e}),null}}};M();var Ba=k("session-store"),Br=class{db;collection;constructor(e){this.db=e}async init(){this.collection=this.db.collection("sessions"),await this.collection.createIndex({updatedAt:1},{expireAfterSeconds:10080*60}),await this.collection.createIndex({agentId:1}),await this.collection.createIndex({threadId:1});let e=await this.collection.countDocuments();Ba.info("Session store connected",{count:e})}async withRetry(e,t,s){try{return await e()}catch(r){return Ba.error("MongoDB operation failed, using fallback",{label:s,error:String(r?.message??r)}),t}}async get(e,t){return this.withRetry(async()=>{let s=await this.collection.findOne({_id:`${e}:${t}`});if(s)return s.sessionId;if(t.startsWith("slack:")){let r=t.split(":").pop();return(await this.collection.findOne({_id:`${e}:${r}`}))?.sessionId}},void 0,`get(${e}:${t})`)}async set(e,t,s,r){await this.withRetry(async()=>{let i=new Date,o={$set:{agentId:e,threadId:t,sessionId:s,updatedAt:i},$setOnInsert:{createdAt:i,compactions:0}};r?(o.$set.inputTokens=r.inputTokens,o.$set.outputTokens=r.outputTokens,o.$set.cacheReadTokens=r.cacheReadTokens,o.$set.cacheCreationTokens=r.cacheCreationTokens,o.$set.contextWindow=r.contextWindow,r.compactions>0&&(o.$inc={compactions:r.compactions},o.$set.lastCompactedAt=i,r.preCompactTokens!==void 0&&(o.$set.preCompactTokens=r.preCompactTokens),delete o.$setOnInsert.compactions)):Object.assign(o.$setOnInsert,{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,contextWindow:0}),await this.collection.updateOne({_id:`${e}:${t}`},o,{upsert:!0})},void 0,`set(${e}:${t})`)}async delete(e,t){await this.withRetry(async()=>{await this.collection.deleteOne({_id:`${e}:${t}`})},void 0,`delete(${e}:${t})`)}async clearAgent(e){await this.withRetry(async()=>{let t=await this.collection.deleteMany({agentId:e});t.deletedCount>0&&Ba.info("Cleared agent sessions",{agentId:e,deleted:t.deletedCount})},void 0,`clearAgent(${e})`)}async findAgentByThread(e){return this.withRetry(async()=>(await this.collection.findOne({threadId:e},{sort:{updatedAt:-1},projection:{agentId:1}}))?.agentId,void 0,`findAgentByThread(${e})`)}async findAgentsByThread(e){return this.withRetry(async()=>{let t=await this.collection.find({threadId:e},{projection:{agentId:1},sort:{updatedAt:-1}}).toArray();return[...new Set(t.map(s=>s.agentId))]},[],`findAgentsByThread(${e})`)}async close(){}};M();M();Ne();import{query as _k}from"@anthropic-ai/claude-agent-sdk";var Ur=k("meeting-classifier"),vk=`You are a meeting facilitator. Given a message and a list of meeting participants, decide which participants should respond.
352
+ ${JSON.stringify(t.payload)}`,source:{kind:"internal",id:d,label:d},sender:"system",threadId:`event:${l}:${r.agentId}:${o.getTime()}`,timestamp:o,meta:{targetAgentId:r.agentId,eventType:t.type,eventDomain:t.domain,eventId:l}};this.onDispatch?this.onDispatch(f):this.agentManager.sendMessage(r.agentId,f).catch(p=>{pe.error("Event dispatch failed",{agentId:r.agentId,eventType:t.type,eventId:l,error:String(p)})})}}}async fireTeamRequests(){if(!this.db)return;let e=await this.db.collection("team_pending_requests").find({status:"pending"}).toArray();for(let t of e){if(!await this.db.collection("team_pending_requests").findOneAndUpdate({_id:t._id,status:"pending"},{$set:{status:"fired",firedAt:new Date}}))continue;let r={id:`team-${String(t._id)}`,text:t.text,source:{kind:"internal",id:t.channelId,label:`internal:${t.fromAgentId}\u2192${t.targetAgentId}`},sender:t.fromAgentId,senderName:t.fromAgentId,threadId:`internal:${t.channelId}:${t.threadId}`,timestamp:new Date,meta:{targetAgentId:t.targetAgentId,teamRequestId:String(t._id),teamRequestType:t.type}};try{if(t.type==="fire_and_forget")this.onDispatch?this.onDispatch(r):this.agentManager.sendMessage(t.targetAgentId,r).catch(o=>pe.error("Fire-and-forget team message failed",{target:t.targetAgentId,error:String(o)}));else if(t.type==="request_response"){let o=await this.agentManager.sendMessage(t.targetAgentId,r);await this.db.collection("team_messages").insertOne({channelId:t.channelId,threadId:t.threadId,senderId:t.targetAgentId,senderType:"agent",senderName:t.targetAgentId,text:o.text,createdAt:new Date}),await this.db.collection("team_pending_requests").updateOne({_id:t._id},{$set:{status:"completed",response:o.text}})}}catch(o){pe.error("Team request dispatch failed",{requestId:String(t._id),target:t.targetAgentId,error:String(o)}),await this.db.collection("team_pending_requests").updateOne({_id:t._id},{$set:{status:"failed",error:String(o)}})}}}};function $M(n,e){let t=n.split(/\s+/);if(t.length!==5)return!1;let[i,r,o,s,a]=t,l=e.getMinutes(),c=e.getHours(),u=e.getDate(),d=e.getMonth()+1,f=e.getDay();return yo(i,l)&&yo(r,c)&&yo(o,u)&&yo(s,d)&&yo(a,f)}function yo(n,e){if(n==="*")return!0;if(n.includes("-")){let[t,i]=n.split("-").map(Number);return e>=t&&e<=i}if(n.includes(","))return n.split(",").map(Number).includes(e);if(n.startsWith("*/")){let t=Number(n.slice(2));return e%t===0}return Number(n)===e}function xM(n,e){return n.getFullYear()===e.getFullYear()&&n.getMonth()===e.getMonth()&&n.getDate()===e.getDate()&&n.getHours()===e.getHours()&&n.getMinutes()===e.getMinutes()}R();var IM=$("health-reporter"),Wc=class{agentManager;memoryManager;registry;constructor(e,t,i){this.agentManager=e,this.memoryManager=t,this.registry=i}generateReport(){let e={};for(let t of this.agentManager.getAllStates())e[t.id]={status:t.status,lastActivity:t.lastActivity.toISOString(),messagesProcessed:t.messagesProcessed,errorCount:t.errorCount,sessionId:t.currentSessionId,activeThreads:t.activeThreadCount??0};return{lastUpdated:new Date().toISOString(),agents:e}}formatForSlack(){let e=this.generateReport();if(Object.keys(e.agents).length===0)return"No agents are currently registered.";let i=[`*Hive Status* \u2014 ${new Date().toLocaleString()}
353
+ `];for(let[r,o]of Object.entries(e.agents)){let l=this.registry?.get(r)?.disabled?":no_entry_sign:":o.status==="idle"?":white_circle:":o.status==="processing"?":large_blue_circle:":o.status==="error"?":red_circle:":":black_circle:",c=o.activeThreads>0?` (${o.activeThreads} threads)`:"";i.push(`${l} *${r}*${c}`),i.push(` Messages: ${o.messagesProcessed} | Errors: ${o.errorCount}`),i.push(` Last active: ${new Date(o.lastActivity).toLocaleString()}`)}return i.join(`
354
+ `)}async writeToMemory(){let e=this.generateReport();await this.memoryManager.write("status/health.json",JSON.stringify(e,null,2)),await this.memoryManager.commitAndPush("heartbeat: update agent status"),IM.info("Health report written to memory")}};R();import{LinearClient as TM}from"@linear/sdk";var Fe=$("linear-client"),Gc=class{client;defaultTeamId;constructor(e,t){this.client=new TM({apiKey:e}),this.defaultTeamId=t}async listTeams(){try{return(await this.client.teams()).nodes.map(t=>({id:t.id,name:t.name,key:t.key}))}catch(e){return Fe.error("Failed to list teams",{error:String(e)}),[]}}async createIssue(e,t){try{let i=t?.teamId??this.defaultTeamId;if(!i)return Fe.error("Cannot create issue: no teamId provided and no default set"),null;let o=await(await this.client.createIssue({teamId:i,title:e,description:t?.description,priority:t?.priority,stateId:t?.stateId,labelIds:t?.labelIds})).issue;return o?(Fe.info("Issue created",{identifier:o.identifier,title:e}),{identifier:o.identifier,id:o.id,url:o.url}):(Fe.error("Issue creation returned no issue",{title:e}),null)}catch(i){return Fe.error("Failed to create issue",{error:String(i),title:e}),null}}async updateIssue(e,t){try{return await this.client.updateIssue(e,t),Fe.info("Issue updated",{issueId:e,...t}),!0}catch(i){return Fe.error("Failed to update issue",{error:String(i),issueId:e}),!1}}async addComment(e,t){try{let r=await(await this.client.createComment({issueId:e,body:t})).comment;return Fe.info("Comment added",{issueId:e,commentId:r?.id}),r?.id??null}catch(i){return Fe.error("Failed to add comment",{error:String(i),issueId:e}),null}}async listIssues(e){try{let t=e?.teamId??this.defaultTeamId,i={};t&&(i.team={id:{eq:t}}),e?.stateType&&(i.state={type:{eq:e.stateType}}),e?.assigneeEmail&&(i.assignee={email:{eq:e.assigneeEmail}});let r=await this.client.issues({filter:i,first:e?.limit??50,orderBy:"updatedAt"}),o=[];for(let s of r.nodes){let a=await s.state,l=await s.assignee;o.push({identifier:s.identifier,id:s.id,title:s.title,state:a?.name??"Unknown",priority:s.priority,url:s.url,assignee:l?{id:l.id,name:l.name,email:l.email}:void 0})}return o}catch(t){return Fe.error("Failed to list issues",{error:String(t)}),[]}}async searchIssues(e,t,i){try{let r=i??this.defaultTeamId,s=(await this.client.searchIssues(e,{first:t??10})).nodes,a=[];for(let l of s){if(r&&(await l.team)?.id!==r)continue;let c=await l.state,u=await l.assignee;a.push({identifier:l.identifier,id:l.id,title:l.title,state:c?.name??"Unknown",priority:l.priority,url:l.url,assignee:u?{id:u.id,name:u.name,email:u.email}:void 0})}return a}catch(r){return Fe.error("Failed to search issues",{error:String(r),term:e}),[]}}async getWorkflowStates(e){try{let t=e??this.defaultTeamId,i={};return t&&(i.team={id:{eq:t}}),(await this.client.workflowStates({filter:i})).nodes.map(o=>({id:o.id,name:o.name,type:o.type}))}catch(t){return Fe.error("Failed to get workflow states",{error:String(t)}),[]}}async searchUsers(e,t){try{return(await this.client.users({filter:{or:[{name:{containsIgnoreCase:e}},{displayName:{containsIgnoreCase:e}},{email:{containsIgnoreCase:e}}]},first:t??10})).nodes.map(r=>({id:r.id,name:r.name,displayName:r.displayName,email:r.email,active:r.active}))}catch(i){return Fe.error("Failed to search users",{error:String(i),query:e}),[]}}async findIssueByIdentifier(e){try{let t=await this.client.issue(e),i=await t.state,r=await t.assignee;return{identifier:t.identifier,id:t.id,title:t.title,state:i?.name??"Unknown",priority:t.priority,url:t.url,description:t.description??void 0,assignee:r?{id:r.id,name:r.name,email:r.email}:void 0}}catch(t){return Fe.error("Failed to find issue",{error:String(t),identifier:e}),null}}};R();var sy=$("session-store"),Jc=class{db;collection;constructor(e){this.db=e}async init(){this.collection=this.db.collection("sessions"),await this.collection.createIndex({updatedAt:1},{expireAfterSeconds:10080*60}),await this.collection.createIndex({agentId:1}),await this.collection.createIndex({threadId:1});let e=await this.collection.countDocuments();sy.info("Session store connected",{count:e})}async withRetry(e,t,i){try{return await e()}catch(r){return sy.error("MongoDB operation failed, using fallback",{label:i,error:String(r?.message??r)}),t}}async get(e,t){return this.withRetry(async()=>{let i=await this.collection.findOne({_id:`${e}:${t}`});if(i)return i.sessionId;if(t.startsWith("slack:")){let r=t.split(":").pop();return(await this.collection.findOne({_id:`${e}:${r}`}))?.sessionId}},void 0,`get(${e}:${t})`)}async set(e,t,i,r){await this.withRetry(async()=>{let o=new Date,s={$set:{agentId:e,threadId:t,sessionId:i,updatedAt:o},$setOnInsert:{createdAt:o,compactions:0}};r?(s.$set.inputTokens=r.inputTokens,s.$set.outputTokens=r.outputTokens,s.$set.cacheReadTokens=r.cacheReadTokens,s.$set.cacheCreationTokens=r.cacheCreationTokens,s.$set.contextWindow=r.contextWindow,r.compactions>0&&(s.$inc={compactions:r.compactions},s.$set.lastCompactedAt=o,r.preCompactTokens!==void 0&&(s.$set.preCompactTokens=r.preCompactTokens),delete s.$setOnInsert.compactions)):Object.assign(s.$setOnInsert,{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,contextWindow:0}),await this.collection.updateOne({_id:`${e}:${t}`},s,{upsert:!0})},void 0,`set(${e}:${t})`)}async delete(e,t){await this.withRetry(async()=>{await this.collection.deleteOne({_id:`${e}:${t}`})},void 0,`delete(${e}:${t})`)}async clearAgent(e){await this.withRetry(async()=>{let t=await this.collection.deleteMany({agentId:e});t.deletedCount>0&&sy.info("Cleared agent sessions",{agentId:e,deleted:t.deletedCount})},void 0,`clearAgent(${e})`)}async findAgentByThread(e){return this.withRetry(async()=>(await this.collection.findOne({threadId:e},{sort:{updatedAt:-1},projection:{agentId:1}}))?.agentId,void 0,`findAgentByThread(${e})`)}async findAgentsByThread(e){return this.withRetry(async()=>{let t=await this.collection.find({threadId:e},{projection:{agentId:1},sort:{updatedAt:-1}}).toArray();return[...new Set(t.map(i=>i.agentId))]},[],`findAgentsByThread(${e})`)}async close(){}};R();R();ot();import{query as EM}from"@anthropic-ai/claude-agent-sdk";var Hc=$("meeting-classifier"),AM=`You are a meeting facilitator. Given a message and a list of meeting participants, decide which participants should respond.
315
355
 
316
356
  Rules:
317
357
  - If someone is addressed by name, they MUST be in the respond list.
@@ -321,34 +361,34 @@ Rules:
321
361
  - If the message is a general question to the room, pick 2-3 most relevant.
322
362
  - For "what does everyone think?" style questions, include all participants.
323
363
 
324
- Respond with ONLY a JSON object: { "respond": ["agent-id-1", "agent-id-2"] }`;function Tk(n,e){let t=o=>{try{let a=JSON.parse(o);if(Array.isArray(a.respond))return a.respond.filter(l=>e.has(l))}catch{}return null},s=t(n);if(s)return s;let r=n.indexOf("{"),i=n.lastIndexOf("}");if(r!==-1&&i>r){let o=t(n.slice(r,i+1));if(o)return o}return null}function Ik(n,e){let s=`Participants:
364
+ Respond with ONLY a JSON object: { "respond": ["agent-id-1", "agent-id-2"] }`;function OM(n,e){let t=s=>{try{let a=JSON.parse(s);if(Array.isArray(a.respond))return a.respond.filter(l=>e.has(l))}catch{}return null},i=t(n);if(i)return i;let r=n.indexOf("{"),o=n.lastIndexOf("}");if(r!==-1&&o>r){let s=t(n.slice(r,o+1));if(s)return s}return null}function CM(n,e){let i=`Participants:
325
365
  ${n.map(r=>`- ${r.agentId} (${r.name}${r.title?`, ${r.title}`:""}): ${r.role}`).join(`
326
- `)}`;return e&&(s+=`
366
+ `)}`;return e&&(i+=`
327
367
 
328
368
  Recent thread context:
329
- ${e}`),s}async function Ua(n,e,t){let s=new Set(e.map(u=>u.agentId));if(e.length===0)return{respondAgentIds:[],costUsd:0,durationMs:0};if(e.length===1)return{respondAgentIds:[e[0].agentId],costUsd:0,durationMs:0};let r=g.modelRouter.model,i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Ur.warn("Meeting classifier timed out",{timeoutMs:g.modelRouter.timeoutMs}),i.close())},g.modelRouter.timeoutMs);try{let u=`${Ik(e,t)}
369
+ ${e}`),i}async function ay(n,e,t){let i=new Set(e.map(d=>d.agentId));if(e.length===0)return{respondAgentIds:[],costUsd:0,durationMs:0};if(e.length===1)return{respondAgentIds:[e[0].agentId],costUsd:0,durationMs:0};let r=g.modelRouter.model,o=null,s="",a=0,l=0,c=setTimeout(()=>{o&&(Hc.warn("Meeting classifier timed out",{timeoutMs:g.modelRouter.timeoutMs}),o.close())},g.modelRouter.timeoutMs);try{let d=`${CM(e,t)}
330
370
 
331
371
  Message:
332
- ${n}`;i=_k({prompt:u,options:{model:r,systemPrompt:vk,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let p=h;if(p.type==="assistant"){let m=p.message?.content;if(Array.isArray(m))for(let f of m)f.type==="text"&&(o=f.text)}if(p.type==="result"){let m=p;a=m.total_cost_usd,l=m.duration_ms,m.subtype==="success"&&m.result&&(o=m.result)}}}catch(u){return Ur.warn("Meeting classifier query failed, selecting all roster members",{error:String(u)}),{respondAgentIds:[...s],costUsd:0,durationMs:0}}finally{clearTimeout(c),i=null}let d=Tk(o,s);return d?(Ur.info("Meeting classifier decision",{respond:d,rosterSize:e.length,costUsd:a,durationMs:l}),{respondAgentIds:d,costUsd:a,durationMs:l}):(Ur.warn("Meeting classifier parse failed, selecting all roster members",{rawText:o.slice(0,200)}),{respondAgentIds:[...s],costUsd:a,durationMs:l})}var q=k("dispatcher"),Ak=80,Ck=[/^status\??$/i,/^how.{0,20}(everyone|agents?|doing|running)/i,/^health\??$/i,/^system status/i],Vh=[/^no response (requested|needed|required|necessary)\.?$/i,/^\(no response\)$/i,/^n\/a\.?$/i],jr=class n{adapters=new Map;registry;agentManager;healthReporter;defaultAgentId;threadAgentMap=new Map;threadParticipants=new Map;threadAgentLastSeen=new Map;recentMessageIds=new Map;auditAdapter;auditChannelIds;fallbackAuditChannelId;taskLedger;retryQueue;teamStore;slackAdapter;meetingRosters=new Map;meetingReactionTracker=new Map;static DEDUP_TTL_MS=6e4;constructor(e,t,s,r,i){this.registry=e,this.agentManager=t,this.healthReporter=s,this.defaultAgentId=r,this.taskLedger=i}registerAdapter(e){this.adapters.set(e.id,e)}setRetryQueue(e){this.retryQueue=e}setTeamStore(e){this.teamStore=e}setAuditChannel(e,t,s){this.auditAdapter=e,this.auditChannelIds=t,this.fallbackAuditChannelId=s}setSlackAdapter(e){this.slackAdapter=e}async dispatch(e){if(this.recentMessageIds.has(e.id)){q.debug("Duplicate message skipped",{id:e.id,source:e.source.adapterId});return}this.recentMessageIds.set(e.id,Date.now()),this.pruneDedup();let t=e.text.trim();if(t.length<=Ak&&Ck.some(d=>d.test(t))){q.info("Status query intercepted",{source:e.source.kind,text:t});let d=this.healthReporter.formatForSlack(),u=this.adapters.get(e.source.adapterId??e.source.kind);if(u)try{await u.deliver({text:d,agentId:"system",workItem:e,costUsd:0,durationMs:0})}catch(h){q.warn("Status delivery failed, queuing for retry",{error:String(h)}),this.retryQueue?.enqueue({text:d,agentId:"system",workItem:e,costUsd:0,durationMs:0},u)}return}let s=await this.resolveAgents(e);if(s.length===0){q.warn("No agent found for work item",{source:e.source.kind,label:e.source.label,text:e.text.slice(0,50)});return}let r=s.filter(({agentId:d})=>this.registry.get(d)?.disabled?(q.info("Message dropped \u2014 agent is disabled",{agentId:d,source:e.source.kind}),!1):!0);if(r.length===0)return;if(r.some(d=>d.conferenceMode)){let d=e.threadId??e.id;this.threadAgentLastSeen.set(d,Date.now()),q.info("Conference fan-out",{agents:r.map(u=>u.agentId)}),await Promise.all(r.map(u=>this.dispatchToAgent(e,u)));return}if(r.length>1){let d=e.threadId??e.id;this.threadParticipants.has(d)||this.threadParticipants.set(d,new Set(r.map(u=>u.agentId))),this.threadAgentLastSeen.set(d,Date.now()),q.info("Multi-agent fan-out",{agents:r.map(u=>u.agentId)}),await Promise.all(r.map(u=>this.dispatchToAgent(e,u)));return}let{agentId:o}=r[0],a=e.threadId??e.id;this.threadAgentMap.set(a,o),this.threadAgentLastSeen.set(a,Date.now());let l=this.taskLedger?.shouldTrack(e)??!1;l&&this.taskLedger.onDispatch(e,o).catch(d=>q.warn("Task ledger dispatch failed",{error:String(d)}));let c=this.adapters.get(e.source.adapterId??e.source.kind);await c?.onProcessingStart?.(e,o);try{let d=await this.agentManager.sendMessage(o,e),u=d.text.trim();if(Vh.some(p=>p.test(u)))q.info("Non-response suppressed",{agentId:o,source:e.source.kind,text:u,costUsd:d.costUsd,durationMs:d.durationMs});else{let p={text:d.text||"_No response._",agentId:o,workItem:e,costUsd:d.costUsd,durationMs:d.durationMs,error:d.error};if(c)try{await c.deliver(p)}catch(m){q.warn("Agent response delivery failed, queuing for retry",{error:String(m)}),this.retryQueue?.enqueue(p,c)}l&&this.taskLedger.onComplete(p).catch(m=>q.warn("Task ledger complete failed",{error:String(m)})),this.auditAdapter&&e.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(p),q.info("Work item dispatched",{agentId:o,source:e.source.kind,costUsd:d.costUsd,durationMs:d.durationMs,llmMs:d.llmMs,toolMs:d.toolMs,toolCalls:d.toolCalls,toolSummary:d.toolSummary})}}catch(d){let u={text:`Something went wrong: ${String(d)}`,agentId:o,workItem:e,costUsd:0,durationMs:0,error:String(d)};if(c)try{await c.deliver(u)}catch(h){q.warn("Error delivery failed, queuing for retry",{error:String(h)}),this.retryQueue?.enqueue(u,c)}q.error("Dispatch failed",{agentId:o,error:String(d)})}finally{await c?.onProcessingEnd?.(e,o)}}pruneDedup(){let e=Date.now()-n.DEDUP_TTL_MS;for(let[t,s]of this.recentMessageIds)s<e&&this.recentMessageIds.delete(t)}async resolveAgents(e){let t=e.meta?.targetAgentId;if(t&&this.registry.get(t))return[{agentId:t}];if(e.source.kind==="team")return this.resolveFromTeam(e);let s=e.meta?.origin;if(s){let a=this.registry.findByOrigin(s);return a?[{agentId:a.id}]:(q.warn("Origin not routed",{origin:s,deviceId:e.meta?.deviceId,text:e.text.slice(0,50)}),[])}if(e.source.kind==="slack"&&e.source.label.startsWith("conf-"))return this.resolveConferenceAgents(e);let r=this.registry.findByChannel(e.source.label);if(r)return[{agentId:r.id}];if(e.threadId){let a=this.registry.findAllByName(e.text),l=new Set(a.map(h=>h.id)),c=this.threadParticipants.get(e.threadId);if(c){for(let h of l)c.add(h);return this.threadAgentLastSeen.set(e.threadId,Date.now()),[...c].map(h=>({agentId:h}))}let d=this.threadAgentMap.get(e.threadId);if(d){let h=a.some(p=>p.id!==d);if(l.size>0&&h){let p=new Set([d,...l]);return this.threadParticipants.set(e.threadId,p),this.threadAgentMap.delete(e.threadId),this.threadAgentLastSeen.set(e.threadId,Date.now()),q.info("Thread transitioned to multi-agent",{threadId:e.threadId,participants:[...p]}),[...p].map(m=>({agentId:m}))}return this.threadAgentLastSeen.set(e.threadId,Date.now()),[{agentId:d}]}let u=await this.agentManager.findAgentsForThread(e.threadId);if(u.length>0){let h=u.filter(p=>this.registry.get(p));if(h.length>1){let p=new Set(h);return this.threadParticipants.set(e.threadId,p),this.threadAgentLastSeen.set(e.threadId,Date.now()),[...p].map(m=>({agentId:m}))}if(h.length===1)return this.threadAgentMap.set(e.threadId,h[0]),this.threadAgentLastSeen.set(e.threadId,Date.now()),[{agentId:h[0]}]}}let i=this.registry.findAllByName(e.text);if(i.length>0)return i.map(a=>({agentId:a.id}));let o=e.meta?.defaultAgentId;return o&&this.registry.get(o)?[{agentId:o}]:this.isDirectMessage(e)&&this.registry.get(this.defaultAgentId)?(q.info("DM routed to default agent",{agentId:this.defaultAgentId,channel:e.source.id}),[{agentId:this.defaultAgentId}]):(q.debug("No agent matched \u2014 dropping",{channel:e.source.label}),[])}isDirectMessage(e){return!!(e.source.kind==="slack"&&e.source.id.startsWith("D")||e.meta?.channelType==="im"||e.source.kind==="team"&&typeof e.source.id=="string"&&e.source.id.startsWith("dm:"))}async resolveFromTeam(e){let t=e.meta?.channelId;if(!t||!this.teamStore){let o=e.meta?.defaultAgentId;return o&&this.registry.get(o)?[{agentId:o}]:[]}let s=await this.teamStore.getChannel(t);if(!s)return q.warn("Team channel not found",{channelId:t}),[];if(s.type==="dm"){let o=s.members.find(a=>a!==e.sender);return o&&this.registry.get(o)?[{agentId:o}]:(q.warn("DM agent not found in registry",{channelId:t,members:s.members}),[])}let r=this.registry.findAllByName(e.text);if(r.length>0){let o=new Set(s.members),a=r.filter(l=>o.has(l.id));if(a.length>0)return a.map(l=>({agentId:l.id}))}let i=s.members.filter(o=>this.registry.get(o));return i.length>0?[{agentId:i[0]}]:(q.warn("No agent members in Team channel",{channelId:t}),[])}async dispatchToAgent(e,t){let{agentId:s}=t,r=e;if(t.conferenceMode){let l=[t.meetingPreamble,"",t.threadContext,"","---","[New message]:"].filter(Boolean).join(`
372
+ ${n}`;o=EM({prompt:d,options:{model:r,systemPrompt:AM,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let f of o){let p=f;if(p.type==="assistant"){let h=p.message?.content;if(Array.isArray(h))for(let m of h)m.type==="text"&&(s=m.text)}if(p.type==="result"){let h=p;a=h.total_cost_usd,l=h.duration_ms,h.subtype==="success"&&h.result&&(s=h.result)}}}catch(d){return Hc.warn("Meeting classifier query failed, selecting all roster members",{error:String(d)}),{respondAgentIds:[...i],costUsd:0,durationMs:0}}finally{clearTimeout(c),o=null}let u=OM(s,i);return u?(Hc.info("Meeting classifier decision",{respond:u,rosterSize:e.length,costUsd:a,durationMs:l}),{respondAgentIds:u,costUsd:a,durationMs:l}):(Hc.warn("Meeting classifier parse failed, selecting all roster members",{rawText:s.slice(0,200)}),{respondAgentIds:[...i],costUsd:a,durationMs:l})}var X=$("dispatcher"),NM=80,DM=[/^status\??$/i,/^how.{0,20}(everyone|agents?|doing|running)/i,/^health\??$/i,/^system status/i],uI=[/^no response (requested|needed|required|necessary)\.?$/i,/^\(no response\)$/i,/^n\/a\.?$/i],Yc=class n{adapters=new Map;registry;agentManager;healthReporter;defaultAgentId;threadAgentMap=new Map;threadParticipants=new Map;threadAgentLastSeen=new Map;recentMessageIds=new Map;auditAdapter;auditChannelIds;fallbackAuditChannelId;taskLedger;retryQueue;teamStore;slackAdapter;meetingRosters=new Map;meetingReactionTracker=new Map;static DEDUP_TTL_MS=6e4;constructor(e,t,i,r,o){this.registry=e,this.agentManager=t,this.healthReporter=i,this.defaultAgentId=r,this.taskLedger=o}registerAdapter(e){this.adapters.set(e.id,e)}setRetryQueue(e){this.retryQueue=e}setTeamStore(e){this.teamStore=e}setAuditChannel(e,t,i){this.auditAdapter=e,this.auditChannelIds=t,this.fallbackAuditChannelId=i}setSlackAdapter(e){this.slackAdapter=e}async dispatch(e){if(this.recentMessageIds.has(e.id)){X.debug("Duplicate message skipped",{id:e.id,source:e.source.adapterId});return}this.recentMessageIds.set(e.id,Date.now()),this.pruneDedup();let t=e.text.trim();if(t.length<=NM&&DM.some(u=>u.test(t))){X.info("Status query intercepted",{source:e.source.kind,text:t});let u=this.healthReporter.formatForSlack(),d=this.adapters.get(e.source.adapterId??e.source.kind);if(d)try{await d.deliver({text:u,agentId:"system",workItem:e,costUsd:0,durationMs:0})}catch(f){X.warn("Status delivery failed, queuing for retry",{error:String(f)}),this.retryQueue?.enqueue({text:u,agentId:"system",workItem:e,costUsd:0,durationMs:0},d)}return}let i=await this.resolveAgents(e);if(i.length===0){X.warn("No agent found for work item",{source:e.source.kind,label:e.source.label,text:e.text.slice(0,50)});return}let r=i.filter(({agentId:u})=>this.registry.get(u)?.disabled?(X.info("Message dropped \u2014 agent is disabled",{agentId:u,source:e.source.kind}),!1):!0);if(r.length===0)return;if(r.some(u=>u.conferenceMode)){let u=e.threadId??e.id;this.threadAgentLastSeen.set(u,Date.now()),X.info("Conference fan-out",{agents:r.map(d=>d.agentId)}),await Promise.all(r.map(d=>this.dispatchToAgent(e,d)));return}if(r.length>1){let u=e.threadId??e.id;this.threadParticipants.has(u)||this.threadParticipants.set(u,new Set(r.map(d=>d.agentId))),this.threadAgentLastSeen.set(u,Date.now()),X.info("Multi-agent fan-out",{agents:r.map(d=>d.agentId)}),await Promise.all(r.map(d=>this.dispatchToAgent(e,d)));return}let{agentId:s}=r[0],a=e.threadId??e.id;this.threadAgentMap.set(a,s),this.threadAgentLastSeen.set(a,Date.now());let l=this.taskLedger?.shouldTrack(e)??!1;l&&this.taskLedger.onDispatch(e,s).catch(u=>X.warn("Task ledger dispatch failed",{error:String(u)}));let c=this.adapters.get(e.source.adapterId??e.source.kind);await c?.onProcessingStart?.(e,s);try{let u=await this.agentManager.sendMessage(s,e),d=u.text.trim();if(uI.some(p=>p.test(d)))X.info("Non-response suppressed",{agentId:s,source:e.source.kind,text:d,costUsd:u.costUsd,durationMs:u.durationMs});else{let p={text:u.text||"_No response._",agentId:s,workItem:e,costUsd:u.costUsd,durationMs:u.durationMs,error:u.error};if(c)try{await c.deliver(p)}catch(h){X.warn("Agent response delivery failed, queuing for retry",{error:String(h)}),this.retryQueue?.enqueue(p,c)}l&&this.taskLedger.onComplete(p).catch(h=>X.warn("Task ledger complete failed",{error:String(h)})),this.auditAdapter&&e.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(p),X.info("Work item dispatched",{agentId:s,source:e.source.kind,costUsd:u.costUsd,durationMs:u.durationMs,llmMs:u.llmMs,toolMs:u.toolMs,toolCalls:u.toolCalls,toolSummary:u.toolSummary})}}catch(u){let d={text:`Something went wrong: ${String(u)}`,agentId:s,workItem:e,costUsd:0,durationMs:0,error:String(u)};if(c)try{await c.deliver(d)}catch(f){X.warn("Error delivery failed, queuing for retry",{error:String(f)}),this.retryQueue?.enqueue(d,c)}X.error("Dispatch failed",{agentId:s,error:String(u)})}finally{await c?.onProcessingEnd?.(e,s)}}pruneDedup(){let e=Date.now()-n.DEDUP_TTL_MS;for(let[t,i]of this.recentMessageIds)i<e&&this.recentMessageIds.delete(t)}async resolveAgents(e){let t=e.meta?.targetAgentId;if(t&&this.registry.get(t))return[{agentId:t}];if(e.source.kind==="team")return this.resolveFromTeam(e);let i=e.meta?.origin;if(i){let a=this.registry.findByOrigin(i);return a?[{agentId:a.id}]:(X.warn("Origin not routed",{origin:i,deviceId:e.meta?.deviceId,text:e.text.slice(0,50)}),[])}if(e.source.kind==="slack"&&e.source.label.startsWith("conf-"))return this.resolveConferenceAgents(e);let r=this.registry.findByChannel(e.source.label);if(r)return[{agentId:r.id}];if(e.threadId){let a=this.registry.findAllByName(e.text),l=new Set(a.map(f=>f.id)),c=this.threadParticipants.get(e.threadId);if(c){for(let f of l)c.add(f);return this.threadAgentLastSeen.set(e.threadId,Date.now()),[...c].map(f=>({agentId:f}))}let u=this.threadAgentMap.get(e.threadId);if(u){let f=a.some(p=>p.id!==u);if(l.size>0&&f){let p=new Set([u,...l]);return this.threadParticipants.set(e.threadId,p),this.threadAgentMap.delete(e.threadId),this.threadAgentLastSeen.set(e.threadId,Date.now()),X.info("Thread transitioned to multi-agent",{threadId:e.threadId,participants:[...p]}),[...p].map(h=>({agentId:h}))}return this.threadAgentLastSeen.set(e.threadId,Date.now()),[{agentId:u}]}let d=await this.agentManager.findAgentsForThread(e.threadId);if(d.length>0){let f=d.filter(p=>this.registry.get(p));if(f.length>1){let p=new Set(f);return this.threadParticipants.set(e.threadId,p),this.threadAgentLastSeen.set(e.threadId,Date.now()),[...p].map(h=>({agentId:h}))}if(f.length===1)return this.threadAgentMap.set(e.threadId,f[0]),this.threadAgentLastSeen.set(e.threadId,Date.now()),[{agentId:f[0]}]}}let o=this.registry.findAllByName(e.text);if(o.length>0)return o.map(a=>({agentId:a.id}));let s=e.meta?.defaultAgentId;return s&&this.registry.get(s)?[{agentId:s}]:this.isDirectMessage(e)&&this.registry.get(this.defaultAgentId)?(X.info("DM routed to default agent",{agentId:this.defaultAgentId,channel:e.source.id}),[{agentId:this.defaultAgentId}]):(X.debug("No agent matched \u2014 dropping",{channel:e.source.label}),[])}isDirectMessage(e){return!!(e.source.kind==="slack"&&e.source.id.startsWith("D")||e.meta?.channelType==="im"||e.source.kind==="team"&&typeof e.source.id=="string"&&e.source.id.startsWith("dm:"))}async resolveFromTeam(e){let t=e.meta?.channelId;if(!t||!this.teamStore){let s=e.meta?.defaultAgentId;return s&&this.registry.get(s)?[{agentId:s}]:[]}let i=await this.teamStore.getChannel(t);if(!i)return X.warn("Team channel not found",{channelId:t}),[];if(i.type==="dm"){let s=i.members.find(a=>a!==e.sender);return s&&this.registry.get(s)?[{agentId:s}]:(X.warn("DM agent not found in registry",{channelId:t,members:i.members}),[])}let r=this.registry.findAllByName(e.text);if(r.length>0){let s=new Set(i.members),a=r.filter(l=>s.has(l.id));if(a.length>0)return a.map(l=>({agentId:l.id}))}let o=i.members.filter(s=>this.registry.get(s));return o.length>0?[{agentId:o[0]}]:(X.warn("No agent members in Team channel",{channelId:t}),[])}async dispatchToAgent(e,t){let{agentId:i}=t,r=e;if(t.conferenceMode){let l=[t.meetingPreamble,"",t.threadContext,"","---","[New message]:"].filter(Boolean).join(`
333
373
  `);r={...e,text:`${l}
334
- ${e.text}`,meta:{...e.meta,conferenceMode:!0,conferenceHumanTs:t.conferenceHumanTs,conferenceRound:t.conferenceRound}}}let i=r.threadId??r.id;this.threadAgentLastSeen.set(i,Date.now());let o=this.taskLedger?.shouldTrack(r)??!1;o&&this.taskLedger.onDispatch(r,s).catch(l=>q.warn("Task ledger dispatch failed",{error:String(l)}));let a=this.adapters.get(r.source.adapterId??r.source.kind);try{let l=await this.agentManager.sendMessage(s,r),c=l.text.trim(),d=Vh.some(u=>u.test(c));if(d)q.info("Non-response suppressed (fan-out)",{agentId:s});else{let u={text:l.text||"_No response._",agentId:s,workItem:r,costUsd:l.costUsd,durationMs:l.durationMs,error:l.error};if(a)try{await a.deliver(u)}catch{this.retryQueue?.enqueue(u,a)}t.conferenceMode&&t.conferenceRound===0&&!d&&this.triggerConferenceReactions(l.text,e,s,t.conferenceHumanTs).catch(h=>q.warn("Conference reaction trigger failed",{error:String(h)})),o&&this.taskLedger.onComplete(u).catch(h=>q.warn("Task ledger complete failed",{error:String(h)})),this.auditAdapter&&r.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(u),q.info("Fan-out dispatch complete",{agentId:s,costUsd:l.costUsd,durationMs:l.durationMs})}}catch(l){let c={text:`Something went wrong: ${String(l)}`,agentId:s,workItem:r,costUsd:0,durationMs:0,error:String(l)};if(a)try{await a.deliver(c)}catch{this.retryQueue?.enqueue(c,a)}q.error("Fan-out dispatch failed",{agentId:s,error:String(l)})}}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.threadAgentLastSeen)i<t&&(this.threadAgentMap.delete(r),this.threadParticipants.delete(r),this.meetingRosters.delete(r),this.meetingReactionTracker.delete(r),this.threadAgentLastSeen.delete(r),s++);return{component:"dispatcher",pruned:s,retried:0,bytesFreed:0,errors:[]}}async resolveConferenceAgents(e){let t=e.threadId??e.id,s=this.meetingRosters.get(t)??new Set,r=this.registry.findAllByName(e.text);for(let d of r)s.add(d.id);if(this.meetingRosters.set(t,s),this.threadAgentLastSeen.set(t,Date.now()),s.size===0)return q.debug("Conference channel \u2014 no roster yet",{channel:e.source.label,threadId:t}),[];let i=[];for(let d of s){let u=this.registry.get(d);!u||u.disabled||i.push({agentId:u.id,name:u.name,title:u.title,role:u.soul.split(`
335
- `)[0]})}if(i.length===0)return[];let o="",a="";if(this.slackAdapter){let d=e.source.id,u=e.meta?.slackThreadTs??e.meta?.slackTs??t,h=await this.slackAdapter.fetchThreadHistory(d,u);o=this.formatThreadContext(h,e.source.label,i),a=h.slice(-5).map(p=>`${p.author}: ${p.text.slice(0,200)}`).join(`
336
- `)}let l=await Ua(e.text,i,a);q.info("Conference classifier result",{channel:e.source.label,threadId:t,roster:[...s],selected:l.respondAgentIds,costUsd:l.costUsd});let c=this.buildMeetingPreamble(e.source.label,i);return l.respondAgentIds.map(d=>({agentId:d,conferenceMode:!0,conferenceHumanTs:e.meta?.slackTs,conferenceRound:0,threadContext:o,meetingPreamble:c}))}formatThreadContext(e,t,s){if(e.length===0)return"";let r=s.map(l=>l.name).join(", "),i=`[Meeting thread in #${t} \u2014 participants: ${r}]`,o=e;if(e.length>105){let l=e.slice(0,5),c=e.slice(-100);o=[...l,...c]}let a=o.map(l=>{let c=this.formatTimeAgo(l.timestamp);return`${l.author} (${c}): ${l.text}`}).join(`
337
- `);return`${i}
374
+ ${e.text}`,meta:{...e.meta,conferenceMode:!0,conferenceHumanTs:t.conferenceHumanTs,conferenceRound:t.conferenceRound}}}let o=r.threadId??r.id;this.threadAgentLastSeen.set(o,Date.now());let s=this.taskLedger?.shouldTrack(r)??!1;s&&this.taskLedger.onDispatch(r,i).catch(l=>X.warn("Task ledger dispatch failed",{error:String(l)}));let a=this.adapters.get(r.source.adapterId??r.source.kind);try{let l=await this.agentManager.sendMessage(i,r),c=l.text.trim(),u=uI.some(d=>d.test(c));if(u)X.info("Non-response suppressed (fan-out)",{agentId:i});else{let d={text:l.text||"_No response._",agentId:i,workItem:r,costUsd:l.costUsd,durationMs:l.durationMs,error:l.error};if(a)try{await a.deliver(d)}catch{this.retryQueue?.enqueue(d,a)}t.conferenceMode&&t.conferenceRound===0&&!u&&this.triggerConferenceReactions(l.text,e,i,t.conferenceHumanTs).catch(f=>X.warn("Conference reaction trigger failed",{error:String(f)})),s&&this.taskLedger.onComplete(d).catch(f=>X.warn("Task ledger complete failed",{error:String(f)})),this.auditAdapter&&r.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(d),X.info("Fan-out dispatch complete",{agentId:i,costUsd:l.costUsd,durationMs:l.durationMs})}}catch(l){let c={text:`Something went wrong: ${String(l)}`,agentId:i,workItem:r,costUsd:0,durationMs:0,error:String(l)};if(a)try{await a.deliver(c)}catch{this.retryQueue?.enqueue(c,a)}X.error("Fan-out dispatch failed",{agentId:i,error:String(l)})}}sweep(e){let t=Date.now()-e,i=0;for(let[r,o]of this.threadAgentLastSeen)o<t&&(this.threadAgentMap.delete(r),this.threadParticipants.delete(r),this.meetingRosters.delete(r),this.meetingReactionTracker.delete(r),this.threadAgentLastSeen.delete(r),i++);return{component:"dispatcher",pruned:i,retried:0,bytesFreed:0,errors:[]}}async resolveConferenceAgents(e){let t=e.threadId??e.id,i=this.meetingRosters.get(t)??new Set,r=this.registry.findAllByName(e.text);for(let u of r)i.add(u.id);if(this.meetingRosters.set(t,i),this.threadAgentLastSeen.set(t,Date.now()),i.size===0)return X.debug("Conference channel \u2014 no roster yet",{channel:e.source.label,threadId:t}),[];let o=[];for(let u of i){let d=this.registry.get(u);!d||d.disabled||o.push({agentId:d.id,name:d.name,title:d.title,role:d.soul.split(`
375
+ `)[0]})}if(o.length===0)return[];let s="",a="";if(this.slackAdapter){let u=e.source.id,d=e.meta?.slackThreadTs??e.meta?.slackTs??t,f=await this.slackAdapter.fetchThreadHistory(u,d);s=this.formatThreadContext(f,e.source.label,o),a=f.slice(-5).map(p=>`${p.author}: ${p.text.slice(0,200)}`).join(`
376
+ `)}let l=await ay(e.text,o,a);X.info("Conference classifier result",{channel:e.source.label,threadId:t,roster:[...i],selected:l.respondAgentIds,costUsd:l.costUsd});let c=this.buildMeetingPreamble(e.source.label,o);return l.respondAgentIds.map(u=>({agentId:u,conferenceMode:!0,conferenceHumanTs:e.meta?.slackTs,conferenceRound:0,threadContext:s,meetingPreamble:c}))}formatThreadContext(e,t,i){if(e.length===0)return"";let r=i.map(l=>l.name).join(", "),o=`[Meeting thread in #${t} \u2014 participants: ${r}]`,s=e;if(e.length>105){let l=e.slice(0,5),c=e.slice(-100);s=[...l,...c]}let a=s.map(l=>{let c=this.formatTimeAgo(l.timestamp);return`${l.author} (${c}): ${l.text}`}).join(`
377
+ `);return`${o}
338
378
 
339
- ${a}`}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);if(t<60)return`${t}s ago`;let s=Math.floor(t/60);return s<60?`${s} min ago`:`${Math.floor(s/60)}h ago`}buildMeetingPreamble(e,t){let s=t.map(r=>r.name).join(", ");return`You are in a meeting in #${e} with ${s}.
379
+ ${a}`}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);if(t<60)return`${t}s ago`;let i=Math.floor(t/60);return i<60?`${i} min ago`:`${Math.floor(i/60)}h ago`}buildMeetingPreamble(e,t){let i=t.map(r=>r.name).join(", ");return`You are in a meeting in #${e} with ${i}.
340
380
 
341
381
  Meeting rules:
342
382
  - Be concise \u2014 others are also responding.
343
383
  - Build on what's been said. Don't repeat points already made.
344
384
  - If you have nothing meaningful to add, respond with "No response needed."
345
385
  - Stay in your lane \u2014 don't cover someone else's domain unless asked.
346
- - Address others by name when responding to their points.`}async triggerConferenceReactions(e,t,s,r){let i=t.threadId??t.id,o=this.meetingRosters.get(i);if(!o)return;this.meetingReactionTracker.has(i)||this.meetingReactionTracker.set(i,new Map);let a=this.meetingReactionTracker.get(i),l=a.get(r)??new Set;a.set(r,l);let c=[];for(let f of o){if(f===s||l.has(f))continue;let y=this.registry.get(f);!y||y.disabled||(l.add(f),c.push({agentId:y.id,name:y.name,title:y.title,role:y.soul.split(`
347
- `)[0]}))}if(c.length===0)return;let d=await Ua(e,c),u=new Set(d.respondAgentIds);for(let f of c)u.has(f.agentId)||l.delete(f.agentId);if(d.respondAgentIds.length===0)return;q.info("Conference depth-1 reactions",{threadId:i,respondingAgent:s,peers:d.respondAgentIds});let h="",p="";if(this.slackAdapter){let f=t.source.id,y=t.meta?.slackThreadTs??t.meta?.slackTs??i,w=await this.slackAdapter.fetchThreadHistory(f,y),S=[];for(let _ of o){let v=this.registry.get(_);!v||v.disabled||S.push({agentId:v.id,name:v.name,title:v.title,role:v.soul.split(`
348
- `)[0]})}h=this.formatThreadContext(w,t.source.label,S),p=this.buildMeetingPreamble(t.source.label,S)}let m=d.respondAgentIds.map(f=>{let y={agentId:f,conferenceMode:!0,conferenceHumanTs:r,conferenceRound:1,threadContext:h,meetingPreamble:p};return this.dispatchToAgent(t,y)});await Promise.all(m)}async postAuditLog(e){if(!this.auditAdapter||!this.auditChannelIds)return;let t=this.registry.get(e.agentId),s=t?.name??e.agentId,r=t?.homeBase,i=(r?this.auditChannelIds.get(r):void 0)??this.fallbackAuditChannelId;if(!i){q.warn("No audit channel resolved for agent",{agentId:e.agentId,homeBase:r});return}if(e.workItem.source.kind==="slack"&&e.workItem.source.id===i)return;let o=e.workItem.source.kind==="sms"?":phone:":e.workItem.source.kind==="imessage"?":speech_balloon:":e.workItem.source.kind==="app"?":iphone:":":incoming_envelope:",a=e.workItem.senderName??e.workItem.sender,l=e.text.length>300?e.text.slice(0,300)+"...":e.text,c={id:`audit:${e.workItem.id}`,text:`${o} *${s}* handled ${e.workItem.source.kind} from ${a}:
386
+ - Address others by name when responding to their points.`}async triggerConferenceReactions(e,t,i,r){let o=t.threadId??t.id,s=this.meetingRosters.get(o);if(!s)return;this.meetingReactionTracker.has(o)||this.meetingReactionTracker.set(o,new Map);let a=this.meetingReactionTracker.get(o),l=a.get(r)??new Set;a.set(r,l);let c=[];for(let m of s){if(m===i||l.has(m))continue;let y=this.registry.get(m);!y||y.disabled||(l.add(m),c.push({agentId:y.id,name:y.name,title:y.title,role:y.soul.split(`
387
+ `)[0]}))}if(c.length===0)return;let u=await ay(e,c),d=new Set(u.respondAgentIds);for(let m of c)d.has(m.agentId)||l.delete(m.agentId);if(u.respondAgentIds.length===0)return;X.info("Conference depth-1 reactions",{threadId:o,respondingAgent:i,peers:u.respondAgentIds});let f="",p="";if(this.slackAdapter){let m=t.source.id,y=t.meta?.slackThreadTs??t.meta?.slackTs??o,_=await this.slackAdapter.fetchThreadHistory(m,y),b=[];for(let k of s){let O=this.registry.get(k);!O||O.disabled||b.push({agentId:O.id,name:O.name,title:O.title,role:O.soul.split(`
388
+ `)[0]})}f=this.formatThreadContext(_,t.source.label,b),p=this.buildMeetingPreamble(t.source.label,b)}let h=u.respondAgentIds.map(m=>{let y={agentId:m,conferenceMode:!0,conferenceHumanTs:r,conferenceRound:1,threadContext:f,meetingPreamble:p};return this.dispatchToAgent(t,y)});await Promise.all(h)}async postAuditLog(e){if(!this.auditAdapter||!this.auditChannelIds)return;let t=this.registry.get(e.agentId),i=t?.name??e.agentId,r=t?.homeBase,o=(r?this.auditChannelIds.get(r):void 0)??this.fallbackAuditChannelId;if(!o){X.warn("No audit channel resolved for agent",{agentId:e.agentId,homeBase:r});return}if(e.workItem.source.kind==="slack"&&e.workItem.source.id===o)return;let s=e.workItem.source.kind==="sms"?":phone:":e.workItem.source.kind==="imessage"?":speech_balloon:":e.workItem.source.kind==="app"?":iphone:":":incoming_envelope:",a=e.workItem.senderName??e.workItem.sender,l=e.text.length>300?e.text.slice(0,300)+"...":e.text,c={id:`audit:${e.workItem.id}`,text:`${s} *${i}* handled ${e.workItem.source.kind} from ${a}:
349
389
  > ${l}
350
- _($${e.costUsd.toFixed(3)} \xB7 ${(e.durationMs/1e3).toFixed(1)}s)_`,source:{kind:"internal",id:i,label:"audit"},sender:"system",timestamp:new Date,meta:{slackThreadTs:e.workItem.meta?.slackThreadTs,slackTs:e.workItem.meta?.slackTs}};await this.auditAdapter.deliver({text:c.text,agentId:"system",workItem:c,costUsd:0,durationMs:0})}};M();function Ek(n){let e=n;return e=e.replace(/^#{1,6}\s+(.+)$/gm,"*$1*"),e=e.replace(/\*{3}(.+?)\*{3}/g,"*_$1_*"),e=e.replace(/\*{2}(.+?)\*{2}/g,"*$1*"),e=e.replace(/__(.+?)__/g,"*$1*"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>"),e=e.replace(/~~(.+?)~~/g,"~$1~"),e=e.replace(/^[-*_]{3,}$/gm,"\u2014\u2014\u2014"),e}function Yh(n){return n?Ek(n.trim()):"_No response._"}function Jh(n){return`Something went wrong: ${n}`}var At=k("slack-adapter"),Nk=[{title:"Daily briefing",message:"What's on my plate today?"},{title:"Open tasks",message:"Show me all open tasks from Linear"},{title:"System status",message:"How's everyone doing?"},{title:"Quick note",message:"I need to remember something..."}],qr=class{id;kind="slack";gateway;registry;excludeChannels;defaultAgentId;botLabel;threadContextMap=new Map;threadContextLastSeen=new Map;constructor(e,t,s=[],r="slack",i,o){this.id=r,this.gateway=e,this.registry=t,this.excludeChannels=new Set(s),this.defaultAgentId=i,this.botLabel=o}async start(e){let t=this.registry.getAll().filter(s=>!s.slackBot||s.slackBot===this.botLabel).flatMap(s=>s.channels).filter(s=>!this.excludeChannels.has(s));this.gateway.addIntegrationChannels(t),this.gateway.onMessage(async s=>{if(this.excludeChannels.has(s.channelName)){At.debug("Ignoring message from excluded channel",{channel:s.channelName});return}let r=this.registry.findByChannel(s.channelName);if(r&&r.slackBot&&r.slackBot!==this.botLabel){At.debug("Ignoring message from other bot's channel",{channel:s.channelName,owner:r.id,botLabel:this.botLabel});return}let i=s.user.startsWith("U")?await this.gateway.resolveUserName(s.user):void 0,o={id:s.ts,text:s.text,source:{kind:"slack",id:s.channel,label:s.channelName,adapterId:this.id},sender:s.user,senderName:i,threadId:`slack:${s.channel}:${s.threadTs??s.ts}`,timestamp:new Date,meta:{slackTs:s.ts,slackThreadTs:s.threadTs,defaultAgentId:this.defaultAgentId},files:s.files};e(o)}),this.gateway.onThreadStarted(async s=>{At.info("Setting up new assistant thread",{channel:s.channel}),await this.gateway.setThreadStatus(s.channel,s.threadTs,"Getting ready..."),await this.gateway.setSuggestedPrompts(s.channel,s.threadTs,Nk),await this.gateway.setThreadStatus(s.channel,s.threadTs,""),s.context.channelId&&(this.threadContextMap.set(s.threadTs,s.context.channelId),this.threadContextLastSeen.set(s.threadTs,Date.now()))}),this.gateway.onThreadContextChanged(async s=>{s.context.channelId&&(this.threadContextMap.set(s.threadTs,s.context.channelId),this.threadContextLastSeen.set(s.threadTs,Date.now()),At.info("Thread context updated",{threadTs:s.threadTs,channelId:s.context.channelId}))}),await this.gateway.start(),At.info("Slack adapter started")}async deliver(e){let t=e.workItem.source.id,s=e.workItem.meta?.slackThreadTs??e.workItem.meta?.slackTs,r=this.registry.get(e.agentId),o=e.workItem.sender?.startsWith("B")||e.workItem.sender==="integration"?void 0:s,a=e.error?Jh(e.error):Yh(e.text);r&&(a=`${r.icon?`${r.icon} `:""}*${r.name}*: ${a}`);let l=r?{name:r.name,icon:r.icon}:void 0;await this.gateway.postMessage(t,a,o,l)}async onProcessingStart(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",r=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&r&&await this.gateway.setThreadStatus(e.source.id,r,"Thinking...")}async onProcessingEnd(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",r=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&r&&await this.gateway.setThreadStatus(e.source.id,r,"")}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.threadContextLastSeen)i<t&&(this.threadContextMap.delete(r),this.threadContextLastSeen.delete(r),s++);return{component:`slack-adapter:${this.id}`,pruned:s,retried:0,bytesFreed:0,errors:[]}}async stop(){await this.gateway.stop(),At.info("Slack adapter stopped")}get client(){return this.gateway.client}async fetchThreadHistory(e,t){try{let s=await this.gateway.client.conversations.replies({channel:e,ts:t,limit:200}),r=[],i=new Map;for(let o of s.messages??[]){if(!o.text&&!o.blocks)continue;let a="Unknown",l=!1,c=o;if(o.bot_id||c.subtype==="bot_message"){let d=o.text?.match(/^\S+\s\*([^*]+)\*:/);a=d?d[1]:c.username??"Agent",l=!0}else if(o.user){let d=i.get(o.user);if(d)a=d;else{try{let u=await this.gateway.client.users.info({user:o.user});a=u.user?.real_name??u.user?.name??o.user}catch{a=o.user}i.set(o.user,a)}}r.push({author:a,text:o.text??"",timestamp:new Date(parseFloat(o.ts??"0")*1e3),isBot:l})}return r}catch(s){return At.warn("Failed to fetch thread history",{channelId:e,threadTs:t,error:String(s)}),[]}}};M();var We=k("sms-adapter"),zh="https://api.openphone.com/v1",Fr=class{id="sms";kind="sms";apiKey;lines;interval=null;constructor(e,t){this.apiKey=e,this.lines=t.map(s=>({id:s.id,label:s.label,number:s.number,routeLabel:s.slackChannel??s.label,lastSeen:new Date().toISOString()}))}async start(e){if(this.lines.length===0){We.warn("SMS adapter has no lines to watch");return}this.poll(e),this.interval=setInterval(()=>this.poll(e),3e4),We.info("SMS adapter started",{lines:this.lines.map(t=>t.label)})}async deliver(e){if(e.error){We.warn("Skipping SMS delivery due to error",{error:e.error});return}let t=e.workItem.sender,s=e.workItem.source.id;try{let r=await fetch(`${zh}/messages`,{method:"POST",headers:{Authorization:this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({from:s,to:[t],content:e.text})});r.ok?We.info("SMS reply sent",{to:t,from:s}):We.error("Failed to send SMS reply",{status:r.status,body:await r.text(),to:t})}catch(r){We.error("SMS delivery error",{error:String(r),to:t})}}async stop(){this.interval&&(clearInterval(this.interval),this.interval=null),We.info("SMS adapter stopped")}async quoApi(e,t={}){let s=new URL(`${zh}${e}`);for(let[i,o]of Object.entries(t))o&&s.searchParams.append(i,o);let r=await fetch(s.toString(),{headers:{Authorization:this.apiKey}});if(!r.ok)throw new Error(`Quo API ${r.status}: ${await r.text()}`);return r.json()}async poll(e){for(let t of this.lines)try{let r=(await this.quoApi("/conversations",{"phoneNumbers[]":t.id,updatedAfter:t.lastSeen,maxResults:"20"})).data??[];if(r.length===0)continue;for(let i of r){let o=i.participants?.[0];if(!o)continue;let l=((await this.quoApi("/messages",{phoneNumberId:t.id,"participants[]":o,maxResults:"10",createdAfter:t.lastSeen})).data??[]).filter(c=>c.direction==="incoming").reverse();for(let c of l){if(!c.text)continue;let d=`SMS from ${c.from} \u2192 ${t.label}:
351
- ${c.text}`,u={id:c.id,text:d,source:{kind:"sms",id:t.id,label:t.routeLabel},sender:c.from,threadId:`sms:${t.id}:${c.from}`,timestamp:new Date,meta:{quoMessageId:c.id,lineNumber:t.number}};We.info("SMS received",{from:c.from,line:t.label,textLength:c.text.length}),e(u)}}t.lastSeen=new Date().toISOString()}catch(s){We.error("SMS poll failed",{line:t.label,error:String(s)})}}};M();import{execFileSync as Bk}from"node:child_process";import{readFileSync as Uk,writeFileSync as jk,existsSync as Xh,mkdirSync as qk}from"node:fs";import{resolve as Zh}from"node:path";M();import xk from"better-sqlite3";var Qh=k("imessage-db"),Ok=978307200,Mk=43;function Dk(n){let e=n/1e9+Ok;return new Date(e*1e3)}function Lk(n){try{let e=Buffer.from("NS.string"),t=n.indexOf(e);if(t===-1){let o=Buffer.from("NS.data");t=n.indexOf(o)}if(t===-1){let o=Buffer.from("streamtyped"),a=n.indexOf(o);return a===-1?null:Pk(n,a+o.length)}for(t+=e.length;t<n.length&&n[t]<32&&n[t]!==10;)t++;let s=t,r=t;for(;r<n.length;){let o=n[r];if(o===0||o===6&&r>s+1)break;r++}if(r<=s)return null;let i=n.subarray(s,r).toString("utf-8").trim();return i.length>0?i:null}catch(e){return Qh.warn("Failed to extract text from attributedBody",{error:String(e)}),null}}function Pk(n,e){let t=e,s=-1,r=0;for(;t<n.length-1;)if($k(n[t])){let o=t,a=0;for(;t<n.length&&Rk(n[t]);)a++,t++;a>r&&a>4&&(s=o,r=a)}else t++;if(s===-1)return null;let i=n.subarray(s,s+r).toString("utf-8").trim();return i.length>0?i:null}function $k(n){return n>=32&&n<=126||n>=192}function Rk(n){return n>=32&&n<=126||n===10||n===13||n===9||n>=128}var Kr=class{db;constructor(e){let t=e??`${process.env.HOME}/Library/Messages/chat.db`;this.db=new xk(t,{readonly:!0})}getNewMessages(e){let t=this.db.prepare(`
390
+ _($${e.costUsd.toFixed(3)} \xB7 ${(e.durationMs/1e3).toFixed(1)}s)_`,source:{kind:"internal",id:o,label:"audit"},sender:"system",timestamp:new Date,meta:{slackThreadTs:e.workItem.meta?.slackThreadTs,slackTs:e.workItem.meta?.slackTs}};await this.auditAdapter.deliver({text:c.text,agentId:"system",workItem:c,costUsd:0,durationMs:0})}};R();function PM(n){let e=n;return e=e.replace(/^#{1,6}\s+(.+)$/gm,"*$1*"),e=e.replace(/\*{3}(.+?)\*{3}/g,"*_$1_*"),e=e.replace(/\*{2}(.+?)\*{2}/g,"*$1*"),e=e.replace(/__(.+?)__/g,"*$1*"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>"),e=e.replace(/~~(.+?)~~/g,"~$1~"),e=e.replace(/^[-*_]{3,}$/gm,"\u2014\u2014\u2014"),e}function dI(n){return n?PM(n.trim()):"_No response._"}function fI(n){return`Something went wrong: ${n}`}var Cn=$("slack-adapter"),MM=[{title:"Daily briefing",message:"What's on my plate today?"},{title:"Open tasks",message:"Show me all open tasks from Linear"},{title:"System status",message:"How's everyone doing?"},{title:"Quick note",message:"I need to remember something..."}],Xc=class{id;kind="slack";gateway;registry;excludeChannels;defaultAgentId;botLabel;threadContextMap=new Map;threadContextLastSeen=new Map;constructor(e,t,i=[],r="slack",o,s){this.id=r,this.gateway=e,this.registry=t,this.excludeChannels=new Set(i),this.defaultAgentId=o,this.botLabel=s}async start(e){let t=this.registry.getAll().filter(i=>!i.slackBot||i.slackBot===this.botLabel).flatMap(i=>i.channels).filter(i=>!this.excludeChannels.has(i));this.gateway.addIntegrationChannels(t),this.gateway.onMessage(async i=>{if(this.excludeChannels.has(i.channelName)){Cn.debug("Ignoring message from excluded channel",{channel:i.channelName});return}let r=this.registry.findByChannel(i.channelName);if(r&&r.slackBot&&r.slackBot!==this.botLabel){Cn.debug("Ignoring message from other bot's channel",{channel:i.channelName,owner:r.id,botLabel:this.botLabel});return}let o=i.user.startsWith("U")?await this.gateway.resolveUserName(i.user):void 0,s={id:i.ts,text:i.text,source:{kind:"slack",id:i.channel,label:i.channelName,adapterId:this.id},sender:i.user,senderName:o,threadId:`slack:${i.channel}:${i.threadTs??i.ts}`,timestamp:new Date,meta:{slackTs:i.ts,slackThreadTs:i.threadTs,defaultAgentId:this.defaultAgentId},files:i.files};e(s)}),this.gateway.onThreadStarted(async i=>{Cn.info("Setting up new assistant thread",{channel:i.channel}),await this.gateway.setThreadStatus(i.channel,i.threadTs,"Getting ready..."),await this.gateway.setSuggestedPrompts(i.channel,i.threadTs,MM),await this.gateway.setThreadStatus(i.channel,i.threadTs,""),i.context.channelId&&(this.threadContextMap.set(i.threadTs,i.context.channelId),this.threadContextLastSeen.set(i.threadTs,Date.now()))}),this.gateway.onThreadContextChanged(async i=>{i.context.channelId&&(this.threadContextMap.set(i.threadTs,i.context.channelId),this.threadContextLastSeen.set(i.threadTs,Date.now()),Cn.info("Thread context updated",{threadTs:i.threadTs,channelId:i.context.channelId}))}),await this.gateway.start(),Cn.info("Slack adapter started")}async deliver(e){let t=e.workItem.source.id,i=e.workItem.meta?.slackThreadTs??e.workItem.meta?.slackTs,r=this.registry.get(e.agentId),s=e.workItem.sender?.startsWith("B")||e.workItem.sender==="integration"?void 0:i,a=e.error?fI(e.error):dI(e.text);r&&(a=`${r.icon?`${r.icon} `:""}*${r.name}*: ${a}`);let l=r?{name:r.name,icon:r.icon}:void 0;await this.gateway.postMessage(t,a,s,l)}async onProcessingStart(e,t){let i=e.sender?.startsWith("B")||e.sender==="integration",r=e.meta?.slackThreadTs??e.meta?.slackTs;!i&&r&&await this.gateway.setThreadStatus(e.source.id,r,"Thinking...")}async onProcessingEnd(e,t){let i=e.sender?.startsWith("B")||e.sender==="integration",r=e.meta?.slackThreadTs??e.meta?.slackTs;!i&&r&&await this.gateway.setThreadStatus(e.source.id,r,"")}sweep(e){let t=Date.now()-e,i=0;for(let[r,o]of this.threadContextLastSeen)o<t&&(this.threadContextMap.delete(r),this.threadContextLastSeen.delete(r),i++);return{component:`slack-adapter:${this.id}`,pruned:i,retried:0,bytesFreed:0,errors:[]}}async stop(){await this.gateway.stop(),Cn.info("Slack adapter stopped")}get client(){return this.gateway.client}async fetchThreadHistory(e,t){try{let i=await this.gateway.client.conversations.replies({channel:e,ts:t,limit:200}),r=[],o=new Map;for(let s of i.messages??[]){if(!s.text&&!s.blocks)continue;let a="Unknown",l=!1,c=s;if(s.bot_id||c.subtype==="bot_message"){let u=s.text?.match(/^\S+\s\*([^*]+)\*:/);a=u?u[1]:c.username??"Agent",l=!0}else if(s.user){let u=o.get(s.user);if(u)a=u;else{try{let d=await this.gateway.client.users.info({user:s.user});a=d.user?.real_name??d.user?.name??s.user}catch{a=s.user}o.set(s.user,a)}}r.push({author:a,text:s.text??"",timestamp:new Date(parseFloat(s.ts??"0")*1e3),isBot:l})}return r}catch(i){return Cn.warn("Failed to fetch thread history",{channelId:e,threadTs:t,error:String(i)}),[]}}};R();var Ot=$("sms-adapter"),pI="https://api.openphone.com/v1",Qc=class{id="sms";kind="sms";apiKey;lines;interval=null;constructor(e,t){this.apiKey=e,this.lines=t.map(i=>({id:i.id,label:i.label,number:i.number,routeLabel:i.slackChannel??i.label,lastSeen:new Date().toISOString()}))}async start(e){if(this.lines.length===0){Ot.warn("SMS adapter has no lines to watch");return}this.poll(e),this.interval=setInterval(()=>this.poll(e),3e4),Ot.info("SMS adapter started",{lines:this.lines.map(t=>t.label)})}async deliver(e){if(e.error){Ot.warn("Skipping SMS delivery due to error",{error:e.error});return}let t=e.workItem.sender,i=e.workItem.source.id;try{let r=await fetch(`${pI}/messages`,{method:"POST",headers:{Authorization:this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({from:i,to:[t],content:e.text})});r.ok?Ot.info("SMS reply sent",{to:t,from:i}):Ot.error("Failed to send SMS reply",{status:r.status,body:await r.text(),to:t})}catch(r){Ot.error("SMS delivery error",{error:String(r),to:t})}}async stop(){this.interval&&(clearInterval(this.interval),this.interval=null),Ot.info("SMS adapter stopped")}async quoApi(e,t={}){let i=new URL(`${pI}${e}`);for(let[o,s]of Object.entries(t))s&&i.searchParams.append(o,s);let r=await fetch(i.toString(),{headers:{Authorization:this.apiKey}});if(!r.ok)throw new Error(`Quo API ${r.status}: ${await r.text()}`);return r.json()}async poll(e){for(let t of this.lines)try{let r=(await this.quoApi("/conversations",{"phoneNumbers[]":t.id,updatedAfter:t.lastSeen,maxResults:"20"})).data??[];if(r.length===0)continue;for(let o of r){let s=o.participants?.[0];if(!s)continue;let l=((await this.quoApi("/messages",{phoneNumberId:t.id,"participants[]":s,maxResults:"10",createdAfter:t.lastSeen})).data??[]).filter(c=>c.direction==="incoming").reverse();for(let c of l){if(!c.text)continue;let u=`SMS from ${c.from} \u2192 ${t.label}:
391
+ ${c.text}`,d={id:c.id,text:u,source:{kind:"sms",id:t.id,label:t.routeLabel},sender:c.from,threadId:`sms:${t.id}:${c.from}`,timestamp:new Date,meta:{quoMessageId:c.id,lineNumber:t.number}};Ot.info("SMS received",{from:c.from,line:t.label,textLength:c.text.length}),e(d)}}t.lastSeen=new Date().toISOString()}catch(i){Ot.error("SMS poll failed",{line:t.label,error:String(i)})}}};R();import{execFileSync as ZM}from"node:child_process";import{readFileSync as KM,writeFileSync as VM,existsSync as hI,mkdirSync as WM}from"node:fs";import{resolve as gI}from"node:path";R();import LM from"better-sqlite3";var mI=$("imessage-db"),zM=978307200,jM=43;function UM(n){let e=n/1e9+zM;return new Date(e*1e3)}function RM(n){try{let e=Buffer.from("NS.string"),t=n.indexOf(e);if(t===-1){let s=Buffer.from("NS.data");t=n.indexOf(s)}if(t===-1){let s=Buffer.from("streamtyped"),a=n.indexOf(s);return a===-1?null:BM(n,a+s.length)}for(t+=e.length;t<n.length&&n[t]<32&&n[t]!==10;)t++;let i=t,r=t;for(;r<n.length;){let s=n[r];if(s===0||s===6&&r>i+1)break;r++}if(r<=i)return null;let o=n.subarray(i,r).toString("utf-8").trim();return o.length>0?o:null}catch(e){return mI.warn("Failed to extract text from attributedBody",{error:String(e)}),null}}function BM(n,e){let t=e,i=-1,r=0;for(;t<n.length-1;)if(FM(n[t])){let s=t,a=0;for(;t<n.length&&qM(n[t]);)a++,t++;a>r&&a>4&&(i=s,r=a)}else t++;if(i===-1)return null;let o=n.subarray(i,i+r).toString("utf-8").trim();return o.length>0?o:null}function FM(n){return n>=32&&n<=126||n>=192}function qM(n){return n>=32&&n<=126||n===10||n===13||n===9||n>=128}var el=class{db;constructor(e){let t=e??`${process.env.HOME}/Library/Messages/chat.db`;this.db=new LM(t,{readonly:!0})}getNewMessages(e){let t=this.db.prepare(`
352
392
  SELECT m.ROWID AS rowId, m.text, m.attributedBody, m.is_from_me AS isFromMe,
353
393
  m.date, m.service, h.id AS sender, h.ROWID AS handleRowId
354
394
  FROM message m
@@ -360,46 +400,46 @@ ${c.text}`,u={id:c.id,text:d,source:{kind:"sms",id:t.id,label:t.routeLabel},send
360
400
  AND m.is_empty = 0
361
401
  AND (c.style IS NULL OR c.style != ?)
362
402
  ORDER BY m.ROWID ASC
363
- `).all(e,Mk),s=[];for(let r of t){let i=r.text;if(!i&&r.attributedBody&&(i=Lk(r.attributedBody),!i)){Qh.warn("Could not extract text from attributedBody, skipping",{rowId:r.rowId});continue}i&&s.push({rowId:r.rowId,text:i,sender:r.sender,handleRowId:r.handleRowId,service:r.service,date:Dk(r.date)})}return s}getMaxRowId(){return this.db.prepare("SELECT MAX(ROWID) AS maxId FROM message").get().maxId??0}close(){this.db.close()}};var ne=k("imessage-adapter"),Hr=class{id="imessage";kind="imessage";config;mongoDb;gateway;db;threadsCollection;contactsCollection;slackChannelId;interval=null;lastSeenRowId=0;lastMessageAt=0;lastColdPoll=0;stateFilePath;constructor(e,t,s,r){this.config=e,this.mongoDb=t,this.gateway=s,this.stateFilePath=Zh(`/tmp/${r}-imessage-state.json`)}async start(e){this.threadsCollection=this.mongoDb.collection("imessage_threads"),this.contactsCollection=this.mongoDb.collection("contacts");try{let s=((await this.gateway.client.conversations.list({types:"public_channel",limit:200})).channels??[]).find(r=>r.name===this.config.slackChannel);s?.id?(this.slackChannelId=s.id,ne.info("Slack mirror channel resolved",{channel:this.config.slackChannel,id:s.id})):ne.warn("Slack mirror channel not found",{channel:this.config.slackChannel})}catch(t){ne.warn("Failed to resolve Slack mirror channel",{error:String(t)})}try{this.db=new Kr}catch(t){ne.error("Failed to open chat.db \u2014 check Full Disk Access for node",{error:String(t)});return}this.loadState(),this.lastSeenRowId===0&&(this.lastSeenRowId=this.db.getMaxRowId(),this.saveState(),ne.info("First run \u2014 initialized lastSeenRowId",{lastSeenRowId:this.lastSeenRowId})),this.interval=setInterval(()=>this.poll(e),this.config.hotIntervalMs),this.poll(e),ne.info("iMessage adapter started",{lastSeenRowId:this.lastSeenRowId,hotIntervalMs:this.config.hotIntervalMs,coldIntervalMs:this.config.coldIntervalMs})}async deliver(e){if(e.error){ne.warn("Skipping iMessage delivery due to error",{error:e.error});return}let t=e.workItem.sender;try{this.sendViaAppleScript(t,e.text),ne.info("iMessage reply sent",{to:t})}catch(s){ne.warn("iMessage send failed, retrying",{error:String(s),to:t});try{await Fk(500),this.sendViaAppleScript(t,e.text),ne.info("iMessage reply sent on retry",{to:t})}catch(r){ne.error("iMessage delivery failed after retry",{error:String(r),to:t});return}}await this.mirrorToSlack(t,e.text,e.agentId,!0)}async stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.db?.close(),ne.info("iMessage adapter stopped")}async poll(e){let t=Date.now(),s=t-this.lastMessageAt<this.config.hotWindowMs;if(!(!s&&t-this.lastColdPoll<this.config.coldIntervalMs)&&(s||(this.lastColdPoll=t),!!this.db))try{let r=this.db.getNewMessages(this.lastSeenRowId);if(r.length===0)return;for(let i of r){this.lastSeenRowId=i.rowId,this.lastMessageAt=t;let o={id:`imsg-${i.rowId}`,text:i.text,source:{kind:"imessage",id:"imessage",label:"imessage"},sender:i.sender,threadId:`imessage:${i.sender}`,timestamp:i.date,meta:{messageRowId:i.rowId,service:i.service}};ne.info("iMessage received",{from:i.sender,service:i.service,textLength:i.text.length}),await this.mirrorToSlack(i.sender,i.text,void 0,!1),e(o)}this.saveState()}catch(r){ne.error("iMessage poll failed",{error:String(r)})}}sendViaAppleScript(e,t){let s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');Bk("osascript",["-e",'tell application "Messages"',"-e","set targetService to 1st account whose service type = iMessage","-e",`set targetBuddy to participant "${e}" of targetService`,"-e",`send "${s}" to targetBuddy`,"-e","end tell"])}async mirrorToSlack(e,t,s,r){if(!(!this.slackChannelId||!this.threadsCollection))try{let i=await this.threadsCollection.findOne({handleId:e}),o;if(i)o=i.slackThreadTs;else{let l=await this.resolveContactName(e),c=`:speech_balloon: iMessage conversation with ${l}`,d=await this.gateway.postMessage(this.slackChannelId,c);if(!d){ne.warn("Failed to create Slack mirror thread",{handleId:e});return}o=d,await this.threadsCollection.insertOne({handleId:e,slackThreadTs:o,displayName:l,createdAt:new Date})}let a=r?s?`*${s}*: `:"*Agent*: ":`*${e}*: `;await this.gateway.postMessage(this.slackChannelId,`${a}${t}`,o)}catch(i){ne.warn("Slack mirror failed",{error:String(i),handleId:e})}}async resolveContactName(e){if(!this.contactsCollection)return e;try{let t=await this.contactsCollection.findOne({$or:[{phones:e},{emails:e}]});if(t?.displayName)return`${t.displayName} (${e})`;if(t?.name)return`${t.name} (${e})`}catch{}return e}loadState(){try{if(Xh(this.stateFilePath)){let e=JSON.parse(Uk(this.stateFilePath,"utf-8"));this.lastSeenRowId=e.lastSeenRowId??0,ne.info("Restored iMessage state",{lastSeenRowId:this.lastSeenRowId})}}catch(e){ne.warn("Failed to load iMessage state, starting fresh",{error:String(e)})}}saveState(){try{let e=Zh(this.stateFilePath,"..");Xh(e)||qk(e,{recursive:!0}),jk(this.stateFilePath,JSON.stringify({lastSeenRowId:this.lastSeenRowId}))}catch(e){ne.warn("Failed to save iMessage state",{error:String(e)})}}};function Fk(n){return new Promise(e=>setTimeout(e,n))}M();var Qt=k("task-client"),Wr=class{apiUrl;apiKey;constructor(e,t){this.apiUrl=e,this.apiKey=t}get isConfigured(){return this.apiKey.length>0}async api(e,t,s){let r=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":this.apiKey,...s?{"Content-Type":"application/json"}:{}},...s?{body:JSON.stringify(s)}:{}});if(!r.ok)throw new Error(`Task API ${r.status}: ${await r.text()}`);return r.json()}async createTask(e){try{let t=await this.api("POST","/tasks",e);return Qt.info("Task created",{taskId:t._id,name:e.name}),t}catch(t){return Qt.error("Failed to create task",{error:String(t),name:e.name}),null}}async updateTask(e,t){try{return await this.api("PUT",`/tasks/${e}`,t),Qt.info("Task updated",{taskId:e,...t}),!0}catch(s){return Qt.error("Failed to update task",{error:String(s),taskId:e}),!1}}async addComment(e,t){try{return await this.api("POST",`/tasks/${e}/comments`,{content:t}),Qt.info("Comment added",{taskId:e}),!0}catch(s){return Qt.error("Failed to add comment",{error:String(s),taskId:e}),!1}}};M();var zs=k("task-ledger"),Gr=class{threadTaskMap=new Map;threadTaskLastSeen=new Map;apiUrl;agentKeys;fallbackKey;constructor(e,t,s){this.apiUrl=e,this.agentKeys=t,this.fallbackKey=s}get isConfigured(){return Object.keys(this.agentKeys).length>0||this.fallbackKey.length>0}shouldTrack(e){return e.source.kind!=="slack"&&e.source.kind!=="sms"}async onDispatch(e,t){let s=this.getApiKey(t);if(!s)return;let r=e.threadId??e.id,i=this.threadTaskMap.get(r);if(i){this.threadTaskLastSeen.set(r,Date.now()),await this.addComment(i,s,this.formatIncomingComment(e));return}let o=await this.createTask(s,e);o&&(this.threadTaskMap.set(r,o),this.threadTaskLastSeen.set(r,Date.now()))}async onComplete(e){let t=this.getApiKey(e.agentId);if(!t)return;let s=e.workItem.threadId??e.workItem.id,r=this.threadTaskMap.get(s);if(r&&this.threadTaskLastSeen.set(s,Date.now()),!r)return;let i=this.formatCompletionComment(e);await this.addComment(r,t,i),e.error||await this.updateTask(r,t,{state:"DONE"})}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.threadTaskLastSeen)i<t&&(this.threadTaskMap.delete(r),this.threadTaskLastSeen.delete(r),s++);return{component:"task-ledger",pruned:s,retried:0,bytesFreed:0,errors:[]}}getApiKey(e){let t=this.agentKeys[e]??this.fallbackKey;return t||(zs.debug("No task ledger API key for agent",{agentId:e}),null)}async createTask(e,t){try{let s=await this.api("POST","/tasks",e,{name:this.taskName(t),type:this.taskType(t),description:this.taskDescription(t)});return zs.info("Task created",{taskId:s.taskId,source:t.source.kind}),s.taskId}catch(s){return zs.error("Failed to create task",{error:String(s),source:t.source.kind}),null}}async addComment(e,t,s){try{await this.api("POST",`/tasks/${e}/comments`,t,{content:s})}catch(r){zs.error("Failed to add comment",{error:String(r),taskId:e})}}async updateTask(e,t,s){try{await this.api("PUT",`/tasks/${e}`,t,s)}catch(r){zs.error("Failed to update task",{error:String(r),taskId:e})}}async api(e,t,s,r){let i=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":s,...r?{"Content-Type":"application/json"}:{}},...r?{body:JSON.stringify(r)}:{}});if(!i.ok)throw new Error(`Task API ${i.status}: ${await i.text()}`);return i.json()}taskName(e){let t=e.text,s=t.match(/\[Scheduled task: (.+?)\]/);if(s)return`[Scheduled] ${s[1]}`;let r=t.match(/Command: `(.+?)`/);if(r)return`[Background] ${r[1].slice(0,80)}`;let i=t.match(/\[Meeting (?:transcript update|ended) — (.+?)\]/);return i?`[Meeting] ${i[1]}`:e.source.kind==="email"?`[Email] ${t.slice(0,80)}`:`[${e.source.kind}] ${t.slice(0,80)}`}taskType(e){return e.source.kind==="email"?"FOLLOW_UP":e.text.includes("[Meeting ended")?"ACTION_ITEM":"AGENT"}taskDescription(e){let t=[`**Source:** ${e.source.kind} / ${e.source.label}`,`**Sender:** ${e.senderName??e.sender}`,`**Time:** ${e.timestamp.toISOString()}`];e.threadId&&t.push(`**Thread:** ${e.threadId}`);let s=5e3,r=e.text.length>s?e.text.slice(0,s)+`
403
+ `).all(e,jM),i=[];for(let r of t){let o=r.text;if(!o&&r.attributedBody&&(o=RM(r.attributedBody),!o)){mI.warn("Could not extract text from attributedBody, skipping",{rowId:r.rowId});continue}o&&i.push({rowId:r.rowId,text:o,sender:r.sender,handleRowId:r.handleRowId,service:r.service,date:UM(r.date)})}return i}getMaxRowId(){return this.db.prepare("SELECT MAX(ROWID) AS maxId FROM message").get().maxId??0}close(){this.db.close()}};var _e=$("imessage-adapter"),tl=class{id="imessage";kind="imessage";config;mongoDb;gateway;db;threadsCollection;contactsCollection;slackChannelId;interval=null;lastSeenRowId=0;lastMessageAt=0;lastColdPoll=0;stateFilePath;constructor(e,t,i,r){this.config=e,this.mongoDb=t,this.gateway=i,this.stateFilePath=gI(`/tmp/${r}-imessage-state.json`)}async start(e){this.threadsCollection=this.mongoDb.collection("imessage_threads"),this.contactsCollection=this.mongoDb.collection("contacts");try{let i=((await this.gateway.client.conversations.list({types:"public_channel",limit:200})).channels??[]).find(r=>r.name===this.config.slackChannel);i?.id?(this.slackChannelId=i.id,_e.info("Slack mirror channel resolved",{channel:this.config.slackChannel,id:i.id})):_e.warn("Slack mirror channel not found",{channel:this.config.slackChannel})}catch(t){_e.warn("Failed to resolve Slack mirror channel",{error:String(t)})}try{this.db=new el}catch(t){_e.error("Failed to open chat.db \u2014 check Full Disk Access for node",{error:String(t)});return}this.loadState(),this.lastSeenRowId===0&&(this.lastSeenRowId=this.db.getMaxRowId(),this.saveState(),_e.info("First run \u2014 initialized lastSeenRowId",{lastSeenRowId:this.lastSeenRowId})),this.interval=setInterval(()=>this.poll(e),this.config.hotIntervalMs),this.poll(e),_e.info("iMessage adapter started",{lastSeenRowId:this.lastSeenRowId,hotIntervalMs:this.config.hotIntervalMs,coldIntervalMs:this.config.coldIntervalMs})}async deliver(e){if(e.error){_e.warn("Skipping iMessage delivery due to error",{error:e.error});return}let t=e.workItem.sender;try{this.sendViaAppleScript(t,e.text),_e.info("iMessage reply sent",{to:t})}catch(i){_e.warn("iMessage send failed, retrying",{error:String(i),to:t});try{await GM(500),this.sendViaAppleScript(t,e.text),_e.info("iMessage reply sent on retry",{to:t})}catch(r){_e.error("iMessage delivery failed after retry",{error:String(r),to:t});return}}await this.mirrorToSlack(t,e.text,e.agentId,!0)}async stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.db?.close(),_e.info("iMessage adapter stopped")}async poll(e){let t=Date.now(),i=t-this.lastMessageAt<this.config.hotWindowMs;if(!(!i&&t-this.lastColdPoll<this.config.coldIntervalMs)&&(i||(this.lastColdPoll=t),!!this.db))try{let r=this.db.getNewMessages(this.lastSeenRowId);if(r.length===0)return;for(let o of r){this.lastSeenRowId=o.rowId,this.lastMessageAt=t;let s={id:`imsg-${o.rowId}`,text:o.text,source:{kind:"imessage",id:"imessage",label:"imessage"},sender:o.sender,threadId:`imessage:${o.sender}`,timestamp:o.date,meta:{messageRowId:o.rowId,service:o.service}};_e.info("iMessage received",{from:o.sender,service:o.service,textLength:o.text.length}),await this.mirrorToSlack(o.sender,o.text,void 0,!1),e(s)}this.saveState()}catch(r){_e.error("iMessage poll failed",{error:String(r)})}}sendViaAppleScript(e,t){let i=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');ZM("osascript",["-e",'tell application "Messages"',"-e","set targetService to 1st account whose service type = iMessage","-e",`set targetBuddy to participant "${e}" of targetService`,"-e",`send "${i}" to targetBuddy`,"-e","end tell"])}async mirrorToSlack(e,t,i,r){if(!(!this.slackChannelId||!this.threadsCollection))try{let o=await this.threadsCollection.findOne({handleId:e}),s;if(o)s=o.slackThreadTs;else{let l=await this.resolveContactName(e),c=`:speech_balloon: iMessage conversation with ${l}`,u=await this.gateway.postMessage(this.slackChannelId,c);if(!u){_e.warn("Failed to create Slack mirror thread",{handleId:e});return}s=u,await this.threadsCollection.insertOne({handleId:e,slackThreadTs:s,displayName:l,createdAt:new Date})}let a=r?i?`*${i}*: `:"*Agent*: ":`*${e}*: `;await this.gateway.postMessage(this.slackChannelId,`${a}${t}`,s)}catch(o){_e.warn("Slack mirror failed",{error:String(o),handleId:e})}}async resolveContactName(e){if(!this.contactsCollection)return e;try{let t=await this.contactsCollection.findOne({$or:[{phones:e},{emails:e}]});if(t?.displayName)return`${t.displayName} (${e})`;if(t?.name)return`${t.name} (${e})`}catch{}return e}loadState(){try{if(hI(this.stateFilePath)){let e=JSON.parse(KM(this.stateFilePath,"utf-8"));this.lastSeenRowId=e.lastSeenRowId??0,_e.info("Restored iMessage state",{lastSeenRowId:this.lastSeenRowId})}}catch(e){_e.warn("Failed to load iMessage state, starting fresh",{error:String(e)})}}saveState(){try{let e=gI(this.stateFilePath,"..");hI(e)||WM(e,{recursive:!0}),VM(this.stateFilePath,JSON.stringify({lastSeenRowId:this.lastSeenRowId}))}catch(e){_e.warn("Failed to save iMessage state",{error:String(e)})}}};function GM(n){return new Promise(e=>setTimeout(e,n))}R();var Mr=$("task-client"),nl=class{apiUrl;apiKey;constructor(e,t){this.apiUrl=e,this.apiKey=t}get isConfigured(){return this.apiKey.length>0}async api(e,t,i){let r=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":this.apiKey,...i?{"Content-Type":"application/json"}:{}},...i?{body:JSON.stringify(i)}:{}});if(!r.ok)throw new Error(`Task API ${r.status}: ${await r.text()}`);return r.json()}async createTask(e){try{let t=await this.api("POST","/tasks",e);return Mr.info("Task created",{taskId:t._id,name:e.name}),t}catch(t){return Mr.error("Failed to create task",{error:String(t),name:e.name}),null}}async updateTask(e,t){try{return await this.api("PUT",`/tasks/${e}`,t),Mr.info("Task updated",{taskId:e,...t}),!0}catch(i){return Mr.error("Failed to update task",{error:String(i),taskId:e}),!1}}async addComment(e,t){try{return await this.api("POST",`/tasks/${e}/comments`,{content:t}),Mr.info("Comment added",{taskId:e}),!0}catch(i){return Mr.error("Failed to add comment",{error:String(i),taskId:e}),!1}}};R();var vo=$("task-ledger"),rl=class{threadTaskMap=new Map;threadTaskLastSeen=new Map;apiUrl;agentKeys;fallbackKey;constructor(e,t,i){this.apiUrl=e,this.agentKeys=t,this.fallbackKey=i}get isConfigured(){return Object.keys(this.agentKeys).length>0||this.fallbackKey.length>0}shouldTrack(e){return e.source.kind!=="slack"&&e.source.kind!=="sms"}async onDispatch(e,t){let i=this.getApiKey(t);if(!i)return;let r=e.threadId??e.id,o=this.threadTaskMap.get(r);if(o){this.threadTaskLastSeen.set(r,Date.now()),await this.addComment(o,i,this.formatIncomingComment(e));return}let s=await this.createTask(i,e);s&&(this.threadTaskMap.set(r,s),this.threadTaskLastSeen.set(r,Date.now()))}async onComplete(e){let t=this.getApiKey(e.agentId);if(!t)return;let i=e.workItem.threadId??e.workItem.id,r=this.threadTaskMap.get(i);if(r&&this.threadTaskLastSeen.set(i,Date.now()),!r)return;let o=this.formatCompletionComment(e);await this.addComment(r,t,o),e.error||await this.updateTask(r,t,{state:"DONE"})}sweep(e){let t=Date.now()-e,i=0;for(let[r,o]of this.threadTaskLastSeen)o<t&&(this.threadTaskMap.delete(r),this.threadTaskLastSeen.delete(r),i++);return{component:"task-ledger",pruned:i,retried:0,bytesFreed:0,errors:[]}}getApiKey(e){let t=this.agentKeys[e]??this.fallbackKey;return t||(vo.debug("No task ledger API key for agent",{agentId:e}),null)}async createTask(e,t){try{let i=await this.api("POST","/tasks",e,{name:this.taskName(t),type:this.taskType(t),description:this.taskDescription(t)});return vo.info("Task created",{taskId:i.taskId,source:t.source.kind}),i.taskId}catch(i){return vo.error("Failed to create task",{error:String(i),source:t.source.kind}),null}}async addComment(e,t,i){try{await this.api("POST",`/tasks/${e}/comments`,t,{content:i})}catch(r){vo.error("Failed to add comment",{error:String(r),taskId:e})}}async updateTask(e,t,i){try{await this.api("PUT",`/tasks/${e}`,t,i)}catch(r){vo.error("Failed to update task",{error:String(r),taskId:e})}}async api(e,t,i,r){let o=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":i,...r?{"Content-Type":"application/json"}:{}},...r?{body:JSON.stringify(r)}:{}});if(!o.ok)throw new Error(`Task API ${o.status}: ${await o.text()}`);return o.json()}taskName(e){let t=e.text,i=t.match(/\[Scheduled task: (.+?)\]/);if(i)return`[Scheduled] ${i[1]}`;let r=t.match(/Command: `(.+?)`/);if(r)return`[Background] ${r[1].slice(0,80)}`;let o=t.match(/\[Meeting (?:transcript update|ended) — (.+?)\]/);return o?`[Meeting] ${o[1]}`:e.source.kind==="email"?`[Email] ${t.slice(0,80)}`:`[${e.source.kind}] ${t.slice(0,80)}`}taskType(e){return e.source.kind==="email"?"FOLLOW_UP":e.text.includes("[Meeting ended")?"ACTION_ITEM":"AGENT"}taskDescription(e){let t=[`**Source:** ${e.source.kind} / ${e.source.label}`,`**Sender:** ${e.senderName??e.sender}`,`**Time:** ${e.timestamp.toISOString()}`];e.threadId&&t.push(`**Thread:** ${e.threadId}`);let i=5e3,r=e.text.length>i?e.text.slice(0,i)+`
364
404
 
365
405
  ... (truncated)`:e.text;return t.push("","---","",r),t.join(`
366
406
  `)}formatIncomingComment(e){return`**Follow-up message** (${e.source.kind})
367
407
 
368
408
  ${e.text.slice(0,5e3)}`}formatCompletionComment(e){let t=[`**Agent response** ($${e.costUsd.toFixed(3)} \xB7 ${(e.durationMs/1e3).toFixed(1)}s)`];e.error&&t.push(`
369
- **Error:** ${e.error}`);let s=5e3,r=e.text.length>s?e.text.slice(0,s)+`
409
+ **Error:** ${e.error}`);let i=5e3,r=e.text.length>i?e.text.slice(0,i)+`
370
410
 
371
411
  ... (truncated)`:e.text;return t.push("",r),t.join(`
372
- `)}};M();import{createServer as Kk}from"node:http";import{spawn as Hk}from"node:child_process";import{mkdir as Wk,readFile as ef,writeFile as Gk,readdir as Vk,stat as Yk,unlink as Jk}from"node:fs/promises";import{openSync as zk,closeSync as Qk}from"node:fs";import{randomUUID as Xk}from"node:crypto";var we=k("bg-task-manager"),ja=100,Zk=5e3,Vr=class{port;authToken;tasksDir;tasks=new Map;onComplete;server=null;orphanPollers=new Map;constructor(e,t,s,r){this.port=e,this.authToken=t,this.tasksDir=s,this.onComplete=r}async start(){await Wk(this.tasksDir,{recursive:!0}),this.server=Kk((e,t)=>{this.handleRequest(e,t).catch(s=>{we.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),we.info("Background task manager started",{port:this.port})}async scanOrphans(){let e;try{e=await Vk(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".json")),s=0,r=0;for(let i of t)try{let o=await ef(`${this.tasksDir}/${i}`,"utf-8"),a=JSON.parse(o);this.tasks.set(a.id,a),a.status==="running"&&a.pid&&(this.isProcessAlive(a.pid)?(this.pollOrphan(a.id,a.pid),r++):(a.status="orphaned",a.completedAt=new Date().toISOString(),await this.writeMeta(a),this.fireCompletion(a),s++))}catch(o){we.warn("Failed to read orphan task file",{file:i,error:String(o)})}(s>0||r>0)&&we.info("Orphan scan complete",{orphaned:s,recovered:r,total:t.length})}async stop(){for(let[,t]of this.orphanPollers)clearInterval(t);this.orphanPollers.clear();let e=[...this.tasks.values()].filter(t=>t.status==="running"&&t.pid);if(e.length>0){we.info("Sending SIGTERM to running background tasks",{count:e.length});for(let t of e)this.killProcess(t.pid,"SIGTERM");await this.sleep(Zk);for(let t of e)t.pid&&this.isProcessAlive(t.pid)&&(we.warn("Background task did not exit after SIGTERM, sending SIGKILL",{id:t.id,pid:t.pid}),this.killProcess(t.pid,"SIGKILL"))}this.server&&(this.server.close(),this.server=null),we.info("Background task manager stopped",{killed:e.length})}killProcess(e,t){try{process.kill(e,t)}catch(s){s.code!=="ESRCH"&&we.warn("Failed to send signal to process",{pid:e,signal:t,error:String(s)})}}sleep(e){return new Promise(t=>setTimeout(t,e))}async handleRequest(e,t){let s=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="POST"&&s.pathname==="/tasks"){let o=await this.readBody(e),a=JSON.parse(o),l=await this.spawnTask(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:l.id,status:"running"}));return}let i=s.pathname.match(/^\/tasks\/([a-f0-9-]+)$/);if(e.method==="GET"&&i){let o=i[1],a=await this.taskStatus(o);if(!a){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Task not found"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(a));return}if(e.method==="GET"&&s.pathname==="/tasks"){let o=s.searchParams.get("agentId")??void 0,a=await this.listTasks(o);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({tasks:a}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}async spawnTask(e){let t=Xk(),s=`${this.tasksDir}/${t}.log`,r=`${this.tasksDir}/${t}.json`,i=e.cwd??process.env.HOME??"/tmp",o=zk(s,"a"),a=Hk(e.command,e.args??[],{cwd:i,detached:!0,stdio:["ignore",o,o]});Qk(o);let l={id:t,command:e.command+(e.args?.length?" "+e.args.join(" "):""),cwd:i,status:"running",exitCode:null,startedAt:new Date().toISOString(),completedAt:null,logPath:s,metaPath:r,context:e.context,pid:a.pid??null};return this.tasks.set(t,l),a.on("exit",c=>this.handleExit(t,c)),a.on("error",c=>{we.error("Background task process error",{id:t,error:String(c)}),this.handleExit(t,1)}),this.writeMeta(l).catch(()=>{}),we.info("Background task spawned",{id:t,command:e.command,cwd:i,pid:a.pid,agentId:e.context.agentId}),l}async handleExit(e,t){let s=this.tasks.get(e);!s||s.status!=="running"||(s.exitCode=t??1,s.status=s.exitCode===0?"completed":"failed",s.completedAt=new Date().toISOString(),await this.writeMeta(s),this.fireCompletion(s))}fireCompletion(e){let t=new Date(e.startedAt).getTime(),r=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-t)/1e3).toFixed(1);this.tailLog(e.logPath,ja).then(i=>{let o=e.status==="completed"?"completed":e.status==="failed"?"failed":"orphaned",a={id:`bg:${e.id}:done:${Date.now()}`,text:[`[Background task ${o}] Task \`${e.id}\` finished with exit code ${e.exitCode??"unknown"}.`,`Command: \`${e.command}\``,`Duration: ${r}s`,`Output (last ${ja} lines):`,"```",i||"(no output)","```"].join(`
373
- `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,bgTaskId:e.id}};we.info("Background task completed, dispatching notification",{id:e.id,status:e.status,exitCode:e.exitCode,durationSec:r,agentId:e.context.agentId}),this.onComplete(a)}).catch(i=>{we.error("Failed to fire completion notification",{id:e.id,error:String(i)})})}async taskStatus(e){let t=this.tasks.get(e);if(!t)return null;let s=await this.tailLog(t.logPath,ja);return{id:t.id,status:t.status,exitCode:t.exitCode,startedAt:t.startedAt,completedAt:t.completedAt,command:t.command,output:s}}async listTasks(e){let t=[];for(let s of this.tasks.values())e&&s.context.agentId!==e||t.push({id:s.id,status:s.status,exitCode:s.exitCode,startedAt:s.startedAt,completedAt:s.completedAt,command:s.command});return t}async writeMeta(e){try{await Gk(e.metaPath,JSON.stringify(e,null,2),"utf-8")}catch(t){we.error("Failed to write task metadata",{id:e.id,error:String(t)})}}async tailLog(e,t){try{return(await ef(e,"utf-8")).split(`
412
+ `)}};R();import{createServer as JM}from"node:http";import{spawn as HM}from"node:child_process";import{mkdir as YM,readFile as yI,writeFile as XM,readdir as QM,stat as eL,unlink as tL}from"node:fs/promises";import{openSync as nL,closeSync as rL}from"node:fs";import{randomUUID as iL}from"node:crypto";var Ve=$("bg-task-manager"),cy=100,oL=5e3,il=class{port;authToken;tasksDir;tasks=new Map;onComplete;server=null;orphanPollers=new Map;constructor(e,t,i,r){this.port=e,this.authToken=t,this.tasksDir=i,this.onComplete=r}async start(){await YM(this.tasksDir,{recursive:!0}),this.server=JM((e,t)=>{this.handleRequest(e,t).catch(i=>{Ve.error("HTTP handler error",{error:String(i)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),Ve.info("Background task manager started",{port:this.port})}async scanOrphans(){let e;try{e=await QM(this.tasksDir)}catch{return}let t=e.filter(o=>o.endsWith(".json")),i=0,r=0;for(let o of t)try{let s=await yI(`${this.tasksDir}/${o}`,"utf-8"),a=JSON.parse(s);this.tasks.set(a.id,a),a.status==="running"&&a.pid&&(this.isProcessAlive(a.pid)?(this.pollOrphan(a.id,a.pid),r++):(a.status="orphaned",a.completedAt=new Date().toISOString(),await this.writeMeta(a),this.fireCompletion(a),i++))}catch(s){Ve.warn("Failed to read orphan task file",{file:o,error:String(s)})}(i>0||r>0)&&Ve.info("Orphan scan complete",{orphaned:i,recovered:r,total:t.length})}async stop(){for(let[,t]of this.orphanPollers)clearInterval(t);this.orphanPollers.clear();let e=[...this.tasks.values()].filter(t=>t.status==="running"&&t.pid);if(e.length>0){Ve.info("Sending SIGTERM to running background tasks",{count:e.length});for(let t of e)this.killProcess(t.pid,"SIGTERM");await this.sleep(oL);for(let t of e)t.pid&&this.isProcessAlive(t.pid)&&(Ve.warn("Background task did not exit after SIGTERM, sending SIGKILL",{id:t.id,pid:t.pid}),this.killProcess(t.pid,"SIGKILL"))}this.server&&(this.server.close(),this.server=null),Ve.info("Background task manager stopped",{killed:e.length})}killProcess(e,t){try{process.kill(e,t)}catch(i){i.code!=="ESRCH"&&Ve.warn("Failed to send signal to process",{pid:e,signal:t,error:String(i)})}}sleep(e){return new Promise(t=>setTimeout(t,e))}async handleRequest(e,t){let i=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="POST"&&i.pathname==="/tasks"){let s=await this.readBody(e),a=JSON.parse(s),l=await this.spawnTask(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:l.id,status:"running"}));return}let o=i.pathname.match(/^\/tasks\/([a-f0-9-]+)$/);if(e.method==="GET"&&o){let s=o[1],a=await this.taskStatus(s);if(!a){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Task not found"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(a));return}if(e.method==="GET"&&i.pathname==="/tasks"){let s=i.searchParams.get("agentId")??void 0,a=await this.listTasks(s);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({tasks:a}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}async spawnTask(e){let t=iL(),i=`${this.tasksDir}/${t}.log`,r=`${this.tasksDir}/${t}.json`,o=e.cwd??process.env.HOME??"/tmp",s=nL(i,"a"),a=HM(e.command,e.args??[],{cwd:o,detached:!0,stdio:["ignore",s,s]});rL(s);let l={id:t,command:e.command+(e.args?.length?" "+e.args.join(" "):""),cwd:o,status:"running",exitCode:null,startedAt:new Date().toISOString(),completedAt:null,logPath:i,metaPath:r,context:e.context,pid:a.pid??null};return this.tasks.set(t,l),a.on("exit",c=>this.handleExit(t,c)),a.on("error",c=>{Ve.error("Background task process error",{id:t,error:String(c)}),this.handleExit(t,1)}),this.writeMeta(l).catch(()=>{}),Ve.info("Background task spawned",{id:t,command:e.command,cwd:o,pid:a.pid,agentId:e.context.agentId}),l}async handleExit(e,t){let i=this.tasks.get(e);!i||i.status!=="running"||(i.exitCode=t??1,i.status=i.exitCode===0?"completed":"failed",i.completedAt=new Date().toISOString(),await this.writeMeta(i),this.fireCompletion(i))}fireCompletion(e){let t=new Date(e.startedAt).getTime(),r=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-t)/1e3).toFixed(1);this.tailLog(e.logPath,cy).then(o=>{let s=e.status==="completed"?"completed":e.status==="failed"?"failed":"orphaned",a={id:`bg:${e.id}:done:${Date.now()}`,text:[`[Background task ${s}] Task \`${e.id}\` finished with exit code ${e.exitCode??"unknown"}.`,`Command: \`${e.command}\``,`Duration: ${r}s`,`Output (last ${cy} lines):`,"```",o||"(no output)","```"].join(`
413
+ `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,bgTaskId:e.id}};Ve.info("Background task completed, dispatching notification",{id:e.id,status:e.status,exitCode:e.exitCode,durationSec:r,agentId:e.context.agentId}),this.onComplete(a)}).catch(o=>{Ve.error("Failed to fire completion notification",{id:e.id,error:String(o)})})}async taskStatus(e){let t=this.tasks.get(e);if(!t)return null;let i=await this.tailLog(t.logPath,cy);return{id:t.id,status:t.status,exitCode:t.exitCode,startedAt:t.startedAt,completedAt:t.completedAt,command:t.command,output:i}}async listTasks(e){let t=[];for(let i of this.tasks.values())e&&i.context.agentId!==e||t.push({id:i.id,status:i.status,exitCode:i.exitCode,startedAt:i.startedAt,completedAt:i.completedAt,command:i.command});return t}async writeMeta(e){try{await XM(e.metaPath,JSON.stringify(e,null,2),"utf-8")}catch(t){Ve.error("Failed to write task metadata",{id:e.id,error:String(t)})}}async tailLog(e,t){try{return(await yI(e,"utf-8")).split(`
374
414
  `).slice(-t).join(`
375
- `).trim()}catch{return""}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}pollOrphan(e,t){let s=setInterval(()=>{if(!this.isProcessAlive(t)){clearInterval(s),this.orphanPollers.delete(e);let r=this.tasks.get(e);r&&r.status==="running"&&(r.status="orphaned",r.completedAt=new Date().toISOString(),this.writeMeta(r).then(()=>this.fireCompletion(r)))}},5e3);this.orphanPollers.set(e,s)}async sweep(e){let t=Date.now()-e,s=0,r=0,i=[];for(let[o,a]of this.tasks)if(!(a.status==="running"||!a.completedAt||new Date(a.completedAt).getTime()>t)){for(let c of[a.metaPath,a.logPath])try{let d=await Yk(c);r+=d.size,await Jk(c)}catch(d){d.code!=="ENOENT"&&i.push(`Failed to delete ${c}: ${String(d)}`)}this.tasks.delete(o),s++}return{component:"bg-task-manager",pruned:s,retried:0,bytesFreed:r,errors:i}}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();import{createServer as nb}from"node:http";import{spawn as rb}from"node:child_process";import{mkdir as ib,readFile as Yr,writeFile as ob,readdir as ab,stat as cb,unlink as lb,open as db}from"node:fs/promises";import{openSync as rf,closeSync as of}from"node:fs";import{randomUUID as ub}from"node:crypto";function tf(n){let e=n.trim();if(!e)return null;try{let t=JSON.parse(e);return t.type!=="result"?null:{sessionId:t.session_id??null,result:t.result??"",subtype:t.subtype??"unknown",costUsd:t.total_cost_usd??0,durationMs:t.duration_ms??0,numTurns:t.num_turns??0,isError:t.is_error===!0}}catch{return null}}var eb=/\*{0,2}Status:?\*{0,2}\s+(NEEDS_CONTEXT|BLOCKED)/i,tb=/\*{0,2}Question:?\*{0,2}\s+(.+?)(?:\n\n|\n\*{0,2}(?:Context|Status|Files|What)|$)/is,sb=/\*{0,2}Context:?\*{0,2}\s+(.+?)(?:\n\n\*{0,2}(?:Status|Question|Files|To respond)|$)/is;function sf(n){if(!n)return null;let e=eb.exec(n);if(!e)return null;let t=e[1].toUpperCase(),r=tb.exec(n)?.[1]?.trim()??"",o=sb.exec(n)?.[1]?.trim()??"";return{status:t,question:r,context:o}}function nf(n,e,t){return t||e?.subtype==="error_max_turns"||e?.subtype==="error_max_budget_usd"?"needs_input":n===0&&e?.subtype==="success"||n===0&&!e?"completed":"failed"}var ee=k("code-task-manager"),Qs=2e3,qa=100,af=5e3,Jr=class{port;authToken;pluginDirs;maxConcurrent;tasksDir;cliBin;options;tasks=new Map;onComplete;server=null;orphanPollers=new Map;reapTimers=new Set;constructor(e,t,s,r,i,o,a){this.port=e,this.authToken=t,this.pluginDirs=s,this.maxConcurrent=r,this.tasksDir=i,this.onComplete=o,this.options=a??{},this.cliBin=this.options.cliBin??"claude"}async start(){await ib(this.tasksDir,{recursive:!0}),this.server=nb((e,t)=>{this.handleRequest(e,t).catch(s=>{ee.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),ee.info("Code task manager started",{port:this.port})}async scanOrphans(){let e;try{e=await ab(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".meta.json")),s=0,r=0;for(let i of t)try{let o=await Yr(`${this.tasksDir}/${i}`,"utf-8"),a=JSON.parse(o);this.tasks.set(a.id,a),a.status==="running"&&a.pid&&(this.isProcessAlive(a.pid)?(this.pollOrphan(a.id,a.pid),r++):(a.status="orphaned",a.completedAt=new Date().toISOString(),await this.writeMeta(a),this.fireCompletion(a),s++))}catch(o){ee.warn("Failed to read orphan task file",{file:i,error:String(o)})}(s>0||r>0)&&ee.info("Orphan scan complete",{orphaned:s,recovered:r,total:t.length})}async stop(){for(let[,t]of this.orphanPollers)clearInterval(t);this.orphanPollers.clear();for(let t of this.reapTimers)clearTimeout(t);this.reapTimers.clear();let e=[...this.tasks.values()].filter(t=>t.status==="running"&&t.pid);if(e.length>0){ee.info("Sending SIGTERM to running code tasks",{count:e.length});for(let t of e)this.killProcess(t.pid,"SIGTERM");await this.sleep(af);for(let t of e)t.pid&&this.isProcessAlive(t.pid)&&(ee.warn("Code task did not exit after SIGTERM, sending SIGKILL",{id:t.id,pid:t.pid}),this.killProcess(t.pid,"SIGKILL"))}this.server&&(this.server.close(),this.server=null),ee.info("Code task manager stopped",{killed:e.length})}async reapStale(){let e=this.options.maxLifetimeMs??288e5,t=this.options.staleGraceMs??1800*1e3,s=Date.now(),r=0,i=0;for(let o of this.tasks.values()){if(o.status!=="running"||!o.pid)continue;let a=s-new Date(o.startedAt).getTime();if(a<e)continue;if(await this.isFileRecentlyModified(o.stderrPath,t)){ee.info("Stale code task spared \u2014 stderr still active",{id:o.id,pid:o.pid,ageHours:(a/36e5).toFixed(1)}),i++;continue}ee.warn("Reaping stale code task",{id:o.id,pid:o.pid,ageHours:(a/36e5).toFixed(1)}),this.killProcess(o.pid,"SIGTERM"),o.status="orphaned";let c=setTimeout(()=>{this.reapTimers.delete(c),o.pid&&this.isProcessAlive(o.pid)&&(ee.warn("Stale code task did not exit after SIGTERM, sending SIGKILL",{id:o.id,pid:o.pid}),this.killProcess(o.pid,"SIGKILL"))},af);this.reapTimers.add(c),r++}return(r>0||i>0)&&ee.info("Stale reap complete",{reaped:r,spared:i}),{reaped:r,spared:i}}async handleRequest(e,t){let s=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="POST"&&s.pathname==="/tasks"){let a;try{a=JSON.parse(await this.readBody(e))}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON body"}));return}try{let l=await this.spawnTask(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:l.id,status:"running"}))}catch(l){let c=String(l instanceof Error?l.message:l),d=c.includes("concurrency")?429:400;t.writeHead(d,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:c}))}return}let i=s.pathname.match(/^\/tasks\/([a-f0-9-]+)\/respond$/);if(e.method==="POST"&&i){let a=i[1],l;try{l=JSON.parse(await this.readBody(e))}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON body"}));return}try{let c=await this.resumeTask(a,l.response,l.context);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:c.id,status:"running",resumedFrom:a}))}catch(c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:String(c instanceof Error?c.message:c)}))}return}let o=s.pathname.match(/^\/tasks\/([a-f0-9-]+)$/);if(e.method==="GET"&&o){let a=o[1],l=await this.taskStatus(a);if(!l){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Task not found"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(l));return}if(e.method==="GET"&&s.pathname==="/tasks"){let a=s.searchParams.get("agentId")??void 0,l=this.listTasks(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({tasks:l}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}async spawnTask(e){if([...this.tasks.values()].filter(S=>S.status==="running").length>=this.maxConcurrent)throw new Error(`Max concurrency reached (${this.maxConcurrent} running). Wait for a task to finish or increase the limit.`);let s=ub(),r=`${this.tasksDir}/${s}.stdout.json`,i=`${this.tasksDir}/${s}.stderr.log`,o=`${this.tasksDir}/${s}.meta.json`,a=e.cwd,l=e.model??"",c=e.maxTurns??100,d=e.maxBudget??5,u=e.prompt;if(this.options?.prefetcher)try{let S=await this.options.prefetcher.getContext(e.prompt,e.context.agentId);S&&(u=S+`
415
+ `).trim()}catch{return""}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}pollOrphan(e,t){let i=setInterval(()=>{if(!this.isProcessAlive(t)){clearInterval(i),this.orphanPollers.delete(e);let r=this.tasks.get(e);r&&r.status==="running"&&(r.status="orphaned",r.completedAt=new Date().toISOString(),this.writeMeta(r).then(()=>this.fireCompletion(r)))}},5e3);this.orphanPollers.set(e,i)}async sweep(e){let t=Date.now()-e,i=0,r=0,o=[];for(let[s,a]of this.tasks)if(!(a.status==="running"||!a.completedAt||new Date(a.completedAt).getTime()>t)){for(let c of[a.metaPath,a.logPath])try{let u=await eL(c);r+=u.size,await tL(c)}catch(u){u.code!=="ENOENT"&&o.push(`Failed to delete ${c}: ${String(u)}`)}this.tasks.delete(s),i++}return{component:"bg-task-manager",pruned:i,retried:0,bytesFreed:r,errors:o}}readBody(e){return new Promise((t,i)=>{let r="";e.on("data",o=>{r+=o.toString()}),e.on("end",()=>t(r)),e.on("error",i)})}};R();import{createServer as lL}from"node:http";import{spawn as uL}from"node:child_process";import{mkdir as dL,readFile as ol,writeFile as fL,readdir as pL,stat as mL,unlink as hL,open as gL}from"node:fs/promises";import{openSync as bI,closeSync as kI}from"node:fs";import{randomUUID as yL}from"node:crypto";function vI(n){let e=n.trim();if(!e)return null;try{let t=JSON.parse(e);return t.type!=="result"?null:{sessionId:t.session_id??null,result:t.result??"",subtype:t.subtype??"unknown",costUsd:t.total_cost_usd??0,durationMs:t.duration_ms??0,numTurns:t.num_turns??0,isError:t.is_error===!0}}catch{return null}}var sL=/\*{0,2}Status:?\*{0,2}\s+(NEEDS_CONTEXT|BLOCKED)/i,aL=/\*{0,2}Question:?\*{0,2}\s+(.+?)(?:\n\n|\n\*{0,2}(?:Context|Status|Files|What)|$)/is,cL=/\*{0,2}Context:?\*{0,2}\s+(.+?)(?:\n\n\*{0,2}(?:Status|Question|Files|To respond)|$)/is;function _I(n){if(!n)return null;let e=sL.exec(n);if(!e)return null;let t=e[1].toUpperCase(),r=aL.exec(n)?.[1]?.trim()??"",s=cL.exec(n)?.[1]?.trim()??"";return{status:t,question:r,context:s}}function wI(n,e,t){return t||e?.subtype==="error_max_turns"||e?.subtype==="error_max_budget_usd"?"needs_input":n===0&&e?.subtype==="success"||n===0&&!e?"completed":"failed"}var ge=$("code-task-manager"),_o=2e3,ly=100,SI=5e3,sl=class{port;authToken;pluginDirs;maxConcurrent;tasksDir;cliBin;options;tasks=new Map;onComplete;server=null;orphanPollers=new Map;reapTimers=new Set;constructor(e,t,i,r,o,s,a){this.port=e,this.authToken=t,this.pluginDirs=i,this.maxConcurrent=r,this.tasksDir=o,this.onComplete=s,this.options=a??{},this.cliBin=this.options.cliBin??"claude"}async start(){await dL(this.tasksDir,{recursive:!0}),this.server=lL((e,t)=>{this.handleRequest(e,t).catch(i=>{ge.error("HTTP handler error",{error:String(i)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),ge.info("Code task manager started",{port:this.port})}async scanOrphans(){let e;try{e=await pL(this.tasksDir)}catch{return}let t=e.filter(o=>o.endsWith(".meta.json")),i=0,r=0;for(let o of t)try{let s=await ol(`${this.tasksDir}/${o}`,"utf-8"),a=JSON.parse(s);this.tasks.set(a.id,a),a.status==="running"&&a.pid&&(this.isProcessAlive(a.pid)?(this.pollOrphan(a.id,a.pid),r++):(a.status="orphaned",a.completedAt=new Date().toISOString(),await this.writeMeta(a),this.fireCompletion(a),i++))}catch(s){ge.warn("Failed to read orphan task file",{file:o,error:String(s)})}(i>0||r>0)&&ge.info("Orphan scan complete",{orphaned:i,recovered:r,total:t.length})}async stop(){for(let[,t]of this.orphanPollers)clearInterval(t);this.orphanPollers.clear();for(let t of this.reapTimers)clearTimeout(t);this.reapTimers.clear();let e=[...this.tasks.values()].filter(t=>t.status==="running"&&t.pid);if(e.length>0){ge.info("Sending SIGTERM to running code tasks",{count:e.length});for(let t of e)this.killProcess(t.pid,"SIGTERM");await this.sleep(SI);for(let t of e)t.pid&&this.isProcessAlive(t.pid)&&(ge.warn("Code task did not exit after SIGTERM, sending SIGKILL",{id:t.id,pid:t.pid}),this.killProcess(t.pid,"SIGKILL"))}this.server&&(this.server.close(),this.server=null),ge.info("Code task manager stopped",{killed:e.length})}async reapStale(){let e=this.options.maxLifetimeMs??288e5,t=this.options.staleGraceMs??1800*1e3,i=Date.now(),r=0,o=0;for(let s of this.tasks.values()){if(s.status!=="running"||!s.pid)continue;let a=i-new Date(s.startedAt).getTime();if(a<e)continue;if(await this.isFileRecentlyModified(s.stderrPath,t)){ge.info("Stale code task spared \u2014 stderr still active",{id:s.id,pid:s.pid,ageHours:(a/36e5).toFixed(1)}),o++;continue}ge.warn("Reaping stale code task",{id:s.id,pid:s.pid,ageHours:(a/36e5).toFixed(1)}),this.killProcess(s.pid,"SIGTERM"),s.status="orphaned";let c=setTimeout(()=>{this.reapTimers.delete(c),s.pid&&this.isProcessAlive(s.pid)&&(ge.warn("Stale code task did not exit after SIGTERM, sending SIGKILL",{id:s.id,pid:s.pid}),this.killProcess(s.pid,"SIGKILL"))},SI);this.reapTimers.add(c),r++}return(r>0||o>0)&&ge.info("Stale reap complete",{reaped:r,spared:o}),{reaped:r,spared:o}}async handleRequest(e,t){let i=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="POST"&&i.pathname==="/tasks"){let a;try{a=JSON.parse(await this.readBody(e))}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON body"}));return}try{let l=await this.spawnTask(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:l.id,status:"running"}))}catch(l){let c=String(l instanceof Error?l.message:l),u=c.includes("concurrency")?429:400;t.writeHead(u,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:c}))}return}let o=i.pathname.match(/^\/tasks\/([a-f0-9-]+)\/respond$/);if(e.method==="POST"&&o){let a=o[1],l;try{l=JSON.parse(await this.readBody(e))}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON body"}));return}try{let c=await this.resumeTask(a,l.response,l.context);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:c.id,status:"running",resumedFrom:a}))}catch(c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:String(c instanceof Error?c.message:c)}))}return}let s=i.pathname.match(/^\/tasks\/([a-f0-9-]+)$/);if(e.method==="GET"&&s){let a=s[1],l=await this.taskStatus(a);if(!l){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Task not found"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(l));return}if(e.method==="GET"&&i.pathname==="/tasks"){let a=i.searchParams.get("agentId")??void 0,l=this.listTasks(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({tasks:l}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}async spawnTask(e){if([...this.tasks.values()].filter(b=>b.status==="running").length>=this.maxConcurrent)throw new Error(`Max concurrency reached (${this.maxConcurrent} running). Wait for a task to finish or increase the limit.`);let i=yL(),r=`${this.tasksDir}/${i}.stdout.json`,o=`${this.tasksDir}/${i}.stderr.log`,s=`${this.tasksDir}/${i}.meta.json`,a=e.cwd,l=e.model??"",c=e.maxTurns??100,u=e.maxBudget??5,d=e.prompt;if(this.options?.prefetcher)try{let b=await this.options.prefetcher.getContext(e.prompt,e.context.agentId);b&&(d=b+`
376
416
 
377
417
  ---
378
418
 
379
- `+e.prompt)}catch(S){ee.warn(`Prefetch failed for task, proceeding without context: ${S}`)}let h=e.sessionId?u:u+`
419
+ `+e.prompt)}catch(b){ge.warn(`Prefetch failed for task, proceeding without context: ${b}`)}let f=e.sessionId?d:d+`
380
420
 
381
421
  ---
382
- IMPORTANT: After completing implementation, you MUST run /quality-gate before reporting done. This includes test creation, lint, typecheck, and build verification. Do not claim completion without quality-gate passing.`,p=this.buildArgs({prompt:h,maxTurns:c,maxBudget:d,model:l,sessionId:e.sessionId}),m=rf(r,"w"),f=rf(i,"w"),y=rb(this.cliBin,p,{cwd:a,detached:!0,stdio:["ignore",m,f],env:process.env});y.on("exit",S=>this.handleExit(s,S)),y.on("error",S=>{ee.error("Code task process error",{id:s,error:String(S)}),this.handleExit(s,1)}),of(m),of(f);let w={id:s,prompt:e.prompt.slice(0,500),cwd:a,model:l,maxTurns:c,maxBudget:d,status:"running",exitCode:null,startedAt:new Date().toISOString(),completedAt:null,stdoutPath:r,stderrPath:i,metaPath:o,context:e.context,pid:y.pid??null,sessionId:e.sessionId??null,costUsd:0,numTurns:0,escalation:null,parentTaskId:e.parentTaskId??null};return this.tasks.set(s,w),await this.writeMeta(w),ee.info("Code task spawned",{id:s,cwd:a,model:l||"(default)",maxTurns:c,maxBudget:d,pid:y.pid,agentId:e.context.agentId,parentTaskId:e.parentTaskId??null}),w}buildArgs(e){let t=[];e.sessionId?t.push("--resume",e.sessionId,"-p",e.prompt):t.push("-p",e.prompt);for(let s of this.pluginDirs)t.push("--plugin-dir",s);return t.push("--output-format","json","--dangerously-skip-permissions"),t.push("--max-turns",String(e.maxTurns)),t.push("--max-budget-usd",String(e.maxBudget)),e.model&&t.push("--model",e.model),t}async resumeTask(e,t,s){let r=this.tasks.get(e);if(!r)throw new Error(`Task ${e} not found`);if(r.status!=="needs_input")throw new Error(`Task ${e} is ${r.status}, not needs_input`);if(!r.sessionId)throw new Error(`Task ${e} has no session ID for resume`);return r.status="running",this.spawnTask({prompt:t,cwd:r.cwd,model:r.model,maxTurns:r.maxTurns,maxBudget:r.maxBudget,sessionId:r.sessionId,context:s??r.context,parentTaskId:e})}async handleExit(e,t){let s=this.tasks.get(e);if(!s||s.status!=="running")return;s.exitCode=t??1,s.completedAt=new Date().toISOString();let r=null;try{let o=await Yr(s.stdoutPath,"utf-8");r=tf(o)}catch{}r&&(s.sessionId=r.sessionId,s.costUsd=r.costUsd,s.numTurns=r.numTurns);let i=r?sf(r.result):null;s.escalation=i,s.status=nf(s.exitCode,r,i),await this.writeMeta(s),this.fireCompletion(s,r)}fireCompletion(e,t){let s=new Date(e.startedAt).getTime(),i=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-s)/1e3).toFixed(1);(async()=>{if(e.status==="needs_input"&&e.escalation){let c=[`[Code task needs input] Task \`${e.id}\` is waiting for a decision.`,""];return e.escalation.status==="BLOCKED"?c.push(`**BLOCKED**: ${e.escalation.question||"No details provided."}`):c.push(`**Needs context**: ${e.escalation.question||"No details provided."}`),e.escalation.context&&c.push("",`Context: ${e.escalation.context}`),c.push("",`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",`To respond: \`code_respond({ id: "${e.id}", response: "your answer" })\``),c.join(`
383
- `)}if(e.status==="needs_input"&&t?.subtype){let c=t.subtype==="error_max_turns"?`Hit max turns limit (${e.maxTurns})`:`Hit budget limit ($${e.maxBudget})`;return[`[Code task limit reached] Task \`${e.id}\` \u2014 ${c}.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"","The session can be resumed with additional budget/turns via `code_respond`.","",`Result (last ${Qs} chars):`,"```",(t.result||"(no output)").slice(-Qs),"```"].join(`
384
- `)}if(e.status==="completed"){let c=t?.result||"(no output)";return[`[Code task completed] Task \`${e.id}\` finished successfully.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",`Result (last ${Qs} chars):`,"```",c.slice(-Qs),"```"].join(`
385
- `)}let a="";try{a=(await Yr(e.stderrPath,"utf-8")).split(`
386
- `).slice(-qa).join(`
387
- `).trim()}catch{a="(no stderr output)"}let l=t?.result?t.result.slice(-Qs):"";return[`[Code task ${e.status}] Task \`${e.id}\` exited with code ${e.exitCode??"unknown"}.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",l?`Result:
422
+ IMPORTANT: After completing implementation, you MUST run /quality-gate before reporting done. This includes test creation, lint, typecheck, and build verification. Do not claim completion without quality-gate passing.`,p=this.buildArgs({prompt:f,maxTurns:c,maxBudget:u,model:l,sessionId:e.sessionId}),h=bI(r,"w"),m=bI(o,"w"),y=uL(this.cliBin,p,{cwd:a,detached:!0,stdio:["ignore",h,m],env:process.env});y.on("exit",b=>this.handleExit(i,b)),y.on("error",b=>{ge.error("Code task process error",{id:i,error:String(b)}),this.handleExit(i,1)}),kI(h),kI(m);let _={id:i,prompt:e.prompt.slice(0,500),cwd:a,model:l,maxTurns:c,maxBudget:u,status:"running",exitCode:null,startedAt:new Date().toISOString(),completedAt:null,stdoutPath:r,stderrPath:o,metaPath:s,context:e.context,pid:y.pid??null,sessionId:e.sessionId??null,costUsd:0,numTurns:0,escalation:null,parentTaskId:e.parentTaskId??null};return this.tasks.set(i,_),await this.writeMeta(_),ge.info("Code task spawned",{id:i,cwd:a,model:l||"(default)",maxTurns:c,maxBudget:u,pid:y.pid,agentId:e.context.agentId,parentTaskId:e.parentTaskId??null}),_}buildArgs(e){let t=[];e.sessionId?t.push("--resume",e.sessionId,"-p",e.prompt):t.push("-p",e.prompt);for(let i of this.pluginDirs)t.push("--plugin-dir",i);return t.push("--output-format","json","--dangerously-skip-permissions"),t.push("--max-turns",String(e.maxTurns)),t.push("--max-budget-usd",String(e.maxBudget)),e.model&&t.push("--model",e.model),t}async resumeTask(e,t,i){let r=this.tasks.get(e);if(!r)throw new Error(`Task ${e} not found`);if(r.status!=="needs_input")throw new Error(`Task ${e} is ${r.status}, not needs_input`);if(!r.sessionId)throw new Error(`Task ${e} has no session ID for resume`);return r.status="running",this.spawnTask({prompt:t,cwd:r.cwd,model:r.model,maxTurns:r.maxTurns,maxBudget:r.maxBudget,sessionId:r.sessionId,context:i??r.context,parentTaskId:e})}async handleExit(e,t){let i=this.tasks.get(e);if(!i||i.status!=="running")return;i.exitCode=t??1,i.completedAt=new Date().toISOString();let r=null;try{let s=await ol(i.stdoutPath,"utf-8");r=vI(s)}catch{}r&&(i.sessionId=r.sessionId,i.costUsd=r.costUsd,i.numTurns=r.numTurns);let o=r?_I(r.result):null;i.escalation=o,i.status=wI(i.exitCode,r,o),await this.writeMeta(i),this.fireCompletion(i,r)}fireCompletion(e,t){let i=new Date(e.startedAt).getTime(),o=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-i)/1e3).toFixed(1);(async()=>{if(e.status==="needs_input"&&e.escalation){let c=[`[Code task needs input] Task \`${e.id}\` is waiting for a decision.`,""];return e.escalation.status==="BLOCKED"?c.push(`**BLOCKED**: ${e.escalation.question||"No details provided."}`):c.push(`**Needs context**: ${e.escalation.question||"No details provided."}`),e.escalation.context&&c.push("",`Context: ${e.escalation.context}`),c.push("",`Duration: ${o}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",`To respond: \`code_respond({ id: "${e.id}", response: "your answer" })\``),c.join(`
423
+ `)}if(e.status==="needs_input"&&t?.subtype){let c=t.subtype==="error_max_turns"?`Hit max turns limit (${e.maxTurns})`:`Hit budget limit ($${e.maxBudget})`;return[`[Code task limit reached] Task \`${e.id}\` \u2014 ${c}.`,`Duration: ${o}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"","The session can be resumed with additional budget/turns via `code_respond`.","",`Result (last ${_o} chars):`,"```",(t.result||"(no output)").slice(-_o),"```"].join(`
424
+ `)}if(e.status==="completed"){let c=t?.result||"(no output)";return[`[Code task completed] Task \`${e.id}\` finished successfully.`,`Duration: ${o}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",`Result (last ${_o} chars):`,"```",c.slice(-_o),"```"].join(`
425
+ `)}let a="";try{a=(await ol(e.stderrPath,"utf-8")).split(`
426
+ `).slice(-ly).join(`
427
+ `).trim()}catch{a="(no stderr output)"}let l=t?.result?t.result.slice(-_o):"";return[`[Code task ${e.status}] Task \`${e.id}\` exited with code ${e.exitCode??"unknown"}.`,`Duration: ${o}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",l?`Result:
388
428
  \`\`\`
389
429
  ${l}
390
430
  \`\`\`
391
- `:"",`Stderr (last ${qa} lines):`,"```",a||"(empty)","```"].filter(Boolean).join(`
392
- `)})().then(a=>{let l={id:`ct:${e.id}:done:${Date.now()}`,text:a,source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,codeTaskId:e.id}};ee.info("Code task completed, dispatching notification",{id:e.id,status:e.status,exitCode:e.exitCode,costUsd:e.costUsd,numTurns:e.numTurns,durationSec:i,agentId:e.context.agentId,hasEscalation:!!e.escalation}),this.onComplete(l),this.options?.knowledgeExtractor&&e.status==="completed"&&t&&this.options.knowledgeExtractor.extract(e.context.agentId,t).then(c=>{c>0&&ee.info(`Extracted ${c} code insights from task ${e.id}`)}).catch(c=>{ee.warn(`Knowledge extraction failed for task ${e.id}: ${c}`)})}).catch(a=>{ee.error("Failed to fire completion notification",{id:e.id,error:String(a)})})}async taskStatus(e){let t=this.tasks.get(e);if(!t)return null;let s="";try{s=(await Yr(t.stderrPath,"utf-8")).split(`
393
- `).slice(-qa).join(`
394
- `).trim()}catch{}return{id:t.id,status:t.status,exitCode:t.exitCode,startedAt:t.startedAt,completedAt:t.completedAt,cwd:t.cwd,model:t.model,costUsd:t.costUsd,numTurns:t.numTurns,sessionId:t.sessionId,escalation:t.escalation,parentTaskId:t.parentTaskId,stderrTail:s}}listTasks(e){let t=[];for(let s of this.tasks.values())e&&s.context.agentId!==e||t.push({id:s.id,status:s.status,exitCode:s.exitCode,startedAt:s.startedAt,completedAt:s.completedAt,costUsd:s.costUsd,numTurns:s.numTurns,cwd:s.cwd,prompt:s.prompt});return t}async sweep(e){let t=Date.now()-e,s=0,r=0,i=[];for(let[o,a]of this.tasks)if(!(a.status==="running"||!a.completedAt||new Date(a.completedAt).getTime()>t)){for(let c of[a.metaPath,a.stdoutPath,a.stderrPath])try{let d=await cb(c);r+=d.size,await lb(c)}catch(d){d.code!=="ENOENT"&&i.push(`Failed to delete ${c}: ${String(d)}`)}this.tasks.delete(o),s++}return{component:"code-task-manager",pruned:s,retried:0,bytesFreed:r,errors:i}}async writeMeta(e){try{await ob(e.metaPath,JSON.stringify(e,null,2),"utf-8")}catch(t){ee.error("Failed to write task metadata",{id:e.id,error:String(t)})}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}pollOrphan(e,t){let s=setInterval(()=>{if(!this.isProcessAlive(t)){clearInterval(s),this.orphanPollers.delete(e);let r=this.tasks.get(e);r&&r.status==="running"&&(r.status="orphaned",r.completedAt=new Date().toISOString(),this.writeMeta(r).then(()=>this.fireCompletion(r)))}},5e3);this.orphanPollers.set(e,s)}killProcess(e,t){try{process.kill(e,t)}catch(s){s.code!=="ESRCH"&&ee.warn("Failed to send signal to process",{pid:e,signal:t,error:String(s)})}}async isFileRecentlyModified(e,t){try{let s=await db(e,"r"),r=await s.stat();return await s.close(),Date.now()-r.mtimeMs<t}catch{return!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();import{createServer as hb}from"node:http";import{randomUUID as fb}from"node:crypto";var re=k("meeting-monitor"),pb=1e4,mb=15e3,gb=2,yb=new Set(["done","fatal","call_ended","media_expired","recording_permission_denied"]),zr=class{port;webhookSecret;onUpdate;server=null;sessions=new Map;sessionsByBotId=new Map;constructor(e,t,s){this.port=e,this.webhookSecret=t,this.onUpdate=s}async start(){this.server=hb((e,t)=>{this.handleRequest(e,t).catch(s=>{re.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),re.info("Meeting monitor started",{port:this.port}),this.webhookSecret||re.error("Webhook verification disabled \u2014 RECALL_WEBHOOK_SECRET not set. All webhook requests will be rejected.")}stop(){for(let e of this.sessions.values())e.pollTimer&&(clearInterval(e.pollTimer),e.pollTimer=null);this.server&&(this.server.close(),this.server=null),re.info("Meeting monitor stopped")}async handleRequest(e,t){let s=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.method==="POST"&&s.pathname==="/meetings/start"){let i=await this.readBody(e),o=JSON.parse(i),a=this.createSession(o);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({sessionId:a.id}));return}let r=s.pathname.match(/^\/meetings\/([a-f0-9-]+)\/stop$/);if(e.method==="POST"&&r){let i=r[1],o=this.sessions.get(i);if(!o){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Session not found"}));return}o.pollTimer&&(clearInterval(o.pollTimer),o.pollTimer=null),o.status="ended",o.endedAt=Date.now(),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"stopped"}));return}if(e.method==="POST"&&s.pathname.startsWith("/webhook/transcript")){if(!this.webhookSecret){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Webhook verification not configured"}));return}if(s.pathname!==`/webhook/transcript/${this.webhookSecret}`){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}));return}let i=await this.readBody(e);this.handleTranscriptWebhook(i),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}if(e.method==="GET"&&s.pathname==="/meetings"){let i=[];for(let o of this.sessions.values())i.push({id:o.id,botId:o.botId,botName:o.botName,meetingUrl:o.meetingUrl,status:o.status,pollCount:o.pollCount,lastSegmentIndex:o.lastSegmentIndex,pendingSegments:o.pendingSegments.length});t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(i));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}handleTranscriptWebhook(e){try{let t=JSON.parse(e),s=t.event,r=t.data?.bot?.id;if(!r){re.warn("Webhook missing bot ID",{event:s});return}let i=this.sessionsByBotId.get(r);if(!i){re.warn("Webhook for unknown bot",{botId:r,event:s});return}let o=this.sessions.get(i);if(!o||o.status!=="monitoring")return;let a=t.data?.data;if(!a)return;let l=a.participant?.id??0,c=a.participant?.name??"Unknown",d=Array.isArray(a.words)?a.words.map(u=>u.text).join(" "):"";if(!d)return;o.idlePollCount=0,s==="transcript.partial_data"?o.activePartials.set(l,{speaker:c,text:d}):s==="transcript.data"&&(o.pendingSegments.push({speaker:c,text:d}),o.activePartials.delete(l),o.lastSegmentIndex++),re.debug("Webhook transcript",{sessionId:i,botId:r,event:s,speaker:c,wordCount:d.split(" ").length})}catch(t){re.error("Webhook parse error",{error:String(t)})}}createSession(e){let t=fb(),s={id:t,botId:e.botId,botName:e.botName,meetingUrl:e.meetingUrl,apiKey:e.apiKey,region:e.region,context:e.context,lastSegmentIndex:0,pendingSegments:[],activePartials:new Map,lastDispatchTime:Date.now(),idlePollCount:0,pollTimer:null,pollCount:0,status:"monitoring",endedAt:null};return this.sessions.set(t,s),this.sessionsByBotId.set(e.botId,t),s.pollTimer=setInterval(()=>{this.pollSession(t).catch(r=>{re.error("Poll session error",{sessionId:t,botId:s.botId,error:String(r)})})},pb),re.info("Meeting session created",{sessionId:t,botId:e.botId,botName:e.botName,meetingUrl:e.meetingUrl,agentId:e.context.agentId}),s}async pollSession(e){let t=this.sessions.get(e);if(!t||t.status!=="monitoring")return;t.pollCount++;let s=t.pendingSegments.length>0||t.activePartials.size>0;(Date.now()-t.lastDispatchTime>=mb&&s||t.idlePollCount>=gb&&s)&&this.dispatchBatch(t),t.pollCount%3===0&&await this.checkBotStatus(t)}async checkBotStatus(e){try{let t=`https://${e.region}.recall.ai/api/v1/bot/${e.botId}/`,s=await fetch(t,{headers:{Authorization:`Token ${e.apiKey}`},signal:AbortSignal.timeout(15e3)});if(!s.ok){re.warn("Bot status check failed",{sessionId:e.id,botId:e.botId,status:s.status});return}let r=await s.json(),i=r.status_changes;if(Array.isArray(i)&&i.length>0){let o=i[i.length-1].code;if(yb.has(o)){re.info("Meeting reached terminal status",{sessionId:e.id,botId:e.botId,statusCode:o});let a=await this.fetchFullTranscript(e,r);this.dispatchEnd(e,a);return}}}catch(t){re.error("Bot status check error",{sessionId:e.id,botId:e.botId,error:String(t)})}}async fetchFullTranscript(e,t){let i=(Array.isArray(t.recordings)?t.recordings:[])[0]?.media_shortcuts?.transcript?.data?.download_url;if(!i)return re.warn("No transcript download URL available",{sessionId:e.id,botId:e.botId}),[...e.pendingSegments];try{let o=await fetch(i,{signal:AbortSignal.timeout(3e4)});if(!o.ok)return re.warn("Transcript download failed",{sessionId:e.id,status:o.status}),[...e.pendingSegments];let a=await o.json();return(Array.isArray(a)?a:Array.isArray(a.results)?a.results:[]).map(c=>({speaker:c.speaker??c.participant?.name??"Unknown",text:Array.isArray(c.words)?c.words.map(d=>d.text).join(" "):typeof c.text=="string"?c.text:""}))}catch(o){return re.error("Transcript download error",{sessionId:e.id,error:String(o)}),[...e.pendingSegments]}}dispatchBatch(e){let t=e.pendingSegments.splice(0,e.pendingSegments.length);for(let r of e.activePartials.values())t.push({speaker:r.speaker,text:`${r.text} [still speaking...]`});if(e.activePartials.clear(),e.lastDispatchTime=Date.now(),t.length===0)return;let s={id:`meeting:${e.botId}:${Date.now()}`,text:[`[Meeting transcript update \u2014 ${e.botName}]`,`Bot ID: ${e.botId}`,"","New transcript:",...t.map(r=>`[${r.speaker}]: ${r.text}`),"","---",`You are participating in this meeting. Use recall_send_chat with bot_id "${e.botId}" if you have relevant input. Otherwise respond "No response needed."`].join(`
395
- `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,meetingBotId:e.botId}};re.info("Dispatching transcript batch",{sessionId:e.id,botId:e.botId,segmentCount:t.length}),this.onUpdate(s)}dispatchEnd(e,t){let s={id:`meeting:${e.botId}:${Date.now()}`,text:[`[Meeting ended \u2014 ${e.botName}]`,`Bot ID: ${e.botId}`,"","Full transcript:",...t.map(r=>`[${r.speaker}]: ${r.text}`),"","---","Meeting has ended. Produce a summary: key decisions made, action items with owners, and open questions."].join(`
396
- `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,meetingBotId:e.botId}};re.info("Dispatching meeting end",{sessionId:e.id,botId:e.botId,totalSegments:t.length}),this.onUpdate(s),e.pollTimer&&(clearInterval(e.pollTimer),e.pollTimer=null),e.status="ended",e.endedAt=Date.now()}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.sessions)i.endedAt!==null&&(i.endedAt>t||(i.pollTimer&&(clearInterval(i.pollTimer),i.pollTimer=null),this.sessionsByBotId.delete(i.botId),this.sessions.delete(r),s++));return{component:"meeting-monitor",pruned:s,retried:0,bytesFreed:0,errors:[]}}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();var Qr=k("retry-queue"),Xr=class{entries=[];config;constructor(e){this.config=e}enqueue(e,t){this.entries.push({result:e,adapter:t,attempts:0,nextRetryAt:Date.now()+this.config.baseDelayMs,createdAt:Date.now()}),Qr.info("Delivery queued for retry",{agentId:e.agentId,adapterId:t.id,queueSize:this.entries.length})}async processRetries(){let e=Date.now(),t={pending:0,retried:0,dropped:0,errors:[]},s=[];for(let r of this.entries){if(r.nextRetryAt>e){s.push(r),t.pending++;continue}r.attempts++;try{await r.adapter.deliver(r.result),t.retried++,Qr.info("Retry delivery succeeded",{agentId:r.result.agentId,adapterId:r.adapter.id,attempt:r.attempts})}catch(i){if(r.attempts>=this.config.maxAttempts){t.dropped++;let o=`Dropped after ${r.attempts} attempts: ${String(i)}`;t.errors.push(o),Qr.error("Retry delivery exhausted",{agentId:r.result.agentId,adapterId:r.adapter.id,attempts:r.attempts,error:String(i)})}else r.nextRetryAt=e+this.config.baseDelayMs*Math.pow(2,r.attempts),s.push(r),t.pending++,Qr.warn("Retry delivery failed, will retry",{agentId:r.result.agentId,adapterId:r.adapter.id,attempt:r.attempts,nextRetryAt:new Date(r.nextRetryAt).toISOString(),error:String(i)})}}return this.entries=s,t}get size(){return this.entries.length}};M();var Ge=k("sweeper"),Zr=class n{config;targets;taskClient;taskId;timer=null;sweepCount=0;gatewayCycleCounter=0;memoryCycleCounter=0;memorySweepEvery;lastDreamAt=0;static GATEWAY_SWEEP_EVERY=12;constructor(e,t,s){this.config=e,this.targets=t,this.taskClient=s;let r=e.memorySweepIntervalHours??6;this.memorySweepEvery=Math.round(r*36e5/e.intervalMs)}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>{Ge.error("Sweep cycle failed",{error:String(e)})})},this.config.intervalMs),Ge.info("Sweeper started",{intervalMs:this.config.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),Ge.info("Sweeper stopped")}async sweep(){let e=Date.now();this.sweepCount++,this.gatewayCycleCounter++;let t=[];try{t.push(this.targets.dispatcher.sweep(this.config.threadTtlMs))}catch(d){t.push({component:"dispatcher",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}for(let d of this.targets.slackAdapters)try{t.push(d.sweep(this.config.threadTtlMs))}catch(u){t.push({component:`slack-adapter:${d.id}`,pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}if(this.targets.taskLedger)try{t.push(this.targets.taskLedger.sweep(this.config.threadTtlMs))}catch(d){t.push({component:"task-ledger",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}try{t.push(await this.targets.bgTaskManager.sweep(this.config.taskFileTtlMs))}catch(d){t.push({component:"bg-task-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.codeTaskManager){try{t.push(await this.targets.codeTaskManager.sweep(this.config.taskFileTtlMs))}catch(d){t.push({component:"code-task-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}try{let{reaped:d,spared:u}=await this.targets.codeTaskManager.reapStale();(d>0||u>0)&&t.push({component:"code-task-reaper",pruned:d,retried:0,bytesFreed:0,errors:u>0?[`${u} task(s) spared \u2014 still active past TTL`]:[]})}catch(d){t.push({component:"code-task-reaper",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}}if(this.targets.meetingMonitor)try{t.push(this.targets.meetingMonitor.sweep(this.config.meetingSessionTtlMs))}catch(d){t.push({component:"meeting-monitor",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.gatewayCycleCounter>=n.GATEWAY_SWEEP_EVERY){this.gatewayCycleCounter=0;for(let d of this.targets.slackGateways)try{t.push(d.sweep())}catch(u){t.push({component:"slack-gateway",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}}try{t.push(this.targets.agentManager.sweep())}catch(d){t.push({component:"agent-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.retryQueue)try{let d=await this.targets.retryQueue.processRetries();t.push({component:"retry-queue",pruned:d.dropped,retried:d.retried,bytesFreed:0,errors:d.errors})}catch(d){t.push({component:"retry-queue",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.memoryLifecycle&&(this.memoryCycleCounter++,this.memoryCycleCounter>=this.memorySweepEvery)){this.memoryCycleCounter=0;try{t.push(await this.targets.memoryLifecycle.sweep())}catch(d){t.push({component:"memory-lifecycle",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}}if(this.targets.memoryLifecycle&&this.config.dreamConfig?.enabled){let d=this.config.dreamConfig,u=d.cooldownMinutes*60*1e3,h=Date.now(),p=h-this.lastDreamAt>u,m=this.memoryCycleCounter===0,f=!1;if(p&&!m){let y=d.idleThresholdMinutes*60*1e3,w=this.targets.agentManager.getAllStates();f=w.length>0&&w.every(S=>S.status==="idle"&&h-S.lastActivity.getTime()>y)}if(p&&(m||f)){let y=m?"post-sweep":"idle";Ge.info("autoDream triggered",{trigger:y});try{let w=await this.targets.memoryLifecycle.dream();this.lastDreamAt=Date.now(),(w.merged+w.contradictions+w.promoted>0||w.errors.length>0)&&t.push({component:"autodream",pruned:w.merged+w.contradictions,retried:w.promoted,bytesFreed:0,errors:w.errors})}catch(w){t.push({component:"autodream",pruned:0,retried:0,bytesFreed:0,errors:[String(w)]})}}}let s=Date.now()-e,r=t.reduce((d,u)=>d+u.pruned,0),i=t.reduce((d,u)=>d+u.retried,0),o=t.reduce((d,u)=>d+u.bytesFreed,0),a=t.flatMap(d=>d.errors),l=r===0&&i===0&&o===0&&a.length===0;return(l?Ge.debug.bind(Ge):Ge.info.bind(Ge))("Sweep cycle complete",{cycle:this.sweepCount,durationMs:s,pruned:r,retried:i,bytesFreed:o,errors:a.length,components:t.map(d=>`${d.component}:${d.pruned}p/${d.retried}r`).join(" ")}),this.taskClient?.isConfigured&&!l&&await this.reportToTaskLedger(s,r,i,o,a),t}async reportToTaskLedger(e,t,s,r,i){try{if(!this.taskId){let a=await this.taskClient.createTask({name:"[Sweeper] Periodic maintenance",type:"AGENT",description:"Long-running system health task. Each comment is a sweep cycle report."});a&&(this.taskId=a._id)}if(!this.taskId)return;let o=[`**Sweep #${this.sweepCount}** (${e}ms)`,`Pruned: ${t} | Retried: ${s} | Freed: ${this.formatBytes(r)}`,i.length>0?`Errors: ${i.join(", ")}`:null].filter(Boolean).join(`
397
- `);await this.taskClient.addComment(this.taskId,o),i.length>0&&await this.taskClient.updateTask(this.taskId,{state:"NEEDS_ATTENTION"})}catch(o){Ge.warn("Failed to report to task ledger",{error:String(o)})}}formatBytes(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,s)).toFixed(1)} ${t[s]}`}};M();import{readdirSync as lf,readFileSync as wb,rmSync as Sb,statSync as kb,existsSync as ei}from"node:fs";import{resolve as Fa,join as df,sep as cf}from"node:path";var Xs=k("retention"),ti=class{config;deps;timer=null;constructor(e,t){this.config=e,this.deps=t}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>Xs.error("Retention sweep failed",{error:String(e)}))},this.config.intervalMs),Xs.info("Retention sweeper started",{intervalMs:this.config.intervalMs,enabled:this.config.enabled,rules:Object.keys(this.config.paths).length}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),Xs.info("Retention sweeper stopped")}async sweep(){let e=new Date,t=[],s=[],r=[];for(let[o,a]of Object.entries(this.config.paths))if(a.days!==0)for(let l of bb(this.deps.hiveHome,o))try{_b(l,o,a.days,e,t)}catch(c){r.push({path:l,error:String(c)})}if(this.config.enabled)for(let o of t)try{Sb(o.path,{recursive:!0,force:!0}),s.push(o)}catch(a){r.push({path:o.path,error:String(a)})}let i={sweptAt:e,dryRun:!this.config.enabled,candidates:t,deleted:s,errors:r};try{await this.deps.report(Tb(i))}catch(o){Xs.warn("Retention report delivery failed",{error:String(o)})}return i}};function bb(n,e){let t=e.split("/"),s=t.indexOf("*");if(s===-1){let a=Fa(n,e);return ei(a)?[a]:[]}if(t.indexOf("*",s+1)!==-1)throw new Error(`Retention rules support at most one '*' segment: ${e}`);let r=t.slice(0,s).join(cf),i=t.slice(s+1).join(cf),o=Fa(n,r);return ei(o)?lf(o,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>Fa(o,a.name,i)).filter(a=>ei(a)):[]}function _b(n,e,t,s,r){let i=vb(n)??t;if(i===0)return;let o=s.getTime()-i*864e5,a=lf(n,{withFileTypes:!0});for(let l of a){if(l.name===".retention-days")continue;let c=df(n,l.name),d;try{d=kb(c)}catch{continue}d.mtimeMs<=o&&r.push({path:c,rule:e,days:i,mtime:d.mtime,ageDays:(s.getTime()-d.mtimeMs)/864e5})}}function vb(n){let e=df(n,".retention-days");if(!ei(e))return null;let t=wb(e,"utf-8").trim(),s=Number(t);return!Number.isFinite(s)||s<0||!Number.isInteger(s)?(Xs.warn("Invalid .retention-days override \u2014 ignoring",{path:e,raw:t}),null):s}function Tb(n){let e=n.dryRun?"would delete":"deleted",t=[`*Retention sweep* (${n.dryRun?"dry-run":"enforced"}) @ ${n.sweptAt.toISOString()}`,`${n.candidates.length} candidates \xB7 ${e} ${n.dryRun?n.candidates.length:n.deleted.length} \xB7 ${n.errors.length} errors`],s=n.candidates.slice(0,10);if(s.length){t.push("```");for(let r of s)t.push(`${r.path} (age ${r.ageDays.toFixed(1)}d, rule ${r.rule}@${r.days}d)`);n.candidates.length>s.length&&t.push(`\u2026 and ${n.candidates.length-s.length} more`),t.push("```")}return n.errors.length&&t.push(`Errors: ${n.errors.slice(0,3).map(r=>`${r.path}: ${r.error}`).join(" | ")}`),t.join(`
398
- `)}Vs();M();var Ib=k("memory-store"),si=class{db;collection;constructor(e){this.db=e}async init(){this.collection=this.db.collection("agent_memory"),await this.collection.createIndex({agentId:1,tier:1}),await this.collection.createIndex({agentId:1,topic:1}),await this.collection.createIndex({agentId:1,updatedAt:1}),await this.collection.createIndex({agentId:1,type:1}),await this.collection.createIndex({agentId:1,purged:1,purgedAt:1}),Ib.info("Memory store initialized",{db:this.db.databaseName})}getCollection(){return this.collection}async save(e,t,s,r,i){let o=new Date,a={agentId:e,content:t.content,type:t.type,topic:t.topic,importance:t.importance,tier:"hot",createdAt:o,updatedAt:o,lastAccessedAt:o,accessCount:0,sourceChannel:r,sourceThread:i,pinned:!1,summarized:!1,qdrantPointId:s},l=await this.collection.insertOne(a);return a._id=l.insertedId,a}async getById(e){return this.collection.findOne({_id:e,purged:{$ne:!0}})}async update(e,t,s,r){let i={content:t,updatedAt:new Date};return s&&(i.importance=s),r&&(i.qdrantPointId=r),await this.collection.findOneAndUpdate({_id:e},{$set:i},{returnDocument:"after"})}async pin(e){return(await this.collection.updateOne({_id:e},{$set:{pinned:!0,tier:"hot"}})).modifiedCount>0}async unpin(e){return(await this.collection.updateOne({_id:e},{$set:{pinned:!1}})).modifiedCount>0}async delete(e){return this.collection.findOneAndDelete({_id:e})}async touchAccess(e){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{lastAccessedAt:new Date},$inc:{accessCount:1}})}async getHotTier(e){let t={critical:4,high:3,medium:2,low:1};return(await this.collection.find({agentId:e,tier:"hot",purged:{$ne:!0},supersededBy:{$exists:!1}}).toArray()).sort((r,i)=>{if(r.pinned!==i.pinned)return r.pinned?-1:1;let o=(t[i.importance]??0)-(t[r.importance]??0);return o!==0?o:i.updatedAt.getTime()-r.updatedAt.getTime()})}async getHotTierWithStats(e){let t=await this.getHotTier(e),s=Date.now();return t.map(r=>({...r,ageDays:Math.floor((s-r.createdAt.getTime())/(1e3*60*60*24)),daysSinceAccess:Math.floor((s-r.lastAccessedAt.getTime())/(1e3*60*60*24))}))}async getByIds(e){return e.length===0?[]:this.collection.find({_id:{$in:e},purged:{$ne:!0}}).toArray()}async countNonHot(e){return this.collection.countDocuments({agentId:e,tier:{$ne:"hot"},purged:{$ne:!0}})}async getAllNonPinned(e){return this.collection.find({agentId:e,pinned:!1,purged:{$ne:!0},supersededBy:{$exists:!1}}).toArray()}async getByTiersForAgent(e,t){return this.collection.find({agentId:e,tier:{$in:t},purged:{$ne:!0},summarized:!1,supersededBy:{$exists:!1}}).toArray()}async getFactsAndDecisionsByTopic(e){let t=await this.collection.find({agentId:e,type:{$in:["fact","decision"]},purged:{$ne:!0},supersededBy:{$exists:!1},needsReview:{$ne:!0}}).toArray(),s=new Map;for(let r of t){let i=s.get(r.topic)??[];i.push(r),s.set(r.topic,i)}return s}async getInteractionsByTopic(e){let t=await this.collection.find({agentId:e,type:"interaction",tier:{$in:["hot","warm"]},purged:{$ne:!0},supersededBy:{$exists:!1},summarized:!1}).toArray(),s=new Map;for(let r of t){let i=s.get(r.topic)??[];i.push(r),s.set(r.topic,i)}return s}async markSuperseded(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{supersededBy:t,tier:"cold"}})}async flagForReview(e){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{needsReview:!0}})}async getAllForAgent(e){return this.collection.find({agentId:e}).toArray()}async setTier(e,t){await this.collection.updateOne({_id:e},{$set:{tier:t}})}async setTierBulk(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{tier:t}})}async getColdByTopic(e,t){return this.collection.find({agentId:e,tier:"cold",topic:t,summarized:!1,purged:{$ne:!0}}).sort({createdAt:1}).toArray()}async getColdTopics(e){return await this.collection.distinct("topic",{agentId:e,tier:"cold",summarized:!1,purged:{$ne:!0}})}async markSummarized(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{summarized:!0,summaryGroup:t,summarizedAt:new Date}})}async deleteSummarizedOlderThan(e,t){return(await this.collection.deleteMany({agentId:e,summarized:!0,summarizedAt:{$lt:t}})).deletedCount}async purge(e,t){if(!(t.topic!==void 0||t.type!==void 0||t.importance!==void 0||t.tier!==void 0||t.olderThan!==void 0))throw new Error("purge() requires at least one filter");let r={agentId:e,pinned:!1,purged:{$ne:!0}};return t.topic!==void 0&&(r.topic=t.topic),t.type!==void 0&&(r.type=t.type),t.importance!==void 0&&(r.importance=t.importance),t.tier!==void 0&&(r.tier=t.tier),t.olderThan!==void 0&&(r.updatedAt={$lt:t.olderThan}),(await this.collection.updateMany(r,{$set:{purged:!0,purgedAt:new Date}})).modifiedCount}async deletePurgedOlderThan(e,t){let s=await this.collection.find({agentId:e,purged:!0,purgedAt:{$lt:t}}).toArray();if(s.length===0)return[];let r=s.map(i=>i._id);return await this.collection.deleteMany({_id:{$in:r}}),s}async getAgentIds(){return this.collection.distinct("agentId")}async close(){}};M();Er();import{QdrantClient as Ab}from"@qdrant/js-client-rest";var uf=k("memory-embedder"),Ct="agent_memory",ni=class{qdrantUrl;ollamaUrl;qdrant=null;collectionReady=!1;constructor(e=process.env.QDRANT_URL??"http://localhost:6333",t=process.env.OLLAMA_URL??"http://localhost:11434"){this.qdrantUrl=e,this.ollamaUrl=t}getClient(){return this.qdrant||(this.qdrant=new Ab({url:this.qdrantUrl})),this.qdrant}async embed(e){return He(this.ollamaUrl,e)}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(r=>r.name===Ct)){let r=await this.embed("test");await e.createCollection(Ct,{vectors:{size:r.length,distance:"Cosine"}}),uf.info("Created Qdrant collection",{collection:Ct,vectorSize:r.length})}this.collectionReady=!0}async upsert(e,t,s){await this.ensureCollection();let r=await this.embed(t);await this.getClient().upsert(Ct,{points:[{id:e,vector:r,payload:s}]})}async remove(e){await this.ensureCollection(),await this.getClient().delete(Ct,{points:[e]})}async search(e,t,s){await this.ensureCollection();let r=await this.embed(e),i=s?.limit??10,o=[{key:"agentId",match:{value:t}}];return s?.type&&o.push({key:"type",match:{value:s.type}}),s?.topic&&o.push({key:"topic",match:{value:s.topic}}),s?.tier&&o.push({key:"tier",match:{value:s.tier}}),s?.importance&&o.push({key:"importance",match:{value:s.importance}}),(await this.getClient().search(Ct,{vector:r,limit:i,with_payload:!0,filter:{must:o}})).map(l=>({mongoId:l.payload?.mongoId,score:l.score}))}async findSimilar(e,t,s,r=10){await this.ensureCollection();let i;try{i=await this.getClient().query(Ct,{query:{recommend:{positive:[e]}},filter:{must:[{key:"agentId",match:{value:t}}]},limit:r,with_payload:!0,score_threshold:s})}catch(o){if(String(o).includes("Not Found")||String(o).includes("does not exists"))return uf.warn("findSimilar skipped orphan point",{pointId:e,agentId:t}),[];throw o}return i.points.map(o=>({mongoId:o.payload?.mongoId,score:o.score??0,pointId:typeof o.id=="string"?o.id:String(o.id)}))}};M();import{ObjectId as Cb}from"mongodb";import{query as ri}from"@anthropic-ai/claude-agent-sdk";var hf={critical:1,high:.75,medium:.5,low:.25},ff={decision:1,fact:.8,preference:.8,summary:.6,task:.5,interaction:.3};var Me=k("memory-lifecycle"),ii=class{store;embedder;config;dreamConfig;getActiveAgentIds;constructor(e,t,s,r,i){this.store=e,this.embedder=t,this.config=s,this.dreamConfig=r,this.getActiveAgentIds=i}async filterActiveAgents(e){if(!this.getActiveAgentIds)return e;let t=await this.getActiveAgentIds(),s=e.filter(i=>t.has(i)),r=e.length-s.length;return r>0&&Me.debug("Skipped retired agents",{skipped:r,retiredIds:e.filter(i=>!t.has(i))}),s}computeScore(e,t){let s=hf[e.importance]??.5,r=ff[e.type]??.5,i=Date.now()-e.updatedAt.getTime(),o=this.config.recencyHalfLifeDays*24*60*60*1e3,a=Math.exp(-.693*i/o),l=t>0?Math.min(e.accessCount/t,1):e.accessCount>0?1:0;return s*.4+a*.3+l*.2+r*.1}estimateTokens(e){return Math.ceil(e.length/4)}async sweep(){let e=Date.now(),t=0,s=0,r=0,i=0,o=0,a=[];try{let c=await this.store.getAgentIds(),d=await this.filterActiveAgents(c);for(let u of d)try{let h=await this.sweepAgent(u);t+=h.promoted,s+=h.demoted,r+=h.summarized,i+=h.cleaned,o+=h.purged}catch(h){a.push(`${u}: ${h}`),Me.error("Memory lifecycle sweep failed for agent",{agentId:u,error:String(h)})}}catch(c){a.push(`global: ${c}`)}return t+s+r+i+o>0&&Me.info("Memory lifecycle sweep complete",{durationMs:Date.now()-e,promoted:t,demoted:s,summarized:r,cleaned:i,purged:o,errors:a.length}),{component:"memory-lifecycle",pruned:s+i+o,retried:t,bytesFreed:0,errors:a}}async sweepAgent(e){let t=0,s=0,r=await this.store.getAllNonPinned(e),i=0,o=0;if(r.length>0){let d=r.map(w=>w.accessCount).sort((w,S)=>w-S),u=d[Math.floor(d.length/2)]??0,h=r.map(w=>({record:w,score:this.computeScore(w,u)})),p=[];for(let{record:w,score:S}of h){let _;S>=this.config.hotThreshold?_="hot":S>=this.config.warmThreshold?_="warm":_="cold",_!==w.tier&&(p.push({id:w._id,newTier:_}),_==="hot"&&w.tier!=="hot"&&t++,_!=="hot"&&w.tier==="hot"&&s++)}for(let w of["hot","warm","cold"]){let S=p.filter(_=>_.newTier===w).map(_=>_.id);await this.store.setTierBulk(S,w)}let m=await this.store.getHotTier(e),f=0,y=[];for(let w of m){let S=this.estimateTokens(w.content);w.pinned||(f+=S,f>this.config.hotBudgetTokens&&y.push(w._id))}y.length>0&&(await this.store.setTierBulk(y,"warm"),s+=y.length);try{i=await this.summarizeCold(e)}catch(w){Me.warn("Cold summarization failed",{agentId:e,error:String(w)})}}let a=new Date(Date.now()-this.config.coldRetentionDays*24*60*60*1e3);o=await this.store.deleteSummarizedOlderThan(e,a);let l=new Date(Date.now()-this.config.purgeRetentionDays*24*60*60*1e3),c=0;try{let d=await this.store.deletePurgedOlderThan(e,l);if(c=d.length,d.length>0){let u=d.map(h=>h.qdrantPointId).filter(Boolean);for(let h of u)await this.embedder.remove(h);Me.info("Hard-deleted purged records",{agentId:e,count:d.length})}}catch(d){Me.warn("Purge hard-delete phase failed",{agentId:e,error:String(d)})}return{promoted:t,demoted:s,summarized:i,cleaned:o,purged:c}}async dream(){if(!this.dreamConfig?.enabled)return{merged:0,contradictions:0,promoted:0,flaggedForReview:0,errors:[]};let e=Date.now(),t=0,s=0,r=0,i=0,o=[];try{let l=await this.store.getAgentIds(),c=await this.filterActiveAgents(l);for(let d of c)try{let u=await this.mergeDuplicates(d);t+=u.merged;let h=await this.detectContradictions(d);s+=h.resolved,i+=h.flagged;let p=await this.promotePatterns(d);r+=p.promoted}catch(u){o.push(`${d}: ${u}`),Me.error("autoDream failed for agent",{agentId:d,error:String(u)})}}catch(l){o.push(`global: ${l}`)}return t+s+r+i>0&&Me.info("autoDream complete",{durationMs:Date.now()-e,merged:t,contradictions:s,promoted:r,flaggedForReview:i,errors:o.length}),{merged:t,contradictions:s,promoted:r,flaggedForReview:i,errors:o}}async mergeDuplicates(e){let t=this.dreamConfig,s=await this.store.getByTiersForAgent(e,["hot","warm"]);if(s.length<2)return{merged:0};let r=new Set,i=0,o=0;for(let a of s){if(o>=t.maxClustersPerRun)break;if(r.has(a.qdrantPointId))continue;let c=(await this.embedder.findSimilar(a.qdrantPointId,e,t.similarityThreshold,10)).filter(I=>!r.has(I.pointId));if(c.length===0)continue;r.add(a.qdrantPointId);for(let I of c)r.add(I.pointId);let d=c.map(I=>new Cb(I.mongoId)),u=await this.store.getByIds(d),h=[a,...u],m=["Merge the following duplicate or overlapping memories into a single consolidated record.","Preserve all unique details. Discard exact duplicates. Be concise.","",h.map(I=>`- [${I.type}/${I.importance}] ${I.content}`).join(`
431
+ `:"",`Stderr (last ${ly} lines):`,"```",a||"(empty)","```"].filter(Boolean).join(`
432
+ `)})().then(a=>{let l={id:`ct:${e.id}:done:${Date.now()}`,text:a,source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,codeTaskId:e.id}};ge.info("Code task completed, dispatching notification",{id:e.id,status:e.status,exitCode:e.exitCode,costUsd:e.costUsd,numTurns:e.numTurns,durationSec:o,agentId:e.context.agentId,hasEscalation:!!e.escalation}),this.onComplete(l),this.options?.knowledgeExtractor&&e.status==="completed"&&t&&this.options.knowledgeExtractor.extract(e.context.agentId,t).then(c=>{c>0&&ge.info(`Extracted ${c} code insights from task ${e.id}`)}).catch(c=>{ge.warn(`Knowledge extraction failed for task ${e.id}: ${c}`)})}).catch(a=>{ge.error("Failed to fire completion notification",{id:e.id,error:String(a)})})}async taskStatus(e){let t=this.tasks.get(e);if(!t)return null;let i="";try{i=(await ol(t.stderrPath,"utf-8")).split(`
433
+ `).slice(-ly).join(`
434
+ `).trim()}catch{}return{id:t.id,status:t.status,exitCode:t.exitCode,startedAt:t.startedAt,completedAt:t.completedAt,cwd:t.cwd,model:t.model,costUsd:t.costUsd,numTurns:t.numTurns,sessionId:t.sessionId,escalation:t.escalation,parentTaskId:t.parentTaskId,stderrTail:i}}listTasks(e){let t=[];for(let i of this.tasks.values())e&&i.context.agentId!==e||t.push({id:i.id,status:i.status,exitCode:i.exitCode,startedAt:i.startedAt,completedAt:i.completedAt,costUsd:i.costUsd,numTurns:i.numTurns,cwd:i.cwd,prompt:i.prompt});return t}async sweep(e){let t=Date.now()-e,i=0,r=0,o=[];for(let[s,a]of this.tasks)if(!(a.status==="running"||!a.completedAt||new Date(a.completedAt).getTime()>t)){for(let c of[a.metaPath,a.stdoutPath,a.stderrPath])try{let u=await mL(c);r+=u.size,await hL(c)}catch(u){u.code!=="ENOENT"&&o.push(`Failed to delete ${c}: ${String(u)}`)}this.tasks.delete(s),i++}return{component:"code-task-manager",pruned:i,retried:0,bytesFreed:r,errors:o}}async writeMeta(e){try{await fL(e.metaPath,JSON.stringify(e,null,2),"utf-8")}catch(t){ge.error("Failed to write task metadata",{id:e.id,error:String(t)})}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}pollOrphan(e,t){let i=setInterval(()=>{if(!this.isProcessAlive(t)){clearInterval(i),this.orphanPollers.delete(e);let r=this.tasks.get(e);r&&r.status==="running"&&(r.status="orphaned",r.completedAt=new Date().toISOString(),this.writeMeta(r).then(()=>this.fireCompletion(r)))}},5e3);this.orphanPollers.set(e,i)}killProcess(e,t){try{process.kill(e,t)}catch(i){i.code!=="ESRCH"&&ge.warn("Failed to send signal to process",{pid:e,signal:t,error:String(i)})}}async isFileRecentlyModified(e,t){try{let i=await gL(e,"r"),r=await i.stat();return await i.close(),Date.now()-r.mtimeMs<t}catch{return!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}readBody(e){return new Promise((t,i)=>{let r="";e.on("data",o=>{r+=o.toString()}),e.on("end",()=>t(r)),e.on("error",i)})}};R();import{createServer as vL}from"node:http";import{randomUUID as _L}from"node:crypto";var be=$("meeting-monitor"),wL=1e4,bL=15e3,kL=2,SL=new Set(["done","fatal","call_ended","media_expired","recording_permission_denied"]),al=class{port;webhookSecret;onUpdate;server=null;sessions=new Map;sessionsByBotId=new Map;constructor(e,t,i){this.port=e,this.webhookSecret=t,this.onUpdate=i}async start(){this.server=vL((e,t)=>{this.handleRequest(e,t).catch(i=>{be.error("HTTP handler error",{error:String(i)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),be.info("Meeting monitor started",{port:this.port}),this.webhookSecret||be.error("Webhook verification disabled \u2014 RECALL_WEBHOOK_SECRET not set. All webhook requests will be rejected.")}stop(){for(let e of this.sessions.values())e.pollTimer&&(clearInterval(e.pollTimer),e.pollTimer=null);this.server&&(this.server.close(),this.server=null),be.info("Meeting monitor stopped")}async handleRequest(e,t){let i=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.method==="POST"&&i.pathname==="/meetings/start"){let o=await this.readBody(e),s=JSON.parse(o),a=this.createSession(s);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({sessionId:a.id}));return}let r=i.pathname.match(/^\/meetings\/([a-f0-9-]+)\/stop$/);if(e.method==="POST"&&r){let o=r[1],s=this.sessions.get(o);if(!s){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Session not found"}));return}s.pollTimer&&(clearInterval(s.pollTimer),s.pollTimer=null),s.status="ended",s.endedAt=Date.now(),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"stopped"}));return}if(e.method==="POST"&&i.pathname.startsWith("/webhook/transcript")){if(!this.webhookSecret){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Webhook verification not configured"}));return}if(i.pathname!==`/webhook/transcript/${this.webhookSecret}`){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}));return}let o=await this.readBody(e);this.handleTranscriptWebhook(o),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}if(e.method==="GET"&&i.pathname==="/meetings"){let o=[];for(let s of this.sessions.values())o.push({id:s.id,botId:s.botId,botName:s.botName,meetingUrl:s.meetingUrl,status:s.status,pollCount:s.pollCount,lastSegmentIndex:s.lastSegmentIndex,pendingSegments:s.pendingSegments.length});t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(o));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}handleTranscriptWebhook(e){try{let t=JSON.parse(e),i=t.event,r=t.data?.bot?.id;if(!r){be.warn("Webhook missing bot ID",{event:i});return}let o=this.sessionsByBotId.get(r);if(!o){be.warn("Webhook for unknown bot",{botId:r,event:i});return}let s=this.sessions.get(o);if(!s||s.status!=="monitoring")return;let a=t.data?.data;if(!a)return;let l=a.participant?.id??0,c=a.participant?.name??"Unknown",u=Array.isArray(a.words)?a.words.map(d=>d.text).join(" "):"";if(!u)return;s.idlePollCount=0,i==="transcript.partial_data"?s.activePartials.set(l,{speaker:c,text:u}):i==="transcript.data"&&(s.pendingSegments.push({speaker:c,text:u}),s.activePartials.delete(l),s.lastSegmentIndex++),be.debug("Webhook transcript",{sessionId:o,botId:r,event:i,speaker:c,wordCount:u.split(" ").length})}catch(t){be.error("Webhook parse error",{error:String(t)})}}createSession(e){let t=_L(),i={id:t,botId:e.botId,botName:e.botName,meetingUrl:e.meetingUrl,apiKey:e.apiKey,region:e.region,context:e.context,lastSegmentIndex:0,pendingSegments:[],activePartials:new Map,lastDispatchTime:Date.now(),idlePollCount:0,pollTimer:null,pollCount:0,status:"monitoring",endedAt:null};return this.sessions.set(t,i),this.sessionsByBotId.set(e.botId,t),i.pollTimer=setInterval(()=>{this.pollSession(t).catch(r=>{be.error("Poll session error",{sessionId:t,botId:i.botId,error:String(r)})})},wL),be.info("Meeting session created",{sessionId:t,botId:e.botId,botName:e.botName,meetingUrl:e.meetingUrl,agentId:e.context.agentId}),i}async pollSession(e){let t=this.sessions.get(e);if(!t||t.status!=="monitoring")return;t.pollCount++;let i=t.pendingSegments.length>0||t.activePartials.size>0;(Date.now()-t.lastDispatchTime>=bL&&i||t.idlePollCount>=kL&&i)&&this.dispatchBatch(t),t.pollCount%3===0&&await this.checkBotStatus(t)}async checkBotStatus(e){try{let t=`https://${e.region}.recall.ai/api/v1/bot/${e.botId}/`,i=await fetch(t,{headers:{Authorization:`Token ${e.apiKey}`},signal:AbortSignal.timeout(15e3)});if(!i.ok){be.warn("Bot status check failed",{sessionId:e.id,botId:e.botId,status:i.status});return}let r=await i.json(),o=r.status_changes;if(Array.isArray(o)&&o.length>0){let s=o[o.length-1].code;if(SL.has(s)){be.info("Meeting reached terminal status",{sessionId:e.id,botId:e.botId,statusCode:s});let a=await this.fetchFullTranscript(e,r);this.dispatchEnd(e,a);return}}}catch(t){be.error("Bot status check error",{sessionId:e.id,botId:e.botId,error:String(t)})}}async fetchFullTranscript(e,t){let o=(Array.isArray(t.recordings)?t.recordings:[])[0]?.media_shortcuts?.transcript?.data?.download_url;if(!o)return be.warn("No transcript download URL available",{sessionId:e.id,botId:e.botId}),[...e.pendingSegments];try{let s=await fetch(o,{signal:AbortSignal.timeout(3e4)});if(!s.ok)return be.warn("Transcript download failed",{sessionId:e.id,status:s.status}),[...e.pendingSegments];let a=await s.json();return(Array.isArray(a)?a:Array.isArray(a.results)?a.results:[]).map(c=>({speaker:c.speaker??c.participant?.name??"Unknown",text:Array.isArray(c.words)?c.words.map(u=>u.text).join(" "):typeof c.text=="string"?c.text:""}))}catch(s){return be.error("Transcript download error",{sessionId:e.id,error:String(s)}),[...e.pendingSegments]}}dispatchBatch(e){let t=e.pendingSegments.splice(0,e.pendingSegments.length);for(let r of e.activePartials.values())t.push({speaker:r.speaker,text:`${r.text} [still speaking...]`});if(e.activePartials.clear(),e.lastDispatchTime=Date.now(),t.length===0)return;let i={id:`meeting:${e.botId}:${Date.now()}`,text:[`[Meeting transcript update \u2014 ${e.botName}]`,`Bot ID: ${e.botId}`,"","New transcript:",...t.map(r=>`[${r.speaker}]: ${r.text}`),"","---",`You are participating in this meeting. Use recall_send_chat with bot_id "${e.botId}" if you have relevant input. Otherwise respond "No response needed."`].join(`
435
+ `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,meetingBotId:e.botId}};be.info("Dispatching transcript batch",{sessionId:e.id,botId:e.botId,segmentCount:t.length}),this.onUpdate(i)}dispatchEnd(e,t){let i={id:`meeting:${e.botId}:${Date.now()}`,text:[`[Meeting ended \u2014 ${e.botName}]`,`Bot ID: ${e.botId}`,"","Full transcript:",...t.map(r=>`[${r.speaker}]: ${r.text}`),"","---","Meeting has ended. Produce a summary: key decisions made, action items with owners, and open questions."].join(`
436
+ `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,meetingBotId:e.botId}};be.info("Dispatching meeting end",{sessionId:e.id,botId:e.botId,totalSegments:t.length}),this.onUpdate(i),e.pollTimer&&(clearInterval(e.pollTimer),e.pollTimer=null),e.status="ended",e.endedAt=Date.now()}sweep(e){let t=Date.now()-e,i=0;for(let[r,o]of this.sessions)o.endedAt!==null&&(o.endedAt>t||(o.pollTimer&&(clearInterval(o.pollTimer),o.pollTimer=null),this.sessionsByBotId.delete(o.botId),this.sessions.delete(r),i++));return{component:"meeting-monitor",pruned:i,retried:0,bytesFreed:0,errors:[]}}readBody(e){return new Promise((t,i)=>{let r="";e.on("data",o=>{r+=o.toString()}),e.on("end",()=>t(r)),e.on("error",i)})}};R();var cl=$("retry-queue"),ll=class{entries=[];config;constructor(e){this.config=e}enqueue(e,t){this.entries.push({result:e,adapter:t,attempts:0,nextRetryAt:Date.now()+this.config.baseDelayMs,createdAt:Date.now()}),cl.info("Delivery queued for retry",{agentId:e.agentId,adapterId:t.id,queueSize:this.entries.length})}async processRetries(){let e=Date.now(),t={pending:0,retried:0,dropped:0,errors:[]},i=[];for(let r of this.entries){if(r.nextRetryAt>e){i.push(r),t.pending++;continue}r.attempts++;try{await r.adapter.deliver(r.result),t.retried++,cl.info("Retry delivery succeeded",{agentId:r.result.agentId,adapterId:r.adapter.id,attempt:r.attempts})}catch(o){if(r.attempts>=this.config.maxAttempts){t.dropped++;let s=`Dropped after ${r.attempts} attempts: ${String(o)}`;t.errors.push(s),cl.error("Retry delivery exhausted",{agentId:r.result.agentId,adapterId:r.adapter.id,attempts:r.attempts,error:String(o)})}else r.nextRetryAt=e+this.config.baseDelayMs*Math.pow(2,r.attempts),i.push(r),t.pending++,cl.warn("Retry delivery failed, will retry",{agentId:r.result.agentId,adapterId:r.adapter.id,attempt:r.attempts,nextRetryAt:new Date(r.nextRetryAt).toISOString(),error:String(o)})}}return this.entries=i,t}get size(){return this.entries.length}};R();var Ct=$("sweeper"),ul=class n{config;targets;taskClient;taskId;timer=null;sweepCount=0;gatewayCycleCounter=0;memoryCycleCounter=0;memorySweepEvery;lastDreamAt=0;static GATEWAY_SWEEP_EVERY=12;constructor(e,t,i){this.config=e,this.targets=t,this.taskClient=i;let r=e.memorySweepIntervalHours??6;this.memorySweepEvery=Math.round(r*36e5/e.intervalMs)}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>{Ct.error("Sweep cycle failed",{error:String(e)})})},this.config.intervalMs),Ct.info("Sweeper started",{intervalMs:this.config.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),Ct.info("Sweeper stopped")}async sweep(){let e=Date.now();this.sweepCount++,this.gatewayCycleCounter++;let t=[];try{t.push(this.targets.dispatcher.sweep(this.config.threadTtlMs))}catch(u){t.push({component:"dispatcher",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}for(let u of this.targets.slackAdapters)try{t.push(u.sweep(this.config.threadTtlMs))}catch(d){t.push({component:`slack-adapter:${u.id}`,pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.taskLedger)try{t.push(this.targets.taskLedger.sweep(this.config.threadTtlMs))}catch(u){t.push({component:"task-ledger",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}try{t.push(await this.targets.bgTaskManager.sweep(this.config.taskFileTtlMs))}catch(u){t.push({component:"bg-task-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}if(this.targets.codeTaskManager){try{t.push(await this.targets.codeTaskManager.sweep(this.config.taskFileTtlMs))}catch(u){t.push({component:"code-task-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}try{let{reaped:u,spared:d}=await this.targets.codeTaskManager.reapStale();(u>0||d>0)&&t.push({component:"code-task-reaper",pruned:u,retried:0,bytesFreed:0,errors:d>0?[`${d} task(s) spared \u2014 still active past TTL`]:[]})}catch(u){t.push({component:"code-task-reaper",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}}if(this.targets.meetingMonitor)try{t.push(this.targets.meetingMonitor.sweep(this.config.meetingSessionTtlMs))}catch(u){t.push({component:"meeting-monitor",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}if(this.gatewayCycleCounter>=n.GATEWAY_SWEEP_EVERY){this.gatewayCycleCounter=0;for(let u of this.targets.slackGateways)try{t.push(u.sweep())}catch(d){t.push({component:"slack-gateway",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}}try{t.push(this.targets.agentManager.sweep())}catch(u){t.push({component:"agent-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}if(this.targets.retryQueue)try{let u=await this.targets.retryQueue.processRetries();t.push({component:"retry-queue",pruned:u.dropped,retried:u.retried,bytesFreed:0,errors:u.errors})}catch(u){t.push({component:"retry-queue",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}if(this.targets.memoryLifecycle&&(this.memoryCycleCounter++,this.memoryCycleCounter>=this.memorySweepEvery)){this.memoryCycleCounter=0;try{t.push(await this.targets.memoryLifecycle.sweep())}catch(u){t.push({component:"memory-lifecycle",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}}if(this.targets.memoryLifecycle&&this.config.dreamConfig?.enabled){let u=this.config.dreamConfig,d=u.cooldownMinutes*60*1e3,f=Date.now(),p=f-this.lastDreamAt>d,h=this.memoryCycleCounter===0,m=!1;if(p&&!h){let y=u.idleThresholdMinutes*60*1e3,_=this.targets.agentManager.getAllStates();m=_.length>0&&_.every(b=>b.status==="idle"&&f-b.lastActivity.getTime()>y)}if(p&&(h||m)){let y=h?"post-sweep":"idle";Ct.info("autoDream triggered",{trigger:y});try{let _=await this.targets.memoryLifecycle.dream();this.lastDreamAt=Date.now(),(_.merged+_.contradictions+_.promoted>0||_.errors.length>0)&&t.push({component:"autodream",pruned:_.merged+_.contradictions,retried:_.promoted,bytesFreed:0,errors:_.errors})}catch(_){t.push({component:"autodream",pruned:0,retried:0,bytesFreed:0,errors:[String(_)]})}}}let i=Date.now()-e,r=t.reduce((u,d)=>u+d.pruned,0),o=t.reduce((u,d)=>u+d.retried,0),s=t.reduce((u,d)=>u+d.bytesFreed,0),a=t.flatMap(u=>u.errors),l=r===0&&o===0&&s===0&&a.length===0;return(l?Ct.debug.bind(Ct):Ct.info.bind(Ct))("Sweep cycle complete",{cycle:this.sweepCount,durationMs:i,pruned:r,retried:o,bytesFreed:s,errors:a.length,components:t.map(u=>`${u.component}:${u.pruned}p/${u.retried}r`).join(" ")}),this.taskClient?.isConfigured&&!l&&await this.reportToTaskLedger(i,r,o,s,a),t}async reportToTaskLedger(e,t,i,r,o){try{if(!this.taskId){let a=await this.taskClient.createTask({name:"[Sweeper] Periodic maintenance",type:"AGENT",description:"Long-running system health task. Each comment is a sweep cycle report."});a&&(this.taskId=a._id)}if(!this.taskId)return;let s=[`**Sweep #${this.sweepCount}** (${e}ms)`,`Pruned: ${t} | Retried: ${i} | Freed: ${this.formatBytes(r)}`,o.length>0?`Errors: ${o.join(", ")}`:null].filter(Boolean).join(`
437
+ `);await this.taskClient.addComment(this.taskId,s),o.length>0&&await this.taskClient.updateTask(this.taskId,{state:"NEEDS_ATTENTION"})}catch(s){Ct.warn("Failed to report to task ledger",{error:String(s)})}}formatBytes(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],i=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,i)).toFixed(1)} ${t[i]}`}};R();import{readdirSync as xI,readFileSync as $L,rmSync as xL,statSync as IL,existsSync as dl}from"node:fs";import{resolve as uy,join as II,sep as $I}from"node:path";var wo=$("retention"),fl=class{config;deps;timer=null;constructor(e,t){this.config=e,this.deps=t}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>wo.error("Retention sweep failed",{error:String(e)}))},this.config.intervalMs),wo.info("Retention sweeper started",{intervalMs:this.config.intervalMs,enabled:this.config.enabled,rules:Object.keys(this.config.paths).length}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),wo.info("Retention sweeper stopped")}async sweep(){let e=new Date,t=[],i=[],r=[];for(let[s,a]of Object.entries(this.config.paths))if(a.days!==0)for(let l of TL(this.deps.hiveHome,s))try{EL(l,s,a.days,e,t)}catch(c){r.push({path:l,error:String(c)})}if(this.config.enabled)for(let s of t)try{xL(s.path,{recursive:!0,force:!0}),i.push(s)}catch(a){r.push({path:s.path,error:String(a)})}let o={sweptAt:e,dryRun:!this.config.enabled,candidates:t,deleted:i,errors:r};try{await this.deps.report(OL(o))}catch(s){wo.warn("Retention report delivery failed",{error:String(s)})}return o}};function TL(n,e){let t=e.split("/"),i=t.indexOf("*");if(i===-1){let a=uy(n,e);return dl(a)?[a]:[]}if(t.indexOf("*",i+1)!==-1)throw new Error(`Retention rules support at most one '*' segment: ${e}`);let r=t.slice(0,i).join($I),o=t.slice(i+1).join($I),s=uy(n,r);return dl(s)?xI(s,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>uy(s,a.name,o)).filter(a=>dl(a)):[]}function EL(n,e,t,i,r){let o=AL(n)??t;if(o===0)return;let s=i.getTime()-o*864e5,a=xI(n,{withFileTypes:!0});for(let l of a){if(l.name===".retention-days")continue;let c=II(n,l.name),u;try{u=IL(c)}catch{continue}u.mtimeMs<=s&&r.push({path:c,rule:e,days:o,mtime:u.mtime,ageDays:(i.getTime()-u.mtimeMs)/864e5})}}function AL(n){let e=II(n,".retention-days");if(!dl(e))return null;let t=$L(e,"utf-8").trim(),i=Number(t);return!Number.isFinite(i)||i<0||!Number.isInteger(i)?(wo.warn("Invalid .retention-days override \u2014 ignoring",{path:e,raw:t}),null):i}function OL(n){let e=n.dryRun?"would delete":"deleted",t=[`*Retention sweep* (${n.dryRun?"dry-run":"enforced"}) @ ${n.sweptAt.toISOString()}`,`${n.candidates.length} candidates \xB7 ${e} ${n.dryRun?n.candidates.length:n.deleted.length} \xB7 ${n.errors.length} errors`],i=n.candidates.slice(0,10);if(i.length){t.push("```");for(let r of i)t.push(`${r.path} (age ${r.ageDays.toFixed(1)}d, rule ${r.rule}@${r.days}d)`);n.candidates.length>i.length&&t.push(`\u2026 and ${n.candidates.length-i.length} more`),t.push("```")}return n.errors.length&&t.push(`Errors: ${n.errors.slice(0,3).map(r=>`${r.path}: ${r.error}`).join(" | ")}`),t.join(`
438
+ `)}ho();R();var CL=$("memory-store"),pl=class{db;collection;constructor(e){this.db=e}async init(){this.collection=this.db.collection("agent_memory"),await this.collection.createIndex({agentId:1,tier:1}),await this.collection.createIndex({agentId:1,topic:1}),await this.collection.createIndex({agentId:1,updatedAt:1}),await this.collection.createIndex({agentId:1,type:1}),await this.collection.createIndex({agentId:1,purged:1,purgedAt:1}),CL.info("Memory store initialized",{db:this.db.databaseName})}getCollection(){return this.collection}async save(e,t,i,r,o){let s=new Date,a={agentId:e,content:t.content,type:t.type,topic:t.topic,importance:t.importance,tier:"hot",createdAt:s,updatedAt:s,lastAccessedAt:s,accessCount:0,sourceChannel:r,sourceThread:o,pinned:!1,summarized:!1,qdrantPointId:i},l=await this.collection.insertOne(a);return a._id=l.insertedId,a}async getById(e){return this.collection.findOne({_id:e,purged:{$ne:!0}})}async update(e,t,i,r){let o={content:t,updatedAt:new Date};return i&&(o.importance=i),r&&(o.qdrantPointId=r),await this.collection.findOneAndUpdate({_id:e},{$set:o},{returnDocument:"after"})}async pin(e){return(await this.collection.updateOne({_id:e},{$set:{pinned:!0,tier:"hot"}})).modifiedCount>0}async unpin(e){return(await this.collection.updateOne({_id:e},{$set:{pinned:!1}})).modifiedCount>0}async delete(e){return this.collection.findOneAndDelete({_id:e})}async touchAccess(e){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{lastAccessedAt:new Date},$inc:{accessCount:1}})}async getHotTier(e){let t={critical:4,high:3,medium:2,low:1};return(await this.collection.find({agentId:e,tier:"hot",purged:{$ne:!0},supersededBy:{$exists:!1}}).toArray()).sort((r,o)=>{if(r.pinned!==o.pinned)return r.pinned?-1:1;let s=(t[o.importance]??0)-(t[r.importance]??0);return s!==0?s:o.updatedAt.getTime()-r.updatedAt.getTime()})}async getHotTierWithStats(e){let t=await this.getHotTier(e),i=Date.now();return t.map(r=>({...r,ageDays:Math.floor((i-r.createdAt.getTime())/(1e3*60*60*24)),daysSinceAccess:Math.floor((i-r.lastAccessedAt.getTime())/(1e3*60*60*24))}))}async getByIds(e){return e.length===0?[]:this.collection.find({_id:{$in:e},purged:{$ne:!0}}).toArray()}async countNonHot(e){return this.collection.countDocuments({agentId:e,tier:{$ne:"hot"},purged:{$ne:!0}})}async getAllNonPinned(e){return this.collection.find({agentId:e,pinned:!1,purged:{$ne:!0},supersededBy:{$exists:!1}}).toArray()}async getByTiersForAgent(e,t){return this.collection.find({agentId:e,tier:{$in:t},purged:{$ne:!0},summarized:!1,supersededBy:{$exists:!1}}).toArray()}async getFactsAndDecisionsByTopic(e){let t=await this.collection.find({agentId:e,type:{$in:["fact","decision"]},purged:{$ne:!0},supersededBy:{$exists:!1},needsReview:{$ne:!0}}).toArray(),i=new Map;for(let r of t){let o=i.get(r.topic)??[];o.push(r),i.set(r.topic,o)}return i}async getInteractionsByTopic(e){let t=await this.collection.find({agentId:e,type:"interaction",tier:{$in:["hot","warm"]},purged:{$ne:!0},supersededBy:{$exists:!1},summarized:!1}).toArray(),i=new Map;for(let r of t){let o=i.get(r.topic)??[];o.push(r),i.set(r.topic,o)}return i}async markSuperseded(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{supersededBy:t,tier:"cold"}})}async flagForReview(e){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{needsReview:!0}})}async getAllForAgent(e){return this.collection.find({agentId:e}).toArray()}async setTier(e,t){await this.collection.updateOne({_id:e},{$set:{tier:t}})}async setTierBulk(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{tier:t}})}async getColdByTopic(e,t){return this.collection.find({agentId:e,tier:"cold",topic:t,summarized:!1,purged:{$ne:!0}}).sort({createdAt:1}).toArray()}async getColdTopics(e){return await this.collection.distinct("topic",{agentId:e,tier:"cold",summarized:!1,purged:{$ne:!0}})}async markSummarized(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{summarized:!0,summaryGroup:t,summarizedAt:new Date}})}async deleteSummarizedOlderThan(e,t){return(await this.collection.deleteMany({agentId:e,summarized:!0,summarizedAt:{$lt:t}})).deletedCount}async purge(e,t){if(!(t.topic!==void 0||t.type!==void 0||t.importance!==void 0||t.tier!==void 0||t.olderThan!==void 0))throw new Error("purge() requires at least one filter");let r={agentId:e,pinned:!1,purged:{$ne:!0}};return t.topic!==void 0&&(r.topic=t.topic),t.type!==void 0&&(r.type=t.type),t.importance!==void 0&&(r.importance=t.importance),t.tier!==void 0&&(r.tier=t.tier),t.olderThan!==void 0&&(r.updatedAt={$lt:t.olderThan}),(await this.collection.updateMany(r,{$set:{purged:!0,purgedAt:new Date}})).modifiedCount}async deletePurgedOlderThan(e,t){let i=await this.collection.find({agentId:e,purged:!0,purgedAt:{$lt:t}}).toArray();if(i.length===0)return[];let r=i.map(o=>o._id);return await this.collection.deleteMany({_id:{$in:r}}),i}async getAgentIds(){return this.collection.distinct("agentId")}async close(){}};R();Lc();import{QdrantClient as NL}from"@qdrant/js-client-rest";var TI=$("memory-embedder"),Nn="agent_memory",ml=class{qdrantUrl;ollamaUrl;qdrant=null;collectionReady=!1;constructor(e=process.env.QDRANT_URL??"http://localhost:6333",t=process.env.OLLAMA_URL??"http://localhost:11434"){this.qdrantUrl=e,this.ollamaUrl=t}getClient(){return this.qdrant||(this.qdrant=new NL({url:this.qdrantUrl})),this.qdrant}async embed(e){return At(this.ollamaUrl,e)}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(r=>r.name===Nn)){let r=await this.embed("test");await e.createCollection(Nn,{vectors:{size:r.length,distance:"Cosine"}}),TI.info("Created Qdrant collection",{collection:Nn,vectorSize:r.length})}this.collectionReady=!0}async upsert(e,t,i){await this.ensureCollection();let r=await this.embed(t);await this.getClient().upsert(Nn,{points:[{id:e,vector:r,payload:i}]})}async remove(e){await this.ensureCollection(),await this.getClient().delete(Nn,{points:[e]})}async search(e,t,i){await this.ensureCollection();let r=await this.embed(e),o=i?.limit??10,s=[{key:"agentId",match:{value:t}}];return i?.type&&s.push({key:"type",match:{value:i.type}}),i?.topic&&s.push({key:"topic",match:{value:i.topic}}),i?.tier&&s.push({key:"tier",match:{value:i.tier}}),i?.importance&&s.push({key:"importance",match:{value:i.importance}}),(await this.getClient().search(Nn,{vector:r,limit:o,with_payload:!0,filter:{must:s}})).map(l=>({mongoId:l.payload?.mongoId,score:l.score}))}async findSimilar(e,t,i,r=10){await this.ensureCollection();let o;try{o=await this.getClient().query(Nn,{query:{recommend:{positive:[e]}},filter:{must:[{key:"agentId",match:{value:t}}]},limit:r,with_payload:!0,score_threshold:i})}catch(s){if(String(s).includes("Not Found")||String(s).includes("does not exists"))return TI.warn("findSimilar skipped orphan point",{pointId:e,agentId:t}),[];throw s}return o.points.map(s=>({mongoId:s.payload?.mongoId,score:s.score??0,pointId:typeof s.id=="string"?s.id:String(s.id)}))}};R();import{ObjectId as DL}from"mongodb";import{query as hl}from"@anthropic-ai/claude-agent-sdk";var EI={critical:1,high:.75,medium:.5,low:.25},AI={decision:1,fact:.8,preference:.8,summary:.6,task:.5,interaction:.3};var ut=$("memory-lifecycle"),gl=class{store;embedder;config;dreamConfig;getActiveAgentIds;constructor(e,t,i,r,o){this.store=e,this.embedder=t,this.config=i,this.dreamConfig=r,this.getActiveAgentIds=o}async filterActiveAgents(e){if(!this.getActiveAgentIds)return e;let t=await this.getActiveAgentIds(),i=e.filter(o=>t.has(o)),r=e.length-i.length;return r>0&&ut.debug("Skipped retired agents",{skipped:r,retiredIds:e.filter(o=>!t.has(o))}),i}computeScore(e,t){let i=EI[e.importance]??.5,r=AI[e.type]??.5,o=Date.now()-e.updatedAt.getTime(),s=this.config.recencyHalfLifeDays*24*60*60*1e3,a=Math.exp(-.693*o/s),l=t>0?Math.min(e.accessCount/t,1):e.accessCount>0?1:0;return i*.4+a*.3+l*.2+r*.1}estimateTokens(e){return Math.ceil(e.length/4)}async sweep(){let e=Date.now(),t=0,i=0,r=0,o=0,s=0,a=[];try{let c=await this.store.getAgentIds(),u=await this.filterActiveAgents(c);for(let d of u)try{let f=await this.sweepAgent(d);t+=f.promoted,i+=f.demoted,r+=f.summarized,o+=f.cleaned,s+=f.purged}catch(f){a.push(`${d}: ${f}`),ut.error("Memory lifecycle sweep failed for agent",{agentId:d,error:String(f)})}}catch(c){a.push(`global: ${c}`)}return t+i+r+o+s>0&&ut.info("Memory lifecycle sweep complete",{durationMs:Date.now()-e,promoted:t,demoted:i,summarized:r,cleaned:o,purged:s,errors:a.length}),{component:"memory-lifecycle",pruned:i+o+s,retried:t,bytesFreed:0,errors:a}}async sweepAgent(e){let t=0,i=0,r=await this.store.getAllNonPinned(e),o=0,s=0;if(r.length>0){let u=r.map(_=>_.accessCount).sort((_,b)=>_-b),d=u[Math.floor(u.length/2)]??0,f=r.map(_=>({record:_,score:this.computeScore(_,d)})),p=[];for(let{record:_,score:b}of f){let k;b>=this.config.hotThreshold?k="hot":b>=this.config.warmThreshold?k="warm":k="cold",k!==_.tier&&(p.push({id:_._id,newTier:k}),k==="hot"&&_.tier!=="hot"&&t++,k!=="hot"&&_.tier==="hot"&&i++)}for(let _ of["hot","warm","cold"]){let b=p.filter(k=>k.newTier===_).map(k=>k.id);await this.store.setTierBulk(b,_)}let h=await this.store.getHotTier(e),m=0,y=[];for(let _ of h){let b=this.estimateTokens(_.content);_.pinned||(m+=b,m>this.config.hotBudgetTokens&&y.push(_._id))}y.length>0&&(await this.store.setTierBulk(y,"warm"),i+=y.length);try{o=await this.summarizeCold(e)}catch(_){ut.warn("Cold summarization failed",{agentId:e,error:String(_)})}}let a=new Date(Date.now()-this.config.coldRetentionDays*24*60*60*1e3);s=await this.store.deleteSummarizedOlderThan(e,a);let l=new Date(Date.now()-this.config.purgeRetentionDays*24*60*60*1e3),c=0;try{let u=await this.store.deletePurgedOlderThan(e,l);if(c=u.length,u.length>0){let d=u.map(f=>f.qdrantPointId).filter(Boolean);for(let f of d)await this.embedder.remove(f);ut.info("Hard-deleted purged records",{agentId:e,count:u.length})}}catch(u){ut.warn("Purge hard-delete phase failed",{agentId:e,error:String(u)})}return{promoted:t,demoted:i,summarized:o,cleaned:s,purged:c}}async dream(){if(!this.dreamConfig?.enabled)return{merged:0,contradictions:0,promoted:0,flaggedForReview:0,errors:[]};let e=Date.now(),t=0,i=0,r=0,o=0,s=[];try{let l=await this.store.getAgentIds(),c=await this.filterActiveAgents(l);for(let u of c)try{let d=await this.mergeDuplicates(u);t+=d.merged;let f=await this.detectContradictions(u);i+=f.resolved,o+=f.flagged;let p=await this.promotePatterns(u);r+=p.promoted}catch(d){s.push(`${u}: ${d}`),ut.error("autoDream failed for agent",{agentId:u,error:String(d)})}}catch(l){s.push(`global: ${l}`)}return t+i+r+o>0&&ut.info("autoDream complete",{durationMs:Date.now()-e,merged:t,contradictions:i,promoted:r,flaggedForReview:o,errors:s.length}),{merged:t,contradictions:i,promoted:r,flaggedForReview:o,errors:s}}async mergeDuplicates(e){let t=this.dreamConfig,i=await this.store.getByTiersForAgent(e,["hot","warm"]);if(i.length<2)return{merged:0};let r=new Set,o=0,s=0;for(let a of i){if(s>=t.maxClustersPerRun)break;if(r.has(a.qdrantPointId))continue;let c=(await this.embedder.findSimilar(a.qdrantPointId,e,t.similarityThreshold,10)).filter(A=>!r.has(A.pointId));if(c.length===0)continue;r.add(a.qdrantPointId);for(let A of c)r.add(A.pointId);let u=c.map(A=>new DL(A.mongoId)),d=await this.store.getByIds(u),f=[a,...d],h=["Merge the following duplicate or overlapping memories into a single consolidated record.","Preserve all unique details. Discard exact duplicates. Be concise.","",f.map(A=>`- [${A.type}/${A.importance}] ${A.content}`).join(`
399
439
  `)].join(`
400
- `),f=ri({prompt:m,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),y="";for await(let I of f){let N=I;if(N.type==="result"){let D=N;D.subtype==="success"&&D.result&&(y=D.result)}}if(!y)continue;let w=this.highestImportance(h),S=crypto.randomUUID(),_=await this.store.save(e,{content:y,type:a.type,topic:a.topic,importance:w},S);await this.embedder.upsert(S,y,{agentId:e,mongoId:_._id.toString(),type:a.type,topic:a.topic,tier:"hot",importance:w,createdAt:Math.floor(Date.now()/1e3)});let v=h.map(I=>I._id);await this.store.markSuperseded(v,_._id),i+=h.length,o++}return i>0&&Me.info("autoDream: duplicates merged",{agentId:e,merged:i,clusters:o}),{merged:i}}highestImportance(e){let t=["critical","high","medium","low"];for(let s of t)if(e.some(r=>r.importance===s))return s;return"medium"}async detectContradictions(e){let t=this.dreamConfig,s=await this.store.getFactsAndDecisionsByTopic(e),r=0,i=0,o=0,a=new Set;for(let[l,c]of s){if(o>=t.maxContradictionPairsPerRun)break;if(!(c.length<2)){for(let d=0;d<c.length-1;d++)if(!a.has(c[d]._id.toString())){for(let u=d+1;u<c.length&&!(o>=t.maxContradictionPairsPerRun);u++){if(a.has(c[u]._id.toString()))continue;let h=c[d],p=c[u],m=["Do these two memories contradict each other?","",`Memory A (${h.type}, created ${h.createdAt.toISOString()}):`,h.content,"",`Memory B (${p.type}, created ${p.createdAt.toISOString()}):`,p.content,"","Reply with exactly one of:",`- "NO" if they don't contradict`,'- "A_WINS" if Memory A is more current/accurate','- "B_WINS" if Memory B is more current/accurate',`- "UNCLEAR" if they contradict but you can't determine which is correct`].join(`
401
- `),f=ri({prompt:m,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),y="";for await(let w of f){let S=w;if(S.type==="result"){let _=S;_.subtype==="success"&&_.result&&(y=_.result.trim().toUpperCase())}}o++,y.includes("A_WINS")?(await this.store.markSuperseded([p._id],h._id),a.add(p._id.toString()),r++):y.includes("B_WINS")?(await this.store.markSuperseded([h._id],p._id),a.add(h._id.toString()),r++):y.includes("UNCLEAR")&&(await this.store.flagForReview([h._id,p._id]),a.add(h._id.toString()),a.add(p._id.toString()),i+=2)}if(o>=t.maxContradictionPairsPerRun)break}}}return(r>0||i>0)&&Me.info("autoDream: contradictions processed",{agentId:e,resolved:r,flagged:i,pairsChecked:o}),{resolved:r,flagged:i}}async promotePatterns(e){let t=this.dreamConfig,s=await this.store.getInteractionsByTopic(e),r=0;for(let[i,o]of s){if(r>=t.maxPromotionsPerRun)break;let a=new Set(o.map(w=>w.sourceThread).filter(Boolean));if(a.size<t.patternMinCount)continue;let d=o.sort((w,S)=>S.createdAt.getTime()-w.createdAt.getTime()).slice(0,10).map(w=>`- [${w.importance}] ${w.content}`).join(`
402
- `),u=[`These ${o.length} interactions across ${a.size} conversations share topic "${i}".`,"Generate a single fact that captures the recurring pattern or insight.","Be concise \u2014 one to three sentences.","",d].join(`
403
- `),h=ri({prompt:u,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),p="";for await(let w of h){let S=w;if(S.type==="result"){let _=S;_.subtype==="success"&&_.result&&(p=_.result)}}if(!p)continue;let m=crypto.randomUUID(),f=await this.store.save(e,{content:p,type:"fact",topic:i,importance:"medium"},m);await this.embedder.upsert(m,p,{agentId:e,mongoId:f._id.toString(),type:"fact",topic:i,tier:"hot",importance:"medium",createdAt:Math.floor(Date.now()/1e3)});let y=o.map(w=>w._id);await this.store.markSuperseded(y,f._id),r++}return r>0&&Me.info("autoDream: patterns promoted",{agentId:e,promoted:r}),{promoted:r}}async summarizeCold(e){let t=await this.store.getColdTopics(e),s=0;for(let r of t){let i=await this.store.getColdByTopic(e,r);if(i.length<this.config.coldSummaryMinRecords)continue;let o=i.map(h=>`- [${h.type}/${h.importance}] ${h.content}`).join(`
404
- `),a=[`Summarize the following memory entries for agent ${e} about topic "${r}".`,"Preserve key facts, decisions, and outcomes. Discard routine interactions.","Be concise \u2014 aim for 2-5 sentences.","",o].join(`
405
- `),l=ri({prompt:a,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),c="";for await(let h of l){let p=h;if(p.type==="result"){let m=p;m.subtype==="success"&&m.result&&(c=m.result)}}if(!c)continue;let d=crypto.randomUUID(),u=await this.store.save(e,{content:c,type:"summary",topic:r,importance:"medium"},d);await this.store.setTier(u._id,"warm"),await this.embedder.upsert(d,c,{agentId:e,mongoId:u._id.toString(),type:"summary",topic:r,tier:"warm",importance:"medium",createdAt:Math.floor(Date.now()/1e3)}),await this.store.markSummarized(i.map(h=>h._id),u._id),s+=i.length}return s}};M();import{createServer as Eb}from"node:http";var pf=k("admin-api"),oi=class{server;port;token;agentDefs;agentVersions;onReload;constructor(e,t,s,r,i){this.port=e,this.token=t,this.agentDefs=s,this.agentVersions=r,this.onReload=i,this.server=Eb((o,a)=>this.handleRequest(o,a))}async start(){return new Promise(e=>{this.server.listen(this.port,()=>{pf.info("Admin API started",{port:this.port}),e()})})}stop(){this.server.close()}async handleRequest(e,t){let s=e.headers.authorization;if(!s||s!==`Bearer ${this.token}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}let r=new URL(e.url??"/",`http://localhost:${this.port}`),i=r.pathname,o=e.method??"GET";try{if(i==="/admin/agents"&&o==="GET")return await this.listAgents(t);if(i==="/admin/agents"&&o==="POST")return await this.createAgent(e,t);let a=i.match(/^\/admin\/agents\/([^/]+)$/);if(a){let u=decodeURIComponent(a[1]);if(o==="GET")return await this.getAgent(u,t);if(o==="PATCH")return await this.updateAgent(u,e,t);if(o==="DELETE")return await this.deleteAgent(u,t)}let l=i.match(/^\/admin\/agents\/([^/]+)\/(enable|disable)$/);if(l&&o==="POST"){let u=decodeURIComponent(l[1]),h=l[2];return await this.toggleAgent(u,h,t)}let c=i.match(/^\/admin\/agents\/([^/]+)\/history$/);if(c&&o==="GET"){let u=decodeURIComponent(c[1]),h=parseInt(r.searchParams.get("limit")??"10",10);return await this.agentHistory(u,h,t)}let d=i.match(/^\/admin\/agents\/([^/]+)\/rollback$/);if(d&&o==="POST"){let u=decodeURIComponent(d[1]);return await this.rollbackAgent(u,e,t)}if(i==="/admin/servers"&&o==="GET")return await this.listServers(t);t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}catch(a){pf.error("Admin API error",{error:String(a),path:i,method:o}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))}}async readBody(e){return new Promise((t,s)=>{let r=[];e.on("data",i=>r.push(i)),e.on("end",()=>{try{t(JSON.parse(Buffer.concat(r).toString()))}catch{s(new Error("Invalid JSON"))}}),e.on("error",s)})}json(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s))}async saveVersion(e,t){let s=await this.agentDefs.findOne({_id:e});s&&await this.agentVersions.insertOne({agentId:e,snapshot:s,changedFields:t,createdAt:new Date})}async listAgents(e){let t=await this.agentDefs.find().toArray();this.json(e,200,t)}async getAgent(e,t){let s=await this.agentDefs.findOne({_id:e});if(!s)return this.json(t,404,{error:"Agent not found"});this.json(t,200,s)}async createAgent(e,t){let s=await this.readBody(e);if(!s._id||!s.name||!s.model)return this.json(t,400,{error:"Required: _id, name, model"});if(await this.agentDefs.findOne({_id:s._id}))return this.json(t,409,{error:"Agent already exists"});let i=new Date,o={_id:s._id,name:s.name,model:s.model,icon:s.icon??X.icon,channels:s.channels??[],passiveChannels:s.passiveChannels??X.passiveChannels,keywords:s.keywords??X.keywords,isDefault:s.isDefault??!1,coreServers:s.coreServers??[],delegateServers:s.delegateServers??[],delegatePrompts:s.delegatePrompts??X.delegatePrompts,plugins:s.plugins,metadata:s.metadata,soul:s.soul??"",systemPrompt:s.systemPrompt??"",schedule:s.schedule??X.schedule,subscribe:s.subscribe,budgetUsd:s.budgetUsd??X.budgetUsd,maxTurns:s.maxTurns??X.maxTurns,maxConcurrent:s.maxConcurrent??X.maxConcurrent,timeoutMs:s.timeoutMs??X.timeoutMs,disabled:s.disabled??!1,slackBot:s.slackBot,createdAt:i,updatedAt:i,updatedBy:"admin-api"};await this.agentDefs.insertOne(o),this.onReload(),this.json(t,201,o)}async updateAgent(e,t,s){let r=await this.readBody(t);if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found"});delete r._id,delete r.createdAt;let o=Object.keys(r);await this.saveVersion(e,o),await this.agentDefs.updateOne({_id:e},{$set:{...r,updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload();let a=await this.agentDefs.findOne({_id:e});this.json(s,200,a)}async deleteAgent(e,t){if(!await this.agentDefs.findOne({_id:e}))return this.json(t,404,{error:"Agent not found"});await this.saveVersion(e,["_deleted"]),await this.agentDefs.deleteOne({_id:e}),this.onReload(),this.json(t,200,{deleted:e})}async toggleAgent(e,t,s){if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found"});await this.saveVersion(e,["disabled"]),await this.agentDefs.updateOne({_id:e},{$set:{disabled:t==="disable",updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload(),this.json(s,200,{[t+"d"]:e})}async agentHistory(e,t,s){let r=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).limit(t).toArray();this.json(s,200,r)}async rollbackAgent(e,t,s){let i=(await this.readBody(t)).version_index??0;if(typeof i!="number"||i<0||!Number.isInteger(i))return this.json(s,400,{error:"version_index must be a non-negative integer"});let o=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).skip(i).limit(1).toArray();if(o.length===0)return this.json(s,404,{error:"No version found at that index"});if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found \u2014 cannot rollback a deleted agent"});await this.saveVersion(e,["_rollback"]);let{_id:l,...c}=o[0].snapshot;await this.agentDefs.updateOne({_id:e},{$set:{...c,updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload();let d=await this.agentDefs.findOne({_id:e});this.json(s,200,d)}async listServers(e){this.json(e,200,{message:"Server registry \u2014 use agent_definitions.coreServers/delegateServers fields"})}};M();var Et=k("activity-logger"),ai=class{db;collection;buffer=[];flushTimer=null;config;connected=!1;constructor(e,t){this.db=e,this.config=t}async connect(){if(!this.config.enabled){Et.info("Activity log disabled");return}this.collection=this.db.collection("activity_log"),await this.collection.createIndex({agentId:1,timestamp:-1}),await this.collection.createIndex({timestamp:1},{expireAfterSeconds:this.config.retentionDays*24*60*60}),this.connected=!0,this.flushTimer=setInterval(()=>{this.flush().catch(t=>Et.warn("Periodic flush failed",{error:String(t)}))},this.config.flushIntervalMs);let e=await this.collection.estimatedDocumentCount();Et.info("Activity log connected",{records:e,retentionDays:this.config.retentionDays})}record(e){!this.config.enabled||!this.connected||(this.buffer.push(e),this.buffer.length>=this.config.bufferSize&&this.flush().catch(t=>Et.warn("Buffer-full flush failed",{error:String(t)})))}async flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0);try{await this.collection.insertMany(e,{ordered:!1})}catch(t){Et.warn("Bulk write failed, retrying once",{count:e.length,error:String(t)});try{await this.collection.insertMany(e,{ordered:!1})}catch(s){Et.error("Bulk write failed after retry, dropping batch",{count:e.length,error:String(s)})}}}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.buffer.length>0&&(Et.info("Draining activity buffer on shutdown",{count:this.buffer.length}),await this.flush()),this.connected=!1}};M();var mf={id:"001-backfill-home-base",async run(n,e){let t=n.collection("agent_definitions"),s=t.find({homeBase:{$exists:!1}}),r=0,i=0;for await(let o of s){let a=o.channels?.find(l=>l.startsWith("agent-"))??o.channels?.[0];if(!a){e.warn("Cannot backfill homeBase \u2014 no channels",{agentId:o._id}),i++;continue}await t.updateOne({_id:o._id},{$set:{homeBase:a}}),r++}e.info("Backfill complete",{migration:"001-backfill-home-base",updated:r,skipped:i})}};var ci=k("migrations"),Nb=[mf];async function gf(n,e=Nb){let t=n.collection("migrations");for(let s of e){if(await t.findOne({_id:s.id})){ci.debug("Migration already applied, skipping",{id:s.id});continue}ci.info("Running migration",{id:s.id}),await s.run(n,ci),await t.insertOne({_id:s.id,ranAt:new Date}),ci.info("Migration applied",{id:s.id})}}M();var Nt=k("first-boot"),yf="hive/first-boot-greeting-sent",wf="chief-of-staff";async function Sf(n,e,t,s){let r;try{r=await n.read(yf)}catch(d){Nt.warn("First-boot flag read failed \u2014 skipping check this startup",{error:String(d)});return}if(r){Nt.debug("First-boot greeting already sent \u2014 skipping");return}let i=e.get(wf),o=i?.homeBase??i?.channels?.[0];if(!o){Nt.warn("First-boot: CoS agent has no homeBase or channels \u2014 skipping, will retry next startup");return}let a=s.get(o);if(!a){Nt.warn("First-boot: could not resolve channel ID for CoS home channel",{channelName:o});return}try{await n.write(yf,"true","system")}catch(d){Nt.error("First-boot: flag write failed \u2014 aborting greeting dispatch",{error:String(d)});return}let l=Date.now(),c={id:`system:first-boot:${l}`,text:"First boot detected. Greet the owner and offer onboarding.",source:{kind:"slack",id:a,label:o,adapterId:"slack"},sender:"system",threadId:`first-boot:${l}`,timestamp:new Date,meta:{targetAgentId:wf,systemTrigger:"first-boot"}};Nt.info("First-boot: dispatching CoS greeting",{channel:o,channelId:a}),t.dispatch(c).catch(d=>{Nt.error("First-boot greeting dispatch failed",{error:String(d)})})}M();import{createServer as xb}from"node:http";var Ka=k("slack-internal-api"),li=class{port;authToken;gateway;agentManager;server=null;constructor(e){this.port=e.port,this.authToken=e.authToken,this.gateway=e.gateway,this.agentManager=e.agentManager}async start(){this.server=xb((e,t)=>{this.handleRequest(e,t).catch(s=>{Ka.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),Ka.info("Slack internal API started",{port:this.port})}async stop(){this.server&&(this.server.close(),this.server=null),Ka.info("Slack internal API stopped")}async handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"method not allowed"}));return}if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"unauthorized"}));return}let r=new URL(e.url??"/",`http://127.0.0.1:${this.port}`),i=await this.readBody(e),o;try{o=JSON.parse(i)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"invalid JSON body"}));return}switch(r.pathname){case"/internal/slack/send":return this.handleSend(o,t);case"/internal/slack/read":return this.handleRead(o,t);case"/internal/slack/channels":return this.handleChannels(o,t);case"/internal/slack/users":return this.handleUsers(o,t);case"/internal/slack/search":t.writeHead(501,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"search deferred pending tool-parity audit"}));return;default:t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"not found"}))}}async handleSend(e,t){let{agent_id:s,channel:r,text:i,thread_ts:o,blocks:a,force_root:l}=e;if(typeof r!="string"||!r){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"channel is required"}));return}if(typeof i!="string"||!i){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"text is required"}));return}let c=await this.gateway.resolveChannelId(r);if(!c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:`unknown channel: ${r}`}));return}let d=o;if(!d&&!l&&typeof s=="string"&&s){let m=this.agentManager.getActiveWorkItems(s).filter(f=>f.source.id===c);if(m.length>0){let f=m[m.length-1];d=f.meta?.slackThreadTs??f.meta?.slackTs}}let u=await this.gateway.postAndRegister(c,i,d),h=u.ok?{ok:!0,ts:u.ts,channel:c}:{ok:!1,error:u.error};t.writeHead(u.ok?200:500,{"Content-Type":"application/json"}),t.end(JSON.stringify(h))}async handleRead(e,t){let{channel:s,limit:r}=e;if(typeof s!="string"||!s){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"channel is required"}));return}let i=await this.gateway.readChannel(s,typeof r=="number"?r:void 0);if(i===void 0){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"failed to read channel history"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,messages:i}))}async handleChannels(e,t){let{query:s}=e,r=await this.gateway.listChannels(typeof s=="string"?s:void 0);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channels:r}))}async handleUsers(e,t){let{user:s}=e;if(typeof s!="string"||!s){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"user is required"}));return}let r=await this.gateway.readUser(s);if(r===void 0){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"failed to look up user"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,user:r}))}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();var Ha=k("slack-scope-preflight"),Ob=["chat:write","chat:write.customize","channels:history","channels:read","users:read"];async function kf(n,e=Ob){let t=await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${n}`}}),s=await t.json();if(!s.ok){Ha.warn("Slack auth.test failed \u2014 skipping scope preflight",{error:s.error??"unknown"});return}let i=(t.headers.get("x-oauth-scopes")??"").split(",").map(a=>a.trim()).filter(Boolean),o=e.filter(a=>!i.includes(a));if(o.length>0){Ha.warn("Slack bot token missing recommended scopes \u2014 some features may degrade silently",{missing:o,required:[...e],note:"Identity-mode posts fall back to plain bot identity if chat:write.customize is missing. Grant the scope and reinstall the app to enable it."});return}Ha.info("Slack scope preflight passed",{required:[...e]})}var x=k("index");function tm(n){for(let e of n)for(let t of[pn(e),Oc(e),Mc(e)])try{pv(t,{recursive:!0})}catch(s){x.warn("Failed to provision agent dir",{agentId:e,dir:t,err:s})}}async function yv(){x.info("Hive starting up",{instance:g.instance.id,portBase:g.instance.portBase}),Tc(em(V,"dist","index.js"))&&Tc(em(cs,"dist","index.js"))&&(x.error("Conflicting engine layouts detected \u2014 both <hiveHome>/dist/ and <hiveHome>/.hive/dist/ exist. Remove the old <hiveHome>/dist/ before starting 0.2.0.",{hiveHome:V,engineDir:cs}),process.exit(1)),qc(V,hn),Fc(V),$c(V),Hc(hn,Xe),g.gemini.apiKey&&(Rh(g.gemini.apiKey),x.info("Gemini vision enabled",{model:g.gemini.visionModel}));let n=new gv(g.mongo.uri,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0});await n.connect();let e=n.db(g.mongo.dbName),t=e.collection("agent_definitions");await t.createIndex({channels:1}),await t.createIndex({disabled:1}),await gf(e);let s,r,i,o=null,a,l=async()=>{if(!r||!i)return;x.info("Hot-reloading agent registry...");let O=await s.load();if(O.added.length&&x.info("New agents online",{agents:O.added}),O.updated.length&&x.info("Agents updated",{agents:O.updated}),tm(s.listIds()),O.removed.length){x.info("Agents removed",{agents:O.removed});for(let ue of O.removed)r.stopAgent(ue)}let B=s.getDisabled();for(let ue of B)r.stopAgent(ue.id);B.length&&x.info("Disabled agents stopped",{agents:B.map(ue=>ue.id)}),await i.reloadSchedules(),r.reloadSkills(),r.rescanPlugins()};s=new yr(t,()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),await s.load(),x.info("Agent registry loaded",{agents:s.listIds()}),tm(s.listIds());let c=new Lr(e);await c.init();let d=new si(e);await d.init(),c.memoryStore=d;let u=new ni,h=new ii(d,u,{hotBudgetTokens:g.memory.hotBudgetTokens,sweepIntervalHours:g.memory.sweepIntervalHours,hotThreshold:g.memory.hotThreshold,warmThreshold:g.memory.warmThreshold,recencyHalfLifeDays:g.memory.recencyHalfLifeDays,coldSummaryMinRecords:g.memory.coldSummaryMinRecords,coldRetentionDays:g.memory.coldRetentionDays,purgeRetentionDays:g.memory.purgeRetentionDays},g.autoDream,async()=>new Set(s.listIds()));x.info("Structured memory lifecycle enabled");let p=new Br(e);await p.init();let m;if(g.activity.enabled&&(m=new ai(e,g.activity),await m.connect()),g.linear.apiKey){let O=new Rr(g.linear.apiKey,g.linear.teamId||void 0);x.info("Linear client configured")}let f=new Wr(g.taskLedger.apiUrl,g.taskLedger.apiKey);f.isConfigured&&x.info("Task ledger client configured",{apiUrl:g.taskLedger.apiUrl});let y=new Gr(g.taskLedger.apiUrl,g.taskLedger.agentKeys,g.taskLedger.apiKey);y.isConfigured&&x.info("Task ledger auto-tracking enabled",{apiUrl:g.taskLedger.apiUrl,agents:Object.keys(g.taskLedger.agentKeys)});let w,S;if(g.codeIndex.enabled){let{CodeIndexPrefetcher:O}=await Promise.resolve().then(()=>(vf(),_f)),{KnowledgeExtractor:B}=await Promise.resolve().then(()=>(If(),Tf));w=new O({db:e,qdrantUrl:process.env.QDRANT_URL??"http://localhost:6333",ollamaUrl:process.env.OLLAMA_URL??"http://localhost:11434",scoreThreshold:g.codeIndex.scoreThreshold,prefetchLimit:g.codeIndex.prefetchLimit}),g.codeIndex.sessionKnowledge.enabled&&(S=new B(d,u)),x.info("Code index integration enabled",{prefetch:!0,sessionKnowledge:S!==void 0})}r=new Or(s,c,p,m,w);let _=new $r(r,c,s),v=new jr(s,r,_,g.defaultAgent,y.isConfigured?y:void 0),I=new Vr(g.background.port,g.background.authToken,g.tasksDir.background,O=>v.dispatch(O).catch(B=>{x.error("Background task completion dispatch failed",{error:String(B)})}));await I.start(),await I.scanOrphans(),x.info("Background task manager started",{port:g.background.port});let N=new Jr(g.codeTask.port,g.codeTask.authToken,g.codeTask.pluginDirs,g.codeTask.maxConcurrent,g.tasksDir.code,O=>v.dispatch(O).catch(B=>{x.error("Code task completion dispatch failed",{error:String(B)})}),{prefetcher:w,knowledgeExtractor:S,maxLifetimeMs:g.codeTask.maxLifetimeMs,staleGraceMs:g.codeTask.staleGraceMs});await N.start(),await N.scanOrphans(),x.info("Code task manager started",{port:g.codeTask.port});let D;g.recall.apiKey&&(D=new zr(g.recall.monitorPort,g.recall.webhookSecret,O=>v.dispatch(O).catch(B=>{x.error("Meeting monitor dispatch failed",{error:String(B)})})),await D.start(),x.info("Meeting monitor started",{port:g.recall.monitorPort}),g.recall.apiKey&&!g.recall.webhookSecret&&x.error("Real-time transcript delivery disabled \u2014 RECALL_WEBHOOK_SECRET not set")),Tc(Xe)&&(mv(Xe,{recursive:!0},()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),x.info("Skills hot-reload enabled",{watched:Xe})),process.on("SIGUSR1",()=>l()),x.info("Hot-reload enabled",{signal:"SIGUSR1"});let A=g.sms.lines.map(O=>O.slackChannel).filter(Boolean),E=new Dr(g.slack.appToken,g.slack.botToken),G=new qr(E,s,A,"slack");v.registerAdapter(G),v.setSlackAdapter(G),await G.start(O=>{v.dispatch(O).catch(B=>{x.error("Slack dispatch failed",{error:String(B),source:O.source.label})})}),x.info("Slack adapter connected");let W=new Map;try{let O;do{let ue=await E.client.conversations.list({types:"public_channel,private_channel",limit:1e3,cursor:O});for(let $t of ue.channels??[])$t.name&&$t.id&&W.set($t.name,$t.id);O=ue.response_metadata?.next_cursor||void 0}while(O);let B=g.slack.auditChannel;a=B?W.get(B):void 0,v.setAuditChannel(G,W,a),x.info("Audit channel configured",{channels:W.size,fallback:B||null,fallbackResolved:!!a})}catch(O){x.warn("Failed to configure audit channel",{error:String(O)})}let $=null;g.slack.localMcpServer&&(await kf(g.slack.botToken),$=new li({port:g.slackInternal.port,authToken:g.slackInternal.authToken,gateway:E,agentManager:r}),await $.start(),x.info("Slack internal API started",{port:g.slackInternal.port}));let le=new Fr(g.quo.apiKey,g.sms.lines);v.registerAdapter(le),g.quo.apiKey&&g.sms.lines.length>0&&(await le.start(O=>{v.dispatch(O).catch(B=>{x.error("SMS dispatch failed",{error:String(B),source:O.source.label})})}),x.info("SMS adapter started",{lines:g.sms.lines.length}));let Ie;g.imessage.enabled&&(Ie=new Hr(g.imessage,e,E,g.instance.id),v.registerAdapter(Ie),await Ie.start(O=>{v.dispatch(O).catch(B=>{x.error("iMessage dispatch failed",{error:String(B)})})}),x.info("iMessage adapter started"));let{AgentRunner:ge}=await Promise.resolve().then(()=>(La(),Lh));ge.registryRef=s;let{TeamStore:ln}=await Promise.resolve().then(()=>(Nf(),Ef)),{CommandRegistry:os}=await Promise.resolve().then(()=>(Of(),xf)),mt=new ln(e);await mt.init();let Ti=O=>{let B=s.getAll(),ue=B.find(Ai=>Ai.id===O);if(ue)return{id:ue.id,name:ue.name};let $t=O.toLowerCase(),Ii=B.find(Ai=>Ai.name.toLowerCase()===$t);return Ii?{id:Ii.id,name:Ii.name}:null},Qe=new os(mt,Ti);v.setTeamStore(mt),x.info("Team layer initialized");let{registerPluginCommands:dn}=await Promise.resolve().then(()=>(kr(),gh));await dn(r.getPlugins(),Qe);let Be;if(g.ws.enabled){let{WsAdapter:O}=await Promise.resolve().then(()=>(qp(),jp));Be=new O(g.ws.port,{teamStore:mt,commandRegistry:Qe,agentRegistry:s,agentManager:r}),v.registerAdapter(Be),await Be.start(B=>{v.dispatch(B).catch(ue=>{x.error("WS dispatch failed",{error:String(ue),source:B.source.label})})}),x.info("WebSocket adapter started",{port:g.ws.port})}let as;if(g.ws.enabled){let{startBeekeeperRegistration:O}=await Promise.resolve().then(()=>(Kp(),Fp)),B=`hive-${g.instance.id}`;as=O({beekeeperPort:g.beekeeper.port,wsPort:g.ws.port,capabilityName:B}),x.info("Beekeeper registration loop started",{beekeeperPort:g.beekeeper.port,wsPort:g.ws.port,capabilityName:B})}let Y;if(g.voice.enabled&&g.voice.serverSecret){let{VoiceAdapter:O}=await Promise.resolve().then(()=>(Zp(),Xp));Y=new O(g.voice.port,g.voice.serverSecret,s,c),await Y.start(),x.info("Voice adapter started",{port:g.voice.port})}i=new Pr(r,c,_,s,O=>{v.dispatch(O).catch(B=>{x.error("Callback dispatch failed",{error:String(B)})})}),await i.connectDb(e),i.start(),x.info("Scheduler started"),await s.startWatching();let L;g.adminApi.token&&(L=new oi(g.adminApi.port,g.adminApi.token,t,e.collection("agent_definition_versions"),()=>l()),await L.start(),x.info("Admin API started",{port:g.adminApi.port}));let P=new Xr({maxAttempts:g.sweeper.retryMaxAttempts,baseDelayMs:g.sweeper.retryBaseDelayMs});v.setRetryQueue(P);let de=[G],un=[E],Pt=new Zr({intervalMs:g.sweeper.intervalMs,threadTtlMs:g.sweeper.threadTtlMs,taskFileTtlMs:g.sweeper.taskFileTtlMs,meetingSessionTtlMs:g.sweeper.meetingSessionTtlMs,cacheTtlMs:g.sweeper.cacheTtlMs,memorySweepIntervalHours:g.memory.sweepIntervalHours,dreamConfig:g.autoDream},{dispatcher:v,slackAdapters:de,bgTaskManager:I,codeTaskManager:N,meetingMonitor:D,taskLedger:y.isConfigured?y:void 0,slackGateways:un,agentManager:r,retryQueue:P,memoryLifecycle:h},f.isConfigured?f:void 0);Pt.start(),x.info("Sweeper started",{intervalMs:g.sweeper.intervalMs});let Ic=new ti(g.retention,{hiveHome:V,report:async O=>{a?await E.postMessage(a,O).catch(B=>x.warn("Retention report: Slack post failed",{error:String(B)})):x.info("Retention report (no audit channel configured)",{text:O})}});Ic.start(),x.info("Retention sweeper started",{enabled:g.retention.enabled,intervalMs:g.retention.intervalMs});let Ac=async O=>{x.info("Shutdown signal received",{signal:O}),Pt.stop(),Ic.stop(),L?.stop(),s.stopWatching(),await le.stop(),$&&await $.stop(),Ie&&await Ie.stop(),as?.stop(),Be&&await Be.stop(),Y?.stop(),i.stop(),await I.stop(),await N.stop(),await w?.close(),D?.stop(),r.stopAll(),m&&await m.stop(),await p.close(),await d.close(),await G.stop(),await n.close(),x.info("Hive shut down cleanly"),process.exit(0)};process.on("SIGTERM",()=>Ac("SIGTERM")),process.on("SIGINT",()=>Ac("SIGINT")),x.info("Hive is running"),Sf(c,s,v,W).catch(O=>{x.error("First-boot check failed",{error:String(O)})})}process.on("unhandledRejection",n=>{x.error("Unhandled promise rejection",{error:String(n),stack:n instanceof Error?n.stack:void 0})});yv().catch(n=>{x.error("Fatal startup error",{error:String(n)}),process.exit(1)});
440
+ `),m=hl({prompt:h,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),y="";for await(let A of m){let j=A;if(j.type==="result"){let L=j;L.subtype==="success"&&L.result&&(y=L.result)}}if(!y)continue;let _=this.highestImportance(f),b=crypto.randomUUID(),k=await this.store.save(e,{content:y,type:a.type,topic:a.topic,importance:_},b);await this.embedder.upsert(b,y,{agentId:e,mongoId:k._id.toString(),type:a.type,topic:a.topic,tier:"hot",importance:_,createdAt:Math.floor(Date.now()/1e3)});let O=f.map(A=>A._id);await this.store.markSuperseded(O,k._id),o+=f.length,s++}return o>0&&ut.info("autoDream: duplicates merged",{agentId:e,merged:o,clusters:s}),{merged:o}}highestImportance(e){let t=["critical","high","medium","low"];for(let i of t)if(e.some(r=>r.importance===i))return i;return"medium"}async detectContradictions(e){let t=this.dreamConfig,i=await this.store.getFactsAndDecisionsByTopic(e),r=0,o=0,s=0,a=new Set;for(let[l,c]of i){if(s>=t.maxContradictionPairsPerRun)break;if(!(c.length<2)){for(let u=0;u<c.length-1;u++)if(!a.has(c[u]._id.toString())){for(let d=u+1;d<c.length&&!(s>=t.maxContradictionPairsPerRun);d++){if(a.has(c[d]._id.toString()))continue;let f=c[u],p=c[d],h=["Do these two memories contradict each other?","",`Memory A (${f.type}, created ${f.createdAt.toISOString()}):`,f.content,"",`Memory B (${p.type}, created ${p.createdAt.toISOString()}):`,p.content,"","Reply with exactly one of:",`- "NO" if they don't contradict`,'- "A_WINS" if Memory A is more current/accurate','- "B_WINS" if Memory B is more current/accurate',`- "UNCLEAR" if they contradict but you can't determine which is correct`].join(`
441
+ `),m=hl({prompt:h,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),y="";for await(let _ of m){let b=_;if(b.type==="result"){let k=b;k.subtype==="success"&&k.result&&(y=k.result.trim().toUpperCase())}}s++,y.includes("A_WINS")?(await this.store.markSuperseded([p._id],f._id),a.add(p._id.toString()),r++):y.includes("B_WINS")?(await this.store.markSuperseded([f._id],p._id),a.add(f._id.toString()),r++):y.includes("UNCLEAR")&&(await this.store.flagForReview([f._id,p._id]),a.add(f._id.toString()),a.add(p._id.toString()),o+=2)}if(s>=t.maxContradictionPairsPerRun)break}}}return(r>0||o>0)&&ut.info("autoDream: contradictions processed",{agentId:e,resolved:r,flagged:o,pairsChecked:s}),{resolved:r,flagged:o}}async promotePatterns(e){let t=this.dreamConfig,i=await this.store.getInteractionsByTopic(e),r=0;for(let[o,s]of i){if(r>=t.maxPromotionsPerRun)break;let a=new Set(s.map(_=>_.sourceThread).filter(Boolean));if(a.size<t.patternMinCount)continue;let u=s.sort((_,b)=>b.createdAt.getTime()-_.createdAt.getTime()).slice(0,10).map(_=>`- [${_.importance}] ${_.content}`).join(`
442
+ `),d=[`These ${s.length} interactions across ${a.size} conversations share topic "${o}".`,"Generate a single fact that captures the recurring pattern or insight.","Be concise \u2014 one to three sentences.","",u].join(`
443
+ `),f=hl({prompt:d,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),p="";for await(let _ of f){let b=_;if(b.type==="result"){let k=b;k.subtype==="success"&&k.result&&(p=k.result)}}if(!p)continue;let h=crypto.randomUUID(),m=await this.store.save(e,{content:p,type:"fact",topic:o,importance:"medium"},h);await this.embedder.upsert(h,p,{agentId:e,mongoId:m._id.toString(),type:"fact",topic:o,tier:"hot",importance:"medium",createdAt:Math.floor(Date.now()/1e3)});let y=s.map(_=>_._id);await this.store.markSuperseded(y,m._id),r++}return r>0&&ut.info("autoDream: patterns promoted",{agentId:e,promoted:r}),{promoted:r}}async summarizeCold(e){let t=await this.store.getColdTopics(e),i=0;for(let r of t){let o=await this.store.getColdByTopic(e,r);if(o.length<this.config.coldSummaryMinRecords)continue;let s=o.map(f=>`- [${f.type}/${f.importance}] ${f.content}`).join(`
444
+ `),a=[`Summarize the following memory entries for agent ${e} about topic "${r}".`,"Preserve key facts, decisions, and outcomes. Discard routine interactions.","Be concise \u2014 aim for 2-5 sentences.","",s].join(`
445
+ `),l=hl({prompt:a,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),c="";for await(let f of l){let p=f;if(p.type==="result"){let h=p;h.subtype==="success"&&h.result&&(c=h.result)}}if(!c)continue;let u=crypto.randomUUID(),d=await this.store.save(e,{content:c,type:"summary",topic:r,importance:"medium"},u);await this.store.setTier(d._id,"warm"),await this.embedder.upsert(u,c,{agentId:e,mongoId:d._id.toString(),type:"summary",topic:r,tier:"warm",importance:"medium",createdAt:Math.floor(Date.now()/1e3)}),await this.store.markSummarized(o.map(f=>f._id),d._id),i+=o.length}return i}};R();import{createServer as PL}from"node:http";var OI=$("admin-api"),yl=class{server;port;token;agentDefs;agentVersions;onReload;constructor(e,t,i,r,o){this.port=e,this.token=t,this.agentDefs=i,this.agentVersions=r,this.onReload=o,this.server=PL((s,a)=>this.handleRequest(s,a))}async start(){return new Promise(e=>{this.server.listen(this.port,()=>{OI.info("Admin API started",{port:this.port}),e()})})}stop(){this.server.close()}async handleRequest(e,t){let i=e.headers.authorization;if(!i||i!==`Bearer ${this.token}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}let r=new URL(e.url??"/",`http://localhost:${this.port}`),o=r.pathname,s=e.method??"GET";try{if(o==="/admin/agents"&&s==="GET")return await this.listAgents(t);if(o==="/admin/agents"&&s==="POST")return await this.createAgent(e,t);let a=o.match(/^\/admin\/agents\/([^/]+)$/);if(a){let d=decodeURIComponent(a[1]);if(s==="GET")return await this.getAgent(d,t);if(s==="PATCH")return await this.updateAgent(d,e,t);if(s==="DELETE")return await this.deleteAgent(d,t)}let l=o.match(/^\/admin\/agents\/([^/]+)\/(enable|disable)$/);if(l&&s==="POST"){let d=decodeURIComponent(l[1]),f=l[2];return await this.toggleAgent(d,f,t)}let c=o.match(/^\/admin\/agents\/([^/]+)\/history$/);if(c&&s==="GET"){let d=decodeURIComponent(c[1]),f=parseInt(r.searchParams.get("limit")??"10",10);return await this.agentHistory(d,f,t)}let u=o.match(/^\/admin\/agents\/([^/]+)\/rollback$/);if(u&&s==="POST"){let d=decodeURIComponent(u[1]);return await this.rollbackAgent(d,e,t)}if(o==="/admin/servers"&&s==="GET")return await this.listServers(t);t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}catch(a){OI.error("Admin API error",{error:String(a),path:o,method:s}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))}}async readBody(e){return new Promise((t,i)=>{let r=[];e.on("data",o=>r.push(o)),e.on("end",()=>{try{t(JSON.parse(Buffer.concat(r).toString()))}catch{i(new Error("Invalid JSON"))}}),e.on("error",i)})}json(e,t,i){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(i))}async saveVersion(e,t){let i=await this.agentDefs.findOne({_id:e});i&&await this.agentVersions.insertOne({agentId:e,snapshot:i,changedFields:t,createdAt:new Date})}async listAgents(e){let t=await this.agentDefs.find().toArray();this.json(e,200,t)}async getAgent(e,t){let i=await this.agentDefs.findOne({_id:e});if(!i)return this.json(t,404,{error:"Agent not found"});this.json(t,200,i)}async createAgent(e,t){let i=await this.readBody(e);if(!i._id||!i.name||!i.model)return this.json(t,400,{error:"Required: _id, name, model"});if(await this.agentDefs.findOne({_id:i._id}))return this.json(t,409,{error:"Agent already exists"});let o=new Date,s={_id:i._id,name:i.name,model:i.model,icon:i.icon??me.icon,channels:i.channels??[],passiveChannels:i.passiveChannels??me.passiveChannels,keywords:i.keywords??me.keywords,isDefault:i.isDefault??!1,coreServers:i.coreServers??[],delegateServers:i.delegateServers??[],delegatePrompts:i.delegatePrompts??me.delegatePrompts,plugins:i.plugins,metadata:i.metadata,soul:i.soul??"",systemPrompt:i.systemPrompt??"",schedule:i.schedule??me.schedule,subscribe:i.subscribe,budgetUsd:i.budgetUsd??me.budgetUsd,maxTurns:i.maxTurns??me.maxTurns,maxConcurrent:i.maxConcurrent??me.maxConcurrent,timeoutMs:i.timeoutMs??me.timeoutMs,disabled:i.disabled??!1,slackBot:i.slackBot,createdAt:o,updatedAt:o,updatedBy:"admin-api"};await this.agentDefs.insertOne(s),this.onReload(),this.json(t,201,s)}async updateAgent(e,t,i){let r=await this.readBody(t);if(!await this.agentDefs.findOne({_id:e}))return this.json(i,404,{error:"Agent not found"});delete r._id,delete r.createdAt;let s=Object.keys(r);await this.saveVersion(e,s),await this.agentDefs.updateOne({_id:e},{$set:{...r,updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload();let a=await this.agentDefs.findOne({_id:e});this.json(i,200,a)}async deleteAgent(e,t){if(!await this.agentDefs.findOne({_id:e}))return this.json(t,404,{error:"Agent not found"});await this.saveVersion(e,["_deleted"]),await this.agentDefs.deleteOne({_id:e}),this.onReload(),this.json(t,200,{deleted:e})}async toggleAgent(e,t,i){if(!await this.agentDefs.findOne({_id:e}))return this.json(i,404,{error:"Agent not found"});await this.saveVersion(e,["disabled"]),await this.agentDefs.updateOne({_id:e},{$set:{disabled:t==="disable",updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload(),this.json(i,200,{[t+"d"]:e})}async agentHistory(e,t,i){let r=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).limit(t).toArray();this.json(i,200,r)}async rollbackAgent(e,t,i){let o=(await this.readBody(t)).version_index??0;if(typeof o!="number"||o<0||!Number.isInteger(o))return this.json(i,400,{error:"version_index must be a non-negative integer"});let s=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).skip(o).limit(1).toArray();if(s.length===0)return this.json(i,404,{error:"No version found at that index"});if(!await this.agentDefs.findOne({_id:e}))return this.json(i,404,{error:"Agent not found \u2014 cannot rollback a deleted agent"});await this.saveVersion(e,["_rollback"]);let{_id:l,...c}=s[0].snapshot;await this.agentDefs.updateOne({_id:e},{$set:{...c,updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload();let u=await this.agentDefs.findOne({_id:e});this.json(i,200,u)}async listServers(e){this.json(e,200,{message:"Server registry \u2014 use agent_definitions.coreServers/delegateServers fields"})}};R();var Dn=$("activity-logger"),vl=class{db;collection;buffer=[];flushTimer=null;config;connected=!1;constructor(e,t){this.db=e,this.config=t}async connect(){if(!this.config.enabled){Dn.info("Activity log disabled");return}this.collection=this.db.collection("activity_log"),await this.collection.createIndex({agentId:1,timestamp:-1}),await this.collection.createIndex({timestamp:1},{expireAfterSeconds:this.config.retentionDays*24*60*60}),this.connected=!0,this.flushTimer=setInterval(()=>{this.flush().catch(t=>Dn.warn("Periodic flush failed",{error:String(t)}))},this.config.flushIntervalMs);let e=await this.collection.estimatedDocumentCount();Dn.info("Activity log connected",{records:e,retentionDays:this.config.retentionDays})}record(e){!this.config.enabled||!this.connected||(this.buffer.push(e),this.buffer.length>=this.config.bufferSize&&this.flush().catch(t=>Dn.warn("Buffer-full flush failed",{error:String(t)})))}async flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0);try{await this.collection.insertMany(e,{ordered:!1})}catch(t){Dn.warn("Bulk write failed, retrying once",{count:e.length,error:String(t)});try{await this.collection.insertMany(e,{ordered:!1})}catch(i){Dn.error("Bulk write failed after retry, dropping batch",{count:e.length,error:String(i)})}}}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.buffer.length>0&&(Dn.info("Draining activity buffer on shutdown",{count:this.buffer.length}),await this.flush()),this.connected=!1}};R();var CI={id:"001-backfill-home-base",async run(n,e){let t=n.collection("agent_definitions"),i=t.find({homeBase:{$exists:!1}}),r=0,o=0;for await(let s of i){let a=s.channels?.find(l=>l.startsWith("agent-"))??s.channels?.[0];if(!a){e.warn("Cannot backfill homeBase \u2014 no channels",{agentId:s._id}),o++;continue}await t.updateOne({_id:s._id},{$set:{homeBase:a}}),r++}e.info("Backfill complete",{migration:"001-backfill-home-base",updated:r,skipped:o})}};var _l=$("migrations"),ML=[CI];async function NI(n,e=ML){let t=n.collection("migrations");for(let i of e){if(await t.findOne({_id:i.id})){_l.debug("Migration already applied, skipping",{id:i.id});continue}_l.info("Running migration",{id:i.id}),await i.run(n,_l),await t.insertOne({_id:i.id,ranAt:new Date}),_l.info("Migration applied",{id:i.id})}}R();var Pn=$("first-boot"),DI="hive/first-boot-greeting-sent",PI="chief-of-staff";async function MI(n,e,t,i){let r;try{r=await n.read(DI)}catch(u){Pn.warn("First-boot flag read failed \u2014 skipping check this startup",{error:String(u)});return}if(r){Pn.debug("First-boot greeting already sent \u2014 skipping");return}let o=e.get(PI),s=o?.homeBase??o?.channels?.[0];if(!s){Pn.warn("First-boot: CoS agent has no homeBase or channels \u2014 skipping, will retry next startup");return}let a=i.get(s);if(!a){Pn.warn("First-boot: could not resolve channel ID for CoS home channel",{channelName:s});return}try{await n.write(DI,"true","system")}catch(u){Pn.error("First-boot: flag write failed \u2014 aborting greeting dispatch",{error:String(u)});return}let l=Date.now(),c={id:`system:first-boot:${l}`,text:"First boot detected. Greet the owner and offer onboarding.",source:{kind:"slack",id:a,label:s,adapterId:"slack"},sender:"system",threadId:`first-boot:${l}`,timestamp:new Date,meta:{targetAgentId:PI,systemTrigger:"first-boot"}};Pn.info("First-boot: dispatching CoS greeting",{channel:s,channelId:a}),t.dispatch(c).catch(u=>{Pn.error("First-boot greeting dispatch failed",{error:String(u)})})}R();import{createServer as LL}from"node:http";var dy=$("slack-internal-api"),wl=class{port;authToken;gateway;agentManager;server=null;constructor(e){this.port=e.port,this.authToken=e.authToken,this.gateway=e.gateway,this.agentManager=e.agentManager}async start(){this.server=LL((e,t)=>{this.handleRequest(e,t).catch(i=>{dy.error("HTTP handler error",{error:String(i)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),dy.info("Slack internal API started",{port:this.port})}async stop(){this.server&&(this.server.close(),this.server=null),dy.info("Slack internal API stopped")}async handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"method not allowed"}));return}if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"unauthorized"}));return}let r=new URL(e.url??"/",`http://127.0.0.1:${this.port}`),o=await this.readBody(e),s;try{s=JSON.parse(o)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"invalid JSON body"}));return}switch(r.pathname){case"/internal/slack/send":return this.handleSend(s,t);case"/internal/slack/read":return this.handleRead(s,t);case"/internal/slack/channels":return this.handleChannels(s,t);case"/internal/slack/users":return this.handleUsers(s,t);case"/internal/slack/search":t.writeHead(501,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"search deferred pending tool-parity audit"}));return;default:t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"not found"}))}}async handleSend(e,t){let{agent_id:i,channel:r,text:o,thread_ts:s,blocks:a,force_root:l}=e;if(typeof r!="string"||!r){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"channel is required"}));return}if(typeof o!="string"||!o){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"text is required"}));return}let c=await this.gateway.resolveChannelId(r);if(!c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:`unknown channel: ${r}`}));return}let u=s;if(!u&&!l&&typeof i=="string"&&i){let h=this.agentManager.getActiveWorkItems(i).filter(m=>m.source.id===c);if(h.length>0){let m=h[h.length-1];u=m.meta?.slackThreadTs??m.meta?.slackTs}}let d=await this.gateway.postAndRegister(c,o,u),f=d.ok?{ok:!0,ts:d.ts,channel:c}:{ok:!1,error:d.error};t.writeHead(d.ok?200:500,{"Content-Type":"application/json"}),t.end(JSON.stringify(f))}async handleRead(e,t){let{channel:i,limit:r}=e;if(typeof i!="string"||!i){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"channel is required"}));return}let o=await this.gateway.readChannel(i,typeof r=="number"?r:void 0);if(o===void 0){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"failed to read channel history"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,messages:o}))}async handleChannels(e,t){let{query:i}=e,r=await this.gateway.listChannels(typeof i=="string"?i:void 0);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channels:r}))}async handleUsers(e,t){let{user:i}=e;if(typeof i!="string"||!i){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"user is required"}));return}let r=await this.gateway.readUser(i);if(r===void 0){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"failed to look up user"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,user:r}))}readBody(e){return new Promise((t,i)=>{let r="";e.on("data",o=>{r+=o.toString()}),e.on("end",()=>t(r)),e.on("error",i)})}};R();var fy=$("slack-scope-preflight"),zL=["chat:write","chat:write.customize","channels:history","channels:read","users:read"];async function LI(n,e=zL){let t=await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${n}`}}),i=await t.json();if(!i.ok){fy.warn("Slack auth.test failed \u2014 skipping scope preflight",{error:i.error??"unknown"});return}let o=(t.headers.get("x-oauth-scopes")??"").split(",").map(a=>a.trim()).filter(Boolean),s=e.filter(a=>!o.includes(a));if(s.length>0){fy.warn("Slack bot token missing recommended scopes \u2014 some features may degrade silently",{missing:s,required:[...e],note:"Identity-mode posts fall back to plain bot identity if chat:write.customize is missing. Grant the scope and reinstall the app to enable it."});return}fy.info("Slack scope preflight passed",{required:[...e]})}var B=$("index");function yT(n){for(let e of n)for(let t of[Do(e),ev(e),tv(e)])try{wj(t,{recursive:!0})}catch(i){B.warn("Failed to provision agent dir",{agentId:e,dir:t,err:i})}}async function Sj(){B.info("Hive starting up",{instance:g.instance.id,portBase:g.instance.portBase}),Vy(gT(se,"dist","index.js"))&&Vy(gT(Vr,"dist","index.js"))&&(B.error("Conflicting engine layouts detected \u2014 both <hiveHome>/dist/ and <hiveHome>/.hive/dist/ exist. Remove the old <hiveHome>/dist/ before starting 0.2.0.",{hiveHome:se,engineDir:Vr}),process.exit(1)),uv(se,Co),dv(se),ov(se),pv(Co,Lt),g.gemini.apiKey&&(Hx(g.gemini.apiKey),B.info("Gemini vision enabled",{model:g.gemini.visionModel}));let n=new kj(g.mongo.uri,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0});await n.connect();let e=n.db(g.mongo.dbName),t=e.collection("agent_definitions");await t.createIndex({channels:1}),await t.createIndex({disabled:1}),await NI(e);let i,r,o,s=null,a,l=async()=>{if(!r||!o)return;B.info("Hot-reloading agent registry...");let F=await i.load();if(F.added.length&&B.info("New agents online",{agents:F.added}),F.updated.length&&B.info("Agents updated",{agents:F.updated}),yT(i.listIds()),F.removed.length){B.info("Agents removed",{agents:F.removed});for(let Me of F.removed)r.stopAgent(Me)}let H=i.getDisabled();for(let Me of H)r.stopAgent(Me.id);H.length&&B.info("Disabled agents stopped",{agents:H.map(Me=>Me.id)}),await o.reloadSchedules(),r.reloadSkills(),r.rescanPlugins()};i=new Ls(t,()=>{s&&clearTimeout(s),s=setTimeout(()=>l(),500)}),await i.load(),B.info("Agent registry loaded",{agents:i.listIds()}),yT(i.listIds());let c=new Rc(e),u=new Bc(c);i.onPostReload(()=>c.invalidateAgents());let d=new Fc(e,c);await d.start();let f=new Kc(e);await f.init();let p=new pl(e);await p.init(),f.memoryStore=p;let h=new ml,m=new gl(p,h,{hotBudgetTokens:g.memory.hotBudgetTokens,sweepIntervalHours:g.memory.sweepIntervalHours,hotThreshold:g.memory.hotThreshold,warmThreshold:g.memory.warmThreshold,recencyHalfLifeDays:g.memory.recencyHalfLifeDays,coldSummaryMinRecords:g.memory.coldSummaryMinRecords,coldRetentionDays:g.memory.coldRetentionDays,purgeRetentionDays:g.memory.purgeRetentionDays},g.autoDream,async()=>new Set(i.listIds()));B.info("Structured memory lifecycle enabled");let y=new Jc(e);await y.init();let _;if(g.activity.enabled&&(_=new vl(e,g.activity),await _.connect()),g.linear.apiKey){let F=new Gc(g.linear.apiKey,g.linear.teamId||void 0);B.info("Linear client configured")}let b=new nl(g.taskLedger.apiUrl,g.taskLedger.apiKey);b.isConfigured&&B.info("Task ledger client configured",{apiUrl:g.taskLedger.apiUrl});let k=new rl(g.taskLedger.apiUrl,g.taskLedger.agentKeys,g.taskLedger.apiKey);k.isConfigured&&B.info("Task ledger auto-tracking enabled",{apiUrl:g.taskLedger.apiUrl,agents:Object.keys(g.taskLedger.agentKeys)});let O,A;if(g.codeIndex.enabled){let{CodeIndexPrefetcher:F}=await Promise.resolve().then(()=>(UI(),jI)),{KnowledgeExtractor:H}=await Promise.resolve().then(()=>(BI(),RI));O=new F({db:e,qdrantUrl:process.env.QDRANT_URL??"http://localhost:6333",ollamaUrl:process.env.OLLAMA_URL??"http://localhost:11434",scoreThreshold:g.codeIndex.scoreThreshold,prefetchLimit:g.codeIndex.prefetchLimit}),g.codeIndex.sessionKnowledge.enabled&&(A=new H(p,h)),B.info("Code index integration enabled",{prefetch:!0,sessionKnowledge:A!==void 0})}r=new Uc(i,f,y,_,O,u);let j=new Wc(r,f,i),L=new Yc(i,r,j,g.defaultAgent,k.isConfigured?k:void 0),P=new il(g.background.port,g.background.authToken,g.tasksDir.background,F=>L.dispatch(F).catch(H=>{B.error("Background task completion dispatch failed",{error:String(H)})}));await P.start(),await P.scanOrphans(),B.info("Background task manager started",{port:g.background.port});let z=new sl(g.codeTask.port,g.codeTask.authToken,g.codeTask.pluginDirs,g.codeTask.maxConcurrent,g.tasksDir.code,F=>L.dispatch(F).catch(H=>{B.error("Code task completion dispatch failed",{error:String(H)})}),{prefetcher:O,knowledgeExtractor:A,maxLifetimeMs:g.codeTask.maxLifetimeMs,staleGraceMs:g.codeTask.staleGraceMs});await z.start(),await z.scanOrphans(),B.info("Code task manager started",{port:g.codeTask.port});let ae;g.recall.apiKey&&(ae=new al(g.recall.monitorPort,g.recall.webhookSecret,F=>L.dispatch(F).catch(H=>{B.error("Meeting monitor dispatch failed",{error:String(H)})})),await ae.start(),B.info("Meeting monitor started",{port:g.recall.monitorPort}),g.recall.apiKey&&!g.recall.webhookSecret&&B.error("Real-time transcript delivery disabled \u2014 RECALL_WEBHOOK_SECRET not set")),Vy(Lt)&&(bj(Lt,{recursive:!0},()=>{s&&clearTimeout(s),s=setTimeout(()=>l(),500)}),B.info("Skills hot-reload enabled",{watched:Lt})),process.on("SIGUSR1",()=>l()),B.info("Hot-reload enabled",{signal:"SIGUSR1"});let ue=g.sms.lines.map(F=>F.slackChannel).filter(Boolean),W=new Zc(g.slack.appToken,g.slack.botToken),Se=new Xc(W,i,ue,"slack");L.registerAdapter(Se),L.setSlackAdapter(Se),await Se.start(F=>{L.dispatch(F).catch(H=>{B.error("Slack dispatch failed",{error:String(H),source:F.source.label})})}),B.info("Slack adapter connected");let tt=new Map;try{let F;do{let Me=await W.client.conversations.list({types:"public_channel,private_channel",limit:1e3,cursor:F});for(let qn of Me.channels??[])qn.name&&qn.id&&tt.set(qn.name,qn.id);F=Me.response_metadata?.next_cursor||void 0}while(F);let H=g.slack.auditChannel;a=H?tt.get(H):void 0,L.setAuditChannel(Se,tt,a),B.info("Audit channel configured",{channels:tt.size,fallback:H||null,fallbackResolved:!!a})}catch(F){B.warn("Failed to configure audit channel",{error:String(F)})}let Ie=null;g.slack.localMcpServer&&(await LI(g.slack.botToken),Ie=new wl({port:g.slackInternal.port,authToken:g.slackInternal.authToken,gateway:W,agentManager:r}),await Ie.start(),B.info("Slack internal API started",{port:g.slackInternal.port}));let Rn=new Qc(g.quo.apiKey,g.sms.lines);L.registerAdapter(Rn),g.quo.apiKey&&g.sms.lines.length>0&&(await Rn.start(F=>{L.dispatch(F).catch(H=>{B.error("SMS dispatch failed",{error:String(H),source:F.source.label})})}),B.info("SMS adapter started",{lines:g.sms.lines.length}));let wt;g.imessage.enabled&&(wt=new tl(g.imessage,e,W,g.instance.id),L.registerAdapter(wt),await wt.start(F=>{L.dispatch(F).catch(H=>{B.error("iMessage dispatch failed",{error:String(H)})})}),B.info("iMessage adapter started"));let{AgentRunner:Oo}=await Promise.resolve().then(()=>(ny(),Wx));Oo.registryRef=i;let{TeamStore:Ml}=await Promise.resolve().then(()=>(KI(),ZI)),{CommandRegistry:un}=await Promise.resolve().then(()=>(WI(),VI)),dn=new Ml(e);await dn.init();let Zr=F=>{let H=i.getAll(),Me=H.find(zl=>zl.id===F);if(Me)return{id:Me.id,name:Me.name};let qn=F.toLowerCase(),Ll=H.find(zl=>zl.name.toLowerCase()===qn);return Ll?{id:Ll.id,name:Ll.name}:null},Kr=new un(dn,Zr);L.setTeamStore(dn),B.info("Team layer initialized");let{registerPluginCommands:de}=await Promise.resolve().then(()=>(Us(),Ub));await de(r.getPlugins(),Kr);let Z;if(g.ws.enabled){let{WsAdapter:F}=await Promise.resolve().then(()=>(rT(),nT));Z=new F(g.ws.port,{teamStore:dn,commandRegistry:Kr,agentRegistry:i,agentManager:r}),L.registerAdapter(Z),await Z.start(H=>{L.dispatch(H).catch(Me=>{B.error("WS dispatch failed",{error:String(Me),source:H.source.label})})}),B.info("WebSocket adapter started",{port:g.ws.port})}let G;if(g.ws.enabled){let{startBeekeeperRegistration:F}=await Promise.resolve().then(()=>(oT(),iT)),H=`hive-${g.instance.id}`;G=F({beekeeperPort:g.beekeeper.port,wsPort:g.ws.port,capabilityName:H}),B.info("Beekeeper registration loop started",{beekeeperPort:g.beekeeper.port,wsPort:g.ws.port,capabilityName:H})}let Te;if(g.voice.enabled&&g.voice.serverSecret){let{VoiceAdapter:F}=await Promise.resolve().then(()=>(hT(),mT));Te=new F(g.voice.port,g.voice.serverSecret,i,f),await Te.start(),B.info("Voice adapter started",{port:g.voice.port})}o=new Vc(r,f,j,i,F=>{L.dispatch(F).catch(H=>{B.error("Callback dispatch failed",{error:String(H)})})}),await o.connectDb(e),o.start(),B.info("Scheduler started"),await i.startWatching();let Bn;g.adminApi.token&&(Bn=new yl(g.adminApi.port,g.adminApi.token,t,e.collection("agent_definition_versions"),()=>l()),await Bn.start(),B.info("Admin API started",{port:g.adminApi.port}));let Fn=new ll({maxAttempts:g.sweeper.retryMaxAttempts,baseDelayMs:g.sweeper.retryBaseDelayMs});L.setRetryQueue(Fn);let vT=[Se],_T=[W],Wy=new ul({intervalMs:g.sweeper.intervalMs,threadTtlMs:g.sweeper.threadTtlMs,taskFileTtlMs:g.sweeper.taskFileTtlMs,meetingSessionTtlMs:g.sweeper.meetingSessionTtlMs,cacheTtlMs:g.sweeper.cacheTtlMs,memorySweepIntervalHours:g.memory.sweepIntervalHours,dreamConfig:g.autoDream},{dispatcher:L,slackAdapters:vT,bgTaskManager:P,codeTaskManager:z,meetingMonitor:ae,taskLedger:k.isConfigured?k:void 0,slackGateways:_T,agentManager:r,retryQueue:Fn,memoryLifecycle:m},b.isConfigured?b:void 0);Wy.start(),B.info("Sweeper started",{intervalMs:g.sweeper.intervalMs});let Gy=new fl(g.retention,{hiveHome:se,report:async F=>{a?await W.postMessage(a,F).catch(H=>B.warn("Retention report: Slack post failed",{error:String(H)})):B.info("Retention report (no audit channel configured)",{text:F})}});Gy.start(),B.info("Retention sweeper started",{enabled:g.retention.enabled,intervalMs:g.retention.intervalMs});let Jy=async F=>{B.info("Shutdown signal received",{signal:F}),Wy.stop(),Gy.stop(),Bn?.stop(),i.stopWatching(),await Rn.stop(),Ie&&await Ie.stop(),wt&&await wt.stop(),G?.stop(),Z&&await Z.stop(),Te?.stop(),o.stop(),await P.stop(),await z.stop(),await O?.close(),ae?.stop(),r.stopAll(),d.stop(),_&&await _.stop(),await y.close(),await p.close(),await Se.stop(),await n.close(),B.info("Hive shut down cleanly"),process.exit(0)};process.on("SIGTERM",()=>Jy("SIGTERM")),process.on("SIGINT",()=>Jy("SIGINT")),B.info("Hive is running"),MI(f,i,L,tt).catch(F=>{B.error("First-boot check failed",{error:String(F)})})}process.on("unhandledRejection",n=>{B.error("Unhandled promise rejection",{error:String(n),stack:n instanceof Error?n.stack:void 0})});Sj().catch(n=>{B.error("Fatal startup error",{error:String(n)}),process.exit(1)});