@keepur/hive 0.2.5 → 0.2.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/pkg/server.min.js CHANGED
@@ -1,18 +1,18 @@
1
1
  import { createRequire as __hiveCreateRequire } from 'module'; const require = __hiveCreateRequire(import.meta.url);
2
- var Jp=Object.create;var Ii=Object.defineProperty;var zp=Object.getOwnPropertyDescriptor;var Qp=Object.getOwnPropertyNames;var Xp=Object.getPrototypeOf,Zp=Object.prototype.hasOwnProperty;var H=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var j=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ue=(r,e)=>{for(var t in e)Ii(r,t,{get:e[t],enumerable:!0})},em=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Qp(e))!Zp.call(r,n)&&n!==t&&Ii(r,n,{get:()=>e[n],enumerable:!(s=zp(e,n))||s.enumerable});return r};var Ce=(r,e,t)=>(t=r!=null?Jp(Xp(r)):{},em(e||!r||!r.__esModule?Ii(t,"default",{value:r,enumerable:!0}):t,r));import{existsSync as tm}from"node:fs";import{resolve as ge}from"node:path";function nm(){return process.env.HIVE_HOME?ge(process.env.HIVE_HOME):tm(ge(process.cwd(),"hive.yaml"))?process.cwd():ge(sm,"hive")}function vc(r){let e=process.env.HIVE_CONFIG||"hive.yaml";return ge(r,e)}function Tc(r){let t=(process.env.HIVE_CONFIG||"hive.yaml").match(/^hive-(.+)\.yaml$/)?.[1];return ge(r,t?`.env-${t}`:".env")}function Cc(r=z){return ge(r,"agents")}function Ac(r,e=z){return ge(Cc(e),r,"scratch")}function Ec(r,e=z){return ge(Cc(e),r,"playwright")}var sm,z,Ze,cs,fn,Sv,Ic,ls=j(()=>{"use strict";sm=process.env.HOME??"/tmp";z=nm(),Ze=ge(z,"skills"),cs=ge(z,".hive"),fn=ge(z,".hive-state"),Sv=ge(fn,"git"),Ic=ge(import.meta.dirname,"..","seeds")});function pn(r,e,t,s){if(Nc[r]<Nc[rm])return;let n={ts:new Date().toISOString(),level:r,component:e,msg:t,...s};(r==="error"?process.stderr:process.stdout).write(JSON.stringify(n)+`
3
- `)}function k(r){return{debug:(e,t)=>pn("debug",r,e,t),info:(e,t)=>pn("info",r,e,t),warn:(e,t)=>pn("warn",r,e,t),error:(e,t)=>pn("error",r,e,t)}}var Nc,rm,O=j(()=>{"use strict";Nc={debug:0,info:1,warn:2,error:3},rm=process.env.LOG_LEVEL||"info"});import{execFileSync as Ci}from"node:child_process";import{existsSync as Ai,mkdirSync as im,unlinkSync as om}from"node:fs";import{join as am,resolve as xc}from"node:path";function Oc(r){let e=xc(r,".hive-state");return{stateDir:e,gitDir:xc(e,"git")}}function Mc(r){let{stateDir:e,gitDir:t}=Oc(r);if(Ai(t))return;im(e,{recursive:!0});let s=(...n)=>Ci("git",[...n],{cwd:r,env:{...process.env,GIT_DIR:t,GIT_WORK_TREE:r},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"),mn.info("Instance-local git initialized",{gitDir:t})}function Dc(r,e,t,s){let{gitDir:n}=Oc(r);if(!Ai(n)){mn.warn("Instance git not initialized \u2014 skipping state commit");return}let i=am(n,"state-index.tmp"),o={...process.env,GIT_DIR:n,GIT_WORK_TREE:r,GIT_INDEX_FILE:i},a=(...l)=>Ci("git",[...l],{cwd:r,env:o,stdio:"pipe",encoding:"utf-8"}).trim();try{a("read-tree","state");for(let m of e)a("add","--force","--",m);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=Ci("git",["commit-tree",l,"-p",c,"-m",t],{env:{...o,...u},encoding:"utf-8"}).trim();a("update-ref","refs/heads/state",h),mn.debug("State branch commit",{message:t,files:e.length})}catch(l){mn.warn("Failed to commit to state branch",{error:String(l),message:t})}finally{try{Ai(i)&&om(i)}catch{}}}var mn,Ei=j(()=>{"use strict";O();mn=k("instance-git")});var Gc=T((qv,qe)=>{var Mi=H("fs"),gn=H("path"),fm=H("os"),pm=H("crypto"),jc=["\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 mm(){return jc[Math.floor(Math.random()*jc.length)]}function $t(r){return typeof r=="string"?!["false","0","no","off",""].includes(r.toLowerCase()):!!r}function gm(){return process.stdout.isTTY}function ym(r){return gm()?`\x1B[2m${r}\x1B[0m`:r}var wm=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Sm(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
4
- `);let s;for(;(s=wm.exec(t))!=null;){let n=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[n]=i}return e}function km(r){r=r||{};let e=Wc(r);r.path=e;let t=te.configDotenv(r);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let s=Hc(r).split(","),n=s.length,i;for(let o=0;o<n;o++)try{let a=s[o].trim(),l=_m(t,a);i=te.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=n)throw a}return te.parse(i)}function bm(r){console.error(`\u26A0 ${r}`)}function ds(r){console.log(`\u2506 ${r}`)}function Kc(r){console.log(`\u25C7 ${r}`)}function Hc(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function _m(r,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 n=t.searchParams.get("environment");if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let i=`DOTENV_VAULT_${n.toUpperCase()}`,o=r.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 Wc(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Mi.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=gn.resolve(process.cwd(),".env.vault");return Mi.existsSync(e)?e:null}function Fc(r){return r[0]==="~"?gn.join(fm.homedir(),r.slice(1)):r}function vm(r){let e=$t(process.env.DOTENV_CONFIG_DEBUG||r&&r.debug),t=$t(process.env.DOTENV_CONFIG_QUIET||r&&r.quiet);(e||!t)&&Kc("loading env from encrypted .env.vault");let s=te._parseVault(r),n=process.env;return r&&r.processEnv!=null&&(n=r.processEnv),te.populate(n,s,r),{parsed:s}}function Tm(r){let e=gn.resolve(process.cwd(),".env"),t="utf8",s=process.env;r&&r.processEnv!=null&&(s=r.processEnv);let n=$t(s.DOTENV_CONFIG_DEBUG||r&&r.debug),i=$t(s.DOTENV_CONFIG_QUIET||r&&r.quiet);r&&r.encoding?t=r.encoding:n&&ds("no encoding is specified (UTF-8 is used by default)");let o=[e];if(r&&r.path)if(!Array.isArray(r.path))o=[Fc(r.path)];else{o=[];for(let d of r.path)o.push(Fc(d))}let a,l={};for(let d of o)try{let u=te.parse(Mi.readFileSync(d,{encoding:t}));te.populate(l,u,r)}catch(u){n&&ds(`failed to load ${d} ${u.message}`),a=u}let c=te.populate(s,l,r);if(n=$t(s.DOTENV_CONFIG_DEBUG||n),i=$t(s.DOTENV_CONFIG_QUIET||i),n||!i){let d=Object.keys(c).length,u=[];for(let h of o)try{let m=gn.relative(process.cwd(),h);u.push(m)}catch(m){n&&ds(`failed to load ${h} ${m.message}`),a=m}Kc(`injected env (${d}) from ${u.join(",")} ${ym(`// tip: ${mm()}`)}`)}return a?{parsed:l,error:a}:{parsed:l}}function Im(r){if(Hc(r).length===0)return te.configDotenv(r);let e=Wc(r);return e?te._configVault(r):(bm(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),te.configDotenv(r))}function Cm(r,e){let t=Buffer.from(e.slice(-64),"hex"),s=Buffer.from(r,"base64"),n=s.subarray(0,12),i=s.subarray(-16);s=s.subarray(12,-16);try{let o=pm.createDecipheriv("aes-256-gcm",t,n);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 Am(r,e,t={}){let s=!!(t&&t.debug),n=!!(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(r,o)?(n===!0&&(r[o]=e[o],i[o]=e[o]),s&&ds(n===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(r[o]=e[o],i[o]=e[o]);return i}var te={configDotenv:Tm,_configVault:vm,_parseVault:km,config:Im,decrypt:Cm,parse:Sm,populate:Am};qe.exports.configDotenv=te.configDotenv;qe.exports._configVault=te._configVault;qe.exports._parseVault=te._parseVault;qe.exports.config=te.config;qe.exports.decrypt=te.decrypt;qe.exports.parse=te.parse;qe.exports.populate=te.populate;qe.exports=te});var U=T(oe=>{"use strict";var Di=Symbol.for("yaml.alias"),Vc=Symbol.for("yaml.document"),yn=Symbol.for("yaml.map"),Yc=Symbol.for("yaml.pair"),Li=Symbol.for("yaml.scalar"),wn=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),Em=r=>!!r&&typeof r=="object"&&r[je]===Di,Nm=r=>!!r&&typeof r=="object"&&r[je]===Vc,xm=r=>!!r&&typeof r=="object"&&r[je]===yn,Om=r=>!!r&&typeof r=="object"&&r[je]===Yc,Jc=r=>!!r&&typeof r=="object"&&r[je]===Li,Mm=r=>!!r&&typeof r=="object"&&r[je]===wn;function zc(r){if(r&&typeof r=="object")switch(r[je]){case yn:case wn:return!0}return!1}function Dm(r){if(r&&typeof r=="object")switch(r[je]){case Di:case yn:case Li:case wn:return!0}return!1}var Lm=r=>(Jc(r)||zc(r))&&!!r.anchor;oe.ALIAS=Di;oe.DOC=Vc;oe.MAP=yn;oe.NODE_TYPE=je;oe.PAIR=Yc;oe.SCALAR=Li;oe.SEQ=wn;oe.hasAnchor=Lm;oe.isAlias=Em;oe.isCollection=zc;oe.isDocument=Nm;oe.isMap=xm;oe.isNode=Dm;oe.isPair=Om;oe.isScalar=Jc;oe.isSeq=Mm});var us=T(Pi=>{"use strict";var se=U(),ue=Symbol("break visit"),Qc=Symbol("skip children"),Le=Symbol("remove node");function Sn(r,e){let t=Xc(e);se.isDocument(r)?Rt(null,r.contents,t,Object.freeze([r]))===Le&&(r.contents=null):Rt(null,r,t,Object.freeze([]))}Sn.BREAK=ue;Sn.SKIP=Qc;Sn.REMOVE=Le;function Rt(r,e,t,s){let n=Zc(r,e,t,s);if(se.isNode(n)||se.isPair(n))return el(r,s,n),Rt(r,n,t,s);if(typeof n!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=Rt(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===ue)return ue;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=Rt("key",e.key,t,s);if(i===ue)return ue;i===Le&&(e.key=null);let o=Rt("value",e.value,t,s);if(o===ue)return ue;o===Le&&(e.value=null)}}return n}async function kn(r,e){let t=Xc(e);se.isDocument(r)?await Bt(null,r.contents,t,Object.freeze([r]))===Le&&(r.contents=null):await Bt(null,r,t,Object.freeze([]))}kn.BREAK=ue;kn.SKIP=Qc;kn.REMOVE=Le;async function Bt(r,e,t,s){let n=await Zc(r,e,t,s);if(se.isNode(n)||se.isPair(n))return el(r,s,n),Bt(r,n,t,s);if(typeof n!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await Bt(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===ue)return ue;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=await Bt("key",e.key,t,s);if(i===ue)return ue;i===Le&&(e.key=null);let o=await Bt("value",e.value,t,s);if(o===ue)return ue;o===Le&&(e.value=null)}}return n}function Xc(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function Zc(r,e,t,s){if(typeof t=="function")return t(r,e,s);if(se.isMap(e))return t.Map?.(r,e,s);if(se.isSeq(e))return t.Seq?.(r,e,s);if(se.isPair(e))return t.Pair?.(r,e,s);if(se.isScalar(e))return t.Scalar?.(r,e,s);if(se.isAlias(e))return t.Alias?.(r,e,s)}function el(r,e,t){let s=e[e.length-1];if(se.isCollection(s))s.items[r]=t;else if(se.isPair(s))r==="key"?s.key=t:s.value=t;else if(se.isDocument(s))s.contents=t;else{let n=se.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Pi.visit=Sn;Pi.visitAsync=kn});var $i=T(sl=>{"use strict";var tl=U(),Pm=us(),$m={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Rm=r=>r.replace(/[!,[\]{}]/g,e=>$m[e]),hs=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),n=s.shift();switch(n){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 ${n}`,!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,n]=e.match(/^(.*!)([^!]*)$/s);n||t(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(n)}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+Rm(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),n;if(e&&s.length>0&&tl.isNode(e.contents)){let i={};Pm.visit(e.contents,(o,a)=>{tl.isNode(a)&&a.tag&&(i[a.tag]=!0)}),n=Object.keys(i)}else n=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.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:"};sl.Directives=hs});var bn=T(fs=>{"use strict";var nl=U(),Bm=us();function Um(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function rl(r){let e=new Set;return Bm.visit(r,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}function il(r,e){for(let t=1;;++t){let s=`${r}${t}`;if(!e.has(s))return s}}function qm(r,e){let t=[],s=new Map,n=null;return{onAnchor:i=>{t.push(i),n??(n=rl(r));let o=il(e,n);return n.add(o),o},setAnchors:()=>{for(let i of t){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(nl.isScalar(o.node)||nl.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=Um;fs.anchorNames=rl;fs.createNodeAnchors=qm;fs.findNewAnchor=il});var Ri=T(ol=>{"use strict";function ps(r,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let n=0,i=s.length;n<i;++n){let o=s[n],a=ps(r,s,String(n),o);a===void 0?delete s[n]:a!==o&&(s[n]=a)}else if(s instanceof Map)for(let n of Array.from(s.keys())){let i=s.get(n),o=ps(r,s,n,i);o===void 0?s.delete(n):o!==i&&s.set(n,o)}else if(s instanceof Set)for(let n of Array.from(s)){let i=ps(r,s,n,n);i===void 0?s.delete(n):i!==n&&(s.delete(n),s.add(i))}else for(let[n,i]of Object.entries(s)){let o=ps(r,s,n,i);o===void 0?delete s[n]:o!==i&&(s[n]=o)}return r.call(e,t,s)}ol.applyReviver=ps});var et=T(cl=>{"use strict";var jm=U();function al(r,e,t){if(Array.isArray(r))return r.map((s,n)=>al(s,String(n),t));if(r&&typeof r.toJSON=="function"){if(!t||!jm.hasAnchor(r))return r.toJSON(e,t);let s={aliasCount:0,count:1,res:void 0};t.anchors.set(r,s),t.onCreate=i=>{s.res=i,delete t.onCreate};let n=r.toJSON(e,t);return t.onCreate&&t.onCreate(n),n}return typeof r=="bigint"&&!t?.keep?Number(r):r}cl.toJS=al});var _n=T(dl=>{"use strict";var Fm=Ri(),ll=U(),Km=et(),Bi=class{constructor(e){Object.defineProperty(this,ll.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:n,reviver:i}={}){if(!ll.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=Km.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof i=="function"?Fm.applyReviver(i,{"":a},"",a):a}};dl.NodeBase=Bi});var ms=T(ul=>{"use strict";var Hm=bn(),Wm=us(),Ut=U(),Gm=_n(),Vm=et(),Ui=class extends Gm.NodeBase{constructor(e){super(Ut.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=[],Wm.visit(e,{Node:(i,o)=>{(Ut.isAlias(o)||Ut.hasAnchor(o))&&s.push(o)}}),t&&(t.aliasResolveCache=s));let n;for(let i of s){if(i===this)break;i.anchor===this.source&&(n=i)}return n}toJSON(e,t){if(!t)return{source:this.source};let{anchors:s,doc:n,maxAliasCount:i}=t,o=this.resolve(n,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||(Vm.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=vn(n,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 n=`*${this.source}`;if(e){if(Hm.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`${n} `}return n}};function vn(r,e,t){if(Ut.isAlias(e)){let s=e.resolve(r),n=t&&s&&t.get(s);return n?n.count*n.aliasCount:0}else if(Ut.isCollection(e)){let s=0;for(let n of e.items){let i=vn(r,n,t);i>s&&(s=i)}return s}else if(Ut.isPair(e)){let s=vn(r,e.key,t),n=vn(r,e.value,t);return Math.max(s,n)}return 1}ul.Alias=Ui});var Z=T(qi=>{"use strict";var Ym=U(),Jm=_n(),zm=et(),Qm=r=>!r||typeof r!="function"&&typeof r!="object",tt=class extends Jm.NodeBase{constructor(e){super(Ym.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:zm.toJS(this.value,e,t)}toString(){return String(this.value)}};tt.BLOCK_FOLDED="BLOCK_FOLDED";tt.BLOCK_LITERAL="BLOCK_LITERAL";tt.PLAIN="PLAIN";tt.QUOTE_DOUBLE="QUOTE_DOUBLE";tt.QUOTE_SINGLE="QUOTE_SINGLE";qi.Scalar=tt;qi.isScalarValue=Qm});var gs=T(fl=>{"use strict";var Xm=ms(),gt=U(),hl=Z(),Zm="tag:yaml.org,2002:";function eg(r,e,t){if(e){let s=t.filter(i=>i.tag===e),n=s.find(i=>!i.format)??s[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return t.find(s=>s.identify?.(r)&&!s.format)}function tg(r,e,t){if(gt.isDocument(r)&&(r=r.contents),gt.isNode(r))return r;if(gt.isPair(r)){let u=t.schema[gt.MAP].createNode?.(t.schema,null,t);return u.items.push(r),u}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:s,onAnchor:n,onTagObj:i,schema:o,sourceObjects:a}=t,l;if(s&&r&&typeof r=="object"){if(l=a.get(r),l)return l.anchor??(l.anchor=n(r)),new Xm.Alias(l.anchor);l={anchor:null,node:null},a.set(r,l)}e?.startsWith("!!")&&(e=Zm+e.slice(2));let c=eg(r,e,o.tags);if(!c){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new hl.Scalar(r);return l&&(l.node=u),u}c=r instanceof Map?o[gt.MAP]:Symbol.iterator in Object(r)?o[gt.SEQ]:o[gt.MAP]}i&&(i(c),delete t.onTagObj);let d=c?.createNode?c.createNode(t.schema,r,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,r,t):new hl.Scalar(r);return e?d.tag=e:c.default||(d.tag=c.tag),l&&(l.node=d),d}fl.createNode=tg});var In=T(Tn=>{"use strict";var sg=gs(),Pe=U(),ng=_n();function ji(r,e,t){let s=t;for(let n=e.length-1;n>=0;--n){let i=e[n];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return sg.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var pl=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Fi=class extends ng.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(pl(e))this.add(t);else{let[s,...n]=e,i=this.get(s,!0);if(Pe.isCollection(i))i.addIn(n,t);else if(i===void 0&&this.schema)this.set(s,ji(this.schema,n,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`)}}deleteIn(e){let[t,...s]=e;if(s.length===0)return this.delete(t);let n=this.get(t,!0);if(Pe.isCollection(n))return n.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){let[s,...n]=e,i=this.get(s,!0);return n.length===0?!t&&Pe.isScalar(i)?i.value:i:Pe.isCollection(i)?i.getIn(n,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 n=this.get(t,!0);return Pe.isCollection(n)?n.hasIn(s):!1}setIn(e,t){let[s,...n]=e;if(n.length===0)this.set(s,t);else{let i=this.get(s,!0);if(Pe.isCollection(i))i.setIn(n,t);else if(i===void 0&&this.schema)this.set(s,ji(this.schema,n,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`)}}};Tn.Collection=Fi;Tn.collectionFromPath=ji;Tn.isEmptyPath=pl});var ys=T(Cn=>{"use strict";var rg=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Ki(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var ig=(r,e,t)=>r.endsWith(`
2
+ var zp=Object.create;var Ii=Object.defineProperty;var Qp=Object.getOwnPropertyDescriptor;var Xp=Object.getOwnPropertyNames;var Zp=Object.getPrototypeOf,em=Object.prototype.hasOwnProperty;var H=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});var j=(r,e)=>()=>(r&&(e=r(r=0)),e);var T=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),Ue=(r,e)=>{for(var t in e)Ii(r,t,{get:e[t],enumerable:!0})},tm=(r,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let n of Xp(e))!em.call(r,n)&&n!==t&&Ii(r,n,{get:()=>e[n],enumerable:!(s=Qp(e,n))||s.enumerable});return r};var Ce=(r,e,t)=>(t=r!=null?zp(Zp(r)):{},tm(e||!r||!r.__esModule?Ii(t,"default",{value:r,enumerable:!0}):t,r));import{existsSync as sm}from"node:fs";import{resolve as ge}from"node:path";function rm(){return process.env.HIVE_HOME?ge(process.env.HIVE_HOME):sm(ge(process.cwd(),"hive.yaml"))?process.cwd():ge(nm,"hive")}function vc(r){let e=process.env.HIVE_CONFIG||"hive.yaml";return ge(r,e)}function Tc(r){let t=(process.env.HIVE_CONFIG||"hive.yaml").match(/^hive-(.+)\.yaml$/)?.[1];return ge(r,t?`.env-${t}`:".env")}function Cc(r=z){return ge(r,"agents")}function Ac(r,e=z){return ge(Cc(e),r,"scratch")}function Ec(r,e=z){return ge(Cc(e),r,"playwright")}var nm,z,Ze,cs,fn,Sv,Ic,ls=j(()=>{"use strict";nm=process.env.HOME??"/tmp";z=rm(),Ze=ge(z,"skills"),cs=ge(z,".hive"),fn=ge(z,".hive-state"),Sv=ge(fn,"git"),Ic=ge(import.meta.dirname,"..","seeds")});function pn(r,e,t,s){if(Nc[r]<Nc[im])return;let n={ts:new Date().toISOString(),level:r,component:e,msg:t,...s};(r==="error"?process.stderr:process.stdout).write(JSON.stringify(n)+`
3
+ `)}function k(r){return{debug:(e,t)=>pn("debug",r,e,t),info:(e,t)=>pn("info",r,e,t),warn:(e,t)=>pn("warn",r,e,t),error:(e,t)=>pn("error",r,e,t)}}var Nc,im,O=j(()=>{"use strict";Nc={debug:0,info:1,warn:2,error:3},im=process.env.LOG_LEVEL||"info"});import{execFileSync as Ci}from"node:child_process";import{existsSync as Ai,mkdirSync as om,unlinkSync as am}from"node:fs";import{join as cm,resolve as xc}from"node:path";function Oc(r){let e=xc(r,".hive-state");return{stateDir:e,gitDir:xc(e,"git")}}function Mc(r){let{stateDir:e,gitDir:t}=Oc(r);if(Ai(t))return;om(e,{recursive:!0});let s=(...n)=>Ci("git",[...n],{cwd:r,env:{...process.env,GIT_DIR:t,GIT_WORK_TREE:r},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"),mn.info("Instance-local git initialized",{gitDir:t})}function Dc(r,e,t,s){let{gitDir:n}=Oc(r);if(!Ai(n)){mn.warn("Instance git not initialized \u2014 skipping state commit");return}let i=cm(n,"state-index.tmp"),o={...process.env,GIT_DIR:n,GIT_WORK_TREE:r,GIT_INDEX_FILE:i},a=(...l)=>Ci("git",[...l],{cwd:r,env:o,stdio:"pipe",encoding:"utf-8"}).trim();try{a("read-tree","state");for(let m of e)a("add","--force","--",m);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=Ci("git",["commit-tree",l,"-p",c,"-m",t],{env:{...o,...u},encoding:"utf-8"}).trim();a("update-ref","refs/heads/state",h),mn.debug("State branch commit",{message:t,files:e.length})}catch(l){mn.warn("Failed to commit to state branch",{error:String(l),message:t})}finally{try{Ai(i)&&am(i)}catch{}}}var mn,Ei=j(()=>{"use strict";O();mn=k("instance-git")});var Gc=T((qv,qe)=>{var Mi=H("fs"),gn=H("path"),pm=H("os"),mm=H("crypto"),jc=["\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 gm(){return jc[Math.floor(Math.random()*jc.length)]}function $t(r){return typeof r=="string"?!["false","0","no","off",""].includes(r.toLowerCase()):!!r}function ym(){return process.stdout.isTTY}function wm(r){return ym()?`\x1B[2m${r}\x1B[0m`:r}var Sm=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function km(r){let e={},t=r.toString();t=t.replace(/\r\n?/mg,`
4
+ `);let s;for(;(s=Sm.exec(t))!=null;){let n=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[n]=i}return e}function bm(r){r=r||{};let e=Wc(r);r.path=e;let t=te.configDotenv(r);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let s=Hc(r).split(","),n=s.length,i;for(let o=0;o<n;o++)try{let a=s[o].trim(),l=vm(t,a);i=te.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=n)throw a}return te.parse(i)}function _m(r){console.error(`\u26A0 ${r}`)}function ds(r){console.log(`\u2506 ${r}`)}function Kc(r){console.log(`\u25C7 ${r}`)}function Hc(r){return r&&r.DOTENV_KEY&&r.DOTENV_KEY.length>0?r.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function vm(r,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 n=t.searchParams.get("environment");if(!n){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let i=`DOTENV_VAULT_${n.toUpperCase()}`,o=r.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 Wc(r){let e=null;if(r&&r.path&&r.path.length>0)if(Array.isArray(r.path))for(let t of r.path)Mi.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=r.path.endsWith(".vault")?r.path:`${r.path}.vault`;else e=gn.resolve(process.cwd(),".env.vault");return Mi.existsSync(e)?e:null}function Fc(r){return r[0]==="~"?gn.join(pm.homedir(),r.slice(1)):r}function Tm(r){let e=$t(process.env.DOTENV_CONFIG_DEBUG||r&&r.debug),t=$t(process.env.DOTENV_CONFIG_QUIET||r&&r.quiet);(e||!t)&&Kc("loading env from encrypted .env.vault");let s=te._parseVault(r),n=process.env;return r&&r.processEnv!=null&&(n=r.processEnv),te.populate(n,s,r),{parsed:s}}function Im(r){let e=gn.resolve(process.cwd(),".env"),t="utf8",s=process.env;r&&r.processEnv!=null&&(s=r.processEnv);let n=$t(s.DOTENV_CONFIG_DEBUG||r&&r.debug),i=$t(s.DOTENV_CONFIG_QUIET||r&&r.quiet);r&&r.encoding?t=r.encoding:n&&ds("no encoding is specified (UTF-8 is used by default)");let o=[e];if(r&&r.path)if(!Array.isArray(r.path))o=[Fc(r.path)];else{o=[];for(let d of r.path)o.push(Fc(d))}let a,l={};for(let d of o)try{let u=te.parse(Mi.readFileSync(d,{encoding:t}));te.populate(l,u,r)}catch(u){n&&ds(`failed to load ${d} ${u.message}`),a=u}let c=te.populate(s,l,r);if(n=$t(s.DOTENV_CONFIG_DEBUG||n),i=$t(s.DOTENV_CONFIG_QUIET||i),n||!i){let d=Object.keys(c).length,u=[];for(let h of o)try{let m=gn.relative(process.cwd(),h);u.push(m)}catch(m){n&&ds(`failed to load ${h} ${m.message}`),a=m}Kc(`injected env (${d}) from ${u.join(",")} ${wm(`// tip: ${gm()}`)}`)}return a?{parsed:l,error:a}:{parsed:l}}function Cm(r){if(Hc(r).length===0)return te.configDotenv(r);let e=Wc(r);return e?te._configVault(r):(_m(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),te.configDotenv(r))}function Am(r,e){let t=Buffer.from(e.slice(-64),"hex"),s=Buffer.from(r,"base64"),n=s.subarray(0,12),i=s.subarray(-16);s=s.subarray(12,-16);try{let o=mm.createDecipheriv("aes-256-gcm",t,n);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 Em(r,e,t={}){let s=!!(t&&t.debug),n=!!(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(r,o)?(n===!0&&(r[o]=e[o],i[o]=e[o]),s&&ds(n===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(r[o]=e[o],i[o]=e[o]);return i}var te={configDotenv:Im,_configVault:Tm,_parseVault:bm,config:Cm,decrypt:Am,parse:km,populate:Em};qe.exports.configDotenv=te.configDotenv;qe.exports._configVault=te._configVault;qe.exports._parseVault=te._parseVault;qe.exports.config=te.config;qe.exports.decrypt=te.decrypt;qe.exports.parse=te.parse;qe.exports.populate=te.populate;qe.exports=te});var U=T(oe=>{"use strict";var Di=Symbol.for("yaml.alias"),Vc=Symbol.for("yaml.document"),yn=Symbol.for("yaml.map"),Yc=Symbol.for("yaml.pair"),Li=Symbol.for("yaml.scalar"),wn=Symbol.for("yaml.seq"),je=Symbol.for("yaml.node.type"),Nm=r=>!!r&&typeof r=="object"&&r[je]===Di,xm=r=>!!r&&typeof r=="object"&&r[je]===Vc,Om=r=>!!r&&typeof r=="object"&&r[je]===yn,Mm=r=>!!r&&typeof r=="object"&&r[je]===Yc,Jc=r=>!!r&&typeof r=="object"&&r[je]===Li,Dm=r=>!!r&&typeof r=="object"&&r[je]===wn;function zc(r){if(r&&typeof r=="object")switch(r[je]){case yn:case wn:return!0}return!1}function Lm(r){if(r&&typeof r=="object")switch(r[je]){case Di:case yn:case Li:case wn:return!0}return!1}var Pm=r=>(Jc(r)||zc(r))&&!!r.anchor;oe.ALIAS=Di;oe.DOC=Vc;oe.MAP=yn;oe.NODE_TYPE=je;oe.PAIR=Yc;oe.SCALAR=Li;oe.SEQ=wn;oe.hasAnchor=Pm;oe.isAlias=Nm;oe.isCollection=zc;oe.isDocument=xm;oe.isMap=Om;oe.isNode=Lm;oe.isPair=Mm;oe.isScalar=Jc;oe.isSeq=Dm});var us=T(Pi=>{"use strict";var se=U(),ue=Symbol("break visit"),Qc=Symbol("skip children"),Le=Symbol("remove node");function Sn(r,e){let t=Xc(e);se.isDocument(r)?Rt(null,r.contents,t,Object.freeze([r]))===Le&&(r.contents=null):Rt(null,r,t,Object.freeze([]))}Sn.BREAK=ue;Sn.SKIP=Qc;Sn.REMOVE=Le;function Rt(r,e,t,s){let n=Zc(r,e,t,s);if(se.isNode(n)||se.isPair(n))return el(r,s,n),Rt(r,n,t,s);if(typeof n!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=Rt(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===ue)return ue;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=Rt("key",e.key,t,s);if(i===ue)return ue;i===Le&&(e.key=null);let o=Rt("value",e.value,t,s);if(o===ue)return ue;o===Le&&(e.value=null)}}return n}async function kn(r,e){let t=Xc(e);se.isDocument(r)?await Bt(null,r.contents,t,Object.freeze([r]))===Le&&(r.contents=null):await Bt(null,r,t,Object.freeze([]))}kn.BREAK=ue;kn.SKIP=Qc;kn.REMOVE=Le;async function Bt(r,e,t,s){let n=await Zc(r,e,t,s);if(se.isNode(n)||se.isPair(n))return el(r,s,n),Bt(r,n,t,s);if(typeof n!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await Bt(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===ue)return ue;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=await Bt("key",e.key,t,s);if(i===ue)return ue;i===Le&&(e.key=null);let o=await Bt("value",e.value,t,s);if(o===ue)return ue;o===Le&&(e.value=null)}}return n}function Xc(r){return typeof r=="object"&&(r.Collection||r.Node||r.Value)?Object.assign({Alias:r.Node,Map:r.Node,Scalar:r.Node,Seq:r.Node},r.Value&&{Map:r.Value,Scalar:r.Value,Seq:r.Value},r.Collection&&{Map:r.Collection,Seq:r.Collection},r):r}function Zc(r,e,t,s){if(typeof t=="function")return t(r,e,s);if(se.isMap(e))return t.Map?.(r,e,s);if(se.isSeq(e))return t.Seq?.(r,e,s);if(se.isPair(e))return t.Pair?.(r,e,s);if(se.isScalar(e))return t.Scalar?.(r,e,s);if(se.isAlias(e))return t.Alias?.(r,e,s)}function el(r,e,t){let s=e[e.length-1];if(se.isCollection(s))s.items[r]=t;else if(se.isPair(s))r==="key"?s.key=t:s.value=t;else if(se.isDocument(s))s.contents=t;else{let n=se.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${n} parent`)}}Pi.visit=Sn;Pi.visitAsync=kn});var $i=T(sl=>{"use strict";var tl=U(),$m=us(),Rm={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Bm=r=>r.replace(/[!,[\]{}]/g,e=>Rm[e]),hs=class r{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},r.defaultYaml,e),this.tags=Object.assign({},r.defaultTags,t)}clone(){let e=new r(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new r(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:r.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},r.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:r.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},r.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),n=s.shift();switch(n){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 ${n}`,!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,n]=e.match(/^(.*!)([^!]*)$/s);n||t(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(n)}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+Bm(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),n;if(e&&s.length>0&&tl.isNode(e.contents)){let i={};$m.visit(e.contents,(o,a)=>{tl.isNode(a)&&a.tag&&(i[a.tag]=!0)}),n=Object.keys(i)}else n=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||n.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:"};sl.Directives=hs});var bn=T(fs=>{"use strict";var nl=U(),Um=us();function qm(r){if(/[\x00-\x19\s,[\]{}]/.test(r)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(r)}`;throw new Error(t)}return!0}function rl(r){let e=new Set;return Um.visit(r,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}function il(r,e){for(let t=1;;++t){let s=`${r}${t}`;if(!e.has(s))return s}}function jm(r,e){let t=[],s=new Map,n=null;return{onAnchor:i=>{t.push(i),n??(n=rl(r));let o=il(e,n);return n.add(o),o},setAnchors:()=>{for(let i of t){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(nl.isScalar(o.node)||nl.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=qm;fs.anchorNames=rl;fs.createNodeAnchors=jm;fs.findNewAnchor=il});var Ri=T(ol=>{"use strict";function ps(r,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let n=0,i=s.length;n<i;++n){let o=s[n],a=ps(r,s,String(n),o);a===void 0?delete s[n]:a!==o&&(s[n]=a)}else if(s instanceof Map)for(let n of Array.from(s.keys())){let i=s.get(n),o=ps(r,s,n,i);o===void 0?s.delete(n):o!==i&&s.set(n,o)}else if(s instanceof Set)for(let n of Array.from(s)){let i=ps(r,s,n,n);i===void 0?s.delete(n):i!==n&&(s.delete(n),s.add(i))}else for(let[n,i]of Object.entries(s)){let o=ps(r,s,n,i);o===void 0?delete s[n]:o!==i&&(s[n]=o)}return r.call(e,t,s)}ol.applyReviver=ps});var et=T(cl=>{"use strict";var Fm=U();function al(r,e,t){if(Array.isArray(r))return r.map((s,n)=>al(s,String(n),t));if(r&&typeof r.toJSON=="function"){if(!t||!Fm.hasAnchor(r))return r.toJSON(e,t);let s={aliasCount:0,count:1,res:void 0};t.anchors.set(r,s),t.onCreate=i=>{s.res=i,delete t.onCreate};let n=r.toJSON(e,t);return t.onCreate&&t.onCreate(n),n}return typeof r=="bigint"&&!t?.keep?Number(r):r}cl.toJS=al});var _n=T(dl=>{"use strict";var Km=Ri(),ll=U(),Hm=et(),Bi=class{constructor(e){Object.defineProperty(this,ll.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:n,reviver:i}={}){if(!ll.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=Hm.toJS(this,"",o);if(typeof n=="function")for(let{count:l,res:c}of o.anchors.values())n(c,l);return typeof i=="function"?Km.applyReviver(i,{"":a},"",a):a}};dl.NodeBase=Bi});var ms=T(ul=>{"use strict";var Wm=bn(),Gm=us(),Ut=U(),Vm=_n(),Ym=et(),Ui=class extends Vm.NodeBase{constructor(e){super(Ut.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=[],Gm.visit(e,{Node:(i,o)=>{(Ut.isAlias(o)||Ut.hasAnchor(o))&&s.push(o)}}),t&&(t.aliasResolveCache=s));let n;for(let i of s){if(i===this)break;i.anchor===this.source&&(n=i)}return n}toJSON(e,t){if(!t)return{source:this.source};let{anchors:s,doc:n,maxAliasCount:i}=t,o=this.resolve(n,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||(Ym.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=vn(n,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 n=`*${this.source}`;if(e){if(Wm.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`${n} `}return n}};function vn(r,e,t){if(Ut.isAlias(e)){let s=e.resolve(r),n=t&&s&&t.get(s);return n?n.count*n.aliasCount:0}else if(Ut.isCollection(e)){let s=0;for(let n of e.items){let i=vn(r,n,t);i>s&&(s=i)}return s}else if(Ut.isPair(e)){let s=vn(r,e.key,t),n=vn(r,e.value,t);return Math.max(s,n)}return 1}ul.Alias=Ui});var Z=T(qi=>{"use strict";var Jm=U(),zm=_n(),Qm=et(),Xm=r=>!r||typeof r!="function"&&typeof r!="object",tt=class extends zm.NodeBase{constructor(e){super(Jm.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:Qm.toJS(this.value,e,t)}toString(){return String(this.value)}};tt.BLOCK_FOLDED="BLOCK_FOLDED";tt.BLOCK_LITERAL="BLOCK_LITERAL";tt.PLAIN="PLAIN";tt.QUOTE_DOUBLE="QUOTE_DOUBLE";tt.QUOTE_SINGLE="QUOTE_SINGLE";qi.Scalar=tt;qi.isScalarValue=Xm});var gs=T(fl=>{"use strict";var Zm=ms(),gt=U(),hl=Z(),eg="tag:yaml.org,2002:";function tg(r,e,t){if(e){let s=t.filter(i=>i.tag===e),n=s.find(i=>!i.format)??s[0];if(!n)throw new Error(`Tag ${e} not found`);return n}return t.find(s=>s.identify?.(r)&&!s.format)}function sg(r,e,t){if(gt.isDocument(r)&&(r=r.contents),gt.isNode(r))return r;if(gt.isPair(r)){let u=t.schema[gt.MAP].createNode?.(t.schema,null,t);return u.items.push(r),u}(r instanceof String||r instanceof Number||r instanceof Boolean||typeof BigInt<"u"&&r instanceof BigInt)&&(r=r.valueOf());let{aliasDuplicateObjects:s,onAnchor:n,onTagObj:i,schema:o,sourceObjects:a}=t,l;if(s&&r&&typeof r=="object"){if(l=a.get(r),l)return l.anchor??(l.anchor=n(r)),new Zm.Alias(l.anchor);l={anchor:null,node:null},a.set(r,l)}e?.startsWith("!!")&&(e=eg+e.slice(2));let c=tg(r,e,o.tags);if(!c){if(r&&typeof r.toJSON=="function"&&(r=r.toJSON()),!r||typeof r!="object"){let u=new hl.Scalar(r);return l&&(l.node=u),u}c=r instanceof Map?o[gt.MAP]:Symbol.iterator in Object(r)?o[gt.SEQ]:o[gt.MAP]}i&&(i(c),delete t.onTagObj);let d=c?.createNode?c.createNode(t.schema,r,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,r,t):new hl.Scalar(r);return e?d.tag=e:c.default||(d.tag=c.tag),l&&(l.node=d),d}fl.createNode=sg});var In=T(Tn=>{"use strict";var ng=gs(),Pe=U(),rg=_n();function ji(r,e,t){let s=t;for(let n=e.length-1;n>=0;--n){let i=e[n];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return ng.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:r,sourceObjects:new Map})}var pl=r=>r==null||typeof r=="object"&&!!r[Symbol.iterator]().next().done,Fi=class extends rg.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(pl(e))this.add(t);else{let[s,...n]=e,i=this.get(s,!0);if(Pe.isCollection(i))i.addIn(n,t);else if(i===void 0&&this.schema)this.set(s,ji(this.schema,n,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`)}}deleteIn(e){let[t,...s]=e;if(s.length===0)return this.delete(t);let n=this.get(t,!0);if(Pe.isCollection(n))return n.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){let[s,...n]=e,i=this.get(s,!0);return n.length===0?!t&&Pe.isScalar(i)?i.value:i:Pe.isCollection(i)?i.getIn(n,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 n=this.get(t,!0);return Pe.isCollection(n)?n.hasIn(s):!1}setIn(e,t){let[s,...n]=e;if(n.length===0)this.set(s,t);else{let i=this.get(s,!0);if(Pe.isCollection(i))i.setIn(n,t);else if(i===void 0&&this.schema)this.set(s,ji(this.schema,n,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${n}`)}}};Tn.Collection=Fi;Tn.collectionFromPath=ji;Tn.isEmptyPath=pl});var ys=T(Cn=>{"use strict";var ig=r=>r.replace(/^(?!$)(?: $)?/gm,"#");function Ki(r,e){return/^\n+$/.test(r)?r.substring(1):e?r.replace(/^(?! *$)/gm,e):r}var og=(r,e,t)=>r.endsWith(`
7
7
  `)?Ki(t,e):t.includes(`
8
8
  `)?`
9
- `+Ki(t,e):(r.endsWith(" ")?"":" ")+t;Cn.indentComment=Ki;Cn.lineComment=ig;Cn.stringifyComment=rg});var gl=T(ws=>{"use strict";var og="flow",Hi="block",An="quoted";function ag(r,e,t="flow",{indentAtStart:s,lineWidth:n=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!n||n<0)return r;n<i&&(i=0);let l=Math.max(1+i,1+n-e.length);if(r.length<=l)return r;let c=[],d={},u=n-e.length;typeof s=="number"&&(s>n-Math.max(2,i)?c.push(0):u=n-s);let h,m,g=!1,f=-1,y=-1,w=-1;t===Hi&&(f=ml(r,f,e.length),f!==-1&&(u=f+l));for(let _;_=r[f+=1];){if(t===An&&_==="\\"){switch(y=f,r[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}w=f}if(_===`
9
+ `+Ki(t,e):(r.endsWith(" ")?"":" ")+t;Cn.indentComment=Ki;Cn.lineComment=og;Cn.stringifyComment=ig});var gl=T(ws=>{"use strict";var ag="flow",Hi="block",An="quoted";function cg(r,e,t="flow",{indentAtStart:s,lineWidth:n=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!n||n<0)return r;n<i&&(i=0);let l=Math.max(1+i,1+n-e.length);if(r.length<=l)return r;let c=[],d={},u=n-e.length;typeof s=="number"&&(s>n-Math.max(2,i)?c.push(0):u=n-s);let h,m,g=!1,f=-1,y=-1,w=-1;t===Hi&&(f=ml(r,f,e.length),f!==-1&&(u=f+l));for(let _;_=r[f+=1];){if(t===An&&_==="\\"){switch(y=f,r[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}w=f}if(_===`
10
10
  `)t===Hi&&(f=ml(r,f,e.length)),u=f+e.length+l,h=void 0;else{if(_===" "&&m&&m!==" "&&m!==`
11
11
  `&&m!==" "){let v=r[f+1];v&&v!==" "&&v!==`
12
12
  `&&v!==" "&&(h=f)}if(f>=u)if(h)c.push(h),u=h+l,h=void 0;else if(t===An){for(;m===" "||m===" ";)m=_,_=r[f+=1],g=!0;let v=f>w+1?f-2:y-1;if(d[v])return r;c.push(v),d[v]=!0,u=v+l,h=void 0}else g=!0}m=_}if(g&&a&&a(),c.length===0)return r;o&&o();let S=r.slice(0,c[0]);for(let _=0;_<c.length;++_){let v=c[_],I=c[_+1]||r.length;v===0?S=`
13
13
  ${e}${r.slice(0,I)}`:(t===An&&d[v]&&(S+=`${r[v]}\\`),S+=`
14
14
  ${e}${r.slice(v+1,I)}`)}return S}function ml(r,e,t){let s=e,n=e+1,i=r[n];for(;i===" "||i===" ";)if(e<n+t)i=r[++e];else{do i=r[++e];while(i&&i!==`
15
- `);s=e,n=e+1,i=r[n]}return s}ws.FOLD_BLOCK=Hi;ws.FOLD_FLOW=og;ws.FOLD_QUOTED=An;ws.foldFlowLines=ag});var ks=T(yl=>{"use strict";var Ae=Z(),st=gl(),Nn=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),xn=r=>/^(%|---|\.\.\.)/m.test(r);function cg(r,e,t){if(!e||e<0)return!1;let s=e-t,n=r.length;if(n<=s)return!1;for(let i=0,o=0;i<n;++i)if(r[i]===`
15
+ `);s=e,n=e+1,i=r[n]}return s}ws.FOLD_BLOCK=Hi;ws.FOLD_FLOW=ag;ws.FOLD_QUOTED=An;ws.foldFlowLines=cg});var ks=T(yl=>{"use strict";var Ae=Z(),st=gl(),Nn=(r,e)=>({indentAtStart:e?r.indent.length:r.indentAtStart,lineWidth:r.options.lineWidth,minContentWidth:r.options.minContentWidth}),xn=r=>/^(%|---|\.\.\.)/m.test(r);function lg(r,e,t){if(!e||e<0)return!1;let s=e-t,n=r.length;if(n<=s)return!1;for(let i=0,o=0;i<n;++i)if(r[i]===`
16
16
  `){if(i-o>s)return!0;if(o=i+1,n-o<=s)return!1}return!0}function Ss(r,e){let t=JSON.stringify(r);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:s}=e,n=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(xn(r)?" ":""),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<n)l+=1;else{for(o+=t.slice(a,l)+`
17
17
 
18
18
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
@@ -21,7 +21,7 @@ ${e}${r.slice(v+1,I)}`)}return S}function ml(r,e,t){let s=e,n=e+1,i=r[n];for(;i=
21
21
  ${t}`)+"'";return e.implicitKey?s:st.foldFlowLines(s,t,st.FOLD_FLOW,Nn(e,!1))}function qt(r,e){let{singleQuote:t}=e.options,s;if(t===!1)s=Ss;else{let n=r.includes('"'),i=r.includes("'");n&&!i?s=Wi:i&&!n?s=Ss:s=t?Wi:Ss}return s(r,e)}var Gi;try{Gi=new RegExp(`(^|(?<!
22
22
  ))
23
23
  +(?!
24
- |$)`,"g")}catch{Gi=/\n+(?!\n|$)/g}function En({comment:r,type:e,value:t},s,n,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||xn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===Ae.Scalar.BLOCK_FOLDED?!1:e===Ae.Scalar.BLOCK_LITERAL?!0:!cg(t,l,c.length);if(!t)return d?`|
24
+ |$)`,"g")}catch{Gi=/\n+(?!\n|$)/g}function En({comment:r,type:e,value:t},s,n,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||xn(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===Ae.Scalar.BLOCK_FOLDED?!1:e===Ae.Scalar.BLOCK_LITERAL?!0:!lg(t,l,c.length);if(!t)return d?`|
25
25
  `:`>
26
26
  `;let u,h;for(h=t.length;h>0;--h){let I=t[h-1];if(I!==`
27
27
  `&&I!==" "&&I!==" ")break}let m=t.substring(h),g=m.indexOf(`
@@ -30,12 +30,12 @@ ${t}`)+"'";return e.implicitKey?s:st.foldFlowLines(s,t,st.FOLD_FLOW,Nn(e,!1))}fu
30
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(r&&(v+=" "+a(r.replace(/ ?[\r\n]+/g," ")),n&&n()),!d){let I=t.replace(/\n+/g,`
31
31
  $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),N=!1,D=Nn(s,!0);o!=="folded"&&e!==Ae.Scalar.BLOCK_FOLDED&&(D.onOverflow=()=>{N=!0});let C=st.foldFlowLines(`${S}${I}${m}`,c,st.FOLD_BLOCK,D);if(!N)return`>${v}
32
32
  ${c}${C}`}return t=t.replace(/\n+/g,`$&${c}`),`|${v}
33
- ${c}${S}${t}${m}`}function lg(r,e,t,s){let{type:n,value:i}=r,{actualString:o,implicitKey:a,indent:l,indentStep:c,inFlow:d}=e;if(a&&i.includes(`
33
+ ${c}${S}${t}${m}`}function dg(r,e,t,s){let{type:n,value:i}=r,{actualString:o,implicitKey:a,indent:l,indentStep:c,inFlow:d}=e;if(a&&i.includes(`
34
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
35
  `)?qt(i,e):En(r,e,t,s);if(!a&&!d&&n!==Ae.Scalar.PLAIN&&i.includes(`
36
36
  `))return En(r,e,t,s);if(xn(i)){if(l==="")return e.forceBlockIndent=!0,En(r,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:m,tags:g}=e.doc.schema;if(g.some(h)||m?.some(h))return qt(i,e)}return a?u:st.foldFlowLines(u,l,st.FOLD_FLOW,Nn(e,!1))}function dg(r,e,t,s){let{implicitKey:n,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==Ae.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ae.Scalar.QUOTE_DOUBLE);let l=d=>{switch(d){case Ae.Scalar.BLOCK_FOLDED:case Ae.Scalar.BLOCK_LITERAL:return n||i?qt(o.value,e):En(o,e,t,s);case Ae.Scalar.QUOTE_DOUBLE:return Ss(o.value,e);case Ae.Scalar.QUOTE_SINGLE:return Wi(o.value,e);case Ae.Scalar.PLAIN:return lg(o,e,t,s);default:return null}},c=l(a);if(c===null){let{defaultKeyType:d,defaultStringType:u}=e.options,h=n&&d||u;if(c=l(h),c===null)throw new Error(`Unsupported default string type ${h}`)}return c}yl.stringifyString=dg});var bs=T(Vi=>{"use strict";var ug=bn(),nt=U(),hg=ys(),fg=ks();function pg(r,e){let t=Object.assign({blockQuote:!0,commentString:hg.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},r.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:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}function mg(r,e){if(e.tag){let n=r.filter(i=>i.tag===e.tag);if(n.length>0)return n.find(i=>i.format===e.format)??n[0]}let t,s;if(nt.isScalar(e)){s=e.value;let n=r.filter(i=>i.identify?.(s));if(n.length>1){let i=n.filter(o=>o.test);i.length>0&&(n=i)}t=n.find(i=>i.format===e.format)??n.find(i=>!i.format)}else s=e,t=r.find(n=>n.nodeClass&&s instanceof n.nodeClass);if(!t){let n=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${n} value`)}return t}function gg(r,e,{anchors:t,doc:s}){if(!s.directives)return"";let n=[],i=(nt.isScalar(r)||nt.isCollection(r))&&r.anchor;i&&ug.anchorIsValid(i)&&(t.add(i),n.push(`&${i}`));let o=r.tag??(e.default?null:e.tag);return o&&n.push(s.directives.tagString(o)),n.join(" ")}function yg(r,e,t,s){if(nt.isPair(r))return r.toString(e,t,s);if(nt.isAlias(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let n,i=nt.isNode(r)?r:e.doc.createNode(r,{onTagObj:l=>n=l});n??(n=mg(e.doc.schema.tags,i));let o=gg(i,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof n.stringify=="function"?n.stringify(i,e,t,s):nt.isScalar(i)?fg.stringifyString(i,e,t,s):i.toString(e,t,s);return o?nt.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
38
- ${e.indent}${a}`:a}Vi.createStringifyContext=pg;Vi.stringify=yg});var bl=T(kl=>{"use strict";var Fe=U(),wl=Z(),Sl=bs(),_s=ys();function wg({key:r,value:e},t,s,n){let{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:c,indentSeq:d,simpleKeys:u}}=t,h=Fe.isNode(r)&&r.comment||null;if(u){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Fe.isCollection(r)||!Fe.isNode(r)&&typeof r=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let m=!u&&(!r||h&&e==null&&!t.inFlow||Fe.isCollection(r)||(Fe.isScalar(r)?r.type===wl.Scalar.BLOCK_FOLDED||r.type===wl.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(u||!i),indent:a+l});let g=!1,f=!1,y=Sl.stringify(r,t,()=>g=!0,()=>f=!0);if(!m&&!t.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(i||e==null)return g&&s&&s(),y===""?"?":m?`? ${y}`:y}else if(i&&!u||e==null&&m)return y=`? ${y}`,h&&!g?y+=_s.lineComment(y,t.indent,c(h)):f&&n&&n(),y;g&&(h=null),m?(h&&(y+=_s.lineComment(y,t.indent,c(h))),y=`? ${y}
37
+ ${l}`);if(o){let h=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(u),{compat:m,tags:g}=e.doc.schema;if(g.some(h)||m?.some(h))return qt(i,e)}return a?u:st.foldFlowLines(u,l,st.FOLD_FLOW,Nn(e,!1))}function ug(r,e,t,s){let{implicitKey:n,inFlow:i}=e,o=typeof r.value=="string"?r:Object.assign({},r,{value:String(r.value)}),{type:a}=r;a!==Ae.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ae.Scalar.QUOTE_DOUBLE);let l=d=>{switch(d){case Ae.Scalar.BLOCK_FOLDED:case Ae.Scalar.BLOCK_LITERAL:return n||i?qt(o.value,e):En(o,e,t,s);case Ae.Scalar.QUOTE_DOUBLE:return Ss(o.value,e);case Ae.Scalar.QUOTE_SINGLE:return Wi(o.value,e);case Ae.Scalar.PLAIN:return dg(o,e,t,s);default:return null}},c=l(a);if(c===null){let{defaultKeyType:d,defaultStringType:u}=e.options,h=n&&d||u;if(c=l(h),c===null)throw new Error(`Unsupported default string type ${h}`)}return c}yl.stringifyString=ug});var bs=T(Vi=>{"use strict";var hg=bn(),nt=U(),fg=ys(),pg=ks();function mg(r,e){let t=Object.assign({blockQuote:!0,commentString:fg.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},r.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:r,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}function gg(r,e){if(e.tag){let n=r.filter(i=>i.tag===e.tag);if(n.length>0)return n.find(i=>i.format===e.format)??n[0]}let t,s;if(nt.isScalar(e)){s=e.value;let n=r.filter(i=>i.identify?.(s));if(n.length>1){let i=n.filter(o=>o.test);i.length>0&&(n=i)}t=n.find(i=>i.format===e.format)??n.find(i=>!i.format)}else s=e,t=r.find(n=>n.nodeClass&&s instanceof n.nodeClass);if(!t){let n=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${n} value`)}return t}function yg(r,e,{anchors:t,doc:s}){if(!s.directives)return"";let n=[],i=(nt.isScalar(r)||nt.isCollection(r))&&r.anchor;i&&hg.anchorIsValid(i)&&(t.add(i),n.push(`&${i}`));let o=r.tag??(e.default?null:e.tag);return o&&n.push(s.directives.tagString(o)),n.join(" ")}function wg(r,e,t,s){if(nt.isPair(r))return r.toString(e,t,s);if(nt.isAlias(r)){if(e.doc.directives)return r.toString(e);if(e.resolvedAliases?.has(r))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(r):e.resolvedAliases=new Set([r]),r=r.resolve(e.doc)}let n,i=nt.isNode(r)?r:e.doc.createNode(r,{onTagObj:l=>n=l});n??(n=gg(e.doc.schema.tags,i));let o=yg(i,n,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof n.stringify=="function"?n.stringify(i,e,t,s):nt.isScalar(i)?pg.stringifyString(i,e,t,s):i.toString(e,t,s);return o?nt.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
38
+ ${e.indent}${a}`:a}Vi.createStringifyContext=mg;Vi.stringify=wg});var bl=T(kl=>{"use strict";var Fe=U(),wl=Z(),Sl=bs(),_s=ys();function Sg({key:r,value:e},t,s,n){let{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:c,indentSeq:d,simpleKeys:u}}=t,h=Fe.isNode(r)&&r.comment||null;if(u){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Fe.isCollection(r)||!Fe.isNode(r)&&typeof r=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let m=!u&&(!r||h&&e==null&&!t.inFlow||Fe.isCollection(r)||(Fe.isScalar(r)?r.type===wl.Scalar.BLOCK_FOLDED||r.type===wl.Scalar.BLOCK_LITERAL:typeof r=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!m&&(u||!i),indent:a+l});let g=!1,f=!1,y=Sl.stringify(r,t,()=>g=!0,()=>f=!0);if(!m&&!t.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");m=!0}if(t.inFlow){if(i||e==null)return g&&s&&s(),y===""?"?":m?`? ${y}`:y}else if(i&&!u||e==null&&m)return y=`? ${y}`,h&&!g?y+=_s.lineComment(y,t.indent,c(h)):f&&n&&n(),y;g&&(h=null),m?(h&&(y+=_s.lineComment(y,t.indent,c(h))),y=`? ${y}
39
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,!m&&!h&&Fe.isScalar(e)&&(t.indentAtStart=y.length+1),f=!1,!d&&l.length>=2&&!t.inFlow&&!m&&Fe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let v=!1,I=Sl.stringify(e,t,()=>v=!0,()=>f=!0),N=" ";if(h||w||S){if(N=w?`
40
40
  `:"",S){let D=c(S);N+=`
41
41
  ${_s.indentComment(D,t.indent)}`}I===""&&!t.inFlow?N===`
@@ -45,32 +45,32 @@ ${_s.indentComment(D,t.indent)}`}I===""&&!t.inFlow?N===`
45
45
  ${t.indent}`}else if(!m&&Fe.isCollection(e)){let D=I[0],C=I.indexOf(`
46
46
  `),E=C!==-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&&$<C&&I[$+1]==="!"&&($=I.indexOf(" ",$+1)),($===-1||C<$)&&(W=!0)}W||(N=`
47
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&&n&&n(),y}kl.stringifyPair=wg});var Ji=T(Yi=>{"use strict";var _l=H("process");function Sg(r,...e){r==="debug"&&console.log(...e)}function kg(r,e){(r==="debug"||r==="warn")&&(typeof _l.emitWarning=="function"?_l.emitWarning(e):console.warn(e))}Yi.debug=Sg;Yi.warn=kg});var Ln=T(Dn=>{"use strict";var vs=U(),vl=Z(),On="<<",Mn={identify:r=>r===On||typeof r=="symbol"&&r.description===On,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new vl.Scalar(Symbol(On)),{addToJSMap:Tl}),stringify:()=>On},bg=(r,e)=>(Mn.identify(e)||vs.isScalar(e)&&(!e.type||e.type===vl.Scalar.PLAIN)&&Mn.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Mn.tag&&t.default);function Tl(r,e,t){if(t=r&&vs.isAlias(t)?t.resolve(r.doc):t,vs.isSeq(t))for(let s of t.items)zi(r,e,s);else if(Array.isArray(t))for(let s of t)zi(r,e,s);else zi(r,e,t)}function zi(r,e,t){let s=r&&vs.isAlias(t)?t.resolve(r.doc):t;if(!vs.isMap(s))throw new Error("Merge sources must be maps or map aliases");let n=s.toJSON(null,r,Map);for(let[i,o]of n)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}Dn.addMergeToJSMap=Tl;Dn.isMergeKey=bg;Dn.merge=Mn});var Xi=T(Al=>{"use strict";var _g=Ji(),Il=Ln(),vg=bs(),Cl=U(),Qi=et();function Tg(r,e,{key:t,value:s}){if(Cl.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,s);else if(Il.isMergeKey(r,t))Il.addMergeToJSMap(r,e,s);else{let n=Qi.toJS(t,"",r);if(e instanceof Map)e.set(n,Qi.toJS(s,n,r));else if(e instanceof Set)e.add(n);else{let i=Ig(t,n,r),o=Qi.toJS(s,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Ig(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Cl.isNode(r)&&t?.doc){let s=vg.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 n=r.toString(s);if(!t.mapKeyWarned){let i=JSON.stringify(n);i.length>40&&(i=i.substring(0,36)+'..."'),_g.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 n}return JSON.stringify(e)}Al.addPairToJSMap=Tg});var rt=T(Zi=>{"use strict";var El=gs(),Cg=bl(),Ag=Xi(),Pn=U();function Eg(r,e,t){let s=El.createNode(r,void 0,t),n=El.createNode(e,void 0,t);return new $n(s,n)}var $n=class r{constructor(e,t=null){Object.defineProperty(this,Pn.NODE_TYPE,{value:Pn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return Pn.isNode(t)&&(t=t.clone(e)),Pn.isNode(s)&&(s=s.clone(e)),new r(t,s)}toJSON(e,t){let s=t?.mapAsMap?new Map:{};return Ag.addPairToJSMap(t,s,this)}toString(e,t,s){return e?.doc?Cg.stringifyPair(this,e,t,s):JSON.stringify(this)}};Zi.Pair=$n;Zi.createPair=Eg});var eo=T(xl=>{"use strict";var yt=U(),Nl=bs(),Rn=ys();function Ng(r,e,t){return(e.inFlow??r.flow?Og:xg)(r,e,t)}function xg({comment:r,items:e},t,{blockItemPrefix:s,flowChars:n,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 g=0;g<e.length;++g){let f=e[g],y=null;if(yt.isNode(f))!u&&f.spaceBefore&&h.push(""),Bn(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(""),Bn(t,h,S.commentBefore,u))}u=!1;let w=Nl.stringify(f,d,()=>y=null,()=>u=!0);y&&(w+=Rn.lineComment(w,i,c(y))),u&&y&&(u=!1),h.push(s+w)}let m;if(h.length===0)m=n.start+n.end;else{m=h[0];for(let g=1;g<h.length;++g){let f=h[g];m+=f?`
48
+ `)&&(N="");return y+=N+I,t.inFlow?v&&s&&s():_&&!v?y+=_s.lineComment(y,t.indent,c(_)):f&&n&&n(),y}kl.stringifyPair=Sg});var Ji=T(Yi=>{"use strict";var _l=H("process");function kg(r,...e){r==="debug"&&console.log(...e)}function bg(r,e){(r==="debug"||r==="warn")&&(typeof _l.emitWarning=="function"?_l.emitWarning(e):console.warn(e))}Yi.debug=kg;Yi.warn=bg});var Ln=T(Dn=>{"use strict";var vs=U(),vl=Z(),On="<<",Mn={identify:r=>r===On||typeof r=="symbol"&&r.description===On,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new vl.Scalar(Symbol(On)),{addToJSMap:Tl}),stringify:()=>On},_g=(r,e)=>(Mn.identify(e)||vs.isScalar(e)&&(!e.type||e.type===vl.Scalar.PLAIN)&&Mn.identify(e.value))&&r?.doc.schema.tags.some(t=>t.tag===Mn.tag&&t.default);function Tl(r,e,t){if(t=r&&vs.isAlias(t)?t.resolve(r.doc):t,vs.isSeq(t))for(let s of t.items)zi(r,e,s);else if(Array.isArray(t))for(let s of t)zi(r,e,s);else zi(r,e,t)}function zi(r,e,t){let s=r&&vs.isAlias(t)?t.resolve(r.doc):t;if(!vs.isMap(s))throw new Error("Merge sources must be maps or map aliases");let n=s.toJSON(null,r,Map);for(let[i,o]of n)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}Dn.addMergeToJSMap=Tl;Dn.isMergeKey=_g;Dn.merge=Mn});var Xi=T(Al=>{"use strict";var vg=Ji(),Il=Ln(),Tg=bs(),Cl=U(),Qi=et();function Ig(r,e,{key:t,value:s}){if(Cl.isNode(t)&&t.addToJSMap)t.addToJSMap(r,e,s);else if(Il.isMergeKey(r,t))Il.addMergeToJSMap(r,e,s);else{let n=Qi.toJS(t,"",r);if(e instanceof Map)e.set(n,Qi.toJS(s,n,r));else if(e instanceof Set)e.add(n);else{let i=Cg(t,n,r),o=Qi.toJS(s,i,r);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Cg(r,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Cl.isNode(r)&&t?.doc){let s=Tg.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 n=r.toString(s);if(!t.mapKeyWarned){let i=JSON.stringify(n);i.length>40&&(i=i.substring(0,36)+'..."'),vg.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 n}return JSON.stringify(e)}Al.addPairToJSMap=Ig});var rt=T(Zi=>{"use strict";var El=gs(),Ag=bl(),Eg=Xi(),Pn=U();function Ng(r,e,t){let s=El.createNode(r,void 0,t),n=El.createNode(e,void 0,t);return new $n(s,n)}var $n=class r{constructor(e,t=null){Object.defineProperty(this,Pn.NODE_TYPE,{value:Pn.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return Pn.isNode(t)&&(t=t.clone(e)),Pn.isNode(s)&&(s=s.clone(e)),new r(t,s)}toJSON(e,t){let s=t?.mapAsMap?new Map:{};return Eg.addPairToJSMap(t,s,this)}toString(e,t,s){return e?.doc?Ag.stringifyPair(this,e,t,s):JSON.stringify(this)}};Zi.Pair=$n;Zi.createPair=Ng});var eo=T(xl=>{"use strict";var yt=U(),Nl=bs(),Rn=ys();function xg(r,e,t){return(e.inFlow??r.flow?Mg:Og)(r,e,t)}function Og({comment:r,items:e},t,{blockItemPrefix:s,flowChars:n,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 g=0;g<e.length;++g){let f=e[g],y=null;if(yt.isNode(f))!u&&f.spaceBefore&&h.push(""),Bn(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(""),Bn(t,h,S.commentBefore,u))}u=!1;let w=Nl.stringify(f,d,()=>y=null,()=>u=!0);y&&(w+=Rn.lineComment(w,i,c(y))),u&&y&&(u=!1),h.push(s+w)}let m;if(h.length===0)m=n.start+n.end;else{m=h[0];for(let g=1;g<h.length;++g){let f=h[g];m+=f?`
49
49
  ${l}${f}`:`
50
50
  `}}return r?(m+=`
51
- `+Rn.indentComment(c(r),l),a&&a()):u&&o&&o(),m}function Og({items:r},e,{flowChars:t,itemIndent:s}){let{indent:n,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 g=0;g<r.length;++g){let f=r[g],y=null;if(yt.isNode(f))f.spaceBefore&&u.push(""),Bn(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(""),Bn(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=Nl.stringify(f,l,()=>y=null);c||(c=u.length>d||w.includes(`
51
+ `+Rn.indentComment(c(r),l),a&&a()):u&&o&&o(),m}function Mg({items:r},e,{flowChars:t,itemIndent:s}){let{indent:n,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 g=0;g<r.length;++g){let f=r[g],y=null;if(yt.isNode(f))f.spaceBefore&&u.push(""),Bn(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(""),Bn(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=Nl.stringify(f,l,()=>y=null);c||(c=u.length>d||w.includes(`
52
52
  `)),g<r.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+=Rn.lineComment(w,s,a(y))),u.push(w),d=u.length}let{start:h,end:m}=t;if(u.length===0)return h+m;if(!c){let g=u.reduce((f,y)=>f+y.length+2,2);c=e.options.lineWidth>0&&g>e.options.lineWidth}if(c){let g=h;for(let f of u)g+=f?`
53
53
  ${i}${n}${f}`:`
54
54
  `;return`${g}
55
- ${n}${m}`}else return`${h}${o}${u.join(" ")}${o}${m}`}function Bn({indent:r,options:{commentString:e}},t,s,n){if(s&&n&&(s=s.replace(/^\n+/,"")),s){let i=Rn.indentComment(e(s),r);t.push(i.trimStart())}}xl.stringifyCollection=Ng});var ot=T(so=>{"use strict";var Mg=eo(),Dg=Xi(),Lg=In(),it=U(),Un=rt(),Pg=Z();function Ts(r,e){let t=it.isScalar(e)?e.value:e;for(let s of r)if(it.isPair(s)&&(s.key===e||s.key===t||it.isScalar(s.key)&&s.key.value===t))return s}var to=class extends Lg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(it.MAP,e),this.items=[]}static from(e,t,s){let{keepUndefined:n,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||n)&&o.items.push(Un.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;it.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new Un.Pair(e,e?.value):s=new Un.Pair(e.key,e.value);let n=Ts(this.items,s.key),i=this.schema?.sortMapEntries;if(n){if(!t)throw new Error(`Key ${s.key} already set`);it.isScalar(n.value)&&Pg.isScalarValue(s.value)?n.value.value=s.value:n.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 n=Ts(this.items,e)?.value;return(!t&&it.isScalar(n)?n.value:n)??void 0}has(e){return!!Ts(this.items,e)}set(e,t){this.add(new Un.Pair(e,t),!0)}toJSON(e,t,s){let n=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(n);for(let i of this.items)Dg.addPairToJSMap(t,n,i);return n}toString(e,t,s){if(!e)return JSON.stringify(this);for(let n of this.items)if(!it.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Mg.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}};so.YAMLMap=to;so.findPair=Ts});var jt=T(Ml=>{"use strict";var $g=U(),Ol=ot(),Rg={collection:"map",default:!0,nodeClass:Ol.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return $g.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ol.YAMLMap.from(r,e,t)};Ml.map=Rg});var at=T(Dl=>{"use strict";var Bg=gs(),Ug=eo(),qg=In(),jn=U(),jg=Z(),Fg=et(),no=class extends qg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(jn.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 n=this.items[s];return!t&&jn.isScalar(n)?n.value:n}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 n=this.items[s];jn.isScalar(n)&&jg.isScalarValue(t)?n.value=t:this.items[s]=t}toJSON(e,t){let s=[];t?.onCreate&&t.onCreate(s);let n=0;for(let i of this.items)s.push(Fg.toJS(i,String(n++),t));return s}toString(e,t,s){return e?Ug.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){let{replacer:n}=s,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof n=="function"){let l=t instanceof Set?a:String(o++);a=n.call(t,l,a)}i.items.push(Bg.createNode(a,void 0,s))}}return i}};function qn(r){let e=jn.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Dl.YAMLSeq=no});var Ft=T(Pl=>{"use strict";var Kg=U(),Ll=at(),Hg={collection:"seq",default:!0,nodeClass:Ll.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Kg.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ll.YAMLSeq.from(r,e,t)};Pl.seq=Hg});var Is=T($l=>{"use strict";var Wg=ks(),Gg={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,s){return e=Object.assign({actualString:!0},e),Wg.stringifyString(r,e,t,s)}};$l.string=Gg});var Fn=T(Ul=>{"use strict";var Rl=Z(),Bl={identify:r=>r==null,createNode:()=>new Rl.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Rl.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Bl.test.test(r)?r:e.options.nullStr};Ul.nullTag=Bl});var ro=T(jl=>{"use strict";var Vg=Z(),ql={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Vg.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&ql.test.test(r)){let s=r[0]==="t"||r[0]==="T";if(e===s)return r}return e?t.options.trueStr:t.options.falseStr}};jl.boolTag=ql});var Kt=T(Fl=>{"use strict";function Yg({format:r,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);let n=typeof s=="number"?s:Number(s);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let i=Object.is(s,-0)?"-0":JSON.stringify(s);if(!r&&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}Fl.stringifyNumber=Yg});var oo=T(Kn=>{"use strict";var Jg=Z(),io=Kt(),zg={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:io.stringifyNumber},Qg={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():io.stringifyNumber(r)}},Xg={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new Jg.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:io.stringifyNumber};Kn.float=Xg;Kn.floatExp=Qg;Kn.floatNaN=zg});var co=T(Wn=>{"use strict";var Kl=Kt(),Hn=r=>typeof r=="bigint"||Number.isInteger(r),ao=(r,e,t,{intAsBigInt:s})=>s?BigInt(r):parseInt(r.substring(e),t);function Hl(r,e,t){let{value:s}=r;return Hn(s)&&s>=0?t+s.toString(e):Kl.stringifyNumber(r)}var Zg={identify:r=>Hn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>ao(r,2,8,t),stringify:r=>Hl(r,8,"0o")},ey={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>ao(r,0,10,t),stringify:Kl.stringifyNumber},ty={identify:r=>Hn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>ao(r,2,16,t),stringify:r=>Hl(r,16,"0x")};Wn.int=ey;Wn.intHex=ty;Wn.intOct=Zg});var Gl=T(Wl=>{"use strict";var sy=jt(),ny=Fn(),ry=Ft(),iy=Is(),oy=ro(),lo=oo(),uo=co(),ay=[sy.map,ry.seq,iy.string,ny.nullTag,oy.boolTag,uo.intOct,uo.int,uo.intHex,lo.floatNaN,lo.floatExp,lo.float];Wl.schema=ay});var Jl=T(Yl=>{"use strict";var cy=Z(),ly=jt(),dy=Ft();function Vl(r){return typeof r=="bigint"||Number.isInteger(r)}var Gn=({value:r})=>JSON.stringify(r),uy=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Gn},{identify:r=>r==null,createNode:()=>new cy.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Gn},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Gn},{identify:Vl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Vl(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Gn}],hy={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},fy=[ly.map,dy.seq].concat(uy,hy);Yl.schema=fy});var fo=T(zl=>{"use strict";var Cs=H("buffer"),ho=Z(),py=ks(),my={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Cs.Buffer=="function")return Cs.Buffer.from(r,"base64");if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let n=0;n<t.length;++n)s[n]=t.charCodeAt(n);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),r},stringify({comment:r,type:e,value:t},s,n,i){if(!t)return"";let o=t,a;if(typeof Cs.Buffer=="function")a=o instanceof Cs.Buffer?o.toString("base64"):Cs.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=ho.Scalar.BLOCK_LITERAL),e!==ho.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===ho.Scalar.BLOCK_LITERAL?`
56
- `:" ")}return py.stringifyString({comment:r,type:e,value:a},s,n,i)}};zl.binary=my});var Jn=T(Yn=>{"use strict";var Vn=U(),po=rt(),gy=Z(),yy=at();function Ql(r,e){if(Vn.isSeq(r))for(let t=0;t<r.items.length;++t){let s=r.items[t];if(!Vn.isPair(s)){if(Vn.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let n=s.items[0]||new po.Pair(new gy.Scalar(null));if(s.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${s.commentBefore}
55
+ ${n}${m}`}else return`${h}${o}${u.join(" ")}${o}${m}`}function Bn({indent:r,options:{commentString:e}},t,s,n){if(s&&n&&(s=s.replace(/^\n+/,"")),s){let i=Rn.indentComment(e(s),r);t.push(i.trimStart())}}xl.stringifyCollection=xg});var ot=T(so=>{"use strict";var Dg=eo(),Lg=Xi(),Pg=In(),it=U(),Un=rt(),$g=Z();function Ts(r,e){let t=it.isScalar(e)?e.value:e;for(let s of r)if(it.isPair(s)&&(s.key===e||s.key===t||it.isScalar(s.key)&&s.key.value===t))return s}var to=class extends Pg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(it.MAP,e),this.items=[]}static from(e,t,s){let{keepUndefined:n,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||n)&&o.items.push(Un.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;it.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new Un.Pair(e,e?.value):s=new Un.Pair(e.key,e.value);let n=Ts(this.items,s.key),i=this.schema?.sortMapEntries;if(n){if(!t)throw new Error(`Key ${s.key} already set`);it.isScalar(n.value)&&$g.isScalarValue(s.value)?n.value.value=s.value:n.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 n=Ts(this.items,e)?.value;return(!t&&it.isScalar(n)?n.value:n)??void 0}has(e){return!!Ts(this.items,e)}set(e,t){this.add(new Un.Pair(e,t),!0)}toJSON(e,t,s){let n=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(n);for(let i of this.items)Lg.addPairToJSMap(t,n,i);return n}toString(e,t,s){if(!e)return JSON.stringify(this);for(let n of this.items)if(!it.isPair(n))throw new Error(`Map items must all be pairs; found ${JSON.stringify(n)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Dg.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}};so.YAMLMap=to;so.findPair=Ts});var jt=T(Ml=>{"use strict";var Rg=U(),Ol=ot(),Bg={collection:"map",default:!0,nodeClass:Ol.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(r,e){return Rg.isMap(r)||e("Expected a mapping for this tag"),r},createNode:(r,e,t)=>Ol.YAMLMap.from(r,e,t)};Ml.map=Bg});var at=T(Dl=>{"use strict";var Ug=gs(),qg=eo(),jg=In(),jn=U(),Fg=Z(),Kg=et(),no=class extends jg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(jn.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 n=this.items[s];return!t&&jn.isScalar(n)?n.value:n}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 n=this.items[s];jn.isScalar(n)&&Fg.isScalarValue(t)?n.value=t:this.items[s]=t}toJSON(e,t){let s=[];t?.onCreate&&t.onCreate(s);let n=0;for(let i of this.items)s.push(Kg.toJS(i,String(n++),t));return s}toString(e,t,s){return e?qg.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){let{replacer:n}=s,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof n=="function"){let l=t instanceof Set?a:String(o++);a=n.call(t,l,a)}i.items.push(Ug.createNode(a,void 0,s))}}return i}};function qn(r){let e=jn.isScalar(r)?r.value:r;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Dl.YAMLSeq=no});var Ft=T(Pl=>{"use strict";var Hg=U(),Ll=at(),Wg={collection:"seq",default:!0,nodeClass:Ll.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(r,e){return Hg.isSeq(r)||e("Expected a sequence for this tag"),r},createNode:(r,e,t)=>Ll.YAMLSeq.from(r,e,t)};Pl.seq=Wg});var Is=T($l=>{"use strict";var Gg=ks(),Vg={identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify(r,e,t,s){return e=Object.assign({actualString:!0},e),Gg.stringifyString(r,e,t,s)}};$l.string=Vg});var Fn=T(Ul=>{"use strict";var Rl=Z(),Bl={identify:r=>r==null,createNode:()=>new Rl.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new Rl.Scalar(null),stringify:({source:r},e)=>typeof r=="string"&&Bl.test.test(r)?r:e.options.nullStr};Ul.nullTag=Bl});var ro=T(jl=>{"use strict";var Yg=Z(),ql={identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:r=>new Yg.Scalar(r[0]==="t"||r[0]==="T"),stringify({source:r,value:e},t){if(r&&ql.test.test(r)){let s=r[0]==="t"||r[0]==="T";if(e===s)return r}return e?t.options.trueStr:t.options.falseStr}};jl.boolTag=ql});var Kt=T(Fl=>{"use strict";function Jg({format:r,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);let n=typeof s=="number"?s:Number(s);if(!isFinite(n))return isNaN(n)?".nan":n<0?"-.inf":".inf";let i=Object.is(s,-0)?"-0":JSON.stringify(s);if(!r&&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}Fl.stringifyNumber=Jg});var oo=T(Kn=>{"use strict";var zg=Z(),io=Kt(),Qg={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:io.stringifyNumber},Xg={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():io.stringifyNumber(r)}},Zg={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(r){let e=new zg.Scalar(parseFloat(r)),t=r.indexOf(".");return t!==-1&&r[r.length-1]==="0"&&(e.minFractionDigits=r.length-t-1),e},stringify:io.stringifyNumber};Kn.float=Zg;Kn.floatExp=Xg;Kn.floatNaN=Qg});var co=T(Wn=>{"use strict";var Kl=Kt(),Hn=r=>typeof r=="bigint"||Number.isInteger(r),ao=(r,e,t,{intAsBigInt:s})=>s?BigInt(r):parseInt(r.substring(e),t);function Hl(r,e,t){let{value:s}=r;return Hn(s)&&s>=0?t+s.toString(e):Kl.stringifyNumber(r)}var ey={identify:r=>Hn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(r,e,t)=>ao(r,2,8,t),stringify:r=>Hl(r,8,"0o")},ty={identify:Hn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(r,e,t)=>ao(r,0,10,t),stringify:Kl.stringifyNumber},sy={identify:r=>Hn(r)&&r>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(r,e,t)=>ao(r,2,16,t),stringify:r=>Hl(r,16,"0x")};Wn.int=ty;Wn.intHex=sy;Wn.intOct=ey});var Gl=T(Wl=>{"use strict";var ny=jt(),ry=Fn(),iy=Ft(),oy=Is(),ay=ro(),lo=oo(),uo=co(),cy=[ny.map,iy.seq,oy.string,ry.nullTag,ay.boolTag,uo.intOct,uo.int,uo.intHex,lo.floatNaN,lo.floatExp,lo.float];Wl.schema=cy});var Jl=T(Yl=>{"use strict";var ly=Z(),dy=jt(),uy=Ft();function Vl(r){return typeof r=="bigint"||Number.isInteger(r)}var Gn=({value:r})=>JSON.stringify(r),hy=[{identify:r=>typeof r=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:r=>r,stringify:Gn},{identify:r=>r==null,createNode:()=>new ly.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Gn},{identify:r=>typeof r=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:r=>r==="true",stringify:Gn},{identify:Vl,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(r,e,{intAsBigInt:t})=>t?BigInt(r):parseInt(r,10),stringify:({value:r})=>Vl(r)?r.toString():JSON.stringify(r)},{identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:r=>parseFloat(r),stringify:Gn}],fy={default:!0,tag:"",test:/^/,resolve(r,e){return e(`Unresolved plain scalar ${JSON.stringify(r)}`),r}},py=[dy.map,uy.seq].concat(hy,fy);Yl.schema=py});var fo=T(zl=>{"use strict";var Cs=H("buffer"),ho=Z(),my=ks(),gy={identify:r=>r instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(r,e){if(typeof Cs.Buffer=="function")return Cs.Buffer.from(r,"base64");if(typeof atob=="function"){let t=atob(r.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let n=0;n<t.length;++n)s[n]=t.charCodeAt(n);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),r},stringify({comment:r,type:e,value:t},s,n,i){if(!t)return"";let o=t,a;if(typeof Cs.Buffer=="function")a=o instanceof Cs.Buffer?o.toString("base64"):Cs.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=ho.Scalar.BLOCK_LITERAL),e!==ho.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===ho.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return my.stringifyString({comment:r,type:e,value:a},s,n,i)}};zl.binary=gy});var Jn=T(Yn=>{"use strict";var Vn=U(),po=rt(),yy=Z(),wy=at();function Ql(r,e){if(Vn.isSeq(r))for(let t=0;t<r.items.length;++t){let s=r.items[t];if(!Vn.isPair(s)){if(Vn.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let n=s.items[0]||new po.Pair(new yy.Scalar(null));if(s.commentBefore&&(n.key.commentBefore=n.key.commentBefore?`${s.commentBefore}
57
57
  ${n.key.commentBefore}`:s.commentBefore),s.comment){let i=n.value??n.key;i.comment=i.comment?`${s.comment}
58
- ${i.comment}`:s.comment}s=n}r.items[t]=Vn.isPair(s)?s:new po.Pair(s)}}else e("Expected a sequence for this tag");return r}function Xl(r,e,t){let{replacer:s}=t,n=new yy.YAMLSeq(r);n.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;n.items.push(po.createPair(a,l,t))}return n}var wy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ql,createNode:Xl};Yn.createPairs=Xl;Yn.pairs=wy;Yn.resolvePairs=Ql});var yo=T(go=>{"use strict";var Zl=U(),mo=et(),As=ot(),Sy=at(),ed=Jn(),wt=class r extends Sy.YAMLSeq{constructor(){super(),this.add=As.YAMLMap.prototype.add.bind(this),this.delete=As.YAMLMap.prototype.delete.bind(this),this.get=As.YAMLMap.prototype.get.bind(this),this.has=As.YAMLMap.prototype.has.bind(this),this.set=As.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let s=new Map;t?.onCreate&&t.onCreate(s);for(let n of this.items){let i,o;if(Zl.isPair(n)?(i=mo.toJS(n.key,"",t),o=mo.toJS(n.value,i,t)):i=mo.toJS(n,"",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 n=ed.createPairs(e,t,s),i=new this;return i.items=n.items,i}};wt.tag="tag:yaml.org,2002:omap";var ky={collection:"seq",identify:r=>r instanceof Map,nodeClass:wt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ed.resolvePairs(r,e),s=[];for(let{key:n}of t.items)Zl.isScalar(n)&&(s.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):s.push(n.value));return Object.assign(new wt,t)},createNode:(r,e,t)=>wt.from(r,e,t)};go.YAMLOMap=wt;go.omap=ky});var id=T(wo=>{"use strict";var td=Z();function sd({value:r,source:e},t){return e&&(r?nd:rd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var nd={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new td.Scalar(!0),stringify:sd},rd={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new td.Scalar(!1),stringify:sd};wo.falseTag=rd;wo.trueTag=nd});var od=T(zn=>{"use strict";var by=Z(),So=Kt(),_y={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:So.stringifyNumber},vy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():So.stringifyNumber(r)}},Ty={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new by.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let s=r.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:So.stringifyNumber};zn.float=Ty;zn.floatExp=vy;zn.floatNaN=_y});var cd=T(Ns=>{"use strict";var ad=Kt(),Es=r=>typeof r=="bigint"||Number.isInteger(r);function Qn(r,e,t,{intAsBigInt:s}){let n=r[0];if((n==="-"||n==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),s){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return n==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return n==="-"?-1*i:i}function ko(r,e,t){let{value:s}=r;if(Es(s)){let n=s.toString(e);return s<0?"-"+t+n.substr(1):t+n}return ad.stringifyNumber(r)}var Iy={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Qn(r,2,2,t),stringify:r=>ko(r,2,"0b")},Cy={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Qn(r,1,8,t),stringify:r=>ko(r,8,"0")},Ay={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Qn(r,0,10,t),stringify:ad.stringifyNumber},Ey={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Qn(r,2,16,t),stringify:r=>ko(r,16,"0x")};Ns.int=Ay;Ns.intBin=Iy;Ns.intHex=Ey;Ns.intOct=Cy});var _o=T(bo=>{"use strict";var er=U(),Xn=rt(),Zn=ot(),St=class r extends Zn.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;er.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Xn.Pair(e.key,null):t=new Xn.Pair(e,null),Zn.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let s=Zn.findPair(this.items,e);return!t&&er.isPair(s)?er.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=Zn.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Xn.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:n}=s,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof n=="function"&&(o=n.call(t,o,o)),i.items.push(Xn.createPair(o,null,s));return i}};St.tag="tag:yaml.org,2002:set";var Ny={collection:"map",identify:r=>r instanceof Set,nodeClass:St,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>St.from(r,e,t),resolve(r,e){if(er.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new St,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};bo.YAMLSet=St;bo.set=Ny});var To=T(tr=>{"use strict";var xy=Kt();function vo(r,e){let t=r[0],s=t==="-"||t==="+"?r.substring(1):r,n=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*n(60)+n(a),n(0));return t==="-"?n(-1)*i:i}function ld(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return xy.stringifyNumber(r);let s="";e<0&&(s="-",e*=t(-1));let n=t(60),i=[e%n];return e<60?i.unshift(0):(e=(e-i[0])/n,i.unshift(e%n),e>=60&&(e=(e-i[0])/n,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var Oy={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>vo(r,t),stringify:ld},My={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>vo(r,!1),stringify:ld},dd={identify:r=>r 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(r){let e=r.match(dd.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,s,n,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,s-1,n,i||0,o||0,a||0,l),d=e[8];if(d&&d!=="Z"){let u=vo(d,!1);Math.abs(u)<30&&(u*=60),c-=6e4*u}return new Date(c)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};tr.floatTime=My;tr.intTime=Oy;tr.timestamp=dd});var fd=T(hd=>{"use strict";var Dy=jt(),Ly=Fn(),Py=Ft(),$y=Is(),Ry=fo(),ud=id(),Io=od(),sr=cd(),By=Ln(),Uy=yo(),qy=Jn(),jy=_o(),Co=To(),Fy=[Dy.map,Py.seq,$y.string,Ly.nullTag,ud.trueTag,ud.falseTag,sr.intBin,sr.intOct,sr.int,sr.intHex,Io.floatNaN,Io.floatExp,Io.float,Ry.binary,By.merge,Uy.omap,qy.pairs,jy.set,Co.intTime,Co.floatTime,Co.timestamp];hd.schema=Fy});var vd=T(No=>{"use strict";var yd=jt(),Ky=Fn(),wd=Ft(),Hy=Is(),Wy=ro(),Ao=oo(),Eo=co(),Gy=Gl(),Vy=Jl(),Sd=fo(),xs=Ln(),kd=yo(),bd=Jn(),pd=fd(),_d=_o(),nr=To(),md=new Map([["core",Gy.schema],["failsafe",[yd.map,wd.seq,Hy.string]],["json",Vy.schema],["yaml11",pd.schema],["yaml-1.1",pd.schema]]),gd={binary:Sd.binary,bool:Wy.boolTag,float:Ao.float,floatExp:Ao.floatExp,floatNaN:Ao.floatNaN,floatTime:nr.floatTime,int:Eo.int,intHex:Eo.intHex,intOct:Eo.intOct,intTime:nr.intTime,map:yd.map,merge:xs.merge,null:Ky.nullTag,omap:kd.omap,pairs:bd.pairs,seq:wd.seq,set:_d.set,timestamp:nr.timestamp},Yy={"tag:yaml.org,2002:binary":Sd.binary,"tag:yaml.org,2002:merge":xs.merge,"tag:yaml.org,2002:omap":kd.omap,"tag:yaml.org,2002:pairs":bd.pairs,"tag:yaml.org,2002:set":_d.set,"tag:yaml.org,2002:timestamp":nr.timestamp};function Jy(r,e,t){let s=md.get(e);if(s&&!r)return t&&!s.includes(xs.merge)?s.concat(xs.merge):s.slice();let n=s;if(!n)if(Array.isArray(r))n=[];else{let i=Array.from(md.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(r))for(let i of r)n=n.concat(i);else typeof r=="function"&&(n=r(n.slice()));return t&&(n=n.concat(xs.merge)),n.reduce((i,o)=>{let a=typeof o=="string"?gd[o]:o;if(!a){let l=JSON.stringify(o),c=Object.keys(gd).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},[])}No.coreKnownTags=Yy;No.getTags=Jy});var Mo=T(Td=>{"use strict";var xo=U(),zy=jt(),Qy=Ft(),Xy=Is(),rr=vd(),Zy=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Oo=class r{constructor({compat:e,customTags:t,merge:s,resolveKnownTags:n,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?rr.getTags(e,"compat"):e?rr.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=n?rr.coreKnownTags:{},this.tags=rr.getTags(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,xo.MAP,{value:zy.map}),Object.defineProperty(this,xo.SCALAR,{value:Xy.string}),Object.defineProperty(this,xo.SEQ,{value:Qy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?Zy:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Td.Schema=Oo});var Cd=T(Id=>{"use strict";var ew=U(),Do=bs(),Os=ys();function tw(r,e){let t=[],s=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),s=!0):r.directives.docStart&&(s=!0)}s&&t.push("---");let n=Do.createStringifyContext(r,e),{commentString:i}=n.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=i(r.commentBefore);t.unshift(Os.indentComment(l,""))}let o=!1,a=null;if(r.contents){if(ew.isNode(r.contents)){if(r.contents.spaceBefore&&s&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(Os.indentComment(d,""))}n.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,c=Do.stringify(r.contents,n,()=>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(Do.stringify(r.contents,n));if(r.directives?.docEnd)if(r.comment){let l=i(r.comment);l.includes(`
58
+ ${i.comment}`:s.comment}s=n}r.items[t]=Vn.isPair(s)?s:new po.Pair(s)}}else e("Expected a sequence for this tag");return r}function Xl(r,e,t){let{replacer:s}=t,n=new wy.YAMLSeq(r);n.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;n.items.push(po.createPair(a,l,t))}return n}var Sy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:Ql,createNode:Xl};Yn.createPairs=Xl;Yn.pairs=Sy;Yn.resolvePairs=Ql});var yo=T(go=>{"use strict";var Zl=U(),mo=et(),As=ot(),ky=at(),ed=Jn(),wt=class r extends ky.YAMLSeq{constructor(){super(),this.add=As.YAMLMap.prototype.add.bind(this),this.delete=As.YAMLMap.prototype.delete.bind(this),this.get=As.YAMLMap.prototype.get.bind(this),this.has=As.YAMLMap.prototype.has.bind(this),this.set=As.YAMLMap.prototype.set.bind(this),this.tag=r.tag}toJSON(e,t){if(!t)return super.toJSON(e);let s=new Map;t?.onCreate&&t.onCreate(s);for(let n of this.items){let i,o;if(Zl.isPair(n)?(i=mo.toJS(n.key,"",t),o=mo.toJS(n.value,i,t)):i=mo.toJS(n,"",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 n=ed.createPairs(e,t,s),i=new this;return i.items=n.items,i}};wt.tag="tag:yaml.org,2002:omap";var by={collection:"seq",identify:r=>r instanceof Map,nodeClass:wt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(r,e){let t=ed.resolvePairs(r,e),s=[];for(let{key:n}of t.items)Zl.isScalar(n)&&(s.includes(n.value)?e(`Ordered maps must not include duplicate keys: ${n.value}`):s.push(n.value));return Object.assign(new wt,t)},createNode:(r,e,t)=>wt.from(r,e,t)};go.YAMLOMap=wt;go.omap=by});var id=T(wo=>{"use strict";var td=Z();function sd({value:r,source:e},t){return e&&(r?nd:rd).test.test(e)?e:r?t.options.trueStr:t.options.falseStr}var nd={identify:r=>r===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new td.Scalar(!0),stringify:sd},rd={identify:r=>r===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new td.Scalar(!1),stringify:sd};wo.falseTag=rd;wo.trueTag=nd});var od=T(zn=>{"use strict";var _y=Z(),So=Kt(),vy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:r=>r.slice(-3).toLowerCase()==="nan"?NaN:r[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:So.stringifyNumber},Ty={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:r=>parseFloat(r.replace(/_/g,"")),stringify(r){let e=Number(r.value);return isFinite(e)?e.toExponential():So.stringifyNumber(r)}},Iy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(r){let e=new _y.Scalar(parseFloat(r.replace(/_/g,""))),t=r.indexOf(".");if(t!==-1){let s=r.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:So.stringifyNumber};zn.float=Iy;zn.floatExp=Ty;zn.floatNaN=vy});var cd=T(Ns=>{"use strict";var ad=Kt(),Es=r=>typeof r=="bigint"||Number.isInteger(r);function Qn(r,e,t,{intAsBigInt:s}){let n=r[0];if((n==="-"||n==="+")&&(e+=1),r=r.substring(e).replace(/_/g,""),s){switch(t){case 2:r=`0b${r}`;break;case 8:r=`0o${r}`;break;case 16:r=`0x${r}`;break}let o=BigInt(r);return n==="-"?BigInt(-1)*o:o}let i=parseInt(r,t);return n==="-"?-1*i:i}function ko(r,e,t){let{value:s}=r;if(Es(s)){let n=s.toString(e);return s<0?"-"+t+n.substr(1):t+n}return ad.stringifyNumber(r)}var Cy={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(r,e,t)=>Qn(r,2,2,t),stringify:r=>ko(r,2,"0b")},Ay={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(r,e,t)=>Qn(r,1,8,t),stringify:r=>ko(r,8,"0")},Ey={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(r,e,t)=>Qn(r,0,10,t),stringify:ad.stringifyNumber},Ny={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(r,e,t)=>Qn(r,2,16,t),stringify:r=>ko(r,16,"0x")};Ns.int=Ey;Ns.intBin=Cy;Ns.intHex=Ny;Ns.intOct=Ay});var _o=T(bo=>{"use strict";var er=U(),Xn=rt(),Zn=ot(),St=class r extends Zn.YAMLMap{constructor(e){super(e),this.tag=r.tag}add(e){let t;er.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Xn.Pair(e.key,null):t=new Xn.Pair(e,null),Zn.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let s=Zn.findPair(this.items,e);return!t&&er.isPair(s)?er.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=Zn.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Xn.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:n}=s,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof n=="function"&&(o=n.call(t,o,o)),i.items.push(Xn.createPair(o,null,s));return i}};St.tag="tag:yaml.org,2002:set";var xy={collection:"map",identify:r=>r instanceof Set,nodeClass:St,default:!1,tag:"tag:yaml.org,2002:set",createNode:(r,e,t)=>St.from(r,e,t),resolve(r,e){if(er.isMap(r)){if(r.hasAllNullValues(!0))return Object.assign(new St,r);e("Set items must all have null values")}else e("Expected a mapping for this tag");return r}};bo.YAMLSet=St;bo.set=xy});var To=T(tr=>{"use strict";var Oy=Kt();function vo(r,e){let t=r[0],s=t==="-"||t==="+"?r.substring(1):r,n=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*n(60)+n(a),n(0));return t==="-"?n(-1)*i:i}function ld(r){let{value:e}=r,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Oy.stringifyNumber(r);let s="";e<0&&(s="-",e*=t(-1));let n=t(60),i=[e%n];return e<60?i.unshift(0):(e=(e-i[0])/n,i.unshift(e%n),e>=60&&(e=(e-i[0])/n,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var My={identify:r=>typeof r=="bigint"||Number.isInteger(r),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(r,e,{intAsBigInt:t})=>vo(r,t),stringify:ld},Dy={identify:r=>typeof r=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:r=>vo(r,!1),stringify:ld},dd={identify:r=>r 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(r){let e=r.match(dd.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,s,n,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,s-1,n,i||0,o||0,a||0,l),d=e[8];if(d&&d!=="Z"){let u=vo(d,!1);Math.abs(u)<30&&(u*=60),c-=6e4*u}return new Date(c)},stringify:({value:r})=>r?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};tr.floatTime=Dy;tr.intTime=My;tr.timestamp=dd});var fd=T(hd=>{"use strict";var Ly=jt(),Py=Fn(),$y=Ft(),Ry=Is(),By=fo(),ud=id(),Io=od(),sr=cd(),Uy=Ln(),qy=yo(),jy=Jn(),Fy=_o(),Co=To(),Ky=[Ly.map,$y.seq,Ry.string,Py.nullTag,ud.trueTag,ud.falseTag,sr.intBin,sr.intOct,sr.int,sr.intHex,Io.floatNaN,Io.floatExp,Io.float,By.binary,Uy.merge,qy.omap,jy.pairs,Fy.set,Co.intTime,Co.floatTime,Co.timestamp];hd.schema=Ky});var vd=T(No=>{"use strict";var yd=jt(),Hy=Fn(),wd=Ft(),Wy=Is(),Gy=ro(),Ao=oo(),Eo=co(),Vy=Gl(),Yy=Jl(),Sd=fo(),xs=Ln(),kd=yo(),bd=Jn(),pd=fd(),_d=_o(),nr=To(),md=new Map([["core",Vy.schema],["failsafe",[yd.map,wd.seq,Wy.string]],["json",Yy.schema],["yaml11",pd.schema],["yaml-1.1",pd.schema]]),gd={binary:Sd.binary,bool:Gy.boolTag,float:Ao.float,floatExp:Ao.floatExp,floatNaN:Ao.floatNaN,floatTime:nr.floatTime,int:Eo.int,intHex:Eo.intHex,intOct:Eo.intOct,intTime:nr.intTime,map:yd.map,merge:xs.merge,null:Hy.nullTag,omap:kd.omap,pairs:bd.pairs,seq:wd.seq,set:_d.set,timestamp:nr.timestamp},Jy={"tag:yaml.org,2002:binary":Sd.binary,"tag:yaml.org,2002:merge":xs.merge,"tag:yaml.org,2002:omap":kd.omap,"tag:yaml.org,2002:pairs":bd.pairs,"tag:yaml.org,2002:set":_d.set,"tag:yaml.org,2002:timestamp":nr.timestamp};function zy(r,e,t){let s=md.get(e);if(s&&!r)return t&&!s.includes(xs.merge)?s.concat(xs.merge):s.slice();let n=s;if(!n)if(Array.isArray(r))n=[];else{let i=Array.from(md.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(r))for(let i of r)n=n.concat(i);else typeof r=="function"&&(n=r(n.slice()));return t&&(n=n.concat(xs.merge)),n.reduce((i,o)=>{let a=typeof o=="string"?gd[o]:o;if(!a){let l=JSON.stringify(o),c=Object.keys(gd).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},[])}No.coreKnownTags=Jy;No.getTags=zy});var Mo=T(Td=>{"use strict";var xo=U(),Qy=jt(),Xy=Ft(),Zy=Is(),rr=vd(),ew=(r,e)=>r.key<e.key?-1:r.key>e.key?1:0,Oo=class r{constructor({compat:e,customTags:t,merge:s,resolveKnownTags:n,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?rr.getTags(e,"compat"):e?rr.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=n?rr.coreKnownTags:{},this.tags=rr.getTags(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,xo.MAP,{value:Qy.map}),Object.defineProperty(this,xo.SCALAR,{value:Zy.string}),Object.defineProperty(this,xo.SEQ,{value:Xy.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ew:null}clone(){let e=Object.create(r.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Td.Schema=Oo});var Cd=T(Id=>{"use strict";var tw=U(),Do=bs(),Os=ys();function sw(r,e){let t=[],s=e.directives===!0;if(e.directives!==!1&&r.directives){let l=r.directives.toString(r);l?(t.push(l),s=!0):r.directives.docStart&&(s=!0)}s&&t.push("---");let n=Do.createStringifyContext(r,e),{commentString:i}=n.options;if(r.commentBefore){t.length!==1&&t.unshift("");let l=i(r.commentBefore);t.unshift(Os.indentComment(l,""))}let o=!1,a=null;if(r.contents){if(tw.isNode(r.contents)){if(r.contents.spaceBefore&&s&&t.push(""),r.contents.commentBefore){let d=i(r.contents.commentBefore);t.push(Os.indentComment(d,""))}n.forceBlockIndent=!!r.comment,a=r.contents.comment}let l=a?void 0:()=>o=!0,c=Do.stringify(r.contents,n,()=>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(Do.stringify(r.contents,n));if(r.directives?.docEnd)if(r.comment){let l=i(r.comment);l.includes(`
59
59
  `)?(t.push("..."),t.push(Os.indentComment(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=r.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(`
60
60
  `)+`
61
- `}Id.stringifyDocument=tw});var Ms=T(Ad=>{"use strict";var sw=ms(),Ht=In(),ke=U(),nw=rt(),rw=et(),iw=Mo(),ow=Cd(),Lo=bn(),aw=Ri(),cw=gs(),Po=$i(),$o=class r{constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ke.NODE_TYPE,{value:ke.DOC});let n=null;typeof t=="function"||Array.isArray(t)?n=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 Po.Directives({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,n,s)}clone(){let e=Object.create(r.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){Wt(this.contents)&&this.contents.add(e)}addIn(e,t){Wt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let s=Lo.anchorNames(this);e.anchor=!t||s.has(t)?Lo.findNewAnchor(t||"a",s):t}return new sw.Alias(e.anchor)}createNode(e,t,s){let n;if(typeof t=="function")e=t.call({"":e},"",e),n=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)),n=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:m}=Lo.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:u,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:m},f=cw.createNode(e,d,g);return a&&ke.isCollection(f)&&(f.flow=!0),h(),f}createPair(e,t,s={}){let n=this.createNode(e,null,s),i=this.createNode(t,null,s);return new nw.Pair(n,i)}delete(e){return Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ht.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Wt(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 Ht.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 Ht.isEmptyPath(e)?this.contents!==void 0:ke.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ht.collectionFromPath(this.schema,[e],t):Wt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ht.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ht.collectionFromPath(this.schema,Array.from(e),t):Wt(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 Po.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 Po.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(s)this.schema=new iw.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:n,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=rw.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"?aw.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 ow.stringifyDocument(this,e)}};function Wt(r){if(ke.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Ad.Document=$o});var Ps=T(Ls=>{"use strict";var Ds=class extends Error{constructor(e,t,s,n){super(),this.name=e,this.code=s,this.message=n,this.pos=t}},Ro=class extends Ds{constructor(e,t,s){super("YAMLParseError",e,t,s)}},Bo=class extends Ds{constructor(e,t,s){super("YAMLWarning",e,t,s)}},lw=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:s,col:n}=t.linePos[0];t.message+=` at line ${s}, column ${n}`;let i=n-1,o=r.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=r.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
61
+ `}Id.stringifyDocument=sw});var Ms=T(Ad=>{"use strict";var nw=ms(),Ht=In(),ke=U(),rw=rt(),iw=et(),ow=Mo(),aw=Cd(),Lo=bn(),cw=Ri(),lw=gs(),Po=$i(),$o=class r{constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ke.NODE_TYPE,{value:ke.DOC});let n=null;typeof t=="function"||Array.isArray(t)?n=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 Po.Directives({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,n,s)}clone(){let e=Object.create(r.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){Wt(this.contents)&&this.contents.add(e)}addIn(e,t){Wt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let s=Lo.anchorNames(this);e.anchor=!t||s.has(t)?Lo.findNewAnchor(t||"a",s):t}return new nw.Alias(e.anchor)}createNode(e,t,s){let n;if(typeof t=="function")e=t.call({"":e},"",e),n=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)),n=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:m}=Lo.createNodeAnchors(this,o||"a"),g={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:u,onTagObj:c,replacer:n,schema:this.schema,sourceObjects:m},f=lw.createNode(e,d,g);return a&&ke.isCollection(f)&&(f.flow=!0),h(),f}createPair(e,t,s={}){let n=this.createNode(e,null,s),i=this.createNode(t,null,s);return new rw.Pair(n,i)}delete(e){return Wt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ht.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Wt(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 Ht.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 Ht.isEmptyPath(e)?this.contents!==void 0:ke.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ht.collectionFromPath(this.schema,[e],t):Wt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ht.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Ht.collectionFromPath(this.schema,Array.from(e),t):Wt(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 Po.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 Po.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let n=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${n}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(s)this.schema=new ow.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:n,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof n=="number"?n:100},l=iw.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"?cw.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 aw.stringifyDocument(this,e)}};function Wt(r){if(ke.isCollection(r))return!0;throw new Error("Expected a YAML collection as document contents")}Ad.Document=$o});var Ps=T(Ls=>{"use strict";var Ds=class extends Error{constructor(e,t,s,n){super(),this.name=e,this.code=s,this.message=n,this.pos=t}},Ro=class extends Ds{constructor(e,t,s){super("YAMLParseError",e,t,s)}},Bo=class extends Ds{constructor(e,t,s){super("YAMLWarning",e,t,s)}},dw=(r,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:s,col:n}=t.linePos[0];t.message+=` at line ${s}, column ${n}`;let i=n-1,o=r.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=r.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
62
62
  `),o=a+o}if(/[^ ]/.test(o)){let a=1,l=t.linePos[1];l?.line===s&&l.col>n&&(a=Math.max(1,Math.min(l.col-n,80-i)));let c=" ".repeat(i)+"^".repeat(a);t.message+=`:
63
63
 
64
64
  ${o}
65
65
  ${c}
66
- `}};Ls.YAMLError=Ds;Ls.YAMLParseError=Ro;Ls.YAMLWarning=Bo;Ls.prettifyError=lw});var $s=T(Ed=>{"use strict";function dw(r,{flow:e,indicator:t,next:s,offset:n,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,c=a,d=a,u="",h="",m=!1,g=!1,f=null,y=null,w=null,S=null,_=null,v=null,I=null;for(let C of r)switch(g&&(C.type!=="space"&&C.type!=="newline"&&C.type!=="comma"&&i(C.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),f&&(c&&C.type!=="comment"&&C.type!=="newline"&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),C.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&C.source.includes(" ")&&(f=C),d=!0;break;case"comment":{d||i(C,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=C.source.substring(1)||" ";u?u+=h+E:u=E,h="",c=!1;break}case"newline":c?u?u+=C.source:(!v||t!=="seq-item-ind")&&(l=!0):h+=C.source,c=!0,m=!0,(y||w)&&(S=C),d=!0;break;case"anchor":y&&i(C,"MULTIPLE_ANCHORS","A node can have at most one anchor"),C.source.endsWith(":")&&i(C.offset+C.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=C,I??(I=C.offset),c=!1,d=!1,g=!0;break;case"tag":{w&&i(C,"MULTIPLE_TAGS","A node can have at most one tag"),w=C,I??(I=C.offset),c=!1,d=!1,g=!0;break}case t:(y||w)&&i(C,"BAD_PROP_ORDER",`Anchors and tags must be after the ${C.source} indicator`),v&&i(C,"UNEXPECTED_TOKEN",`Unexpected ${C.source} in ${e??"collection"}`),v=C,c=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){_&&i(C,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=C,c=!1,d=!1;break}default:i(C,"UNEXPECTED_TOKEN",`Unexpected ${C.type} token`),c=!1,d=!1}let N=r[r.length-1],D=N?N.offset+N.source.length:n;return g&&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:m,anchor:y,tag:w,newlineAfterProp:S,end:D,start:I??D}}Ed.resolveProps=dw});var ir=T(Nd=>{"use strict";function Uo(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
67
- `))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.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(Uo(e.key)||Uo(e.value))return!0}return!1;default:return!0}}Nd.containsNewline=Uo});var qo=T(xd=>{"use strict";var uw=ir();function hw(r,e,t){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===r&&(s.source==="]"||s.source==="}")&&uw.containsNewline(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xd.flowIndentCheck=hw});var jo=T(Md=>{"use strict";var Od=U();function fw(r,e,t){let{uniqueKeys:s}=r.options;if(s===!1)return!1;let n=typeof s=="function"?s:(i,o)=>i===o||Od.isScalar(i)&&Od.isScalar(o)&&i.value===o.value;return e.some(i=>n(i.key,t))}Md.mapIncludes=fw});var Bd=T(Rd=>{"use strict";var Dd=rt(),pw=ot(),Ld=$s(),mw=ir(),Pd=qo(),gw=jo(),$d="All mapping items must start at the same column";function yw({composeNode:r,composeEmptyNode:e},t,s,n,i){let o=i?.nodeClass??pw.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:m,value:g}=d,f=Ld.resolveProps(u,{indicator:"explicit-key-ind",next:h??m?.[0],offset:l,onError:n,parentIndent:s.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==s.indent&&n(l,"BAD_INDENT",$d)),!f.anchor&&!f.tag&&!m){c=f.end,f.comment&&(a.comment?a.comment+=`
68
- `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||mw.containsNewline(h))&&n(h??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==s.indent&&n(l,"BAD_INDENT",$d);t.atKey=!0;let w=f.end,S=h?r(t,h,f,n):e(t,w,u,null,f,n);t.schema.compat&&Pd.flowIndentCheck(s.indent,h,n),t.atKey=!1,gw.mapIncludes(t,a.items,S)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let _=Ld.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:S.range[2],onError:n,parentIndent:s.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=_.end,_.found){y&&(g?.type==="block-map"&&!_.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<_.found.offset-1024&&n(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=g?r(t,g,_,n):e(t,l,m,null,_,n);t.schema.compat&&Pd.flowIndentCheck(s.indent,g,n),l=v.range[2];let I=new Dd.Pair(S,v);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}else{y&&n(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 Dd.Pair(S);t.options.keepSourceTokens&&(v.srcToken=d),a.items.push(v)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,l,c??l],a}Rd.resolveBlockMap=yw});var qd=T(Ud=>{"use strict";var ww=at(),Sw=$s(),kw=qo();function bw({composeNode:r,composeEmptyNode:e},t,s,n,i){let o=i?.nodeClass??ww.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=Sw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:l,onError:n,parentIndent:s.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||u)u?.type==="block-seq"?n(h.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=h.end,h.comment&&(a.comment=h.comment);continue}let m=u?r(t,u,h,n):e(t,h.end,d,null,h,n);t.schema.compat&&kw.flowIndentCheck(s.indent,u,n),l=m.range[2],a.items.push(m)}return a.range=[s.offset,l,c??l],a}Ud.resolveBlockSeq=bw});var Gt=T(jd=>{"use strict";function _w(r,e,t,s){let n="";if(r){let i=!1,o="";for(let a of r){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)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=l),i=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:n,offset:e}}jd.resolveEnd=_w});var Wd=T(Hd=>{"use strict";var vw=U(),Tw=rt(),Fd=ot(),Iw=at(),Cw=Gt(),Kd=$s(),Aw=ir(),Ew=jo(),Fo="Block collections are not allowed within flow collections",Ko=r=>r&&(r.type==="block-map"||r.type==="block-seq");function Nw({composeNode:r,composeEmptyNode:e},t,s,n,i){let o=s.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?Fd.YAMLMap:Iw.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=Kd.resolveProps(S,{flow:a,indicator:"explicit-key-ind",next:_??v?.[0],offset:u,onError:n,parentIndent:s.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!v&&!I){y===0&&N.comma?n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&n(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&&Aw.containsNewline(_)&&n(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)N.comma&&n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||n(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(let C of S)switch(C.type){case"comma":case"space":break;case"comment":D=C.source.substring(1);break e;default:break e}if(D){let C=c.items[c.items.length-1];vw.isPair(C)&&(C=C.value??C.key),C.comment?C.comment+=`
66
+ `}};Ls.YAMLError=Ds;Ls.YAMLParseError=Ro;Ls.YAMLWarning=Bo;Ls.prettifyError=dw});var $s=T(Ed=>{"use strict";function uw(r,{flow:e,indicator:t,next:s,offset:n,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,c=a,d=a,u="",h="",m=!1,g=!1,f=null,y=null,w=null,S=null,_=null,v=null,I=null;for(let C of r)switch(g&&(C.type!=="space"&&C.type!=="newline"&&C.type!=="comma"&&i(C.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),g=!1),f&&(c&&C.type!=="comment"&&C.type!=="newline"&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),C.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&C.source.includes(" ")&&(f=C),d=!0;break;case"comment":{d||i(C,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=C.source.substring(1)||" ";u?u+=h+E:u=E,h="",c=!1;break}case"newline":c?u?u+=C.source:(!v||t!=="seq-item-ind")&&(l=!0):h+=C.source,c=!0,m=!0,(y||w)&&(S=C),d=!0;break;case"anchor":y&&i(C,"MULTIPLE_ANCHORS","A node can have at most one anchor"),C.source.endsWith(":")&&i(C.offset+C.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=C,I??(I=C.offset),c=!1,d=!1,g=!0;break;case"tag":{w&&i(C,"MULTIPLE_TAGS","A node can have at most one tag"),w=C,I??(I=C.offset),c=!1,d=!1,g=!0;break}case t:(y||w)&&i(C,"BAD_PROP_ORDER",`Anchors and tags must be after the ${C.source} indicator`),v&&i(C,"UNEXPECTED_TOKEN",`Unexpected ${C.source} in ${e??"collection"}`),v=C,c=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){_&&i(C,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=C,c=!1,d=!1;break}default:i(C,"UNEXPECTED_TOKEN",`Unexpected ${C.type} token`),c=!1,d=!1}let N=r[r.length-1],D=N?N.offset+N.source.length:n;return g&&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:m,anchor:y,tag:w,newlineAfterProp:S,end:D,start:I??D}}Ed.resolveProps=uw});var ir=T(Nd=>{"use strict";function Uo(r){if(!r)return null;switch(r.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(r.source.includes(`
67
+ `))return!0;if(r.end){for(let e of r.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of r.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(Uo(e.key)||Uo(e.value))return!0}return!1;default:return!0}}Nd.containsNewline=Uo});var qo=T(xd=>{"use strict";var hw=ir();function fw(r,e,t){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===r&&(s.source==="]"||s.source==="}")&&hw.containsNewline(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}xd.flowIndentCheck=fw});var jo=T(Md=>{"use strict";var Od=U();function pw(r,e,t){let{uniqueKeys:s}=r.options;if(s===!1)return!1;let n=typeof s=="function"?s:(i,o)=>i===o||Od.isScalar(i)&&Od.isScalar(o)&&i.value===o.value;return e.some(i=>n(i.key,t))}Md.mapIncludes=pw});var Bd=T(Rd=>{"use strict";var Dd=rt(),mw=ot(),Ld=$s(),gw=ir(),Pd=qo(),yw=jo(),$d="All mapping items must start at the same column";function ww({composeNode:r,composeEmptyNode:e},t,s,n,i){let o=i?.nodeClass??mw.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:m,value:g}=d,f=Ld.resolveProps(u,{indicator:"explicit-key-ind",next:h??m?.[0],offset:l,onError:n,parentIndent:s.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?n(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==s.indent&&n(l,"BAD_INDENT",$d)),!f.anchor&&!f.tag&&!m){c=f.end,f.comment&&(a.comment?a.comment+=`
68
+ `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||gw.containsNewline(h))&&n(h??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==s.indent&&n(l,"BAD_INDENT",$d);t.atKey=!0;let w=f.end,S=h?r(t,h,f,n):e(t,w,u,null,f,n);t.schema.compat&&Pd.flowIndentCheck(s.indent,h,n),t.atKey=!1,yw.mapIncludes(t,a.items,S)&&n(w,"DUPLICATE_KEY","Map keys must be unique");let _=Ld.resolveProps(m??[],{indicator:"map-value-ind",next:g,offset:S.range[2],onError:n,parentIndent:s.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=_.end,_.found){y&&(g?.type==="block-map"&&!_.hasNewline&&n(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<_.found.offset-1024&&n(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=g?r(t,g,_,n):e(t,l,m,null,_,n);t.schema.compat&&Pd.flowIndentCheck(s.indent,g,n),l=v.range[2];let I=new Dd.Pair(S,v);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}else{y&&n(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 Dd.Pair(S);t.options.keepSourceTokens&&(v.srcToken=d),a.items.push(v)}}return c&&c<l&&n(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,l,c??l],a}Rd.resolveBlockMap=ww});var qd=T(Ud=>{"use strict";var Sw=at(),kw=$s(),bw=qo();function _w({composeNode:r,composeEmptyNode:e},t,s,n,i){let o=i?.nodeClass??Sw.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=kw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:l,onError:n,parentIndent:s.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||u)u?.type==="block-seq"?n(h.end,"BAD_INDENT","All sequence items must start at the same column"):n(l,"MISSING_CHAR","Sequence item without - indicator");else{c=h.end,h.comment&&(a.comment=h.comment);continue}let m=u?r(t,u,h,n):e(t,h.end,d,null,h,n);t.schema.compat&&bw.flowIndentCheck(s.indent,u,n),l=m.range[2],a.items.push(m)}return a.range=[s.offset,l,c??l],a}Ud.resolveBlockSeq=_w});var Gt=T(jd=>{"use strict";function vw(r,e,t,s){let n="";if(r){let i=!1,o="";for(let a of r){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)||" ";n?n+=o+d:n=d,o="";break}case"newline":n&&(o+=l),i=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:n,offset:e}}jd.resolveEnd=vw});var Wd=T(Hd=>{"use strict";var Tw=U(),Iw=rt(),Fd=ot(),Cw=at(),Aw=Gt(),Kd=$s(),Ew=ir(),Nw=jo(),Fo="Block collections are not allowed within flow collections",Ko=r=>r&&(r.type==="block-map"||r.type==="block-seq");function xw({composeNode:r,composeEmptyNode:e},t,s,n,i){let o=s.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?Fd.YAMLMap:Cw.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=Kd.resolveProps(S,{flow:a,indicator:"explicit-key-ind",next:_??v?.[0],offset:u,onError:n,parentIndent:s.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!v&&!I){y===0&&N.comma?n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&n(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&&Ew.containsNewline(_)&&n(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)N.comma&&n(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||n(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(let C of S)switch(C.type){case"comma":case"space":break;case"comment":D=C.source.substring(1);break e;default:break e}if(D){let C=c.items[c.items.length-1];Tw.isPair(C)&&(C=C.value??C.key),C.comment?C.comment+=`
71
71
  `+D:C.comment=D,N.comment=N.comment.substring(D.length+1)}}if(!o&&!v&&!N.found){let D=I?r(t,I,N,n):e(t,N.end,v,null,N,n);c.items.push(D),u=D.range[2],Ko(I)&&n(D.range,"BLOCK_IN_FLOW",Fo)}else{t.atKey=!0;let D=N.end,C=_?r(t,_,N,n):e(t,D,S,null,N,n);Ko(_)&&n(C.range,"BLOCK_IN_FLOW",Fo),t.atKey=!1;let E=Kd.resolveProps(v??[],{flow:a,indicator:"map-value-ind",next:I,offset:C.range[2],onError:n,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"){n($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<E.found.offset-1024&&n(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]===":"?n(I,"MISSING_CHAR",`Missing space after : in ${a}`):n(E.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let G=I?r(t,I,E,n):E.found?e(t,E.end,v,null,E,n):null;G?Ko(I)&&n(G.range,"BLOCK_IN_FLOW",Fo):E.comment&&(C.comment?C.comment+=`
72
- `+E.comment:C.comment=E.comment);let W=new Tw.Pair(C,G);if(t.options.keepSourceTokens&&(W.srcToken=w),o){let $=c;Ew.mapIncludes(t,$.items,C)&&n(D,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(W)}else{let $=new Fd.YAMLMap(t.schema);$.flow=!0,$.items.push(W);let ce=(G??C).range;$.range=[C.range[0],ce[1],ce[2]],c.items.push($)}u=G?G.range[2]:E.end}}let h=o?"}":"]",[m,...g]=s.end,f=u;if(m?.source===h)f=m.offset+m.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}`;n(u,d?"MISSING_CHAR":"BAD_INDENT",w),m&&m.source.length!==1&&g.unshift(m)}if(g.length>0){let y=Cw.resolveEnd(g,f,t.options.strict,n);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}Hd.resolveFlowCollection=Nw});var Vd=T(Gd=>{"use strict";var xw=U(),Ow=Z(),Mw=ot(),Dw=at(),Lw=Bd(),Pw=qd(),$w=Wd();function Ho(r,e,t,s,n,i){let o=t.type==="block-map"?Lw.resolveBlockMap(r,e,t,s,i):t.type==="block-seq"?Pw.resolveBlockSeq(r,e,t,s,i):$w.resolveFlowCollection(r,e,t,s,i),a=o.constructor;return n==="!"||n===a.tagName?(o.tag=a.tagName,o):(n&&(o.tag=n),o)}function Rw(r,e,t,s,n){let i=s.tag,o=i?e.directives.tagName(i.source,h=>n(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=s,g=h&&i?h.offset>i.offset?h:i:h??i;g&&(!m||m.offset<g.offset)&&n(g,"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===Mw.YAMLMap.tagName&&a==="map"||o===Dw.YAMLSeq.tagName&&a==="seq")return Ho(r,e,t,n,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?n(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ho(r,e,t,n,o)}let c=Ho(r,e,t,n,o,l),d=l.resolve?.(c,h=>n(i,"TAG_RESOLVE_FAILED",h),e.options)??c,u=xw.isNode(d)?d:new Ow.Scalar(d);return u.range=c.range,u.tag=o,l?.format&&(u.format=l.format),u}Gd.composeCollection=Rw});var Go=T(Yd=>{"use strict";var Wo=Z();function Bw(r,e,t){let s=e.offset,n=Uw(e,r.options.strict,t);if(!n)return{value:"",type:null,comment:"",range:[s,s,s]};let i=n.mode===">"?Wo.Scalar.BLOCK_FOLDED:Wo.Scalar.BLOCK_LITERAL,o=e.source?qw(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=n.chomp==="+"&&o.length>0?`
72
+ `+E.comment:C.comment=E.comment);let W=new Iw.Pair(C,G);if(t.options.keepSourceTokens&&(W.srcToken=w),o){let $=c;Nw.mapIncludes(t,$.items,C)&&n(D,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(W)}else{let $=new Fd.YAMLMap(t.schema);$.flow=!0,$.items.push(W);let ce=(G??C).range;$.range=[C.range[0],ce[1],ce[2]],c.items.push($)}u=G?G.range[2]:E.end}}let h=o?"}":"]",[m,...g]=s.end,f=u;if(m?.source===h)f=m.offset+m.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}`;n(u,d?"MISSING_CHAR":"BAD_INDENT",w),m&&m.source.length!==1&&g.unshift(m)}if(g.length>0){let y=Aw.resolveEnd(g,f,t.options.strict,n);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}Hd.resolveFlowCollection=xw});var Vd=T(Gd=>{"use strict";var Ow=U(),Mw=Z(),Dw=ot(),Lw=at(),Pw=Bd(),$w=qd(),Rw=Wd();function Ho(r,e,t,s,n,i){let o=t.type==="block-map"?Pw.resolveBlockMap(r,e,t,s,i):t.type==="block-seq"?$w.resolveBlockSeq(r,e,t,s,i):Rw.resolveFlowCollection(r,e,t,s,i),a=o.constructor;return n==="!"||n===a.tagName?(o.tag=a.tagName,o):(n&&(o.tag=n),o)}function Bw(r,e,t,s,n){let i=s.tag,o=i?e.directives.tagName(i.source,h=>n(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:m}=s,g=h&&i?h.offset>i.offset?h:i:h??i;g&&(!m||m.offset<g.offset)&&n(g,"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===Dw.YAMLMap.tagName&&a==="map"||o===Lw.YAMLSeq.tagName&&a==="seq")return Ho(r,e,t,n,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?n(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):n(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Ho(r,e,t,n,o)}let c=Ho(r,e,t,n,o,l),d=l.resolve?.(c,h=>n(i,"TAG_RESOLVE_FAILED",h),e.options)??c,u=Ow.isNode(d)?d:new Mw.Scalar(d);return u.range=c.range,u.tag=o,l?.format&&(u.format=l.format),u}Gd.composeCollection=Bw});var Go=T(Yd=>{"use strict";var Wo=Z();function Uw(r,e,t){let s=e.offset,n=qw(e,r.options.strict,t);if(!n)return{value:"",type:null,comment:"",range:[s,s,s]};let i=n.mode===">"?Wo.Scalar.BLOCK_FOLDED:Wo.Scalar.BLOCK_LITERAL,o=e.source?jw(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=n.chomp==="+"&&o.length>0?`
74
74
  `.repeat(Math.max(1,o.length-1)):"",y=s+n.length;return e.source&&(y+=e.source.length),{value:f,type:i,comment:n.comment,range:[s,y,y]}}let l=e.indent+n.indent,c=e.offset+n.length,d=0;for(let f=0;f<a;++f){let[y,w]=o[f];if(w===""||w==="\r")n.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"),n.indent===0&&(l=y.length),d=f,l===0&&!r.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="",m=!1;for(let f=0;f<d;++f)u+=o[f][0].slice(l)+`
75
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 ${n.indent?"explicit indentation indicator":"first line"}`;t(c-w.length-(S?2:1),"BAD_INDENT",v),y=""}i===Wo.Scalar.BLOCK_LITERAL?(u+=h+y.slice(l)+w,h=`
76
76
  `):y.length>l||w[0]===" "?(h===" "?h=`
@@ -85,41 +85,41 @@ ${c}
85
85
  `+o[f][0].slice(l);u[u.length-1]!==`
86
86
  `&&(u+=`
87
87
  `);break;default:u+=`
88
- `}let g=s+n.length+e.source.length;return{value:u,type:i,comment:n.comment,range:[s,g,g]}}function Uw({offset:r,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],i=n[0],o=0,a="",l=-1;for(let h=1;h<n.length;++h){let m=n[h];if(!a&&(m==="-"||m==="+"))a=m;else{let g=Number(m);!o&&g?o=g:l===-1&&(l=r+h)}}l!==-1&&s(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,d="",u=n.length;for(let h=1;h<e.length;++h){let m=e[h];switch(m.type){case"space":c=!0;case"newline":u+=m.source.length;break;case"comment":t&&!c&&s(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=m.source.length,d=m.source.substring(1);break;case"error":s(m,"UNEXPECTED_TOKEN",m.message),u+=m.source.length;break;default:{let g=`Unexpected token in block scalar header: ${m.type}`;s(m,"UNEXPECTED_TOKEN",g);let f=m.source;f&&typeof f=="string"&&(u+=f.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function qw(r){let e=r.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}Yd.resolveBlockScalar=Bw});var Yo=T(zd=>{"use strict";var Vo=Z(),jw=Gt();function Fw(r,e,t){let{offset:s,type:n,source:i,end:o}=r,a,l,c=(h,m,g)=>t(s+h,m,g);switch(n){case"scalar":a=Vo.Scalar.PLAIN,l=Kw(i,c);break;case"single-quoted-scalar":a=Vo.Scalar.QUOTE_SINGLE,l=Hw(i,c);break;case"double-quoted-scalar":a=Vo.Scalar.QUOTE_DOUBLE,l=Ww(i,c);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[s,s+i.length,s+i.length]}}let d=s+i.length,u=jw.resolveEnd(o,d,e,t);return{value:l,type:a,comment:u.comment,range:[s,d,u.offset]}}function Kw(r,e){let t="";switch(r[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 ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Jd(r)}function Hw(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Jd(r.slice(1,-1)).replace(/''/g,"'")}function Jd(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
88
+ `}let g=s+n.length+e.source.length;return{value:u,type:i,comment:n.comment,range:[s,g,g]}}function qw({offset:r,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:n}=e[0],i=n[0],o=0,a="",l=-1;for(let h=1;h<n.length;++h){let m=n[h];if(!a&&(m==="-"||m==="+"))a=m;else{let g=Number(m);!o&&g?o=g:l===-1&&(l=r+h)}}l!==-1&&s(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${n}`);let c=!1,d="",u=n.length;for(let h=1;h<e.length;++h){let m=e[h];switch(m.type){case"space":c=!0;case"newline":u+=m.source.length;break;case"comment":t&&!c&&s(m,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=m.source.length,d=m.source.substring(1);break;case"error":s(m,"UNEXPECTED_TOKEN",m.message),u+=m.source.length;break;default:{let g=`Unexpected token in block scalar header: ${m.type}`;s(m,"UNEXPECTED_TOKEN",g);let f=m.source;f&&typeof f=="string"&&(u+=f.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function jw(r){let e=r.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}Yd.resolveBlockScalar=Uw});var Yo=T(zd=>{"use strict";var Vo=Z(),Fw=Gt();function Kw(r,e,t){let{offset:s,type:n,source:i,end:o}=r,a,l,c=(h,m,g)=>t(s+h,m,g);switch(n){case"scalar":a=Vo.Scalar.PLAIN,l=Hw(i,c);break;case"single-quoted-scalar":a=Vo.Scalar.QUOTE_SINGLE,l=Ww(i,c);break;case"double-quoted-scalar":a=Vo.Scalar.QUOTE_DOUBLE,l=Gw(i,c);break;default:return t(r,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${n}`),{value:"",type:null,comment:"",range:[s,s+i.length,s+i.length]}}let d=s+i.length,u=Fw.resolveEnd(o,d,e,t);return{value:l,type:a,comment:u.comment,range:[s,d,u.offset]}}function Hw(r,e){let t="";switch(r[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 ${r[0]}`;break}case"@":case"`":{t=`reserved character ${r[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Jd(r)}function Ww(r,e){return(r[r.length-1]!=="'"||r.length===1)&&e(r.length,"MISSING_CHAR","Missing closing 'quote"),Jd(r.slice(1,-1)).replace(/''/g,"'")}function Jd(r){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
89
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
90
90
  `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(r);if(!s)return r;let n=s[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;s=t.exec(r);)s[1]===""?i===`
91
91
  `?n+=i:i=`
92
- `:(n+=i+s[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(r),n+i+(s?.[1]??"")}function Ww(r,e){let t="";for(let s=1;s<r.length-1;++s){let n=r[s];if(!(n==="\r"&&r[s+1]===`
92
+ `:(n+=i+s[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(r),n+i+(s?.[1]??"")}function Gw(r,e){let t="";for(let s=1;s<r.length-1;++s){let n=r[s];if(!(n==="\r"&&r[s+1]===`
93
93
  `))if(n===`
94
- `){let{fold:i,offset:o}=Gw(r,s);t+=i,s=o}else if(n==="\\"){let i=r[++s],o=Vw[i];if(o)t+=o;else if(i===`
94
+ `){let{fold:i,offset:o}=Vw(r,s);t+=i,s=o}else if(n==="\\"){let i=r[++s],o=Yw[i];if(o)t+=o;else if(i===`
95
95
  `)for(i=r[s+1];i===" "||i===" ";)i=r[++s+1];else if(i==="\r"&&r[s+1]===`
96
- `)for(i=r[++s+1];i===" "||i===" ";)i=r[++s+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=Yw(r,s+1,a,e),s+=a}else{let a=r.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(n===" "||n===" "){let i=s,o=r[s+1];for(;o===" "||o===" ";)o=r[++s+1];o!==`
96
+ `)for(i=r[++s+1];i===" "||i===" ";)i=r[++s+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=Jw(r,s+1,a,e),s+=a}else{let a=r.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(n===" "||n===" "){let i=s,o=r[s+1];for(;o===" "||o===" ";)o=r[++s+1];o!==`
97
97
  `&&!(o==="\r"&&r[s+2]===`
98
- `)&&(t+=s>i?r.slice(i,s+1):n)}else t+=n}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function Gw(r,e){let t="",s=r[e+1];for(;(s===" "||s===" "||s===`
98
+ `)&&(t+=s>i?r.slice(i,s+1):n)}else t+=n}return(r[r.length-1]!=='"'||r.length===1)&&e(r.length,"MISSING_CHAR",'Missing closing "quote'),t}function Vw(r,e){let t="",s=r[e+1];for(;(s===" "||s===" "||s===`
99
99
  `||s==="\r")&&!(s==="\r"&&r[e+2]!==`
100
100
  `);)s===`
101
101
  `&&(t+=`
102
- `),e+=1,s=r[e+1];return t||(t=" "),{fold:t,offset:e}}var Vw={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 Yw(r,e,t,s){let n=r.substr(e,t),o=n.length===t&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;if(isNaN(o)){let a=r.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}zd.resolveFlowScalar=Fw});var Zd=T(Xd=>{"use strict";var kt=U(),Qd=Z(),Jw=Go(),zw=Yo();function Qw(r,e,t,s){let{value:n,type:i,comment:o,range:a}=e.type==="block-scalar"?Jw.resolveBlockScalar(r,e,s):zw.resolveFlowScalar(e,r.options.strict,s),l=t?r.directives.tagName(t.source,u=>s(t,"TAG_RESOLVE_FAILED",u)):null,c;r.options.stringKeys&&r.atKey?c=r.schema[kt.SCALAR]:l?c=Xw(r.schema,n,l,t,s):e.type==="scalar"?c=Zw(r,n,e,s):c=r.schema[kt.SCALAR];let d;try{let u=c.resolve(n,h=>s(t??e,"TAG_RESOLVE_FAILED",h),r.options);d=kt.isScalar(u)?u:new Qd.Scalar(u)}catch(u){let h=u instanceof Error?u.message:String(u);s(t??e,"TAG_RESOLVE_FAILED",h),d=new Qd.Scalar(n)}return d.range=a,d.source=n,i&&(d.type=i),l&&(d.tag=l),c.format&&(d.format=c.format),o&&(d.comment=o),d}function Xw(r,e,t,s,n){if(t==="!")return r[kt.SCALAR];let i=[];for(let a of r.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=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[kt.SCALAR])}function Zw({atKey:r,directives:e,schema:t},s,n,i){let o=t.tags.find(a=>(a.default===!0||r&&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(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}Xd.composeScalar=Qw});var tu=T(eu=>{"use strict";function eS(r,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let n=e[s];switch(n.type){case"space":case"comment":case"newline":r-=n.source.length;continue}for(n=e[++s];n?.type==="space";)r+=n.source.length,n=e[++s];break}}return r}eu.emptyScalarPosition=eS});var ru=T(zo=>{"use strict";var tS=ms(),sS=U(),nS=Vd(),su=Zd(),rS=Gt(),iS=tu(),oS={composeNode:nu,composeEmptyNode:Jo};function nu(r,e,t,s){let n=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t,c,d=!0;switch(e.type){case"alias":c=aS(r,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=su.composeScalar(r,e,l,s),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=nS.composeCollection(oS,r,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=Jo(r,e.offset,void 0,null,t,s)),a&&c.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),n&&r.options.stringKeys&&(!sS.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),r.options.keepSourceTokens&&d&&(c.srcToken=e),c}function Jo(r,e,t,s,{spaceBefore:n,comment:i,anchor:o,tag:a,end:l},c){let d={type:"scalar",offset:iS.emptyScalarPosition(e,t,s),indent:-1,source:""},u=su.composeScalar(r,d,a,c);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=l),u}function aS({options:r},{offset:e,source:t,end:s},n){let i=new tS.Alias(t.substring(1));i.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&n(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=rS.resolveEnd(s,o,r.strict,n);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}zo.composeEmptyNode=Jo;zo.composeNode=nu});var au=T(ou=>{"use strict";var cS=Ms(),iu=ru(),lS=Gt(),dS=$s();function uS(r,e,{offset:t,start:s,value:n,end:i},o){let a=Object.assign({_directives:e},r),l=new cS.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=dS.resolveProps(s,{indicator:"doc-start",next:n??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=n?iu.composeNode(c,n,d,o):iu.composeEmptyNode(c,d.end,s,null,d,o);let u=l.contents.range[2],h=lS.resolveEnd(i,u,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,u,h.offset],l}ou.composeDoc=uS});var Xo=T(du=>{"use strict";var hS=H("process"),fS=$i(),pS=Ms(),Rs=Ps(),cu=U(),mS=au(),gS=Gt();function Bs(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function lu(r){let e="",t=!1,s=!1;for(let n=0;n<r.length;++n){let i=r[n];switch(i[0]){case"#":e+=(e===""?"":s?`
102
+ `),e+=1,s=r[e+1];return t||(t=" "),{fold:t,offset:e}}var Yw={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 Jw(r,e,t,s){let n=r.substr(e,t),o=n.length===t&&/^[0-9a-fA-F]+$/.test(n)?parseInt(n,16):NaN;if(isNaN(o)){let a=r.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}zd.resolveFlowScalar=Kw});var Zd=T(Xd=>{"use strict";var kt=U(),Qd=Z(),zw=Go(),Qw=Yo();function Xw(r,e,t,s){let{value:n,type:i,comment:o,range:a}=e.type==="block-scalar"?zw.resolveBlockScalar(r,e,s):Qw.resolveFlowScalar(e,r.options.strict,s),l=t?r.directives.tagName(t.source,u=>s(t,"TAG_RESOLVE_FAILED",u)):null,c;r.options.stringKeys&&r.atKey?c=r.schema[kt.SCALAR]:l?c=Zw(r.schema,n,l,t,s):e.type==="scalar"?c=eS(r,n,e,s):c=r.schema[kt.SCALAR];let d;try{let u=c.resolve(n,h=>s(t??e,"TAG_RESOLVE_FAILED",h),r.options);d=kt.isScalar(u)?u:new Qd.Scalar(u)}catch(u){let h=u instanceof Error?u.message:String(u);s(t??e,"TAG_RESOLVE_FAILED",h),d=new Qd.Scalar(n)}return d.range=a,d.source=n,i&&(d.type=i),l&&(d.tag=l),c.format&&(d.format=c.format),o&&(d.comment=o),d}function Zw(r,e,t,s,n){if(t==="!")return r[kt.SCALAR];let i=[];for(let a of r.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=r.knownTags[t];return o&&!o.collection?(r.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(n(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),r[kt.SCALAR])}function eS({atKey:r,directives:e,schema:t},s,n,i){let o=t.tags.find(a=>(a.default===!0||r&&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(n,"TAG_RESOLVE_FAILED",d,!0)}}return o}Xd.composeScalar=Xw});var tu=T(eu=>{"use strict";function tS(r,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let n=e[s];switch(n.type){case"space":case"comment":case"newline":r-=n.source.length;continue}for(n=e[++s];n?.type==="space";)r+=n.source.length,n=e[++s];break}}return r}eu.emptyScalarPosition=tS});var ru=T(zo=>{"use strict";var sS=ms(),nS=U(),rS=Vd(),su=Zd(),iS=Gt(),oS=tu(),aS={composeNode:nu,composeEmptyNode:Jo};function nu(r,e,t,s){let n=r.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t,c,d=!0;switch(e.type){case"alias":c=cS(r,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=su.composeScalar(r,e,l,s),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=rS.composeCollection(aS,r,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=Jo(r,e.offset,void 0,null,t,s)),a&&c.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),n&&r.options.stringKeys&&(!nS.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),r.options.keepSourceTokens&&d&&(c.srcToken=e),c}function Jo(r,e,t,s,{spaceBefore:n,comment:i,anchor:o,tag:a,end:l},c){let d={type:"scalar",offset:oS.emptyScalarPosition(e,t,s),indent:-1,source:""},u=su.composeScalar(r,d,a,c);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),n&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=l),u}function cS({options:r},{offset:e,source:t,end:s},n){let i=new sS.Alias(t.substring(1));i.source===""&&n(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&n(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=iS.resolveEnd(s,o,r.strict,n);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}zo.composeEmptyNode=Jo;zo.composeNode=nu});var au=T(ou=>{"use strict";var lS=Ms(),iu=ru(),dS=Gt(),uS=$s();function hS(r,e,{offset:t,start:s,value:n,end:i},o){let a=Object.assign({_directives:e},r),l=new lS.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=uS.resolveProps(s,{indicator:"doc-start",next:n??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,n&&(n.type==="block-map"||n.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=n?iu.composeNode(c,n,d,o):iu.composeEmptyNode(c,d.end,s,null,d,o);let u=l.contents.range[2],h=dS.resolveEnd(i,u,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,u,h.offset],l}ou.composeDoc=hS});var Xo=T(du=>{"use strict";var fS=H("process"),pS=$i(),mS=Ms(),Rs=Ps(),cu=U(),gS=au(),yS=Gt();function Bs(r){if(typeof r=="number")return[r,r+1];if(Array.isArray(r))return r.length===2?r:[r[0],r[1]];let{offset:e,source:t}=r;return[e,e+(typeof t=="string"?t.length:1)]}function lu(r){let e="",t=!1,s=!1;for(let n=0;n<r.length;++n){let i=r[n];switch(i[0]){case"#":e+=(e===""?"":s?`
104
104
 
105
105
  `:`
106
- `)+(i.substring(1)||" "),t=!0,s=!1;break;case"%":r[n+1]?.[0]!=="#"&&(n+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}var Qo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,n,i)=>{let o=Bs(t);i?this.warnings.push(new Rs.YAMLWarning(o,s,n)):this.errors.push(new Rs.YAMLParseError(o,s,n))},this.directives=new fS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:s,afterEmptyLine:n}=lu(this.prelude);if(s){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
106
+ `)+(i.substring(1)||" "),t=!0,s=!1;break;case"%":r[n+1]?.[0]!=="#"&&(n+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}var Qo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,n,i)=>{let o=Bs(t);i?this.warnings.push(new Rs.YAMLWarning(o,s,n)):this.errors.push(new Rs.YAMLParseError(o,s,n))},this.directives=new pS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:s,afterEmptyLine:n}=lu(this.prelude);if(s){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
107
107
  ${s}`:s;else if(n||e.directives.docStart||!i)e.commentBefore=s;else if(cu.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];cu.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${s}
108
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:lu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(let n of e)yield*this.next(n);yield*this.end(t,s)}*next(e){switch(hS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,s,n)=>{let i=Bs(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",s,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=mS.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=gS.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),n=new pS.Document(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}};du.Composer=Qo});var fu=T(or=>{"use strict";var yS=Go(),wS=Yo(),SS=Ps(),uu=ks();function kS(r,e=!0,t){if(r){let s=(n,i,o)=>{let a=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(t)t(a,i,o);else throw new SS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return wS.resolveFlowScalar(r,e,s);case"block-scalar":return yS.resolveBlockScalar({options:{strict:e}},r,s)}}return null}function bS(r,e){let{implicitKey:t=!1,indent:s,inFlow:n=!1,offset:i=-1,type:o="PLAIN"}=e,a=uu.stringifyString({type:o,value:r},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:s,source:`
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:lu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(let n of e)yield*this.next(n);yield*this.end(t,s)}*next(e){switch(fS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,s,n)=>{let i=Bs(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",s,n)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=gS.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=yS.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),n=new mS.Document(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),n.range=[0,t,t],this.decorate(n,!1),yield n}}};du.Composer=Qo});var fu=T(or=>{"use strict";var wS=Go(),SS=Yo(),kS=Ps(),uu=ks();function bS(r,e=!0,t){if(r){let s=(n,i,o)=>{let a=typeof n=="number"?n:Array.isArray(n)?n[0]:n.offset;if(t)t(a,i,o);else throw new kS.YAMLParseError([a,a+1],i,o)};switch(r.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return SS.resolveFlowScalar(r,e,s);case"block-scalar":return wS.resolveBlockScalar({options:{strict:e}},r,s)}}return null}function _S(r,e){let{implicitKey:t=!1,indent:s,inFlow:n=!1,offset:i=-1,type:o="PLAIN"}=e,a=uu.stringifyString({type:o,value:r},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:n,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:s,source:`
111
111
  `}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
112
112
  `),d=a.substring(0,c),u=a.substring(c+1)+`
113
113
  `,h=[{type:"block-scalar-header",offset:i,indent:s,source:d}];return hu(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 _S(r,e,t={}){let{afterKey:s=!1,implicitKey:n=!1,inFlow:i=!1,type:o}=t,a="indent"in r?r.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(r.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=r.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=uu.stringifyString({type:o,value:e},{implicitKey:n||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":vS(r,l);break;case'"':Zo(r,l,"double-quoted-scalar");break;case"'":Zo(r,l,"single-quoted-scalar");break;default:Zo(r,l,"scalar")}}function vS(r,e){let t=e.indexOf(`
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 vS(r,e,t={}){let{afterKey:s=!1,implicitKey:n=!1,inFlow:i=!1,type:o}=t,a="indent"in r?r.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(r.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=r.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=uu.stringifyString({type:o,value:e},{implicitKey:n||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":TS(r,l);break;case'"':Zo(r,l,"double-quoted-scalar");break;case"'":Zo(r,l,"single-quoted-scalar");break;default:Zo(r,l,"scalar")}}function TS(r,e){let t=e.indexOf(`
115
115
  `),s=e.substring(0,t),n=e.substring(t+1)+`
116
116
  `;if(r.type==="block-scalar"){let i=r.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=s,r.source=n}else{let{offset:i}=r,o="indent"in r?r.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:s}];hu(a,"end"in r?r.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
117
117
  `});for(let l of Object.keys(r))l!=="type"&&l!=="offset"&&delete r[l];Object.assign(r,{type:"block-scalar",indent:o,props:a,source:n})}}function hu(r,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":r.push(t);break;case"newline":return r.push(t),!0}return!1}function Zo(r,e,t){switch(r.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":r.type=t,r.source=e;break;case"block-scalar":{let s=r.props.slice(1),n=e.length;r.props[0].type==="block-scalar-header"&&(n-=r.props[0].source.length);for(let i of s)i.offset+=n;delete r.props,Object.assign(r,{type:t,source:e,end:s});break}case"block-map":case"block-seq":{let n={type:"newline",offset:r.offset+e.length,indent:r.indent,source:`
118
- `};delete r.items,Object.assign(r,{type:t,source:e,end:[n]});break}default:{let s="indent"in r?r.indent:-1,n="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:s,source:e,end:n})}}}or.createScalarToken=bS;or.resolveAsScalar=kS;or.setScalarValue=_S});var mu=T(pu=>{"use strict";var TS=r=>"type"in r?cr(r):ar(r);function cr(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=cr(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=ar(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=ar(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=ar(r);if(r.end)for(let t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(let t of r.end)e+=t.source;return e}}}function ar({start:r,key:e,sep:t,value:s}){let n="";for(let i of r)n+=i.source;if(e&&(n+=cr(e)),t)for(let i of t)n+=i.source;return s&&(n+=cr(s)),n}pu.stringify=TS});var Su=T(wu=>{"use strict";var ea=Symbol("break visit"),IS=Symbol("skip children"),gu=Symbol("remove item");function bt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),yu(Object.freeze([]),r,e)}bt.BREAK=ea;bt.SKIP=IS;bt.REMOVE=gu;bt.itemAtPath=(r,e)=>{let t=r;for(let[s,n]of e){let i=t?.[s];if(i&&"items"in i)t=i.items[n];else return}return t};bt.parentCollection=(r,e)=>{let t=bt.itemAtPath(r,e.slice(0,-1)),s=e[e.length-1][0],n=t?.[s];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function yu(r,e,t){let s=t(e,r);if(typeof s=="symbol")return s;for(let n of["key","value"]){let i=e[n];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=yu(Object.freeze(r.concat([[n,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ea)return ea;a===gu&&(i.items.splice(o,1),o-=1)}}typeof s=="function"&&n==="key"&&(s=s(e,r))}}return typeof s=="function"?s(e,r):s}wu.visit=bt});var lr=T(he=>{"use strict";var ta=fu(),CS=mu(),AS=Su(),sa="\uFEFF",na="",ra="",ia="",ES=r=>!!r&&"items"in r,NS=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function xS(r){switch(r){case sa:return"<BOM>";case na:return"<DOC>";case ra:return"<FLOW_END>";case ia:return"<SCALAR>";default:return JSON.stringify(r)}}function OS(r){switch(r){case sa:return"byte-order-mark";case na:return"doc-mode";case ra:return"flow-error-end";case ia:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
118
+ `};delete r.items,Object.assign(r,{type:t,source:e,end:[n]});break}default:{let s="indent"in r?r.indent:-1,n="end"in r&&Array.isArray(r.end)?r.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(r))i!=="type"&&i!=="offset"&&delete r[i];Object.assign(r,{type:t,indent:s,source:e,end:n})}}}or.createScalarToken=_S;or.resolveAsScalar=bS;or.setScalarValue=vS});var mu=T(pu=>{"use strict";var IS=r=>"type"in r?cr(r):ar(r);function cr(r){switch(r.type){case"block-scalar":{let e="";for(let t of r.props)e+=cr(t);return e+r.source}case"block-map":case"block-seq":{let e="";for(let t of r.items)e+=ar(t);return e}case"flow-collection":{let e=r.start.source;for(let t of r.items)e+=ar(t);for(let t of r.end)e+=t.source;return e}case"document":{let e=ar(r);if(r.end)for(let t of r.end)e+=t.source;return e}default:{let e=r.source;if("end"in r&&r.end)for(let t of r.end)e+=t.source;return e}}}function ar({start:r,key:e,sep:t,value:s}){let n="";for(let i of r)n+=i.source;if(e&&(n+=cr(e)),t)for(let i of t)n+=i.source;return s&&(n+=cr(s)),n}pu.stringify=IS});var Su=T(wu=>{"use strict";var ea=Symbol("break visit"),CS=Symbol("skip children"),gu=Symbol("remove item");function bt(r,e){"type"in r&&r.type==="document"&&(r={start:r.start,value:r.value}),yu(Object.freeze([]),r,e)}bt.BREAK=ea;bt.SKIP=CS;bt.REMOVE=gu;bt.itemAtPath=(r,e)=>{let t=r;for(let[s,n]of e){let i=t?.[s];if(i&&"items"in i)t=i.items[n];else return}return t};bt.parentCollection=(r,e)=>{let t=bt.itemAtPath(r,e.slice(0,-1)),s=e[e.length-1][0],n=t?.[s];if(n&&"items"in n)return n;throw new Error("Parent collection not found")};function yu(r,e,t){let s=t(e,r);if(typeof s=="symbol")return s;for(let n of["key","value"]){let i=e[n];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=yu(Object.freeze(r.concat([[n,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===ea)return ea;a===gu&&(i.items.splice(o,1),o-=1)}}typeof s=="function"&&n==="key"&&(s=s(e,r))}}return typeof s=="function"?s(e,r):s}wu.visit=bt});var lr=T(he=>{"use strict";var ta=fu(),AS=mu(),ES=Su(),sa="\uFEFF",na="",ra="",ia="",NS=r=>!!r&&"items"in r,xS=r=>!!r&&(r.type==="scalar"||r.type==="single-quoted-scalar"||r.type==="double-quoted-scalar"||r.type==="block-scalar");function OS(r){switch(r){case sa:return"<BOM>";case na:return"<DOC>";case ra:return"<FLOW_END>";case ia:return"<SCALAR>";default:return JSON.stringify(r)}}function MS(r){switch(r){case sa:return"byte-order-mark";case na:return"doc-mode";case ra:return"flow-error-end";case ia: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(r[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}he.createScalarToken=ta.createScalarToken;he.resolveAsScalar=ta.resolveAsScalar;he.setScalarValue=ta.setScalarValue;he.stringify=CS.stringify;he.visit=AS.visit;he.BOM=sa;he.DOCUMENT=na;he.FLOW_END=ra;he.SCALAR=ia;he.isCollection=ES;he.isScalar=NS;he.prettyToken=xS;he.tokenType=OS});var ca=T(bu=>{"use strict";var Us=lr();function Ee(r){switch(r){case void 0:case" ":case`
121
- `:case"\r":case" ":return!0;default:return!1}}var ku=new Set("0123456789ABCDEFabcdef"),MS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),dr=new Set(",[]{}"),DS=new Set(` ,[]{}
122
- \r `),oa=r=>!r||DS.has(r),aa=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(r[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}he.createScalarToken=ta.createScalarToken;he.resolveAsScalar=ta.resolveAsScalar;he.setScalarValue=ta.setScalarValue;he.stringify=AS.stringify;he.visit=ES.visit;he.BOM=sa;he.DOCUMENT=na;he.FLOW_END=ra;he.SCALAR=ia;he.isCollection=NS;he.isScalar=xS;he.prettyToken=OS;he.tokenType=MS});var ca=T(bu=>{"use strict";var Us=lr();function Ee(r){switch(r){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var ku=new Set("0123456789ABCDEFabcdef"),DS=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),dr=new Set(",[]{}"),LS=new Set(` ,[]{}
122
+ \r `),oa=r=>!r||LS.has(r),aa=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===`
123
123
  `?!0:t==="\r"?this.buffer[e+1]===`
124
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 n=this.buffer[s+e+1];if(n===`
125
125
  `||!n&&!this.atEnd)return e+s+1}return t===`
@@ -134,22 +134,22 @@ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.pus
134
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,n;for(;n=this.buffer[++s];)if(n===":"){let i=this.buffer[s+1];if(Ee(i)||e&&dr.has(i))break;t=s}else if(Ee(n)){let i=this.buffer[s+1];if(n==="\r"&&(i===`
135
135
  `?(s+=1,n=`
136
136
  `,i=this.buffer[s+1]):t=s),i==="#"||e&&dr.has(i))break;if(n===`
137
- `){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&dr.has(n))break;t=s}return!n&&!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(oa))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Ee(t)||e&&dr.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(MS.has(t))t=this.buffer[++e];else if(t==="%"&&ku.has(this.buffer[e+1])&&ku.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===`
137
+ `){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&dr.has(n))break;t=s}return!n&&!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(oa))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Ee(t)||e&&dr.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(DS.has(t))t=this.buffer[++e];else if(t==="%"&&ku.has(this.buffer[e+1])&&ku.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 n=t-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=t),n}*pushUntil(e){let t=this.pos,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};bu.Lexer=aa});var da=T(_u=>{"use strict";var la=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 n=this.lineStarts[t-1];return{line:t,col:e-n+1}}}};_u.LineCounter=la});var ha=T(Au=>{"use strict";var LS=H("process"),vu=lr(),PS=ca();function ct(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Tu(r){for(let e=0;e<r.length;++e)switch(r[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Cu(r){switch(r?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function ur(r){switch(r.type){case"document":return r.start;case"block-map":{let e=r.items[r.items.length-1];return e.sep??e.start}case"block-seq":return r.items[r.items.length-1].start;default:return[]}}function Vt(r){if(r.length===0)return[];let e=r.length;e:for(;--e>=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function Iu(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!ct(e.start,"explicit-key-ind")&&!ct(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Cu(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 ua=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 PS.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,LS.env.LOG_TOKENS&&console.log("|",vu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=vu.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"&&Iu(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{let n=s.items[s.items.length-1];if(n.value){s.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=s.items[s.items.length-1];n.value?s.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{let n=s.items[s.items.length-1];!n||n.value?s.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{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 n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Tu(n.start)===-1&&(t.indent===0||n.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(s.type==="document"?s.end=n.start:s.items.push({start:n.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":{Tu(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=ur(this.peek(2)),s=Vt(t),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:n}]};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,s;do s=this.buffer[++t];while(s===" "||e&&s===" ");let n=t-this.pos;return n>0&&(yield this.buffer.substr(this.pos,n),this.pos=t),n}*pushUntil(e){let t=this.pos,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};bu.Lexer=aa});var da=T(_u=>{"use strict";var la=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 n=this.lineStarts[t-1];return{line:t,col:e-n+1}}}};_u.LineCounter=la});var ha=T(Au=>{"use strict";var PS=H("process"),vu=lr(),$S=ca();function ct(r,e){for(let t=0;t<r.length;++t)if(r[t].type===e)return!0;return!1}function Tu(r){for(let e=0;e<r.length;++e)switch(r[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Cu(r){switch(r?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function ur(r){switch(r.type){case"document":return r.start;case"block-map":{let e=r.items[r.items.length-1];return e.sep??e.start}case"block-seq":return r.items[r.items.length-1].start;default:return[]}}function Vt(r){if(r.length===0)return[];let e=r.length;e:for(;--e>=0;)switch(r[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;r[++e]?.type==="space";);return r.splice(e,r.length)}function Iu(r){if(r.start.type==="flow-seq-start")for(let e of r.items)e.sep&&!e.value&&!ct(e.start,"explicit-key-ind")&&!ct(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Cu(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 ua=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 $S.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,PS.env.LOG_TOKENS&&console.log("|",vu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=vu.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"&&Iu(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{let n=s.items[s.items.length-1];if(n.value){s.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case"block-seq":{let n=s.items[s.items.length-1];n.value?s.items.push({start:[],value:t}):n.value=t;break}case"flow-collection":{let n=s.items[s.items.length-1];!n||n.value?s.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{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 n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Tu(n.start)===-1&&(t.indent===0||n.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(s.type==="document"?s.end=n.start:s.items.push({start:n.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":{Tu(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=ur(this.peek(2)),s=Vt(t),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:n}]};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(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
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 n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.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,n=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(n&&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":n||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):n||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(ct(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(Cu(t.key)&&!ct(t.sep,"newline")){let o=Vt(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(ct(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Vt(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||n?e.items.push({start:i,key:null,sep:[this.sourceToken]}):ct(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);n||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&&!ct(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 n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){Array.prototype.push.apply(n,t.start),n.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||ct(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 n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,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 n=ur(s),i=Vt(n);Iu(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(`
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=ur(e),s=Vt(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=ur(e),s=Vt(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())}}};Au.Parser=ua});var Mu=T(js=>{"use strict";var Eu=Xo(),$S=Ms(),qs=Ps(),RS=Ji(),BS=U(),US=da(),Nu=ha();function xu(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new US.LineCounter||null,prettyErrors:e}}function qS(r,e={}){let{lineCounter:t,prettyErrors:s}=xu(e),n=new Nu.Parser(t?.addNewLine),i=new Eu.Composer(e),o=Array.from(i.compose(n.parse(r)));if(s&&t)for(let a of o)a.errors.forEach(qs.prettifyError(r,t)),a.warnings.forEach(qs.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Ou(r,e={}){let{lineCounter:t,prettyErrors:s}=xu(e),n=new Nu.Parser(t?.addNewLine),i=new Eu.Composer(e),o=null;for(let a of i.compose(n.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new qs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(qs.prettifyError(r,t)),o.warnings.forEach(qs.prettifyError(r,t))),o}function jS(r,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);let n=Ou(r,t);if(!n)return null;if(n.warnings.forEach(i=>RS.warn(n.options.logLevel,i)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:s},t))}function FS(r,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 n=Math.round(t);t=n<1?void 0:n>8?{indent:8}:{indent:n}}if(r===void 0){let{keepUndefined:n}=t??e??{};if(!n)return}return BS.isDocument(r)&&!s?r.toString(t):new $S.Document(r,s,t).toString(t)}js.parse=jS;js.parseAllDocuments=qS;js.parseDocument=Ou;js.stringify=FS});var pa=T(F=>{"use strict";var KS=Xo(),HS=Ms(),WS=Mo(),fa=Ps(),GS=ms(),lt=U(),VS=rt(),YS=Z(),JS=ot(),zS=at(),QS=lr(),XS=ca(),ZS=da(),e0=ha(),hr=Mu(),Du=us();F.Composer=KS.Composer;F.Document=HS.Document;F.Schema=WS.Schema;F.YAMLError=fa.YAMLError;F.YAMLParseError=fa.YAMLParseError;F.YAMLWarning=fa.YAMLWarning;F.Alias=GS.Alias;F.isAlias=lt.isAlias;F.isCollection=lt.isCollection;F.isDocument=lt.isDocument;F.isMap=lt.isMap;F.isNode=lt.isNode;F.isPair=lt.isPair;F.isScalar=lt.isScalar;F.isSeq=lt.isSeq;F.Pair=VS.Pair;F.Scalar=YS.Scalar;F.YAMLMap=JS.YAMLMap;F.YAMLSeq=zS.YAMLSeq;F.CST=QS;F.Lexer=XS.Lexer;F.LineCounter=ZS.LineCounter;F.Parser=e0.Parser;F.parse=hr.parse;F.parseAllDocuments=hr.parseAllDocuments;F.parseDocument=hr.parseDocument;F.stringify=hr.stringify;F.visit=Du.visit;F.visitAsync=Du.visitAsync});function Lu(r={},e){let t={};for(let s of Object.keys(Yt)){let n=r[s]??Yt[s];t[s]=n&&(e?.[s]??!0)}return t}var Yt,ma=j(()=>{"use strict";Yt={externalComms:!0,codeTask:!1,codeAccess:!1}});import{execFileSync as t0}from"node:child_process";function Jt(r,e){if(process.platform!=="darwin")return"";try{return t0("security",["find-generic-password","-s",`hive/${r}/${e}`,"-w"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}var fr=j(()=>{"use strict"});import{readFileSync as s0,existsSync as Bu,readdirSync as n0,statSync as r0}from"node:fs";import{resolve as ga}from"node:path";import{randomUUID as ya}from"node:crypto";function Pu(r){let e=process.env[r]||qu(r);if(!e)throw new Error(`Missing required env var: ${r}`);return e}function b(r,e){return process.env[r]||qu(r)||e}function o0(r){if(r?.length)return r.map(t=>ga(t.replace(/^~/,process.env.HOME??"/tmp")));let e=ga(cs,"plugins/claude-code");return Bu(e)?n0(e).map(t=>ga(e,t)).filter(t=>r0(t).isDirectory()):[]}var Ru,Uu,i0,$u,A,pI,Fs,qu,dt,_t,p,Ne=j(()=>{"use strict";Ru=Ce(Gc(),1),Uu=Ce(pa(),1);ma();fr();ls();i0=Tc(z);Ru.default.config({path:i0});$u=vc(z),A={};Bu($u)&&(A=(0,Uu.parse)(s0($u,"utf-8"))??{});pI=process.env.HOME??"/tmp",Fs=A.instance?.id??"hive",qu=r=>Jt(Fs,r),dt=A.instance?.portBase??3100,_t=A.instance?.ports??{},p={instance:{id:Fs,portBase:dt},business:{name:A.business?.name??b("BUSINESS_NAME",""),description:A.business?.description??"",location:A.business?.location??"",ownerName:A.business?.owner?.name??"",ownerRole:A.business?.owner?.role??""},slack:{appToken:Pu("SLACK_APP_TOKEN"),botToken:Pu("SLACK_BOT_TOKEN"),mcpToken:b("SLACK_MCP_TOKEN",""),auditChannel:b("SLACK_AUDIT_CHANNEL",A.slack?.auditChannel??""),localMcpServer:!!(A.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(([r])=>r.startsWith("TASK_LEDGER_KEY_")).map(([r,e])=>[r.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",A.google?.account??""),client:b("GOG_CLIENT",A.google?.client??""),accounts:A.google?.accounts??{},sharedFolder:b("DRIVE_SHARED_FOLDER",A.google?.sharedFolder??A.googleWorkspace?.sharedFolder??"")},googleWorkspace:{account:b("GWS_ACCOUNT",A.googleWorkspace?.account??""),gwsPath:b("GWS_PATH",""),sharedFolder:b("GWS_SHARED_FOLDER",A.googleWorkspace?.sharedFolder??"")},quo:{apiKey:b("QUO_API_KEY",""),phoneNumberId:b("QUO_PHONE_NUMBER_ID",""),lines:A.quo?.lines??{}},sms:{lines:A.sms?.lines??[]},imessage:{enabled:A.imessage?.enabled??!1,slackChannel:A.imessage?.slackChannel??"imessage",hotWindowMs:A.imessage?.hotWindowMs??3e5,coldIntervalMs:A.imessage?.coldIntervalMs??3e5,hotIntervalMs:A.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",A.resend?.emailDomain??""),businessName:b("RESEND_BUSINESS_NAME",A.resend?.businessName??"")},plugins:A.plugins??[],skillRegistries:A.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??dt+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??dt)),10),authToken:b("BG_TASK_AUTH_TOKEN","")||ya()},slackInternal:{port:parseInt(b("SLACK_INTERNAL_PORT",String(_t.slackInternal??dt+6)),10),authToken:b("SLACK_INTERNAL_TOKEN","")||ya()},codeTask:{port:parseInt(b("CODE_TASK_PORT",String(_t.codeTask??dt+2)),10),authToken:b("CODE_TASK_AUTH_TOKEN","")||ya(),pluginDirs:o0(A.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??dt+3)),10)},beekeeper:{port:parseInt(b("BEEKEEPER_PORT",String(A.beekeeper?.port??8420)),10)},workflow:{enabled:b("WORKFLOW_ENABLED","false")==="true"},adminApi:{port:parseInt(b("ADMIN_API_PORT",String(_t.adminApi??dt+4)),10),token:b("ADMIN_API_TOKEN","")},voice:{enabled:!!A.voice?.provider,provider:A.voice?.provider??"",publicUrl:A.voice?.publicUrl??"",phoneNumberId:A.voice?.phoneNumberId??"",assistants:A.voice?.assistants??{},apiKey:b("VAPI_API_KEY",""),serverSecret:b("VAPI_SERVER_SECRET",""),port:parseInt(b("VOICE_PORT",String(_t.voice??dt+5)),10)},autonomy:{externalComms:A.autonomy?.externalComms??Yt.externalComms,codeTask:A.autonomy?.codeTask??Yt.codeTask,codeAccess:A.autonomy?.codeAccess??Yt.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 r=A.retention?.paths??{data:7,"agents/*/scratch":7,"agents/*/feeds":7,"agents/*/playwright":3,"agents/*/reports":0,logs:30},e={};for(let[n,i]of Object.entries(r)){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new Error(`Invalid retention.paths.${n}: must be a non-negative integer (got ${i})`);e[n]={days:i}}let t=Number(A.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(A.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:!!(A.retention?.enabled??!1),intervalMs:s,defaultDays:t,paths:e}})(),memory:{hotBudgetTokens:parseInt(b("MEMORY_HOT_BUDGET_TOKENS",String(A.memory?.hotBudgetTokens??3e3)),10),sweepIntervalHours:parseFloat(b("MEMORY_SWEEP_INTERVAL_HOURS",String(A.memory?.sweepIntervalHours??6))),hotThreshold:parseFloat(b("MEMORY_HOT_THRESHOLD",String(A.memory?.hotThreshold??.6))),warmThreshold:parseFloat(b("MEMORY_WARM_THRESHOLD",String(A.memory?.warmThreshold??.3))),recencyHalfLifeDays:parseFloat(b("MEMORY_RECENCY_HALF_LIFE_DAYS",String(A.memory?.recencyHalfLifeDays??7))),coldSummaryMinRecords:parseInt(b("MEMORY_COLD_SUMMARY_MIN",String(A.memory?.coldSummaryMinRecords??5)),10),coldRetentionDays:parseInt(b("MEMORY_COLD_RETENTION_DAYS",String(A.memory?.coldRetentionDays??90)),10),purgeRetentionDays:parseInt(b("MEMORY_PURGE_RETENTION_DAYS",String(A.memory?.purgeRetentionDays??7)),10),reflectionMinTurns:parseInt(b("MEMORY_REFLECTION_MIN_TURNS",String(A.memory?.reflectionMinTurns??3)),10)},codeIndex:{enabled:A.codeIndex?.enabled===!0||process.env.CODE_INDEX_ENABLED==="true",scoreThreshold:parseFloat(b("CODE_INDEX_SCORE_THRESHOLD",String(A.codeIndex?.scoreThreshold??.65))),prefetchLimit:parseInt(b("CODE_INDEX_PREFETCH_LIMIT",String(A.codeIndex?.prefetchLimit??8)),10),sessionKnowledge:{enabled:(A.codeIndex?.sessionKnowledge?.enabled??!0)&&process.env.CODE_INDEX_SESSION_KNOWLEDGE!=="false"},repos:A.codeIndex?.repos??{}},events:{retentionDays:parseInt(b("EVENT_RETENTION_DAYS",String(A.events?.retentionDays??30)),10)},activity:{enabled:(A.activity?.enabled??!0)&&process.env.ACTIVITY_LOG_ENABLED!=="false",bufferSize:parseInt(b("ACTIVITY_BUFFER_SIZE",String(A.activity?.bufferSize??200)),10),flushIntervalMs:parseInt(b("ACTIVITY_FLUSH_INTERVAL_MS",String(A.activity?.flushIntervalMs??3e4)),10),retentionDays:parseInt(b("ACTIVITY_RETENTION_DAYS",String(A.activity?.retentionDays??90)),10)},autoDream:{enabled:A.autoDream?.enabled??!0,idleThresholdMinutes:parseInt(b("AUTODREAM_IDLE_THRESHOLD_MINUTES",String(A.autoDream?.idleThresholdMinutes??30)),10),cooldownMinutes:parseInt(b("AUTODREAM_COOLDOWN_MINUTES",String(A.autoDream?.cooldownMinutes??60)),10),similarityThreshold:parseFloat(b("AUTODREAM_SIMILARITY_THRESHOLD",String(A.autoDream?.similarityThreshold??.85))),patternMinCount:parseInt(b("AUTODREAM_PATTERN_MIN_COUNT",String(A.autoDream?.patternMinCount??3)),10),maxClustersPerRun:parseInt(b("AUTODREAM_MAX_CLUSTERS",String(A.autoDream?.maxClustersPerRun??20)),10),maxContradictionPairsPerRun:parseInt(b("AUTODREAM_MAX_CONTRADICTIONS",String(A.autoDream?.maxContradictionPairsPerRun??30)),10),maxPromotionsPerRun:parseInt(b("AUTODREAM_MAX_PROMOTIONS",String(A.autoDream?.maxPromotionsPerRun??10)),10),maxBudgetUsd:parseFloat(b("AUTODREAM_MAX_BUDGET_USD",String(A.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 Ku(r){wa.has(r.id)&&Fu.warn("Archetype already registered \u2014 overwriting",{id:r.id}),wa.set(r.id,r),Fu.info("Registered archetype",{id:r.id})}function pr(r){return wa.get(r)}var Fu,wa,mr=j(()=>{"use strict";O();Fu=k("archetypes"),wa=new Map});import{readFileSync as p0}from"node:fs";import{resolve as oh}from"node:path";function g0(){let r=[oh(import.meta.dirname,"..","..","package.json"),oh(import.meta.dirname,"..","package.json")];for(let e of r)try{let t=JSON.parse(p0(e,"utf-8"));if(t?.name==="@keepur/hive"&&typeof t.hiveApi=="string")return t.hiveApi}catch{continue}return null}var m0,ah,ka,ch=j(()=>{"use strict";O();m0=k("api-version");ah=g0();ah||m0.warn("Could not read hiveApi from package.json; falling back to 1.0.0");ka=ah??"1.0.0"});var hh={};Ue(hh,{isHiveApiCompatible:()=>dh,loadPlugins:()=>ba,normalizeManifest:()=>uh,registerPluginCommands:()=>w0,rescanPluginBrokenServers:()=>_a,resolvePluginServerPath:()=>Ks});import{readFileSync as y0,existsSync as wr}from"node:fs";import{resolve as ut,join as yr}from"node:path";function Ks(r,e,t){let s=e.replace(/\.ts$/,".js"),n=e.replace(/\.ts$/,".min.js"),i=[];t.distDir&&i.push(ut(t.distDir,`plugins/${r}/${s}`)),i.push(ut(t.hiveHome,"plugins","node_modules",r,"dist",n),ut(t.hiveHome,"plugins","node_modules",r,"dist",s),ut(t.hiveHome,"plugins",r,"dist",n),ut(t.hiveHome,"plugins",r,"dist",s));for(let o of i)if(wr(o))return{path:o};return{reason:"no compiled entry found (expected one of .min.js or .js under dist/)",pathsChecked:i}}function ba(r,e,t){let s=[];for(let n of r){let i=ut(e,"plugins","node_modules",n),o=ut(e,"plugins",n),a=yr(i,"plugin.yaml"),l=yr(o,"plugin.yaml"),c;if(wr(a))c=i;else if(wr(l))c=o;else{ht.warn("Plugin manifest not found, skipping",{plugin:n,tried:[a,l]});continue}let d=yr(c,"plugin.yaml"),u=(0,lh.parse)(y0(d,"utf-8")),h=uh(u);if(h.hiveApi&&!dh(h.hiveApi,ka)){ht.warn("Plugin declares incompatible hiveApi range, skipping",{plugin:n,requires:h.hiveApi,running:ka});continue}let m={};for(let[f,y]of Object.entries(h.mcpServers)){let w=Ks(n,y.entry,{hiveHome:e,distDir:t?.distDir});"reason"in w&&(m[f]=w,ht.error("Plugin MCP server entry not resolvable",{plugin:n,server:f,entry:y.entry,reason:w.reason,pathsChecked:w.pathsChecked}))}for(let f of h.agentSeeds){let y=yr(c,"agent-seeds",f);wr(y)||ht.warn("Plugin agent seed not found",{plugin:n,seed:f,path:y})}s.push({name:n,dir:c,manifest:h,brokenServers:m});let g=Object.keys(m);ht.info("Plugin loaded",{plugin:n,mcpServers:Object.keys(h.mcpServers),seeds:h.agentSeeds,...g.length?{brokenServers:g}:{}})}return s}function _a(r,e,t){let s={},n={};for(let i of r){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)):(n[i.name]??=[]).push(a)}}return{rescued:s,stillBroken:n}}function dh(r,e){let t=r.trim();if(t===e)return!0;if(t.startsWith("^")){let s=t.slice(1).split(".").map(Number),n=e.split(".").map(Number);return!(s.length<1||n.length<1||s[0]!==n[0]||(n[1]??0)<(s[1]??0)||(n[1]??0)===(s[1]??0)&&(n[2]??0)<(s[2]??0))}return ht.warn("Unrecognized hiveApi range syntax, accepting",{range:r}),!0}function uh(r){return{name:r.name??"",description:r.description??"",hiveApi:r.hiveApi??r["hive-api"]??void 0,mcpServers:Object.fromEntries(Object.entries(r["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:r["agent-seeds"]??r["agents-templates"]??[],registerCommands:r["register-commands"]??void 0}}async function w0(r,e){for(let t of r)if(t.manifest.registerCommands)try{let n=await import(ut(t.dir,"dist",t.manifest.registerCommands));typeof n.registerCommands=="function"&&(n.registerCommands(e),ht.info("Plugin commands registered",{plugin:t.name}))}catch(s){ht.warn("Failed to load plugin commands",{plugin:t.name,error:String(s)})}}var lh,ht,Sr=j(()=>{"use strict";lh=Ce(pa(),1);O();ch();ht=k("plugin-loader")});import{readFileSync as S0,writeFileSync as k0}from"node:fs";function b0(r){let e=r.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)throw new Error("No YAML frontmatter found");let t=e[1],s=e[2],n={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")n.name=vt(d);else if(c==="description")n.description=vt(d);else if(c==="workflow")n.workflow=vt(d);else if(c==="agents"){let u=d.match(/^\[([^\]]*)\]$/);if(u)n.agents=u[1].split(",").map(h=>vt(h.trim())).filter(h=>h.length>0);else if(d==="")for(n.agents=[];o+1<i.length&&i[o+1].match(/^\s+-\s+/);){o++;let h=i[o].replace(/^\s+-\s+/,"").trim();n.agents.push(vt(h))}else n.agents=[vt(d)]}else if(c==="origin")for(n.origin=fh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;else if(c==="author")for(n.author=fh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;o++}return{frontmatter:n,body:s}}function fh(r,e){let t={},s=e+1;for(;s<r.length&&r[s].match(/^\s+\S/);){let n=r[s].match(/^\s+([\w][\w-]*):\s*(.*)/);if(n){let i=n[2].trim();i==="true"?t[n[1]]=!0:i==="false"?t[n[1]]=!1:t[n[1]]=vt(i)}s++}return t}function vt(r){return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):r}function _0(r,e){let t=[];t.push(`name: ${kr(r.name)}`),t.push(`description: ${kr(r.description)}`);let s=r.agents.join(", ");return t.push(`agents: [${s}]`),r.workflow&&t.push(`workflow: ${kr(r.workflow)}`),r.origin&&(t.push("origin:"),ph(t,r.origin)),r.author&&(t.push("author:"),ph(t,r.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=ur(e),s=Vt(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=ur(e),s=Vt(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())}}};Au.Parser=ua});var Mu=T(js=>{"use strict";var Eu=Xo(),RS=Ms(),qs=Ps(),BS=Ji(),US=U(),qS=da(),Nu=ha();function xu(r){let e=r.prettyErrors!==!1;return{lineCounter:r.lineCounter||e&&new qS.LineCounter||null,prettyErrors:e}}function jS(r,e={}){let{lineCounter:t,prettyErrors:s}=xu(e),n=new Nu.Parser(t?.addNewLine),i=new Eu.Composer(e),o=Array.from(i.compose(n.parse(r)));if(s&&t)for(let a of o)a.errors.forEach(qs.prettifyError(r,t)),a.warnings.forEach(qs.prettifyError(r,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Ou(r,e={}){let{lineCounter:t,prettyErrors:s}=xu(e),n=new Nu.Parser(t?.addNewLine),i=new Eu.Composer(e),o=null;for(let a of i.compose(n.parse(r),!0,r.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new qs.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(qs.prettifyError(r,t)),o.warnings.forEach(qs.prettifyError(r,t))),o}function FS(r,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);let n=Ou(r,t);if(!n)return null;if(n.warnings.forEach(i=>BS.warn(n.options.logLevel,i)),n.errors.length>0){if(n.options.logLevel!=="silent")throw n.errors[0];n.errors=[]}return n.toJS(Object.assign({reviver:s},t))}function KS(r,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 n=Math.round(t);t=n<1?void 0:n>8?{indent:8}:{indent:n}}if(r===void 0){let{keepUndefined:n}=t??e??{};if(!n)return}return US.isDocument(r)&&!s?r.toString(t):new RS.Document(r,s,t).toString(t)}js.parse=FS;js.parseAllDocuments=jS;js.parseDocument=Ou;js.stringify=KS});var pa=T(F=>{"use strict";var HS=Xo(),WS=Ms(),GS=Mo(),fa=Ps(),VS=ms(),lt=U(),YS=rt(),JS=Z(),zS=ot(),QS=at(),XS=lr(),ZS=ca(),e0=da(),t0=ha(),hr=Mu(),Du=us();F.Composer=HS.Composer;F.Document=WS.Document;F.Schema=GS.Schema;F.YAMLError=fa.YAMLError;F.YAMLParseError=fa.YAMLParseError;F.YAMLWarning=fa.YAMLWarning;F.Alias=VS.Alias;F.isAlias=lt.isAlias;F.isCollection=lt.isCollection;F.isDocument=lt.isDocument;F.isMap=lt.isMap;F.isNode=lt.isNode;F.isPair=lt.isPair;F.isScalar=lt.isScalar;F.isSeq=lt.isSeq;F.Pair=YS.Pair;F.Scalar=JS.Scalar;F.YAMLMap=zS.YAMLMap;F.YAMLSeq=QS.YAMLSeq;F.CST=XS;F.Lexer=ZS.Lexer;F.LineCounter=e0.LineCounter;F.Parser=t0.Parser;F.parse=hr.parse;F.parseAllDocuments=hr.parseAllDocuments;F.parseDocument=hr.parseDocument;F.stringify=hr.stringify;F.visit=Du.visit;F.visitAsync=Du.visitAsync});function Lu(r={},e){let t={};for(let s of Object.keys(Yt)){let n=r[s]??Yt[s];t[s]=n&&(e?.[s]??!0)}return t}var Yt,ma=j(()=>{"use strict";Yt={externalComms:!0,codeTask:!1,codeAccess:!1}});import{execFileSync as s0}from"node:child_process";function Jt(r,e){if(process.platform!=="darwin")return"";try{return s0("security",["find-generic-password","-s",`hive/${r}/${e}`,"-w"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}var fr=j(()=>{"use strict"});import{readFileSync as n0,existsSync as Bu,readdirSync as r0,statSync as i0}from"node:fs";import{resolve as ga}from"node:path";import{randomUUID as ya}from"node:crypto";function Pu(r){let e=process.env[r]||qu(r);if(!e)throw new Error(`Missing required env var: ${r}`);return e}function b(r,e){return process.env[r]||qu(r)||e}function a0(r){if(r?.length)return r.map(t=>ga(t.replace(/^~/,process.env.HOME??"/tmp")));let e=ga(cs,"plugins/claude-code");return Bu(e)?r0(e).map(t=>ga(e,t)).filter(t=>i0(t).isDirectory()):[]}var Ru,Uu,o0,$u,A,pI,Fs,qu,dt,_t,p,Ne=j(()=>{"use strict";Ru=Ce(Gc(),1),Uu=Ce(pa(),1);ma();fr();ls();o0=Tc(z);Ru.default.config({path:o0});$u=vc(z),A={};Bu($u)&&(A=(0,Uu.parse)(n0($u,"utf-8"))??{});pI=process.env.HOME??"/tmp",Fs=A.instance?.id??"hive",qu=r=>Jt(Fs,r),dt=A.instance?.portBase??3100,_t=A.instance?.ports??{},p={instance:{id:Fs,portBase:dt},business:{name:A.business?.name??b("BUSINESS_NAME",""),description:A.business?.description??"",location:A.business?.location??"",ownerName:A.business?.owner?.name??"",ownerRole:A.business?.owner?.role??""},slack:{appToken:Pu("SLACK_APP_TOKEN"),botToken:Pu("SLACK_BOT_TOKEN"),mcpToken:b("SLACK_MCP_TOKEN",""),auditChannel:b("SLACK_AUDIT_CHANNEL",A.slack?.auditChannel??""),localMcpServer:!!(A.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(([r])=>r.startsWith("TASK_LEDGER_KEY_")).map(([r,e])=>[r.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",A.google?.account??""),client:b("GOG_CLIENT",A.google?.client??""),accounts:A.google?.accounts??{},sharedFolder:b("DRIVE_SHARED_FOLDER",A.google?.sharedFolder??A.googleWorkspace?.sharedFolder??"")},googleWorkspace:{account:b("GWS_ACCOUNT",A.googleWorkspace?.account??""),gwsPath:b("GWS_PATH",""),sharedFolder:b("GWS_SHARED_FOLDER",A.googleWorkspace?.sharedFolder??"")},quo:{apiKey:b("QUO_API_KEY",""),phoneNumberId:b("QUO_PHONE_NUMBER_ID",""),lines:A.quo?.lines??{}},sms:{lines:A.sms?.lines??[]},imessage:{enabled:A.imessage?.enabled??!1,slackChannel:A.imessage?.slackChannel??"imessage",hotWindowMs:A.imessage?.hotWindowMs??3e5,coldIntervalMs:A.imessage?.coldIntervalMs??3e5,hotIntervalMs:A.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",A.resend?.emailDomain??""),businessName:b("RESEND_BUSINESS_NAME",A.resend?.businessName??"")},plugins:A.plugins??[],skillRegistries:A.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??dt+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??dt)),10),authToken:b("BG_TASK_AUTH_TOKEN","")||ya()},slackInternal:{port:parseInt(b("SLACK_INTERNAL_PORT",String(_t.slackInternal??dt+6)),10),authToken:b("SLACK_INTERNAL_TOKEN","")||ya()},codeTask:{port:parseInt(b("CODE_TASK_PORT",String(_t.codeTask??dt+2)),10),authToken:b("CODE_TASK_AUTH_TOKEN","")||ya(),pluginDirs:a0(A.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??dt+3)),10)},beekeeper:{port:parseInt(b("BEEKEEPER_PORT",String(A.beekeeper?.port??8420)),10)},workflow:{enabled:b("WORKFLOW_ENABLED","false")==="true"},adminApi:{port:parseInt(b("ADMIN_API_PORT",String(_t.adminApi??dt+4)),10),token:b("ADMIN_API_TOKEN","")},voice:{enabled:!!A.voice?.provider,provider:A.voice?.provider??"",publicUrl:A.voice?.publicUrl??"",phoneNumberId:A.voice?.phoneNumberId??"",assistants:A.voice?.assistants??{},apiKey:b("VAPI_API_KEY",""),serverSecret:b("VAPI_SERVER_SECRET",""),port:parseInt(b("VOICE_PORT",String(_t.voice??dt+5)),10)},autonomy:{externalComms:A.autonomy?.externalComms??Yt.externalComms,codeTask:A.autonomy?.codeTask??Yt.codeTask,codeAccess:A.autonomy?.codeAccess??Yt.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 r=A.retention?.paths??{data:7,"agents/*/scratch":7,"agents/*/feeds":7,"agents/*/playwright":3,"agents/*/reports":0,logs:30},e={};for(let[n,i]of Object.entries(r)){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new Error(`Invalid retention.paths.${n}: must be a non-negative integer (got ${i})`);e[n]={days:i}}let t=Number(A.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(A.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:!!(A.retention?.enabled??!1),intervalMs:s,defaultDays:t,paths:e}})(),memory:{hotBudgetTokens:parseInt(b("MEMORY_HOT_BUDGET_TOKENS",String(A.memory?.hotBudgetTokens??3e3)),10),sweepIntervalHours:parseFloat(b("MEMORY_SWEEP_INTERVAL_HOURS",String(A.memory?.sweepIntervalHours??6))),hotThreshold:parseFloat(b("MEMORY_HOT_THRESHOLD",String(A.memory?.hotThreshold??.6))),warmThreshold:parseFloat(b("MEMORY_WARM_THRESHOLD",String(A.memory?.warmThreshold??.3))),recencyHalfLifeDays:parseFloat(b("MEMORY_RECENCY_HALF_LIFE_DAYS",String(A.memory?.recencyHalfLifeDays??7))),coldSummaryMinRecords:parseInt(b("MEMORY_COLD_SUMMARY_MIN",String(A.memory?.coldSummaryMinRecords??5)),10),coldRetentionDays:parseInt(b("MEMORY_COLD_RETENTION_DAYS",String(A.memory?.coldRetentionDays??90)),10),purgeRetentionDays:parseInt(b("MEMORY_PURGE_RETENTION_DAYS",String(A.memory?.purgeRetentionDays??7)),10),reflectionMinTurns:parseInt(b("MEMORY_REFLECTION_MIN_TURNS",String(A.memory?.reflectionMinTurns??3)),10)},codeIndex:{enabled:A.codeIndex?.enabled===!0||process.env.CODE_INDEX_ENABLED==="true",scoreThreshold:parseFloat(b("CODE_INDEX_SCORE_THRESHOLD",String(A.codeIndex?.scoreThreshold??.65))),prefetchLimit:parseInt(b("CODE_INDEX_PREFETCH_LIMIT",String(A.codeIndex?.prefetchLimit??8)),10),sessionKnowledge:{enabled:(A.codeIndex?.sessionKnowledge?.enabled??!0)&&process.env.CODE_INDEX_SESSION_KNOWLEDGE!=="false"},repos:A.codeIndex?.repos??{}},events:{retentionDays:parseInt(b("EVENT_RETENTION_DAYS",String(A.events?.retentionDays??30)),10)},activity:{enabled:(A.activity?.enabled??!0)&&process.env.ACTIVITY_LOG_ENABLED!=="false",bufferSize:parseInt(b("ACTIVITY_BUFFER_SIZE",String(A.activity?.bufferSize??200)),10),flushIntervalMs:parseInt(b("ACTIVITY_FLUSH_INTERVAL_MS",String(A.activity?.flushIntervalMs??3e4)),10),retentionDays:parseInt(b("ACTIVITY_RETENTION_DAYS",String(A.activity?.retentionDays??90)),10)},autoDream:{enabled:A.autoDream?.enabled??!0,idleThresholdMinutes:parseInt(b("AUTODREAM_IDLE_THRESHOLD_MINUTES",String(A.autoDream?.idleThresholdMinutes??30)),10),cooldownMinutes:parseInt(b("AUTODREAM_COOLDOWN_MINUTES",String(A.autoDream?.cooldownMinutes??60)),10),similarityThreshold:parseFloat(b("AUTODREAM_SIMILARITY_THRESHOLD",String(A.autoDream?.similarityThreshold??.85))),patternMinCount:parseInt(b("AUTODREAM_PATTERN_MIN_COUNT",String(A.autoDream?.patternMinCount??3)),10),maxClustersPerRun:parseInt(b("AUTODREAM_MAX_CLUSTERS",String(A.autoDream?.maxClustersPerRun??20)),10),maxContradictionPairsPerRun:parseInt(b("AUTODREAM_MAX_CONTRADICTIONS",String(A.autoDream?.maxContradictionPairsPerRun??30)),10),maxPromotionsPerRun:parseInt(b("AUTODREAM_MAX_PROMOTIONS",String(A.autoDream?.maxPromotionsPerRun??10)),10),maxBudgetUsd:parseFloat(b("AUTODREAM_MAX_BUDGET_USD",String(A.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 Ku(r){wa.has(r.id)&&Fu.warn("Archetype already registered \u2014 overwriting",{id:r.id}),wa.set(r.id,r),Fu.info("Registered archetype",{id:r.id})}function pr(r){return wa.get(r)}var Fu,wa,mr=j(()=>{"use strict";O();Fu=k("archetypes"),wa=new Map});import{readFileSync as m0}from"node:fs";import{resolve as oh}from"node:path";function y0(){let r=[oh(import.meta.dirname,"..","..","package.json"),oh(import.meta.dirname,"..","package.json")];for(let e of r)try{let t=JSON.parse(m0(e,"utf-8"));if(t?.name==="@keepur/hive"&&typeof t.hiveApi=="string")return t.hiveApi}catch{continue}return null}var g0,ah,ka,ch=j(()=>{"use strict";O();g0=k("api-version");ah=y0();ah||g0.warn("Could not read hiveApi from package.json; falling back to 1.0.0");ka=ah??"1.0.0"});var hh={};Ue(hh,{isHiveApiCompatible:()=>dh,loadPlugins:()=>ba,normalizeManifest:()=>uh,registerPluginCommands:()=>S0,rescanPluginBrokenServers:()=>_a,resolvePluginServerPath:()=>Ks});import{readFileSync as w0,existsSync as wr}from"node:fs";import{resolve as ut,join as yr}from"node:path";function Ks(r,e,t){let s=e.replace(/\.ts$/,".js"),n=e.replace(/\.ts$/,".min.js"),i=[];t.distDir&&i.push(ut(t.distDir,`plugins/${r}/${s}`)),i.push(ut(t.hiveHome,"plugins","node_modules",r,"dist",n),ut(t.hiveHome,"plugins","node_modules",r,"dist",s),ut(t.hiveHome,"plugins",r,"dist",n),ut(t.hiveHome,"plugins",r,"dist",s));for(let o of i)if(wr(o))return{path:o};return{reason:"no compiled entry found (expected one of .min.js or .js under dist/)",pathsChecked:i}}function ba(r,e,t){let s=[];for(let n of r){let i=ut(e,"plugins","node_modules",n),o=ut(e,"plugins",n),a=yr(i,"plugin.yaml"),l=yr(o,"plugin.yaml"),c;if(wr(a))c=i;else if(wr(l))c=o;else{ht.warn("Plugin manifest not found, skipping",{plugin:n,tried:[a,l]});continue}let d=yr(c,"plugin.yaml"),u=(0,lh.parse)(w0(d,"utf-8")),h=uh(u);if(h.hiveApi&&!dh(h.hiveApi,ka)){ht.warn("Plugin declares incompatible hiveApi range, skipping",{plugin:n,requires:h.hiveApi,running:ka});continue}let m={};for(let[f,y]of Object.entries(h.mcpServers)){let w=Ks(n,y.entry,{hiveHome:e,distDir:t?.distDir});"reason"in w&&(m[f]=w,ht.error("Plugin MCP server entry not resolvable",{plugin:n,server:f,entry:y.entry,reason:w.reason,pathsChecked:w.pathsChecked}))}for(let f of h.agentSeeds){let y=yr(c,"agent-seeds",f);wr(y)||ht.warn("Plugin agent seed not found",{plugin:n,seed:f,path:y})}s.push({name:n,dir:c,manifest:h,brokenServers:m});let g=Object.keys(m);ht.info("Plugin loaded",{plugin:n,mcpServers:Object.keys(h.mcpServers),seeds:h.agentSeeds,...g.length?{brokenServers:g}:{}})}return s}function _a(r,e,t){let s={},n={};for(let i of r){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)):(n[i.name]??=[]).push(a)}}return{rescued:s,stillBroken:n}}function dh(r,e){let t=r.trim();if(t===e)return!0;if(t.startsWith("^")){let s=t.slice(1).split(".").map(Number),n=e.split(".").map(Number);return!(s.length<1||n.length<1||s[0]!==n[0]||(n[1]??0)<(s[1]??0)||(n[1]??0)===(s[1]??0)&&(n[2]??0)<(s[2]??0))}return ht.warn("Unrecognized hiveApi range syntax, accepting",{range:r}),!0}function uh(r){return{name:r.name??"",description:r.description??"",hiveApi:r.hiveApi??r["hive-api"]??void 0,mcpServers:Object.fromEntries(Object.entries(r["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:r["agent-seeds"]??r["agents-templates"]??[],registerCommands:r["register-commands"]??void 0}}async function S0(r,e){for(let t of r)if(t.manifest.registerCommands)try{let n=await import(ut(t.dir,"dist",t.manifest.registerCommands));typeof n.registerCommands=="function"&&(n.registerCommands(e),ht.info("Plugin commands registered",{plugin:t.name}))}catch(s){ht.warn("Failed to load plugin commands",{plugin:t.name,error:String(s)})}}var lh,ht,Sr=j(()=>{"use strict";lh=Ce(pa(),1);O();ch();ht=k("plugin-loader")});import{readFileSync as k0,writeFileSync as b0}from"node:fs";function _0(r){let e=r.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)throw new Error("No YAML frontmatter found");let t=e[1],s=e[2],n={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")n.name=vt(d);else if(c==="description")n.description=vt(d);else if(c==="workflow")n.workflow=vt(d);else if(c==="agents"){let u=d.match(/^\[([^\]]*)\]$/);if(u)n.agents=u[1].split(",").map(h=>vt(h.trim())).filter(h=>h.length>0);else if(d==="")for(n.agents=[];o+1<i.length&&i[o+1].match(/^\s+-\s+/);){o++;let h=i[o].replace(/^\s+-\s+/,"").trim();n.agents.push(vt(h))}else n.agents=[vt(d)]}else if(c==="origin")for(n.origin=fh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;else if(c==="author")for(n.author=fh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;o++}return{frontmatter:n,body:s}}function fh(r,e){let t={},s=e+1;for(;s<r.length&&r[s].match(/^\s+\S/);){let n=r[s].match(/^\s+([\w][\w-]*):\s*(.*)/);if(n){let i=n[2].trim();i==="true"?t[n[1]]=!0:i==="false"?t[n[1]]=!1:t[n[1]]=vt(i)}s++}return t}function vt(r){return r.startsWith('"')&&r.endsWith('"')||r.startsWith("'")&&r.endsWith("'")?r.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):r}function v0(r,e){let t=[];t.push(`name: ${kr(r.name)}`),t.push(`description: ${kr(r.description)}`);let s=r.agents.join(", ");return t.push(`agents: [${s}]`),r.workflow&&t.push(`workflow: ${kr(r.workflow)}`),r.origin&&(t.push("origin:"),ph(t,r.origin)),r.author&&(t.push("author:"),ph(t,r.author)),`---
145
145
  ${t.join(`
146
146
  `)}
147
147
  ---
148
- ${e}`}function ph(r,e){for(let[t,s]of Object.entries(e))s!==void 0&&r.push(` ${t}: ${kr(String(s))}`)}function kr(r){return r.includes(":")||r.includes("#")||r.includes('"')?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function mh(r){let e=S0(r,"utf-8");return b0(e)}function gh(r,e,t){k0(r,_0(e,t),"utf-8")}function yh(r){let e=r.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);if(!e)return r;let t=e[1],s=e[2],n=e[3],i=e[4],o=s.split(`
148
+ ${e}`}function ph(r,e){for(let[t,s]of Object.entries(e))s!==void 0&&r.push(` ${t}: ${kr(String(s))}`)}function kr(r){return r.includes(":")||r.includes("#")||r.includes('"')?`"${r.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:r}function mh(r){let e=k0(r,"utf-8");return _0(e)}function gh(r,e,t){b0(r,v0(e,t),"utf-8")}function yh(r){let e=r.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);if(!e)return r;let t=e[1],s=e[2],n=e[3],i=e[4],o=s.split(`
149
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
- `)+n+i}var va=j(()=>{"use strict"});import{createHash as v0}from"node:crypto";import{readdirSync as T0,readFileSync as I0,statSync as C0}from"node:fs";import{join as wh}from"node:path";function Sh(r){let e=kh(r).sort(),t=v0("sha256");for(let s=0;s<e.length;s++){s>0&&t.update("\0");let n=wh(r,e[s]),i=I0(n,"utf-8");e[s]==="SKILL.md"?t.update(yh(i)):t.update(i)}return t.digest("hex")}function kh(r,e=""){let t=T0(r),s=[];for(let n of t){let i=wh(r,n),o=e?`${e}/${n}`:n;C0(i).isDirectory()?s.push(...kh(i,o)):s.push(o)}return s}var bh=j(()=>{"use strict";va()});import{readdirSync as Ia,readFileSync as A0,statSync as Ca,existsSync as Tt}from"node:fs";import{join as xe,relative as E0,resolve as N0}from"node:path";function Aa(r,e,t){let s=new Map,n=[],i=new Map;for(let o of t??[]){let a=xe(o,"skills");if(!Tt(a))continue;let l=o.split("/").pop()??"seed";Ta(a,`seed:${l}`,i,s,n,!1)}for(let o of e??[]){let a=xe(o.dir,"skills");Tt(a)&&Ta(a,o.name,i,s,n,!1)}if(Tt(r)?Ta(r,"customer",i,s,n,!0):be.debug("No customer skills directory found",{path:r}),n.length>0){for(let o of[...s.keys()])s.get(o).push(...n);s.set("__universal__",n)}return x0=O0(i,r),be.info("Skill index loaded",{workflows:i.size,agents:s.size-(s.has("__universal__")?1:0)}),s}function _h(r,e,t){for(let[s,n]of e){let i=n.filter(o=>o.path!==r);i.length!==n.length&&(i.length===0?e.delete(s):e.set(s,i))}for(let s=t.length-1;s>=0;s--)t[s].path===r&&t.splice(s,1)}function Ta(r,e,t,s,n,i){let o;try{o=Ia(r).filter(a=>{try{return Ca(xe(r,a)).isDirectory()}catch{return!1}})}catch(a){be.warn("Failed to read skills directory",{source:e,path:r,error:String(a)});return}for(let a of o){let l=xe(r,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}}),_h(d.path,s,n),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}}),_h(d.path,s,n),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,m=!1,g;try{g=Ia(c).filter(f=>{try{return Ca(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 g){let y=xe(c,f,"SKILL.md");if(!Tt(y))continue;let w=M0(A0(y,"utf-8"));for(let S of w)S==="all"?m=!0:h.add(S)}if(m)n.push(u),be.debug("Workflow registered as universal",{source:e,workflow:a,skills:g.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:g.length})}}}function vh(r,e){let t=r.get(e)??[],s=r.get("__universal__")??[];if(t.length>0&&s.length>0){let n=new Set(t.map(o=>o.path)),i=s.filter(o=>!n.has(o.path));return[...t,...i]}return t.length===0&&s.length>0?[...s]:t}function O0(r,e){let t=new Set,s=N0(e,"..");for(let[n,i]of r){if(i.source!=="customer")continue;let o=xe(i.path,"skills");if(!Tt(o))continue;let a;try{a=Ia(o).filter(l=>{try{return Ca(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}=mh(d);if(!u.origin?.["base-content-hash"])continue;let m=Sh(c);if(m!==u.origin["base-content-hash"]&&(t.add(c),be.warn("Registry-installed skill has been modified",{workflow:n,skill:l,source:u.origin.source,baseHash:u.origin["base-content-hash"],currentHash:m}),!u.origin.modified)){u.origin.modified=!0;try{gh(d,u,h),Dc(s,[E0(s,d)],`detect-modified: ${l} content hash changed`)}catch(g){be.error("Failed to persist modified flag to disk",{path:d,error:String(g)})}}}catch{}}}return t}function M0(r){let e=r.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 n=t.match(/^agents:\s*\[([^\]]*)\]/m);return n?n[1].split(",").map(i=>i.trim()).filter(Boolean):[]}var be,x0,Ea=j(()=>{"use strict";O();bh();va();Ei();be=k("skill-loader"),x0=new Set});function Na(r,e){let t=`- ${r}: ${e.description}`,s=[];return e.usage&&s.push(`Use for: ${e.usage}.`),e.notFor&&s.push(`Not for: ${e.notFor}.`),s.length>0&&(t+=`
152
- \u2192 ${s.join(" ")}`),t}var Hs,xa=j(()=>{"use strict";Hs={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:"CRM deal/company data \u2014 use a CRM plugin's tools instead"},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"},schedule:{description:"Self-service schedule management \u2014 view, add, update, remove your schedules",usage:"Managing your recurring or one-time scheduled tasks"},"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"},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 Th(r=[]){let e=[],t=[],s=[];for(let i of Object.keys(Hs)){if(L0.has(i)){e.push(i);continue}let o=D0[i];!o||o()?e.push(i):t.push(i)}let n=p.instance?.id??"unknown";for(let i of r)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(m=>!!process.env[m]),h=d.every(m=>!!process.env[m]||!!Jt(n,m));u&&h?e.push(o):t.push(o)}return{instanceId:p.instance?.id??"unknown",servers:{configured:e,unconfigured:t,broken:s}}}var D0,L0,Ih=j(()=>{"use strict";Ne();fr();xa();D0={google:()=>Object.keys(p.google?.accounts??{}).length>0||!!p.google?.account,resend:()=>!!p.resend?.apiKey,"brave-search":()=>!!p.brave?.apiKey,linear:()=>!!p.linear?.apiKey,clickup:()=>!!p.clickup?.apiToken,"github-issues":()=>!!p.github?.repo,quo:()=>!!p.quo?.apiKey,recall:()=>!!p.recall?.apiKey,"code-task":()=>!0,"code-search":()=>!!p.codeIndex?.enabled,browser:()=>!!p.browser?.cdpEndpoint,tasks:()=>(p.taskLedger?.apiUrl??"")!=="http://localhost:3002"},L0=new Set(["memory","slack","contacts","callback","background","schedule","event-bus","conversation-search","keychain","admin"])});var Eh={};Ue(Eh,{AgentRunner:()=>Gs,DIST_DIR:()=>Ke,ensurePluginNodeModulesLink:()=>Ah});import{query as P0}from"@anthropic-ai/claude-agent-sdk";import{resolve as Oe}from"node:path";import{existsSync as Ws,statSync as $0,mkdirSync as Ch,symlinkSync as R0,lstatSync as B0}from"node:fs";import{createRequire as U0}from"node:module";import{readFile as q0}from"node:fs/promises";function j0(r){return JSON.stringify(Th(r))}function F0(r){let e=r;for(let t=0;t<15;t++){let s=Oe(e,"node_modules"),n=Oe(e,"package.json");if(Ws(s)&&Ws(n))return s;let i=Oe(e,"..");if(i===e)break;e=i}return null}function Ah(r){if(!Oa)return;let e=Oe(r,"node_modules");try{B0(e);return}catch{}try{R0(Oa,e,"dir"),R.info("Linked plugin node_modules to engine deps",{pluginDir:r,target:Oa})}catch(t){R.warn("Failed to link plugin node_modules",{pluginDir:r,error:String(t)})}}function Y(r){let e=K0[r];if(e){let t=Oe(Ke,"mcp",e);if(Ws(t))return t}return Oe(Ke,r)}var R,Ke,Oa,K0,Gs,Ma=j(()=>{"use strict";mr();O();Ne();fr();ls();Sr();Ea();xa();Ih();R=k("agent-runner");Ke=Ws(Oe(import.meta.dirname,"mcp"))?import.meta.dirname:Oe(import.meta.dirname,"..");Oa=F0(Ke);K0={"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"};Gs=class r{static registryRef;agentConfig;memoryManager;plugins;skillIndex;activeQuery=null;eventSubscribersJson;prefetcher;_archetypeDef=void 0;constructor(e,t,s=[],n=new Map,i="{}",o){this.agentConfig=e,this.memoryManager=t,this.plugins=s,this.skillIndex=n,this.eventSubscribersJson=i,this.prefetcher=o}async buildSystemPrompt(e,t){let s=[];this.agentConfig.soul&&s.push(this.agentConfig.soul);let n=this.getArchetypeDef();if(n&&this.agentConfig.archetypeConfig)try{let u=n.systemPromptCard({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});u&&s.push(u)}catch(u){R.error("Archetype systemPromptCard threw \u2014 omitting card",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(u)})}s.push(this.agentConfig.systemPrompt);let i=await this.memoryManager.read("shared/constitution.md");i&&s.push(i);let o=e.filter(u=>!r.INFRASTRUCTURE_SERVERS.has(u));if(o.length>0){let u=o.map(h=>Na(h,this.getServerCatalogEntry(h)));s.push(`## Your tools
150
+ `)+n+i}var va=j(()=>{"use strict"});import{createHash as T0}from"node:crypto";import{readdirSync as I0,readFileSync as C0,statSync as A0}from"node:fs";import{join as wh}from"node:path";function Sh(r){let e=kh(r).sort(),t=T0("sha256");for(let s=0;s<e.length;s++){s>0&&t.update("\0");let n=wh(r,e[s]),i=C0(n,"utf-8");e[s]==="SKILL.md"?t.update(yh(i)):t.update(i)}return t.digest("hex")}function kh(r,e=""){let t=I0(r),s=[];for(let n of t){let i=wh(r,n),o=e?`${e}/${n}`:n;A0(i).isDirectory()?s.push(...kh(i,o)):s.push(o)}return s}var bh=j(()=>{"use strict";va()});import{readdirSync as Ia,readFileSync as E0,statSync as Ca,existsSync as Tt}from"node:fs";import{join as xe,relative as N0,resolve as x0}from"node:path";function Aa(r,e,t){let s=new Map,n=[],i=new Map;for(let o of t??[]){let a=xe(o,"skills");if(!Tt(a))continue;let l=o.split("/").pop()??"seed";Ta(a,`seed:${l}`,i,s,n,!1)}for(let o of e??[]){let a=xe(o.dir,"skills");Tt(a)&&Ta(a,o.name,i,s,n,!1)}if(Tt(r)?Ta(r,"customer",i,s,n,!0):be.debug("No customer skills directory found",{path:r}),n.length>0){for(let o of[...s.keys()])s.get(o).push(...n);s.set("__universal__",n)}return O0=M0(i,r),be.info("Skill index loaded",{workflows:i.size,agents:s.size-(s.has("__universal__")?1:0)}),s}function _h(r,e,t){for(let[s,n]of e){let i=n.filter(o=>o.path!==r);i.length!==n.length&&(i.length===0?e.delete(s):e.set(s,i))}for(let s=t.length-1;s>=0;s--)t[s].path===r&&t.splice(s,1)}function Ta(r,e,t,s,n,i){let o;try{o=Ia(r).filter(a=>{try{return Ca(xe(r,a)).isDirectory()}catch{return!1}})}catch(a){be.warn("Failed to read skills directory",{source:e,path:r,error:String(a)});return}for(let a of o){let l=xe(r,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}}),_h(d.path,s,n),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}}),_h(d.path,s,n),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,m=!1,g;try{g=Ia(c).filter(f=>{try{return Ca(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 g){let y=xe(c,f,"SKILL.md");if(!Tt(y))continue;let w=D0(E0(y,"utf-8"));for(let S of w)S==="all"?m=!0:h.add(S)}if(m)n.push(u),be.debug("Workflow registered as universal",{source:e,workflow:a,skills:g.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:g.length})}}}function vh(r,e){let t=r.get(e)??[],s=r.get("__universal__")??[];if(t.length>0&&s.length>0){let n=new Set(t.map(o=>o.path)),i=s.filter(o=>!n.has(o.path));return[...t,...i]}return t.length===0&&s.length>0?[...s]:t}function M0(r,e){let t=new Set,s=x0(e,"..");for(let[n,i]of r){if(i.source!=="customer")continue;let o=xe(i.path,"skills");if(!Tt(o))continue;let a;try{a=Ia(o).filter(l=>{try{return Ca(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}=mh(d);if(!u.origin?.["base-content-hash"])continue;let m=Sh(c);if(m!==u.origin["base-content-hash"]&&(t.add(c),be.warn("Registry-installed skill has been modified",{workflow:n,skill:l,source:u.origin.source,baseHash:u.origin["base-content-hash"],currentHash:m}),!u.origin.modified)){u.origin.modified=!0;try{gh(d,u,h),Dc(s,[N0(s,d)],`detect-modified: ${l} content hash changed`)}catch(g){be.error("Failed to persist modified flag to disk",{path:d,error:String(g)})}}}catch{}}}return t}function D0(r){let e=r.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 n=t.match(/^agents:\s*\[([^\]]*)\]/m);return n?n[1].split(",").map(i=>i.trim()).filter(Boolean):[]}var be,O0,Ea=j(()=>{"use strict";O();bh();va();Ei();be=k("skill-loader"),O0=new Set});function Na(r,e){let t=`- ${r}: ${e.description}`,s=[];return e.usage&&s.push(`Use for: ${e.usage}.`),e.notFor&&s.push(`Not for: ${e.notFor}.`),s.length>0&&(t+=`
152
+ \u2192 ${s.join(" ")}`),t}var Hs,xa=j(()=>{"use strict";Hs={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:"CRM deal/company data \u2014 use a CRM plugin's tools instead"},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"},schedule:{description:"Self-service schedule management \u2014 view, add, update, remove your schedules",usage:"Managing your recurring or one-time scheduled tasks"},"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"},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 Th(r=[]){let e=[],t=[],s=[];for(let i of Object.keys(Hs)){if(P0.has(i)){e.push(i);continue}let o=L0[i];!o||o()?e.push(i):t.push(i)}let n=p.instance?.id??"unknown";for(let i of r)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(m=>!!process.env[m]),h=d.every(m=>!!process.env[m]||!!Jt(n,m));u&&h?e.push(o):t.push(o)}return{instanceId:p.instance?.id??"unknown",servers:{configured:e,unconfigured:t,broken:s}}}var L0,P0,Ih=j(()=>{"use strict";Ne();fr();xa();L0={google:()=>Object.keys(p.google?.accounts??{}).length>0||!!p.google?.account,resend:()=>!!p.resend?.apiKey,"brave-search":()=>!!p.brave?.apiKey,linear:()=>!!p.linear?.apiKey,clickup:()=>!!p.clickup?.apiToken,"github-issues":()=>!!p.github?.repo,quo:()=>!!p.quo?.apiKey,recall:()=>!!p.recall?.apiKey,"code-task":()=>!0,"code-search":()=>!!p.codeIndex?.enabled,browser:()=>!!p.browser?.cdpEndpoint,tasks:()=>(p.taskLedger?.apiUrl??"")!=="http://localhost:3002"},P0=new Set(["memory","slack","contacts","callback","background","schedule","event-bus","conversation-search","keychain","admin"])});var Eh={};Ue(Eh,{AgentRunner:()=>Gs,DIST_DIR:()=>Ke,ensurePluginNodeModulesLink:()=>Ah});import{query as $0}from"@anthropic-ai/claude-agent-sdk";import{resolve as Oe}from"node:path";import{existsSync as Ws,statSync as R0,mkdirSync as Ch,symlinkSync as B0,lstatSync as U0}from"node:fs";import{createRequire as q0}from"node:module";import{readFile as j0}from"node:fs/promises";function F0(r){return JSON.stringify(Th(r))}function K0(r){let e=r;for(let t=0;t<15;t++){let s=Oe(e,"node_modules"),n=Oe(e,"package.json");if(Ws(s)&&Ws(n))return s;let i=Oe(e,"..");if(i===e)break;e=i}return null}function Ah(r){if(!Oa)return;let e=Oe(r,"node_modules");try{U0(e);return}catch{}try{B0(Oa,e,"dir"),R.info("Linked plugin node_modules to engine deps",{pluginDir:r,target:Oa})}catch(t){R.warn("Failed to link plugin node_modules",{pluginDir:r,error:String(t)})}}function Y(r){let e=H0[r];if(e){let t=Oe(Ke,"mcp",e);if(Ws(t))return t}return Oe(Ke,r)}var R,Ke,Oa,H0,Gs,Ma=j(()=>{"use strict";mr();O();Ne();fr();ls();Sr();Ea();xa();Ih();R=k("agent-runner");Ke=Ws(Oe(import.meta.dirname,"mcp"))?import.meta.dirname:Oe(import.meta.dirname,"..");Oa=K0(Ke);H0={"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"};Gs=class r{static registryRef;agentConfig;memoryManager;plugins;skillIndex;activeQuery=null;eventSubscribersJson;prefetcher;_archetypeDef=void 0;constructor(e,t,s=[],n=new Map,i="{}",o){this.agentConfig=e,this.memoryManager=t,this.plugins=s,this.skillIndex=n,this.eventSubscribersJson=i,this.prefetcher=o}async buildSystemPrompt(e,t){let s=[];this.agentConfig.soul&&s.push(this.agentConfig.soul);let n=this.getArchetypeDef();if(n&&this.agentConfig.archetypeConfig)try{let u=n.systemPromptCard({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});u&&s.push(u)}catch(u){R.error("Archetype systemPromptCard threw \u2014 omitting card",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(u)})}s.push(this.agentConfig.systemPrompt);let i=await this.memoryManager.read("shared/constitution.md");i&&s.push(i);let o=e.filter(u=>!r.INFRASTRUCTURE_SERVERS.has(u));if(o.length>0){let u=o.map(h=>Na(h,this.getServerCatalogEntry(h)));s.push(`## Your tools
153
153
 
154
154
  Direct tools available to you:
155
155
  ${u.join(`
@@ -165,10 +165,10 @@ You have ${g.length} reference file(s) in your memory directory:
165
165
 
166
166
  ---
167
167
 
168
- `)}buildServerConfig(e,t){return this.buildAllServerConfigs(t)[e]}buildAllServerConfigs(e){let t={};if(p.slack.localMcpServer)t.slack={type:"stdio",command:"node",args:[Y("slack/slack-mcp-server.js")],env:{HIVE_INTERNAL_URL:`http://127.0.0.1:${p.slackInternal.port}`,HIVE_INTERNAL_TOKEN:p.slackInternal.authToken,HIVE_AGENT_ID:this.agentConfig.id}};else{let c=p.slack.mcpToken;c&&(t.slack={type:"http",url:"https://mcp.slack.com/mcp",headers:{Authorization:`Bearer ${c}`}})}let s=[{id:"self",backing:"mongo"}],n=this.getArchetypeDef();if(n&&this.agentConfig.archetypeConfig)try{let c=n.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:[Y("memory/memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,MEMORY_SCOPES_JSON:JSON.stringify(s)}},t["structured-memory"]={type:"stdio",command:"node",args:[Y("memory/structured-memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.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:[Y("keychain/keychain-mcp-server.js")],env:{KEYCHAIN_SERVICE:`hive/${p.instance.id}`}};let i=p.google.accounts[this.agentConfig.id]||p.google.account,o=p.google.client;if(t.google={type:"stdio",command:"node",args:[Y("google/google-mcp-server.js")],env:{...i?{GOG_ACCOUNT:i}:{},...o?{GOG_CLIENT:o}:{},DRIVE_SHARED_FOLDER:p.google.sharedFolder,INSTANCE_ID:p.instance.id,PATH:process.env.PATH??""}},p.quo.apiKey&&(t.quo={type:"stdio",command:"node",args:[Y("quo/quo-mcp-server.js")],env:{QUO_API_KEY:p.quo.apiKey,...p.quo.phoneNumberId?{QUO_PHONE_NUMBER_ID:p.quo.phoneNumberId}:{},QUO_LINES_JSON:JSON.stringify(p.quo.lines)}}),p.voice.enabled&&p.voice.apiKey){let c=Object.entries(p.voice.assistants).find(([d,u])=>u===this.agentConfig.id)?.[0]??"";t.voice={type:"stdio",command:"node",args:[Y("voice/voice-mcp-server.js")],env:{VAPI_API_KEY:p.voice.apiKey,VAPI_PHONE_NUMBER_ID:p.voice.phoneNumberId,VAPI_ASSISTANT_ID:c,AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name}}}t.contacts={type:"stdio",command:"node",args:[Y("contacts/contacts-mcp-server.js")],env:{MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName}};let a=p.taskLedger.agentKeys[this.agentConfig.id]??p.taskLedger.apiKey;if(a&&(t.tasks={type:"stdio",command:"node",args:[Y("tasks/task-mcp-server.js")],env:{TASK_LEDGER_API_URL:p.taskLedger.apiUrl,TASK_LEDGER_API_KEY:a}}),p.brave.apiKey&&(t["brave-search"]={type:"stdio",command:"node",args:[U0(import.meta.url).resolve("brave-search-mcp/dist/index.js")],env:{BRAVE_API_KEY:p.brave.apiKey}}),p.resend.apiKey){let c=this.agentConfig.name.toLowerCase(),d=p.resend.emailDomain,u=p.resend.businessName?` (${p.resend.businessName})`:"",h=d?`${this.agentConfig.name}${u} <${c}@${d}>`:p.resend.fromAddress;t.resend={type:"stdio",command:"node",args:[Y("resend/resend-mcp-server.js")],env:{RESEND_API_KEY:p.resend.apiKey,RESEND_FROM_ADDRESS:h,RESEND_DEFAULT_CC:p.resend.defaultCc,RESEND_DEFAULT_BCC:p.resend.defaultBcc}}}if(p.linear.apiKey){let c={LINEAR_API_KEY:p.linear.apiKey};p.linear.teamId&&(c.LINEAR_TEAM_ID=p.linear.teamId),t.linear={type:"stdio",command:"node",args:[Y("linear/linear-mcp-server.js")],env:c}}if(p.github.repo){let c={GITHUB_REPO:p.github.repo,PATH:process.env.PATH??""};p.github.token&&(c.GH_TOKEN=p.github.token),t["github-issues"]={type:"stdio",command:"node",args:[Y("github/github-issues-mcp-server.js")],env:c}}if(p.clickup.apiToken&&(t.clickup={type:"stdio",command:"node",args:[Y("clickup/clickup-mcp-server.js")],env:{CLICKUP_API_TOKEN:p.clickup.apiToken}}),p.recall.apiKey&&(t.recall={type:"stdio",command:"node",args:[Y("recall/recall-mcp-server.js")],env:{RECALL_API_KEY:p.recall.apiKey,RECALL_API_REGION:p.recall.region,RECALL_WEBHOOK_SECRET:p.recall.webhookSecret,MEETING_MONITOR_API:`http://127.0.0.1:${p.recall.monitorPort}`,MEETING_MONITOR_PUBLIC_URL:p.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??""}}),p.browser.cdpEndpoint){let c=Ec(this.agentConfig.id,z);Ch(c,{recursive:!0}),t.browser={type:"stdio",command:"npx",args:["@playwright/mcp@latest","--cdp-endpoint",p.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:[Y("background/background-task-mcp-server.js")],env:{BG_TASK_API:`http://127.0.0.1:${p.background.port}`,BG_AUTH_TOKEN:p.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:[Y("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:p.mongo.uri,MONGODB_DB:p.mongo.dbName}},t["code-task"]={type:"stdio",command:"node",args:[Y("code-task/code-task-mcp-server.js")],env:{CT_TASK_API:`http://127.0.0.1:${p.codeTask.port}`,CT_AUTH_TOKEN:p.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:[Y("search/conversation-search-mcp-server.js")],env:{...l,AGENT_ID:this.agentConfig.id,DEFAULT_AGENT:p.defaultAgent}},t["code-search"]={type:"stdio",command:"node",args:[Y("code-index/code-search-mcp-server.js")],env:{MONGODB_URI:p.mongo.uri,MONGODB_DB:p.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:z,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 m=h.path;Ah(c.dir);let g=p.taskLedger.agentKeys[this.agentConfig.id]??p.taskLedger.apiKey,f={AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,TASK_LEDGER_API_URL:p.taskLedger.apiUrl,...g?{TASK_LEDGER_API_KEY:g}:{},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]||Jt(p.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]=r.resolveAgentEnvPath(this.agentConfig,w);t[d]={type:"stdio",command:"node",args:[m],env:f}}return t["event-bus"]={type:"stdio",command:"node",args:[Y("events/event-bus-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}},r.registryRef||R.warn("registryRef not set \u2014 agents will get empty AGENT_IDS for team server"),t.team={type:"stdio",command:"node",args:[Y("team/team-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,AGENT_IDS:JSON.stringify(r.registryRef?.getAll().map(c=>c.id)??[])}},p.workflow.enabled&&(t.workflow={type:"stdio",command:"node",args:[Y("workflow/workflow-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}}),t.schedule={type:"stdio",command:"node",args:[Y("schedule/schedule-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName}},t.admin={type:"stdio",command:"node",args:[Y("admin/admin-mcp-server.js")],env:{MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,AGENT_ID:this.agentConfig.id,INSTANCE_CAPABILITIES:j0(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"),p.workflow.enabled&&s.add("workflow");for(let n of Object.keys(t))s.has(n)||delete t[n];if(!this.agentConfig.autonomy.externalComms)for(let n of["resend","quo"])t[n]&&(R.debug("Autonomy: externalComms disabled \u2014 removing server",{server:n,agent:this.agentConfig.id}),delete t[n]);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("."),n=e;for(let i of s){if(n==null||typeof n!="object")return"";n=n[i]}return n==null?"":String(n)}static INFRASTRUCTURE_SERVERS=new Set(["schedule","structured-memory","team"]);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={},n=new Set;this.agentConfig.autonomy.externalComms||(n.add("resend"),n.add("quo")),this.agentConfig.autonomy.codeTask||n.add("code-task"),this.agentConfig.autonomy.codeAccess||n.add("code-search");for(let i of t){if(n.has(i)){R.debug("Autonomy gate \u2014 skipping delegate server",{server:i,agent:this.agentConfig.id});continue}r.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(Hs[e])return Hs[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 n of e){if(n.includes("/")||n.includes("\\")||n===".."||n.startsWith(".")){R.warn("Invalid plugin name, skipping",{plugin:n,agent:this.agentConfig.id});continue}let i=Oe(s,n);if(!Ws(i)){R.warn("Plugin not found, skipping",{plugin:n,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(n=>n.path)}),t}buildNativeSkills(){return vh(this.skillIndex,this.agentConfig.id)}getArchetypeDef(){return this._archetypeDef===void 0&&(this._archetypeDef=this.agentConfig.archetype?pr(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 n=s.preToolUseHooks({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:e});n.length>0&&(t.PreToolUse=n)}catch(n){R.error("Archetype preToolUseHooks threw \u2014 installing deny-all PreToolUse hook",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(n)}),t.PreToolUse=[{hooks:[async()=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Archetype hook initialization failed (${String(n)}). 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(n,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(`
169
- `),l="";if(s&&n?.transcript_path)try{let d=await q0(n.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}
168
+ `)}buildServerConfig(e,t){return this.buildAllServerConfigs(t)[e]}buildAllServerConfigs(e){let t={};if(p.slack.localMcpServer)t.slack={type:"stdio",command:"node",args:[Y("slack/slack-mcp-server.js")],env:{HIVE_INTERNAL_URL:`http://127.0.0.1:${p.slackInternal.port}`,HIVE_INTERNAL_TOKEN:p.slackInternal.authToken,HIVE_AGENT_ID:this.agentConfig.id}};else{let c=p.slack.mcpToken;c&&(t.slack={type:"http",url:"https://mcp.slack.com/mcp",headers:{Authorization:`Bearer ${c}`}})}let s=[{id:"self",backing:"mongo"}],n=this.getArchetypeDef();if(n&&this.agentConfig.archetypeConfig)try{let c=n.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:[Y("memory/memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,MEMORY_SCOPES_JSON:JSON.stringify(s)}},t["structured-memory"]={type:"stdio",command:"node",args:[Y("memory/structured-memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.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:[Y("keychain/keychain-mcp-server.js")],env:{KEYCHAIN_SERVICE:`hive/${p.instance.id}`}};let i=p.google.accounts[this.agentConfig.id]||p.google.account,o=p.google.client;if(t.google={type:"stdio",command:"node",args:[Y("google/google-mcp-server.js")],env:{...i?{GOG_ACCOUNT:i}:{},...o?{GOG_CLIENT:o}:{},DRIVE_SHARED_FOLDER:p.google.sharedFolder,INSTANCE_ID:p.instance.id,PATH:process.env.PATH??""}},p.quo.apiKey&&(t.quo={type:"stdio",command:"node",args:[Y("quo/quo-mcp-server.js")],env:{QUO_API_KEY:p.quo.apiKey,...p.quo.phoneNumberId?{QUO_PHONE_NUMBER_ID:p.quo.phoneNumberId}:{},QUO_LINES_JSON:JSON.stringify(p.quo.lines)}}),p.voice.enabled&&p.voice.apiKey){let c=Object.entries(p.voice.assistants).find(([d,u])=>u===this.agentConfig.id)?.[0]??"";t.voice={type:"stdio",command:"node",args:[Y("voice/voice-mcp-server.js")],env:{VAPI_API_KEY:p.voice.apiKey,VAPI_PHONE_NUMBER_ID:p.voice.phoneNumberId,VAPI_ASSISTANT_ID:c,AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name}}}t.contacts={type:"stdio",command:"node",args:[Y("contacts/contacts-mcp-server.js")],env:{MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName}};let a=p.taskLedger.agentKeys[this.agentConfig.id]??p.taskLedger.apiKey;if(a&&(t.tasks={type:"stdio",command:"node",args:[Y("tasks/task-mcp-server.js")],env:{TASK_LEDGER_API_URL:p.taskLedger.apiUrl,TASK_LEDGER_API_KEY:a}}),p.brave.apiKey&&(t["brave-search"]={type:"stdio",command:"node",args:[q0(import.meta.url).resolve("brave-search-mcp/dist/index.js")],env:{BRAVE_API_KEY:p.brave.apiKey}}),p.resend.apiKey){let c=this.agentConfig.name.toLowerCase(),d=p.resend.emailDomain,u=p.resend.businessName?` (${p.resend.businessName})`:"",h=d?`${this.agentConfig.name}${u} <${c}@${d}>`:p.resend.fromAddress;t.resend={type:"stdio",command:"node",args:[Y("resend/resend-mcp-server.js")],env:{RESEND_API_KEY:p.resend.apiKey,RESEND_FROM_ADDRESS:h,RESEND_DEFAULT_CC:p.resend.defaultCc,RESEND_DEFAULT_BCC:p.resend.defaultBcc}}}if(p.linear.apiKey){let c={LINEAR_API_KEY:p.linear.apiKey};p.linear.teamId&&(c.LINEAR_TEAM_ID=p.linear.teamId),t.linear={type:"stdio",command:"node",args:[Y("linear/linear-mcp-server.js")],env:c}}if(p.github.repo){let c={GITHUB_REPO:p.github.repo,PATH:process.env.PATH??""};p.github.token&&(c.GH_TOKEN=p.github.token),t["github-issues"]={type:"stdio",command:"node",args:[Y("github/github-issues-mcp-server.js")],env:c}}if(p.clickup.apiToken&&(t.clickup={type:"stdio",command:"node",args:[Y("clickup/clickup-mcp-server.js")],env:{CLICKUP_API_TOKEN:p.clickup.apiToken}}),p.recall.apiKey&&(t.recall={type:"stdio",command:"node",args:[Y("recall/recall-mcp-server.js")],env:{RECALL_API_KEY:p.recall.apiKey,RECALL_API_REGION:p.recall.region,RECALL_WEBHOOK_SECRET:p.recall.webhookSecret,MEETING_MONITOR_API:`http://127.0.0.1:${p.recall.monitorPort}`,MEETING_MONITOR_PUBLIC_URL:p.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??""}}),p.browser.cdpEndpoint){let c=Ec(this.agentConfig.id,z);Ch(c,{recursive:!0}),t.browser={type:"stdio",command:"npx",args:["@playwright/mcp@latest","--cdp-endpoint",p.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:[Y("background/background-task-mcp-server.js")],env:{BG_TASK_API:`http://127.0.0.1:${p.background.port}`,BG_AUTH_TOKEN:p.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:[Y("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:p.mongo.uri,MONGODB_DB:p.mongo.dbName}},t["code-task"]={type:"stdio",command:"node",args:[Y("code-task/code-task-mcp-server.js")],env:{CT_TASK_API:`http://127.0.0.1:${p.codeTask.port}`,CT_AUTH_TOKEN:p.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:[Y("search/conversation-search-mcp-server.js")],env:{...l,AGENT_ID:this.agentConfig.id,DEFAULT_AGENT:p.defaultAgent}},t["code-search"]={type:"stdio",command:"node",args:[Y("code-index/code-search-mcp-server.js")],env:{MONGODB_URI:p.mongo.uri,MONGODB_DB:p.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:z,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 m=h.path;Ah(c.dir);let g=p.taskLedger.agentKeys[this.agentConfig.id]??p.taskLedger.apiKey,f={AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,TASK_LEDGER_API_URL:p.taskLedger.apiUrl,...g?{TASK_LEDGER_API_KEY:g}:{},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]||Jt(p.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]=r.resolveAgentEnvPath(this.agentConfig,w);t[d]={type:"stdio",command:"node",args:[m],env:f}}return t["event-bus"]={type:"stdio",command:"node",args:[Y("events/event-bus-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}},r.registryRef||R.warn("registryRef not set \u2014 agents will get empty AGENT_IDS for team server"),t.team={type:"stdio",command:"node",args:[Y("team/team-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,AGENT_IDS:JSON.stringify(r.registryRef?.getAll().map(c=>c.id)??[])}},p.workflow.enabled&&(t.workflow={type:"stdio",command:"node",args:[Y("workflow/workflow-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}}),t.schedule={type:"stdio",command:"node",args:[Y("schedule/schedule-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName}},t.admin={type:"stdio",command:"node",args:[Y("admin/admin-mcp-server.js")],env:{MONGODB_URI:p.mongo.uri,MONGODB_DB:p.mongo.dbName,AGENT_ID:this.agentConfig.id,INSTANCE_CAPABILITIES:F0(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"),p.workflow.enabled&&s.add("workflow");for(let n of Object.keys(t))s.has(n)||delete t[n];if(!this.agentConfig.autonomy.externalComms)for(let n of["resend","quo"])t[n]&&(R.debug("Autonomy: externalComms disabled \u2014 removing server",{server:n,agent:this.agentConfig.id}),delete t[n]);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("."),n=e;for(let i of s){if(n==null||typeof n!="object")return"";n=n[i]}return n==null?"":String(n)}static INFRASTRUCTURE_SERVERS=new Set(["schedule","structured-memory","team"]);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={},n=new Set;this.agentConfig.autonomy.externalComms||(n.add("resend"),n.add("quo")),this.agentConfig.autonomy.codeTask||n.add("code-task"),this.agentConfig.autonomy.codeAccess||n.add("code-search");for(let i of t){if(n.has(i)){R.debug("Autonomy gate \u2014 skipping delegate server",{server:i,agent:this.agentConfig.id});continue}r.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(Hs[e])return Hs[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 n of e){if(n.includes("/")||n.includes("\\")||n===".."||n.startsWith(".")){R.warn("Invalid plugin name, skipping",{plugin:n,agent:this.agentConfig.id});continue}let i=Oe(s,n);if(!Ws(i)){R.warn("Plugin not found, skipping",{plugin:n,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(n=>n.path)}),t}buildNativeSkills(){return vh(this.skillIndex,this.agentConfig.id)}getArchetypeDef(){return this._archetypeDef===void 0&&(this._archetypeDef=this.agentConfig.archetype?pr(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 n=s.preToolUseHooks({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:e});n.length>0&&(t.PreToolUse=n)}catch(n){R.error("Archetype preToolUseHooks threw \u2014 installing deny-all PreToolUse hook",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(n)}),t.PreToolUse=[{hooks:[async()=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Archetype hook initialization failed (${String(n)}). 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(n,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(`
169
+ `),l="";if(s&&n?.transcript_path)try{let d=await j0(n.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}
170
170
 
171
- ${l}`:a}}]}]}async send(e,t,s,n,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(n),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 m={},g=this.getArchetypeDef();if(g&&this.agentConfig.archetypeConfig)try{m=g.sessionOptions({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:n})}catch(V){R.error("Archetype sessionOptions threw \u2014 ignoring",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(V)})}let f=typeof m.cwd=="string"?"archetype":"default",y=f==="archetype"?m.cwd:Ac(this.agentConfig.id,z);if(f==="default")Ch(y,{recursive:!0});else{let V;try{V=$0(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(!V.isDirectory()){let L=`Archetype cwd is not a directory: ${y}`;throw R.error(L,{agent:this.agentConfig.id}),new Error(L)}}let w=P0({prompt:e,options:{model:a,systemPrompt:u,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:o?.maxTurns??this.agentConfig.maxTurns,maxBudgetUsd:o?.budgetUsd??this.agentConfig.budgetUsd,thinking:{type:"disabled"},cwd:y,settingSources:m.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(n),...this.agentConfig.betas?.length?{betas:this.agentConfig.betas}:{},env:{...process.env,...p.anthropic.apiKey?{ANTHROPIC_API_KEY:p.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 C=0,E=0,G=0,W=0,$=0,ce=0,Ie,me=[],dn=null,os=null,Qe=o?.timeoutMs??this.agentConfig.timeoutMs??3e5,_i=setTimeout(()=>{R.warn("Agent query timed out, aborting",{agent:this.agentConfig.id,timeoutMs:Qe}),this.abort()},Qe);try{for await(let V of w){let L=V;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;ce++,Ie=P?.pre_tokens,R.info("Context compacted",{agent:this.agentConfig.id,trigger:P?.trigger,preTokens:P?.pre_tokens,compactionNumber:ce})}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 le of P)le.type==="text"?S=le.text:le.type==="tool_use"&&(os&&me.length>0&&(me[me.length-1].endMs=Date.now()),os=le.name,dn=Date.now(),me.push({tool:le.name,startMs:dn}),R.info("Tool call started",{agent:this.agentConfig.id,tool:le.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 le=P.usage;le&&(C=le.input_tokens??0,E=le.output_tokens??0,G=le.cache_read_input_tokens??0,W=le.cache_creation_input_tokens??0);let hn=P.modelUsage;if(hn)for(let Lt of Object.values(hn))Lt.contextWindow&&Lt.contextWindow>$&&($=Lt.contextWindow);P.subtype==="success"?S=P.result||S:(D=P.subtype,"errors"in P&&Array.isArray(P.errors)&&(D=P.errors.join("; ")))}}}catch(V){let L=String(V);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(_i),this.activeQuery=null}os&&me.length>0&&(me[me.length-1].endMs=Date.now());let Xe={};for(let V of me){let L=(V.endMs??Date.now())-V.startMs,P=V.tool.includes("__")?V.tool.split("__")[1]:V.tool;Xe[P]||(Xe[P]={count:0,totalMs:0}),Xe[P].count++,Xe[P].totalMs+=L}let un=Object.entries(Xe).sort((V,L)=>L[1].totalMs-V[1].totalMs).map(([V,L])=>`${V}:${L.count}x/${(L.totalMs/1e3).toFixed(1)}s`).join(", "),Be=me.reduce((V,L)=>V+((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:me.length,toolSummary:un||"none",inputTokens:C,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:ce,preCompactTokens:Ie,streamed:N,hasError:!!D}),{text:S,sessionId:_,costUsd:v,durationMs:I,llmMs:as,toolMs:Be,toolCalls:me.length,toolSummary:un||"none",streamed:N,inputTokens:C,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:ce,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 La,mkdirSync as H0}from"node:fs";import{join as _r,extname as Pa}from"node:path";import{tmpdir as W0}from"node:os";function Oh(r){Da=r}async function Mh(r,e){if(!Da)return null;try{let t=r.toString("base64"),s=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Nh}:generateContent?key=${Da}`,{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:Nh,chars:i.length}),i||null}catch(t){return ye.warn("Gemini vision failed",{error:t.message}),null}}async function Dh(r,e,t){let s=Pa(e).slice(1).toLowerCase();if(G0.has(s)||t.startsWith("text/"))return{textContent:br(r.toString("utf-8")),isImage:!1};if(s==="pdf"||t==="application/pdf")try{let n=await import("pdf-parse"),o=await(n.default??n)(r);return{textContent:br(o.text),isImage:!1}}catch(n){return ye.warn("PDF parse failed",{name:e,error:n.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:r});return{textContent:br(i.value),isImage:!1}}catch(n){return ye.warn("DOCX parse failed",{name:e,error:n.message}),{textContent:"[DOCX \u2014 could not extract text]",isImage:!1}}if(s==="xlsx"||s==="xls"||t.includes("spreadsheet"))try{let n=await import("xlsx"),i=n.read(r,{type:"buffer"}),o=i.SheetNames.map(a=>{let l=n.utils.sheet_to_csv(i.Sheets[a]);return`--- Sheet: ${a} ---
171
+ ${l}`:a}}]}]}async send(e,t,s,n,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(n),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 m={},g=this.getArchetypeDef();if(g&&this.agentConfig.archetypeConfig)try{m=g.sessionOptions({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:n})}catch(V){R.error("Archetype sessionOptions threw \u2014 ignoring",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(V)})}let f=typeof m.cwd=="string"?"archetype":"default",y=f==="archetype"?m.cwd:Ac(this.agentConfig.id,z);if(f==="default")Ch(y,{recursive:!0});else{let V;try{V=R0(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(!V.isDirectory()){let L=`Archetype cwd is not a directory: ${y}`;throw R.error(L,{agent:this.agentConfig.id}),new Error(L)}}let w=$0({prompt:e,options:{model:a,systemPrompt:u,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:o?.maxTurns??this.agentConfig.maxTurns,maxBudgetUsd:o?.budgetUsd??this.agentConfig.budgetUsd,thinking:{type:"disabled"},cwd:y,settingSources:m.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(n),...this.agentConfig.betas?.length?{betas:this.agentConfig.betas}:{},env:{...process.env,...p.anthropic.apiKey?{ANTHROPIC_API_KEY:p.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 C=0,E=0,G=0,W=0,$=0,ce=0,Ie,me=[],dn=null,os=null,Qe=o?.timeoutMs??this.agentConfig.timeoutMs??3e5,_i=setTimeout(()=>{R.warn("Agent query timed out, aborting",{agent:this.agentConfig.id,timeoutMs:Qe}),this.abort()},Qe);try{for await(let V of w){let L=V;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;ce++,Ie=P?.pre_tokens,R.info("Context compacted",{agent:this.agentConfig.id,trigger:P?.trigger,preTokens:P?.pre_tokens,compactionNumber:ce})}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 le of P)le.type==="text"?S=le.text:le.type==="tool_use"&&(os&&me.length>0&&(me[me.length-1].endMs=Date.now()),os=le.name,dn=Date.now(),me.push({tool:le.name,startMs:dn}),R.info("Tool call started",{agent:this.agentConfig.id,tool:le.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 le=P.usage;le&&(C=le.input_tokens??0,E=le.output_tokens??0,G=le.cache_read_input_tokens??0,W=le.cache_creation_input_tokens??0);let hn=P.modelUsage;if(hn)for(let Lt of Object.values(hn))Lt.contextWindow&&Lt.contextWindow>$&&($=Lt.contextWindow);P.subtype==="success"?S=P.result||S:(D=P.subtype,"errors"in P&&Array.isArray(P.errors)&&(D=P.errors.join("; ")))}}}catch(V){let L=String(V);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(_i),this.activeQuery=null}os&&me.length>0&&(me[me.length-1].endMs=Date.now());let Xe={};for(let V of me){let L=(V.endMs??Date.now())-V.startMs,P=V.tool.includes("__")?V.tool.split("__")[1]:V.tool;Xe[P]||(Xe[P]={count:0,totalMs:0}),Xe[P].count++,Xe[P].totalMs+=L}let un=Object.entries(Xe).sort((V,L)=>L[1].totalMs-V[1].totalMs).map(([V,L])=>`${V}:${L.count}x/${(L.totalMs/1e3).toFixed(1)}s`).join(", "),Be=me.reduce((V,L)=>V+((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:me.length,toolSummary:un||"none",inputTokens:C,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:ce,preCompactTokens:Ie,streamed:N,hasError:!!D}),{text:S,sessionId:_,costUsd:v,durationMs:I,llmMs:as,toolMs:Be,toolCalls:me.length,toolSummary:un||"none",streamed:N,inputTokens:C,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:ce,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 La,mkdirSync as W0}from"node:fs";import{join as _r,extname as Pa}from"node:path";import{tmpdir as G0}from"node:os";function Oh(r){Da=r}async function Mh(r,e){if(!Da)return null;try{let t=r.toString("base64"),s=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Nh}:generateContent?key=${Da}`,{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:Nh,chars:i.length}),i||null}catch(t){return ye.warn("Gemini vision failed",{error:t.message}),null}}async function Dh(r,e,t){let s=Pa(e).slice(1).toLowerCase();if(V0.has(s)||t.startsWith("text/"))return{textContent:br(r.toString("utf-8")),isImage:!1};if(s==="pdf"||t==="application/pdf")try{let n=await import("pdf-parse"),o=await(n.default??n)(r);return{textContent:br(o.text),isImage:!1}}catch(n){return ye.warn("PDF parse failed",{name:e,error:n.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:r});return{textContent:br(i.value),isImage:!1}}catch(n){return ye.warn("DOCX parse failed",{name:e,error:n.message}),{textContent:"[DOCX \u2014 could not extract text]",isImage:!1}}if(s==="xlsx"||s==="xls"||t.includes("spreadsheet"))try{let n=await import("xlsx"),i=n.read(r,{type:"buffer"}),o=i.SheetNames.map(a=>{let l=n.utils.sheet_to_csv(i.Sheets[a]);return`--- Sheet: ${a} ---
172
172
  ${l}`});return{textContent:br(o.join(`
173
173
 
174
174
  `)),isImage:!1}}catch(n){return ye.warn("XLSX parse failed",{name:e,error:n.message}),{textContent:"[Spreadsheet \u2014 could not extract content]",isImage:!1}}return null}async function Lh(r,e){let t=r.url_private_download||r.url_private;if(!t)return ye.warn("No download URL for file",{id:r.id,name:r.name}),null;try{ye.info("Downloading file",{id:r.id,url:t.slice(0,80),mimetype:r.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:r.id}),s=await fetch(d))}if(!s.ok)return ye.error("Failed to download file",{id:r.id,status:s.status}),null;let n=Buffer.from(await s.arrayBuffer());if(n.length<100&&n.length>0){let d=n.toString("utf-8").trim();if(d.includes("requested")&&d.includes("file")&&d.includes("not found"))return ye.error("Slack file error response",{id:r.id,name:r.name,errorText:d,bufferSize:n.length}),null}let i=r.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=_r(vr,`${r.id}-${i}`);La(o,n);let a=Pa(r.name).slice(1).toLowerCase();if(xh.has(a)||r.mimetype.startsWith("image/")){let d=await Mh(n,r.mimetype);return{name:r.name,mimetype:r.mimetype,size:r.size,localPath:o,textContent:d??"[Image \u2014 could not extract description]",isImage:!0}}let c=await Dh(n,r.name,r.mimetype);return c?{name:r.name,mimetype:r.mimetype,size:r.size,localPath:o,...c}:(ye.info("Unsupported file type",{name:r.name,ext:a,mimetype:r.mimetype}),{name:r.name,mimetype:r.mimetype,size:r.size,localPath:o,textContent:null,isImage:!1})}catch(s){return ye.error("File processing failed",{id:r.id,name:r.name,error:s.message}),null}}async function Vs(r,e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_"),n=_r(vr,`ws-${Date.now()}-${s}`);La(n,r);let i=await Mh(r,t);return{name:e,mimetype:t,size:r.length,localPath:n,textContent:i??"[Image \u2014 could not extract description]",isImage:!0}}async function Ph(r,e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_"),n=_r(vr,`team-${Date.now()}-${s}`);La(n,r);let i=Pa(e).slice(1).toLowerCase();if(xh.has(i)||t.startsWith("image/"))return Vs(r,e,t);let a=await Dh(r,e,t);return a?{name:e,mimetype:t,size:r.length,localPath:n,...a}:{name:e,mimetype:t,size:r.length,localPath:n,textContent:null,isImage:!1}}function $h(r){return r.length===0?"":`
@@ -186,13 +186,13 @@ ${t.textContent}
186
186
 
187
187
  `)}function Rh(r){return r<1024?`${r} B`:r<1024*1024?`${(r/1024).toFixed(1)} KB`:`${(r/(1024*1024)).toFixed(1)} MB`}function br(r,e=5e4){return r.length<=e?r:r.slice(0,e)+`
188
188
 
189
- [... truncated at ${Rh(e)} \u2014 full file at local path]`}var ye,vr,xh,Da,Nh,G0,Ys=j(()=>{"use strict";O();ye=k("file-processor"),vr=_r(W0(),"hive-slack-files");H0(vr,{recursive:!0});xh=new Set(["png","jpg","jpeg","gif","webp","bmp","heic"]),Da="",Nh=process.env.GEMINI_VISION_MODEL||"gemini-2.5-flash";G0=new Set(["csv","tsv","txt","text","md","markdown","json","xml","html","yaml","yml","log"])});async function He(r,e){let t=await fetch(`${r}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:X0,input:e})});if(!t.ok)throw new Error(`Ollama embed ${t.status}: ${await t.text()}`);return(await t.json()).embeddings[0]}var X0,Cr=j(()=>{"use strict";X0=process.env.KB_EMBED_MODEL??"bge-large"});var ja,aN,mf=j(()=>{"use strict";ja="code_index",aN=Buffer.from("6ba7b8109dad11d180b400c04fd430c8","hex")});var gf={};Ue(gf,{CodeIndexPrefetcher:()=>Fa});import{QdrantClient as Nb}from"@qdrant/js-client-rest";import{MongoClient as xb}from"mongodb";var Fa,yf=j(()=>{"use strict";Cr();mf();Fa=class{options;mongo;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.mongo=new xb(this.options.mongoUri),await this.mongo.connect(),this.qdrant=new Nb({url:this.options.qdrantUrl}),this.connected=!0)}async getContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],n;try{n=await He(this.options.ollamaUrl,e)}catch{return""}try{let o=(await this.qdrant.search(ja,{vector:n,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:**
189
+ [... truncated at ${Rh(e)} \u2014 full file at local path]`}var ye,vr,xh,Da,Nh,V0,Ys=j(()=>{"use strict";O();ye=k("file-processor"),vr=_r(G0(),"hive-slack-files");W0(vr,{recursive:!0});xh=new Set(["png","jpg","jpeg","gif","webp","bmp","heic"]),Da="",Nh=process.env.GEMINI_VISION_MODEL||"gemini-2.5-flash";V0=new Set(["csv","tsv","txt","text","md","markdown","json","xml","html","yaml","yml","log"])});async function He(r,e){let t=await fetch(`${r}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:Z0,input:e})});if(!t.ok)throw new Error(`Ollama embed ${t.status}: ${await t.text()}`);return(await t.json()).embeddings[0]}var Z0,Cr=j(()=>{"use strict";Z0=process.env.KB_EMBED_MODEL??"bge-large"});var ja,aN,gf=j(()=>{"use strict";ja="code_index",aN=Buffer.from("6ba7b8109dad11d180b400c04fd430c8","hex")});var yf={};Ue(yf,{CodeIndexPrefetcher:()=>Fa});import{QdrantClient as Nb}from"@qdrant/js-client-rest";import{MongoClient as xb}from"mongodb";var Fa,wf=j(()=>{"use strict";Cr();gf();Fa=class{options;mongo;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.mongo=new xb(this.options.mongoUri),await this.mongo.connect(),this.qdrant=new Nb({url:this.options.qdrantUrl}),this.connected=!0)}async getContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],n;try{n=await He(this.options.ollamaUrl,e)}catch{return""}try{let o=(await this.qdrant.search(ja,{vector:n,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:**
190
190
  `+a.join(`
191
191
  `))}}catch{}if(t)try{let o=(await this.qdrant.search("agent_memory",{vector:n,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.mongo.db(this.options.dbName).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:**
192
192
  `+u.join(`
193
193
  `))}}}}catch{}return s.length===0?"":["## Codebase Context (auto-retrieved)",...s,"","_Results may be stale \u2014 verify by reading files._"].join(`
194
194
  `)}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,n;for(;(n=t.exec(e))!==null;)s.add(n[1]);return[...s]}async getCompactionContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],n=[],i=new Set;try{let c=this.extractFilePaths(e);if(c.length>0){let u=await this.mongo.db(this.options.dbName).collection("code_index").find({filePath:{$in:c}}).project({repo:1,filePath:1,summary:1,role:1}).toArray();for(let h of u){let m=`${h.repo}:${h.filePath}`;i.has(m)||(i.add(m),s.push(`- ${m} \u2014 ${h.summary} [${h.role}]`))}}}catch{}try{let c=e.slice(-2e3),d=await He(this.options.ollamaUrl,c),u=await this.qdrant.search(ja,{vector:d,limit:this.prefetchLimit,with_payload:!0});for(let h of u){if(h.score<this.scoreThreshold)continue;let m=h.payload,g=`${m.repo}:${m.filePath}`;i.has(g)||(i.add(g),s.push(`- ${g} \u2014 ${m.summary} [${m.role}]`))}if(t){let m=(await this.qdrant.search("agent_memory",{vector:d,limit:10,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(g=>g.score>=this.scoreThreshold).filter(g=>typeof g.payload?.topic=="string"&&g.payload.topic.startsWith("code:"));if(m.length>0){let g=m.map(f=>f.payload?.mongoId).filter(Boolean);if(g.length>0){let{ObjectId:f}=await import("mongodb"),w=await this.mongo.db(this.options.dbName).collection("agent_memory").find({_id:{$in:g.map(S=>new f(S))}}).toArray();for(let S of w){let _=String(S.topic??"").replace(/^code:/,""),v=String(S.content??"");n.push(`- ${_}: ${v}`)}}}}}catch{}if(s.length===0&&n.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=n.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(`
195
- `)}async close(){this.connected&&await this.mongo.close()}}});var wf={};Ue(wf,{KnowledgeExtractor:()=>Ka});import Ob from"@anthropic-ai/sdk";var Mb,Ka,Sf=j(()=>{"use strict";O();Mb=k("knowledge-extractor"),Ka=class{memoryStore;memoryEmbedder;anthropic;constructor(e,t){this.memoryStore=e,this.memoryEmbedder=t,this.anthropic=new Ob}async extract(e,t){if(!t?.result)return 0;let s=t.result.length>3e4?t.result.slice(0,3e4)+`
195
+ `)}async close(){this.connected&&await this.mongo.close()}}});var Sf={};Ue(Sf,{KnowledgeExtractor:()=>Ka});import Ob from"@anthropic-ai/sdk";var Mb,Ka,kf=j(()=>{"use strict";O();Mb=k("knowledge-extractor"),Ka=class{memoryStore;memoryEmbedder;anthropic;constructor(e,t){this.memoryStore=e,this.memoryEmbedder=t,this.anthropic=new Ob}async extract(e,t){if(!t?.result)return 0;let s=t.result.length>3e4?t.result.slice(0,3e4)+`
196
196
  [...truncated]`:t.result,n=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:
197
197
  - filePath: the relative file path
198
198
  - repo: which repository this file belongs to, inferred from the working directory or file paths
@@ -202,23 +202,23 @@ ${t.textContent}
202
202
  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.
203
203
 
204
204
  Session output:
205
- ${s}`}]}),o=(n.content[0].type==="text"?n.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 m={content:c.insight,type:"fact",topic:d,importance:c.wasModified?"high":"medium"},g=crypto.randomUUID(),f=await this.memoryStore.save(e,m,g);await this.memoryEmbedder.upsert(g,c.insight,{agentId:e,mongoId:f._id.toString(),type:"fact",topic:d,tier:"hot",importance:m.importance,createdAt:Date.now()}),l++}catch(u){Mb.error("Failed to save insight",{topic:d,error:String(u)})}}return l}}});function kf(r,e){let t=[r,e].sort();return`dm:${t[0]}:${t[1]}`}var bf=j(()=>{"use strict"});var _f={};Ue(_f,{TeamStore:()=>Wa});import{MongoClient as Db,ObjectId as Lb}from"mongodb";var Ha,Wa,vf=j(()=>{"use strict";O();bf();Ha=k("team-store"),Wa=class{uri;dbName;client;db;channels;messages;constructor(e,t){this.uri=e,this.dbName=t,this.client=new Db(e)}async connect(){await this.client.connect(),this.db=this.client.db(this.dbName),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}),Ha.info("Team store connected",{db:this.dbName})}async close(){await this.client.close()}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),Ha.info("Channel created",{id:e._id,type:e.type}),e}async getOrCreateDm(e,t,s){let n=kf(e,t),i=await this.channels.findOne({_id:n});if(i)return i;let o={_id:n,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),Ha.info("DM created",{id:n,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 Lb().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),n={channelId:e};t?.before&&(n._id={$lt:t.before}),t?.threadId&&(n.threadId=t.threadId);let i=await this.messages.find(n).sort({createdAt:-1}).limit(s+1).toArray(),o=i.length>s;return o&&i.pop(),{messages:i.reverse(),hasMore:o}}}});var Tf={};Ue(Tf,{CommandRegistry:()=>Va});var Ga,Va,If=j(()=>{"use strict";O();Ga=k("command-registry"),Va=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)&&Ga.warn("Command already registered, overwriting",{name:e.def.name}),this.commands.set(e.def.name,e),Ga.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(n){return Ga.error("Command execution failed",{name:e,error:String(n)}),{found:!0,result:`Command failed: ${String(n)}`}}}registerCoreCommands(){this.register({def:{name:"help",source:"core",description:"List available commands"},execute:async()=>`Available commands:
205
+ ${s}`}]}),o=(n.content[0].type==="text"?n.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 m={content:c.insight,type:"fact",topic:d,importance:c.wasModified?"high":"medium"},g=crypto.randomUUID(),f=await this.memoryStore.save(e,m,g);await this.memoryEmbedder.upsert(g,c.insight,{agentId:e,mongoId:f._id.toString(),type:"fact",topic:d,tier:"hot",importance:m.importance,createdAt:Date.now()}),l++}catch(u){Mb.error("Failed to save insight",{topic:d,error:String(u)})}}return l}}});function bf(r,e){let t=[r,e].sort();return`dm:${t[0]}:${t[1]}`}var _f=j(()=>{"use strict"});var vf={};Ue(vf,{TeamStore:()=>Wa});import{MongoClient as Db,ObjectId as Lb}from"mongodb";var Ha,Wa,Tf=j(()=>{"use strict";O();_f();Ha=k("team-store"),Wa=class{uri;dbName;client;db;channels;messages;constructor(e,t){this.uri=e,this.dbName=t,this.client=new Db(e)}async connect(){await this.client.connect(),this.db=this.client.db(this.dbName),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}),Ha.info("Team store connected",{db:this.dbName})}async close(){await this.client.close()}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),Ha.info("Channel created",{id:e._id,type:e.type}),e}async getOrCreateDm(e,t,s){let n=bf(e,t),i=await this.channels.findOne({_id:n});if(i)return i;let o={_id:n,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),Ha.info("DM created",{id:n,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 Lb().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),n={channelId:e};t?.before&&(n._id={$lt:t.before}),t?.threadId&&(n.threadId=t.threadId);let i=await this.messages.find(n).sort({createdAt:-1}).limit(s+1).toArray(),o=i.length>s;return o&&i.pop(),{messages:i.reverse(),hasMore:o}}}});var If={};Ue(If,{CommandRegistry:()=>Va});var Ga,Va,Cf=j(()=>{"use strict";O();Ga=k("command-registry"),Va=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)&&Ga.warn("Command already registered, overwriting",{name:e.def.name}),this.commands.set(e.def.name,e),Ga.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(n){return Ga.error("Command execution failed",{name:e,error:String(n)}),{found:!0,result:`Command failed: ${String(n)}`}}}registerCoreCommands(){this.register({def:{name:"help",source:"core",description:"List available commands"},execute:async()=>`Available commands:
206
206
  ${this.list().map(s=>` /${s.name} \u2014 ${s.description}`).join(`
207
207
  `)}`}),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}:
208
208
  ${t.members.map(s=>` - ${s}`).join(`
209
- `)}`:"Channel not found"}})}}});var Ve=T((kN,Ef)=>{"use strict";var Cf=["nodebuffer","arraybuffer","fragments"],Af=typeof Blob<"u";Af&&Cf.push("blob");Ef.exports={BINARY_TYPES:Cf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Af,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var en=T((bN,ci)=>{"use strict";var{EMPTY_BUFFER:Pb}=Ve(),Ya=Buffer[Symbol.species];function $b(r,e){if(r.length===0)return Pb;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),s=0;for(let n=0;n<r.length;n++){let i=r[n];t.set(i,s),s+=i.length}return s<e?new Ya(t.buffer,t.byteOffset,s):t}function Nf(r,e,t,s,n){for(let i=0;i<n;i++)t[s+i]=r[i]^e[i&3]}function xf(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Rb(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ja(r){if(Ja.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ya(r):ArrayBuffer.isView(r)?e=new Ya(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ja.readOnly=!1),e}ci.exports={concat:$b,mask:Nf,toArrayBuffer:Rb,toBuffer:Ja,unmask:xf};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=H("bufferutil");ci.exports.mask=function(e,t,s,n,i){i<48?Nf(e,t,s,n,i):r.mask(e,t,s,n,i)},ci.exports.unmask=function(e,t){e.length<32?xf(e,t):r.unmask(e,t)}}catch{}});var Df=T((_N,Mf)=>{"use strict";var Of=Symbol("kDone"),za=Symbol("kRun"),Qa=class{constructor(e){this[Of]=()=>{this.pending--,this[za]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[za]()}[za](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Of])}}};Mf.exports=Qa});var es=T((vN,Rf)=>{"use strict";var tn=H("zlib"),Lf=en(),Bb=Df(),{kStatusCode:Pf}=Ve(),Ub=Buffer[Symbol.species],qb=Buffer.from([0,0,255,255]),di=Symbol("permessage-deflate"),Ye=Symbol("total-length"),Xt=Symbol("callback"),pt=Symbol("buffers"),Zt=Symbol("error"),li,Xa=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,!li){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;li=new Bb(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(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!n.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 n=t[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);t[s]=n})}),e}decompress(e,t,s){li.add(n=>{this._decompress(e,t,(i,o)=>{n(),s(i,o)})})}compress(e,t,s){li.add(n=>{this._compress(e,t,(i,o)=>{n(),s(i,o)})})}_decompress(e,t,s){let n=this._isServer?"client":"server";if(!this._inflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?tn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=tn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[di]=this,this._inflate[Ye]=0,this._inflate[pt]=[],this._inflate.on("error",Fb),this._inflate.on("data",$f)}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=Lf.concat(this._inflate[pt],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[pt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,t,s){let n=this._isServer?"server":"client";if(!this._deflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?tn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=tn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ye]=0,this._deflate[pt]=[],this._deflate.on("data",jb)}this._deflate[Xt]=s,this._deflate.write(e),this._deflate.flush(tn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Lf.concat(this._deflate[pt],this._deflate[Ye]);t&&(i=new Ub(i.buffer,i.byteOffset,i.length-4)),this._deflate[Xt]=null,this._deflate[Ye]=0,this._deflate[pt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Rf.exports=Xa;function jb(r){this[pt].push(r),this[Ye]+=r.length}function $f(r){if(this[Ye]+=r.length,this[di]._maxPayload<1||this[Ye]<=this[di]._maxPayload){this[pt].push(r);return}this[Zt]=new RangeError("Max payload size exceeded"),this[Zt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zt][Pf]=1009,this.removeListener("data",$f),this.reset()}function Fb(r){if(this[di]._inflate=null,this[Zt]){this[Xt](this[Zt]);return}r[Pf]=1007,this[Xt](r)}});var ts=T((TN,ui)=>{"use strict";var{isUtf8:Bf}=H("buffer"),{hasBlob:Kb}=Ve(),Hb=[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 Wb(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Za(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Gb(r){return Kb&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}ui.exports={isBlob:Gb,isValidStatusCode:Wb,isValidUTF8:Za,tokenChars:Hb};if(Bf)ui.exports.isValidUTF8=function(r){return r.length<24?Za(r):Bf(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=H("utf-8-validate");ui.exports.isValidUTF8=function(e){return e.length<32?Za(e):r(e)}}catch{}});var rc=T((IN,Wf)=>{"use strict";var{Writable:Vb}=H("stream"),Uf=es(),{BINARY_TYPES:Yb,EMPTY_BUFFER:qf,kStatusCode:Jb,kWebSocket:zb}=Ve(),{concat:ec,toArrayBuffer:Qb,unmask:Xb}=en(),{isValidStatusCode:Zb,isValidUTF8:jf}=ts(),hi=Buffer[Symbol.species],_e=0,Ff=1,Kf=2,Hf=3,tc=4,sc=5,fi=6,nc=class extends Vb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Yb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[zb]=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 hi(s.buffer,s.byteOffset+e,s.length-e),new hi(s.buffer,s.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=t.length-e;e>=s.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new hi(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 Ff:this.getPayloadLength16(e);break;case Kf:this.getPayloadLength64(e);break;case Hf:this.getMask();break;case tc:this.getData(e);break;case sc:case fi: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 n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(t[0]&64)===64;if(s&&!this._extensions[Uf.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Ff:this._payloadLength===127?this._state=Kf: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 n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);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=Hf:this._state=tc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=tc}getData(e){let t=qf;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&&Xb(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=sc,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Uf.extensionName].decompress(e,this._fin,(n,i)=>{if(n)return t(n);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 n;this._binaryType==="nodebuffer"?n=ec(s,t):this._binaryType==="arraybuffer"?n=Qb(ec(s,t)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=_e):(this._state=fi,setImmediate(()=>{this.emit("message",n,!0),this._state=_e,this.startLoop(e)}))}else{let n=ec(s,t);if(!this._skipUTF8Validation&&!jf(n)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===sc||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=_e):(this._state=fi,setImmediate(()=>{this.emit("message",n,!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,qf),this.end();else{let s=e.readUInt16BE(0);if(!Zb(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let n=new hi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!jf(n)){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,n),this.end()}this._state=_e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_e):(this._state=fi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_e,this.startLoop(t)}))}createError(e,t,s,n,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[Jb]=n,o}};Wf.exports=nc});var ac=T((AN,Yf)=>{"use strict";var{Duplex:CN}=H("stream"),{randomFillSync:e_}=H("crypto"),Gf=es(),{EMPTY_BUFFER:t_,kWebSocket:s_,NOOP:n_}=Ve(),{isBlob:ss,isValidStatusCode:r_}=ts(),{mask:Vf,toBuffer:Nt}=en(),ve=Symbol("kByteLength"),i_=Buffer.alloc(4),pi=8*1024,xt,ns=pi,De=0,o_=1,a_=2,ic=class r{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=n_,this[s_]=void 0}static frame(e,t){let s,n=!1,i=2,o=!1;t.mask&&(s=t.maskBuffer||i_,t.generateMask?t.generateMask(s):(ns===pi&&(xt===void 0&&(xt=Buffer.alloc(pi)),e_(xt,0,pi),ns=0),s[0]=xt[ns++],s[1]=xt[ns++],s[2]=xt[ns++],s[3]=xt[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,n=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(n?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]:n?(Vf(e,s,c,i,a),[c]):(Vf(e,s,e,0,a),[c,e])):[c,e]}close(e,t,s,n){let i;if(e===void 0)i=t_;else{if(typeof e!="number"||!r_(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,n]):this.sendFrame(r.frame(i,o),n)}ping(e,t,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):ss(e)?(n=e.size,i=!1):(e=Nt(e),n=e.length,i=Nt.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:n,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(r.frame(e,o),s)}pong(e,t,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):ss(e)?(n=e.size,i=!1):(e=Nt(e),n=e.length,i=Nt.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:n,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(r.frame(e,o),s)}send(e,t,s){let n=this._extensions[Gf.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=Nt(e),a=e.length,l=Nt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=n._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,n){this._bufferedBytes+=s[ve],this._state=a_,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(oc,this,a,n);return}this._bufferedBytes-=s[ve];let o=Nt(i);t?this.dispatch(o,t,s,n):(this._state=De,this.sendFrame(r.frame(o,s),n),this.dequeue())}).catch(i=>{process.nextTick(c_,this,i,n)})}dispatch(e,t,s,n){if(!t){this.sendFrame(r.frame(e,s),n);return}let i=this._extensions[Gf.extensionName];this._bufferedBytes+=s[ve],this._state=o_,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");oc(this,l,n);return}this._bufferedBytes-=s[ve],this._state=De,s.readOnly=!1,this.sendFrame(r.frame(a,s),n),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)}};Yf.exports=ic;function oc(r,e,t){typeof t=="function"&&t(e);for(let s=0;s<r._queue.length;s++){let n=r._queue[s],i=n[n.length-1];typeof i=="function"&&i(e)}}function c_(r,e,t){oc(r,e,t),r.onerror(e)}});var np=T((EN,sp)=>{"use strict";var{kForOnEventAttribute:sn,kListener:cc}=Ve(),Jf=Symbol("kCode"),zf=Symbol("kData"),Qf=Symbol("kError"),Xf=Symbol("kMessage"),Zf=Symbol("kReason"),rs=Symbol("kTarget"),ep=Symbol("kType"),tp=Symbol("kWasClean"),Je=class{constructor(e){this[rs]=null,this[ep]=e}get target(){return this[rs]}get type(){return this[ep]}};Object.defineProperty(Je.prototype,"target",{enumerable:!0});Object.defineProperty(Je.prototype,"type",{enumerable:!0});var Ot=class extends Je{constructor(e,t={}){super(e),this[Jf]=t.code===void 0?0:t.code,this[Zf]=t.reason===void 0?"":t.reason,this[tp]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[Jf]}get reason(){return this[Zf]}get wasClean(){return this[tp]}};Object.defineProperty(Ot.prototype,"code",{enumerable:!0});Object.defineProperty(Ot.prototype,"reason",{enumerable:!0});Object.defineProperty(Ot.prototype,"wasClean",{enumerable:!0});var is=class extends Je{constructor(e,t={}){super(e),this[Qf]=t.error===void 0?null:t.error,this[Xf]=t.message===void 0?"":t.message}get error(){return this[Qf]}get message(){return this[Xf]}};Object.defineProperty(is.prototype,"error",{enumerable:!0});Object.defineProperty(is.prototype,"message",{enumerable:!0});var nn=class extends Je{constructor(e,t={}){super(e),this[zf]=t.data===void 0?null:t.data}get data(){return this[zf]}};Object.defineProperty(nn.prototype,"data",{enumerable:!0});var l_={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[sn]&&n[cc]===e&&!n[sn])return;let s;if(r==="message")s=function(i,o){let a=new nn("message",{data:o?i:i.toString()});a[rs]=this,mi(e,this,a)};else if(r==="close")s=function(i,o){let a=new Ot("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[rs]=this,mi(e,this,a)};else if(r==="error")s=function(i){let o=new is("error",{error:i,message:i.message});o[rs]=this,mi(e,this,o)};else if(r==="open")s=function(){let i=new Je("open");i[rs]=this,mi(e,this,i)};else return;s[sn]=!!t[sn],s[cc]=e,t.once?this.once(r,s):this.on(r,s)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[cc]===e&&!t[sn]){this.removeListener(r,t);break}}};sp.exports={CloseEvent:Ot,ErrorEvent:is,Event:Je,EventTarget:l_,MessageEvent:nn};function mi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var gi=T((NN,rp)=>{"use strict";var{tokenChars:rn}=ts();function $e(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function d_(r){let e=Object.create(null),t=Object.create(null),s=!1,n=!1,i=!1,o,a,l=-1,c=-1,d=-1,u=0;for(;u<r.length;u++)if(c=r.charCodeAt(u),o===void 0)if(d===-1&&rn[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 m=r.slice(l,d);c===44?($e(e,m,t),t=Object.create(null)):o=m,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&rn[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,r.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=r.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(n){if(rn[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:s||(s=!0),n=!1}else if(i)if(rn[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)i=!1,d=u;else if(c===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&rn[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 m=r.slice(l,d);s&&(m=m.replace(/\\/g,""),s=!1),$e(t,a,m),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=r.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 u_(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(s=>[e].concat(Object.keys(s).map(n=>{let i=s[n];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?n:`${n}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}rp.exports={format:u_,parse:d_}});var ki=T((MN,gp)=>{"use strict";var h_=H("events"),f_=H("https"),p_=H("http"),ap=H("net"),m_=H("tls"),{randomBytes:g_,createHash:y_}=H("crypto"),{Duplex:xN,Readable:ON}=H("stream"),{URL:lc}=H("url"),mt=es(),w_=rc(),S_=ac(),{isBlob:k_}=ts(),{BINARY_TYPES:ip,CLOSE_TIMEOUT:b_,EMPTY_BUFFER:yi,GUID:__,kForOnEventAttribute:dc,kListener:v_,kStatusCode:T_,kWebSocket:ie,NOOP:cp}=Ve(),{EventTarget:{addEventListener:I_,removeEventListener:C_}}=np(),{format:A_,parse:E_}=gi(),{toBuffer:N_}=en(),lp=Symbol("kAborted"),uc=[8,13],ze=["CONNECTING","OPEN","CLOSING","CLOSED"],x_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,J=class r extends h_{constructor(e,t,s){super(),this._binaryType=ip[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=yi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.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]),dp(this,e,t,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){ip.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 n=new w_({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new S_(e,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[ie]=this,i[ie]=this,e[ie]=this,n.on("conclude",D_),n.on("drain",L_),n.on("error",P_),n.on("message",$_),n.on("ping",R_),n.on("pong",B_),i.onerror=U_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",fp),e.on("data",Si),e.on("end",pp),e.on("error",mp),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[mt.extensionName]&&this._extensions[mt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),hp(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===r.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!==r.OPEN){hc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||yi,t,s)}pong(e,t,s){if(this.readyState===r.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!==r.OPEN){hc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||yi,t,s)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===r.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!==r.OPEN){hc(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[mt.extensionName]||(n.compress=!1),this._sender.send(e||yi,n,s)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(J,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(J.prototype,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(J,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(J.prototype,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(J,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(J.prototype,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(J,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});Object.defineProperty(J.prototype,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(J.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(J.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[dc])return e[v_];return null},set(e){for(let t of this.listeners(r))if(t[dc]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[dc]:!0})}})});J.prototype.addEventListener=I_;J.prototype.removeEventListener=C_;gp.exports=J;function dp(r,e,t,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:b_,protocolVersion:uc[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(r._autoPong=n.autoPong,r._closeTimeout=n.closeTimeout,!uc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${uc.join(", ")})`);let i;if(e instanceof lc)i=e;else try{i=new lc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._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(r._redirects===0)throw f;wi(r,f);return}let c=o?443:80,d=g_(16).toString("base64"),u=o?f_.request:p_.request,h=new Set,m;if(n.createConnection=n.createConnection||(o?M_:O_),n.defaultPort=n.defaultPort||c,n.port=i.port||c,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(m=new mt({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=A_({[mt.extensionName]:m.offer()})),t.length){for(let f of t){if(typeof f!="string"||!x_.test(f)||h.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(f)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){let f=n.path.split(":");n.socketPath=f[0],n.path=f[1]}let g;if(n.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?n.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(r.listenerCount("redirect")===0){let f=a?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!f||r._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,f||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=r._req=u(n),r._redirects&&r.emit("redirect",r.url,g)}else g=r._req=u(n);n.timeout&&g.on("timeout",()=>{Se(r,g,"Opening handshake has timed out")}),g.on("error",f=>{g===null||g[lp]||(g=r._req=null,wi(r,f))}),g.on("response",f=>{let y=f.headers.location,w=f.statusCode;if(y&&n.followRedirects&&w>=300&&w<400){if(++r._redirects>n.maxRedirects){Se(r,g,"Maximum redirects exceeded");return}g.abort();let S;try{S=new lc(y,e)}catch{let v=new SyntaxError(`Invalid URL: ${y}`);wi(r,v);return}dp(r,S,t,s)}else r.emit("unexpected-response",g,f)||Se(r,g,`Unexpected server response: ${f.statusCode}`)}),g.on("upgrade",(f,y,w)=>{if(r.emit("upgrade",f),r.readyState!==J.CONNECTING)return;g=r._req=null;let S=f.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){Se(r,y,"Invalid Upgrade header");return}let _=y_("sha1").update(d+__).digest("base64");if(f.headers["sec-websocket-accept"]!==_){Se(r,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(r,y,I);return}v&&(r._protocol=v);let N=f.headers["sec-websocket-extensions"];if(N!==void 0){if(!m){Se(r,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let D;try{D=E_(N)}catch{Se(r,y,"Invalid Sec-WebSocket-Extensions header");return}let C=Object.keys(D);if(C.length!==1||C[0]!==mt.extensionName){Se(r,y,"Server indicated an extension that was not requested");return}try{m.accept(D[mt.extensionName])}catch{Se(r,y,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[mt.extensionName]=m}r.setSocket(y,w,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,r):g.end()}function wi(r,e){r._readyState=J.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function O_(r){return r.path=r.socketPath,ap.connect(r)}function M_(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=ap.isIP(r.host)?"":r.host),m_.connect(r)}function Se(r,e,t){r._readyState=J.CLOSING;let s=new Error(t);Error.captureStackTrace(s,Se),e.setHeader?(e[lp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(wi,r,s)):(e.destroy(s),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function hc(r,e,t){if(e){let s=k_(e)?e.size:N_(e).length;r._socket?r._sender._bufferedBytes+=s:r._bufferedAmount+=s}if(t){let s=new Error(`WebSocket is not open: readyState ${r.readyState} (${ze[r.readyState]})`);process.nextTick(t,s)}}function D_(r,e){let t=this[ie];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ie]!==void 0&&(t._socket.removeListener("data",Si),process.nextTick(up,t._socket),r===1005?t.close():t.close(r,e))}function L_(){let r=this[ie];r.isPaused||r._socket.resume()}function P_(r){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",Si),process.nextTick(up,e._socket),e.close(r[T_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function op(){this[ie].emitClose()}function $_(r,e){this[ie].emit("message",r,e)}function R_(r){let e=this[ie];e._autoPong&&e.pong(r,!this._isServer,cp),e.emit("ping",r)}function B_(r){this[ie].emit("pong",r)}function up(r){r.resume()}function U_(r){let e=this[ie];e.readyState!==J.CLOSED&&(e.readyState===J.OPEN&&(e._readyState=J.CLOSING,hp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function hp(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function fp(){let r=this[ie];if(this.removeListener("close",fp),this.removeListener("data",Si),this.removeListener("end",pp),r._readyState=J.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[ie]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",op),r._receiver.on("finish",op))}function Si(r){this[ie]._receiver.write(r)||this.pause()}function pp(){let r=this[ie];r._readyState=J.CLOSING,r._receiver.end(),this.end()}function mp(){let r=this[ie];this.removeListener("error",mp),this.on("error",cp),r&&(r._readyState=J.CLOSING,this.destroy())}});var kp=T((LN,Sp)=>{"use strict";var DN=ki(),{Duplex:q_}=H("stream");function yp(r){r.emit("close")}function j_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function wp(r){this.removeListener("error",wp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function F_(r,e){let t=!0,s=new q_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||r.pause()}),r.once("error",function(i){s.destroyed||(t=!1,s.destroy(i))}),r.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,i){if(r.readyState===r.CLOSED){i(n),process.nextTick(yp,s);return}let o=!1;r.once("error",function(l){o=!0,i(l)}),r.once("close",function(){o||i(n),process.nextTick(yp,s)}),t&&r.terminate()},s._final=function(n){if(r.readyState===r.CONNECTING){r.once("open",function(){s._final(n)});return}r._socket!==null&&(r._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(r._socket.once("finish",function(){n()}),r.close()))},s._read=function(){r.isPaused&&r.resume()},s._write=function(n,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){s._write(n,i,o)});return}r.send(n,o)},s.on("end",j_),s.on("error",wp),s}Sp.exports=F_});var fc=T((PN,bp)=>{"use strict";var{tokenChars:K_}=ts();function H_(r){let e=new Set,t=-1,s=-1,n=0;for(n;n<r.length;n++){let o=r.charCodeAt(n);if(s===-1&&K_[o]===1)t===-1&&(t=n);else if(n!==0&&(o===32||o===9))s===-1&&t!==-1&&(s=n);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=r.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 ${n}`)}if(t===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,n);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}bp.exports={parse:H_}});var Ep=T((RN,Ap)=>{"use strict";var W_=H("events"),bi=H("http"),{Duplex:$N}=H("stream"),{createHash:G_}=H("crypto"),_p=gi(),Mt=es(),V_=fc(),Y_=ki(),{CLOSE_TIMEOUT:J_,GUID:z_,kWebSocket:Q_}=Ve(),X_=/^[+/0-9A-Za-z]{22}==$/,vp=0,Tp=1,Cp=2,pc=class extends W_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:J_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Y_,...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=bi.createServer((s,n)=>{let i=bi.STATUS_CODES[426];n.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),n.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=Z_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,i,o)=>{this.handleUpgrade(n,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=vp}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===Cp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(on,this);return}if(e&&this.once("close",e),this._state!==Tp)if(this._state=Tp,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(on,this):process.nextTick(on,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{on(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,n){t.on("error",Ip);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Dt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Dt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!X_.test(i)){Dt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Dt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){an(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=V_.parse(l)}catch{Dt(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 Mt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=_p.parse(d);m[Mt.extensionName]&&(h.accept(m[Mt.extensionName]),u[Mt.extensionName]=h)}catch{Dt(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,(m,g,f,y)=>{if(!m)return an(t,g||401,f,y);this.completeUpgrade(u,i,c,e,t,s,n)});return}if(!this.options.verifyClient(h))return an(t,401)}this.completeUpgrade(u,i,c,e,t,s,n)}completeUpgrade(e,t,s,n,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Q_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>vp)return an(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${G_("sha1").update(t+z_).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(s.size){let u=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Mt.extensionName]){let u=e[Mt.extensionName].params,h=_p.format({[Mt.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",c,n),i.write(c.concat(`\r
209
+ `)}`:"Channel not found"}})}}});var Ve=T((kN,Nf)=>{"use strict";var Af=["nodebuffer","arraybuffer","fragments"],Ef=typeof Blob<"u";Ef&&Af.push("blob");Nf.exports={BINARY_TYPES:Af,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ef,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var en=T((bN,ci)=>{"use strict";var{EMPTY_BUFFER:Pb}=Ve(),Ya=Buffer[Symbol.species];function $b(r,e){if(r.length===0)return Pb;if(r.length===1)return r[0];let t=Buffer.allocUnsafe(e),s=0;for(let n=0;n<r.length;n++){let i=r[n];t.set(i,s),s+=i.length}return s<e?new Ya(t.buffer,t.byteOffset,s):t}function xf(r,e,t,s,n){for(let i=0;i<n;i++)t[s+i]=r[i]^e[i&3]}function Of(r,e){for(let t=0;t<r.length;t++)r[t]^=e[t&3]}function Rb(r){return r.length===r.buffer.byteLength?r.buffer:r.buffer.slice(r.byteOffset,r.byteOffset+r.length)}function Ja(r){if(Ja.readOnly=!0,Buffer.isBuffer(r))return r;let e;return r instanceof ArrayBuffer?e=new Ya(r):ArrayBuffer.isView(r)?e=new Ya(r.buffer,r.byteOffset,r.byteLength):(e=Buffer.from(r),Ja.readOnly=!1),e}ci.exports={concat:$b,mask:xf,toArrayBuffer:Rb,toBuffer:Ja,unmask:Of};if(!process.env.WS_NO_BUFFER_UTIL)try{let r=H("bufferutil");ci.exports.mask=function(e,t,s,n,i){i<48?xf(e,t,s,n,i):r.mask(e,t,s,n,i)},ci.exports.unmask=function(e,t){e.length<32?Of(e,t):r.unmask(e,t)}}catch{}});var Lf=T((_N,Df)=>{"use strict";var Mf=Symbol("kDone"),za=Symbol("kRun"),Qa=class{constructor(e){this[Mf]=()=>{this.pending--,this[za]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[za]()}[za](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Mf])}}};Df.exports=Qa});var es=T((vN,Bf)=>{"use strict";var tn=H("zlib"),Pf=en(),Bb=Lf(),{kStatusCode:$f}=Ve(),Ub=Buffer[Symbol.species],qb=Buffer.from([0,0,255,255]),di=Symbol("permessage-deflate"),Ye=Symbol("total-length"),Xt=Symbol("callback"),pt=Symbol("buffers"),Zt=Symbol("error"),li,Xa=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,!li){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;li=new Bb(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(n=>!(t.serverNoContextTakeover===!1&&n.server_no_context_takeover||n.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>n.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!n.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 n=t[s];if(n.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(n=n[0],s==="client_max_window_bits"){if(n!==!0){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else if(s==="server_max_window_bits"){let i=+n;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${n}`);n=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(n!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${n}`)}else throw new Error(`Unknown parameter "${s}"`);t[s]=n})}),e}decompress(e,t,s){li.add(n=>{this._decompress(e,t,(i,o)=>{n(),s(i,o)})})}compress(e,t,s){li.add(n=>{this._compress(e,t,(i,o)=>{n(),s(i,o)})})}_decompress(e,t,s){let n=this._isServer?"client":"server";if(!this._inflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?tn.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=tn.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[di]=this,this._inflate[Ye]=0,this._inflate[pt]=[],this._inflate.on("error",Fb),this._inflate.on("data",Rf)}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=Pf.concat(this._inflate[pt],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[pt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,t,s){let n=this._isServer?"server":"client";if(!this._deflate){let i=`${n}_max_window_bits`,o=typeof this.params[i]!="number"?tn.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=tn.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ye]=0,this._deflate[pt]=[],this._deflate.on("data",jb)}this._deflate[Xt]=s,this._deflate.write(e),this._deflate.flush(tn.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=Pf.concat(this._deflate[pt],this._deflate[Ye]);t&&(i=new Ub(i.buffer,i.byteOffset,i.length-4)),this._deflate[Xt]=null,this._deflate[Ye]=0,this._deflate[pt]=[],t&&this.params[`${n}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Bf.exports=Xa;function jb(r){this[pt].push(r),this[Ye]+=r.length}function Rf(r){if(this[Ye]+=r.length,this[di]._maxPayload<1||this[Ye]<=this[di]._maxPayload){this[pt].push(r);return}this[Zt]=new RangeError("Max payload size exceeded"),this[Zt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zt][$f]=1009,this.removeListener("data",Rf),this.reset()}function Fb(r){if(this[di]._inflate=null,this[Zt]){this[Xt](this[Zt]);return}r[$f]=1007,this[Xt](r)}});var ts=T((TN,ui)=>{"use strict";var{isUtf8:Uf}=H("buffer"),{hasBlob:Kb}=Ve(),Hb=[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 Wb(r){return r>=1e3&&r<=1014&&r!==1004&&r!==1005&&r!==1006||r>=3e3&&r<=4999}function Za(r){let e=r.length,t=0;for(;t<e;)if((r[t]&128)===0)t++;else if((r[t]&224)===192){if(t+1===e||(r[t+1]&192)!==128||(r[t]&254)===192)return!1;t+=2}else if((r[t]&240)===224){if(t+2>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||r[t]===224&&(r[t+1]&224)===128||r[t]===237&&(r[t+1]&224)===160)return!1;t+=3}else if((r[t]&248)===240){if(t+3>=e||(r[t+1]&192)!==128||(r[t+2]&192)!==128||(r[t+3]&192)!==128||r[t]===240&&(r[t+1]&240)===128||r[t]===244&&r[t+1]>143||r[t]>244)return!1;t+=4}else return!1;return!0}function Gb(r){return Kb&&typeof r=="object"&&typeof r.arrayBuffer=="function"&&typeof r.type=="string"&&typeof r.stream=="function"&&(r[Symbol.toStringTag]==="Blob"||r[Symbol.toStringTag]==="File")}ui.exports={isBlob:Gb,isValidStatusCode:Wb,isValidUTF8:Za,tokenChars:Hb};if(Uf)ui.exports.isValidUTF8=function(r){return r.length<24?Za(r):Uf(r)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let r=H("utf-8-validate");ui.exports.isValidUTF8=function(e){return e.length<32?Za(e):r(e)}}catch{}});var rc=T((IN,Gf)=>{"use strict";var{Writable:Vb}=H("stream"),qf=es(),{BINARY_TYPES:Yb,EMPTY_BUFFER:jf,kStatusCode:Jb,kWebSocket:zb}=Ve(),{concat:ec,toArrayBuffer:Qb,unmask:Xb}=en(),{isValidStatusCode:Zb,isValidUTF8:Ff}=ts(),hi=Buffer[Symbol.species],_e=0,Kf=1,Hf=2,Wf=3,tc=4,sc=5,fi=6,nc=class extends Vb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Yb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[zb]=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 hi(s.buffer,s.byteOffset+e,s.length-e),new hi(s.buffer,s.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],n=t.length-e;e>=s.length?t.set(this._buffers.shift(),n):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),n),this._buffers[0]=new hi(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 Kf:this.getPayloadLength16(e);break;case Hf:this.getPayloadLength64(e);break;case Wf:this.getMask();break;case tc:this.getData(e);break;case sc:case fi: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 n=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(n);return}let s=(t[0]&64)===64;if(s&&!this._extensions[qf.extensionName]){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(!this._fragmented){let n=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let n=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(n);return}if(s){let n=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(n);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let n=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(n);return}}else{let n=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(n);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let n=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(n);return}}else if(this._masked){let n=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(n);return}this._payloadLength===126?this._state=Kf:this._payloadLength===127?this._state=Hf: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 n=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(n);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=Wf:this._state=tc}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=tc}getData(e){let t=jf;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&&Xb(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=sc,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[qf.extensionName].decompress(e,this._fin,(n,i)=>{if(n)return t(n);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 n;this._binaryType==="nodebuffer"?n=ec(s,t):this._binaryType==="arraybuffer"?n=Qb(ec(s,t)):this._binaryType==="blob"?n=new Blob(s):n=s,this._allowSynchronousEvents?(this.emit("message",n,!0),this._state=_e):(this._state=fi,setImmediate(()=>{this.emit("message",n,!0),this._state=_e,this.startLoop(e)}))}else{let n=ec(s,t);if(!this._skipUTF8Validation&&!Ff(n)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===sc||this._allowSynchronousEvents?(this.emit("message",n,!1),this._state=_e):(this._state=fi,setImmediate(()=>{this.emit("message",n,!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,jf),this.end();else{let s=e.readUInt16BE(0);if(!Zb(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let n=new hi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Ff(n)){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,n),this.end()}this._state=_e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_e):(this._state=fi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_e,this.startLoop(t)}))}createError(e,t,s,n,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[Jb]=n,o}};Gf.exports=nc});var ac=T((AN,Jf)=>{"use strict";var{Duplex:CN}=H("stream"),{randomFillSync:e_}=H("crypto"),Vf=es(),{EMPTY_BUFFER:t_,kWebSocket:s_,NOOP:n_}=Ve(),{isBlob:ss,isValidStatusCode:r_}=ts(),{mask:Yf,toBuffer:Nt}=en(),ve=Symbol("kByteLength"),i_=Buffer.alloc(4),pi=8*1024,xt,ns=pi,De=0,o_=1,a_=2,ic=class r{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=n_,this[s_]=void 0}static frame(e,t){let s,n=!1,i=2,o=!1;t.mask&&(s=t.maskBuffer||i_,t.generateMask?t.generateMask(s):(ns===pi&&(xt===void 0&&(xt=Buffer.alloc(pi)),e_(xt,0,pi),ns=0),s[0]=xt[ns++],s[1]=xt[ns++],s[2]=xt[ns++],s[3]=xt[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,n=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(n?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]:n?(Yf(e,s,c,i,a),[c]):(Yf(e,s,e,0,a),[c,e])):[c,e]}close(e,t,s,n){let i;if(e===void 0)i=t_;else{if(typeof e!="number"||!r_(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,n]):this.sendFrame(r.frame(i,o),n)}ping(e,t,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):ss(e)?(n=e.size,i=!1):(e=Nt(e),n=e.length,i=Nt.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:n,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(r.frame(e,o),s)}pong(e,t,s){let n,i;if(typeof e=="string"?(n=Buffer.byteLength(e),i=!1):ss(e)?(n=e.size,i=!1):(e=Nt(e),n=e.length,i=Nt.readOnly),n>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:n,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(r.frame(e,o),s)}send(e,t,s){let n=this._extensions[Vf.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=Nt(e),a=e.length,l=Nt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&n&&n.params[n._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=n._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,n){this._bufferedBytes+=s[ve],this._state=a_,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(oc,this,a,n);return}this._bufferedBytes-=s[ve];let o=Nt(i);t?this.dispatch(o,t,s,n):(this._state=De,this.sendFrame(r.frame(o,s),n),this.dequeue())}).catch(i=>{process.nextTick(c_,this,i,n)})}dispatch(e,t,s,n){if(!t){this.sendFrame(r.frame(e,s),n);return}let i=this._extensions[Vf.extensionName];this._bufferedBytes+=s[ve],this._state=o_,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");oc(this,l,n);return}this._bufferedBytes-=s[ve],this._state=De,s.readOnly=!1,this.sendFrame(r.frame(a,s),n),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)}};Jf.exports=ic;function oc(r,e,t){typeof t=="function"&&t(e);for(let s=0;s<r._queue.length;s++){let n=r._queue[s],i=n[n.length-1];typeof i=="function"&&i(e)}}function c_(r,e,t){oc(r,e,t),r.onerror(e)}});var rp=T((EN,np)=>{"use strict";var{kForOnEventAttribute:sn,kListener:cc}=Ve(),zf=Symbol("kCode"),Qf=Symbol("kData"),Xf=Symbol("kError"),Zf=Symbol("kMessage"),ep=Symbol("kReason"),rs=Symbol("kTarget"),tp=Symbol("kType"),sp=Symbol("kWasClean"),Je=class{constructor(e){this[rs]=null,this[tp]=e}get target(){return this[rs]}get type(){return this[tp]}};Object.defineProperty(Je.prototype,"target",{enumerable:!0});Object.defineProperty(Je.prototype,"type",{enumerable:!0});var Ot=class extends Je{constructor(e,t={}){super(e),this[zf]=t.code===void 0?0:t.code,this[ep]=t.reason===void 0?"":t.reason,this[sp]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[zf]}get reason(){return this[ep]}get wasClean(){return this[sp]}};Object.defineProperty(Ot.prototype,"code",{enumerable:!0});Object.defineProperty(Ot.prototype,"reason",{enumerable:!0});Object.defineProperty(Ot.prototype,"wasClean",{enumerable:!0});var is=class extends Je{constructor(e,t={}){super(e),this[Xf]=t.error===void 0?null:t.error,this[Zf]=t.message===void 0?"":t.message}get error(){return this[Xf]}get message(){return this[Zf]}};Object.defineProperty(is.prototype,"error",{enumerable:!0});Object.defineProperty(is.prototype,"message",{enumerable:!0});var nn=class extends Je{constructor(e,t={}){super(e),this[Qf]=t.data===void 0?null:t.data}get data(){return this[Qf]}};Object.defineProperty(nn.prototype,"data",{enumerable:!0});var l_={addEventListener(r,e,t={}){for(let n of this.listeners(r))if(!t[sn]&&n[cc]===e&&!n[sn])return;let s;if(r==="message")s=function(i,o){let a=new nn("message",{data:o?i:i.toString()});a[rs]=this,mi(e,this,a)};else if(r==="close")s=function(i,o){let a=new Ot("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[rs]=this,mi(e,this,a)};else if(r==="error")s=function(i){let o=new is("error",{error:i,message:i.message});o[rs]=this,mi(e,this,o)};else if(r==="open")s=function(){let i=new Je("open");i[rs]=this,mi(e,this,i)};else return;s[sn]=!!t[sn],s[cc]=e,t.once?this.once(r,s):this.on(r,s)},removeEventListener(r,e){for(let t of this.listeners(r))if(t[cc]===e&&!t[sn]){this.removeListener(r,t);break}}};np.exports={CloseEvent:Ot,ErrorEvent:is,Event:Je,EventTarget:l_,MessageEvent:nn};function mi(r,e,t){typeof r=="object"&&r.handleEvent?r.handleEvent.call(r,t):r.call(e,t)}});var gi=T((NN,ip)=>{"use strict";var{tokenChars:rn}=ts();function $e(r,e,t){r[e]===void 0?r[e]=[t]:r[e].push(t)}function d_(r){let e=Object.create(null),t=Object.create(null),s=!1,n=!1,i=!1,o,a,l=-1,c=-1,d=-1,u=0;for(;u<r.length;u++)if(c=r.charCodeAt(u),o===void 0)if(d===-1&&rn[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 m=r.slice(l,d);c===44?($e(e,m,t),t=Object.create(null)):o=m,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&rn[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,r.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=r.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(n){if(rn[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:s||(s=!0),n=!1}else if(i)if(rn[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)i=!1,d=u;else if(c===92)n=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&r.charCodeAt(u-1)===61)i=!0;else if(d===-1&&rn[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 m=r.slice(l,d);s&&(m=m.replace(/\\/g,""),s=!1),$e(t,a,m),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=r.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 u_(r){return Object.keys(r).map(e=>{let t=r[e];return Array.isArray(t)||(t=[t]),t.map(s=>[e].concat(Object.keys(s).map(n=>{let i=s[n];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?n:`${n}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}ip.exports={format:u_,parse:d_}});var ki=T((MN,yp)=>{"use strict";var h_=H("events"),f_=H("https"),p_=H("http"),cp=H("net"),m_=H("tls"),{randomBytes:g_,createHash:y_}=H("crypto"),{Duplex:xN,Readable:ON}=H("stream"),{URL:lc}=H("url"),mt=es(),w_=rc(),S_=ac(),{isBlob:k_}=ts(),{BINARY_TYPES:op,CLOSE_TIMEOUT:b_,EMPTY_BUFFER:yi,GUID:__,kForOnEventAttribute:dc,kListener:v_,kStatusCode:T_,kWebSocket:ie,NOOP:lp}=Ve(),{EventTarget:{addEventListener:I_,removeEventListener:C_}}=rp(),{format:A_,parse:E_}=gi(),{toBuffer:N_}=en(),dp=Symbol("kAborted"),uc=[8,13],ze=["CONNECTING","OPEN","CLOSING","CLOSED"],x_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,J=class r extends h_{constructor(e,t,s){super(),this._binaryType=op[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=yi,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=r.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]),up(this,e,t,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){op.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 n=new w_({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new S_(e,this._extensions,s.generateMask);this._receiver=n,this._sender=i,this._socket=e,n[ie]=this,i[ie]=this,e[ie]=this,n.on("conclude",D_),n.on("drain",L_),n.on("error",P_),n.on("message",$_),n.on("ping",R_),n.on("pong",B_),i.onerror=U_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",pp),e.on("data",Si),e.on("end",mp),e.on("error",gp),this._readyState=r.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[mt.extensionName]&&this._extensions[mt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=r.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===r.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=r.CLOSING,this._sender.close(e,t,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),fp(this)}}pause(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===r.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!==r.OPEN){hc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||yi,t,s)}pong(e,t,s){if(this.readyState===r.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!==r.OPEN){hc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||yi,t,s)}resume(){this.readyState===r.CONNECTING||this.readyState===r.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===r.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!==r.OPEN){hc(this,e,s);return}let n={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[mt.extensionName]||(n.compress=!1),this._sender.send(e||yi,n,s)}terminate(){if(this.readyState!==r.CLOSED){if(this.readyState===r.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=r.CLOSING,this._socket.destroy())}}};Object.defineProperty(J,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(J.prototype,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(J,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(J.prototype,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(J,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(J.prototype,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(J,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});Object.defineProperty(J.prototype,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(r=>{Object.defineProperty(J.prototype,r,{enumerable:!0})});["open","error","close","message"].forEach(r=>{Object.defineProperty(J.prototype,`on${r}`,{enumerable:!0,get(){for(let e of this.listeners(r))if(e[dc])return e[v_];return null},set(e){for(let t of this.listeners(r))if(t[dc]){this.removeListener(r,t);break}typeof e=="function"&&this.addEventListener(r,e,{[dc]:!0})}})});J.prototype.addEventListener=I_;J.prototype.removeEventListener=C_;yp.exports=J;function up(r,e,t,s){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:b_,protocolVersion:uc[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(r._autoPong=n.autoPong,r._closeTimeout=n.closeTimeout,!uc.includes(n.protocolVersion))throw new RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${uc.join(", ")})`);let i;if(e instanceof lc)i=e;else try{i=new lc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),r._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(r._redirects===0)throw f;wi(r,f);return}let c=o?443:80,d=g_(16).toString("base64"),u=o?f_.request:p_.request,h=new Set,m;if(n.createConnection=n.createConnection||(o?M_:O_),n.defaultPort=n.defaultPort||c,n.port=i.port||c,n.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},n.path=i.pathname+i.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate&&(m=new mt({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=A_({[mt.extensionName]:m.offer()})),t.length){for(let f of t){if(typeof f!="string"||!x_.test(f)||h.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(f)}n.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(n.origin&&(n.protocolVersion<13?n.headers["Sec-WebSocket-Origin"]=n.origin:n.headers.Origin=n.origin),(i.username||i.password)&&(n.auth=`${i.username}:${i.password}`),a){let f=n.path.split(":");n.socketPath=f[0],n.path=f[1]}let g;if(n.followRedirects){if(r._redirects===0){r._originalIpc=a,r._originalSecure=o,r._originalHostOrSocketPath=a?n.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(r.listenerCount("redirect")===0){let f=a?r._originalIpc?n.socketPath===r._originalHostOrSocketPath:!1:r._originalIpc?!1:i.host===r._originalHostOrSocketPath;(!f||r._originalSecure&&!o)&&(delete n.headers.authorization,delete n.headers.cookie,f||delete n.headers.host,n.auth=void 0)}n.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64")),g=r._req=u(n),r._redirects&&r.emit("redirect",r.url,g)}else g=r._req=u(n);n.timeout&&g.on("timeout",()=>{Se(r,g,"Opening handshake has timed out")}),g.on("error",f=>{g===null||g[dp]||(g=r._req=null,wi(r,f))}),g.on("response",f=>{let y=f.headers.location,w=f.statusCode;if(y&&n.followRedirects&&w>=300&&w<400){if(++r._redirects>n.maxRedirects){Se(r,g,"Maximum redirects exceeded");return}g.abort();let S;try{S=new lc(y,e)}catch{let v=new SyntaxError(`Invalid URL: ${y}`);wi(r,v);return}up(r,S,t,s)}else r.emit("unexpected-response",g,f)||Se(r,g,`Unexpected server response: ${f.statusCode}`)}),g.on("upgrade",(f,y,w)=>{if(r.emit("upgrade",f),r.readyState!==J.CONNECTING)return;g=r._req=null;let S=f.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){Se(r,y,"Invalid Upgrade header");return}let _=y_("sha1").update(d+__).digest("base64");if(f.headers["sec-websocket-accept"]!==_){Se(r,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(r,y,I);return}v&&(r._protocol=v);let N=f.headers["sec-websocket-extensions"];if(N!==void 0){if(!m){Se(r,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let D;try{D=E_(N)}catch{Se(r,y,"Invalid Sec-WebSocket-Extensions header");return}let C=Object.keys(D);if(C.length!==1||C[0]!==mt.extensionName){Se(r,y,"Server indicated an extension that was not requested");return}try{m.accept(D[mt.extensionName])}catch{Se(r,y,"Invalid Sec-WebSocket-Extensions header");return}r._extensions[mt.extensionName]=m}r.setSocket(y,w,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest?n.finishRequest(g,r):g.end()}function wi(r,e){r._readyState=J.CLOSING,r._errorEmitted=!0,r.emit("error",e),r.emitClose()}function O_(r){return r.path=r.socketPath,cp.connect(r)}function M_(r){return r.path=void 0,!r.servername&&r.servername!==""&&(r.servername=cp.isIP(r.host)?"":r.host),m_.connect(r)}function Se(r,e,t){r._readyState=J.CLOSING;let s=new Error(t);Error.captureStackTrace(s,Se),e.setHeader?(e[dp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(wi,r,s)):(e.destroy(s),e.once("error",r.emit.bind(r,"error")),e.once("close",r.emitClose.bind(r)))}function hc(r,e,t){if(e){let s=k_(e)?e.size:N_(e).length;r._socket?r._sender._bufferedBytes+=s:r._bufferedAmount+=s}if(t){let s=new Error(`WebSocket is not open: readyState ${r.readyState} (${ze[r.readyState]})`);process.nextTick(t,s)}}function D_(r,e){let t=this[ie];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=r,t._socket[ie]!==void 0&&(t._socket.removeListener("data",Si),process.nextTick(hp,t._socket),r===1005?t.close():t.close(r,e))}function L_(){let r=this[ie];r.isPaused||r._socket.resume()}function P_(r){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",Si),process.nextTick(hp,e._socket),e.close(r[T_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r))}function ap(){this[ie].emitClose()}function $_(r,e){this[ie].emit("message",r,e)}function R_(r){let e=this[ie];e._autoPong&&e.pong(r,!this._isServer,lp),e.emit("ping",r)}function B_(r){this[ie].emit("pong",r)}function hp(r){r.resume()}function U_(r){let e=this[ie];e.readyState!==J.CLOSED&&(e.readyState===J.OPEN&&(e._readyState=J.CLOSING,fp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",r)))}function fp(r){r._closeTimer=setTimeout(r._socket.destroy.bind(r._socket),r._closeTimeout)}function pp(){let r=this[ie];if(this.removeListener("close",pp),this.removeListener("data",Si),this.removeListener("end",mp),r._readyState=J.CLOSING,!this._readableState.endEmitted&&!r._closeFrameReceived&&!r._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);r._receiver.write(e)}r._receiver.end(),this[ie]=void 0,clearTimeout(r._closeTimer),r._receiver._writableState.finished||r._receiver._writableState.errorEmitted?r.emitClose():(r._receiver.on("error",ap),r._receiver.on("finish",ap))}function Si(r){this[ie]._receiver.write(r)||this.pause()}function mp(){let r=this[ie];r._readyState=J.CLOSING,r._receiver.end(),this.end()}function gp(){let r=this[ie];this.removeListener("error",gp),this.on("error",lp),r&&(r._readyState=J.CLOSING,this.destroy())}});var bp=T((LN,kp)=>{"use strict";var DN=ki(),{Duplex:q_}=H("stream");function wp(r){r.emit("close")}function j_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Sp(r){this.removeListener("error",Sp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",r)}function F_(r,e){let t=!0,s=new q_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return r.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||r.pause()}),r.once("error",function(i){s.destroyed||(t=!1,s.destroy(i))}),r.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(n,i){if(r.readyState===r.CLOSED){i(n),process.nextTick(wp,s);return}let o=!1;r.once("error",function(l){o=!0,i(l)}),r.once("close",function(){o||i(n),process.nextTick(wp,s)}),t&&r.terminate()},s._final=function(n){if(r.readyState===r.CONNECTING){r.once("open",function(){s._final(n)});return}r._socket!==null&&(r._socket._writableState.finished?(n(),s._readableState.endEmitted&&s.destroy()):(r._socket.once("finish",function(){n()}),r.close()))},s._read=function(){r.isPaused&&r.resume()},s._write=function(n,i,o){if(r.readyState===r.CONNECTING){r.once("open",function(){s._write(n,i,o)});return}r.send(n,o)},s.on("end",j_),s.on("error",Sp),s}kp.exports=F_});var fc=T((PN,_p)=>{"use strict";var{tokenChars:K_}=ts();function H_(r){let e=new Set,t=-1,s=-1,n=0;for(n;n<r.length;n++){let o=r.charCodeAt(n);if(s===-1&&K_[o]===1)t===-1&&(t=n);else if(n!==0&&(o===32||o===9))s===-1&&t!==-1&&(s=n);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${n}`);s===-1&&(s=n);let a=r.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 ${n}`)}if(t===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=r.slice(t,n);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}_p.exports={parse:H_}});var Np=T((RN,Ep)=>{"use strict";var W_=H("events"),bi=H("http"),{Duplex:$N}=H("stream"),{createHash:G_}=H("crypto"),vp=gi(),Mt=es(),V_=fc(),Y_=ki(),{CLOSE_TIMEOUT:J_,GUID:z_,kWebSocket:Q_}=Ve(),X_=/^[+/0-9A-Za-z]{22}==$/,Tp=0,Ip=1,Ap=2,pc=class extends W_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:J_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Y_,...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=bi.createServer((s,n)=>{let i=bi.STATUS_CODES[426];n.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),n.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=Z_(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(n,i,o)=>{this.handleUpgrade(n,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Tp}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===Ap){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(on,this);return}if(e&&this.once("close",e),this._state!==Ip)if(this._state=Ip,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(on,this):process.nextTick(on,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{on(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,n){t.on("error",Cp);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Dt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Dt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!X_.test(i)){Dt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Dt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){an(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=V_.parse(l)}catch{Dt(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 Mt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let m=vp.parse(d);m[Mt.extensionName]&&(h.accept(m[Mt.extensionName]),u[Mt.extensionName]=h)}catch{Dt(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,(m,g,f,y)=>{if(!m)return an(t,g||401,f,y);this.completeUpgrade(u,i,c,e,t,s,n)});return}if(!this.options.verifyClient(h))return an(t,401)}this.completeUpgrade(u,i,c,e,t,s,n)}completeUpgrade(e,t,s,n,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[Q_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Tp)return an(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${G_("sha1").update(t+z_).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(s.size){let u=this.options.handleProtocols?this.options.handleProtocols(s,n):s.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Mt.extensionName]){let u=e[Mt.extensionName].params,h=vp.format({[Mt.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",c,n),i.write(c.concat(`\r
210
210
  `).join(`\r
211
- `)),i.removeListener("error",Ip),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(on,this)})),a(d,n)}};Ap.exports=pc;function Z_(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let s of Object.keys(e))r.removeListener(s,e[s])}}function on(r){r._state=Cp,r.emit("close")}function Ip(){this.destroy()}function an(r,e,t,s){t=t||bi.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...s},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${bi.STATUS_CODES[e]}\r
211
+ `)),i.removeListener("error",Cp),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(on,this)})),a(d,n)}};Ep.exports=pc;function Z_(r,e){for(let t of Object.keys(e))r.on(t,e[t]);return function(){for(let s of Object.keys(e))r.removeListener(s,e[s])}}function on(r){r._state=Ap,r.emit("close")}function Cp(){this.destroy()}function an(r,e,t,s){t=t||bi.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...s},r.once("finish",r.destroy),r.end(`HTTP/1.1 ${e} ${bi.STATUS_CODES[e]}\r
212
212
  `+Object.keys(s).map(n=>`${n}: ${s[n]}`).join(`\r
213
213
  `)+`\r
214
214
  \r
215
- `+t)}function Dt(r,e,t,s,n,i){if(r.listenerCount("wsClientError")){let o=new Error(n);Error.captureStackTrace(o,Dt),r.emit("wsClientError",o,t,e)}else an(t,s,n,i)}});var ev,tv,sv,nv,rv,iv,cn,mc,Np=j(()=>{ev=Ce(kp(),1),tv=Ce(gi(),1),sv=Ce(es(),1),nv=Ce(rc(),1),rv=Ce(ac(),1),iv=Ce(fc(),1),cn=Ce(ki(),1),mc=Ce(Ep(),1)});function xp(r){let e;try{e=JSON.parse(r)}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 Op(r){return(r.type==="message"||r.type==="image"||r.type==="file")&&"channelId"in r}var Mp=j(()=>{"use strict"});var Lp={};Ue(Lp,{WsAdapter:()=>gc});import{createServer as ov}from"node:http";import{randomUUID as ln}from"node:crypto";function Dp(r){let e=r.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,gc,Pp=j(()=>{"use strict";Np();O();Mp();Ys();Te=k("ws-adapter"),gc=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=ov(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 n=new URL(t.url??"/",`http://localhost:${this.port}`);if(t.method==="GET"&&n.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 mc.default({noServer:!0,maxPayload:10*1024*1024}),this.server.on("upgrade",(t,s,n)=>{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
215
+ `+t)}function Dt(r,e,t,s,n,i){if(r.listenerCount("wsClientError")){let o=new Error(n);Error.captureStackTrace(o,Dt),r.emit("wsClientError",o,t,e)}else an(t,s,n,i)}});var ev,tv,sv,nv,rv,iv,cn,mc,xp=j(()=>{ev=Ce(bp(),1),tv=Ce(gi(),1),sv=Ce(es(),1),nv=Ce(rc(),1),rv=Ce(ac(),1),iv=Ce(fc(),1),cn=Ce(ki(),1),mc=Ce(Np(),1)});function Op(r){let e;try{e=JSON.parse(r)}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 Mp(r){return(r.type==="message"||r.type==="image"||r.type==="file")&&"channelId"in r}var Dp=j(()=>{"use strict"});var Pp={};Ue(Pp,{WsAdapter:()=>gc});import{createServer as ov}from"node:http";import{randomUUID as ln}from"node:crypto";function Lp(r){let e=r.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,gc,$p=j(()=>{"use strict";xp();O();Dp();Ys();Te=k("ws-adapter"),gc=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=ov(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 n=new URL(t.url??"/",`http://localhost:${this.port}`);if(t.method==="GET"&&n.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 mc.default({noServer:!0,maxPayload:10*1024*1024}),this.server.on("upgrade",(t,s,n)=>{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
216
216
  \r
217
217
  `),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
218
218
  \r
219
219
  `),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
220
220
  \r
221
- `),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,n,m=>{this.wss.emit("connection",m,t,h)})}),this.wss.on("connection",(t,s,n)=>{let i=n._id;Te.info("Device connected",{deviceId:i,label:n.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=xp(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,n,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(Op(c)){c.type==="message"?await this.handleTeamMessage(t,c,n,i):c.type==="image"?await this.handleTeamImage(t,c,n,i):c.type==="file"&&await this.handleTeamFile(t,c,n,i);return}if(c.type==="message"){this.send(t,{type:"ack",id:c.id});let d={id:c.id||ln(),text:c.text,source:{kind:"app",id:i,label:`app:${n.label}`,adapterId:"ws"},sender:i,senderName:n.label,threadId:`app:${i}`,timestamp:new Date,meta:{deviceId:i,defaultAgentId:n.defaultAgentId,origin:n.origin}};this.onWorkItem(d)}if(c.type==="image"){this.send(t,{type:"ack",id:c.id});let d=Buffer.from(c.data,"base64"),u=Dp(c.filename);try{let h=await Vs(d,c.filename,u),m={id:c.id||ln(),text:`[Photo: ${c.filename}]`,source:{kind:"app",id:i,label:`app:${n.label}`,adapterId:"ws"},sender:i,senderName:n.label,threadId:`app:${i}`,timestamp:new Date,files:[h],meta:{deviceId:i,defaultAgentId:n.defaultAgentId,origin:n.origin}};this.onWorkItem(m)}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,n=e.workItem.meta?.channelId,i=this.agentRegistry.get(e.agentId)?.name??e.agentId;n&&await this.teamStore.saveMessage({channelId:n,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,...n?{channelId:n}:{}},a=this.connections.get(t);if(a&&a.readyState===cn.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 n=this.connections.get(s);n&&n.readyState===cn.default.OPEN&&this.send(n,{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 n=await this.teamStore.getChannel(t);return n?n.members.includes(s)?n:(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,n){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,n);if(!i)return;await this.teamStore.saveMessage({channelId:t.channelId,threadId:t.threadId,senderId:n,senderType:"person",senderName:s.label,text:t.text,createdAt:new Date});let o=i.type==="dm"?i.members.find(l=>l!==n):void 0,a={id:t.id||ln(),text:t.text,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:n,senderName:s.label,threadId:t.threadId??`team:${t.channelId}`,timestamp:new Date,meta:{deviceId:n,channelId:t.channelId,...s.user?{user:s.user}:{},...o?{targetAgentId:o}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(a)}async handleTeamImage(e,t,s,n){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,n);if(!i)return;let o=Buffer.from(t.data,"base64"),a=Dp(t.filename);try{let l=await Vs(o,t.filename,a);await this.teamStore.saveMessage({channelId:t.channelId,senderId:n,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!==n):void 0,d={id:t.id||ln(),text:`[Photo: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:n,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[l],meta:{deviceId:n,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:n,filename:t.filename,error:String(l)}),this.send(e,{type:"error",message:"Failed to process image"})}}async handleTeamFile(e,t,s,n){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,n);if(!i)return;let o=Buffer.from(t.data,"base64");try{let a=t.mimetype.startsWith("image/")?await Vs(o,t.filename,t.mimetype):await Ph(o,t.filename,t.mimetype);await this.teamStore.saveMessage({channelId:t.channelId,senderId:n,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!==n):void 0,c={id:t.id||ln(),text:`[File: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:n,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[a],meta:{deviceId:n,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:n,filename:t.filename,error:String(a)}),this.send(e,{type:"error",message:"Failed to process file"})}}async handleCommand(e,t,s,n){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:n,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(n=>({name:n.name,description:n.description,args:n.args})),id:t.id})}async handleChannelList(e,t,s){let n=await this.teamStore.listChannels(s);this.send(e,{type:"channel_list",channels:n.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:n,hasMore:i}=await this.teamStore.getHistory(t.channelId,{before:t.before,limit:t.limit});this.send(e,{type:"history",channelId:t.channelId,messages:n.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===cn.default.OPEN&&e.send(JSON.stringify(t))}}});var $p={};Ue($p,{startBeekeeperRegistration:()=>av});function av(r){let{beekeeperPort:e,wsPort:t}=r,s=r.intervalMs??3e4,n=`http://127.0.0.1:${e}/internal/register-capability`,i={name:r.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(n,{method:"POST",headers:{"content-type":"application/json"},body:o});if(c.ok)yc.debug("Registered with beekeeper",{beekeeperPort:e,wsPort:t});else{let d=await c.text().catch(()=>"");yc.warn("Beekeeper registration failed",{status:c.status,body:d})}}catch(c){yc.warn("Beekeeper registration error",{error:String(c)})}};a();let l=setInterval(()=>{a()},s);return{stop:()=>clearInterval(l)}}var yc,Rp=j(()=>{"use strict";O();yc=k("beekeeper-client")});async function Bp(r,e,t){let s=[];r.soul&&s.push(r.soul),s.push(r.systemPrompt);let n=await e.read("shared/constitution.md");n&&s.push(n),s.push(`## Voice Call Mode
221
+ `),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,n,m=>{this.wss.emit("connection",m,t,h)})}),this.wss.on("connection",(t,s,n)=>{let i=n._id;Te.info("Device connected",{deviceId:i,label:n.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=Op(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,n,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(Mp(c)){c.type==="message"?await this.handleTeamMessage(t,c,n,i):c.type==="image"?await this.handleTeamImage(t,c,n,i):c.type==="file"&&await this.handleTeamFile(t,c,n,i);return}if(c.type==="message"){this.send(t,{type:"ack",id:c.id});let d={id:c.id||ln(),text:c.text,source:{kind:"app",id:i,label:`app:${n.label}`,adapterId:"ws"},sender:i,senderName:n.label,threadId:`app:${i}`,timestamp:new Date,meta:{deviceId:i,defaultAgentId:n.defaultAgentId,origin:n.origin}};this.onWorkItem(d)}if(c.type==="image"){this.send(t,{type:"ack",id:c.id});let d=Buffer.from(c.data,"base64"),u=Lp(c.filename);try{let h=await Vs(d,c.filename,u),m={id:c.id||ln(),text:`[Photo: ${c.filename}]`,source:{kind:"app",id:i,label:`app:${n.label}`,adapterId:"ws"},sender:i,senderName:n.label,threadId:`app:${i}`,timestamp:new Date,files:[h],meta:{deviceId:i,defaultAgentId:n.defaultAgentId,origin:n.origin}};this.onWorkItem(m)}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,n=e.workItem.meta?.channelId,i=this.agentRegistry.get(e.agentId)?.name??e.agentId;n&&await this.teamStore.saveMessage({channelId:n,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,...n?{channelId:n}:{}},a=this.connections.get(t);if(a&&a.readyState===cn.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 n=this.connections.get(s);n&&n.readyState===cn.default.OPEN&&this.send(n,{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 n=await this.teamStore.getChannel(t);return n?n.members.includes(s)?n:(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,n){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,n);if(!i)return;await this.teamStore.saveMessage({channelId:t.channelId,threadId:t.threadId,senderId:n,senderType:"person",senderName:s.label,text:t.text,createdAt:new Date});let o=i.type==="dm"?i.members.find(l=>l!==n):void 0,a={id:t.id||ln(),text:t.text,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:n,senderName:s.label,threadId:t.threadId??`team:${t.channelId}`,timestamp:new Date,meta:{deviceId:n,channelId:t.channelId,...s.user?{user:s.user}:{},...o?{targetAgentId:o}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(a)}async handleTeamImage(e,t,s,n){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,n);if(!i)return;let o=Buffer.from(t.data,"base64"),a=Lp(t.filename);try{let l=await Vs(o,t.filename,a);await this.teamStore.saveMessage({channelId:t.channelId,senderId:n,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!==n):void 0,d={id:t.id||ln(),text:`[Photo: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:n,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[l],meta:{deviceId:n,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:n,filename:t.filename,error:String(l)}),this.send(e,{type:"error",message:"Failed to process image"})}}async handleTeamFile(e,t,s,n){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,n);if(!i)return;let o=Buffer.from(t.data,"base64");try{let a=t.mimetype.startsWith("image/")?await Vs(o,t.filename,t.mimetype):await Ph(o,t.filename,t.mimetype);await this.teamStore.saveMessage({channelId:t.channelId,senderId:n,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!==n):void 0,c={id:t.id||ln(),text:`[File: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:n,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[a],meta:{deviceId:n,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:n,filename:t.filename,error:String(a)}),this.send(e,{type:"error",message:"Failed to process file"})}}async handleCommand(e,t,s,n){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:n,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(n=>({name:n.name,description:n.description,args:n.args})),id:t.id})}async handleChannelList(e,t,s){let n=await this.teamStore.listChannels(s);this.send(e,{type:"channel_list",channels:n.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:n,hasMore:i}=await this.teamStore.getHistory(t.channelId,{before:t.before,limit:t.limit});this.send(e,{type:"history",channelId:t.channelId,messages:n.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===cn.default.OPEN&&e.send(JSON.stringify(t))}}});var Rp={};Ue(Rp,{startBeekeeperRegistration:()=>av});function av(r){let{beekeeperPort:e,wsPort:t}=r,s=r.intervalMs??3e4,n=`http://127.0.0.1:${e}/internal/register-capability`,i={name:r.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(n,{method:"POST",headers:{"content-type":"application/json"},body:o});if(c.ok)yc.debug("Registered with beekeeper",{beekeeperPort:e,wsPort:t});else{let d=await c.text().catch(()=>"");yc.warn("Beekeeper registration failed",{status:c.status,body:d})}}catch(c){yc.warn("Beekeeper registration error",{error:String(c)})}};a();let l=setInterval(()=>{a()},s);return{stop:()=>clearInterval(l)}}var yc,Bp=j(()=>{"use strict";O();yc=k("beekeeper-client")});async function Up(r,e,t){let s=[];r.soul&&s.push(r.soul),s.push(r.systemPrompt);let n=await e.read("shared/constitution.md");n&&s.push(n),s.push(`## Voice Call Mode
222
222
 
223
223
  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
224
224
 
@@ -229,20 +229,20 @@ ${c}`)}let a=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",w
229
229
 
230
230
  ---
231
231
 
232
- `)}var Up=j(()=>{"use strict";Ne()});function qp(r,e){let t=[];for(let s of r)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 n=[];s.content&&n.push({type:"text",text:s.content});for(let i of s.tool_calls)n.push({type:"tool_use",id:i.id,name:i.function.name,input:cv(i.function.arguments)});t.push({role:"assistant",content:n})}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 jp(r){if(!(!r||r.length===0))return r.map(e=>({name:e.function.name,description:e.function.description??"",input_schema:e.function.parameters??{type:"object",properties:{}}}))}function Fp(r,e,t){let s={id:r,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)}
232
+ `)}var qp=j(()=>{"use strict";Ne()});function jp(r,e){let t=[];for(let s of r)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 n=[];s.content&&n.push({type:"text",text:s.content});for(let i of s.tool_calls)n.push({type:"tool_use",id:i.id,name:i.function.name,input:cv(i.function.arguments)});t.push({role:"assistant",content:n})}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 Fp(r){if(!(!r||r.length===0))return r.map(e=>({name:e.function.name,description:e.function.description??"",input_schema:e.function.parameters??{type:"object",properties:{}}}))}function Kp(r,e,t){let s={id:r,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)}
233
233
 
234
234
  `}function wc(r,e,t="stop"){let s={id:r,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:{},finish_reason:t}]};return`data: ${JSON.stringify(s)}
235
235
 
236
236
  data: [DONE]
237
237
 
238
- `}function Kp(r,e,t){return{id:r,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}]}}function cv(r){if(!r)return{};try{return JSON.parse(r)}catch{return{}}}var Hp=j(()=>{"use strict"});var Gp={};Ue(Gp,{VoiceAdapter:()=>Sc});import{createServer as lv}from"node:http";import dv from"@anthropic-ai/sdk";import{randomUUID as Wp}from"node:crypto";function hv(r){return new Promise((e,t)=>{let s=[];r.on("data",n=>s.push(n)),r.on("end",()=>e(Buffer.concat(s).toString("utf-8"))),r.on("error",t)})}var Re,uv,Sc,Vp=j(()=>{"use strict";O();Up();Hp();Ne();Re=k("voice-adapter"),uv=7200*1e3,Sc=class{port;serverSecret;registry;memoryManager;httpServer;anthropic;sessions=new Map;sweepTimer;constructor(e,t,s,n){this.port=e,this.serverSecret=t,this.registry=s,this.memoryManager=n,this.anthropic=new dv}async start(){this.httpServer=lv((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,n]of this.sessions)e-n.startedAt.getTime()>uv&&(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 n=await hv(e),i;try{i=JSON.parse(n)}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??Wp();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 Bp(a,this.memoryManager,{goal:c?.goal,context:c?.context}),{system:u,messages:h}=qp(i.messages,d),m=jp(i.tools),g=a.model,f=`chatcmpl-${Wp()}`;if(i.stream===!1){let S=(await this.anthropic.messages.create({model:g,max_tokens:1024,system:u,messages:h,...m?{tools:m}:{}})).content.filter(_=>_.type==="text").map(_=>_.text).join("");t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(Kp(f,S,g)));return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{let y=this.anthropic.messages.stream({model:g,max_tokens:1024,system:u,messages:h,...m?{tools:m}:{}});for await(let w of y)if(w.type==="content_block_delta"){let S=w.delta;S.type==="text_delta"&&t.write(Fp(f,S.text??"",g))}t.writableEnded||t.write(wc(f,g))}catch(y){Re.error("Claude streaming error",{error:String(y),callId:l,agentId:o}),t.writableEnded||t.write(wc(f,g,"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&&p.voice.assistants[s])return p.voice.assistants[s];let n=e.call?.metadata;if(n?.hive_agent_id)return n.hive_agent_id}}});ls();Ei();import{existsSync as kc,watch as fv}from"node:fs";import{resolve as Yp}from"node:path";import{MongoClient as pv}from"mongodb";O();import{existsSync as Lc,readFileSync as Pc,readdirSync as cm,statSync as Ev,writeFileSync as Nv,mkdirSync as xv}from"node:fs";import{resolve as $c,join as Mv}from"node:path";import{createHash as lm}from"node:crypto";var Ni=k("integrity");function Rc(r,e){let t=$c(e,"installed-snapshot.json");if(!Lc(t))return Ni.warn("No installed-snapshot.json \u2014 skipping integrity check (first install?)"),{ok:!0,warnings:[]};let s=JSON.parse(Pc(t,"utf-8"));if(!Array.isArray(s))return{ok:!1,warnings:[`installed-snapshot.json is malformed (expected array, got ${typeof s})`]};let n=s,i=[];for(let o of n){let a=$c(r,o.path);if(!Lc(a)){i.push(`missing: ${o.path}`);continue}let l=Pc(a);lm("sha256").update(l).digest("hex")!==o.hash&&i.push(`modified: ${o.path}`)}if(i.length>0)throw Ni.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:
238
+ `}function Hp(r,e,t){return{id:r,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}]}}function cv(r){if(!r)return{};try{return JSON.parse(r)}catch{return{}}}var Wp=j(()=>{"use strict"});var Vp={};Ue(Vp,{VoiceAdapter:()=>Sc});import{createServer as lv}from"node:http";import dv from"@anthropic-ai/sdk";import{randomUUID as Gp}from"node:crypto";function hv(r){return new Promise((e,t)=>{let s=[];r.on("data",n=>s.push(n)),r.on("end",()=>e(Buffer.concat(s).toString("utf-8"))),r.on("error",t)})}var Re,uv,Sc,Yp=j(()=>{"use strict";O();qp();Wp();Ne();Re=k("voice-adapter"),uv=7200*1e3,Sc=class{port;serverSecret;registry;memoryManager;httpServer;anthropic;sessions=new Map;sweepTimer;constructor(e,t,s,n){this.port=e,this.serverSecret=t,this.registry=s,this.memoryManager=n,this.anthropic=new dv}async start(){this.httpServer=lv((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,n]of this.sessions)e-n.startedAt.getTime()>uv&&(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 n=await hv(e),i;try{i=JSON.parse(n)}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??Gp();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 Up(a,this.memoryManager,{goal:c?.goal,context:c?.context}),{system:u,messages:h}=jp(i.messages,d),m=Fp(i.tools),g=a.model,f=`chatcmpl-${Gp()}`;if(i.stream===!1){let S=(await this.anthropic.messages.create({model:g,max_tokens:1024,system:u,messages:h,...m?{tools:m}:{}})).content.filter(_=>_.type==="text").map(_=>_.text).join("");t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(Hp(f,S,g)));return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{let y=this.anthropic.messages.stream({model:g,max_tokens:1024,system:u,messages:h,...m?{tools:m}:{}});for await(let w of y)if(w.type==="content_block_delta"){let S=w.delta;S.type==="text_delta"&&t.write(Kp(f,S.text??"",g))}t.writableEnded||t.write(wc(f,g))}catch(y){Re.error("Claude streaming error",{error:String(y),callId:l,agentId:o}),t.writableEnded||t.write(wc(f,g,"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&&p.voice.assistants[s])return p.voice.assistants[s];let n=e.call?.metadata;if(n?.hive_agent_id)return n.hive_agent_id}}});ls();Ei();import{existsSync as kc,watch as fv}from"node:fs";import{resolve as Jp}from"node:path";import{MongoClient as pv}from"mongodb";O();import{existsSync as Lc,readFileSync as Pc,readdirSync as lm,statSync as Ev,writeFileSync as Nv,mkdirSync as xv}from"node:fs";import{resolve as $c,join as Mv}from"node:path";import{createHash as dm}from"node:crypto";var Ni=k("integrity");function Rc(r,e){let t=$c(e,"installed-snapshot.json");if(!Lc(t))return Ni.warn("No installed-snapshot.json \u2014 skipping integrity check (first install?)"),{ok:!0,warnings:[]};let s=JSON.parse(Pc(t,"utf-8"));if(!Array.isArray(s))return{ok:!1,warnings:[`installed-snapshot.json is malformed (expected array, got ${typeof s})`]};let n=s,i=[];for(let o of n){let a=$c(r,o.path);if(!Lc(a)){i.push(`missing: ${o.path}`);continue}let l=Pc(a);dm("sha256").update(l).digest("hex")!==o.hash&&i.push(`modified: ${o.path}`)}if(i.length>0)throw Ni.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:
239
239
  `+i.map(o=>` - ${o}`).join(`
240
240
  `)+`
241
- Reinstall with: npm install @keepur/hive@<version>`);return{ok:!0,warnings:[]}}function Bc(r){let e=["skills","plugins","workflow","data","agents","logs",".hive",".hive-state",".env","hive.yaml","hive-","beekeeper.yaml",".hive-generated.json"];try{let t=cm(r),s=[];for(let n of t)e.some(i=>n.startsWith(i))||s.push(n);s.length>0&&Ni.warn("Unexpected files in instance directory",{files:s})}catch{}}O();import{existsSync as xi,readFileSync as dm,writeFileSync as um,mkdirSync as hm}from"node:fs";import{resolve as Oi}from"node:path";var Uc=k("upgrade-notice");function qc(r,e){let t=Oi(r,"upgrade-notice-emitted");if(xi(t))return;let s=Oi(r,"previous-snapshot.json");if(xi(s))try{let n=JSON.parse(dm(s,"utf-8")),i=[];for(let l of n)if(typeof l.path=="string"&&l.path.startsWith("skills/")&&l.path.endsWith("SKILL.md")){let c=l.path.match(/^skills\/([^/]+)\//);c&&!xi(Oi(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(`
242
- `);Uc.info(a),hm(r,{recursive:!0}),um(t,new Date().toISOString())}catch(n){Uc.warn("Failed to check upgrade notice",{error:String(n)})}}Ne();O();O();ma();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 ju(r,e){return{id:r._id,name:r.name,aliases:r.aliases??[],model:r.model,channels:r.channels??[],homeBase:r.homeBase,catches:r.catches,passiveChannels:r.passiveChannels??X.passiveChannels,keywords:r.keywords??X.keywords,isDefault:r.isDefault??!1,schedule:r.schedule??X.schedule,budgetUsd:r.budgetUsd??X.budgetUsd,maxTurns:r.maxTurns??X.maxTurns,icon:r.icon??X.icon,slackBot:r.slackBot,coreServers:r.coreServers??[...X.coreServers],delegateServers:r.delegateServers??[...X.delegateServers],plugins:r.plugins,maxConcurrent:r.maxConcurrent??X.maxConcurrent,timeoutMs:r.timeoutMs??X.timeoutMs,betas:r.betas,metadata:r.metadata,disabled:r.disabled??!1,subscribe:r.subscribe??[],resourceTiers:r.resourceTiers,delegatePrompts:r.delegatePrompts??X.delegatePrompts,soul:r.soul??"",systemPrompt:r.systemPrompt??"",archetype:r.archetype,title:r.title,archetypeConfig:r.archetypeConfig,autonomy:Lu(e,r.autonomy)}}Ne();mr();mr();import{statSync as a0}from"node:fs";import{normalize as Hu,resolve as Wu}from"node:path";var Gu=new Set(["linear","github","clickup"]);function Yu(r){if(!r||typeof r!="object")throw new Error("software-engineer archetypeConfig must be an object");let e=r;if(typeof e.workshop!="string"||!e.workshop.startsWith("/"))throw new Error("workshop must be an absolute path");let t=Hu(e.workshop);Vu(t,"workshop");let s=e.workspaces??[];if(!Array.isArray(s))throw new Error("workspaces must be an array");let n=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(n.has(l.name))throw new Error(`workspaces[${a}]: duplicate workspace name "${l.name}"`);if(n.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=Hu(l.path);Vu(c,`workspaces[${a}] (${l.name})`);let d=Wu(c),u=Wu(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"||!Gu.has(h.type))throw new Error(`workspaces[${a}] (${l.name}): tracker.type must be one of: ${[...Gu].join(", ")}`);return c0(h,a,l.name),{name:l.name,path:c,tracker:h,...l.primary===!0?{primary:!0}:{}}});return{workshop:t,workspaces:i}}function Vu(r,e){let t;try{t=a0(r)}catch{throw new Error(`${e}: path does not exist: ${r}`)}if(!t.isDirectory())throw new Error(`${e}: path is not a directory: ${r}`)}function c0(r,e,t){switch(r.type){case"linear":if(typeof r.project!="string"||r.project.length===0)throw new Error(`workspaces[${e}] (${t}): linear tracker requires project`);break;case"github":if(typeof r.repo!="string"||r.repo.length===0)throw new Error(`workspaces[${e}] (${t}): github tracker requires repo`);break;case"clickup":if(typeof r.list!="string"||r.list.length===0)throw new Error(`workspaces[${e}] (${t}): clickup tracker requires list`);break}}function Ju(r){let e=r.archetypeConfig,t=r.agentConfig.title||r.agentConfig.name,s=[];s.push(`# Software Engineer
241
+ Reinstall with: npm install @keepur/hive@<version>`);return{ok:!0,warnings:[]}}function Bc(r){let e=["skills","plugins","workflow","data","agents","logs",".hive",".hive-state",".env","hive.yaml","hive-","beekeeper.yaml",".hive-generated.json"];try{let t=lm(r),s=[];for(let n of t)e.some(i=>n.startsWith(i))||s.push(n);s.length>0&&Ni.warn("Unexpected files in instance directory",{files:s})}catch{}}O();import{existsSync as xi,readFileSync as um,writeFileSync as hm,mkdirSync as fm}from"node:fs";import{resolve as Oi}from"node:path";var Uc=k("upgrade-notice");function qc(r,e){let t=Oi(r,"upgrade-notice-emitted");if(xi(t))return;let s=Oi(r,"previous-snapshot.json");if(xi(s))try{let n=JSON.parse(um(s,"utf-8")),i=[];for(let l of n)if(typeof l.path=="string"&&l.path.startsWith("skills/")&&l.path.endsWith("SKILL.md")){let c=l.path.match(/^skills\/([^/]+)\//);c&&!xi(Oi(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(`
242
+ `);Uc.info(a),fm(r,{recursive:!0}),hm(t,new Date().toISOString())}catch(n){Uc.warn("Failed to check upgrade notice",{error:String(n)})}}Ne();O();O();ma();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 ju(r,e){return{id:r._id,name:r.name,aliases:r.aliases??[],model:r.model,channels:r.channels??[],homeBase:r.homeBase,catches:r.catches,passiveChannels:r.passiveChannels??X.passiveChannels,keywords:r.keywords??X.keywords,isDefault:r.isDefault??!1,schedule:r.schedule??X.schedule,budgetUsd:r.budgetUsd??X.budgetUsd,maxTurns:r.maxTurns??X.maxTurns,icon:r.icon??X.icon,slackBot:r.slackBot,coreServers:r.coreServers??[...X.coreServers],delegateServers:r.delegateServers??[...X.delegateServers],plugins:r.plugins,maxConcurrent:r.maxConcurrent??X.maxConcurrent,timeoutMs:r.timeoutMs??X.timeoutMs,betas:r.betas,metadata:r.metadata,disabled:r.disabled??!1,subscribe:r.subscribe??[],resourceTiers:r.resourceTiers,delegatePrompts:r.delegatePrompts??X.delegatePrompts,soul:r.soul??"",systemPrompt:r.systemPrompt??"",archetype:r.archetype,title:r.title,archetypeConfig:r.archetypeConfig,autonomy:Lu(e,r.autonomy)}}Ne();mr();mr();import{statSync as c0}from"node:fs";import{normalize as Hu,resolve as Wu}from"node:path";var Gu=new Set(["linear","github","clickup"]);function Yu(r){if(!r||typeof r!="object")throw new Error("software-engineer archetypeConfig must be an object");let e=r;if(typeof e.workshop!="string"||!e.workshop.startsWith("/"))throw new Error("workshop must be an absolute path");let t=Hu(e.workshop);Vu(t,"workshop");let s=e.workspaces??[];if(!Array.isArray(s))throw new Error("workspaces must be an array");let n=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(n.has(l.name))throw new Error(`workspaces[${a}]: duplicate workspace name "${l.name}"`);if(n.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=Hu(l.path);Vu(c,`workspaces[${a}] (${l.name})`);let d=Wu(c),u=Wu(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"||!Gu.has(h.type))throw new Error(`workspaces[${a}] (${l.name}): tracker.type must be one of: ${[...Gu].join(", ")}`);return l0(h,a,l.name),{name:l.name,path:c,tracker:h,...l.primary===!0?{primary:!0}:{}}});return{workshop:t,workspaces:i}}function Vu(r,e){let t;try{t=c0(r)}catch{throw new Error(`${e}: path does not exist: ${r}`)}if(!t.isDirectory())throw new Error(`${e}: path is not a directory: ${r}`)}function l0(r,e,t){switch(r.type){case"linear":if(typeof r.project!="string"||r.project.length===0)throw new Error(`workspaces[${e}] (${t}): linear tracker requires project`);break;case"github":if(typeof r.repo!="string"||r.repo.length===0)throw new Error(`workspaces[${e}] (${t}): github tracker requires repo`);break;case"clickup":if(typeof r.list!="string"||r.list.length===0)throw new Error(`workspaces[${e}] (${t}): clickup tracker requires list`);break}}function Ju(r){let e=r.archetypeConfig,t=r.agentConfig.title||r.agentConfig.name,s=[];s.push(`# Software Engineer
243
243
 
244
244
  You are a software engineer. Your title is ${t}. Your discipline is owning codebases and shipping production code through disciplined delivery.`);let n=[`Your workshop is \`${e.workshop}\`. This is your working directory.`];if(e.workspaces.length>0){n.push(`
245
- Workspaces:`);for(let i of e.workspaces){let o=l0(i.tracker),a=i.primary?" (primary)":"";n.push(`- **${i.name}**${a}: \`${i.path}\` \u2014 tracker: ${o}`)}}else n.push(`
245
+ Workspaces:`);for(let i of e.workspaces){let o=d0(i.tracker),a=i.primary?" (primary)":"";n.push(`- **${i.name}**${a}: \`${i.path}\` \u2014 tracker: ${o}`)}}else n.push(`
246
246
  No workspaces configured yet. You have full agency over your entire workshop.`);return s.push(n.join(`
247
247
  `)),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
248
248
 
@@ -269,7 +269,7 @@ A task is done when ALL of these are true:
269
269
  - **Always** verify PR + CI status before closing a ticket
270
270
  - **Always** file a ticket before delegating work`),s.join(`
271
271
 
272
- `)}function l0(r){switch(r.type){case"linear":return`Linear (project: ${r.project})`;case"github":return`GitHub Issues (repo: ${r.repo})`;case"clickup":return`ClickUp (list: ${r.list})`;default:return r.type}}import{resolve as d0}from"node:path";import{normalize as zu,resolve as Qu}from"node:path";function Sa(r){if(typeof r!="string"||!r.startsWith("/"))throw new Error(`claudeProjectSlug: path must be absolute, got ${String(r)}`);return r.replace(/\/+$/,"").replace(/[/_.]/g,"-").replace(/-+/g,"-")}function Xu(r,e){let t=zu(Qu(r));return e.workspaces.find(s=>{let n=zu(Qu(s.path));return t===n||t.startsWith(n+"/")})}function Zu(r){return Sa(r.workshop)}function eh(r){return Sa(r.path)}var u0=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function h0(r,e){return r==="NotebookEdit"?e.notebook_path??e.file_path:e.file_path}function th(r){let e=r.archetypeConfig;return e.workspaces.length===0?[]:[{hooks:[async t=>{try{let s=t,n=s.tool_name??"";if(!u0.has(n))return{continue:!0};let i=h0(n,s.tool_input??{});if(typeof i!="string"||i.length===0)return{continue:!0};let o=d0(e.workshop,i),a=Xu(o,e);return a?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${n} 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 f0}from"node:os";import{join as sh}from"node:path";function nh(r){let e=r.archetypeConfig,t=f0(),s=[];s.push({id:"workshop",backing:"filesystem",dir:sh(t,".claude/projects",Zu(e),"memory")});for(let n of e.workspaces)s.push({id:`workspace:${n.name}`,backing:"filesystem",dir:sh(t,".claude/projects",eh(n),"memory")});return s}function rh(r){return{cwd:r.archetypeConfig.workshop,settingSources:["project"]}}Ku({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:Yu,systemPromptCard:Ju,preToolUseHooks:th,memoryScopes:nh,sessionOptions:rh});var fe=k("agent-registry"),ih=3e4,gr=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,n=[],i=[],o=[],a=[];for(let l of e){let c=ju(l,p.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),fe.info("Disabled agent removed from active map",{id:c.id}));continue}if(c.archetype){let d=pr(c.archetype);if(!d)fe.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){fe.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),fe.warn("Evicted previously-loaded agent due to archetype validation failure",{id:c.id}));continue}}t.has(c.id)?i.push(c.id):n.push(c.id),this.agents.set(c.id,c),fe.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),fe.info("Removed agent",{id:l}));return this.lastPollTime=new Date,this.rebuildOriginIndex(),{added:n,updated:i,removed:o}}async startWatching(){try{this.changeStream=this.agentDefs.watch([],{fullDocument:"updateLookup"}),this.changeStream.on("change",()=>{fe.info("Agent definition changed (change stream), triggering reload"),this.onReload?.()}),this.changeStream.on("error",e=>{fe.warn("Change stream error, falling back to polling",{error:String(e)}),this.changeStream=null,this.startPolling()}),fe.info("Agent registry watching via change stream")}catch{fe.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&&(fe.info("Agent definitions changed (poll), triggering reload",{changed:e}),this.onReload?.())}catch(e){fe.error("Poll check failed",{error:String(e)})}},ih),fe.info("Agent registry watching via polling",{intervalMs:ih})}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)){fe.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(n=>{let i=n.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 n=s.includes(":")?s.split(":")[0]:s;e[n]||(e[n]=[]),e[n].includes(t.id)||e[n].push(t.id)}return e}};O();Ma();Ys();O();Ne();import{query as V0}from"@anthropic-ai/claude-agent-sdk";var Js=k("model-router"),Y0={haiku:{timeoutMs:12e4,maxTurns:20,budgetUsd:1},sonnet:{timeoutMs:3e5,maxTurns:50,budgetUsd:5},opus:{timeoutMs:6e5,maxTurns:200,budgetUsd:50}};function Tr(r,e){let t=Y0[r],s=e?.[r];return s?{timeoutMs:s.timeoutMs??t.timeoutMs,maxTurns:s.maxTurns??t.maxTurns,budgetUsd:s.budgetUsd??t.budgetUsd}:{...t}}var ft={haiku:0,sonnet:1,opus:2},Ir={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-6"};function J0(r){return r.includes("opus")?"opus":r.includes("haiku")?"haiku":"sonnet"}var z0=`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.
272
+ `)}function d0(r){switch(r.type){case"linear":return`Linear (project: ${r.project})`;case"github":return`GitHub Issues (repo: ${r.repo})`;case"clickup":return`ClickUp (list: ${r.list})`;default:return r.type}}import{resolve as u0}from"node:path";import{normalize as zu,resolve as Qu}from"node:path";function Sa(r){if(typeof r!="string"||!r.startsWith("/"))throw new Error(`claudeProjectSlug: path must be absolute, got ${String(r)}`);return r.replace(/\/+$/,"").replace(/[/_.]/g,"-").replace(/-+/g,"-")}function Xu(r,e){let t=zu(Qu(r));return e.workspaces.find(s=>{let n=zu(Qu(s.path));return t===n||t.startsWith(n+"/")})}function Zu(r){return Sa(r.workshop)}function eh(r){return Sa(r.path)}var h0=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function f0(r,e){return r==="NotebookEdit"?e.notebook_path??e.file_path:e.file_path}function th(r){let e=r.archetypeConfig;return e.workspaces.length===0?[]:[{hooks:[async t=>{try{let s=t,n=s.tool_name??"";if(!h0.has(n))return{continue:!0};let i=f0(n,s.tool_input??{});if(typeof i!="string"||i.length===0)return{continue:!0};let o=u0(e.workshop,i),a=Xu(o,e);return a?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${n} 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 p0}from"node:os";import{join as sh}from"node:path";function nh(r){let e=r.archetypeConfig,t=p0(),s=[];s.push({id:"workshop",backing:"filesystem",dir:sh(t,".claude/projects",Zu(e),"memory")});for(let n of e.workspaces)s.push({id:`workspace:${n.name}`,backing:"filesystem",dir:sh(t,".claude/projects",eh(n),"memory")});return s}function rh(r){return{cwd:r.archetypeConfig.workshop,settingSources:["project"]}}Ku({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:Yu,systemPromptCard:Ju,preToolUseHooks:th,memoryScopes:nh,sessionOptions:rh});var fe=k("agent-registry"),ih=3e4,gr=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,n=[],i=[],o=[],a=[];for(let l of e){let c=ju(l,p.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),fe.info("Disabled agent removed from active map",{id:c.id}));continue}if(c.archetype){let d=pr(c.archetype);if(!d)fe.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){fe.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),fe.warn("Evicted previously-loaded agent due to archetype validation failure",{id:c.id}));continue}}t.has(c.id)?i.push(c.id):n.push(c.id),this.agents.set(c.id,c),fe.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),fe.info("Removed agent",{id:l}));return this.lastPollTime=new Date,this.rebuildOriginIndex(),{added:n,updated:i,removed:o}}async startWatching(){try{this.changeStream=this.agentDefs.watch([],{fullDocument:"updateLookup"}),this.changeStream.on("change",()=>{fe.info("Agent definition changed (change stream), triggering reload"),this.onReload?.()}),this.changeStream.on("error",e=>{fe.warn("Change stream error, falling back to polling",{error:String(e)}),this.changeStream=null,this.startPolling()}),fe.info("Agent registry watching via change stream")}catch{fe.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&&(fe.info("Agent definitions changed (poll), triggering reload",{changed:e}),this.onReload?.())}catch(e){fe.error("Poll check failed",{error:String(e)})}},ih),fe.info("Agent registry watching via polling",{intervalMs:ih})}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)){fe.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(n=>{let i=n.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 n=s.includes(":")?s.split(":")[0]:s;e[n]||(e[n]=[]),e[n].includes(t.id)||e[n].push(t.id)}return e}};O();Ma();Ys();O();Ne();import{query as Y0}from"@anthropic-ai/claude-agent-sdk";var Js=k("model-router"),J0={haiku:{timeoutMs:12e4,maxTurns:20,budgetUsd:1},sonnet:{timeoutMs:3e5,maxTurns:50,budgetUsd:5},opus:{timeoutMs:6e5,maxTurns:200,budgetUsd:50}};function Tr(r,e){let t=J0[r],s=e?.[r];return s?{timeoutMs:s.timeoutMs??t.timeoutMs,maxTurns:s.maxTurns??t.maxTurns,budgetUsd:s.budgetUsd??t.budgetUsd}:{...t}}var ft={haiku:0,sonnet:1,opus:2},Ir={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-6"};function z0(r){return r.includes("opus")?"opus":r.includes("haiku")?"haiku":"sonnet"}var Q0=`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.
273
273
 
274
274
  Tiers:
275
275
  - **haiku**: Greetings, simple factual questions, acknowledgments, status checks, yes/no answers, brief lookups, routine updates. Fast and cheap.
@@ -282,10 +282,10 @@ Rules:
282
282
  - Look at the TASK complexity, not the message length.
283
283
  - Scheduled/cron tasks that say "execute your scheduled X task" are routine \u2192 haiku unless the task itself is complex.
284
284
 
285
- Respond with ONLY a JSON object: { "tier": "haiku" | "sonnet" | "opus" }`;function Q0(r){try{let s=JSON.parse(r);if(s.tier&&ft[s.tier]!==void 0)return s.tier}catch{}let e=r.indexOf("{"),t=r.lastIndexOf("}");if(e!==-1&&t>e)try{let s=JSON.parse(r.slice(e,t+1));if(s.tier&&ft[s.tier]!==void 0)return s.tier}catch{}return null}async function Bh(r,e,t){let s=J0(e),n=p.modelRouter.model;if(s==="haiku")return{tier:"haiku",model:Ir.haiku,costUsd:0,durationMs:0,resourceLimits:Tr("haiku",t)};let i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Js.warn("Model router timed out",{timeoutMs:p.modelRouter.timeoutMs}),i.close())},p.modelRouter.timeoutMs);try{i=V0({prompt:r,options:{model:n,systemPrompt:z0,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,thinking:{type:"disabled"},disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...p.anthropic.apiKey?{ANTHROPIC_API_KEY:p.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let m=h;if(m.type==="assistant"){let g=m.message?.content;if(Array.isArray(g))for(let f of g)f.type==="text"&&(o=f.text)}if(m.type==="result"){let g=m;a=g.total_cost_usd,l=g.duration_ms,g.subtype==="success"&&g.result&&(o=g.result)}}}catch(h){Js.warn("Model router query failed, defaulting to sonnet",{error:String(h)});let m=ft[s]>=ft.sonnet?"sonnet":s;return{tier:m,model:Ir[m],costUsd:0,durationMs:0,resourceLimits:Tr(m,t)}}finally{clearTimeout(c),i=null}let d=Q0(o);if(!d){Js.warn("Model router parse failed, defaulting to sonnet",{rawText:o.slice(0,200)});let h=ft[s]>=ft.sonnet?"sonnet":s;return{tier:h,model:Ir[h],costUsd:0,durationMs:0,resourceLimits:Tr(h,t)}}let u=d;return ft[d]>ft[s]&&(u=s,Js.debug("Model router capped by ceiling",{requested:d,ceiling:s})),Js.info("Model router decision",{tier:u,requested:d,ceiling:s,costUsd:a,durationMs:l,textPreview:r.slice(0,100)}),{tier:u,model:Ir[u],costUsd:a,durationMs:l,resourceLimits:Tr(u,t)}}Ne();Sr();Ea();ls();import{existsSync as Uh,readdirSync as ek,statSync as tk}from"node:fs";import{join as qh}from"node:path";Cr();import{QdrantClient as Z0}from"@qdrant/js-client-rest";var Ar="conversations",Er=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 Z0({url:this.qdrantUrl})),this.qdrant}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(n=>n.name===Ar)){let i=(await He(this.ollamaUrl,"test")).length;await e.createCollection(Ar,{vectors:{size:i,distance:"Cosine"}})}this.collectionReady=!0}async index(e){await this.ensureCollection();let t=this.getClient(),s=e.inbound+`
285
+ Respond with ONLY a JSON object: { "tier": "haiku" | "sonnet" | "opus" }`;function X0(r){try{let s=JSON.parse(r);if(s.tier&&ft[s.tier]!==void 0)return s.tier}catch{}let e=r.indexOf("{"),t=r.lastIndexOf("}");if(e!==-1&&t>e)try{let s=JSON.parse(r.slice(e,t+1));if(s.tier&&ft[s.tier]!==void 0)return s.tier}catch{}return null}async function Bh(r,e,t){let s=z0(e),n=p.modelRouter.model;if(s==="haiku")return{tier:"haiku",model:Ir.haiku,costUsd:0,durationMs:0,resourceLimits:Tr("haiku",t)};let i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Js.warn("Model router timed out",{timeoutMs:p.modelRouter.timeoutMs}),i.close())},p.modelRouter.timeoutMs);try{i=Y0({prompt:r,options:{model:n,systemPrompt:Q0,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,thinking:{type:"disabled"},disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...p.anthropic.apiKey?{ANTHROPIC_API_KEY:p.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let m=h;if(m.type==="assistant"){let g=m.message?.content;if(Array.isArray(g))for(let f of g)f.type==="text"&&(o=f.text)}if(m.type==="result"){let g=m;a=g.total_cost_usd,l=g.duration_ms,g.subtype==="success"&&g.result&&(o=g.result)}}}catch(h){Js.warn("Model router query failed, defaulting to sonnet",{error:String(h)});let m=ft[s]>=ft.sonnet?"sonnet":s;return{tier:m,model:Ir[m],costUsd:0,durationMs:0,resourceLimits:Tr(m,t)}}finally{clearTimeout(c),i=null}let d=X0(o);if(!d){Js.warn("Model router parse failed, defaulting to sonnet",{rawText:o.slice(0,200)});let h=ft[s]>=ft.sonnet?"sonnet":s;return{tier:h,model:Ir[h],costUsd:0,durationMs:0,resourceLimits:Tr(h,t)}}let u=d;return ft[d]>ft[s]&&(u=s,Js.debug("Model router capped by ceiling",{requested:d,ceiling:s})),Js.info("Model router decision",{tier:u,requested:d,ceiling:s,costUsd:a,durationMs:l,textPreview:r.slice(0,100)}),{tier:u,model:Ir[u],costUsd:a,durationMs:l,resourceLimits:Tr(u,t)}}Ne();Sr();Ea();ls();import{existsSync as Uh,readdirSync as tk,statSync as sk}from"node:fs";import{join as qh}from"node:path";Cr();import{QdrantClient as ek}from"@qdrant/js-client-rest";var Ar="conversations",Er=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 ek({url:this.qdrantUrl})),this.qdrant}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(n=>n.name===Ar)){let i=(await He(this.ollamaUrl,"test")).length;await e.createCollection(Ar,{vectors:{size:i,distance:"Cosine"}})}this.collectionReady=!0}async index(e){await this.ensureCollection();let t=this.getClient(),s=e.inbound+`
286
286
 
287
- `+e.response,n=await He(this.ollamaUrl,s),i=crypto.randomUUID();await t.upsert(Ar,{points:[{id:i,vector:n,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,n){await this.ensureCollection();let i=this.getClient(),o=await He(this.ollamaUrl,e),a=[{key:"agentId",match:{value:t}}];return n!==void 0&&a.push({key:"timestampUnix",range:{gte:n}}),(await i.search(Ar,{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"),sk=new Er;function nk(r){if(!Uh(r))return[];try{return ek(r).map(e=>qh(r,e)).filter(e=>{try{return tk(e).isDirectory()&&Uh(qh(e,"skills"))}catch{return!1}})}catch{return[]}}var Nr=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,n,i){this.registry=e,this.memoryManager=t,this.sessionStore=s,this.activityLogger=n,this.prefetcher=i,this.plugins=ba(p.plugins,z,{distDir:Ke}),this.seedDirs=nk(Ic),this.skillIndex=Aa(Ze,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 Gs(t,this.memoryManager,this.plugins,this.skillIndex,s,this.prefetcher)}reloadSkills(){try{this.skillIndex=Aa(Ze,this.plugins,this.seedDirs)}catch(e){ae.warn("Skill reload failed, retaining previous index",{error:String(e)})}}rescanPlugins(){let{rescued:e,stillBroken:t}=_a(this.plugins,z,{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,n=(this.spawnWindow.get(e)??[]).filter(i=>t-i<s);if(n.push(t),this.spawnWindow.set(e,n),n.length>3&&ae.warn("Session spawn rate exceeded",{channelId:e,count:n.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 n=t.threadId??t.id,i=`${e}:${n}`;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 n=this.registry.get(e),i=n?.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 g=s.shift(),f=this.activeWorkItems.get(e)??[];f.push(g.message),this.activeWorkItems.set(e,f);try{let y=g.message.threadId??g.message.id,w=await this.sessionStore.get(e,y);w||this.recordSpawn(g.message.source.id);let S={adapterId:g.message.source.adapterId??g.message.source.kind,channelId:g.message.source.id,channelKind:g.message.source.kind,channelLabel:g.message.source.label,threadId:g.message.threadId??g.message.id,slackTs:g.message.meta?.slackTs??"",slackThreadTs:g.message.meta?.slackThreadTs??""},_=g.message.senderName??g.message.sender,v=g.message.source.kind==="team"?g.message.meta?.user:void 0,I;if(v)I=`[user:${v} via ${_} in #${g.message.source.label}]: ${g.message.text}`;else if(g.message.senderName){let W=g.message.meta?.slackThreadTs,$=g.message.meta?.slackTs,ce=W??$,Ie=ce?`, thread=${ce}`:"";I=`[${_} in #${g.message.source.label}${Ie}]: ${g.message.text}`}else I=g.message.text;g.message.files?.length&&(I+=$h(g.message.files));let N,D=0,C;if(p.modelRouter.enabled&&g.message.sender!=="system")try{let W=this.registry.get(e);if(W){let $=await Bh(g.message.text,W.model,W.resourceTiers);N=$.model!==W.model?$.model:void 0,D=$.costUsd,C=$.resourceLimits}}catch(W){ae.warn("Model router failed, using default",{agentId:e,error:String(W)})}let E=await a.send(I,w,g.onStream,S,N,C);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)),g.resolve(E),c++,d=g,u=E,E.text&&!E.error&&sk.index({agentId:e,threadId:y,channelId:g.message.source.id,source:g.message.source.kind,senderName:g.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:g.message.sender,senderName:g.message.senderName,channel:g.message.source.label,channelKind:g.message.source.kind,model:N??n?.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:g.message.threadId??g.message.id,timestamp:new Date,sender:g.message.sender,senderName:g.message.senderName,channel:g.message.source.label,channelKind:g.message.source.kind,model:n?.model??"unknown",costUsd:0,durationMs:0,inputTokens:0,outputTokens:0,contextWindow:0,toolCalls:0,toolSummary:"none",compactions:0,streamed:!1,error:String(y)}),g.reject(y instanceof Error?y:new Error(String(y)))}finally{let y=(this.activeWorkItems.get(e)??[]).filter(w=>w.id!==g.message.id);y.length===0?this.activeWorkItems.delete(e):this.activeWorkItems.set(e,y)}}let h=[...n?.coreServers??[],...n?.delegateServers??[]];if((h.includes("memory")||h.includes("structured-memory"))&&u&&d&&!u.error&&!u.aborted&&c>=p.memory.reflectionMinTurns&&d.message.sender!=="system")try{let g=["[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(`
288
- `),f=await a.send(g,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(g){ae.warn("Reflection failed, non-critical",{agentId:e,threadKey:t,error:String(g)})}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,n]of this.queues)if(s.startsWith(t)&&n.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[n,i]of this.states)!this.registry.get(n)&&(i.status==="stopped"||i.status==="idle")&&(this.states.delete(n),this.activeRunners.delete(n),this.activeThreads.delete(n),e++,ae.info("Zombie agent state removed",{agentId:n}));for(let n of this.processing){let i=n.split(":")[0],o=this.activeRunners.get(i);if(!o||o.size===0){this.processing.delete(n);let a=this.activeThreads.get(i);a&&(a.delete(n),this.updateThreadCount(i),a.size===0&&this.updateStatus(i,"idle")),e++,ae.warn("Stuck processing flag cleared",{threadKey:n,agentId:i});let l=this.queues.get(n);l&&l.length>0&&this.processThreadQueue(i,n).catch(c=>{ae.error("Failed to restart stuck queue",{threadKey:n,error:String(c)})})}}let s=new Set;for(let n of this.queues.keys())s.add(n.split(":")[0]);for(let n of s)this.retryDeferredThreads(n);return{component:"agent-manager",pruned:e,retried:0,bytesFreed:0,errors:t}}};O();Ys();import{SocketModeClient as ik}from"@slack/socket-mode";import{WebClient as ok}from"@slack/web-api";O();var rk=k("outbound-ts-cache"),xr=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,n]of this.entries)n<=e&&(this.entries.delete(s),t++);t>0&&rk.debug(`evicted ${t} expired entries`,{evicted:t})}};var K=k("slack-gateway"),Or=class r{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 xr;integrationChannels=new Set;botToken;constructor(e,t){this.socket=new ik({appToken:e}),this.web=new ok(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 n=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+`
287
+ `+e.response,n=await He(this.ollamaUrl,s),i=crypto.randomUUID();await t.upsert(Ar,{points:[{id:i,vector:n,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,n){await this.ensureCollection();let i=this.getClient(),o=await He(this.ollamaUrl,e),a=[{key:"agentId",match:{value:t}}];return n!==void 0&&a.push({key:"timestampUnix",range:{gte:n}}),(await i.search(Ar,{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"),nk=new Er;function rk(r){if(!Uh(r))return[];try{return tk(r).map(e=>qh(r,e)).filter(e=>{try{return sk(e).isDirectory()&&Uh(qh(e,"skills"))}catch{return!1}})}catch{return[]}}var Nr=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,n,i){this.registry=e,this.memoryManager=t,this.sessionStore=s,this.activityLogger=n,this.prefetcher=i,this.plugins=ba(p.plugins,z,{distDir:Ke}),this.seedDirs=rk(Ic),this.skillIndex=Aa(Ze,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 Gs(t,this.memoryManager,this.plugins,this.skillIndex,s,this.prefetcher)}reloadSkills(){try{this.skillIndex=Aa(Ze,this.plugins,this.seedDirs)}catch(e){ae.warn("Skill reload failed, retaining previous index",{error:String(e)})}}rescanPlugins(){let{rescued:e,stillBroken:t}=_a(this.plugins,z,{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,n=(this.spawnWindow.get(e)??[]).filter(i=>t-i<s);if(n.push(t),this.spawnWindow.set(e,n),n.length>3&&ae.warn("Session spawn rate exceeded",{channelId:e,count:n.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 n=t.threadId??t.id,i=`${e}:${n}`;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 n=this.registry.get(e),i=n?.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 g=s.shift(),f=this.activeWorkItems.get(e)??[];f.push(g.message),this.activeWorkItems.set(e,f);try{let y=g.message.threadId??g.message.id,w=await this.sessionStore.get(e,y);w||this.recordSpawn(g.message.source.id);let S={adapterId:g.message.source.adapterId??g.message.source.kind,channelId:g.message.source.id,channelKind:g.message.source.kind,channelLabel:g.message.source.label,threadId:g.message.threadId??g.message.id,slackTs:g.message.meta?.slackTs??"",slackThreadTs:g.message.meta?.slackThreadTs??""},_=g.message.senderName??g.message.sender,v=g.message.source.kind==="team"?g.message.meta?.user:void 0,I;if(v)I=`[user:${v} via ${_} in #${g.message.source.label}]: ${g.message.text}`;else if(g.message.senderName){let W=g.message.meta?.slackThreadTs,$=g.message.meta?.slackTs,ce=W??$,Ie=ce?`, thread=${ce}`:"";I=`[${_} in #${g.message.source.label}${Ie}]: ${g.message.text}`}else I=g.message.text;g.message.files?.length&&(I+=$h(g.message.files));let N,D=0,C;if(p.modelRouter.enabled&&g.message.sender!=="system")try{let W=this.registry.get(e);if(W){let $=await Bh(g.message.text,W.model,W.resourceTiers);N=$.model!==W.model?$.model:void 0,D=$.costUsd,C=$.resourceLimits}}catch(W){ae.warn("Model router failed, using default",{agentId:e,error:String(W)})}let E=await a.send(I,w,g.onStream,S,N,C);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)),g.resolve(E),c++,d=g,u=E,E.text&&!E.error&&nk.index({agentId:e,threadId:y,channelId:g.message.source.id,source:g.message.source.kind,senderName:g.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:g.message.sender,senderName:g.message.senderName,channel:g.message.source.label,channelKind:g.message.source.kind,model:N??n?.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:g.message.threadId??g.message.id,timestamp:new Date,sender:g.message.sender,senderName:g.message.senderName,channel:g.message.source.label,channelKind:g.message.source.kind,model:n?.model??"unknown",costUsd:0,durationMs:0,inputTokens:0,outputTokens:0,contextWindow:0,toolCalls:0,toolSummary:"none",compactions:0,streamed:!1,error:String(y)}),g.reject(y instanceof Error?y:new Error(String(y)))}finally{let y=(this.activeWorkItems.get(e)??[]).filter(w=>w.id!==g.message.id);y.length===0?this.activeWorkItems.delete(e):this.activeWorkItems.set(e,y)}}let h=[...n?.coreServers??[],...n?.delegateServers??[]];if((h.includes("memory")||h.includes("structured-memory"))&&u&&d&&!u.error&&!u.aborted&&c>=p.memory.reflectionMinTurns&&d.message.sender!=="system")try{let g=["[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(`
288
+ `),f=await a.send(g,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(g){ae.warn("Reflection failed, non-critical",{agentId:e,threadKey:t,error:String(g)})}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,n]of this.queues)if(s.startsWith(t)&&n.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[n,i]of this.states)!this.registry.get(n)&&(i.status==="stopped"||i.status==="idle")&&(this.states.delete(n),this.activeRunners.delete(n),this.activeThreads.delete(n),e++,ae.info("Zombie agent state removed",{agentId:n}));for(let n of this.processing){let i=n.split(":")[0],o=this.activeRunners.get(i);if(!o||o.size===0){this.processing.delete(n);let a=this.activeThreads.get(i);a&&(a.delete(n),this.updateThreadCount(i),a.size===0&&this.updateStatus(i,"idle")),e++,ae.warn("Stuck processing flag cleared",{threadKey:n,agentId:i});let l=this.queues.get(n);l&&l.length>0&&this.processThreadQueue(i,n).catch(c=>{ae.error("Failed to restart stuck queue",{threadKey:n,error:String(c)})})}}let s=new Set;for(let n of this.queues.keys())s.add(n.split(":")[0]);for(let n of s)this.retryDeferredThreads(n);return{component:"agent-manager",pruned:e,retried:0,bytesFreed:0,errors:t}}};O();Ys();import{SocketModeClient as ok}from"@slack/socket-mode";import{WebClient as ak}from"@slack/web-api";O();var ik=k("outbound-ts-cache"),xr=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,n]of this.entries)n<=e&&(this.entries.delete(s),t++);t>0&&ik.debug(`evicted ${t} expired entries`,{evicted:t})}};var K=k("slack-gateway"),Or=class r{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 xr;integrationChannels=new Set;botToken;constructor(e,t){this.socket=new ok({appToken:e}),this.web=new ak(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 n=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+`
289
289
  `);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(`
290
290
  `):"").filter(Boolean).join(`
291
291
  `)),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=>Lh(c,this.botToken)))).filter(Boolean)),!i&&o.length===0){K.info("Skipping message with no extractable text or files",{channel:t.channel,channelName:n,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:n,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:n,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 n=t?.assistant_thread;n&&this.threadStartedHandler?.({channel:n.channel_id,threadTs:n.thread_ts,context:n.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 n=t?.assistant_thread;n&&this.threadContextHandler?.({channel:n.channel_id,threadTs:n.thread_ts,context:n.context??{}})}),this.socket.on("slack_event",async({ack:t,body:s})=>{await t();let n=s?.event;n&&K.debug("slack_event",{type:n.type,subtype:n.subtype,channel:n.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(n){K.warn("Failed to set thread status",{error:String(n)})}}async setSuggestedPrompts(e,t,s){try{await this.web.assistant.threads.setSuggestedPrompts({channel_id:e,thread_ts:t,prompts:s})}catch(n){K.warn("Failed to set suggested prompts",{error:String(n)})}}async setThreadTitle(e,t,s){try{await this.web.assistant.threads.setTitle({channel_id:e,thread_ts:t,title:s})}catch(n){K.warn("Failed to set thread title",{error:String(n)})}}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(n){K.warn("Failed to append stream",{error:String(n)})}}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,n){return t.length<=r.SLACK_MAX_CHARS?this.postSingle(e,t,s,n):t.length<=r.SPLIT_MAX_CHARS?this.postSplit(e,t,s,n):this.postAsFile(e,t,s,n)}async postSingle(e,t,s,n){if(n)try{let i={};n.icon&&(n.icon.startsWith(":")&&n.icon.endsWith(":")?i.icon_emoji=n.icon:i.icon_url=n.icon);let o=await this.web.chat.postMessage({channel:e,text:t,thread_ts:s,unfurl_links:!1,username:n.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=r.SLACK_MAX_CHARS,s=[],n=e;for(;n.length>t;){let i=-1,o=n.lastIndexOf(`
@@ -297,18 +297,18 @@ Respond with ONLY a JSON object: { "tier": "haiku" | "sonnet" | "opus" }`;functi
297
297
  `),i.lastIndexOf("! "));if(a>0)o=i.slice(0,a+1);else{let h=i.lastIndexOf(`
298
298
  `);h>0&&(o=i.slice(0,h))}o=`${o.trimEnd()}
299
299
 
300
- _(full response attached)_`;let l=n?.name??"hive",c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=`${l.toLowerCase()}-${c}.md`,u=await this.postSingle(e,o,s,n);try{let h={content:t,filename:d,title:`${l} response`},m=s?{channel_id:e,thread_ts:s}:{channel_id:e};return await this.web.files.uploadV2({...h,...m}),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,n)}}async addReaction(e,t,s){try{await this.web.reactions.add({channel:e,name:s,timestamp:t})}catch(n){let i=String(n);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 n=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}n=n.replace(i[0],`@${a}`)}return n}registerOutboundTs(e,t){this.outboundTsCache.register(e,t)}isOutboundEcho(e,t){return this.outboundTsCache.has(e,t)}async postAndRegister(e,t,s){try{let n=await this.postMessage(e,t,s);return n?{ok:!0,ts:n}:{ok:!1,error:"postMessage returned no ts"}}catch(n){return{ok:!1,error:n.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 n;do{let i=await this.web.conversations.list({limit:1e3,cursor:n,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));n=i.response_metadata?.next_cursor||void 0}while(n)}catch(n){return K.warn("channel id resolve failed",{name:t,error:n.message}),null}return this.channelIdCache.get(t)??null}async resolveChannelName(e){let t=this.channelNameCache.get(e);if(t)return t;try{let n=(await this.web.conversations.info({channel:e})).channel?.name??e;return this.channelNameCache.set(e,n),n}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 n=await this.web.conversations.list({limit:1e3,cursor:s,exclude_archived:!0,types:"public_channel,private_channel"});for(let i of n.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=n.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}};O();import{MongoClient as ak}from"mongodb";var ck=k("memory-manager"),Mr=class{mongoUri;dbName;client;db;collection;versions;_memoryStore;set memoryStore(e){this._memoryStore=e}constructor(e,t="hive"){this.mongoUri=e,this.dbName=t}async init(){this.client=new ak(this.mongoUri),await this.client.connect(),this.db=this.client.db(this.dbName),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}),ck.info("Memory manager connected to MongoDB",{db:this.dbName})}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:`^${lk(t)}[^/]+$`}}).project({path:1}).toArray()).map(n=>n.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 n={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})`,m=Math.ceil(h.length/4);if(a+m>t&&!d.pinned)break;if(a+=m,d.pinned)o.push(`- ${d.content} (${d.importance}, pinned)`);else{let g=d.type;i[g]||(i[g]=[]),i[g].push(h)}}let l=["## Your Memory"];for(let[d,u]of Object.entries(n))i[d]?.length&&l.push(`### ${u}
300
+ _(full response attached)_`;let l=n?.name??"hive",c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=`${l.toLowerCase()}-${c}.md`,u=await this.postSingle(e,o,s,n);try{let h={content:t,filename:d,title:`${l} response`},m=s?{channel_id:e,thread_ts:s}:{channel_id:e};return await this.web.files.uploadV2({...h,...m}),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,n)}}async addReaction(e,t,s){try{await this.web.reactions.add({channel:e,name:s,timestamp:t})}catch(n){let i=String(n);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 n=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}n=n.replace(i[0],`@${a}`)}return n}registerOutboundTs(e,t){this.outboundTsCache.register(e,t)}isOutboundEcho(e,t){return this.outboundTsCache.has(e,t)}async postAndRegister(e,t,s){try{let n=await this.postMessage(e,t,s);return n?{ok:!0,ts:n}:{ok:!1,error:"postMessage returned no ts"}}catch(n){return{ok:!1,error:n.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 n;do{let i=await this.web.conversations.list({limit:1e3,cursor:n,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));n=i.response_metadata?.next_cursor||void 0}while(n)}catch(n){return K.warn("channel id resolve failed",{name:t,error:n.message}),null}return this.channelIdCache.get(t)??null}async resolveChannelName(e){let t=this.channelNameCache.get(e);if(t)return t;try{let n=(await this.web.conversations.info({channel:e})).channel?.name??e;return this.channelNameCache.set(e,n),n}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 n=await this.web.conversations.list({limit:1e3,cursor:s,exclude_archived:!0,types:"public_channel,private_channel"});for(let i of n.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=n.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}};O();import{MongoClient as ck}from"mongodb";var lk=k("memory-manager"),Mr=class{mongoUri;dbName;client;db;collection;versions;_memoryStore;set memoryStore(e){this._memoryStore=e}constructor(e,t="hive"){this.mongoUri=e,this.dbName=t}async init(){this.client=new ck(this.mongoUri),await this.client.connect(),this.db=this.client.db(this.dbName),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}),lk.info("Memory manager connected to MongoDB",{db:this.dbName})}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:`^${dk(t)}[^/]+$`}}).project({path:1}).toArray()).map(n=>n.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 n={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})`,m=Math.ceil(h.length/4);if(a+m>t&&!d.pinned)break;if(a+=m,d.pinned)o.push(`- ${d.content} (${d.importance}, pinned)`);else{let g=d.type;i[g]||(i[g]=[]),i[g].push(h)}}let l=["## Your Memory"];for(let[d,u]of Object.entries(n))i[d]?.length&&l.push(`### ${u}
301
301
  ${i[d].join(`
302
302
  `)}`);o.length>0&&l.push(`### Pinned
303
303
  ${o.join(`
304
304
  `)}`);let c=await this._memoryStore.countNonHot(e);return c>0&&l.push(`---
305
305
  You have ${c} additional memories available via \`memory_recall\`. Use it to search for context before starting tasks.`),l.join(`
306
306
 
307
- `)}async write(e,t,s){let n=await this.collection.findOne({path:e});n&&await this.versions.insertOne({path:e,content:n.content,savedAt:n.updatedAt,savedBy:n.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(){await this.client?.close()}};function lk(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}O();Ne();import{MongoClient as dk}from"mongodb";var Q=k("scheduler"),Dr=class{heartbeatTimer=null;cronTimer=null;callbackTimer=null;eventTimer=null;teamTimer=null;agentManager;memoryManager;healthReporter;registry;cronJobs=[];mongoClient=null;db=null;callbackCollection=null;eventsCollection=null;onDispatch;constructor(e,t,s,n,i){this.agentManager=e,this.memoryManager=t,this.healthReporter=s,this.registry=n,this.onDispatch=i;for(let o of n.getAll())for(let a of o.schedule)this.cronJobs.push({agentId:o.id,cron:a.cron,task:a.task,lastRun:null})}async connectDb(e,t){this.mongoClient=new dk(e),await this.mongoClient.connect(),this.db=this.mongoClient.db(t),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:p.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:t})}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)})}},p.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:p.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),this.mongoClient?.close().catch(()=>{}),Q.info("Scheduler stopped")}checkCronJobs(){let e=new Date;for(let t of this.cronJobs)if(uk(t.cron,e)){if(t.lastRun&&hk(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 n=s?.homeBase??s?.channels?.[0];if(!n){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:n,label:n},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(n=>n.status==="pending");for(let n of s){let i=new Date;if((await this.eventsCollection.updateOne({_id:t._id,deliveries:{$elemMatch:{agentId:n.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(n.agentId);if(!a){Q.warn("Event target agent not found, skipping",{agentId:n.agentId,eventType:t.type});continue}if(a.disabled){Q.info("Event target agent disabled, skipping",{agentId:n.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:n.agentId,sourceAgent:t.sourceAgentId});let u=a.homeBase??`agent-${n.agentId}`,h={id:`event:${l}:${n.agentId}`,text:`[Event: ${t.type} from ${d}]
307
+ `)}async write(e,t,s){let n=await this.collection.findOne({path:e});n&&await this.versions.insertOne({path:e,content:n.content,savedAt:n.updatedAt,savedBy:n.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(){await this.client?.close()}};function dk(r){return r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}O();Ne();import{MongoClient as uk}from"mongodb";var Q=k("scheduler"),Dr=class{heartbeatTimer=null;cronTimer=null;callbackTimer=null;eventTimer=null;teamTimer=null;agentManager;memoryManager;healthReporter;registry;cronJobs=[];mongoClient=null;db=null;callbackCollection=null;eventsCollection=null;onDispatch;constructor(e,t,s,n,i){this.agentManager=e,this.memoryManager=t,this.healthReporter=s,this.registry=n,this.onDispatch=i;for(let o of n.getAll())for(let a of o.schedule)this.cronJobs.push({agentId:o.id,cron:a.cron,task:a.task,lastRun:null})}async connectDb(e,t){this.mongoClient=new uk(e),await this.mongoClient.connect(),this.db=this.mongoClient.db(t),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:p.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:t})}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)})}},p.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:p.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),this.mongoClient?.close().catch(()=>{}),Q.info("Scheduler stopped")}checkCronJobs(){let e=new Date;for(let t of this.cronJobs)if(hk(t.cron,e)){if(t.lastRun&&fk(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 n=s?.homeBase??s?.channels?.[0];if(!n){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:n,label:n},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(n=>n.status==="pending");for(let n of s){let i=new Date;if((await this.eventsCollection.updateOne({_id:t._id,deliveries:{$elemMatch:{agentId:n.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(n.agentId);if(!a){Q.warn("Event target agent not found, skipping",{agentId:n.agentId,eventType:t.type});continue}if(a.disabled){Q.info("Event target agent disabled, skipping",{agentId:n.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:n.agentId,sourceAgent:t.sourceAgentId});let u=a.homeBase??`agent-${n.agentId}`,h={id:`event:${l}:${n.agentId}`,text:`[Event: ${t.type} from ${d}]
308
308
 
309
- ${JSON.stringify(t.payload)}`,source:{kind:"internal",id:u,label:u},sender:"system",threadId:`event:${l}:${n.agentId}:${i.getTime()}`,timestamp:i,meta:{targetAgentId:n.agentId,eventType:t.type,eventDomain:t.domain,eventId:l}};this.onDispatch?this.onDispatch(h):this.agentManager.sendMessage(n.agentId,h).catch(m=>{Q.error("Event dispatch failed",{agentId:n.agentId,eventType:t.type,eventId:l,error:String(m)})})}}}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 n={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(n):this.agentManager.sendMessage(t.targetAgentId,n).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,n);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 uk(r,e){let t=r.split(/\s+/);if(t.length!==5)return!1;let[s,n,i,o,a]=t,l=e.getMinutes(),c=e.getHours(),d=e.getDate(),u=e.getMonth()+1,h=e.getDay();return zs(s,l)&&zs(n,c)&&zs(i,d)&&zs(o,u)&&zs(a,h)}function zs(r,e){if(r==="*")return!0;if(r.includes("-")){let[t,s]=r.split("-").map(Number);return e>=t&&e<=s}if(r.includes(","))return r.split(",").map(Number).includes(e);if(r.startsWith("*/")){let t=Number(r.slice(2));return e%t===0}return Number(r)===e}function hk(r,e){return r.getFullYear()===e.getFullYear()&&r.getMonth()===e.getMonth()&&r.getDate()===e.getDate()&&r.getHours()===e.getHours()&&r.getMinutes()===e.getMinutes()}O();var fk=k("health-reporter"),Lr=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()}
309
+ ${JSON.stringify(t.payload)}`,source:{kind:"internal",id:u,label:u},sender:"system",threadId:`event:${l}:${n.agentId}:${i.getTime()}`,timestamp:i,meta:{targetAgentId:n.agentId,eventType:t.type,eventDomain:t.domain,eventId:l}};this.onDispatch?this.onDispatch(h):this.agentManager.sendMessage(n.agentId,h).catch(m=>{Q.error("Event dispatch failed",{agentId:n.agentId,eventType:t.type,eventId:l,error:String(m)})})}}}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 n={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(n):this.agentManager.sendMessage(t.targetAgentId,n).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,n);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 hk(r,e){let t=r.split(/\s+/);if(t.length!==5)return!1;let[s,n,i,o,a]=t,l=e.getMinutes(),c=e.getHours(),d=e.getDate(),u=e.getMonth()+1,h=e.getDay();return zs(s,l)&&zs(n,c)&&zs(i,d)&&zs(o,u)&&zs(a,h)}function zs(r,e){if(r==="*")return!0;if(r.includes("-")){let[t,s]=r.split("-").map(Number);return e>=t&&e<=s}if(r.includes(","))return r.split(",").map(Number).includes(e);if(r.startsWith("*/")){let t=Number(r.slice(2));return e%t===0}return Number(r)===e}function fk(r,e){return r.getFullYear()===e.getFullYear()&&r.getMonth()===e.getMonth()&&r.getDate()===e.getDate()&&r.getHours()===e.getHours()&&r.getMinutes()===e.getMinutes()}O();var pk=k("health-reporter"),Lr=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()}
310
310
  `];for(let[n,i]of Object.entries(e.agents)){let l=this.registry?.get(n)?.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} *${n}*${c}`),s.push(` Messages: ${i.messagesProcessed} | Errors: ${i.errorCount}`),s.push(` Last active: ${new Date(i.lastActivity).toLocaleString()}`)}return s.join(`
311
- `)}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"),fk.info("Health report written to memory")}};O();import{LinearClient as pk}from"@linear/sdk";var pe=k("linear-client"),Pr=class{client;defaultTeamId;constructor(e,t){this.client=new pk({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 pe.error("Failed to list teams",{error:String(e)}),[]}}async createIssue(e,t){try{let s=t?.teamId??this.defaultTeamId;if(!s)return pe.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?(pe.info("Issue created",{identifier:i.identifier,title:e}),{identifier:i.identifier,id:i.id,url:i.url}):(pe.error("Issue creation returned no issue",{title:e}),null)}catch(s){return pe.error("Failed to create issue",{error:String(s),title:e}),null}}async updateIssue(e,t){try{return await this.client.updateIssue(e,t),pe.info("Issue updated",{issueId:e,...t}),!0}catch(s){return pe.error("Failed to update issue",{error:String(s),issueId:e}),!1}}async addComment(e,t){try{let n=await(await this.client.createComment({issueId:e,body:t})).comment;return pe.info("Comment added",{issueId:e,commentId:n?.id}),n?.id??null}catch(s){return pe.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 n=await this.client.issues({filter:s,first:e?.limit??50,orderBy:"updatedAt"}),i=[];for(let o of n.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 pe.error("Failed to list issues",{error:String(t)}),[]}}async searchIssues(e,t,s){try{let n=s??this.defaultTeamId,o=(await this.client.searchIssues(e,{first:t??10})).nodes,a=[];for(let l of o){if(n&&(await l.team)?.id!==n)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(n){return pe.error("Failed to search issues",{error:String(n),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 pe.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(n=>({id:n.id,name:n.name,displayName:n.displayName,email:n.email,active:n.active}))}catch(s){return pe.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,n=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:n?{id:n.id,name:n.name,email:n.email}:void 0}}catch(t){return pe.error("Failed to find issue",{error:String(t),identifier:e}),null}}};O();import{MongoClient as jh}from"mongodb";var zt=k("session-store"),$r=class{client;db;collection;uri;dbName;constructor(e,t="hive"){this.uri=e,this.dbName=t,this.client=new jh(e,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0})}async connect(e){this.dbName=e??this.dbName,await this.client.connect(),this.db=this.client.db(this.dbName),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 t=await this.collection.countDocuments();zt.info("Session store connected",{count:t})}async reconnect(){zt.warn("Reconnecting to MongoDB...");try{await this.client.close().catch(()=>{})}catch{}this.client=new jh(this.uri,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0}),await this.client.connect(),this.db=this.client.db(this.dbName),this.collection=this.db.collection("sessions"),zt.info("MongoDB reconnected")}async withRetry(e,t,s){try{return await e()}catch(n){let i=String(n?.message??n);zt.warn("MongoDB operation failed, retrying after reconnect",{label:s,error:i});try{return await this.reconnect(),await e()}catch(o){return zt.error("MongoDB operation failed after retry, using fallback",{label:s,error:String(o?.message??o)}),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 n=t.split(":").pop();return(await this.collection.findOne({_id:`${e}:${n}`}))?.sessionId}},void 0,`get(${e}:${t})`)}async set(e,t,s,n){await this.withRetry(async()=>{let i=new Date,o={$set:{agentId:e,threadId:t,sessionId:s,updatedAt:i},$setOnInsert:{createdAt:i,compactions:0}};n?(o.$set.inputTokens=n.inputTokens,o.$set.outputTokens=n.outputTokens,o.$set.cacheReadTokens=n.cacheReadTokens,o.$set.cacheCreationTokens=n.cacheCreationTokens,o.$set.contextWindow=n.contextWindow,n.compactions>0&&(o.$inc={compactions:n.compactions},o.$set.lastCompactedAt=i,n.preCompactTokens!==void 0&&(o.$set.preCompactTokens=n.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&&zt.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(){await this.client.close()}};O();O();Ne();import{query as mk}from"@anthropic-ai/claude-agent-sdk";var Rr=k("meeting-classifier"),gk=`You are a meeting facilitator. Given a message and a list of meeting participants, decide which participants should respond.
311
+ `)}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"),pk.info("Health report written to memory")}};O();import{LinearClient as mk}from"@linear/sdk";var pe=k("linear-client"),Pr=class{client;defaultTeamId;constructor(e,t){this.client=new mk({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 pe.error("Failed to list teams",{error:String(e)}),[]}}async createIssue(e,t){try{let s=t?.teamId??this.defaultTeamId;if(!s)return pe.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?(pe.info("Issue created",{identifier:i.identifier,title:e}),{identifier:i.identifier,id:i.id,url:i.url}):(pe.error("Issue creation returned no issue",{title:e}),null)}catch(s){return pe.error("Failed to create issue",{error:String(s),title:e}),null}}async updateIssue(e,t){try{return await this.client.updateIssue(e,t),pe.info("Issue updated",{issueId:e,...t}),!0}catch(s){return pe.error("Failed to update issue",{error:String(s),issueId:e}),!1}}async addComment(e,t){try{let n=await(await this.client.createComment({issueId:e,body:t})).comment;return pe.info("Comment added",{issueId:e,commentId:n?.id}),n?.id??null}catch(s){return pe.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 n=await this.client.issues({filter:s,first:e?.limit??50,orderBy:"updatedAt"}),i=[];for(let o of n.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 pe.error("Failed to list issues",{error:String(t)}),[]}}async searchIssues(e,t,s){try{let n=s??this.defaultTeamId,o=(await this.client.searchIssues(e,{first:t??10})).nodes,a=[];for(let l of o){if(n&&(await l.team)?.id!==n)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(n){return pe.error("Failed to search issues",{error:String(n),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 pe.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(n=>({id:n.id,name:n.name,displayName:n.displayName,email:n.email,active:n.active}))}catch(s){return pe.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,n=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:n?{id:n.id,name:n.name,email:n.email}:void 0}}catch(t){return pe.error("Failed to find issue",{error:String(t),identifier:e}),null}}};O();import{MongoClient as jh}from"mongodb";var zt=k("session-store"),$r=class{client;db;collection;uri;dbName;constructor(e,t="hive"){this.uri=e,this.dbName=t,this.client=new jh(e,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0})}async connect(e){this.dbName=e??this.dbName,await this.client.connect(),this.db=this.client.db(this.dbName),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 t=await this.collection.countDocuments();zt.info("Session store connected",{count:t})}async reconnect(){zt.warn("Reconnecting to MongoDB...");try{await this.client.close().catch(()=>{})}catch{}this.client=new jh(this.uri,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0}),await this.client.connect(),this.db=this.client.db(this.dbName),this.collection=this.db.collection("sessions"),zt.info("MongoDB reconnected")}async withRetry(e,t,s){try{return await e()}catch(n){let i=String(n?.message??n);zt.warn("MongoDB operation failed, retrying after reconnect",{label:s,error:i});try{return await this.reconnect(),await e()}catch(o){return zt.error("MongoDB operation failed after retry, using fallback",{label:s,error:String(o?.message??o)}),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 n=t.split(":").pop();return(await this.collection.findOne({_id:`${e}:${n}`}))?.sessionId}},void 0,`get(${e}:${t})`)}async set(e,t,s,n){await this.withRetry(async()=>{let i=new Date,o={$set:{agentId:e,threadId:t,sessionId:s,updatedAt:i},$setOnInsert:{createdAt:i,compactions:0}};n?(o.$set.inputTokens=n.inputTokens,o.$set.outputTokens=n.outputTokens,o.$set.cacheReadTokens=n.cacheReadTokens,o.$set.cacheCreationTokens=n.cacheCreationTokens,o.$set.contextWindow=n.contextWindow,n.compactions>0&&(o.$inc={compactions:n.compactions},o.$set.lastCompactedAt=i,n.preCompactTokens!==void 0&&(o.$set.preCompactTokens=n.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&&zt.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(){await this.client.close()}};O();O();Ne();import{query as gk}from"@anthropic-ai/claude-agent-sdk";var Rr=k("meeting-classifier"),yk=`You are a meeting facilitator. Given a message and a list of meeting participants, decide which participants should respond.
312
312
 
313
313
  Rules:
314
314
  - If someone is addressed by name, they MUST be in the respond list.
@@ -318,15 +318,15 @@ Rules:
318
318
  - If the message is a general question to the room, pick 2-3 most relevant.
319
319
  - For "what does everyone think?" style questions, include all participants.
320
320
 
321
- Respond with ONLY a JSON object: { "respond": ["agent-id-1", "agent-id-2"] }`;function yk(r,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(r);if(s)return s;let n=r.indexOf("{"),i=r.lastIndexOf("}");if(n!==-1&&i>n){let o=t(r.slice(n,i+1));if(o)return o}return null}function wk(r,e){let s=`Participants:
321
+ Respond with ONLY a JSON object: { "respond": ["agent-id-1", "agent-id-2"] }`;function wk(r,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(r);if(s)return s;let n=r.indexOf("{"),i=r.lastIndexOf("}");if(n!==-1&&i>n){let o=t(r.slice(n,i+1));if(o)return o}return null}function Sk(r,e){let s=`Participants:
322
322
  ${r.map(n=>`- ${n.agentId} (${n.name}${n.title?`, ${n.title}`:""}): ${n.role}`).join(`
323
323
  `)}`;return e&&(s+=`
324
324
 
325
325
  Recent thread context:
326
- ${e}`),s}async function $a(r,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 n=p.modelRouter.model,i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Rr.warn("Meeting classifier timed out",{timeoutMs:p.modelRouter.timeoutMs}),i.close())},p.modelRouter.timeoutMs);try{let u=`${wk(e,t)}
326
+ ${e}`),s}async function $a(r,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 n=p.modelRouter.model,i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Rr.warn("Meeting classifier timed out",{timeoutMs:p.modelRouter.timeoutMs}),i.close())},p.modelRouter.timeoutMs);try{let u=`${Sk(e,t)}
327
327
 
328
328
  Message:
329
- ${r}`;i=mk({prompt:u,options:{model:n,systemPrompt:gk,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,thinking:{type:"disabled"},disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...p.anthropic.apiKey?{ANTHROPIC_API_KEY:p.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let m=h;if(m.type==="assistant"){let g=m.message?.content;if(Array.isArray(g))for(let f of g)f.type==="text"&&(o=f.text)}if(m.type==="result"){let g=m;a=g.total_cost_usd,l=g.duration_ms,g.subtype==="success"&&g.result&&(o=g.result)}}}catch(u){return Rr.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=yk(o,s);return d?(Rr.info("Meeting classifier decision",{respond:d,rosterSize:e.length,costUsd:a,durationMs:l}),{respondAgentIds:d,costUsd:a,durationMs:l}):(Rr.warn("Meeting classifier parse failed, selecting all roster members",{rawText:o.slice(0,200)}),{respondAgentIds:[...s],costUsd:a,durationMs:l})}var q=k("dispatcher"),Sk=80,kk=[/^status\??$/i,/^how.{0,20}(everyone|agents?|doing|running)/i,/^health\??$/i,/^system status/i],Fh=[/^no response (requested|needed|required|necessary)\.?$/i,/^\(no response\)$/i,/^n\/a\.?$/i],Br=class r{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,n,i){this.registry=e,this.agentManager=t,this.healthReporter=s,this.defaultAgentId=n,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<=Sk&&kk.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 n=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(n.length===0)return;if(n.some(d=>d.conferenceMode)){let d=e.threadId??e.id;this.threadAgentLastSeen.set(d,Date.now()),q.info("Conference fan-out",{agents:n.map(u=>u.agentId)}),await Promise.all(n.map(u=>this.dispatchToAgent(e,u)));return}if(n.length>1){let d=e.threadId??e.id;this.threadParticipants.has(d)||this.threadParticipants.set(d,new Set(n.map(u=>u.agentId))),this.threadAgentLastSeen.set(d,Date.now()),q.info("Multi-agent fan-out",{agents:n.map(u=>u.agentId)}),await Promise.all(n.map(u=>this.dispatchToAgent(e,u)));return}let{agentId:o}=n[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(Fh.some(m=>m.test(u)))q.info("Non-response suppressed",{agentId:o,source:e.source.kind,text:u,costUsd:d.costUsd,durationMs:d.durationMs});else{let m={text:d.text||"_No response._",agentId:o,workItem:e,costUsd:d.costUsd,durationMs:d.durationMs,error:d.error};if(c)try{await c.deliver(m)}catch(g){q.warn("Agent response delivery failed, queuing for retry",{error:String(g)}),this.retryQueue?.enqueue(m,c)}l&&this.taskLedger.onComplete(m).catch(g=>q.warn("Task ledger complete failed",{error:String(g)})),this.auditAdapter&&e.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(m),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()-r.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 n=this.registry.findByChannel(e.source.label);if(n)return[{agentId:n.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(m=>m.id!==d);if(l.size>0&&h){let m=new Set([d,...l]);return this.threadParticipants.set(e.threadId,m),this.threadAgentMap.delete(e.threadId),this.threadAgentLastSeen.set(e.threadId,Date.now()),q.info("Thread transitioned to multi-agent",{threadId:e.threadId,participants:[...m]}),[...m].map(g=>({agentId:g}))}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(m=>this.registry.get(m));if(h.length>1){let m=new Set(h);return this.threadParticipants.set(e.threadId,m),this.threadAgentLastSeen.set(e.threadId,Date.now()),[...m].map(g=>({agentId:g}))}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 n=this.registry.findAllByName(e.text);if(n.length>0){let o=new Set(s.members),a=n.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,n=e;if(t.conferenceMode){let l=[t.meetingPreamble,"",t.threadContext,"","---","[New message]:"].filter(Boolean).join(`
329
+ ${r}`;i=gk({prompt:u,options:{model:n,systemPrompt:yk,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,thinking:{type:"disabled"},disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...p.anthropic.apiKey?{ANTHROPIC_API_KEY:p.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let m=h;if(m.type==="assistant"){let g=m.message?.content;if(Array.isArray(g))for(let f of g)f.type==="text"&&(o=f.text)}if(m.type==="result"){let g=m;a=g.total_cost_usd,l=g.duration_ms,g.subtype==="success"&&g.result&&(o=g.result)}}}catch(u){return Rr.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=wk(o,s);return d?(Rr.info("Meeting classifier decision",{respond:d,rosterSize:e.length,costUsd:a,durationMs:l}),{respondAgentIds:d,costUsd:a,durationMs:l}):(Rr.warn("Meeting classifier parse failed, selecting all roster members",{rawText:o.slice(0,200)}),{respondAgentIds:[...s],costUsd:a,durationMs:l})}var q=k("dispatcher"),kk=80,bk=[/^status\??$/i,/^how.{0,20}(everyone|agents?|doing|running)/i,/^health\??$/i,/^system status/i],Fh=[/^no response (requested|needed|required|necessary)\.?$/i,/^\(no response\)$/i,/^n\/a\.?$/i],Br=class r{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,n,i){this.registry=e,this.agentManager=t,this.healthReporter=s,this.defaultAgentId=n,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<=kk&&bk.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 n=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(n.length===0)return;if(n.some(d=>d.conferenceMode)){let d=e.threadId??e.id;this.threadAgentLastSeen.set(d,Date.now()),q.info("Conference fan-out",{agents:n.map(u=>u.agentId)}),await Promise.all(n.map(u=>this.dispatchToAgent(e,u)));return}if(n.length>1){let d=e.threadId??e.id;this.threadParticipants.has(d)||this.threadParticipants.set(d,new Set(n.map(u=>u.agentId))),this.threadAgentLastSeen.set(d,Date.now()),q.info("Multi-agent fan-out",{agents:n.map(u=>u.agentId)}),await Promise.all(n.map(u=>this.dispatchToAgent(e,u)));return}let{agentId:o}=n[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(Fh.some(m=>m.test(u)))q.info("Non-response suppressed",{agentId:o,source:e.source.kind,text:u,costUsd:d.costUsd,durationMs:d.durationMs});else{let m={text:d.text||"_No response._",agentId:o,workItem:e,costUsd:d.costUsd,durationMs:d.durationMs,error:d.error};if(c)try{await c.deliver(m)}catch(g){q.warn("Agent response delivery failed, queuing for retry",{error:String(g)}),this.retryQueue?.enqueue(m,c)}l&&this.taskLedger.onComplete(m).catch(g=>q.warn("Task ledger complete failed",{error:String(g)})),this.auditAdapter&&e.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(m),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()-r.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 n=this.registry.findByChannel(e.source.label);if(n)return[{agentId:n.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(m=>m.id!==d);if(l.size>0&&h){let m=new Set([d,...l]);return this.threadParticipants.set(e.threadId,m),this.threadAgentMap.delete(e.threadId),this.threadAgentLastSeen.set(e.threadId,Date.now()),q.info("Thread transitioned to multi-agent",{threadId:e.threadId,participants:[...m]}),[...m].map(g=>({agentId:g}))}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(m=>this.registry.get(m));if(h.length>1){let m=new Set(h);return this.threadParticipants.set(e.threadId,m),this.threadAgentLastSeen.set(e.threadId,Date.now()),[...m].map(g=>({agentId:g}))}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 n=this.registry.findAllByName(e.text);if(n.length>0){let o=new Set(s.members),a=n.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,n=e;if(t.conferenceMode){let l=[t.meetingPreamble,"",t.threadContext,"","---","[New message]:"].filter(Boolean).join(`
330
330
  `);n={...e,text:`${l}
331
331
  ${e.text}`,meta:{...e.meta,conferenceMode:!0,conferenceHumanTs:t.conferenceHumanTs,conferenceRound:t.conferenceRound}}}let i=n.threadId??n.id;this.threadAgentLastSeen.set(i,Date.now());let o=this.taskLedger?.shouldTrack(n)??!1;o&&this.taskLedger.onDispatch(n,s).catch(l=>q.warn("Task ledger dispatch failed",{error:String(l)}));let a=this.adapters.get(n.source.adapterId??n.source.kind);try{let l=await this.agentManager.sendMessage(s,n),c=l.text.trim(),d=Fh.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:n,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&&n.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:n,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[n,i]of this.threadAgentLastSeen)i<t&&(this.threadAgentMap.delete(n),this.threadParticipants.delete(n),this.meetingRosters.delete(n),this.meetingReactionTracker.delete(n),this.threadAgentLastSeen.delete(n),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,n=this.registry.findAllByName(e.text);for(let d of n)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(`
332
332
  `)[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(m=>`${m.author}: ${m.text.slice(0,200)}`).join(`
@@ -344,8 +344,8 @@ Meeting rules:
344
344
  `)[0]}))}if(c.length===0)return;let d=await $a(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="",m="";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(`
345
345
  `)[0]})}h=this.formatThreadContext(w,t.source.label,S),m=this.buildMeetingPreamble(t.source.label,S)}let g=d.respondAgentIds.map(f=>{let y={agentId:f,conferenceMode:!0,conferenceHumanTs:n,conferenceRound:1,threadContext:h,meetingPreamble:m};return this.dispatchToAgent(t,y)});await Promise.all(g)}async postAuditLog(e){if(!this.auditAdapter||!this.auditChannelIds)return;let t=this.registry.get(e.agentId),s=t?.name??e.agentId,n=t?.homeBase,i=(n?this.auditChannelIds.get(n):void 0)??this.fallbackAuditChannelId;if(!i){q.warn("No audit channel resolved for agent",{agentId:e.agentId,homeBase:n});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}:
346
346
  > ${l}
347
- _($${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})}};O();function bk(r){let e=r;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 Kh(r){return r?bk(r.trim()):"_No response._"}function Hh(r){return`Something went wrong: ${r}`}var It=k("slack-adapter"),_k=[{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..."}],Ur=class{id;kind="slack";gateway;registry;excludeChannels;defaultAgentId;botLabel;threadContextMap=new Map;threadContextLastSeen=new Map;constructor(e,t,s=[],n="slack",i,o){this.id=n,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)){It.debug("Ignoring message from excluded channel",{channel:s.channelName});return}let n=this.registry.findByChannel(s.channelName);if(n&&n.slackBot&&n.slackBot!==this.botLabel){It.debug("Ignoring message from other bot's channel",{channel:s.channelName,owner:n.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=>{It.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,_k),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()),It.info("Thread context updated",{threadTs:s.threadTs,channelId:s.context.channelId}))}),await this.gateway.start(),It.info("Slack adapter started")}async deliver(e){let t=e.workItem.source.id,s=e.workItem.meta?.slackThreadTs??e.workItem.meta?.slackTs,n=this.registry.get(e.agentId),o=e.workItem.sender?.startsWith("B")||e.workItem.sender==="integration"?void 0:s,a=e.error?Hh(e.error):Kh(e.text);n&&(a=`${n.icon?`${n.icon} `:""}*${n.name}*: ${a}`);let l=n?{name:n.name,icon:n.icon}:void 0;await this.gateway.postMessage(t,a,o,l)}async onProcessingStart(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",n=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&n&&await this.gateway.setThreadStatus(e.source.id,n,"Thinking...")}async onProcessingEnd(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",n=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&n&&await this.gateway.setThreadStatus(e.source.id,n,"")}sweep(e){let t=Date.now()-e,s=0;for(let[n,i]of this.threadContextLastSeen)i<t&&(this.threadContextMap.delete(n),this.threadContextLastSeen.delete(n),s++);return{component:`slack-adapter:${this.id}`,pruned:s,retried:0,bytesFreed:0,errors:[]}}async stop(){await this.gateway.stop(),It.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}),n=[],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)}}n.push({author:a,text:o.text??"",timestamp:new Date(parseFloat(o.ts??"0")*1e3),isBot:l})}return n}catch(s){return It.warn("Failed to fetch thread history",{channelId:e,threadTs:t,error:String(s)}),[]}}};O();var We=k("sms-adapter"),Wh="https://api.openphone.com/v1",qr=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 n=await fetch(`${Wh}/messages`,{method:"POST",headers:{Authorization:this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({from:s,to:[t],content:e.text})});n.ok?We.info("SMS reply sent",{to:t,from:s}):We.error("Failed to send SMS reply",{status:n.status,body:await n.text(),to:t})}catch(n){We.error("SMS delivery error",{error:String(n),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(`${Wh}${e}`);for(let[i,o]of Object.entries(t))o&&s.searchParams.append(i,o);let n=await fetch(s.toString(),{headers:{Authorization:this.apiKey}});if(!n.ok)throw new Error(`Quo API ${n.status}: ${await n.text()}`);return n.json()}async poll(e){for(let t of this.lines)try{let n=(await this.quoApi("/conversations",{"phoneNumbers[]":t.id,updatedAfter:t.lastSeen,maxResults:"20"})).data??[];if(n.length===0)continue;for(let i of n){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}:
348
- ${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)})}}};O();import{execFileSync as Ok}from"node:child_process";import{readFileSync as Mk,writeFileSync as Dk,existsSync as Vh,mkdirSync as Lk}from"node:fs";import{resolve as Yh}from"node:path";import{MongoClient as Pk}from"mongodb";O();import vk from"better-sqlite3";var Gh=k("imessage-db"),Tk=978307200,Ik=43;function Ck(r){let e=r/1e9+Tk;return new Date(e*1e3)}function Ak(r){try{let e=Buffer.from("NS.string"),t=r.indexOf(e);if(t===-1){let o=Buffer.from("NS.data");t=r.indexOf(o)}if(t===-1){let o=Buffer.from("streamtyped"),a=r.indexOf(o);return a===-1?null:Ek(r,a+o.length)}for(t+=e.length;t<r.length&&r[t]<32&&r[t]!==10;)t++;let s=t,n=t;for(;n<r.length;){let o=r[n];if(o===0||o===6&&n>s+1)break;n++}if(n<=s)return null;let i=r.subarray(s,n).toString("utf-8").trim();return i.length>0?i:null}catch(e){return Gh.warn("Failed to extract text from attributedBody",{error:String(e)}),null}}function Ek(r,e){let t=e,s=-1,n=0;for(;t<r.length-1;)if(Nk(r[t])){let o=t,a=0;for(;t<r.length&&xk(r[t]);)a++,t++;a>n&&a>4&&(s=o,n=a)}else t++;if(s===-1)return null;let i=r.subarray(s,s+n).toString("utf-8").trim();return i.length>0?i:null}function Nk(r){return r>=32&&r<=126||r>=192}function xk(r){return r>=32&&r<=126||r===10||r===13||r===9||r>=128}var jr=class{db;constructor(e){let t=e??`${process.env.HOME}/Library/Messages/chat.db`;this.db=new vk(t,{readonly:!0})}getNewMessages(e){let t=this.db.prepare(`
347
+ _($${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})}};O();function _k(r){let e=r;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 Kh(r){return r?_k(r.trim()):"_No response._"}function Hh(r){return`Something went wrong: ${r}`}var It=k("slack-adapter"),vk=[{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..."}],Ur=class{id;kind="slack";gateway;registry;excludeChannels;defaultAgentId;botLabel;threadContextMap=new Map;threadContextLastSeen=new Map;constructor(e,t,s=[],n="slack",i,o){this.id=n,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)){It.debug("Ignoring message from excluded channel",{channel:s.channelName});return}let n=this.registry.findByChannel(s.channelName);if(n&&n.slackBot&&n.slackBot!==this.botLabel){It.debug("Ignoring message from other bot's channel",{channel:s.channelName,owner:n.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=>{It.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,vk),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()),It.info("Thread context updated",{threadTs:s.threadTs,channelId:s.context.channelId}))}),await this.gateway.start(),It.info("Slack adapter started")}async deliver(e){let t=e.workItem.source.id,s=e.workItem.meta?.slackThreadTs??e.workItem.meta?.slackTs,n=this.registry.get(e.agentId),o=e.workItem.sender?.startsWith("B")||e.workItem.sender==="integration"?void 0:s,a=e.error?Hh(e.error):Kh(e.text);n&&(a=`${n.icon?`${n.icon} `:""}*${n.name}*: ${a}`);let l=n?{name:n.name,icon:n.icon}:void 0;await this.gateway.postMessage(t,a,o,l)}async onProcessingStart(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",n=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&n&&await this.gateway.setThreadStatus(e.source.id,n,"Thinking...")}async onProcessingEnd(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",n=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&n&&await this.gateway.setThreadStatus(e.source.id,n,"")}sweep(e){let t=Date.now()-e,s=0;for(let[n,i]of this.threadContextLastSeen)i<t&&(this.threadContextMap.delete(n),this.threadContextLastSeen.delete(n),s++);return{component:`slack-adapter:${this.id}`,pruned:s,retried:0,bytesFreed:0,errors:[]}}async stop(){await this.gateway.stop(),It.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}),n=[],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)}}n.push({author:a,text:o.text??"",timestamp:new Date(parseFloat(o.ts??"0")*1e3),isBot:l})}return n}catch(s){return It.warn("Failed to fetch thread history",{channelId:e,threadTs:t,error:String(s)}),[]}}};O();var We=k("sms-adapter"),Wh="https://api.openphone.com/v1",qr=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 n=await fetch(`${Wh}/messages`,{method:"POST",headers:{Authorization:this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({from:s,to:[t],content:e.text})});n.ok?We.info("SMS reply sent",{to:t,from:s}):We.error("Failed to send SMS reply",{status:n.status,body:await n.text(),to:t})}catch(n){We.error("SMS delivery error",{error:String(n),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(`${Wh}${e}`);for(let[i,o]of Object.entries(t))o&&s.searchParams.append(i,o);let n=await fetch(s.toString(),{headers:{Authorization:this.apiKey}});if(!n.ok)throw new Error(`Quo API ${n.status}: ${await n.text()}`);return n.json()}async poll(e){for(let t of this.lines)try{let n=(await this.quoApi("/conversations",{"phoneNumbers[]":t.id,updatedAfter:t.lastSeen,maxResults:"20"})).data??[];if(n.length===0)continue;for(let i of n){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}:
348
+ ${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)})}}};O();import{execFileSync as Mk}from"node:child_process";import{readFileSync as Dk,writeFileSync as Lk,existsSync as Vh,mkdirSync as Pk}from"node:fs";import{resolve as Yh}from"node:path";import{MongoClient as $k}from"mongodb";O();import Tk from"better-sqlite3";var Gh=k("imessage-db"),Ik=978307200,Ck=43;function Ak(r){let e=r/1e9+Ik;return new Date(e*1e3)}function Ek(r){try{let e=Buffer.from("NS.string"),t=r.indexOf(e);if(t===-1){let o=Buffer.from("NS.data");t=r.indexOf(o)}if(t===-1){let o=Buffer.from("streamtyped"),a=r.indexOf(o);return a===-1?null:Nk(r,a+o.length)}for(t+=e.length;t<r.length&&r[t]<32&&r[t]!==10;)t++;let s=t,n=t;for(;n<r.length;){let o=r[n];if(o===0||o===6&&n>s+1)break;n++}if(n<=s)return null;let i=r.subarray(s,n).toString("utf-8").trim();return i.length>0?i:null}catch(e){return Gh.warn("Failed to extract text from attributedBody",{error:String(e)}),null}}function Nk(r,e){let t=e,s=-1,n=0;for(;t<r.length-1;)if(xk(r[t])){let o=t,a=0;for(;t<r.length&&Ok(r[t]);)a++,t++;a>n&&a>4&&(s=o,n=a)}else t++;if(s===-1)return null;let i=r.subarray(s,s+n).toString("utf-8").trim();return i.length>0?i:null}function xk(r){return r>=32&&r<=126||r>=192}function Ok(r){return r>=32&&r<=126||r===10||r===13||r===9||r>=128}var jr=class{db;constructor(e){let t=e??`${process.env.HOME}/Library/Messages/chat.db`;this.db=new Tk(t,{readonly:!0})}getNewMessages(e){let t=this.db.prepare(`
349
349
  SELECT m.ROWID AS rowId, m.text, m.attributedBody, m.is_from_me AS isFromMe,
350
350
  m.date, m.service, h.id AS sender, h.ROWID AS handleRowId
351
351
  FROM message m
@@ -357,7 +357,7 @@ ${c.text}`,u={id:c.id,text:d,source:{kind:"sms",id:t.id,label:t.routeLabel},send
357
357
  AND m.is_empty = 0
358
358
  AND (c.style IS NULL OR c.style != ?)
359
359
  ORDER BY m.ROWID ASC
360
- `).all(e,Ik),s=[];for(let n of t){let i=n.text;if(!i&&n.attributedBody&&(i=Ak(n.attributedBody),!i)){Gh.warn("Could not extract text from attributedBody, skipping",{rowId:n.rowId});continue}i&&s.push({rowId:n.rowId,text:i,sender:n.sender,handleRowId:n.handleRowId,service:n.service,date:Ck(n.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"),Fr=class{id="imessage";kind="imessage";config;mongoUri;dbName;gateway;db;mongo;threadsCollection;contactsCollection;slackChannelId;interval=null;lastSeenRowId=0;lastMessageAt=0;lastColdPoll=0;stateFilePath;constructor(e,t,s,n,i){this.config=e,this.mongoUri=t,this.dbName=s,this.gateway=n,this.stateFilePath=Yh(`/tmp/${i}-imessage-state.json`)}async start(e){this.mongo=new Pk(this.mongoUri),await this.mongo.connect();let t=this.mongo.db(this.dbName);this.threadsCollection=t.collection("imessage_threads"),this.contactsCollection=t.collection("contacts");try{let n=((await this.gateway.client.conversations.list({types:"public_channel",limit:200})).channels??[]).find(i=>i.name===this.config.slackChannel);n?.id?(this.slackChannelId=n.id,ne.info("Slack mirror channel resolved",{channel:this.config.slackChannel,id:n.id})):ne.warn("Slack mirror channel not found",{channel:this.config.slackChannel})}catch(s){ne.warn("Failed to resolve Slack mirror channel",{error:String(s)})}try{this.db=new jr}catch(s){ne.error("Failed to open chat.db \u2014 check Full Disk Access for node",{error:String(s)});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 $k(500),this.sendViaAppleScript(t,e.text),ne.info("iMessage reply sent on retry",{to:t})}catch(n){ne.error("iMessage delivery failed after retry",{error:String(n),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(),await this.mongo?.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 n=this.db.getNewMessages(this.lastSeenRowId);if(n.length===0)return;for(let i of n){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(n){ne.error("iMessage poll failed",{error:String(n)})}}sendViaAppleScript(e,t){let s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');Ok("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,n){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=n?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(Vh(this.stateFilePath)){let e=JSON.parse(Mk(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=Yh(this.stateFilePath,"..");Vh(e)||Lk(e,{recursive:!0}),Dk(this.stateFilePath,JSON.stringify({lastSeenRowId:this.lastSeenRowId}))}catch(e){ne.warn("Failed to save iMessage state",{error:String(e)})}}};function $k(r){return new Promise(e=>setTimeout(e,r))}O();var Qt=k("task-client"),Kr=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 n=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(!n.ok)throw new Error(`Task API ${n.status}: ${await n.text()}`);return n.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}}};O();var Qs=k("task-ledger"),Hr=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 n=e.threadId??e.id,i=this.threadTaskMap.get(n);if(i){this.threadTaskLastSeen.set(n,Date.now()),await this.addComment(i,s,this.formatIncomingComment(e));return}let o=await this.createTask(s,e);o&&(this.threadTaskMap.set(n,o),this.threadTaskLastSeen.set(n,Date.now()))}async onComplete(e){let t=this.getApiKey(e.agentId);if(!t)return;let s=e.workItem.threadId??e.workItem.id,n=this.threadTaskMap.get(s);if(n&&this.threadTaskLastSeen.set(s,Date.now()),!n)return;let i=this.formatCompletionComment(e);await this.addComment(n,t,i),e.error||await this.updateTask(n,t,{state:"DONE"})}sweep(e){let t=Date.now()-e,s=0;for(let[n,i]of this.threadTaskLastSeen)i<t&&(this.threadTaskMap.delete(n),this.threadTaskLastSeen.delete(n),s++);return{component:"task-ledger",pruned:s,retried:0,bytesFreed:0,errors:[]}}getApiKey(e){let t=this.agentKeys[e]??this.fallbackKey;return t||(Qs.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 Qs.info("Task created",{taskId:s.taskId,source:t.source.kind}),s.taskId}catch(s){return Qs.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(n){Qs.error("Failed to add comment",{error:String(n),taskId:e})}}async updateTask(e,t,s){try{await this.api("PUT",`/tasks/${e}`,t,s)}catch(n){Qs.error("Failed to update task",{error:String(n),taskId:e})}}async api(e,t,s,n){let i=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":s,...n?{"Content-Type":"application/json"}:{}},...n?{body:JSON.stringify(n)}:{}});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 n=t.match(/Command: `(.+?)`/);if(n)return`[Background] ${n[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,n=e.text.length>s?e.text.slice(0,s)+`
360
+ `).all(e,Ck),s=[];for(let n of t){let i=n.text;if(!i&&n.attributedBody&&(i=Ek(n.attributedBody),!i)){Gh.warn("Could not extract text from attributedBody, skipping",{rowId:n.rowId});continue}i&&s.push({rowId:n.rowId,text:i,sender:n.sender,handleRowId:n.handleRowId,service:n.service,date:Ak(n.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"),Fr=class{id="imessage";kind="imessage";config;mongoUri;dbName;gateway;db;mongo;threadsCollection;contactsCollection;slackChannelId;interval=null;lastSeenRowId=0;lastMessageAt=0;lastColdPoll=0;stateFilePath;constructor(e,t,s,n,i){this.config=e,this.mongoUri=t,this.dbName=s,this.gateway=n,this.stateFilePath=Yh(`/tmp/${i}-imessage-state.json`)}async start(e){this.mongo=new $k(this.mongoUri),await this.mongo.connect();let t=this.mongo.db(this.dbName);this.threadsCollection=t.collection("imessage_threads"),this.contactsCollection=t.collection("contacts");try{let n=((await this.gateway.client.conversations.list({types:"public_channel",limit:200})).channels??[]).find(i=>i.name===this.config.slackChannel);n?.id?(this.slackChannelId=n.id,ne.info("Slack mirror channel resolved",{channel:this.config.slackChannel,id:n.id})):ne.warn("Slack mirror channel not found",{channel:this.config.slackChannel})}catch(s){ne.warn("Failed to resolve Slack mirror channel",{error:String(s)})}try{this.db=new jr}catch(s){ne.error("Failed to open chat.db \u2014 check Full Disk Access for node",{error:String(s)});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 Rk(500),this.sendViaAppleScript(t,e.text),ne.info("iMessage reply sent on retry",{to:t})}catch(n){ne.error("iMessage delivery failed after retry",{error:String(n),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(),await this.mongo?.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 n=this.db.getNewMessages(this.lastSeenRowId);if(n.length===0)return;for(let i of n){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(n){ne.error("iMessage poll failed",{error:String(n)})}}sendViaAppleScript(e,t){let s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');Mk("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,n){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=n?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(Vh(this.stateFilePath)){let e=JSON.parse(Dk(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=Yh(this.stateFilePath,"..");Vh(e)||Pk(e,{recursive:!0}),Lk(this.stateFilePath,JSON.stringify({lastSeenRowId:this.lastSeenRowId}))}catch(e){ne.warn("Failed to save iMessage state",{error:String(e)})}}};function Rk(r){return new Promise(e=>setTimeout(e,r))}O();var Qt=k("task-client"),Kr=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 n=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(!n.ok)throw new Error(`Task API ${n.status}: ${await n.text()}`);return n.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}}};O();var Qs=k("task-ledger"),Hr=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 n=e.threadId??e.id,i=this.threadTaskMap.get(n);if(i){this.threadTaskLastSeen.set(n,Date.now()),await this.addComment(i,s,this.formatIncomingComment(e));return}let o=await this.createTask(s,e);o&&(this.threadTaskMap.set(n,o),this.threadTaskLastSeen.set(n,Date.now()))}async onComplete(e){let t=this.getApiKey(e.agentId);if(!t)return;let s=e.workItem.threadId??e.workItem.id,n=this.threadTaskMap.get(s);if(n&&this.threadTaskLastSeen.set(s,Date.now()),!n)return;let i=this.formatCompletionComment(e);await this.addComment(n,t,i),e.error||await this.updateTask(n,t,{state:"DONE"})}sweep(e){let t=Date.now()-e,s=0;for(let[n,i]of this.threadTaskLastSeen)i<t&&(this.threadTaskMap.delete(n),this.threadTaskLastSeen.delete(n),s++);return{component:"task-ledger",pruned:s,retried:0,bytesFreed:0,errors:[]}}getApiKey(e){let t=this.agentKeys[e]??this.fallbackKey;return t||(Qs.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 Qs.info("Task created",{taskId:s.taskId,source:t.source.kind}),s.taskId}catch(s){return Qs.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(n){Qs.error("Failed to add comment",{error:String(n),taskId:e})}}async updateTask(e,t,s){try{await this.api("PUT",`/tasks/${e}`,t,s)}catch(n){Qs.error("Failed to update task",{error:String(n),taskId:e})}}async api(e,t,s,n){let i=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":s,...n?{"Content-Type":"application/json"}:{}},...n?{body:JSON.stringify(n)}:{}});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 n=t.match(/Command: `(.+?)`/);if(n)return`[Background] ${n[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,n=e.text.length>s?e.text.slice(0,s)+`
361
361
 
362
362
  ... (truncated)`:e.text;return t.push("","---","",n),t.join(`
363
363
  `)}formatIncomingComment(e){return`**Follow-up message** (${e.source.kind})
@@ -366,17 +366,17 @@ ${e.text.slice(0,5e3)}`}formatCompletionComment(e){let t=[`**Agent response** ($
366
366
  **Error:** ${e.error}`);let s=5e3,n=e.text.length>s?e.text.slice(0,s)+`
367
367
 
368
368
  ... (truncated)`:e.text;return t.push("",n),t.join(`
369
- `)}};O();import{createServer as Rk}from"node:http";import{spawn as Bk}from"node:child_process";import{mkdir as Uk,readFile as Jh,writeFile as qk,readdir as jk,stat as Fk,unlink as Kk}from"node:fs/promises";import{openSync as Hk,closeSync as Wk}from"node:fs";import{randomUUID as Gk}from"node:crypto";var we=k("bg-task-manager"),Ra=100,Vk=5e3,Wr=class{port;authToken;tasksDir;tasks=new Map;onComplete;server=null;orphanPollers=new Map;constructor(e,t,s,n){this.port=e,this.authToken=t,this.tasksDir=s,this.onComplete=n}async start(){await Uk(this.tasksDir,{recursive:!0}),this.server=Rk((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 jk(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".json")),s=0,n=0;for(let i of t)try{let o=await Jh(`${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),n++):(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||n>0)&&we.info("Orphan scan complete",{orphaned:s,recovered:n,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(Vk);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=Gk(),s=`${this.tasksDir}/${t}.log`,n=`${this.tasksDir}/${t}.json`,i=e.cwd??process.env.HOME??"/tmp",o=Hk(s,"a"),a=Bk(e.command,e.args??[],{cwd:i,detached:!0,stdio:["ignore",o,o]});Wk(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:n,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(),n=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-t)/1e3).toFixed(1);this.tailLog(e.logPath,Ra).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: ${n}s`,`Output (last ${Ra} lines):`,"```",i||"(no output)","```"].join(`
370
- `),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:n,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,Ra);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 qk(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 Jh(e,"utf-8")).split(`
369
+ `)}};O();import{createServer as Bk}from"node:http";import{spawn as Uk}from"node:child_process";import{mkdir as qk,readFile as Jh,writeFile as jk,readdir as Fk,stat as Kk,unlink as Hk}from"node:fs/promises";import{openSync as Wk,closeSync as Gk}from"node:fs";import{randomUUID as Vk}from"node:crypto";var we=k("bg-task-manager"),Ra=100,Yk=5e3,Wr=class{port;authToken;tasksDir;tasks=new Map;onComplete;server=null;orphanPollers=new Map;constructor(e,t,s,n){this.port=e,this.authToken=t,this.tasksDir=s,this.onComplete=n}async start(){await qk(this.tasksDir,{recursive:!0}),this.server=Bk((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 Fk(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".json")),s=0,n=0;for(let i of t)try{let o=await Jh(`${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),n++):(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||n>0)&&we.info("Orphan scan complete",{orphaned:s,recovered:n,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(Yk);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=Vk(),s=`${this.tasksDir}/${t}.log`,n=`${this.tasksDir}/${t}.json`,i=e.cwd??process.env.HOME??"/tmp",o=Wk(s,"a"),a=Uk(e.command,e.args??[],{cwd:i,detached:!0,stdio:["ignore",o,o]});Gk(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:n,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(),n=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-t)/1e3).toFixed(1);this.tailLog(e.logPath,Ra).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: ${n}s`,`Output (last ${Ra} lines):`,"```",i||"(no output)","```"].join(`
370
+ `),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:n,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,Ra);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 jk(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 Jh(e,"utf-8")).split(`
371
371
  `).slice(-t).join(`
372
- `).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 n=this.tasks.get(e);n&&n.status==="running"&&(n.status="orphaned",n.completedAt=new Date().toISOString(),this.writeMeta(n).then(()=>this.fireCompletion(n)))}},5e3);this.orphanPollers.set(e,s)}async sweep(e){let t=Date.now()-e,s=0,n=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 Fk(c);n+=d.size,await Kk(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:n,errors:i}}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();import{createServer as Qk}from"node:http";import{spawn as Xk}from"node:child_process";import{mkdir as Zk,readFile as Gr,writeFile as eb,readdir as tb,stat as sb,unlink as nb,open as rb}from"node:fs/promises";import{openSync as Zh,closeSync as ef}from"node:fs";import{randomUUID as ib}from"node:crypto";function zh(r){let e=r.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 Yk=/\*{0,2}Status:?\*{0,2}\s+(NEEDS_CONTEXT|BLOCKED)/i,Jk=/\*{0,2}Question:?\*{0,2}\s+(.+?)(?:\n\n|\n\*{0,2}(?:Context|Status|Files|What)|$)/is,zk=/\*{0,2}Context:?\*{0,2}\s+(.+?)(?:\n\n\*{0,2}(?:Status|Question|Files|To respond)|$)/is;function Qh(r){if(!r)return null;let e=Yk.exec(r);if(!e)return null;let t=e[1].toUpperCase(),n=Jk.exec(r)?.[1]?.trim()??"",o=zk.exec(r)?.[1]?.trim()??"";return{status:t,question:n,context:o}}function Xh(r,e,t){return t||e?.subtype==="error_max_turns"||e?.subtype==="error_max_budget_usd"?"needs_input":r===0&&e?.subtype==="success"||r===0&&!e?"completed":"failed"}var ee=k("code-task-manager"),Xs=2e3,Ba=100,tf=5e3,Vr=class{port;authToken;pluginDirs;maxConcurrent;tasksDir;cliBin;options;tasks=new Map;onComplete;server=null;orphanPollers=new Map;reapTimers=new Set;constructor(e,t,s,n,i,o,a){this.port=e,this.authToken=t,this.pluginDirs=s,this.maxConcurrent=n,this.tasksDir=i,this.onComplete=o,this.options=a??{},this.cliBin=this.options.cliBin??"claude"}async start(){await Zk(this.tasksDir,{recursive:!0}),this.server=Qk((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 tb(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".meta.json")),s=0,n=0;for(let i of t)try{let o=await Gr(`${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),n++):(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||n>0)&&ee.info("Orphan scan complete",{orphaned:s,recovered:n,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(tf);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(),n=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"))},tf);this.reapTimers.add(c),n++}return(n>0||i>0)&&ee.info("Stale reap complete",{reaped:n,spared:i}),{reaped:n,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=ib(),n=`${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+`
372
+ `).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 n=this.tasks.get(e);n&&n.status==="running"&&(n.status="orphaned",n.completedAt=new Date().toISOString(),this.writeMeta(n).then(()=>this.fireCompletion(n)))}},5e3);this.orphanPollers.set(e,s)}async sweep(e){let t=Date.now()-e,s=0,n=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 Kk(c);n+=d.size,await Hk(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:n,errors:i}}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();import{createServer as Xk}from"node:http";import{spawn as Zk}from"node:child_process";import{mkdir as eb,readFile as Gr,writeFile as tb,readdir as sb,stat as nb,unlink as rb,open as ib}from"node:fs/promises";import{openSync as Zh,closeSync as ef}from"node:fs";import{randomUUID as ob}from"node:crypto";function zh(r){let e=r.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 Jk=/\*{0,2}Status:?\*{0,2}\s+(NEEDS_CONTEXT|BLOCKED)/i,zk=/\*{0,2}Question:?\*{0,2}\s+(.+?)(?:\n\n|\n\*{0,2}(?:Context|Status|Files|What)|$)/is,Qk=/\*{0,2}Context:?\*{0,2}\s+(.+?)(?:\n\n\*{0,2}(?:Status|Question|Files|To respond)|$)/is;function Qh(r){if(!r)return null;let e=Jk.exec(r);if(!e)return null;let t=e[1].toUpperCase(),n=zk.exec(r)?.[1]?.trim()??"",o=Qk.exec(r)?.[1]?.trim()??"";return{status:t,question:n,context:o}}function Xh(r,e,t){return t||e?.subtype==="error_max_turns"||e?.subtype==="error_max_budget_usd"?"needs_input":r===0&&e?.subtype==="success"||r===0&&!e?"completed":"failed"}var ee=k("code-task-manager"),Xs=2e3,Ba=100,tf=5e3,Vr=class{port;authToken;pluginDirs;maxConcurrent;tasksDir;cliBin;options;tasks=new Map;onComplete;server=null;orphanPollers=new Map;reapTimers=new Set;constructor(e,t,s,n,i,o,a){this.port=e,this.authToken=t,this.pluginDirs=s,this.maxConcurrent=n,this.tasksDir=i,this.onComplete=o,this.options=a??{},this.cliBin=this.options.cliBin??"claude"}async start(){await eb(this.tasksDir,{recursive:!0}),this.server=Xk((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 sb(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".meta.json")),s=0,n=0;for(let i of t)try{let o=await Gr(`${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),n++):(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||n>0)&&ee.info("Orphan scan complete",{orphaned:s,recovered:n,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(tf);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(),n=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"))},tf);this.reapTimers.add(c),n++}return(n>0||i>0)&&ee.info("Stale reap complete",{reaped:n,spared:i}),{reaped:n,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=ob(),n=`${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+`
373
373
 
374
374
  ---
375
375
 
376
376
  `+e.prompt)}catch(S){ee.warn(`Prefetch failed for task, proceeding without context: ${S}`)}let h=e.sessionId?u:u+`
377
377
 
378
378
  ---
379
- 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.`,m=this.buildArgs({prompt:h,maxTurns:c,maxBudget:d,model:l,sessionId:e.sessionId}),g=Zh(n,"w"),f=Zh(i,"w"),y=Xk(this.cliBin,m,{cwd:a,detached:!0,stdio:["ignore",g,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)}),ef(g),ef(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:n,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 n=this.tasks.get(e);if(!n)throw new Error(`Task ${e} not found`);if(n.status!=="needs_input")throw new Error(`Task ${e} is ${n.status}, not needs_input`);if(!n.sessionId)throw new Error(`Task ${e} has no session ID for resume`);return n.status="running",this.spawnTask({prompt:t,cwd:n.cwd,model:n.model,maxTurns:n.maxTurns,maxBudget:n.maxBudget,sessionId:n.sessionId,context:s??n.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 n=null;try{let o=await Gr(s.stdoutPath,"utf-8");n=zh(o)}catch{}n&&(s.sessionId=n.sessionId,s.costUsd=n.costUsd,s.numTurns=n.numTurns);let i=n?Qh(n.result):null;s.escalation=i,s.status=Xh(s.exitCode,n,i),await this.writeMeta(s),this.fireCompletion(s,n)}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(`
379
+ 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.`,m=this.buildArgs({prompt:h,maxTurns:c,maxBudget:d,model:l,sessionId:e.sessionId}),g=Zh(n,"w"),f=Zh(i,"w"),y=Zk(this.cliBin,m,{cwd:a,detached:!0,stdio:["ignore",g,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)}),ef(g),ef(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:n,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 n=this.tasks.get(e);if(!n)throw new Error(`Task ${e} not found`);if(n.status!=="needs_input")throw new Error(`Task ${e} is ${n.status}, not needs_input`);if(!n.sessionId)throw new Error(`Task ${e} has no session ID for resume`);return n.status="running",this.spawnTask({prompt:t,cwd:n.cwd,model:n.model,maxTurns:n.maxTurns,maxBudget:n.maxBudget,sessionId:n.sessionId,context:s??n.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 n=null;try{let o=await Gr(s.stdoutPath,"utf-8");n=zh(o)}catch{}n&&(s.sessionId=n.sessionId,s.costUsd=n.costUsd,s.numTurns=n.numTurns);let i=n?Qh(n.result):null;s.escalation=i,s.status=Xh(s.exitCode,n,i),await this.writeMeta(s),this.fireCompletion(s,n)}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(`
380
380
  `)}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 ${Xs} chars):`,"```",(t.result||"(no output)").slice(-Xs),"```"].join(`
381
381
  `)}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 ${Xs} chars):`,"```",c.slice(-Xs),"```"].join(`
382
382
  `)}let a="";try{a=(await Gr(e.stderrPath,"utf-8")).split(`
@@ -388,15 +388,15 @@ ${l}
388
388
  `:"",`Stderr (last ${Ba} lines):`,"```",a||"(empty)","```"].filter(Boolean).join(`
389
389
  `)})().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 Gr(t.stderrPath,"utf-8")).split(`
390
390
  `).slice(-Ba).join(`
391
- `).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,n=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 sb(c);n+=d.size,await nb(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:n,errors:i}}async writeMeta(e){try{await eb(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 n=this.tasks.get(e);n&&n.status==="running"&&(n.status="orphaned",n.completedAt=new Date().toISOString(),this.writeMeta(n).then(()=>this.fireCompletion(n)))}},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 rb(e,"r"),n=await s.stat();return await s.close(),Date.now()-n.mtimeMs<t}catch{return!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();import{createServer as ob}from"node:http";import{randomUUID as ab}from"node:crypto";var re=k("meeting-monitor"),cb=1e4,lb=15e3,db=2,ub=new Set(["done","fatal","call_ended","media_expired","recording_permission_denied"]),Yr=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=ob((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 n=s.pathname.match(/^\/meetings\/([a-f0-9-]+)\/stop$/);if(e.method==="POST"&&n){let i=n[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,n=t.data?.bot?.id;if(!n){re.warn("Webhook missing bot ID",{event:s});return}let i=this.sessionsByBotId.get(n);if(!i){re.warn("Webhook for unknown bot",{botId:n,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:n,event:s,speaker:c,wordCount:d.split(" ").length})}catch(t){re.error("Webhook parse error",{error:String(t)})}}createSession(e){let t=ab(),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(n=>{re.error("Poll session error",{sessionId:t,botId:s.botId,error:String(n)})})},cb),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>=lb&&s||t.idlePollCount>=db&&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 n=await s.json(),i=n.status_changes;if(Array.isArray(i)&&i.length>0){let o=i[i.length-1].code;if(ub.has(o)){re.info("Meeting reached terminal status",{sessionId:e.id,botId:e.botId,statusCode:o});let a=await this.fetchFullTranscript(e,n);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 n of e.activePartials.values())t.push({speaker:n.speaker,text:`${n.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(n=>`[${n.speaker}]: ${n.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(`
391
+ `).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,n=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 nb(c);n+=d.size,await rb(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:n,errors:i}}async writeMeta(e){try{await tb(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 n=this.tasks.get(e);n&&n.status==="running"&&(n.status="orphaned",n.completedAt=new Date().toISOString(),this.writeMeta(n).then(()=>this.fireCompletion(n)))}},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 ib(e,"r"),n=await s.stat();return await s.close(),Date.now()-n.mtimeMs<t}catch{return!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();import{createServer as ab}from"node:http";import{randomUUID as cb}from"node:crypto";var re=k("meeting-monitor"),lb=1e4,db=15e3,ub=2,hb=new Set(["done","fatal","call_ended","media_expired","recording_permission_denied"]),Yr=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=ab((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 n=s.pathname.match(/^\/meetings\/([a-f0-9-]+)\/stop$/);if(e.method==="POST"&&n){let i=n[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,n=t.data?.bot?.id;if(!n){re.warn("Webhook missing bot ID",{event:s});return}let i=this.sessionsByBotId.get(n);if(!i){re.warn("Webhook for unknown bot",{botId:n,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:n,event:s,speaker:c,wordCount:d.split(" ").length})}catch(t){re.error("Webhook parse error",{error:String(t)})}}createSession(e){let t=cb(),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(n=>{re.error("Poll session error",{sessionId:t,botId:s.botId,error:String(n)})})},lb),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>=db&&s||t.idlePollCount>=ub&&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 n=await s.json(),i=n.status_changes;if(Array.isArray(i)&&i.length>0){let o=i[i.length-1].code;if(hb.has(o)){re.info("Meeting reached terminal status",{sessionId:e.id,botId:e.botId,statusCode:o});let a=await this.fetchFullTranscript(e,n);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 n of e.activePartials.values())t.push({speaker:n.speaker,text:`${n.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(n=>`[${n.speaker}]: ${n.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(`
392
392
  `),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(n=>`[${n.speaker}]: ${n.text}`),"","---","Meeting has ended. Produce a summary: key decisions made, action items with owners, and open questions."].join(`
393
393
  `),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[n,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(n),s++));return{component:"meeting-monitor",pruned:s,retried:0,bytesFreed:0,errors:[]}}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();var Jr=k("retry-queue"),zr=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()}),Jr.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 n of this.entries){if(n.nextRetryAt>e){s.push(n),t.pending++;continue}n.attempts++;try{await n.adapter.deliver(n.result),t.retried++,Jr.info("Retry delivery succeeded",{agentId:n.result.agentId,adapterId:n.adapter.id,attempt:n.attempts})}catch(i){if(n.attempts>=this.config.maxAttempts){t.dropped++;let o=`Dropped after ${n.attempts} attempts: ${String(i)}`;t.errors.push(o),Jr.error("Retry delivery exhausted",{agentId:n.result.agentId,adapterId:n.adapter.id,attempts:n.attempts,error:String(i)})}else n.nextRetryAt=e+this.config.baseDelayMs*Math.pow(2,n.attempts),s.push(n),t.pending++,Jr.warn("Retry delivery failed, will retry",{agentId:n.result.agentId,adapterId:n.adapter.id,attempt:n.attempts,nextRetryAt:new Date(n.nextRetryAt).toISOString(),error:String(i)})}}return this.entries=s,t}get size(){return this.entries.length}};O();var Ge=k("sweeper"),Qr=class r{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 n=e.memorySweepIntervalHours??6;this.memorySweepEvery=Math.round(n*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>=r.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(),m=h-this.lastDreamAt>u,g=this.memoryCycleCounter===0,f=!1;if(m&&!g){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(m&&(g||f)){let y=g?"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,n=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=n===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:n,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,n,i,o,a),t}async reportToTaskLedger(e,t,s,n,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(n)}`,i.length>0?`Errors: ${i.join(", ")}`:null].filter(Boolean).join(`
394
- `);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]}`}};O();import{readdirSync as nf,readFileSync as hb,rmSync as fb,statSync as pb,existsSync as Xr}from"node:fs";import{resolve as Ua,join as rf,sep as sf}from"node:path";var Zs=k("retention"),Zr=class{config;deps;timer=null;constructor(e,t){this.config=e,this.deps=t}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>Zs.error("Retention sweep failed",{error:String(e)}))},this.config.intervalMs),Zs.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),Zs.info("Retention sweeper stopped")}async sweep(){let e=new Date,t=[],s=[],n=[];for(let[o,a]of Object.entries(this.config.paths))if(a.days!==0)for(let l of mb(this.deps.hiveHome,o))try{gb(l,o,a.days,e,t)}catch(c){n.push({path:l,error:String(c)})}if(this.config.enabled)for(let o of t)try{fb(o.path,{recursive:!0,force:!0}),s.push(o)}catch(a){n.push({path:o.path,error:String(a)})}let i={sweptAt:e,dryRun:!this.config.enabled,candidates:t,deleted:s,errors:n};try{await this.deps.report(wb(i))}catch(o){Zs.warn("Retention report delivery failed",{error:String(o)})}return i}};function mb(r,e){let t=e.split("/"),s=t.indexOf("*");if(s===-1){let a=Ua(r,e);return Xr(a)?[a]:[]}if(t.indexOf("*",s+1)!==-1)throw new Error(`Retention rules support at most one '*' segment: ${e}`);let n=t.slice(0,s).join(sf),i=t.slice(s+1).join(sf),o=Ua(r,n);return Xr(o)?nf(o,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>Ua(o,a.name,i)).filter(a=>Xr(a)):[]}function gb(r,e,t,s,n){let i=yb(r)??t;if(i===0)return;let o=s.getTime()-i*864e5,a=nf(r,{withFileTypes:!0});for(let l of a){if(l.name===".retention-days")continue;let c=rf(r,l.name),d;try{d=pb(c)}catch{continue}d.mtimeMs<=o&&n.push({path:c,rule:e,days:i,mtime:d.mtime,ageDays:(s.getTime()-d.mtimeMs)/864e5})}}function yb(r){let e=rf(r,".retention-days");if(!Xr(e))return null;let t=hb(e,"utf-8").trim(),s=Number(t);return!Number.isFinite(s)||s<0||!Number.isInteger(s)?(Zs.warn("Invalid .retention-days override \u2014 ignoring",{path:e,raw:t}),null):s}function wb(r){let e=r.dryRun?"would delete":"deleted",t=[`*Retention sweep* (${r.dryRun?"dry-run":"enforced"}) @ ${r.sweptAt.toISOString()}`,`${r.candidates.length} candidates \xB7 ${e} ${r.dryRun?r.candidates.length:r.deleted.length} \xB7 ${r.errors.length} errors`],s=r.candidates.slice(0,10);if(s.length){t.push("```");for(let n of s)t.push(`${n.path} (age ${n.ageDays.toFixed(1)}d, rule ${n.rule}@${n.days}d)`);r.candidates.length>s.length&&t.push(`\u2026 and ${r.candidates.length-s.length} more`),t.push("```")}return r.errors.length&&t.push(`Errors: ${r.errors.slice(0,3).map(n=>`${n.path}: ${n.error}`).join(" | ")}`),t.join(`
395
- `)}Ys();O();import{MongoClient as Sb}from"mongodb";var kb=k("memory-store"),ei=class{mongoUri;dbName;client;db;collection;constructor(e,t){this.mongoUri=e,this.dbName=t,this.client=new Sb(e)}async init(){await this.client.connect(),this.db=this.client.db(this.dbName),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}),kb.info("Memory store initialized",{db:this.dbName})}getCollection(){return this.collection}async save(e,t,s,n,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:n,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,n){let i={content:t,updatedAt:new Date};return s&&(i.importance=s),n&&(i.qdrantPointId=n),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((n,i)=>{if(n.pinned!==i.pinned)return n.pinned?-1:1;let o=(t[i.importance]??0)-(t[n.importance]??0);return o!==0?o:i.updatedAt.getTime()-n.updatedAt.getTime()})}async getHotTierWithStats(e){let t=await this.getHotTier(e),s=Date.now();return t.map(n=>({...n,ageDays:Math.floor((s-n.createdAt.getTime())/(1e3*60*60*24)),daysSinceAccess:Math.floor((s-n.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 n of t){let i=s.get(n.topic)??[];i.push(n),s.set(n.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 n of t){let i=s.get(n.topic)??[];i.push(n),s.set(n.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 n={agentId:e,pinned:!1,purged:{$ne:!0}};return t.topic!==void 0&&(n.topic=t.topic),t.type!==void 0&&(n.type=t.type),t.importance!==void 0&&(n.importance=t.importance),t.tier!==void 0&&(n.tier=t.tier),t.olderThan!==void 0&&(n.updatedAt={$lt:t.olderThan}),(await this.collection.updateMany(n,{$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 n=s.map(i=>i._id);return await this.collection.deleteMany({_id:{$in:n}}),s}async getAgentIds(){return this.collection.distinct("agentId")}async close(){await this.client.close()}};O();Cr();import{QdrantClient as bb}from"@qdrant/js-client-rest";var _b=k("memory-embedder"),Ct="agent_memory",ti=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 bb({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(n=>n.name===Ct)){let n=await this.embed("test");await e.createCollection(Ct,{vectors:{size:n.length,distance:"Cosine"}}),_b.info("Created Qdrant collection",{collection:Ct,vectorSize:n.length})}this.collectionReady=!0}async upsert(e,t,s){await this.ensureCollection();let n=await this.embed(t);await this.getClient().upsert(Ct,{points:[{id:e,vector:n,payload:s}]})}async remove(e){await this.ensureCollection(),await this.getClient().delete(Ct,{points:[e]})}async search(e,t,s){await this.ensureCollection();let n=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:n,limit:i,with_payload:!0,filter:{must:o}})).map(l=>({mongoId:l.payload?.mongoId,score:l.score}))}async findSimilar(e,t,s,n=10){return await this.ensureCollection(),(await this.getClient().query(Ct,{query:{recommend:{positive:[e]}},filter:{must:[{key:"agentId",match:{value:t}}]},limit:n,with_payload:!0,score_threshold:s})).points.map(o=>({mongoId:o.payload?.mongoId,score:o.score??0,pointId:typeof o.id=="string"?o.id:String(o.id)}))}};O();import{ObjectId as vb}from"mongodb";import{query as si}from"@anthropic-ai/claude-agent-sdk";var of={critical:1,high:.75,medium:.5,low:.25},af={decision:1,fact:.8,preference:.8,summary:.6,task:.5,interaction:.3};var Me=k("memory-lifecycle"),ni=class{store;embedder;config;dreamConfig;getActiveAgentIds;constructor(e,t,s,n,i){this.store=e,this.embedder=t,this.config=s,this.dreamConfig=n,this.getActiveAgentIds=i}async filterActiveAgents(e){if(!this.getActiveAgentIds)return e;let t=await this.getActiveAgentIds(),s=e.filter(i=>t.has(i)),n=e.length-s.length;return n>0&&Me.debug("Skipped retired agents",{skipped:n,retiredIds:e.filter(i=>!t.has(i))}),s}computeScore(e,t){let s=of[e.importance]??.5,n=af[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+n*.1}estimateTokens(e){return Math.ceil(e.length/4)}async sweep(){let e=Date.now(),t=0,s=0,n=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,n+=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+n+i+o>0&&Me.info("Memory lifecycle sweep complete",{durationMs:Date.now()-e,promoted:t,demoted:s,summarized:n,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,n=await this.store.getAllNonPinned(e),i=0,o=0;if(n.length>0){let d=n.map(w=>w.accessCount).sort((w,S)=>w-S),u=d[Math.floor(d.length/2)]??0,h=n.map(w=>({record:w,score:this.computeScore(w,u)})),m=[];for(let{record:w,score:S}of h){let _;S>=this.config.hotThreshold?_="hot":S>=this.config.warmThreshold?_="warm":_="cold",_!==w.tier&&(m.push({id:w._id,newTier:_}),_==="hot"&&w.tier!=="hot"&&t++,_!=="hot"&&w.tier==="hot"&&s++)}for(let w of["hot","warm","cold"]){let S=m.filter(_=>_.newTier===w).map(_=>_.id);await this.store.setTierBulk(S,w)}let g=await this.store.getHotTier(e),f=0,y=[];for(let w of g){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,n=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 m=await this.promotePatterns(d);n+=m.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+n+i>0&&Me.info("autoDream complete",{durationMs:Date.now()-e,merged:t,contradictions:s,promoted:n,flaggedForReview:i,errors:o.length}),{merged:t,contradictions:s,promoted:n,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 n=new Set,i=0,o=0;for(let a of s){if(o>=t.maxClustersPerRun)break;if(n.has(a.qdrantPointId))continue;let c=(await this.embedder.findSimilar(a.qdrantPointId,e,t.similarityThreshold,10)).filter(I=>!n.has(I.pointId));if(c.length===0)continue;n.add(a.qdrantPointId);for(let I of c)n.add(I.pointId);let d=c.map(I=>new vb(I.mongoId)),u=await this.store.getByIds(d),h=[a,...u],g=["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(`
394
+ `);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]}`}};O();import{readdirSync as nf,readFileSync as fb,rmSync as pb,statSync as mb,existsSync as Xr}from"node:fs";import{resolve as Ua,join as rf,sep as sf}from"node:path";var Zs=k("retention"),Zr=class{config;deps;timer=null;constructor(e,t){this.config=e,this.deps=t}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>Zs.error("Retention sweep failed",{error:String(e)}))},this.config.intervalMs),Zs.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),Zs.info("Retention sweeper stopped")}async sweep(){let e=new Date,t=[],s=[],n=[];for(let[o,a]of Object.entries(this.config.paths))if(a.days!==0)for(let l of gb(this.deps.hiveHome,o))try{yb(l,o,a.days,e,t)}catch(c){n.push({path:l,error:String(c)})}if(this.config.enabled)for(let o of t)try{pb(o.path,{recursive:!0,force:!0}),s.push(o)}catch(a){n.push({path:o.path,error:String(a)})}let i={sweptAt:e,dryRun:!this.config.enabled,candidates:t,deleted:s,errors:n};try{await this.deps.report(Sb(i))}catch(o){Zs.warn("Retention report delivery failed",{error:String(o)})}return i}};function gb(r,e){let t=e.split("/"),s=t.indexOf("*");if(s===-1){let a=Ua(r,e);return Xr(a)?[a]:[]}if(t.indexOf("*",s+1)!==-1)throw new Error(`Retention rules support at most one '*' segment: ${e}`);let n=t.slice(0,s).join(sf),i=t.slice(s+1).join(sf),o=Ua(r,n);return Xr(o)?nf(o,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>Ua(o,a.name,i)).filter(a=>Xr(a)):[]}function yb(r,e,t,s,n){let i=wb(r)??t;if(i===0)return;let o=s.getTime()-i*864e5,a=nf(r,{withFileTypes:!0});for(let l of a){if(l.name===".retention-days")continue;let c=rf(r,l.name),d;try{d=mb(c)}catch{continue}d.mtimeMs<=o&&n.push({path:c,rule:e,days:i,mtime:d.mtime,ageDays:(s.getTime()-d.mtimeMs)/864e5})}}function wb(r){let e=rf(r,".retention-days");if(!Xr(e))return null;let t=fb(e,"utf-8").trim(),s=Number(t);return!Number.isFinite(s)||s<0||!Number.isInteger(s)?(Zs.warn("Invalid .retention-days override \u2014 ignoring",{path:e,raw:t}),null):s}function Sb(r){let e=r.dryRun?"would delete":"deleted",t=[`*Retention sweep* (${r.dryRun?"dry-run":"enforced"}) @ ${r.sweptAt.toISOString()}`,`${r.candidates.length} candidates \xB7 ${e} ${r.dryRun?r.candidates.length:r.deleted.length} \xB7 ${r.errors.length} errors`],s=r.candidates.slice(0,10);if(s.length){t.push("```");for(let n of s)t.push(`${n.path} (age ${n.ageDays.toFixed(1)}d, rule ${n.rule}@${n.days}d)`);r.candidates.length>s.length&&t.push(`\u2026 and ${r.candidates.length-s.length} more`),t.push("```")}return r.errors.length&&t.push(`Errors: ${r.errors.slice(0,3).map(n=>`${n.path}: ${n.error}`).join(" | ")}`),t.join(`
395
+ `)}Ys();O();import{MongoClient as kb}from"mongodb";var bb=k("memory-store"),ei=class{mongoUri;dbName;client;db;collection;constructor(e,t){this.mongoUri=e,this.dbName=t,this.client=new kb(e)}async init(){await this.client.connect(),this.db=this.client.db(this.dbName),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}),bb.info("Memory store initialized",{db:this.dbName})}getCollection(){return this.collection}async save(e,t,s,n,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:n,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,n){let i={content:t,updatedAt:new Date};return s&&(i.importance=s),n&&(i.qdrantPointId=n),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((n,i)=>{if(n.pinned!==i.pinned)return n.pinned?-1:1;let o=(t[i.importance]??0)-(t[n.importance]??0);return o!==0?o:i.updatedAt.getTime()-n.updatedAt.getTime()})}async getHotTierWithStats(e){let t=await this.getHotTier(e),s=Date.now();return t.map(n=>({...n,ageDays:Math.floor((s-n.createdAt.getTime())/(1e3*60*60*24)),daysSinceAccess:Math.floor((s-n.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 n of t){let i=s.get(n.topic)??[];i.push(n),s.set(n.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 n of t){let i=s.get(n.topic)??[];i.push(n),s.set(n.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 n={agentId:e,pinned:!1,purged:{$ne:!0}};return t.topic!==void 0&&(n.topic=t.topic),t.type!==void 0&&(n.type=t.type),t.importance!==void 0&&(n.importance=t.importance),t.tier!==void 0&&(n.tier=t.tier),t.olderThan!==void 0&&(n.updatedAt={$lt:t.olderThan}),(await this.collection.updateMany(n,{$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 n=s.map(i=>i._id);return await this.collection.deleteMany({_id:{$in:n}}),s}async getAgentIds(){return this.collection.distinct("agentId")}async close(){await this.client.close()}};O();Cr();import{QdrantClient as _b}from"@qdrant/js-client-rest";var of=k("memory-embedder"),Ct="agent_memory",ti=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 _b({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(n=>n.name===Ct)){let n=await this.embed("test");await e.createCollection(Ct,{vectors:{size:n.length,distance:"Cosine"}}),of.info("Created Qdrant collection",{collection:Ct,vectorSize:n.length})}this.collectionReady=!0}async upsert(e,t,s){await this.ensureCollection();let n=await this.embed(t);await this.getClient().upsert(Ct,{points:[{id:e,vector:n,payload:s}]})}async remove(e){await this.ensureCollection(),await this.getClient().delete(Ct,{points:[e]})}async search(e,t,s){await this.ensureCollection();let n=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:n,limit:i,with_payload:!0,filter:{must:o}})).map(l=>({mongoId:l.payload?.mongoId,score:l.score}))}async findSimilar(e,t,s,n=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:n,with_payload:!0,score_threshold:s})}catch(o){if(String(o).includes("Not Found")||String(o).includes("does not exists"))return of.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)}))}};O();import{ObjectId as vb}from"mongodb";import{query as si}from"@anthropic-ai/claude-agent-sdk";var af={critical:1,high:.75,medium:.5,low:.25},cf={decision:1,fact:.8,preference:.8,summary:.6,task:.5,interaction:.3};var Me=k("memory-lifecycle"),ni=class{store;embedder;config;dreamConfig;getActiveAgentIds;constructor(e,t,s,n,i){this.store=e,this.embedder=t,this.config=s,this.dreamConfig=n,this.getActiveAgentIds=i}async filterActiveAgents(e){if(!this.getActiveAgentIds)return e;let t=await this.getActiveAgentIds(),s=e.filter(i=>t.has(i)),n=e.length-s.length;return n>0&&Me.debug("Skipped retired agents",{skipped:n,retiredIds:e.filter(i=>!t.has(i))}),s}computeScore(e,t){let s=af[e.importance]??.5,n=cf[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+n*.1}estimateTokens(e){return Math.ceil(e.length/4)}async sweep(){let e=Date.now(),t=0,s=0,n=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,n+=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+n+i+o>0&&Me.info("Memory lifecycle sweep complete",{durationMs:Date.now()-e,promoted:t,demoted:s,summarized:n,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,n=await this.store.getAllNonPinned(e),i=0,o=0;if(n.length>0){let d=n.map(w=>w.accessCount).sort((w,S)=>w-S),u=d[Math.floor(d.length/2)]??0,h=n.map(w=>({record:w,score:this.computeScore(w,u)})),m=[];for(let{record:w,score:S}of h){let _;S>=this.config.hotThreshold?_="hot":S>=this.config.warmThreshold?_="warm":_="cold",_!==w.tier&&(m.push({id:w._id,newTier:_}),_==="hot"&&w.tier!=="hot"&&t++,_!=="hot"&&w.tier==="hot"&&s++)}for(let w of["hot","warm","cold"]){let S=m.filter(_=>_.newTier===w).map(_=>_.id);await this.store.setTierBulk(S,w)}let g=await this.store.getHotTier(e),f=0,y=[];for(let w of g){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,n=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 m=await this.promotePatterns(d);n+=m.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+n+i>0&&Me.info("autoDream complete",{durationMs:Date.now()-e,merged:t,contradictions:s,promoted:n,flaggedForReview:i,errors:o.length}),{merged:t,contradictions:s,promoted:n,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 n=new Set,i=0,o=0;for(let a of s){if(o>=t.maxClustersPerRun)break;if(n.has(a.qdrantPointId))continue;let c=(await this.embedder.findSimilar(a.qdrantPointId,e,t.similarityThreshold,10)).filter(I=>!n.has(I.pointId));if(c.length===0)continue;n.add(a.qdrantPointId);for(let I of c)n.add(I.pointId);let d=c.map(I=>new vb(I.mongoId)),u=await this.store.getByIds(d),h=[a,...u],g=["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(`
396
396
  `)].join(`
397
397
  `),f=si({prompt:g,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(n=>n.importance===s))return s;return"medium"}async detectContradictions(e){let t=this.dreamConfig,s=await this.store.getFactsAndDecisionsByTopic(e),n=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],m=c[u],g=["Do these two memories contradict each other?","",`Memory A (${h.type}, created ${h.createdAt.toISOString()}):`,h.content,"",`Memory B (${m.type}, created ${m.createdAt.toISOString()}):`,m.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(`
398
398
  `),f=si({prompt:g,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([m._id],h._id),a.add(m._id.toString()),n++):y.includes("B_WINS")?(await this.store.markSuperseded([h._id],m._id),a.add(h._id.toString()),n++):y.includes("UNCLEAR")&&(await this.store.flagForReview([h._id,m._id]),a.add(h._id.toString()),a.add(m._id.toString()),i+=2)}if(o>=t.maxContradictionPairsPerRun)break}}}return(n>0||i>0)&&Me.info("autoDream: contradictions processed",{agentId:e,resolved:n,flagged:i,pairsChecked:o}),{resolved:n,flagged:i}}async promotePatterns(e){let t=this.dreamConfig,s=await this.store.getInteractionsByTopic(e),n=0;for(let[i,o]of s){if(n>=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(`
399
399
  `),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(`
400
400
  `),h=si({prompt:u,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),m="";for await(let w of h){let S=w;if(S.type==="result"){let _=S;_.subtype==="success"&&_.result&&(m=_.result)}}if(!m)continue;let g=crypto.randomUUID(),f=await this.store.save(e,{content:m,type:"fact",topic:i,importance:"medium"},g);await this.embedder.upsert(g,m,{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),n++}return n>0&&Me.info("autoDream: patterns promoted",{agentId:e,promoted:n}),{promoted:n}}async summarizeCold(e){let t=await this.store.getColdTopics(e),s=0;for(let n of t){let i=await this.store.getColdByTopic(e,n);if(i.length<this.config.coldSummaryMinRecords)continue;let o=i.map(h=>`- [${h.type}/${h.importance}] ${h.content}`).join(`
401
401
  `),a=[`Summarize the following memory entries for agent ${e} about topic "${n}".`,"Preserve key facts, decisions, and outcomes. Discard routine interactions.","Be concise \u2014 aim for 2-5 sentences.","",o].join(`
402
- `),l=si({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 m=h;if(m.type==="result"){let g=m;g.subtype==="success"&&g.result&&(c=g.result)}}if(!c)continue;let d=crypto.randomUUID(),u=await this.store.save(e,{content:c,type:"summary",topic:n,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:n,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}};O();import{createServer as Tb}from"node:http";var cf=k("admin-api"),ri=class{server;port;token;agentDefs;agentVersions;onReload;constructor(e,t,s,n,i){this.port=e,this.token=t,this.agentDefs=s,this.agentVersions=n,this.onReload=i,this.server=Tb((o,a)=>this.handleRequest(o,a))}async start(){return new Promise(e=>{this.server.listen(this.port,()=>{cf.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 n=new URL(e.url??"/",`http://localhost:${this.port}`),i=n.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(n.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){cf.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 n=[];e.on("data",i=>n.push(i)),e.on("end",()=>{try{t(JSON.parse(Buffer.concat(n).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 n=await this.readBody(t);if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found"});delete n._id,delete n.createdAt;let o=Object.keys(n);await this.saveVersion(e,o),await this.agentDefs.updateOne({_id:e},{$set:{...n,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 n=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).limit(t).toArray();this.json(s,200,n)}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"})}};O();var At=k("activity-logger"),ii=class{db;collection;buffer=[];flushTimer=null;config;connected=!1;constructor(e,t){this.db=e,this.config=t}async connect(){if(!this.config.enabled){At.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=>At.warn("Periodic flush failed",{error:String(t)}))},this.config.flushIntervalMs);let e=await this.collection.estimatedDocumentCount();At.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=>At.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){At.warn("Bulk write failed, retrying once",{count:e.length,error:String(t)});try{await this.collection.insertMany(e,{ordered:!1})}catch(s){At.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&&(At.info("Draining activity buffer on shutdown",{count:this.buffer.length}),await this.flush()),this.connected=!1}};O();var lf={id:"001-backfill-home-base",async run(r,e){let t=r.collection("agent_definitions"),s=t.find({homeBase:{$exists:!1}}),n=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}}),n++}e.info("Backfill complete",{migration:"001-backfill-home-base",updated:n,skipped:i})}};var oi=k("migrations"),Ib=[lf];async function df(r,e=Ib){let t=r.collection("migrations");for(let s of e){if(await t.findOne({_id:s.id})){oi.debug("Migration already applied, skipping",{id:s.id});continue}oi.info("Running migration",{id:s.id}),await s.run(r,oi),await t.insertOne({_id:s.id,ranAt:new Date}),oi.info("Migration applied",{id:s.id})}}O();var Et=k("first-boot"),uf="hive/first-boot-greeting-sent",hf="chief-of-staff";async function ff(r,e,t,s){let n;try{n=await r.read(uf)}catch(d){Et.warn("First-boot flag read failed \u2014 skipping check this startup",{error:String(d)});return}if(n){Et.debug("First-boot greeting already sent \u2014 skipping");return}let i=e.get(hf),o=i?.homeBase??i?.channels?.[0];if(!o){Et.warn("First-boot: CoS agent has no homeBase or channels \u2014 skipping, will retry next startup");return}let a=s.get(o);if(!a){Et.warn("First-boot: could not resolve channel ID for CoS home channel",{channelName:o});return}try{await r.write(uf,"true","system")}catch(d){Et.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:hf,systemTrigger:"first-boot"}};Et.info("First-boot: dispatching CoS greeting",{channel:o,channelId:a}),t.dispatch(c).catch(d=>{Et.error("First-boot greeting dispatch failed",{error:String(d)})})}O();import{createServer as Cb}from"node:http";var qa=k("slack-internal-api"),ai=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=Cb((e,t)=>{this.handleRequest(e,t).catch(s=>{qa.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())}),qa.info("Slack internal API started",{port:this.port})}async stop(){this.server&&(this.server.close(),this.server=null),qa.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 n=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(n.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:n,text:i,thread_ts:o,blocks:a,force_root:l}=e;if(typeof n!="string"||!n){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(n);if(!c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:`unknown channel: ${n}`}));return}let d=o;if(!d&&!l&&typeof s=="string"&&s){let g=this.agentManager.getActiveWorkItems(s).filter(f=>f.source.id===c);if(g.length>0){let f=g[g.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:n}=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 n=="number"?n: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,n=await this.gateway.listChannels(typeof s=="string"?s:void 0);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channels:n}))}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 n=await this.gateway.readUser(s);if(n===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:n}))}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();var Ab=k("slack-scope-preflight"),Eb=["chat:write","chat:write.public","chat:write.customize","channels:history","channels:read","users:read"];async function pf(r,e=Eb){let t=await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${r}`}}),s=await t.json();if(!s.ok)throw new Error(`Slack auth.test failed: ${s.error??"unknown"}`);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)throw new Error(`Slack bot token missing required scopes: ${o.join(", ")}`);Ab.info("Slack scope preflight passed",{required:[...e]})}var M=k("index");async function mv(){M.info("Hive starting up",{instance:p.instance.id,portBase:p.instance.portBase}),kc(Yp(z,"dist","index.js"))&&kc(Yp(cs,"dist","index.js"))&&(M.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:z,engineDir:cs}),process.exit(1)),Rc(z,fn),Bc(z),Mc(z),qc(fn,Ze),p.gemini.apiKey&&(Oh(p.gemini.apiKey),M.info("Gemini vision enabled",{model:p.gemini.visionModel}));let r=new pv(p.mongo.uri);await r.connect();let e=r.db(p.mongo.dbName),t=e.collection("agent_definitions");await t.createIndex({channels:1}),await t.createIndex({disabled:1}),await df(e);let s,n,i,o=null,a,l=async()=>{if(!n||!i)return;M.info("Hot-reloading agent registry...");let x=await s.load();if(x.added.length&&M.info("New agents online",{agents:x.added}),x.updated.length&&M.info("Agents updated",{agents:x.updated}),x.removed.length){M.info("Agents removed",{agents:x.removed});for(let de of x.removed)n.stopAgent(de)}let B=s.getDisabled();for(let de of B)n.stopAgent(de.id);B.length&&M.info("Disabled agents stopped",{agents:B.map(de=>de.id)}),await i.reloadSchedules(),n.reloadSkills(),n.rescanPlugins()};s=new gr(t,()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),await s.load(),M.info("Agent registry loaded",{agents:s.listIds()});let c=new Mr(p.mongo.uri,p.mongo.dbName);await c.init();let d=new ei(p.mongo.uri,p.mongo.dbName);await d.init(),c.memoryStore=d;let u=new ti,h=new ni(d,u,{hotBudgetTokens:p.memory.hotBudgetTokens,sweepIntervalHours:p.memory.sweepIntervalHours,hotThreshold:p.memory.hotThreshold,warmThreshold:p.memory.warmThreshold,recencyHalfLifeDays:p.memory.recencyHalfLifeDays,coldSummaryMinRecords:p.memory.coldSummaryMinRecords,coldRetentionDays:p.memory.coldRetentionDays,purgeRetentionDays:p.memory.purgeRetentionDays},p.autoDream,async()=>new Set(s.listIds()));M.info("Structured memory lifecycle enabled");let m=new $r(p.mongo.uri);await m.connect(p.mongo.dbName);let g;if(p.activity.enabled&&(g=new ii(e,p.activity),await g.connect()),p.linear.apiKey){let x=new Pr(p.linear.apiKey,p.linear.teamId||void 0);M.info("Linear client configured")}let f=new Kr(p.taskLedger.apiUrl,p.taskLedger.apiKey);f.isConfigured&&M.info("Task ledger client configured",{apiUrl:p.taskLedger.apiUrl});let y=new Hr(p.taskLedger.apiUrl,p.taskLedger.agentKeys,p.taskLedger.apiKey);y.isConfigured&&M.info("Task ledger auto-tracking enabled",{apiUrl:p.taskLedger.apiUrl,agents:Object.keys(p.taskLedger.agentKeys)});let w,S;if(p.codeIndex.enabled){let{CodeIndexPrefetcher:x}=await Promise.resolve().then(()=>(yf(),gf)),{KnowledgeExtractor:B}=await Promise.resolve().then(()=>(Sf(),wf));w=new x({mongoUri:p.mongo.uri,dbName:p.mongo.dbName,qdrantUrl:process.env.QDRANT_URL??"http://localhost:6333",ollamaUrl:process.env.OLLAMA_URL??"http://localhost:11434",scoreThreshold:p.codeIndex.scoreThreshold,prefetchLimit:p.codeIndex.prefetchLimit}),p.codeIndex.sessionKnowledge.enabled&&(S=new B(d,u)),M.info("Code index integration enabled",{prefetch:!0,sessionKnowledge:S!==void 0})}n=new Nr(s,c,m,g,w);let _=new Lr(n,c,s),v=new Br(s,n,_,p.defaultAgent,y.isConfigured?y:void 0),I=new Wr(p.background.port,p.background.authToken,p.tasksDir.background,x=>v.dispatch(x).catch(B=>{M.error("Background task completion dispatch failed",{error:String(B)})}));await I.start(),await I.scanOrphans(),M.info("Background task manager started",{port:p.background.port});let N=new Vr(p.codeTask.port,p.codeTask.authToken,p.codeTask.pluginDirs,p.codeTask.maxConcurrent,p.tasksDir.code,x=>v.dispatch(x).catch(B=>{M.error("Code task completion dispatch failed",{error:String(B)})}),{prefetcher:w,knowledgeExtractor:S,maxLifetimeMs:p.codeTask.maxLifetimeMs,staleGraceMs:p.codeTask.staleGraceMs});await N.start(),await N.scanOrphans(),M.info("Code task manager started",{port:p.codeTask.port});let D;p.recall.apiKey&&(D=new Yr(p.recall.monitorPort,p.recall.webhookSecret,x=>v.dispatch(x).catch(B=>{M.error("Meeting monitor dispatch failed",{error:String(B)})})),await D.start(),M.info("Meeting monitor started",{port:p.recall.monitorPort}),p.recall.apiKey&&!p.recall.webhookSecret&&M.error("Real-time transcript delivery disabled \u2014 RECALL_WEBHOOK_SECRET not set")),kc(Ze)&&(fv(Ze,{recursive:!0},()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),M.info("Skills hot-reload enabled",{watched:Ze})),process.on("SIGUSR1",()=>l()),M.info("Hot-reload enabled",{signal:"SIGUSR1"});let C=p.sms.lines.map(x=>x.slackChannel).filter(Boolean),E=new Or(p.slack.appToken,p.slack.botToken),G=new Ur(E,s,C,"slack");v.registerAdapter(G),v.setSlackAdapter(G),await G.start(x=>{v.dispatch(x).catch(B=>{M.error("Slack dispatch failed",{error:String(B),source:x.source.label})})}),M.info("Slack adapter connected");let W=new Map;try{let x;do{let de=await E.client.conversations.list({types:"public_channel,private_channel",limit:1e3,cursor:x});for(let Pt of de.channels??[])Pt.name&&Pt.id&&W.set(Pt.name,Pt.id);x=de.response_metadata?.next_cursor||void 0}while(x);let B=p.slack.auditChannel;a=B?W.get(B):void 0,v.setAuditChannel(G,W,a),M.info("Audit channel configured",{channels:W.size,fallback:B||null,fallbackResolved:!!a})}catch(x){M.warn("Failed to configure audit channel",{error:String(x)})}let $=null;p.slack.localMcpServer&&(await pf(p.slack.botToken),$=new ai({port:p.slackInternal.port,authToken:p.slackInternal.authToken,gateway:E,agentManager:n}),await $.start(),M.info("Slack internal API started",{port:p.slackInternal.port}));let ce=new qr(p.quo.apiKey,p.sms.lines);v.registerAdapter(ce),p.quo.apiKey&&p.sms.lines.length>0&&(await ce.start(x=>{v.dispatch(x).catch(B=>{M.error("SMS dispatch failed",{error:String(B),source:x.source.label})})}),M.info("SMS adapter started",{lines:p.sms.lines.length}));let Ie;p.imessage.enabled&&(Ie=new Fr(p.imessage,p.mongo.uri,p.mongo.dbName,E,p.instance.id),v.registerAdapter(Ie),await Ie.start(x=>{v.dispatch(x).catch(B=>{M.error("iMessage dispatch failed",{error:String(B)})})}),M.info("iMessage adapter started"));let{AgentRunner:me}=await Promise.resolve().then(()=>(Ma(),Eh));me.registryRef=s;let{TeamStore:dn}=await Promise.resolve().then(()=>(vf(),_f)),{CommandRegistry:os}=await Promise.resolve().then(()=>(If(),Tf)),Qe=new dn(p.mongo.uri,p.mongo.dbName);await Qe.connect();let _i=x=>{let B=s.getAll(),de=B.find(Ti=>Ti.id===x);if(de)return{id:de.id,name:de.name};let Pt=x.toLowerCase(),vi=B.find(Ti=>Ti.name.toLowerCase()===Pt);return vi?{id:vi.id,name:vi.name}:null},Xe=new os(Qe,_i);v.setTeamStore(Qe),M.info("Team layer initialized");let{registerPluginCommands:un}=await Promise.resolve().then(()=>(Sr(),hh));await un(n.getPlugins(),Xe);let Be;if(p.ws.enabled){let{WsAdapter:x}=await Promise.resolve().then(()=>(Pp(),Lp));Be=new x(p.ws.port,{teamStore:Qe,commandRegistry:Xe,agentRegistry:s,agentManager:n}),v.registerAdapter(Be),await Be.start(B=>{v.dispatch(B).catch(de=>{M.error("WS dispatch failed",{error:String(de),source:B.source.label})})}),M.info("WebSocket adapter started",{port:p.ws.port})}let as;if(p.ws.enabled){let{startBeekeeperRegistration:x}=await Promise.resolve().then(()=>(Rp(),$p)),B=`hive-${p.instance.id}`;as=x({beekeeperPort:p.beekeeper.port,wsPort:p.ws.port,capabilityName:B}),M.info("Beekeeper registration loop started",{beekeeperPort:p.beekeeper.port,wsPort:p.ws.port,capabilityName:B})}let V;if(p.voice.enabled&&p.voice.serverSecret){let{VoiceAdapter:x}=await Promise.resolve().then(()=>(Vp(),Gp));V=new x(p.voice.port,p.voice.serverSecret,s,c),await V.start(),M.info("Voice adapter started",{port:p.voice.port})}i=new Dr(n,c,_,s,x=>{v.dispatch(x).catch(B=>{M.error("Callback dispatch failed",{error:String(B)})})}),await i.connectDb(p.mongo.uri,p.mongo.dbName),i.start(),M.info("Scheduler started"),await s.startWatching();let L;p.adminApi.token&&(L=new ri(p.adminApi.port,p.adminApi.token,t,e.collection("agent_definition_versions"),()=>l()),await L.start(),M.info("Admin API started",{port:p.adminApi.port}));let P=new zr({maxAttempts:p.sweeper.retryMaxAttempts,baseDelayMs:p.sweeper.retryBaseDelayMs});v.setRetryQueue(P);let le=[G],hn=[E],Lt=new Qr({intervalMs:p.sweeper.intervalMs,threadTtlMs:p.sweeper.threadTtlMs,taskFileTtlMs:p.sweeper.taskFileTtlMs,meetingSessionTtlMs:p.sweeper.meetingSessionTtlMs,cacheTtlMs:p.sweeper.cacheTtlMs,memorySweepIntervalHours:p.memory.sweepIntervalHours,dreamConfig:p.autoDream},{dispatcher:v,slackAdapters:le,bgTaskManager:I,codeTaskManager:N,meetingMonitor:D,taskLedger:y.isConfigured?y:void 0,slackGateways:hn,agentManager:n,retryQueue:P,memoryLifecycle:h},f.isConfigured?f:void 0);Lt.start(),M.info("Sweeper started",{intervalMs:p.sweeper.intervalMs});let bc=new Zr(p.retention,{hiveHome:z,report:async x=>{a?await E.postMessage(a,x).catch(B=>M.warn("Retention report: Slack post failed",{error:String(B)})):M.info("Retention report (no audit channel configured)",{text:x})}});bc.start(),M.info("Retention sweeper started",{enabled:p.retention.enabled,intervalMs:p.retention.intervalMs});let _c=async x=>{M.info("Shutdown signal received",{signal:x}),Lt.stop(),bc.stop(),L?.stop(),s.stopWatching(),await ce.stop(),$&&await $.stop(),Ie&&await Ie.stop(),as?.stop(),Be&&await Be.stop(),V?.stop(),await Qe.close(),i.stop(),await I.stop(),await N.stop(),await w?.close(),D?.stop(),n.stopAll(),g&&await g.stop(),await m.close(),await d.close(),await G.stop(),await r.close(),M.info("Hive shut down cleanly"),process.exit(0)};process.on("SIGTERM",()=>_c("SIGTERM")),process.on("SIGINT",()=>_c("SIGINT")),M.info("Hive is running"),ff(c,s,v,W).catch(x=>{M.error("First-boot check failed",{error:String(x)})})}process.on("unhandledRejection",r=>{M.error("Unhandled promise rejection",{error:String(r),stack:r instanceof Error?r.stack:void 0})});mv().catch(r=>{M.error("Fatal startup error",{error:String(r)}),process.exit(1)});
402
+ `),l=si({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 m=h;if(m.type==="result"){let g=m;g.subtype==="success"&&g.result&&(c=g.result)}}if(!c)continue;let d=crypto.randomUUID(),u=await this.store.save(e,{content:c,type:"summary",topic:n,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:n,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}};O();import{createServer as Tb}from"node:http";var lf=k("admin-api"),ri=class{server;port;token;agentDefs;agentVersions;onReload;constructor(e,t,s,n,i){this.port=e,this.token=t,this.agentDefs=s,this.agentVersions=n,this.onReload=i,this.server=Tb((o,a)=>this.handleRequest(o,a))}async start(){return new Promise(e=>{this.server.listen(this.port,()=>{lf.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 n=new URL(e.url??"/",`http://localhost:${this.port}`),i=n.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(n.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){lf.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 n=[];e.on("data",i=>n.push(i)),e.on("end",()=>{try{t(JSON.parse(Buffer.concat(n).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 n=await this.readBody(t);if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found"});delete n._id,delete n.createdAt;let o=Object.keys(n);await this.saveVersion(e,o),await this.agentDefs.updateOne({_id:e},{$set:{...n,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 n=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).limit(t).toArray();this.json(s,200,n)}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"})}};O();var At=k("activity-logger"),ii=class{db;collection;buffer=[];flushTimer=null;config;connected=!1;constructor(e,t){this.db=e,this.config=t}async connect(){if(!this.config.enabled){At.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=>At.warn("Periodic flush failed",{error:String(t)}))},this.config.flushIntervalMs);let e=await this.collection.estimatedDocumentCount();At.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=>At.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){At.warn("Bulk write failed, retrying once",{count:e.length,error:String(t)});try{await this.collection.insertMany(e,{ordered:!1})}catch(s){At.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&&(At.info("Draining activity buffer on shutdown",{count:this.buffer.length}),await this.flush()),this.connected=!1}};O();var df={id:"001-backfill-home-base",async run(r,e){let t=r.collection("agent_definitions"),s=t.find({homeBase:{$exists:!1}}),n=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}}),n++}e.info("Backfill complete",{migration:"001-backfill-home-base",updated:n,skipped:i})}};var oi=k("migrations"),Ib=[df];async function uf(r,e=Ib){let t=r.collection("migrations");for(let s of e){if(await t.findOne({_id:s.id})){oi.debug("Migration already applied, skipping",{id:s.id});continue}oi.info("Running migration",{id:s.id}),await s.run(r,oi),await t.insertOne({_id:s.id,ranAt:new Date}),oi.info("Migration applied",{id:s.id})}}O();var Et=k("first-boot"),hf="hive/first-boot-greeting-sent",ff="chief-of-staff";async function pf(r,e,t,s){let n;try{n=await r.read(hf)}catch(d){Et.warn("First-boot flag read failed \u2014 skipping check this startup",{error:String(d)});return}if(n){Et.debug("First-boot greeting already sent \u2014 skipping");return}let i=e.get(ff),o=i?.homeBase??i?.channels?.[0];if(!o){Et.warn("First-boot: CoS agent has no homeBase or channels \u2014 skipping, will retry next startup");return}let a=s.get(o);if(!a){Et.warn("First-boot: could not resolve channel ID for CoS home channel",{channelName:o});return}try{await r.write(hf,"true","system")}catch(d){Et.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:ff,systemTrigger:"first-boot"}};Et.info("First-boot: dispatching CoS greeting",{channel:o,channelId:a}),t.dispatch(c).catch(d=>{Et.error("First-boot greeting dispatch failed",{error:String(d)})})}O();import{createServer as Cb}from"node:http";var qa=k("slack-internal-api"),ai=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=Cb((e,t)=>{this.handleRequest(e,t).catch(s=>{qa.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())}),qa.info("Slack internal API started",{port:this.port})}async stop(){this.server&&(this.server.close(),this.server=null),qa.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 n=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(n.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:n,text:i,thread_ts:o,blocks:a,force_root:l}=e;if(typeof n!="string"||!n){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(n);if(!c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:`unknown channel: ${n}`}));return}let d=o;if(!d&&!l&&typeof s=="string"&&s){let g=this.agentManager.getActiveWorkItems(s).filter(f=>f.source.id===c);if(g.length>0){let f=g[g.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:n}=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 n=="number"?n: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,n=await this.gateway.listChannels(typeof s=="string"?s:void 0);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channels:n}))}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 n=await this.gateway.readUser(s);if(n===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:n}))}readBody(e){return new Promise((t,s)=>{let n="";e.on("data",i=>{n+=i.toString()}),e.on("end",()=>t(n)),e.on("error",s)})}};O();var Ab=k("slack-scope-preflight"),Eb=["chat:write","chat:write.public","chat:write.customize","channels:history","channels:read","users:read"];async function mf(r,e=Eb){let t=await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${r}`}}),s=await t.json();if(!s.ok)throw new Error(`Slack auth.test failed: ${s.error??"unknown"}`);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)throw new Error(`Slack bot token missing required scopes: ${o.join(", ")}`);Ab.info("Slack scope preflight passed",{required:[...e]})}var M=k("index");async function mv(){M.info("Hive starting up",{instance:p.instance.id,portBase:p.instance.portBase}),kc(Jp(z,"dist","index.js"))&&kc(Jp(cs,"dist","index.js"))&&(M.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:z,engineDir:cs}),process.exit(1)),Rc(z,fn),Bc(z),Mc(z),qc(fn,Ze),p.gemini.apiKey&&(Oh(p.gemini.apiKey),M.info("Gemini vision enabled",{model:p.gemini.visionModel}));let r=new pv(p.mongo.uri);await r.connect();let e=r.db(p.mongo.dbName),t=e.collection("agent_definitions");await t.createIndex({channels:1}),await t.createIndex({disabled:1}),await uf(e);let s,n,i,o=null,a,l=async()=>{if(!n||!i)return;M.info("Hot-reloading agent registry...");let x=await s.load();if(x.added.length&&M.info("New agents online",{agents:x.added}),x.updated.length&&M.info("Agents updated",{agents:x.updated}),x.removed.length){M.info("Agents removed",{agents:x.removed});for(let de of x.removed)n.stopAgent(de)}let B=s.getDisabled();for(let de of B)n.stopAgent(de.id);B.length&&M.info("Disabled agents stopped",{agents:B.map(de=>de.id)}),await i.reloadSchedules(),n.reloadSkills(),n.rescanPlugins()};s=new gr(t,()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),await s.load(),M.info("Agent registry loaded",{agents:s.listIds()});let c=new Mr(p.mongo.uri,p.mongo.dbName);await c.init();let d=new ei(p.mongo.uri,p.mongo.dbName);await d.init(),c.memoryStore=d;let u=new ti,h=new ni(d,u,{hotBudgetTokens:p.memory.hotBudgetTokens,sweepIntervalHours:p.memory.sweepIntervalHours,hotThreshold:p.memory.hotThreshold,warmThreshold:p.memory.warmThreshold,recencyHalfLifeDays:p.memory.recencyHalfLifeDays,coldSummaryMinRecords:p.memory.coldSummaryMinRecords,coldRetentionDays:p.memory.coldRetentionDays,purgeRetentionDays:p.memory.purgeRetentionDays},p.autoDream,async()=>new Set(s.listIds()));M.info("Structured memory lifecycle enabled");let m=new $r(p.mongo.uri);await m.connect(p.mongo.dbName);let g;if(p.activity.enabled&&(g=new ii(e,p.activity),await g.connect()),p.linear.apiKey){let x=new Pr(p.linear.apiKey,p.linear.teamId||void 0);M.info("Linear client configured")}let f=new Kr(p.taskLedger.apiUrl,p.taskLedger.apiKey);f.isConfigured&&M.info("Task ledger client configured",{apiUrl:p.taskLedger.apiUrl});let y=new Hr(p.taskLedger.apiUrl,p.taskLedger.agentKeys,p.taskLedger.apiKey);y.isConfigured&&M.info("Task ledger auto-tracking enabled",{apiUrl:p.taskLedger.apiUrl,agents:Object.keys(p.taskLedger.agentKeys)});let w,S;if(p.codeIndex.enabled){let{CodeIndexPrefetcher:x}=await Promise.resolve().then(()=>(wf(),yf)),{KnowledgeExtractor:B}=await Promise.resolve().then(()=>(kf(),Sf));w=new x({mongoUri:p.mongo.uri,dbName:p.mongo.dbName,qdrantUrl:process.env.QDRANT_URL??"http://localhost:6333",ollamaUrl:process.env.OLLAMA_URL??"http://localhost:11434",scoreThreshold:p.codeIndex.scoreThreshold,prefetchLimit:p.codeIndex.prefetchLimit}),p.codeIndex.sessionKnowledge.enabled&&(S=new B(d,u)),M.info("Code index integration enabled",{prefetch:!0,sessionKnowledge:S!==void 0})}n=new Nr(s,c,m,g,w);let _=new Lr(n,c,s),v=new Br(s,n,_,p.defaultAgent,y.isConfigured?y:void 0),I=new Wr(p.background.port,p.background.authToken,p.tasksDir.background,x=>v.dispatch(x).catch(B=>{M.error("Background task completion dispatch failed",{error:String(B)})}));await I.start(),await I.scanOrphans(),M.info("Background task manager started",{port:p.background.port});let N=new Vr(p.codeTask.port,p.codeTask.authToken,p.codeTask.pluginDirs,p.codeTask.maxConcurrent,p.tasksDir.code,x=>v.dispatch(x).catch(B=>{M.error("Code task completion dispatch failed",{error:String(B)})}),{prefetcher:w,knowledgeExtractor:S,maxLifetimeMs:p.codeTask.maxLifetimeMs,staleGraceMs:p.codeTask.staleGraceMs});await N.start(),await N.scanOrphans(),M.info("Code task manager started",{port:p.codeTask.port});let D;p.recall.apiKey&&(D=new Yr(p.recall.monitorPort,p.recall.webhookSecret,x=>v.dispatch(x).catch(B=>{M.error("Meeting monitor dispatch failed",{error:String(B)})})),await D.start(),M.info("Meeting monitor started",{port:p.recall.monitorPort}),p.recall.apiKey&&!p.recall.webhookSecret&&M.error("Real-time transcript delivery disabled \u2014 RECALL_WEBHOOK_SECRET not set")),kc(Ze)&&(fv(Ze,{recursive:!0},()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),M.info("Skills hot-reload enabled",{watched:Ze})),process.on("SIGUSR1",()=>l()),M.info("Hot-reload enabled",{signal:"SIGUSR1"});let C=p.sms.lines.map(x=>x.slackChannel).filter(Boolean),E=new Or(p.slack.appToken,p.slack.botToken),G=new Ur(E,s,C,"slack");v.registerAdapter(G),v.setSlackAdapter(G),await G.start(x=>{v.dispatch(x).catch(B=>{M.error("Slack dispatch failed",{error:String(B),source:x.source.label})})}),M.info("Slack adapter connected");let W=new Map;try{let x;do{let de=await E.client.conversations.list({types:"public_channel,private_channel",limit:1e3,cursor:x});for(let Pt of de.channels??[])Pt.name&&Pt.id&&W.set(Pt.name,Pt.id);x=de.response_metadata?.next_cursor||void 0}while(x);let B=p.slack.auditChannel;a=B?W.get(B):void 0,v.setAuditChannel(G,W,a),M.info("Audit channel configured",{channels:W.size,fallback:B||null,fallbackResolved:!!a})}catch(x){M.warn("Failed to configure audit channel",{error:String(x)})}let $=null;p.slack.localMcpServer&&(await mf(p.slack.botToken),$=new ai({port:p.slackInternal.port,authToken:p.slackInternal.authToken,gateway:E,agentManager:n}),await $.start(),M.info("Slack internal API started",{port:p.slackInternal.port}));let ce=new qr(p.quo.apiKey,p.sms.lines);v.registerAdapter(ce),p.quo.apiKey&&p.sms.lines.length>0&&(await ce.start(x=>{v.dispatch(x).catch(B=>{M.error("SMS dispatch failed",{error:String(B),source:x.source.label})})}),M.info("SMS adapter started",{lines:p.sms.lines.length}));let Ie;p.imessage.enabled&&(Ie=new Fr(p.imessage,p.mongo.uri,p.mongo.dbName,E,p.instance.id),v.registerAdapter(Ie),await Ie.start(x=>{v.dispatch(x).catch(B=>{M.error("iMessage dispatch failed",{error:String(B)})})}),M.info("iMessage adapter started"));let{AgentRunner:me}=await Promise.resolve().then(()=>(Ma(),Eh));me.registryRef=s;let{TeamStore:dn}=await Promise.resolve().then(()=>(Tf(),vf)),{CommandRegistry:os}=await Promise.resolve().then(()=>(Cf(),If)),Qe=new dn(p.mongo.uri,p.mongo.dbName);await Qe.connect();let _i=x=>{let B=s.getAll(),de=B.find(Ti=>Ti.id===x);if(de)return{id:de.id,name:de.name};let Pt=x.toLowerCase(),vi=B.find(Ti=>Ti.name.toLowerCase()===Pt);return vi?{id:vi.id,name:vi.name}:null},Xe=new os(Qe,_i);v.setTeamStore(Qe),M.info("Team layer initialized");let{registerPluginCommands:un}=await Promise.resolve().then(()=>(Sr(),hh));await un(n.getPlugins(),Xe);let Be;if(p.ws.enabled){let{WsAdapter:x}=await Promise.resolve().then(()=>($p(),Pp));Be=new x(p.ws.port,{teamStore:Qe,commandRegistry:Xe,agentRegistry:s,agentManager:n}),v.registerAdapter(Be),await Be.start(B=>{v.dispatch(B).catch(de=>{M.error("WS dispatch failed",{error:String(de),source:B.source.label})})}),M.info("WebSocket adapter started",{port:p.ws.port})}let as;if(p.ws.enabled){let{startBeekeeperRegistration:x}=await Promise.resolve().then(()=>(Bp(),Rp)),B=`hive-${p.instance.id}`;as=x({beekeeperPort:p.beekeeper.port,wsPort:p.ws.port,capabilityName:B}),M.info("Beekeeper registration loop started",{beekeeperPort:p.beekeeper.port,wsPort:p.ws.port,capabilityName:B})}let V;if(p.voice.enabled&&p.voice.serverSecret){let{VoiceAdapter:x}=await Promise.resolve().then(()=>(Yp(),Vp));V=new x(p.voice.port,p.voice.serverSecret,s,c),await V.start(),M.info("Voice adapter started",{port:p.voice.port})}i=new Dr(n,c,_,s,x=>{v.dispatch(x).catch(B=>{M.error("Callback dispatch failed",{error:String(B)})})}),await i.connectDb(p.mongo.uri,p.mongo.dbName),i.start(),M.info("Scheduler started"),await s.startWatching();let L;p.adminApi.token&&(L=new ri(p.adminApi.port,p.adminApi.token,t,e.collection("agent_definition_versions"),()=>l()),await L.start(),M.info("Admin API started",{port:p.adminApi.port}));let P=new zr({maxAttempts:p.sweeper.retryMaxAttempts,baseDelayMs:p.sweeper.retryBaseDelayMs});v.setRetryQueue(P);let le=[G],hn=[E],Lt=new Qr({intervalMs:p.sweeper.intervalMs,threadTtlMs:p.sweeper.threadTtlMs,taskFileTtlMs:p.sweeper.taskFileTtlMs,meetingSessionTtlMs:p.sweeper.meetingSessionTtlMs,cacheTtlMs:p.sweeper.cacheTtlMs,memorySweepIntervalHours:p.memory.sweepIntervalHours,dreamConfig:p.autoDream},{dispatcher:v,slackAdapters:le,bgTaskManager:I,codeTaskManager:N,meetingMonitor:D,taskLedger:y.isConfigured?y:void 0,slackGateways:hn,agentManager:n,retryQueue:P,memoryLifecycle:h},f.isConfigured?f:void 0);Lt.start(),M.info("Sweeper started",{intervalMs:p.sweeper.intervalMs});let bc=new Zr(p.retention,{hiveHome:z,report:async x=>{a?await E.postMessage(a,x).catch(B=>M.warn("Retention report: Slack post failed",{error:String(B)})):M.info("Retention report (no audit channel configured)",{text:x})}});bc.start(),M.info("Retention sweeper started",{enabled:p.retention.enabled,intervalMs:p.retention.intervalMs});let _c=async x=>{M.info("Shutdown signal received",{signal:x}),Lt.stop(),bc.stop(),L?.stop(),s.stopWatching(),await ce.stop(),$&&await $.stop(),Ie&&await Ie.stop(),as?.stop(),Be&&await Be.stop(),V?.stop(),await Qe.close(),i.stop(),await I.stop(),await N.stop(),await w?.close(),D?.stop(),n.stopAll(),g&&await g.stop(),await m.close(),await d.close(),await G.stop(),await r.close(),M.info("Hive shut down cleanly"),process.exit(0)};process.on("SIGTERM",()=>_c("SIGTERM")),process.on("SIGINT",()=>_c("SIGINT")),M.info("Hive is running"),pf(c,s,v,W).catch(x=>{M.error("First-boot check failed",{error:String(x)})})}process.on("unhandledRejection",r=>{M.error("Unhandled promise rejection",{error:String(r),stack:r instanceof Error?r.stack:void 0})});mv().catch(r=>{M.error("Fatal startup error",{error:String(r)}),process.exit(1)});