@keepur/hive 0.2.9 → 0.3.1

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,179 +1,182 @@
1
1
  import { createRequire as __hiveCreateRequire } from 'module'; const require = __hiveCreateRequire(import.meta.url);
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
- `)?Ki(t,e):t.includes(`
2
+ var sm=Object.create;var Ci=Object.defineProperty;var nm=Object.getOwnPropertyDescriptor;var rm=Object.getOwnPropertyNames;var im=Object.getPrototypeOf,om=Object.prototype.hasOwnProperty;var H=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var j=(n,e)=>()=>(n&&(e=n(n=0)),e);var T=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),Ue=(n,e)=>{for(var t in e)Ci(n,t,{get:e[t],enumerable:!0})},am=(n,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of rm(e))!om.call(n,r)&&r!==t&&Ci(n,r,{get:()=>e[r],enumerable:!(s=nm(e,r))||s.enumerable});return n};var Ae=(n,e,t)=>(t=n!=null?sm(im(n)):{},am(e||!n||!n.__esModule?Ci(t,"default",{value:n,enumerable:!0}):t,n));import{existsSync as cm}from"node:fs";import{resolve as ce}from"node:path";function dm(){return process.env.HIVE_HOME?ce(process.env.HIVE_HOME):cm(ce(process.cwd(),"hive.yaml"))?process.cwd():ce(lm,"hive")}function Cc(n){let e=process.env.HIVE_CONFIG||"hive.yaml";return ce(n,e)}function Ec(n){let t=(process.env.HIVE_CONFIG||"hive.yaml").match(/^hive-(.+)\.yaml$/)?.[1];return ce(n,t?`.env-${t}`:".env")}function fn(n=V){return ce(n,"agents")}function pn(n,e=V){return ce(fn(e),n,"scratch")}function xc(n,e=V){return ce(fn(e),n,"playwright")}function Oc(n,e=V){return ce(fn(e),n,"reports")}function Mc(n,e=V){return ce(fn(e),n,"feeds")}var lm,V,Xe,cs,hn,bv,Nc,ls=j(()=>{"use strict";lm=process.env.HOME??"/tmp";V=dm(),Xe=ce(V,"skills"),cs=ce(V,".hive"),hn=ce(V,".hive-state"),bv=ce(hn,"git"),Nc=ce(import.meta.dirname,"..","seeds")});function mn(n,e,t,s){if(Dc[n]<Dc[um])return;let r={ts:new Date().toISOString(),level:n,component:e,msg:t,...s};(n==="error"?process.stderr:process.stdout).write(JSON.stringify(r)+`
3
+ `)}function k(n){return{debug:(e,t)=>mn("debug",n,e,t),info:(e,t)=>mn("info",n,e,t),warn:(e,t)=>mn("warn",n,e,t),error:(e,t)=>mn("error",n,e,t)}}var Dc,um,M=j(()=>{"use strict";Dc={debug:0,info:1,warn:2,error:3},um=process.env.LOG_LEVEL||"info"});import{execFileSync as Ei}from"node:child_process";import{existsSync as Ni,mkdirSync as hm,unlinkSync as fm}from"node:fs";import{join as pm,resolve as Lc}from"node:path";function Pc(n){let e=Lc(n,".hive-state");return{stateDir:e,gitDir:Lc(e,"git")}}function $c(n){let{stateDir:e,gitDir:t}=Pc(n);if(Ni(t))return;hm(e,{recursive:!0});let s=(...r)=>Ei("git",[...r],{cwd:n,env:{...process.env,GIT_DIR:t,GIT_WORK_TREE:n},stdio:"pipe"});s("init"),s("config","user.name","hive-instance"),s("config","user.email","hive@localhost"),s("checkout","-b","installed"),s("commit","--allow-empty","-m","init: installed branch"),s("checkout","-b","state"),s("commit","--allow-empty","-m","init: state branch"),gn.info("Instance-local git initialized",{gitDir:t})}function Rc(n,e,t,s){let{gitDir:r}=Pc(n);if(!Ni(r)){gn.warn("Instance git not initialized \u2014 skipping state commit");return}let i=pm(r,"state-index.tmp"),o={...process.env,GIT_DIR:r,GIT_WORK_TREE:n,GIT_INDEX_FILE:i},a=(...l)=>Ei("git",[...l],{cwd:n,env:o,stdio:"pipe",encoding:"utf-8"}).trim();try{a("read-tree","state");for(let p of e)a("add","--force","--",p);try{a("rm","--cached","--ignore-unmatch","-r","--","**/.DS_Store")}catch{}let l=a("write-tree"),c=a("rev-parse","state"),d=a("rev-parse","state^{tree}");if(l===d)return;let u=s?{GIT_AUTHOR_NAME:s,GIT_AUTHOR_EMAIL:`${s}@hive`,GIT_COMMITTER_NAME:s,GIT_COMMITTER_EMAIL:`${s}@hive`}:{GIT_AUTHOR_NAME:"hive",GIT_AUTHOR_EMAIL:"hive@localhost",GIT_COMMITTER_NAME:"hive",GIT_COMMITTER_EMAIL:"hive@localhost"},h=Ei("git",["commit-tree",l,"-p",c,"-m",t],{env:{...o,...u},encoding:"utf-8"}).trim();a("update-ref","refs/heads/state",h),gn.debug("State branch commit",{message:t,files:e.length})}catch(l){gn.warn("Failed to commit to state branch",{error:String(l),message:t})}finally{try{Ni(i)&&fm(i)}catch{}}}var gn,xi=j(()=>{"use strict";M();gn=k("instance-git")});var zc=T((Fv,je)=>{var Li=H("fs"),yn=H("path"),km=H("os"),bm=H("crypto"),Wc=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function _m(){return Wc[Math.floor(Math.random()*Wc.length)]}function Rt(n){return typeof n=="string"?!["false","0","no","off",""].includes(n.toLowerCase()):!!n}function vm(){return process.stdout.isTTY}function Tm(n){return vm()?`\x1B[2m${n}\x1B[0m`:n}var Im=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Am(n){let e={},t=n.toString();t=t.replace(/\r\n?/mg,`
4
+ `);let s;for(;(s=Im.exec(t))!=null;){let r=s[1],i=s[2]||"";i=i.trim();let o=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(i=i.replace(/\\n/g,`
5
+ `),i=i.replace(/\\r/g,"\r")),e[r]=i}return e}function Cm(n){n=n||{};let e=Jc(n);n.path=e;let t=te.configDotenv(n);if(!t.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let s=Yc(n).split(","),r=s.length,i;for(let o=0;o<r;o++)try{let a=s[o].trim(),l=Nm(t,a);i=te.decrypt(l.ciphertext,l.key);break}catch(a){if(o+1>=r)throw a}return te.parse(i)}function Em(n){console.error(`\u26A0 ${n}`)}function ds(n){console.log(`\u2506 ${n}`)}function Vc(n){console.log(`\u25C7 ${n}`)}function Yc(n){return n&&n.DOTENV_KEY&&n.DOTENV_KEY.length>0?n.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function Nm(n,e){let t;try{t=new URL(e)}catch(a){if(a.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw a}let s=t.password;if(!s){let a=new Error("INVALID_DOTENV_KEY: Missing key part");throw a.code="INVALID_DOTENV_KEY",a}let r=t.searchParams.get("environment");if(!r){let a=new Error("INVALID_DOTENV_KEY: Missing environment part");throw a.code="INVALID_DOTENV_KEY",a}let i=`DOTENV_VAULT_${r.toUpperCase()}`,o=n.parsed[i];if(!o){let a=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw a.code="NOT_FOUND_DOTENV_ENVIRONMENT",a}return{ciphertext:o,key:s}}function Jc(n){let e=null;if(n&&n.path&&n.path.length>0)if(Array.isArray(n.path))for(let t of n.path)Li.existsSync(t)&&(e=t.endsWith(".vault")?t:`${t}.vault`);else e=n.path.endsWith(".vault")?n.path:`${n.path}.vault`;else e=yn.resolve(process.cwd(),".env.vault");return Li.existsSync(e)?e:null}function Gc(n){return n[0]==="~"?yn.join(km.homedir(),n.slice(1)):n}function xm(n){let e=Rt(process.env.DOTENV_CONFIG_DEBUG||n&&n.debug),t=Rt(process.env.DOTENV_CONFIG_QUIET||n&&n.quiet);(e||!t)&&Vc("loading env from encrypted .env.vault");let s=te._parseVault(n),r=process.env;return n&&n.processEnv!=null&&(r=n.processEnv),te.populate(r,s,n),{parsed:s}}function Om(n){let e=yn.resolve(process.cwd(),".env"),t="utf8",s=process.env;n&&n.processEnv!=null&&(s=n.processEnv);let r=Rt(s.DOTENV_CONFIG_DEBUG||n&&n.debug),i=Rt(s.DOTENV_CONFIG_QUIET||n&&n.quiet);n&&n.encoding?t=n.encoding:r&&ds("no encoding is specified (UTF-8 is used by default)");let o=[e];if(n&&n.path)if(!Array.isArray(n.path))o=[Gc(n.path)];else{o=[];for(let d of n.path)o.push(Gc(d))}let a,l={};for(let d of o)try{let u=te.parse(Li.readFileSync(d,{encoding:t}));te.populate(l,u,n)}catch(u){r&&ds(`failed to load ${d} ${u.message}`),a=u}let c=te.populate(s,l,n);if(r=Rt(s.DOTENV_CONFIG_DEBUG||r),i=Rt(s.DOTENV_CONFIG_QUIET||i),r||!i){let d=Object.keys(c).length,u=[];for(let h of o)try{let p=yn.relative(process.cwd(),h);u.push(p)}catch(p){r&&ds(`failed to load ${h} ${p.message}`),a=p}Vc(`injected env (${d}) from ${u.join(",")} ${Tm(`// tip: ${_m()}`)}`)}return a?{parsed:l,error:a}:{parsed:l}}function Mm(n){if(Yc(n).length===0)return te.configDotenv(n);let e=Jc(n);return e?te._configVault(n):(Em(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),te.configDotenv(n))}function Dm(n,e){let t=Buffer.from(e.slice(-64),"hex"),s=Buffer.from(n,"base64"),r=s.subarray(0,12),i=s.subarray(-16);s=s.subarray(12,-16);try{let o=bm.createDecipheriv("aes-256-gcm",t,r);return o.setAuthTag(i),`${o.update(s)}${o.final()}`}catch(o){let a=o instanceof RangeError,l=o.message==="Invalid key length",c=o.message==="Unsupported state or unable to authenticate data";if(a||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(c){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw o}}function Lm(n,e,t={}){let s=!!(t&&t.debug),r=!!(t&&t.override),i={};if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(n,o)?(r===!0&&(n[o]=e[o],i[o]=e[o]),s&&ds(r===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(n[o]=e[o],i[o]=e[o]);return i}var te={configDotenv:Om,_configVault:xm,_parseVault:Cm,config:Mm,decrypt:Dm,parse:Am,populate:Lm};je.exports.configDotenv=te.configDotenv;je.exports._configVault=te._configVault;je.exports._parseVault=te._parseVault;je.exports.config=te.config;je.exports.decrypt=te.decrypt;je.exports.parse=te.parse;je.exports.populate=te.populate;je.exports=te});var U=T(oe=>{"use strict";var Pi=Symbol.for("yaml.alias"),Qc=Symbol.for("yaml.document"),wn=Symbol.for("yaml.map"),Xc=Symbol.for("yaml.pair"),$i=Symbol.for("yaml.scalar"),Sn=Symbol.for("yaml.seq"),qe=Symbol.for("yaml.node.type"),Pm=n=>!!n&&typeof n=="object"&&n[qe]===Pi,$m=n=>!!n&&typeof n=="object"&&n[qe]===Qc,Rm=n=>!!n&&typeof n=="object"&&n[qe]===wn,Bm=n=>!!n&&typeof n=="object"&&n[qe]===Xc,Zc=n=>!!n&&typeof n=="object"&&n[qe]===$i,Um=n=>!!n&&typeof n=="object"&&n[qe]===Sn;function el(n){if(n&&typeof n=="object")switch(n[qe]){case wn:case Sn:return!0}return!1}function jm(n){if(n&&typeof n=="object")switch(n[qe]){case Pi:case wn:case $i:case Sn:return!0}return!1}var qm=n=>(Zc(n)||el(n))&&!!n.anchor;oe.ALIAS=Pi;oe.DOC=Qc;oe.MAP=wn;oe.NODE_TYPE=qe;oe.PAIR=Xc;oe.SCALAR=$i;oe.SEQ=Sn;oe.hasAnchor=qm;oe.isAlias=Pm;oe.isCollection=el;oe.isDocument=$m;oe.isMap=Rm;oe.isNode=jm;oe.isPair=Bm;oe.isScalar=Zc;oe.isSeq=Um});var us=T(Ri=>{"use strict";var se=U(),he=Symbol("break visit"),tl=Symbol("skip children"),Le=Symbol("remove node");function kn(n,e){let t=sl(e);se.isDocument(n)?Bt(null,n.contents,t,Object.freeze([n]))===Le&&(n.contents=null):Bt(null,n,t,Object.freeze([]))}kn.BREAK=he;kn.SKIP=tl;kn.REMOVE=Le;function Bt(n,e,t,s){let r=nl(n,e,t,s);if(se.isNode(r)||se.isPair(r))return rl(n,s,r),Bt(n,r,t,s);if(typeof r!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=Bt(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===he)return he;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=Bt("key",e.key,t,s);if(i===he)return he;i===Le&&(e.key=null);let o=Bt("value",e.value,t,s);if(o===he)return he;o===Le&&(e.value=null)}}return r}async function bn(n,e){let t=sl(e);se.isDocument(n)?await Ut(null,n.contents,t,Object.freeze([n]))===Le&&(n.contents=null):await Ut(null,n,t,Object.freeze([]))}bn.BREAK=he;bn.SKIP=tl;bn.REMOVE=Le;async function Ut(n,e,t,s){let r=await nl(n,e,t,s);if(se.isNode(r)||se.isPair(r))return rl(n,s,r),Ut(n,r,t,s);if(typeof r!="symbol"){if(se.isCollection(e)){s=Object.freeze(s.concat(e));for(let i=0;i<e.items.length;++i){let o=await Ut(i,e.items[i],t,s);if(typeof o=="number")i=o-1;else{if(o===he)return he;o===Le&&(e.items.splice(i,1),i-=1)}}}else if(se.isPair(e)){s=Object.freeze(s.concat(e));let i=await Ut("key",e.key,t,s);if(i===he)return he;i===Le&&(e.key=null);let o=await Ut("value",e.value,t,s);if(o===he)return he;o===Le&&(e.value=null)}}return r}function sl(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function nl(n,e,t,s){if(typeof t=="function")return t(n,e,s);if(se.isMap(e))return t.Map?.(n,e,s);if(se.isSeq(e))return t.Seq?.(n,e,s);if(se.isPair(e))return t.Pair?.(n,e,s);if(se.isScalar(e))return t.Scalar?.(n,e,s);if(se.isAlias(e))return t.Alias?.(n,e,s)}function rl(n,e,t){let s=e[e.length-1];if(se.isCollection(s))s.items[n]=t;else if(se.isPair(s))n==="key"?s.key=t:s.value=t;else if(se.isDocument(s))s.contents=t;else{let r=se.isAlias(s)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Ri.visit=kn;Ri.visitAsync=bn});var Bi=T(ol=>{"use strict";var il=U(),Fm=us(),Km={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},Hm=n=>n.replace(/[!,[\]{}]/g,e=>Km[e]),hs=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let s=e.trim().split(/[ \t]+/),r=s.shift();switch(r){case"%TAG":{if(s.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),s.length<2))return!1;let[i,o]=s;return this.tags[i]=o,!0}case"%YAML":{if(this.yaml.explicit=!0,s.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[i]=s;if(i==="1.1"||i==="1.2")return this.yaml.version=i,!0;{let o=/^\d+\.\d+$/.test(i);return t(6,`Unsupported YAML version ${i}`,o),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let o=e.slice(2,-1);return o==="!"||o==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),o)}let[,s,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[s];if(i)try{return i+decodeURIComponent(r)}catch(o){return t(String(o)),null}return s==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,s]of Object.entries(this.tags))if(e.startsWith(s))return t+Hm(e.substring(s.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],s=Object.entries(this.tags),r;if(e&&s.length>0&&il.isNode(e.contents)){let i={};Fm.visit(e.contents,(o,a)=>{il.isNode(a)&&a.tag&&(i[a.tag]=!0)}),r=Object.keys(i)}else r=[];for(let[i,o]of s)i==="!!"&&o==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(o)))&&t.push(`%TAG ${i} ${o}`);return t.join(`
6
+ `)}};hs.defaultYaml={explicit:!1,version:"1.2"};hs.defaultTags={"!!":"tag:yaml.org,2002:"};ol.Directives=hs});var _n=T(fs=>{"use strict";var al=U(),Wm=us();function Gm(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function cl(n){let e=new Set;return Wm.visit(n,{Value(t,s){s.anchor&&e.add(s.anchor)}}),e}function ll(n,e){for(let t=1;;++t){let s=`${n}${t}`;if(!e.has(s))return s}}function Vm(n,e){let t=[],s=new Map,r=null;return{onAnchor:i=>{t.push(i),r??(r=cl(n));let o=ll(e,r);return r.add(o),o},setAnchors:()=>{for(let i of t){let o=s.get(i);if(typeof o=="object"&&o.anchor&&(al.isScalar(o.node)||al.isCollection(o.node)))o.node.anchor=o.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=i,a}}},sourceObjects:s}}fs.anchorIsValid=Gm;fs.anchorNames=cl;fs.createNodeAnchors=Vm;fs.findNewAnchor=ll});var Ui=T(dl=>{"use strict";function ps(n,e,t,s){if(s&&typeof s=="object")if(Array.isArray(s))for(let r=0,i=s.length;r<i;++r){let o=s[r],a=ps(n,s,String(r),o);a===void 0?delete s[r]:a!==o&&(s[r]=a)}else if(s instanceof Map)for(let r of Array.from(s.keys())){let i=s.get(r),o=ps(n,s,r,i);o===void 0?s.delete(r):o!==i&&s.set(r,o)}else if(s instanceof Set)for(let r of Array.from(s)){let i=ps(n,s,r,r);i===void 0?s.delete(r):i!==r&&(s.delete(r),s.add(i))}else for(let[r,i]of Object.entries(s)){let o=ps(n,s,r,i);o===void 0?delete s[r]:o!==i&&(s[r]=o)}return n.call(e,t,s)}dl.applyReviver=ps});var Ze=T(hl=>{"use strict";var Ym=U();function ul(n,e,t){if(Array.isArray(n))return n.map((s,r)=>ul(s,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!Ym.hasAnchor(n))return n.toJSON(e,t);let s={aliasCount:0,count:1,res:void 0};t.anchors.set(n,s),t.onCreate=i=>{s.res=i,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}hl.toJS=ul});var vn=T(pl=>{"use strict";var Jm=Ui(),fl=U(),zm=Ze(),ji=class{constructor(e){Object.defineProperty(this,fl.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:s,onAnchor:r,reviver:i}={}){if(!fl.isDocument(e))throw new TypeError("A document argument is required");let o={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof s=="number"?s:100},a=zm.toJS(this,"",o);if(typeof r=="function")for(let{count:l,res:c}of o.anchors.values())r(c,l);return typeof i=="function"?Jm.applyReviver(i,{"":a},"",a):a}};pl.NodeBase=ji});var ms=T(ml=>{"use strict";var Qm=_n(),Xm=us(),jt=U(),Zm=vn(),eg=Ze(),qi=class extends Zm.NodeBase{constructor(e){super(jt.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){let s;t?.aliasResolveCache?s=t.aliasResolveCache:(s=[],Xm.visit(e,{Node:(i,o)=>{(jt.isAlias(o)||jt.hasAnchor(o))&&s.push(o)}}),t&&(t.aliasResolveCache=s));let r;for(let i of s){if(i===this)break;i.anchor===this.source&&(r=i)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:s,doc:r,maxAliasCount:i}=t,o=this.resolve(r,t);if(!o){let l=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(l)}let a=s.get(o);if(a||(eg.toJS(o,null,t),a=s.get(o)),a?.res===void 0){let l="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(l)}if(i>=0&&(a.count+=1,a.aliasCount===0&&(a.aliasCount=Tn(r,o,s)),a.count*a.aliasCount>i)){let l="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(l)}return a.res}toString(e,t,s){let r=`*${this.source}`;if(e){if(Qm.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let i=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(i)}if(e.implicitKey)return`${r} `}return r}};function Tn(n,e,t){if(jt.isAlias(e)){let s=e.resolve(n),r=t&&s&&t.get(s);return r?r.count*r.aliasCount:0}else if(jt.isCollection(e)){let s=0;for(let r of e.items){let i=Tn(n,r,t);i>s&&(s=i)}return s}else if(jt.isPair(e)){let s=Tn(n,e.key,t),r=Tn(n,e.value,t);return Math.max(s,r)}return 1}ml.Alias=qi});var Z=T(Fi=>{"use strict";var tg=U(),sg=vn(),ng=Ze(),rg=n=>!n||typeof n!="function"&&typeof n!="object",et=class extends sg.NodeBase{constructor(e){super(tg.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:ng.toJS(this.value,e,t)}toString(){return String(this.value)}};et.BLOCK_FOLDED="BLOCK_FOLDED";et.BLOCK_LITERAL="BLOCK_LITERAL";et.PLAIN="PLAIN";et.QUOTE_DOUBLE="QUOTE_DOUBLE";et.QUOTE_SINGLE="QUOTE_SINGLE";Fi.Scalar=et;Fi.isScalarValue=rg});var gs=T(yl=>{"use strict";var ig=ms(),gt=U(),gl=Z(),og="tag:yaml.org,2002:";function ag(n,e,t){if(e){let s=t.filter(i=>i.tag===e),r=s.find(i=>!i.format)??s[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(s=>s.identify?.(n)&&!s.format)}function cg(n,e,t){if(gt.isDocument(n)&&(n=n.contents),gt.isNode(n))return n;if(gt.isPair(n)){let u=t.schema[gt.MAP].createNode?.(t.schema,null,t);return u.items.push(n),u}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:s,onAnchor:r,onTagObj:i,schema:o,sourceObjects:a}=t,l;if(s&&n&&typeof n=="object"){if(l=a.get(n),l)return l.anchor??(l.anchor=r(n)),new ig.Alias(l.anchor);l={anchor:null,node:null},a.set(n,l)}e?.startsWith("!!")&&(e=og+e.slice(2));let c=ag(n,e,o.tags);if(!c){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let u=new gl.Scalar(n);return l&&(l.node=u),u}c=n instanceof Map?o[gt.MAP]:Symbol.iterator in Object(n)?o[gt.SEQ]:o[gt.MAP]}i&&(i(c),delete t.onTagObj);let d=c?.createNode?c.createNode(t.schema,n,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,n,t):new gl.Scalar(n);return e?d.tag=e:c.default||(d.tag=c.tag),l&&(l.node=d),d}yl.createNode=cg});var An=T(In=>{"use strict";var lg=gs(),Pe=U(),dg=vn();function Ki(n,e,t){let s=t;for(let r=e.length-1;r>=0;--r){let i=e[r];if(typeof i=="number"&&Number.isInteger(i)&&i>=0){let o=[];o[i]=s,s=o}else s=new Map([[i,s]])}return lg.createNode(s,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var wl=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Hi=class extends dg.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(s=>Pe.isNode(s)||Pe.isPair(s)?s.clone(e):s),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(wl(e))this.add(t);else{let[s,...r]=e,i=this.get(s,!0);if(Pe.isCollection(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(s,Ki(this.schema,r,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}deleteIn(e){let[t,...s]=e;if(s.length===0)return this.delete(t);let r=this.get(t,!0);if(Pe.isCollection(r))return r.deleteIn(s);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${s}`)}getIn(e,t){let[s,...r]=e,i=this.get(s,!0);return r.length===0?!t&&Pe.isScalar(i)?i.value:i:Pe.isCollection(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Pe.isPair(t))return!1;let s=t.value;return s==null||e&&Pe.isScalar(s)&&s.value==null&&!s.commentBefore&&!s.comment&&!s.tag})}hasIn(e){let[t,...s]=e;if(s.length===0)return this.has(t);let r=this.get(t,!0);return Pe.isCollection(r)?r.hasIn(s):!1}setIn(e,t){let[s,...r]=e;if(r.length===0)this.set(s,t);else{let i=this.get(s,!0);if(Pe.isCollection(i))i.setIn(r,t);else if(i===void 0&&this.schema)this.set(s,Ki(this.schema,r,t));else throw new Error(`Expected YAML collection at ${s}. Remaining path: ${r}`)}}};In.Collection=Hi;In.collectionFromPath=Ki;In.isEmptyPath=wl});var ys=T(Cn=>{"use strict";var ug=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function Wi(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var hg=(n,e,t)=>n.endsWith(`
7
+ `)?Wi(t,e):t.includes(`
8
8
  `)?`
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
- `)t===Hi&&(f=ml(r,f,e.length)),u=f+e.length+l,h=void 0;else{if(_===" "&&m&&m!==" "&&m!==`
11
- `&&m!==" "){let v=r[f+1];v&&v!==" "&&v!==`
12
- `&&v!==" "&&(h=f)}if(f>=u)if(h)c.push(h),u=h+l,h=void 0;else if(t===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
- ${e}${r.slice(0,I)}`:(t===An&&d[v]&&(S+=`${r[v]}\\`),S+=`
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=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
- `){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)+`
9
+ `+Wi(t,e):(n.endsWith(" ")?"":" ")+t;Cn.indentComment=Wi;Cn.lineComment=hg;Cn.stringifyComment=ug});var kl=T(ws=>{"use strict";var fg="flow",Gi="block",En="quoted";function pg(n,e,t="flow",{indentAtStart:s,lineWidth:r=80,minContentWidth:i=20,onFold:o,onOverflow:a}={}){if(!r||r<0)return n;r<i&&(i=0);let l=Math.max(1+i,1+r-e.length);if(n.length<=l)return n;let c=[],d={},u=r-e.length;typeof s=="number"&&(s>r-Math.max(2,i)?c.push(0):u=r-s);let h,p,m=!1,f=-1,y=-1,w=-1;t===Gi&&(f=Sl(n,f,e.length),f!==-1&&(u=f+l));for(let _;_=n[f+=1];){if(t===En&&_==="\\"){switch(y=f,n[f+1]){case"x":f+=3;break;case"u":f+=5;break;case"U":f+=9;break;default:f+=1}w=f}if(_===`
10
+ `)t===Gi&&(f=Sl(n,f,e.length)),u=f+e.length+l,h=void 0;else{if(_===" "&&p&&p!==" "&&p!==`
11
+ `&&p!==" "){let v=n[f+1];v&&v!==" "&&v!==`
12
+ `&&v!==" "&&(h=f)}if(f>=u)if(h)c.push(h),u=h+l,h=void 0;else if(t===En){for(;p===" "||p===" ";)p=_,_=n[f+=1],m=!0;let v=f>w+1?f-2:y-1;if(d[v])return n;c.push(v),d[v]=!0,u=v+l,h=void 0}else m=!0}p=_}if(m&&a&&a(),c.length===0)return n;o&&o();let S=n.slice(0,c[0]);for(let _=0;_<c.length;++_){let v=c[_],I=c[_+1]||n.length;v===0?S=`
13
+ ${e}${n.slice(0,I)}`:(t===En&&d[v]&&(S+=`${n[v]}\\`),S+=`
14
+ ${e}${n.slice(v+1,I)}`)}return S}function Sl(n,e,t){let s=e,r=e+1,i=n[r];for(;i===" "||i===" ";)if(e<r+t)i=n[++e];else{do i=n[++e];while(i&&i!==`
15
+ `);s=e,r=e+1,i=n[r]}return s}ws.FOLD_BLOCK=Gi;ws.FOLD_FLOW=fg;ws.FOLD_QUOTED=En;ws.foldFlowLines=pg});var ks=T(bl=>{"use strict";var Ce=Z(),tt=kl(),xn=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),On=n=>/^(%|---|\.\.\.)/m.test(n);function mg(n,e,t){if(!e||e<0)return!1;let s=e-t,r=n.length;if(r<=s)return!1;for(let i=0,o=0;i<r;++i)if(n[i]===`
16
+ `){if(i-o>s)return!0;if(o=i+1,r-o<=s)return!1}return!0}function Ss(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:s}=e,r=e.options.doubleQuotedMinMultiLineLength,i=e.indent||(On(n)?" ":""),o="",a=0;for(let l=0,c=t[l];c;c=t[++l])if(c===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(o+=t.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(t[l+1]){case"u":{o+=t.slice(a,l);let d=t.substr(l+2,4);switch(d){case"0000":o+="\\0";break;case"0007":o+="\\a";break;case"000b":o+="\\v";break;case"001b":o+="\\e";break;case"0085":o+="\\N";break;case"00a0":o+="\\_";break;case"2028":o+="\\L";break;case"2029":o+="\\P";break;default:d.substr(0,2)==="00"?o+="\\x"+d.substr(2):o+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(s||t[l+2]==='"'||t.length<r)l+=1;else{for(o+=t.slice(a,l)+`
17
17
 
18
18
  `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)o+=`
19
- `,l+=2;o+=i,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,s?o:st.foldFlowLines(o,i,st.FOLD_QUOTED,Nn(e,!1))}function Wi(r,e){if(e.options.singleQuote===!1||e.implicitKey&&r.includes(`
20
- `)||/[ \t]\n|\n[ \t]/.test(r))return Ss(r,e);let t=e.indent||(xn(r)?" ":""),s="'"+r.replace(/'/g,"''").replace(/\n+/g,`$&
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(`(^|(?<!
19
+ `,l+=2;o+=i,t[l+2]===" "&&(o+="\\"),l+=1,a=l+1}break;default:l+=1}return o=a?o+t.slice(a):t,s?o:tt.foldFlowLines(o,i,tt.FOLD_QUOTED,xn(e,!1))}function Vi(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
20
+ `)||/[ \t]\n|\n[ \t]/.test(n))return Ss(n,e);let t=e.indent||(On(n)?" ":""),s="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
21
+ ${t}`)+"'";return e.implicitKey?s:tt.foldFlowLines(s,t,tt.FOLD_FLOW,xn(e,!1))}function qt(n,e){let{singleQuote:t}=e.options,s;if(t===!1)s=Ss;else{let r=n.includes('"'),i=n.includes("'");r&&!i?s=Vi:i&&!r?s=Ss:s=t?Vi:Ss}return s(n,e)}var Yi;try{Yi=new RegExp(`(^|(?<!
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:!lg(t,l,c.length);if(!t)return d?`|
24
+ |$)`,"g")}catch{Yi=/\n+(?!\n|$)/g}function Nn({comment:n,type:e,value:t},s,r,i){let{blockQuote:o,commentString:a,lineWidth:l}=s.options;if(!o||/\n[\t ]+$/.test(t))return qt(t,s);let c=s.indent||(s.forceBlockIndent||On(t)?" ":""),d=o==="literal"?!0:o==="folded"||e===Ce.Scalar.BLOCK_FOLDED?!1:e===Ce.Scalar.BLOCK_LITERAL?!0:!mg(t,l,c.length);if(!t)return d?`|
25
25
  `:`>
26
26
  `;let u,h;for(h=t.length;h>0;--h){let I=t[h-1];if(I!==`
27
- `&&I!==" "&&I!==" ")break}let m=t.substring(h),g=m.indexOf(`
28
- `);g===-1?u="-":t===m||g!==m.length-1?(u="+",i&&i()):u="",m&&(t=t.slice(0,-m.length),m[m.length-1]===`
29
- `&&(m=m.slice(0,-1)),m=m.replace(Gi,`$&${c}`));let f=!1,y,w=-1;for(y=0;y<t.length;++y){let I=t[y];if(I===" ")f=!0;else if(I===`
30
- `)w=y;else break}let S=t.substring(0,w<y?w+1:y);S&&(t=t.substring(S.length),S=S.replace(/\n+/g,`$&${c}`));let v=(f?c?"2":"1":"")+u;if(r&&(v+=" "+a(r.replace(/ ?[\r\n]+/g," ")),n&&n()),!d){let I=t.replace(/\n+/g,`
31
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),N=!1,D=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
- ${c}${C}`}return t=t.replace(/\n+/g,`$&${c}`),`|${v}
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(`
27
+ `&&I!==" "&&I!==" ")break}let p=t.substring(h),m=p.indexOf(`
28
+ `);m===-1?u="-":t===p||m!==p.length-1?(u="+",i&&i()):u="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
29
+ `&&(p=p.slice(0,-1)),p=p.replace(Yi,`$&${c}`));let f=!1,y,w=-1;for(y=0;y<t.length;++y){let I=t[y];if(I===" ")f=!0;else if(I===`
30
+ `)w=y;else break}let S=t.substring(0,w<y?w+1:y);S&&(t=t.substring(S.length),S=S.replace(/\n+/g,`$&${c}`));let v=(f?c?"2":"1":"")+u;if(n&&(v+=" "+a(n.replace(/ ?[\r\n]+/g," ")),r&&r()),!d){let I=t.replace(/\n+/g,`
31
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),N=!1,D=xn(s,!0);o!=="folded"&&e!==Ce.Scalar.BLOCK_FOLDED&&(D.onOverflow=()=>{N=!0});let A=tt.foldFlowLines(`${S}${I}${p}`,c,tt.FOLD_BLOCK,D);if(!N)return`>${v}
32
+ ${c}${A}`}return t=t.replace(/\n+/g,`$&${c}`),`|${v}
33
+ ${c}${S}${t}${p}`}function gg(n,e,t,s){let{type:r,value:i}=n,{actualString:o,implicitKey:a,indent:l,indentStep:c,inFlow:d}=e;if(a&&i.includes(`
34
34
  `)||d&&/[[\]{},]/.test(i))return qt(i,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(i))return a||d||!i.includes(`
35
- `)?qt(i,e):En(r,e,t,s);if(!a&&!d&&n!==Ae.Scalar.PLAIN&&i.includes(`
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 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
- ${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?`
35
+ `)?qt(i,e):Nn(n,e,t,s);if(!a&&!d&&r!==Ce.Scalar.PLAIN&&i.includes(`
36
+ `))return Nn(n,e,t,s);if(On(i)){if(l==="")return e.forceBlockIndent=!0,Nn(n,e,t,s);if(a&&l===c)return qt(i,e)}let u=i.replace(/\n+/g,`$&
37
+ ${l}`);if(o){let h=f=>f.default&&f.tag!=="tag:yaml.org,2002:str"&&f.test?.test(u),{compat:p,tags:m}=e.doc.schema;if(m.some(h)||p?.some(h))return qt(i,e)}return a?u:tt.foldFlowLines(u,l,tt.FOLD_FLOW,xn(e,!1))}function yg(n,e,t,s){let{implicitKey:r,inFlow:i}=e,o=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==Ce.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(a=Ce.Scalar.QUOTE_DOUBLE);let l=d=>{switch(d){case Ce.Scalar.BLOCK_FOLDED:case Ce.Scalar.BLOCK_LITERAL:return r||i?qt(o.value,e):Nn(o,e,t,s);case Ce.Scalar.QUOTE_DOUBLE:return Ss(o.value,e);case Ce.Scalar.QUOTE_SINGLE:return Vi(o.value,e);case Ce.Scalar.PLAIN:return gg(o,e,t,s);default:return null}},c=l(a);if(c===null){let{defaultKeyType:d,defaultStringType:u}=e.options,h=r&&d||u;if(c=l(h),c===null)throw new Error(`Unsupported default string type ${h}`)}return c}bl.stringifyString=yg});var bs=T(Ji=>{"use strict";var wg=_n(),st=U(),Sg=ys(),kg=ks();function bg(n,e){let t=Object.assign({blockQuote:!0,commentString:Sg.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),s;switch(t.collectionStyle){case"block":s=!1;break;case"flow":s=!0;break;default:s=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:s,options:t}}function _g(n,e){if(e.tag){let r=n.filter(i=>i.tag===e.tag);if(r.length>0)return r.find(i=>i.format===e.format)??r[0]}let t,s;if(st.isScalar(e)){s=e.value;let r=n.filter(i=>i.identify?.(s));if(r.length>1){let i=r.filter(o=>o.test);i.length>0&&(r=i)}t=r.find(i=>i.format===e.format)??r.find(i=>!i.format)}else s=e,t=n.find(r=>r.nodeClass&&s instanceof r.nodeClass);if(!t){let r=s?.constructor?.name??(s===null?"null":typeof s);throw new Error(`Tag not resolved for ${r} value`)}return t}function vg(n,e,{anchors:t,doc:s}){if(!s.directives)return"";let r=[],i=(st.isScalar(n)||st.isCollection(n))&&n.anchor;i&&wg.anchorIsValid(i)&&(t.add(i),r.push(`&${i}`));let o=n.tag??(e.default?null:e.tag);return o&&r.push(s.directives.tagString(o)),r.join(" ")}function Tg(n,e,t,s){if(st.isPair(n))return n.toString(e,t,s);if(st.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,i=st.isNode(n)?n:e.doc.createNode(n,{onTagObj:l=>r=l});r??(r=_g(e.doc.schema.tags,i));let o=vg(i,r,e);o.length>0&&(e.indentAtStart=(e.indentAtStart??0)+o.length+1);let a=typeof r.stringify=="function"?r.stringify(i,e,t,s):st.isScalar(i)?kg.stringifyString(i,e,t,s):i.toString(e,t,s);return o?st.isScalar(i)||a[0]==="{"||a[0]==="["?`${o} ${a}`:`${o}
38
+ ${e.indent}${a}`:a}Ji.createStringifyContext=bg;Ji.stringify=Tg});var Il=T(Tl=>{"use strict";var Fe=U(),_l=Z(),vl=bs(),_s=ys();function Ig({key:n,value:e},t,s,r){let{allNullValues:i,doc:o,indent:a,indentStep:l,options:{commentString:c,indentSeq:d,simpleKeys:u}}=t,h=Fe.isNode(n)&&n.comment||null;if(u){if(h)throw new Error("With simple keys, key nodes cannot have comments");if(Fe.isCollection(n)||!Fe.isNode(n)&&typeof n=="object"){let D="With simple keys, collection cannot be used as a key value";throw new Error(D)}}let p=!u&&(!n||h&&e==null&&!t.inFlow||Fe.isCollection(n)||(Fe.isScalar(n)?n.type===_l.Scalar.BLOCK_FOLDED||n.type===_l.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(u||!i),indent:a+l});let m=!1,f=!1,y=vl.stringify(n,t,()=>m=!0,()=>f=!0);if(!p&&!t.inFlow&&y.length>1024){if(u)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(i||e==null)return m&&s&&s(),y===""?"?":p?`? ${y}`:y}else if(i&&!u||e==null&&p)return y=`? ${y}`,h&&!m?y+=_s.lineComment(y,t.indent,c(h)):f&&r&&r(),y;m&&(h=null),p?(h&&(y+=_s.lineComment(y,t.indent,c(h))),y=`? ${y}
39
+ ${a}:`):(y=`${y}:`,h&&(y+=_s.lineComment(y,t.indent,c(h))));let w,S,_;Fe.isNode(e)?(w=!!e.spaceBefore,S=e.commentBefore,_=e.comment):(w=!1,S=null,_=null,e&&typeof e=="object"&&(e=o.createNode(e))),t.implicitKey=!1,!p&&!h&&Fe.isScalar(e)&&(t.indentAtStart=y.length+1),f=!1,!d&&l.length>=2&&!t.inFlow&&!p&&Fe.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let v=!1,I=vl.stringify(e,t,()=>v=!0,()=>f=!0),N=" ";if(h||w||S){if(N=w?`
40
40
  `:"",S){let D=c(S);N+=`
41
41
  ${_s.indentComment(D,t.indent)}`}I===""&&!t.inFlow?N===`
42
42
  `&&_&&(N=`
43
43
 
44
44
  `):N+=`
45
- ${t.indent}`}else if(!m&&Fe.isCollection(e)){let D=I[0],C=I.indexOf(`
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=`
45
+ ${t.indent}`}else if(!p&&Fe.isCollection(e)){let D=I[0],A=I.indexOf(`
46
+ `),E=A!==-1,G=t.inFlow??e.flow??e.items.length===0;if(E||!G){let W=!1;if(E&&(D==="&"||D==="!")){let $=I.indexOf(" ");D==="&"&&$!==-1&&$<A&&I[$+1]==="!"&&($=I.indexOf(" ",$+1)),($===-1||A<$)&&(W=!0)}W||(N=`
47
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=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?`
48
+ `)&&(N="");return y+=N+I,t.inFlow?v&&s&&s():_&&!v?y+=_s.lineComment(y,t.indent,c(_)):f&&r&&r(),y}Tl.stringifyPair=Ig});var Qi=T(zi=>{"use strict";var Al=H("process");function Ag(n,...e){n==="debug"&&console.log(...e)}function Cg(n,e){(n==="debug"||n==="warn")&&(typeof Al.emitWarning=="function"?Al.emitWarning(e):console.warn(e))}zi.debug=Ag;zi.warn=Cg});var Pn=T(Ln=>{"use strict";var vs=U(),Cl=Z(),Mn="<<",Dn={identify:n=>n===Mn||typeof n=="symbol"&&n.description===Mn,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Cl.Scalar(Symbol(Mn)),{addToJSMap:El}),stringify:()=>Mn},Eg=(n,e)=>(Dn.identify(e)||vs.isScalar(e)&&(!e.type||e.type===Cl.Scalar.PLAIN)&&Dn.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===Dn.tag&&t.default);function El(n,e,t){if(t=n&&vs.isAlias(t)?t.resolve(n.doc):t,vs.isSeq(t))for(let s of t.items)Xi(n,e,s);else if(Array.isArray(t))for(let s of t)Xi(n,e,s);else Xi(n,e,t)}function Xi(n,e,t){let s=n&&vs.isAlias(t)?t.resolve(n.doc):t;if(!vs.isMap(s))throw new Error("Merge sources must be maps or map aliases");let r=s.toJSON(null,n,Map);for(let[i,o]of r)e instanceof Map?e.has(i)||e.set(i,o):e instanceof Set?e.add(i):Object.prototype.hasOwnProperty.call(e,i)||Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0});return e}Ln.addMergeToJSMap=El;Ln.isMergeKey=Eg;Ln.merge=Dn});var eo=T(Ol=>{"use strict";var Ng=Qi(),Nl=Pn(),xg=bs(),xl=U(),Zi=Ze();function Og(n,e,{key:t,value:s}){if(xl.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,s);else if(Nl.isMergeKey(n,t))Nl.addMergeToJSMap(n,e,s);else{let r=Zi.toJS(t,"",n);if(e instanceof Map)e.set(r,Zi.toJS(s,r,n));else if(e instanceof Set)e.add(r);else{let i=Mg(t,r,n),o=Zi.toJS(s,i,n);i in e?Object.defineProperty(e,i,{value:o,writable:!0,enumerable:!0,configurable:!0}):e[i]=o}}return e}function Mg(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(xl.isNode(n)&&t?.doc){let s=xg.createStringifyContext(t.doc,{});s.anchors=new Set;for(let i of t.anchors.keys())s.anchors.add(i.anchor);s.inFlow=!0,s.inStringifyKey=!0;let r=n.toString(s);if(!t.mapKeyWarned){let i=JSON.stringify(r);i.length>40&&(i=i.substring(0,36)+'..."'),Ng.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${i}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}Ol.addPairToJSMap=Og});var nt=T(to=>{"use strict";var Ml=gs(),Dg=Il(),Lg=eo(),$n=U();function Pg(n,e,t){let s=Ml.createNode(n,void 0,t),r=Ml.createNode(e,void 0,t);return new Rn(s,r)}var Rn=class n{constructor(e,t=null){Object.defineProperty(this,$n.NODE_TYPE,{value:$n.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:s}=this;return $n.isNode(t)&&(t=t.clone(e)),$n.isNode(s)&&(s=s.clone(e)),new n(t,s)}toJSON(e,t){let s=t?.mapAsMap?new Map:{};return Lg.addPairToJSMap(t,s,this)}toString(e,t,s){return e?.doc?Dg.stringifyPair(this,e,t,s):JSON.stringify(this)}};to.Pair=Rn;to.createPair=Pg});var so=T(Ll=>{"use strict";var yt=U(),Dl=bs(),Bn=ys();function $g(n,e,t){return(e.inFlow??n.flow?Bg:Rg)(n,e,t)}function Rg({comment:n,items:e},t,{blockItemPrefix:s,flowChars:r,itemIndent:i,onChompKeep:o,onComment:a}){let{indent:l,options:{commentString:c}}=t,d=Object.assign({},t,{indent:i,type:null}),u=!1,h=[];for(let m=0;m<e.length;++m){let f=e[m],y=null;if(yt.isNode(f))!u&&f.spaceBefore&&h.push(""),Un(t,h,f.commentBefore,u),f.comment&&(y=f.comment);else if(yt.isPair(f)){let S=yt.isNode(f.key)?f.key:null;S&&(!u&&S.spaceBefore&&h.push(""),Un(t,h,S.commentBefore,u))}u=!1;let w=Dl.stringify(f,d,()=>y=null,()=>u=!0);y&&(w+=Bn.lineComment(w,i,c(y))),u&&y&&(u=!1),h.push(s+w)}let p;if(h.length===0)p=r.start+r.end;else{p=h[0];for(let m=1;m<h.length;++m){let f=h[m];p+=f?`
49
49
  ${l}${f}`:`
50
- `}}return r?(m+=`
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
- `)),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
- ${i}${n}${f}`:`
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=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
- ${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 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
- `)?(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(`
50
+ `}}return n?(p+=`
51
+ `+Bn.indentComment(c(n),l),a&&a()):u&&o&&o(),p}function Bg({items:n},e,{flowChars:t,itemIndent:s}){let{indent:r,indentStep:i,flowCollectionPadding:o,options:{commentString:a}}=e;s+=i;let l=Object.assign({},e,{indent:s,inFlow:!0,type:null}),c=!1,d=0,u=[];for(let m=0;m<n.length;++m){let f=n[m],y=null;if(yt.isNode(f))f.spaceBefore&&u.push(""),Un(e,u,f.commentBefore,!1),f.comment&&(y=f.comment);else if(yt.isPair(f)){let S=yt.isNode(f.key)?f.key:null;S&&(S.spaceBefore&&u.push(""),Un(e,u,S.commentBefore,!1),S.comment&&(c=!0));let _=yt.isNode(f.value)?f.value:null;_?(_.comment&&(y=_.comment),_.commentBefore&&(c=!0)):f.value==null&&S?.comment&&(y=S.comment)}y&&(c=!0);let w=Dl.stringify(f,l,()=>y=null);c||(c=u.length>d||w.includes(`
52
+ `)),m<n.length-1?w+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=u.reduce((S,_)=>S+_.length+2,2)+(w.length+2)>e.options.lineWidth)),c&&(w+=",")),y&&(w+=Bn.lineComment(w,s,a(y))),u.push(w),d=u.length}let{start:h,end:p}=t;if(u.length===0)return h+p;if(!c){let m=u.reduce((f,y)=>f+y.length+2,2);c=e.options.lineWidth>0&&m>e.options.lineWidth}if(c){let m=h;for(let f of u)m+=f?`
53
+ ${i}${r}${f}`:`
54
+ `;return`${m}
55
+ ${r}${p}`}else return`${h}${o}${u.join(" ")}${o}${p}`}function Un({indent:n,options:{commentString:e}},t,s,r){if(s&&r&&(s=s.replace(/^\n+/,"")),s){let i=Bn.indentComment(e(s),n);t.push(i.trimStart())}}Ll.stringifyCollection=$g});var it=T(ro=>{"use strict";var Ug=so(),jg=eo(),qg=An(),rt=U(),jn=nt(),Fg=Z();function Ts(n,e){let t=rt.isScalar(e)?e.value:e;for(let s of n)if(rt.isPair(s)&&(s.key===e||s.key===t||rt.isScalar(s.key)&&s.key.value===t))return s}var no=class extends qg.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(rt.MAP,e),this.items=[]}static from(e,t,s){let{keepUndefined:r,replacer:i}=s,o=new this(e),a=(l,c)=>{if(typeof i=="function")c=i.call(t,l,c);else if(Array.isArray(i)&&!i.includes(l))return;(c!==void 0||r)&&o.items.push(jn.createPair(l,c,s))};if(t instanceof Map)for(let[l,c]of t)a(l,c);else if(t&&typeof t=="object")for(let l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&o.items.sort(e.sortMapEntries),o}add(e,t){let s;rt.isPair(e)?s=e:!e||typeof e!="object"||!("key"in e)?s=new jn.Pair(e,e?.value):s=new jn.Pair(e.key,e.value);let r=Ts(this.items,s.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${s.key} already set`);rt.isScalar(r.value)&&Fg.isScalarValue(s.value)?r.value.value=s.value:r.value=s.value}else if(i){let o=this.items.findIndex(a=>i(s,a)<0);o===-1?this.items.push(s):this.items.splice(o,0,s)}else this.items.push(s)}delete(e){let t=Ts(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=Ts(this.items,e)?.value;return(!t&&rt.isScalar(r)?r.value:r)??void 0}has(e){return!!Ts(this.items,e)}set(e,t){this.add(new jn.Pair(e,t),!0)}toJSON(e,t,s){let r=s?new s:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let i of this.items)jg.addPairToJSMap(t,r,i);return r}toString(e,t,s){if(!e)return JSON.stringify(this);for(let r of this.items)if(!rt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Ug.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:s,onComment:t})}};ro.YAMLMap=no;ro.findPair=Ts});var Ft=T($l=>{"use strict";var Kg=U(),Pl=it(),Hg={collection:"map",default:!0,nodeClass:Pl.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return Kg.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>Pl.YAMLMap.from(n,e,t)};$l.map=Hg});var ot=T(Rl=>{"use strict";var Wg=gs(),Gg=so(),Vg=An(),Fn=U(),Yg=Z(),Jg=Ze(),io=class extends Vg.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(Fn.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=qn(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let s=qn(e);if(typeof s!="number")return;let r=this.items[s];return!t&&Fn.isScalar(r)?r.value:r}has(e){let t=qn(e);return typeof t=="number"&&t<this.items.length}set(e,t){let s=qn(e);if(typeof s!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[s];Fn.isScalar(r)&&Yg.isScalarValue(t)?r.value=t:this.items[s]=t}toJSON(e,t){let s=[];t?.onCreate&&t.onCreate(s);let r=0;for(let i of this.items)s.push(Jg.toJS(i,String(r++),t));return s}toString(e,t,s){return e?Gg.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:s,onComment:t}):JSON.stringify(this)}static from(e,t,s){let{replacer:r}=s,i=new this(e);if(t&&Symbol.iterator in Object(t)){let o=0;for(let a of t){if(typeof r=="function"){let l=t instanceof Set?a:String(o++);a=r.call(t,l,a)}i.items.push(Wg.createNode(a,void 0,s))}}return i}};function qn(n){let e=Fn.isScalar(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Rl.YAMLSeq=io});var Kt=T(Ul=>{"use strict";var zg=U(),Bl=ot(),Qg={collection:"seq",default:!0,nodeClass:Bl.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return zg.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>Bl.YAMLSeq.from(n,e,t)};Ul.seq=Qg});var Is=T(jl=>{"use strict";var Xg=ks(),Zg={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,s){return e=Object.assign({actualString:!0},e),Xg.stringifyString(n,e,t,s)}};jl.string=Zg});var Kn=T(Kl=>{"use strict";var ql=Z(),Fl={identify:n=>n==null,createNode:()=>new ql.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ql.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&Fl.test.test(n)?n:e.options.nullStr};Kl.nullTag=Fl});var oo=T(Wl=>{"use strict";var ey=Z(),Hl={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new ey.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&Hl.test.test(n)){let s=n[0]==="t"||n[0]==="T";if(e===s)return n}return e?t.options.trueStr:t.options.falseStr}};Wl.boolTag=Hl});var Ht=T(Gl=>{"use strict";function ty({format:n,minFractionDigits:e,tag:t,value:s}){if(typeof s=="bigint")return String(s);let r=typeof s=="number"?s:Number(s);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let i=Object.is(s,-0)?"-0":JSON.stringify(s);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^\d/.test(i)){let o=i.indexOf(".");o<0&&(o=i.length,i+=".");let a=e-(i.length-o-1);for(;a-- >0;)i+="0"}return i}Gl.stringifyNumber=ty});var co=T(Hn=>{"use strict";var sy=Z(),ao=Ht(),ny={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ao.stringifyNumber},ry={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():ao.stringifyNumber(n)}},iy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new sy.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:ao.stringifyNumber};Hn.float=iy;Hn.floatExp=ry;Hn.floatNaN=ny});var uo=T(Gn=>{"use strict";var Vl=Ht(),Wn=n=>typeof n=="bigint"||Number.isInteger(n),lo=(n,e,t,{intAsBigInt:s})=>s?BigInt(n):parseInt(n.substring(e),t);function Yl(n,e,t){let{value:s}=n;return Wn(s)&&s>=0?t+s.toString(e):Vl.stringifyNumber(n)}var oy={identify:n=>Wn(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>lo(n,2,8,t),stringify:n=>Yl(n,8,"0o")},ay={identify:Wn,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>lo(n,0,10,t),stringify:Vl.stringifyNumber},cy={identify:n=>Wn(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>lo(n,2,16,t),stringify:n=>Yl(n,16,"0x")};Gn.int=ay;Gn.intHex=cy;Gn.intOct=oy});var zl=T(Jl=>{"use strict";var ly=Ft(),dy=Kn(),uy=Kt(),hy=Is(),fy=oo(),ho=co(),fo=uo(),py=[ly.map,uy.seq,hy.string,dy.nullTag,fy.boolTag,fo.intOct,fo.int,fo.intHex,ho.floatNaN,ho.floatExp,ho.float];Jl.schema=py});var Zl=T(Xl=>{"use strict";var my=Z(),gy=Ft(),yy=Kt();function Ql(n){return typeof n=="bigint"||Number.isInteger(n)}var Vn=({value:n})=>JSON.stringify(n),wy=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:Vn},{identify:n=>n==null,createNode:()=>new my.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:Vn},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:Vn},{identify:Ql,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>Ql(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:Vn}],Sy={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},ky=[gy.map,yy.seq].concat(wy,Sy);Xl.schema=ky});var mo=T(ed=>{"use strict";var As=H("buffer"),po=Z(),by=ks(),_y={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof As.Buffer=="function")return As.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),s=new Uint8Array(t.length);for(let r=0;r<t.length;++r)s[r]=t.charCodeAt(r);return s}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},s,r,i){if(!t)return"";let o=t,a;if(typeof As.Buffer=="function")a=o instanceof As.Buffer?o.toString("base64"):As.Buffer.from(o.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<o.length;++c)l+=String.fromCharCode(o[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=po.Scalar.BLOCK_LITERAL),e!==po.Scalar.QUOTE_DOUBLE){let l=Math.max(s.options.lineWidth-s.indent.length,s.options.minContentWidth),c=Math.ceil(a.length/l),d=new Array(c);for(let u=0,h=0;u<c;++u,h+=l)d[u]=a.substr(h,l);a=d.join(e===po.Scalar.BLOCK_LITERAL?`
56
+ `:" ")}return by.stringifyString({comment:n,type:e,value:a},s,r,i)}};ed.binary=_y});var zn=T(Jn=>{"use strict";var Yn=U(),go=nt(),vy=Z(),Ty=ot();function td(n,e){if(Yn.isSeq(n))for(let t=0;t<n.items.length;++t){let s=n.items[t];if(!Yn.isPair(s)){if(Yn.isMap(s)){s.items.length>1&&e("Each pair must have its own sequence indicator");let r=s.items[0]||new go.Pair(new vy.Scalar(null));if(s.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${s.commentBefore}
57
+ ${r.key.commentBefore}`:s.commentBefore),s.comment){let i=r.value??r.key;i.comment=i.comment?`${s.comment}
58
+ ${i.comment}`:s.comment}s=r}n.items[t]=Yn.isPair(s)?s:new go.Pair(s)}}else e("Expected a sequence for this tag");return n}function sd(n,e,t){let{replacer:s}=t,r=new Ty.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let i=0;if(e&&Symbol.iterator in Object(e))for(let o of e){typeof s=="function"&&(o=s.call(e,String(i++),o));let a,l;if(Array.isArray(o))if(o.length===2)a=o[0],l=o[1];else throw new TypeError(`Expected [key, value] tuple: ${o}`);else if(o&&o instanceof Object){let c=Object.keys(o);if(c.length===1)a=c[0],l=o[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=o;r.items.push(go.createPair(a,l,t))}return r}var Iy={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:td,createNode:sd};Jn.createPairs=sd;Jn.pairs=Iy;Jn.resolvePairs=td});var So=T(wo=>{"use strict";var nd=U(),yo=Ze(),Cs=it(),Ay=ot(),rd=zn(),wt=class n extends Ay.YAMLSeq{constructor(){super(),this.add=Cs.YAMLMap.prototype.add.bind(this),this.delete=Cs.YAMLMap.prototype.delete.bind(this),this.get=Cs.YAMLMap.prototype.get.bind(this),this.has=Cs.YAMLMap.prototype.has.bind(this),this.set=Cs.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let s=new Map;t?.onCreate&&t.onCreate(s);for(let r of this.items){let i,o;if(nd.isPair(r)?(i=yo.toJS(r.key,"",t),o=yo.toJS(r.value,i,t)):i=yo.toJS(r,"",t),s.has(i))throw new Error("Ordered maps must not include duplicate keys");s.set(i,o)}return s}static from(e,t,s){let r=rd.createPairs(e,t,s),i=new this;return i.items=r.items,i}};wt.tag="tag:yaml.org,2002:omap";var Cy={collection:"seq",identify:n=>n instanceof Map,nodeClass:wt,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=rd.resolvePairs(n,e),s=[];for(let{key:r}of t.items)nd.isScalar(r)&&(s.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):s.push(r.value));return Object.assign(new wt,t)},createNode:(n,e,t)=>wt.from(n,e,t)};wo.YAMLOMap=wt;wo.omap=Cy});var ld=T(ko=>{"use strict";var id=Z();function od({value:n,source:e},t){return e&&(n?ad:cd).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var ad={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new id.Scalar(!0),stringify:od},cd={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new id.Scalar(!1),stringify:od};ko.falseTag=cd;ko.trueTag=ad});var dd=T(Qn=>{"use strict";var Ey=Z(),bo=Ht(),Ny={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:bo.stringifyNumber},xy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():bo.stringifyNumber(n)}},Oy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new Ey.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let s=n.substring(t+1).replace(/_/g,"");s[s.length-1]==="0"&&(e.minFractionDigits=s.length)}return e},stringify:bo.stringifyNumber};Qn.float=Oy;Qn.floatExp=xy;Qn.floatNaN=Ny});var hd=T(Ns=>{"use strict";var ud=Ht(),Es=n=>typeof n=="bigint"||Number.isInteger(n);function Xn(n,e,t,{intAsBigInt:s}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),s){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let o=BigInt(n);return r==="-"?BigInt(-1)*o:o}let i=parseInt(n,t);return r==="-"?-1*i:i}function _o(n,e,t){let{value:s}=n;if(Es(s)){let r=s.toString(e);return s<0?"-"+t+r.substr(1):t+r}return ud.stringifyNumber(n)}var My={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>Xn(n,2,2,t),stringify:n=>_o(n,2,"0b")},Dy={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>Xn(n,1,8,t),stringify:n=>_o(n,8,"0")},Ly={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>Xn(n,0,10,t),stringify:ud.stringifyNumber},Py={identify:Es,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>Xn(n,2,16,t),stringify:n=>_o(n,16,"0x")};Ns.int=Ly;Ns.intBin=My;Ns.intHex=Py;Ns.intOct=Dy});var To=T(vo=>{"use strict";var tr=U(),Zn=nt(),er=it(),St=class n extends er.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;tr.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Zn.Pair(e.key,null):t=new Zn.Pair(e,null),er.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let s=er.findPair(this.items,e);return!t&&tr.isPair(s)?tr.isScalar(s.key)?s.key.value:s.key:s}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let s=er.findPair(this.items,e);s&&!t?this.items.splice(this.items.indexOf(s),1):!s&&t&&this.items.push(new Zn.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,s){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,s);throw new Error("Set items must all have null values")}static from(e,t,s){let{replacer:r}=s,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let o of t)typeof r=="function"&&(o=r.call(t,o,o)),i.items.push(Zn.createPair(o,null,s));return i}};St.tag="tag:yaml.org,2002:set";var $y={collection:"map",identify:n=>n instanceof Set,nodeClass:St,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>St.from(n,e,t),resolve(n,e){if(tr.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new St,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};vo.YAMLSet=St;vo.set=$y});var Ao=T(sr=>{"use strict";var Ry=Ht();function Io(n,e){let t=n[0],s=t==="-"||t==="+"?n.substring(1):n,r=o=>e?BigInt(o):Number(o),i=s.replace(/_/g,"").split(":").reduce((o,a)=>o*r(60)+r(a),r(0));return t==="-"?r(-1)*i:i}function fd(n){let{value:e}=n,t=o=>o;if(typeof e=="bigint")t=o=>BigInt(o);else if(isNaN(e)||!isFinite(e))return Ry.stringifyNumber(n);let s="";e<0&&(s="-",e*=t(-1));let r=t(60),i=[e%r];return e<60?i.unshift(0):(e=(e-i[0])/r,i.unshift(e%r),e>=60&&(e=(e-i[0])/r,i.unshift(e))),s+i.map(o=>String(o).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var By={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>Io(n,t),stringify:fd},Uy={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>Io(n,!1),stringify:fd},pd={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(pd.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,s,r,i,o,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,s-1,r,i||0,o||0,a||0,l),d=e[8];if(d&&d!=="Z"){let u=Io(d,!1);Math.abs(u)<30&&(u*=60),c-=6e4*u}return new Date(c)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};sr.floatTime=Uy;sr.intTime=By;sr.timestamp=pd});var yd=T(gd=>{"use strict";var jy=Ft(),qy=Kn(),Fy=Kt(),Ky=Is(),Hy=mo(),md=ld(),Co=dd(),nr=hd(),Wy=Pn(),Gy=So(),Vy=zn(),Yy=To(),Eo=Ao(),Jy=[jy.map,Fy.seq,Ky.string,qy.nullTag,md.trueTag,md.falseTag,nr.intBin,nr.intOct,nr.int,nr.intHex,Co.floatNaN,Co.floatExp,Co.float,Hy.binary,Wy.merge,Gy.omap,Vy.pairs,Yy.set,Eo.intTime,Eo.floatTime,Eo.timestamp];gd.schema=Jy});var Cd=T(Oo=>{"use strict";var bd=Ft(),zy=Kn(),_d=Kt(),Qy=Is(),Xy=oo(),No=co(),xo=uo(),Zy=zl(),ew=Zl(),vd=mo(),xs=Pn(),Td=So(),Id=zn(),wd=yd(),Ad=To(),rr=Ao(),Sd=new Map([["core",Zy.schema],["failsafe",[bd.map,_d.seq,Qy.string]],["json",ew.schema],["yaml11",wd.schema],["yaml-1.1",wd.schema]]),kd={binary:vd.binary,bool:Xy.boolTag,float:No.float,floatExp:No.floatExp,floatNaN:No.floatNaN,floatTime:rr.floatTime,int:xo.int,intHex:xo.intHex,intOct:xo.intOct,intTime:rr.intTime,map:bd.map,merge:xs.merge,null:zy.nullTag,omap:Td.omap,pairs:Id.pairs,seq:_d.seq,set:Ad.set,timestamp:rr.timestamp},tw={"tag:yaml.org,2002:binary":vd.binary,"tag:yaml.org,2002:merge":xs.merge,"tag:yaml.org,2002:omap":Td.omap,"tag:yaml.org,2002:pairs":Id.pairs,"tag:yaml.org,2002:set":Ad.set,"tag:yaml.org,2002:timestamp":rr.timestamp};function sw(n,e,t){let s=Sd.get(e);if(s&&!n)return t&&!s.includes(xs.merge)?s.concat(xs.merge):s.slice();let r=s;if(!r)if(Array.isArray(n))r=[];else{let i=Array.from(Sd.keys()).filter(o=>o!=="yaml11").map(o=>JSON.stringify(o)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${i} or define customTags array`)}if(Array.isArray(n))for(let i of n)r=r.concat(i);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(xs.merge)),r.reduce((i,o)=>{let a=typeof o=="string"?kd[o]:o;if(!a){let l=JSON.stringify(o),c=Object.keys(kd).map(d=>JSON.stringify(d)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return i.includes(a)||i.push(a),i},[])}Oo.coreKnownTags=tw;Oo.getTags=sw});var Lo=T(Ed=>{"use strict";var Mo=U(),nw=Ft(),rw=Kt(),iw=Is(),ir=Cd(),ow=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,Do=class n{constructor({compat:e,customTags:t,merge:s,resolveKnownTags:r,schema:i,sortMapEntries:o,toStringDefaults:a}){this.compat=Array.isArray(e)?ir.getTags(e,"compat"):e?ir.getTags(null,e):null,this.name=typeof i=="string"&&i||"core",this.knownTags=r?ir.coreKnownTags:{},this.tags=ir.getTags(t,this.name,s),this.toStringOptions=a??null,Object.defineProperty(this,Mo.MAP,{value:nw.map}),Object.defineProperty(this,Mo.SCALAR,{value:iw.string}),Object.defineProperty(this,Mo.SEQ,{value:rw.seq}),this.sortMapEntries=typeof o=="function"?o:o===!0?ow:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Ed.Schema=Do});var xd=T(Nd=>{"use strict";var aw=U(),Po=bs(),Os=ys();function cw(n,e){let t=[],s=e.directives===!0;if(e.directives!==!1&&n.directives){let l=n.directives.toString(n);l?(t.push(l),s=!0):n.directives.docStart&&(s=!0)}s&&t.push("---");let r=Po.createStringifyContext(n,e),{commentString:i}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let l=i(n.commentBefore);t.unshift(Os.indentComment(l,""))}let o=!1,a=null;if(n.contents){if(aw.isNode(n.contents)){if(n.contents.spaceBefore&&s&&t.push(""),n.contents.commentBefore){let d=i(n.contents.commentBefore);t.push(Os.indentComment(d,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let l=a?void 0:()=>o=!0,c=Po.stringify(n.contents,r,()=>a=null,l);a&&(c+=Os.lineComment(c,"",i(a))),(c[0]==="|"||c[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${c}`:t.push(c)}else t.push(Po.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let l=i(n.comment);l.includes(`
59
+ `)?(t.push("..."),t.push(Os.indentComment(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=n.comment;l&&o&&(l=l.replace(/^\n+/,"")),l&&((!o||a)&&t[t.length-1]!==""&&t.push(""),t.push(Os.indentComment(i(l),"")))}return t.join(`
60
60
  `)+`
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
- `),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+=`:
61
+ `}Nd.stringifyDocument=cw});var Ms=T(Od=>{"use strict";var lw=ms(),Wt=An(),ke=U(),dw=nt(),uw=Ze(),hw=Lo(),fw=xd(),$o=_n(),pw=Ui(),mw=gs(),Ro=Bi(),Bo=class n{constructor(e,t,s){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,ke.NODE_TYPE,{value:ke.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:s===void 0&&t&&(s=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},s);this.options=i;let{version:o}=i;s?._directives?(this.directives=s._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new Ro.Directives({version:o}),this.setSchema(o,s),this.contents=e===void 0?null:this.createNode(e,r,s)}clone(){let e=Object.create(n.prototype,{[ke.NODE_TYPE]:{value:ke.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=ke.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Gt(this.contents)&&this.contents.add(e)}addIn(e,t){Gt(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let s=$o.anchorNames(this);e.anchor=!t||s.has(t)?$o.findNewAnchor(t||"a",s):t}return new lw.Alias(e.anchor)}createNode(e,t,s){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let y=S=>typeof S=="number"||S instanceof String||S instanceof Number,w=t.filter(y).map(String);w.length>0&&(t=t.concat(w)),r=t}else s===void 0&&t&&(s=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:o,flow:a,keepUndefined:l,onTagObj:c,tag:d}=s??{},{onAnchor:u,setAnchors:h,sourceObjects:p}=$o.createNodeAnchors(this,o||"a"),m={aliasDuplicateObjects:i??!0,keepUndefined:l??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p},f=mw.createNode(e,d,m);return a&&ke.isCollection(f)&&(f.flow=!0),h(),f}createPair(e,t,s={}){let r=this.createNode(e,null,s),i=this.createNode(t,null,s);return new dw.Pair(r,i)}delete(e){return Gt(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Wt.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Gt(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return ke.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Wt.isEmptyPath(e)?!t&&ke.isScalar(this.contents)?this.contents.value:this.contents:ke.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return ke.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return Wt.isEmptyPath(e)?this.contents!==void 0:ke.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Wt.collectionFromPath(this.schema,[e],t):Gt(this.contents)&&this.contents.set(e,t)}setIn(e,t){Wt.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=Wt.collectionFromPath(this.schema,Array.from(e),t):Gt(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let s;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Ro.Directives({version:"1.1"}),s={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Ro.Directives({version:e}),s={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,s=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(s)this.schema=new hw.Schema(Object.assign(s,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:s,maxAliasCount:r,onAnchor:i,reviver:o}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:s===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=uw.toJS(this.contents,t??"",a);if(typeof i=="function")for(let{count:c,res:d}of a.anchors.values())i(d,c);return typeof o=="function"?pw.applyReviver(o,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return fw.stringifyDocument(this,e)}};function Gt(n){if(ke.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}Od.Document=Bo});var Ps=T(Ls=>{"use strict";var Ds=class extends Error{constructor(e,t,s,r){super(),this.name=e,this.code=s,this.message=r,this.pos=t}},Uo=class extends Ds{constructor(e,t,s){super("YAMLParseError",e,t,s)}},jo=class extends Ds{constructor(e,t,s){super("YAMLWarning",e,t,s)}},gw=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:s,col:r}=t.linePos[0];t.message+=` at line ${s}, column ${r}`;let i=r-1,o=n.substring(e.lineStarts[s-1],e.lineStarts[s]).replace(/[\n\r]+$/,"");if(i>=60&&o.length>80){let a=Math.min(i-39,o.length-79);o="\u2026"+o.substring(a),i-=a-1}if(o.length>80&&(o=o.substring(0,79)+"\u2026"),s>1&&/^ *$/.test(o.substring(0,i))){let a=n.substring(e.lineStarts[s-2],e.lineStarts[s-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
62
+ `),o=a+o}if(/[^ ]/.test(o)){let a=1,l=t.linePos[1];l?.line===s&&l.col>r&&(a=Math.max(1,Math.min(l.col-r,80-i)));let c=" ".repeat(i)+"^".repeat(a);t.message+=`:
63
63
 
64
64
  ${o}
65
65
  ${c}
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
- `+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 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
- `.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
- `;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=`
66
+ `}};Ls.YAMLError=Ds;Ls.YAMLParseError=Uo;Ls.YAMLWarning=jo;Ls.prettifyError=gw});var $s=T(Md=>{"use strict";function yw(n,{flow:e,indicator:t,next:s,offset:r,onError:i,parentIndent:o,startOnNewline:a}){let l=!1,c=a,d=a,u="",h="",p=!1,m=!1,f=null,y=null,w=null,S=null,_=null,v=null,I=null;for(let A of n)switch(m&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&i(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m=!1),f&&(c&&A.type!=="comment"&&A.type!=="newline"&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),f=null),A.type){case"space":!e&&(t!=="doc-start"||s?.type!=="flow-collection")&&A.source.includes(" ")&&(f=A),d=!0;break;case"comment":{d||i(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let E=A.source.substring(1)||" ";u?u+=h+E:u=E,h="",c=!1;break}case"newline":c?u?u+=A.source:(!v||t!=="seq-item-ind")&&(l=!0):h+=A.source,c=!0,p=!0,(y||w)&&(S=A),d=!0;break;case"anchor":y&&i(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&i(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),y=A,I??(I=A.offset),c=!1,d=!1,m=!0;break;case"tag":{w&&i(A,"MULTIPLE_TAGS","A node can have at most one tag"),w=A,I??(I=A.offset),c=!1,d=!1,m=!0;break}case t:(y||w)&&i(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),v&&i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),v=A,c=t==="seq-item-ind"||t==="explicit-key-ind",d=!1;break;case"comma":if(e){_&&i(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),_=A,c=!1,d=!1;break}default:i(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),c=!1,d=!1}let N=n[n.length-1],D=N?N.offset+N.source.length:r;return m&&s&&s.type!=="space"&&s.type!=="newline"&&s.type!=="comma"&&(s.type!=="scalar"||s.source!=="")&&i(s.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f&&(c&&f.indent<=o||s?.type==="block-map"||s?.type==="block-seq")&&i(f,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:_,found:v,spaceBefore:l,comment:u,hasNewline:p,anchor:y,tag:w,newlineAfterProp:S,end:D,start:I??D}}Md.resolveProps=yw});var or=T(Dd=>{"use strict";function qo(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
67
+ `))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(qo(e.key)||qo(e.value))return!0}return!1;default:return!0}}Dd.containsNewline=qo});var Fo=T(Ld=>{"use strict";var ww=or();function Sw(n,e,t){if(e?.type==="flow-collection"){let s=e.end[0];s.indent===n&&(s.source==="]"||s.source==="}")&&ww.containsNewline(e)&&t(s,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}Ld.flowIndentCheck=Sw});var Ko=T($d=>{"use strict";var Pd=U();function kw(n,e,t){let{uniqueKeys:s}=n.options;if(s===!1)return!1;let r=typeof s=="function"?s:(i,o)=>i===o||Pd.isScalar(i)&&Pd.isScalar(o)&&i.value===o.value;return e.some(i=>r(i.key,t))}$d.mapIncludes=kw});var Fd=T(qd=>{"use strict";var Rd=nt(),bw=it(),Bd=$s(),_w=or(),Ud=Fo(),vw=Ko(),jd="All mapping items must start at the same column";function Tw({composeNode:n,composeEmptyNode:e},t,s,r,i){let o=i?.nodeClass??bw.YAMLMap,a=new o(t.schema);t.atRoot&&(t.atRoot=!1);let l=s.offset,c=null;for(let d of s.items){let{start:u,key:h,sep:p,value:m}=d,f=Bd.resolveProps(u,{indicator:"explicit-key-ind",next:h??p?.[0],offset:l,onError:r,parentIndent:s.indent,startOnNewline:!0}),y=!f.found;if(y){if(h&&(h.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in h&&h.indent!==s.indent&&r(l,"BAD_INDENT",jd)),!f.anchor&&!f.tag&&!p){c=f.end,f.comment&&(a.comment?a.comment+=`
68
+ `+f.comment:a.comment=f.comment);continue}(f.newlineAfterProp||_w.containsNewline(h))&&r(h??u[u.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else f.found?.indent!==s.indent&&r(l,"BAD_INDENT",jd);t.atKey=!0;let w=f.end,S=h?n(t,h,f,r):e(t,w,u,null,f,r);t.schema.compat&&Ud.flowIndentCheck(s.indent,h,r),t.atKey=!1,vw.mapIncludes(t,a.items,S)&&r(w,"DUPLICATE_KEY","Map keys must be unique");let _=Bd.resolveProps(p??[],{indicator:"map-value-ind",next:m,offset:S.range[2],onError:r,parentIndent:s.indent,startOnNewline:!h||h.type==="block-scalar"});if(l=_.end,_.found){y&&(m?.type==="block-map"&&!_.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&f.start<_.found.offset-1024&&r(S.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let v=m?n(t,m,_,r):e(t,l,p,null,_,r);t.schema.compat&&Ud.flowIndentCheck(s.indent,m,r),l=v.range[2];let I=new Rd.Pair(S,v);t.options.keepSourceTokens&&(I.srcToken=d),a.items.push(I)}else{y&&r(S.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),_.comment&&(S.comment?S.comment+=`
69
+ `+_.comment:S.comment=_.comment);let v=new Rd.Pair(S);t.options.keepSourceTokens&&(v.srcToken=d),a.items.push(v)}}return c&&c<l&&r(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[s.offset,l,c??l],a}qd.resolveBlockMap=Tw});var Hd=T(Kd=>{"use strict";var Iw=ot(),Aw=$s(),Cw=Fo();function Ew({composeNode:n,composeEmptyNode:e},t,s,r,i){let o=i?.nodeClass??Iw.YAMLSeq,a=new o(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=s.offset,c=null;for(let{start:d,value:u}of s.items){let h=Aw.resolveProps(d,{indicator:"seq-item-ind",next:u,offset:l,onError:r,parentIndent:s.indent,startOnNewline:!0});if(!h.found)if(h.anchor||h.tag||u)u?.type==="block-seq"?r(h.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{c=h.end,h.comment&&(a.comment=h.comment);continue}let p=u?n(t,u,h,r):e(t,h.end,d,null,h,r);t.schema.compat&&Cw.flowIndentCheck(s.indent,u,r),l=p.range[2],a.items.push(p)}return a.range=[s.offset,l,c??l],a}Kd.resolveBlockSeq=Ew});var Vt=T(Wd=>{"use strict";function Nw(n,e,t,s){let r="";if(n){let i=!1,o="";for(let a of n){let{source:l,type:c}=a;switch(c){case"space":i=!0;break;case"comment":{t&&!i&&s(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let d=l.substring(1)||" ";r?r+=o+d:r=d,o="";break}case"newline":r&&(o+=l),i=!0;break;default:s(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:r,offset:e}}Wd.resolveEnd=Nw});var Jd=T(Yd=>{"use strict";var xw=U(),Ow=nt(),Gd=it(),Mw=ot(),Dw=Vt(),Vd=$s(),Lw=or(),Pw=Ko(),Ho="Block collections are not allowed within flow collections",Wo=n=>n&&(n.type==="block-map"||n.type==="block-seq");function $w({composeNode:n,composeEmptyNode:e},t,s,r,i){let o=s.start.source==="{",a=o?"flow map":"flow sequence",l=i?.nodeClass??(o?Gd.YAMLMap:Mw.YAMLSeq),c=new l(t.schema);c.flow=!0;let d=t.atRoot;d&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let u=s.offset+s.start.source.length;for(let y=0;y<s.items.length;++y){let w=s.items[y],{start:S,key:_,sep:v,value:I}=w,N=Vd.resolveProps(S,{flow:a,indicator:"explicit-key-ind",next:_??v?.[0],offset:u,onError:r,parentIndent:s.indent,startOnNewline:!1});if(!N.found){if(!N.anchor&&!N.tag&&!v&&!I){y===0&&N.comma?r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):y<s.items.length-1&&r(N.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),N.comment&&(c.comment?c.comment+=`
70
+ `+N.comment:c.comment=N.comment),u=N.end;continue}!o&&t.options.strict&&Lw.containsNewline(_)&&r(_,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(y===0)N.comma&&r(N.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(N.comma||r(N.start,"MISSING_CHAR",`Missing , between ${a} items`),N.comment){let D="";e:for(let A of S)switch(A.type){case"comma":case"space":break;case"comment":D=A.source.substring(1);break e;default:break e}if(D){let A=c.items[c.items.length-1];xw.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
71
+ `+D:A.comment=D,N.comment=N.comment.substring(D.length+1)}}if(!o&&!v&&!N.found){let D=I?n(t,I,N,r):e(t,N.end,v,null,N,r);c.items.push(D),u=D.range[2],Wo(I)&&r(D.range,"BLOCK_IN_FLOW",Ho)}else{t.atKey=!0;let D=N.end,A=_?n(t,_,N,r):e(t,D,S,null,N,r);Wo(_)&&r(A.range,"BLOCK_IN_FLOW",Ho),t.atKey=!1;let E=Vd.resolveProps(v??[],{flow:a,indicator:"map-value-ind",next:I,offset:A.range[2],onError:r,parentIndent:s.indent,startOnNewline:!1});if(E.found){if(!o&&!N.found&&t.options.strict){if(v)for(let $ of v){if($===E.found)break;if($.type==="newline"){r($,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}N.start<E.found.offset-1024&&r(E.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else I&&("source"in I&&I.source?.[0]===":"?r(I,"MISSING_CHAR",`Missing space after : in ${a}`):r(E.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let G=I?n(t,I,E,r):E.found?e(t,E.end,v,null,E,r):null;G?Wo(I)&&r(G.range,"BLOCK_IN_FLOW",Ho):E.comment&&(A.comment?A.comment+=`
72
+ `+E.comment:A.comment=E.comment);let W=new Ow.Pair(A,G);if(t.options.keepSourceTokens&&(W.srcToken=w),o){let $=c;Pw.mapIncludes(t,$.items,A)&&r(D,"DUPLICATE_KEY","Map keys must be unique"),$.items.push(W)}else{let $=new Gd.YAMLMap(t.schema);$.flow=!0,$.items.push(W);let le=(G??A).range;$.range=[A.range[0],le[1],le[2]],c.items.push($)}u=G?G.range[2]:E.end}}let h=o?"}":"]",[p,...m]=s.end,f=u;if(p?.source===h)f=p.offset+p.source.length;else{let y=a[0].toUpperCase()+a.substring(1),w=d?`${y} must end with a ${h}`:`${y} in block collection must be sufficiently indented and end with a ${h}`;r(u,d?"MISSING_CHAR":"BAD_INDENT",w),p&&p.source.length!==1&&m.unshift(p)}if(m.length>0){let y=Dw.resolveEnd(m,f,t.options.strict,r);y.comment&&(c.comment?c.comment+=`
73
+ `+y.comment:c.comment=y.comment),c.range=[s.offset,f,y.offset]}else c.range=[s.offset,f,f];return c}Yd.resolveFlowCollection=$w});var Qd=T(zd=>{"use strict";var Rw=U(),Bw=Z(),Uw=it(),jw=ot(),qw=Fd(),Fw=Hd(),Kw=Jd();function Go(n,e,t,s,r,i){let o=t.type==="block-map"?qw.resolveBlockMap(n,e,t,s,i):t.type==="block-seq"?Fw.resolveBlockSeq(n,e,t,s,i):Kw.resolveFlowCollection(n,e,t,s,i),a=o.constructor;return r==="!"||r===a.tagName?(o.tag=a.tagName,o):(r&&(o.tag=r),o)}function Hw(n,e,t,s,r){let i=s.tag,o=i?e.directives.tagName(i.source,h=>r(i,"TAG_RESOLVE_FAILED",h)):null;if(t.type==="block-seq"){let{anchor:h,newlineAfterProp:p}=s,m=h&&i?h.offset>i.offset?h:i:h??i;m&&(!p||p.offset<m.offset)&&r(m,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!i||!o||o==="!"||o===Uw.YAMLMap.tagName&&a==="map"||o===jw.YAMLSeq.tagName&&a==="seq")return Go(n,e,t,r,o);let l=e.schema.tags.find(h=>h.tag===o&&h.collection===a);if(!l){let h=e.schema.knownTags[o];if(h?.collection===a)e.schema.tags.push(Object.assign({},h,{default:!1})),l=h;else return h?r(i,"BAD_COLLECTION_TYPE",`${h.tag} used for ${a} collection, but expects ${h.collection??"scalar"}`,!0):r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${o}`,!0),Go(n,e,t,r,o)}let c=Go(n,e,t,r,o,l),d=l.resolve?.(c,h=>r(i,"TAG_RESOLVE_FAILED",h),e.options)??c,u=Rw.isNode(d)?d:new Bw.Scalar(d);return u.range=c.range,u.tag=o,l?.format&&(u.format=l.format),u}zd.composeCollection=Hw});var Yo=T(Xd=>{"use strict";var Vo=Z();function Ww(n,e,t){let s=e.offset,r=Gw(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[s,s,s]};let i=r.mode===">"?Vo.Scalar.BLOCK_FOLDED:Vo.Scalar.BLOCK_LITERAL,o=e.source?Vw(e.source):[],a=o.length;for(let f=o.length-1;f>=0;--f){let y=o[f][1];if(y===""||y==="\r")a=f;else break}if(a===0){let f=r.chomp==="+"&&o.length>0?`
74
+ `.repeat(Math.max(1,o.length-1)):"",y=s+r.length;return e.source&&(y+=e.source.length),{value:f,type:i,comment:r.comment,range:[s,y,y]}}let l=e.indent+r.indent,c=e.offset+r.length,d=0;for(let f=0;f<a;++f){let[y,w]=o[f];if(w===""||w==="\r")r.indent===0&&y.length>l&&(l=y.length);else{y.length<l&&t(c+y.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=y.length),d=f,l===0&&!n.atRoot&&t(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=y.length+w.length+1}for(let f=o.length-1;f>=a;--f)o[f][0].length>l&&(a=f+1);let u="",h="",p=!1;for(let f=0;f<d;++f)u+=o[f][0].slice(l)+`
75
+ `;for(let f=d;f<a;++f){let[y,w]=o[f];c+=y.length+w.length+1;let S=w[w.length-1]==="\r";if(S&&(w=w.slice(0,-1)),w&&y.length<l){let v=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(c-w.length-(S?2:1),"BAD_INDENT",v),y=""}i===Vo.Scalar.BLOCK_LITERAL?(u+=h+y.slice(l)+w,h=`
76
76
  `):y.length>l||w[0]===" "?(h===" "?h=`
77
- `:!m&&h===`
77
+ `:!p&&h===`
78
78
  `&&(h=`
79
79
 
80
80
  `),u+=h+y.slice(l)+w,h=`
81
- `,m=!0):w===""?h===`
81
+ `,p=!0):w===""?h===`
82
82
  `?u+=`
83
83
  `:h=`
84
- `:(u+=h+w,h=" ",m=!1)}switch(n.chomp){case"-":break;case"+":for(let f=a;f<o.length;++f)u+=`
84
+ `:(u+=h+w,h=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let f=a;f<o.length;++f)u+=`
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 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?
88
+ `}let m=s+r.length+e.source.length;return{value:u,type:i,comment:r.comment,range:[s,m,m]}}function Gw({offset:n,props:e},t,s){if(e[0].type!=="block-scalar-header")return s(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],i=r[0],o=0,a="",l=-1;for(let h=1;h<r.length;++h){let p=r[h];if(!a&&(p==="-"||p==="+"))a=p;else{let m=Number(p);!o&&m?o=m:l===-1&&(l=n+h)}}l!==-1&&s(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let c=!1,d="",u=r.length;for(let h=1;h<e.length;++h){let p=e[h];switch(p.type){case"space":c=!0;case"newline":u+=p.source.length;break;case"comment":t&&!c&&s(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),u+=p.source.length,d=p.source.substring(1);break;case"error":s(p,"UNEXPECTED_TOKEN",p.message),u+=p.source.length;break;default:{let m=`Unexpected token in block scalar header: ${p.type}`;s(p,"UNEXPECTED_TOKEN",m);let f=p.source;f&&typeof f=="string"&&(u+=f.length)}}}return{mode:i,indent:o,chomp:a,comment:d,length:u}}function Vw(n){let e=n.split(/\n( *)/),t=e[0],s=t.match(/^( *)/),i=[s?.[1]?[s[1],t.slice(s[1].length)]:["",t]];for(let o=1;o<e.length;o+=2)i.push([e[o],e[o+1]]);return i}Xd.resolveBlockScalar=Ww});var zo=T(eu=>{"use strict";var Jo=Z(),Yw=Vt();function Jw(n,e,t){let{offset:s,type:r,source:i,end:o}=n,a,l,c=(h,p,m)=>t(s+h,p,m);switch(r){case"scalar":a=Jo.Scalar.PLAIN,l=zw(i,c);break;case"single-quoted-scalar":a=Jo.Scalar.QUOTE_SINGLE,l=Qw(i,c);break;case"double-quoted-scalar":a=Jo.Scalar.QUOTE_DOUBLE,l=Xw(i,c);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[s,s+i.length,s+i.length]}}let d=s+i.length,u=Yw.resolveEnd(o,d,e,t);return{value:l,type:a,comment:u.comment,range:[s,d,u.offset]}}function zw(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),Zd(n)}function Qw(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),Zd(n.slice(1,-1)).replace(/''/g,"'")}function Zd(n){let e,t;try{e=new RegExp(`(.*?)(?<![ ])[ ]*\r?
89
89
  `,"sy"),t=new RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
90
- `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(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
- `?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 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
- `))if(n===`
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
- `)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+=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
- `&&!(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 Vw(r,e){let t="",s=r[e+1];for(;(s===" "||s===" "||s===`
99
- `||s==="\r")&&!(s==="\r"&&r[e+2]!==`
90
+ `,"sy")}catch{e=/(.*?)[ \t]*\r?\n/sy,t=/[ \t]*(.*?)[ \t]*\r?\n/sy}let s=e.exec(n);if(!s)return n;let r=s[1],i=" ",o=e.lastIndex;for(t.lastIndex=o;s=t.exec(n);)s[1]===""?i===`
91
+ `?r+=i:i=`
92
+ `:(r+=i+s[1],i=" "),o=t.lastIndex;let a=/[ \t]*(.*)/sy;return a.lastIndex=o,s=a.exec(n),r+i+(s?.[1]??"")}function Xw(n,e){let t="";for(let s=1;s<n.length-1;++s){let r=n[s];if(!(r==="\r"&&n[s+1]===`
93
+ `))if(r===`
94
+ `){let{fold:i,offset:o}=Zw(n,s);t+=i,s=o}else if(r==="\\"){let i=n[++s],o=eS[i];if(o)t+=o;else if(i===`
95
+ `)for(i=n[s+1];i===" "||i===" ";)i=n[++s+1];else if(i==="\r"&&n[s+1]===`
96
+ `)for(i=n[++s+1];i===" "||i===" ";)i=n[++s+1];else if(i==="x"||i==="u"||i==="U"){let a={x:2,u:4,U:8}[i];t+=tS(n,s+1,a,e),s+=a}else{let a=n.substr(s-1,2);e(s-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(r===" "||r===" "){let i=s,o=n[s+1];for(;o===" "||o===" ";)o=n[++s+1];o!==`
97
+ `&&!(o==="\r"&&n[s+2]===`
98
+ `)&&(t+=s>i?n.slice(i,s+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function Zw(n,e){let t="",s=n[e+1];for(;(s===" "||s===" "||s===`
99
+ `||s==="\r")&&!(s==="\r"&&n[e+2]!==`
100
100
  `);)s===`
101
101
  `&&(t+=`
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?`
102
+ `),e+=1,s=n[e+1];return t||(t=" "),{fold:t,offset:e}}var eS={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
103
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function tS(n,e,t,s){let r=n.substr(e,t),o=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;if(isNaN(o)){let a=n.substr(e-2,t+2);return s(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}return String.fromCodePoint(o)}eu.resolveFlowScalar=Jw});var nu=T(su=>{"use strict";var kt=U(),tu=Z(),sS=Yo(),nS=zo();function rS(n,e,t,s){let{value:r,type:i,comment:o,range:a}=e.type==="block-scalar"?sS.resolveBlockScalar(n,e,s):nS.resolveFlowScalar(e,n.options.strict,s),l=t?n.directives.tagName(t.source,u=>s(t,"TAG_RESOLVE_FAILED",u)):null,c;n.options.stringKeys&&n.atKey?c=n.schema[kt.SCALAR]:l?c=iS(n.schema,r,l,t,s):e.type==="scalar"?c=oS(n,r,e,s):c=n.schema[kt.SCALAR];let d;try{let u=c.resolve(r,h=>s(t??e,"TAG_RESOLVE_FAILED",h),n.options);d=kt.isScalar(u)?u:new tu.Scalar(u)}catch(u){let h=u instanceof Error?u.message:String(u);s(t??e,"TAG_RESOLVE_FAILED",h),d=new tu.Scalar(r)}return d.range=a,d.source=r,i&&(d.type=i),l&&(d.tag=l),c.format&&(d.format=c.format),o&&(d.comment=o),d}function iS(n,e,t,s,r){if(t==="!")return n[kt.SCALAR];let i=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)i.push(a);else return a;for(let a of i)if(a.test?.test(e))return a;let o=n.knownTags[t];return o&&!o.collection?(n.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(r(s,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[kt.SCALAR])}function oS({atKey:n,directives:e,schema:t},s,r,i){let o=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(s))||t[kt.SCALAR];if(t.compat){let a=t.compat.find(l=>l.default&&l.test?.test(s))??t[kt.SCALAR];if(o.tag!==a.tag){let l=e.tagString(o.tag),c=e.tagString(a.tag),d=`Value may be parsed as either ${l} or ${c}`;i(r,"TAG_RESOLVE_FAILED",d,!0)}}return o}su.composeScalar=rS});var iu=T(ru=>{"use strict";function aS(n,e,t){if(e){t??(t=e.length);for(let s=t-1;s>=0;--s){let r=e[s];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++s];r?.type==="space";)n+=r.source.length,r=e[++s];break}}return n}ru.emptyScalarPosition=aS});var cu=T(Xo=>{"use strict";var cS=ms(),lS=U(),dS=Qd(),ou=nu(),uS=Vt(),hS=iu(),fS={composeNode:au,composeEmptyNode:Qo};function au(n,e,t,s){let r=n.atKey,{spaceBefore:i,comment:o,anchor:a,tag:l}=t,c,d=!0;switch(e.type){case"alias":c=pS(n,e,s),(a||l)&&s(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=ou.composeScalar(n,e,l,s),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=dS.composeCollection(fS,n,e,t,s),a&&(c.anchor=a.source.substring(1))}catch(u){let h=u instanceof Error?u.message:String(u);s(e,"RESOURCE_EXHAUSTION",h)}break;default:{let u=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;s(e,"UNEXPECTED_TOKEN",u),d=!1}}return c??(c=Qo(n,e.offset,void 0,null,t,s)),a&&c.anchor===""&&s(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!lS.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&s(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),i&&(c.spaceBefore=!0),o&&(e.type==="scalar"&&e.source===""?c.comment=o:c.commentBefore=o),n.options.keepSourceTokens&&d&&(c.srcToken=e),c}function Qo(n,e,t,s,{spaceBefore:r,comment:i,anchor:o,tag:a,end:l},c){let d={type:"scalar",offset:hS.emptyScalarPosition(e,t,s),indent:-1,source:""},u=ou.composeScalar(n,d,a,c);return o&&(u.anchor=o.source.substring(1),u.anchor===""&&c(o,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(u.spaceBefore=!0),i&&(u.comment=i,u.range[2]=l),u}function pS({options:n},{offset:e,source:t,end:s},r){let i=new cS.Alias(t.substring(1));i.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),i.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let o=e+t.length,a=uS.resolveEnd(s,o,n.strict,r);return i.range=[e,o,a.offset],a.comment&&(i.comment=a.comment),i}Xo.composeEmptyNode=Qo;Xo.composeNode=au});var uu=T(du=>{"use strict";var mS=Ms(),lu=cu(),gS=Vt(),yS=$s();function wS(n,e,{offset:t,start:s,value:r,end:i},o){let a=Object.assign({_directives:e},n),l=new mS.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},d=yS.resolveProps(s,{indicator:"doc-start",next:r??i?.[0],offset:t,onError:o,parentIndent:0,startOnNewline:!0});d.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!d.hasNewline&&o(d.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?lu.composeNode(c,r,d,o):lu.composeEmptyNode(c,d.end,s,null,d,o);let u=l.contents.range[2],h=gS.resolveEnd(i,u,!1,o);return h.comment&&(l.comment=h.comment),l.range=[t,u,h.offset],l}du.composeDoc=wS});var ea=T(pu=>{"use strict";var SS=H("process"),kS=Bi(),bS=Ms(),Rs=Ps(),hu=U(),_S=uu(),vS=Vt();function Bs(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function fu(n){let e="",t=!1,s=!1;for(let r=0;r<n.length;++r){let i=n[r];switch(i[0]){case"#":e+=(e===""?"":s?`
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 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
- ${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}
106
+ `)+(i.substring(1)||" "),t=!0,s=!1;break;case"%":n[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(s=!0),t=!1}}return{comment:e,afterEmptyLine:s}}var Zo=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,s,r,i)=>{let o=Bs(t);i?this.warnings.push(new Rs.YAMLWarning(o,s,r)):this.errors.push(new Rs.YAMLParseError(o,s,r))},this.directives=new kS.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:s,afterEmptyLine:r}=fu(this.prelude);if(s){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}
107
+ ${s}`:s;else if(r||e.directives.docStart||!i)e.commentBefore=s;else if(hu.isCollection(i)&&!i.flow&&i.items.length>0){let o=i.items[0];hu.isPair(o)&&(o=o.key);let a=o.commentBefore;o.commentBefore=a?`${s}
108
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(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:`
109
+ ${o}`:s}}t?(Array.prototype.push.apply(e.errors,this.errors),Array.prototype.push.apply(e.warnings,this.warnings)):(e.errors=this.errors,e.warnings=this.warnings),this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:fu(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,s=-1){for(let r of e)yield*this.next(r);yield*this.end(t,s)}*next(e){switch(SS.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,s,r)=>{let i=Bs(e);i[0]+=t,this.onError(i,"BAD_DIRECTIVE",s,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=_S.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,s=new Rs.YAMLParseError(Bs(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(s):this.doc.errors.push(s);break}case"doc-end":{if(!this.doc){let s="Unexpected doc-end without preceding document";this.errors.push(new Rs.YAMLParseError(Bs(e),"UNEXPECTED_TOKEN",s));break}this.doc.directives.docEnd=!0;let t=vS.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let s=this.doc.comment;this.doc.comment=s?`${s}
110
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Rs.YAMLParseError(Bs(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let s=Object.assign({_directives:this.directives},this.options),r=new bS.Document(void 0,s);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};pu.Composer=Zo});var yu=T(ar=>{"use strict";var TS=Yo(),IS=zo(),AS=Ps(),mu=ks();function CS(n,e=!0,t){if(n){let s=(r,i,o)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,i,o);else throw new AS.YAMLParseError([a,a+1],i,o)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return IS.resolveFlowScalar(n,e,s);case"block-scalar":return TS.resolveBlockScalar({options:{strict:e}},n,s)}}return null}function ES(n,e){let{implicitKey:t=!1,indent:s,inFlow:r=!1,offset:i=-1,type:o="PLAIN"}=e,a=mu.stringifyString({type:o,value:n},{implicitKey:t,indent:s>0?" ".repeat(s):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:s,source:`
111
111
  `}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
112
112
  `),d=a.substring(0,c),u=a.substring(c+1)+`
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 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
- `),s=e.substring(0,t),n=e.substring(t+1)+`
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
- `});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=_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`
113
+ `,h=[{type:"block-scalar-header",offset:i,indent:s,source:d}];return gu(h,l)||h.push({type:"newline",offset:-1,indent:s,source:`
114
+ `}),{type:"block-scalar",offset:i,indent:s,props:h,source:u}}case'"':return{type:"double-quoted-scalar",offset:i,indent:s,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:i,indent:s,source:a,end:l};default:return{type:"scalar",offset:i,indent:s,source:a,end:l}}}function NS(n,e,t={}){let{afterKey:s=!1,implicitKey:r=!1,inFlow:i=!1,type:o}=t,a="indent"in n?n.indent:null;if(s&&typeof a=="number"&&(a+=2),!o)switch(n.type){case"single-quoted-scalar":o="QUOTE_SINGLE";break;case"double-quoted-scalar":o="QUOTE_DOUBLE";break;case"block-scalar":{let c=n.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:o="PLAIN"}let l=mu.stringifyString({type:o,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:i,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":xS(n,l);break;case'"':ta(n,l,"double-quoted-scalar");break;case"'":ta(n,l,"single-quoted-scalar");break;default:ta(n,l,"scalar")}}function xS(n,e){let t=e.indexOf(`
115
+ `),s=e.substring(0,t),r=e.substring(t+1)+`
116
+ `;if(n.type==="block-scalar"){let i=n.props[0];if(i.type!=="block-scalar-header")throw new Error("Invalid block scalar header");i.source=s,n.source=r}else{let{offset:i}=n,o="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:i,indent:o,source:s}];gu(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:o,source:`
117
+ `});for(let l of Object.keys(n))l!=="type"&&l!=="offset"&&delete n[l];Object.assign(n,{type:"block-scalar",indent:o,props:a,source:r})}}function gu(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function ta(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let s=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let i of s)i.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:s});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
118
+ `};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let s="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(i=>i.type==="space"||i.type==="comment"||i.type==="newline"):[];for(let i of Object.keys(n))i!=="type"&&i!=="offset"&&delete n[i];Object.assign(n,{type:t,indent:s,source:e,end:r})}}}ar.createScalarToken=ES;ar.resolveAsScalar=CS;ar.setScalarValue=NS});var Su=T(wu=>{"use strict";var OS=n=>"type"in n?lr(n):cr(n);function lr(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=lr(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=cr(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=cr(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=cr(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function cr({start:n,key:e,sep:t,value:s}){let r="";for(let i of n)r+=i.source;if(e&&(r+=lr(e)),t)for(let i of t)r+=i.source;return s&&(r+=lr(s)),r}wu.stringify=OS});var vu=T(_u=>{"use strict";var sa=Symbol("break visit"),MS=Symbol("skip children"),ku=Symbol("remove item");function bt(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),bu(Object.freeze([]),n,e)}bt.BREAK=sa;bt.SKIP=MS;bt.REMOVE=ku;bt.itemAtPath=(n,e)=>{let t=n;for(let[s,r]of e){let i=t?.[s];if(i&&"items"in i)t=i.items[r];else return}return t};bt.parentCollection=(n,e)=>{let t=bt.itemAtPath(n,e.slice(0,-1)),s=e[e.length-1][0],r=t?.[s];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function bu(n,e,t){let s=t(e,n);if(typeof s=="symbol")return s;for(let r of["key","value"]){let i=e[r];if(i&&"items"in i){for(let o=0;o<i.items.length;++o){let a=bu(Object.freeze(n.concat([[r,o]])),i.items[o],t);if(typeof a=="number")o=a-1;else{if(a===sa)return sa;a===ku&&(i.items.splice(o,1),o-=1)}}typeof s=="function"&&r==="key"&&(s=s(e,n))}}return typeof s=="function"?s(e,n):s}_u.visit=bt});var dr=T(fe=>{"use strict";var na=yu(),DS=Su(),LS=vu(),ra="\uFEFF",ia="",oa="",aa="",PS=n=>!!n&&"items"in n,$S=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function RS(n){switch(n){case ra:return"<BOM>";case ia:return"<DOC>";case oa:return"<FLOW_END>";case aa:return"<SCALAR>";default:return JSON.stringify(n)}}function BS(n){switch(n){case ra:return"byte-order-mark";case ia:return"doc-mode";case oa:return"flow-error-end";case aa:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
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=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===`
120
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}fe.createScalarToken=na.createScalarToken;fe.resolveAsScalar=na.resolveAsScalar;fe.setScalarValue=na.setScalarValue;fe.stringify=DS.stringify;fe.visit=LS.visit;fe.BOM=ra;fe.DOCUMENT=ia;fe.FLOW_END=oa;fe.SCALAR=aa;fe.isCollection=PS;fe.isScalar=$S;fe.prettyToken=RS;fe.tokenType=BS});var da=T(Iu=>{"use strict";var Us=dr();function Ee(n){switch(n){case void 0:case" ":case`
121
+ `:case"\r":case" ":return!0;default:return!1}}var Tu=new Set("0123456789ABCDEFabcdef"),US=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),ur=new Set(",[]{}"),jS=new Set(` ,[]{}
122
+ \r `),ca=n=>!n||jS.has(n),la=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let s=this.next??"stream";for(;s&&(t||this.hasChars(1));)s=yield*this.parseNext(s)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
123
123
  `?!0:t==="\r"?this.buffer[e+1]===`
124
- `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let s=0;for(;t===" ";)t=this.buffer[++s+e];if(t==="\r"){let n=this.buffer[s+e+1];if(n===`
125
- `||!n&&!this.atEnd)return e+s+1}return t===`
124
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let s=0;for(;t===" ";)t=this.buffer[++s+e];if(t==="\r"){let r=this.buffer[s+e+1];if(r===`
125
+ `||!r&&!this.atEnd)return e+s+1}return t===`
126
126
  `||s>=this.indentNext||!t&&!this.atEnd?e+s:-1}if(t==="-"||t==="."){let s=this.buffer.substr(e,3);if((s==="---"||s==="...")&&Ee(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
127
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Us.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,s=e.indexOf("#");for(;s!==-1;){let i=e[s-1];if(i===" "||i===" "){t=s-1;break}else s=e.indexOf("#",s+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let n=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-n),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Us.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Ee(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ee(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ee(t)){let s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(oa),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,s=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=s=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let n=this.getLine();if(n===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&n[0]!=="#"||s===0&&(n.startsWith("---")||n.startsWith("..."))&&Ee(n[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(n[0]==="]"||n[0]==="}")))return this.flowLevel=0,yield Us.FLOW_END,yield*this.parseLineStart();let i=0;for(;n[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),n[i]){case void 0:return"flow";case"#":return yield*this.pushCount(n.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(oa),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ee(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let s=this.buffer.substring(0,t),n=s.indexOf(`
128
- `,this.pos);if(n!==-1){for(;n!==-1;){let i=this.continueScalar(n+1);if(i===-1)break;n=s.indexOf(`
129
- `,i)}n!==-1&&(t=n-(s[n-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ee(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,s;e:for(let i=this.pos;s=this.buffer[i];++i)switch(s){case" ":t+=1;break;case`
127
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Us.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,s=e.indexOf("#");for(;s!==-1;){let i=e[s-1];if(i===" "||i===" "){t=s-1;break}else s=e.indexOf("#",s+1)}for(;;){let i=e[t-1];if(i===" "||i===" ")t-=1;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Us.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&Ee(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Ee(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&Ee(t)){let s=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=s,yield*this.parseBlockStart()}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(ca),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,s=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=s=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((s!==-1&&s<this.indentNext&&r[0]!=="#"||s===0&&(r.startsWith("---")||r.startsWith("..."))&&Ee(r[3]))&&!(s===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Us.FLOW_END,yield*this.parseLineStart();let i=0;for(;r[i]===",";)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-i),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(ca),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let o=this.charAt(1);if(this.flowKey||Ee(o)||o===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let i=0;for(;this.buffer[t-1-i]==="\\";)i+=1;if(i%2===0)break;t=this.buffer.indexOf('"',t+1)}let s=this.buffer.substring(0,t),r=s.indexOf(`
128
+ `,this.pos);if(r!==-1){for(;r!==-1;){let i=this.continueScalar(r+1);if(i===-1)break;r=s.indexOf(`
129
+ `,i)}r!==-1&&(t=r-(s[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>Ee(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,s;e:for(let i=this.pos;s=this.buffer[i];++i)switch(s){case" ":t+=1;break;case`
130
130
  `:e=i,t=0;break;case"\r":{let o=this.buffer[i+1];if(!o&&!this.atEnd)return this.setNext("block-scalar");if(o===`
131
131
  `)break}default:break e}if(!s&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let i=this.continueScalar(e+1);if(i===-1)break;e=this.buffer.indexOf(`
132
- `,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let n=e+1;for(s=this.buffer[n];s===" ";)s=this.buffer[++n];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
133
- `;)s=this.buffer[++n];e=n-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
134
- `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Us.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,s=this.pos-1,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
- `?(s+=1,n=`
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(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===`
132
+ `,i)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(s=this.buffer[r];s===" ";)s=this.buffer[++r];if(s===" "){for(;s===" "||s===" "||s==="\r"||s===`
133
+ `;)s=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let i=e-1,o=this.buffer[i];o==="\r"&&(o=this.buffer[--i]);let a=i;for(;o===" ";)o=this.buffer[--i];if(o===`
134
+ `&&i>=this.pos&&i+1+t>a)e=i;else break}while(!0);return yield Us.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,s=this.pos-1,r;for(;r=this.buffer[++s];)if(r===":"){let i=this.buffer[s+1];if(Ee(i)||e&&ur.has(i))break;t=s}else if(Ee(r)){let i=this.buffer[s+1];if(r==="\r"&&(i===`
135
+ `?(s+=1,r=`
136
+ `,i=this.buffer[s+1]):t=s),i==="#"||e&&ur.has(i))break;if(r===`
137
+ `){let o=this.continueScalar(s+1);if(o===-1)break;s=Math.max(s,o-2)}}else{if(e&&ur.has(r))break;t=s}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Us.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let s=this.buffer.slice(this.pos,e);return s?(yield s,this.pos+=s.length,s.length):(t&&(yield""),0)}*pushIndicators(){switch(this.charAt(0)){case"!":return(yield*this.pushTag())+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"&":return(yield*this.pushUntil(ca))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators());case"-":case"?":case":":{let e=this.flowLevel>0,t=this.charAt(1);if(Ee(t)||e&&ur.has(t))return e?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,(yield*this.pushCount(1))+(yield*this.pushSpaces(!0))+(yield*this.pushIndicators())}}return 0}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!Ee(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(US.has(t))t=this.buffer[++e];else if(t==="%"&&Tu.has(this.buffer[e+1])&&Tu.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
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 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(`
139
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,s;do s=this.buffer[++t];while(s===" "||e&&s===" ");let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,s=this.buffer[t];for(;!e(s);)s=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};Iu.Lexer=la});var ha=T(Au=>{"use strict";var ua=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,s=this.lineStarts.length;for(;t<s;){let i=t+s>>1;this.lineStarts[i]<e?t=i+1:s=i}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};Au.LineCounter=ua});var pa=T(Ou=>{"use strict";var qS=H("process"),Cu=dr(),FS=da();function at(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Eu(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function xu(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function hr(n){switch(n.type){case"document":return n.start;case"block-map":{let e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function Yt(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function Nu(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!at(e.start,"explicit-key-ind")&&!at(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,xu(e.value)?e.value.end?Array.prototype.push.apply(e.value.end,e.sep):e.value.end=e.sep:Array.prototype.push.apply(e.start,e.sep),delete e.sep)}var fa=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new FS.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let s of this.lexer.lex(e,t))yield*this.next(s);t||(yield*this.end())}*next(e){if(this.source=e,qS.env.LOG_TOKENS&&console.log("|",Cu.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Cu.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let s=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:s,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let s=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in s?s.indent:0:t.type==="flow-collection"&&s.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Nu(t),s.type){case"document":s.value=t;break;case"block-scalar":s.props.push(t);break;case"block-map":{let r=s.items[s.items.length-1];if(r.value){s.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=s.items[s.items.length-1];r.value?s.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=s.items[s.items.length-1];!r||r.value?s.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((s.type==="document"||s.type==="block-map"||s.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Eu(r.start)===-1&&(t.indent===0||r.start.every(i=>i.type!=="comment"||i.indent<t.indent))&&(s.type==="document"?s.end=r.start:s.items.push({start:r.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Eu(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=hr(this.peek(2)),s=Yt(t),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let i={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:s,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
140
140
  `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
141
- `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let 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(`
141
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let s=!this.onKeyLine&&this.indent===e.indent,r=s&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",i=[];if(r&&t.sep&&!t.value){let o=[];for(let a=0;a<t.sep.length;++a){let l=t.sep[a];switch(l.type){case"newline":o.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(o.length=0);break;default:o.length=0}}o.length>=2&&(i=t.sep.splice(o[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(at(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(xu(t.key)&&!at(t.sep,"newline")){let o=Yt(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:a,sep:l}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken);else if(at(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let o=Yt(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):at(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let o=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:o,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(o):(Object.assign(t,{key:o,sep:[]}),this.onKeyLine=!0);return}default:{let o=this.startBlockValue(e);if(o){if(o.type==="block-seq"){if(!t.explicitKey&&t.sep&&!at(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else s&&e.items.push({start:i});this.stack.push(o);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let s="end"in t.value?t.value.end:void 0;(Array.isArray(s)?s[s.length-1]:void 0)?.type==="comment"?s?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Array.prototype.push.apply(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||at(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let s=this.startBlockValue(e);if(s){this.stack.push(s);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let s;do yield*this.pop(),s=this.peek(1);while(s?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let s=this.startBlockValue(e);s?this.stack.push(s):(yield*this.pop(),yield*this.step())}else{let s=this.peek(2);if(s.type==="block-map"&&(this.type==="map-value-ind"&&s.indent===e.indent||this.type==="newline"&&!s.items[s.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&s.type!=="flow-collection"){let r=hr(s),i=Yt(r);Nu(e);let o=e.end.splice(1,e.end.length);o.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:o}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
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(),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)),`---
143
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=hr(e),s=Yt(t);return s.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=hr(e),s=Yt(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(s=>s.type==="newline"||s.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};Ou.Parser=fa});var $u=T(qs=>{"use strict";var Mu=ea(),KS=Ms(),js=Ps(),HS=Qi(),WS=U(),GS=ha(),Du=pa();function Lu(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new GS.LineCounter||null,prettyErrors:e}}function VS(n,e={}){let{lineCounter:t,prettyErrors:s}=Lu(e),r=new Du.Parser(t?.addNewLine),i=new Mu.Composer(e),o=Array.from(i.compose(r.parse(n)));if(s&&t)for(let a of o)a.errors.forEach(js.prettifyError(n,t)),a.warnings.forEach(js.prettifyError(n,t));return o.length>0?o:Object.assign([],{empty:!0},i.streamInfo())}function Pu(n,e={}){let{lineCounter:t,prettyErrors:s}=Lu(e),r=new Du.Parser(t?.addNewLine),i=new Mu.Composer(e),o=null;for(let a of i.compose(r.parse(n),!0,n.length))if(!o)o=a;else if(o.options.logLevel!=="silent"){o.errors.push(new js.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return s&&t&&(o.errors.forEach(js.prettifyError(n,t)),o.warnings.forEach(js.prettifyError(n,t))),o}function YS(n,e,t){let s;typeof e=="function"?s=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=Pu(n,t);if(!r)return null;if(r.warnings.forEach(i=>HS.warn(r.options.logLevel,i)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:s},t))}function JS(n,e,t){let s=null;if(typeof e=="function"||Array.isArray(e)?s=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return WS.isDocument(n)&&!s?n.toString(t):new KS.Document(n,s,t).toString(t)}qs.parse=YS;qs.parseAllDocuments=VS;qs.parseDocument=Pu;qs.stringify=JS});var ga=T(F=>{"use strict";var zS=ea(),QS=Ms(),XS=Lo(),ma=Ps(),ZS=ms(),ct=U(),e0=nt(),t0=Z(),s0=it(),n0=ot(),r0=dr(),i0=da(),o0=ha(),a0=pa(),fr=$u(),Ru=us();F.Composer=zS.Composer;F.Document=QS.Document;F.Schema=XS.Schema;F.YAMLError=ma.YAMLError;F.YAMLParseError=ma.YAMLParseError;F.YAMLWarning=ma.YAMLWarning;F.Alias=ZS.Alias;F.isAlias=ct.isAlias;F.isCollection=ct.isCollection;F.isDocument=ct.isDocument;F.isMap=ct.isMap;F.isNode=ct.isNode;F.isPair=ct.isPair;F.isScalar=ct.isScalar;F.isSeq=ct.isSeq;F.Pair=e0.Pair;F.Scalar=t0.Scalar;F.YAMLMap=s0.YAMLMap;F.YAMLSeq=n0.YAMLSeq;F.CST=r0;F.Lexer=i0.Lexer;F.LineCounter=o0.LineCounter;F.Parser=a0.Parser;F.parse=fr.parse;F.parseAllDocuments=fr.parseAllDocuments;F.parseDocument=fr.parseDocument;F.stringify=fr.stringify;F.visit=Ru.visit;F.visitAsync=Ru.visitAsync});function Bu(n={},e){let t={};for(let s of Object.keys(Jt)){let r=n[s]??Jt[s];t[s]=r&&(e?.[s]??!0)}return t}var Jt,ya=j(()=>{"use strict";Jt={externalComms:!0,codeTask:!1,codeAccess:!1}});import{execFileSync as c0}from"node:child_process";function zt(n,e){if(process.platform!=="darwin")return"";try{return c0("security",["find-generic-password","-s",`hive/${n}/${e}`,"-w"],{encoding:"utf-8",stdio:["pipe","pipe","pipe"]}).trim()}catch{return""}}var pr=j(()=>{"use strict"});import{readFileSync as l0,existsSync as Fu,readdirSync as d0,statSync as u0}from"node:fs";import{resolve as wa}from"node:path";import{randomUUID as Sa}from"node:crypto";function Uu(n){let e=process.env[n]||Hu(n);if(!e)throw new Error(`Missing required env var: ${n}`);return e}function b(n,e){return process.env[n]||Hu(n)||e}function f0(n){if(n?.length)return n.map(t=>wa(t.replace(/^~/,process.env.HOME??"/tmp")));let e=wa(cs,"plugins/claude-code");return Fu(e)?d0(e).map(t=>wa(e,t)).filter(t=>u0(t).isDirectory()):[]}var qu,Ku,h0,ju,C,gI,Fs,Hu,lt,_t,g,Ne=j(()=>{"use strict";qu=Ae(zc(),1),Ku=Ae(ga(),1);ya();pr();ls();h0=Ec(V);qu.default.config({path:h0});ju=Cc(V),C={};Fu(ju)&&(C=(0,Ku.parse)(l0(ju,"utf-8"))??{});gI=process.env.HOME??"/tmp",Fs=C.instance?.id??"hive",Hu=n=>zt(Fs,n),lt=C.instance?.portBase??3100,_t=C.instance?.ports??{},g={instance:{id:Fs,portBase:lt},business:{name:C.business?.name??b("BUSINESS_NAME",""),description:C.business?.description??"",location:C.business?.location??"",ownerName:C.business?.owner?.name??"",ownerRole:C.business?.owner?.role??""},slack:{appToken:Uu("SLACK_APP_TOKEN"),botToken:Uu("SLACK_BOT_TOKEN"),mcpToken:b("SLACK_MCP_TOKEN",""),auditChannel:b("SLACK_AUDIT_CHANNEL",C.slack?.auditChannel??""),localMcpServer:!!(C.slack?.localMcpServer??!1)},anthropic:{apiKey:b("ANTHROPIC_API_KEY","")},linear:{apiKey:b("LINEAR_API_KEY",""),teamId:b("LINEAR_TEAM_ID","")},clickup:{apiToken:b("CLICKUP_API_TOKEN","")},github:{repo:b("GITHUB_REPO",""),token:b("GH_TOKEN","")},brave:{apiKey:b("BRAVE_API_KEY","")},taskLedger:{apiUrl:b("TASK_LEDGER_API_URL","http://localhost:3002"),agentKeys:Object.fromEntries(Object.entries(process.env).filter(([n])=>n.startsWith("TASK_LEDGER_KEY_")).map(([n,e])=>[n.replace("TASK_LEDGER_KEY_","").toLowerCase().replace(/_/g,"-"),e])),apiKey:b("TASK_LEDGER_API_KEY","")},mongo:{uri:b("MONGODB_URI","mongodb://localhost:27017"),dbName:b("MONGODB_DB",`hive_${Fs}`)},defaultAgent:b("DEFAULT_AGENT","chief-of-staff"),google:{account:b("GOOGLE_ACCOUNT",C.google?.account??""),client:b("GOG_CLIENT",C.google?.client??""),accounts:C.google?.accounts??{},sharedFolder:b("DRIVE_SHARED_FOLDER",C.google?.sharedFolder??C.googleWorkspace?.sharedFolder??"")},googleWorkspace:{account:b("GWS_ACCOUNT",C.googleWorkspace?.account??""),gwsPath:b("GWS_PATH",""),sharedFolder:b("GWS_SHARED_FOLDER",C.googleWorkspace?.sharedFolder??"")},quo:{apiKey:b("QUO_API_KEY",""),phoneNumberId:b("QUO_PHONE_NUMBER_ID",""),lines:C.quo?.lines??{}},sms:{lines:C.sms?.lines??[]},imessage:{enabled:C.imessage?.enabled??!1,slackChannel:C.imessage?.slackChannel??"imessage",hotWindowMs:C.imessage?.hotWindowMs??3e5,coldIntervalMs:C.imessage?.coldIntervalMs??3e5,hotIntervalMs:C.imessage?.hotIntervalMs??1e4},resend:{apiKey:b("RESEND_API_KEY",""),fromAddress:b("RESEND_FROM_ADDRESS",""),defaultCc:b("RESEND_DEFAULT_CC",""),defaultBcc:b("RESEND_DEFAULT_BCC",""),emailDomain:b("RESEND_EMAIL_DOMAIN",C.resend?.emailDomain??""),businessName:b("RESEND_BUSINESS_NAME",C.resend?.businessName??"")},plugins:C.plugins??[],skillRegistries:C.skillRegistries??[{name:"keepur-default",url:"https://github.com/keepur/hive-skills",default:!0}],gemini:{apiKey:b("GEMINI_API_KEY",""),visionModel:b("GEMINI_VISION_MODEL","gemini-2.5-flash")},permits:{mongoUri:b("PERMITS_MONGO_URI","mongodb://localhost:27017/permits")},recall:{apiKey:b("RECALL_API_KEY",""),region:b("RECALL_API_REGION","us-west-2"),monitorPort:parseInt(b("MEETING_MONITOR_PORT",String(_t.recall??lt+1)),10),monitorPublicUrl:b("MEETING_MONITOR_PUBLIC_URL",""),webhookSecret:b("RECALL_WEBHOOK_SECRET","")},scheduler:{heartbeatIntervalMs:parseInt(b("HEARTBEAT_INTERVAL_MS","120000"),10)},background:{port:parseInt(b("BG_TASK_PORT",String(_t.background??lt)),10),authToken:b("BG_TASK_AUTH_TOKEN","")||Sa()},slackInternal:{port:parseInt(b("SLACK_INTERNAL_PORT",String(_t.slackInternal??lt+6)),10),authToken:b("SLACK_INTERNAL_TOKEN","")||Sa()},codeTask:{port:parseInt(b("CODE_TASK_PORT",String(_t.codeTask??lt+2)),10),authToken:b("CODE_TASK_AUTH_TOKEN","")||Sa(),pluginDirs:f0(C.codeTask?.pluginDirs),defaultModel:b("CODE_TASK_MODEL","claude-sonnet-4-6"),defaultMaxTurns:parseInt(b("CODE_TASK_MAX_TURNS","100"),10),defaultMaxBudget:parseFloat(b("CODE_TASK_MAX_BUDGET","5.00")),maxConcurrent:parseInt(b("CODE_TASK_MAX_CONCURRENT","2"),10),maxLifetimeMs:parseInt(b("CODE_TASK_MAX_LIFETIME_MS",String(480*60*1e3)),10),staleGraceMs:parseInt(b("CODE_TASK_STALE_GRACE_MS",String(1800*1e3)),10)},ws:{enabled:b("WS_ENABLED","false")==="true",port:parseInt(b("WS_PORT",String(_t.ws??lt+3)),10)},beekeeper:{port:parseInt(b("BEEKEEPER_PORT",String(C.beekeeper?.port??8420)),10)},workflow:{enabled:b("WORKFLOW_ENABLED","false")==="true"},adminApi:{port:parseInt(b("ADMIN_API_PORT",String(_t.adminApi??lt+4)),10),token:b("ADMIN_API_TOKEN","")},voice:{enabled:!!C.voice?.provider,provider:C.voice?.provider??"",publicUrl:C.voice?.publicUrl??"",phoneNumberId:C.voice?.phoneNumberId??"",assistants:C.voice?.assistants??{},apiKey:b("VAPI_API_KEY",""),serverSecret:b("VAPI_SERVER_SECRET",""),port:parseInt(b("VOICE_PORT",String(_t.voice??lt+5)),10)},autonomy:{externalComms:C.autonomy?.externalComms??Jt.externalComms,codeTask:C.autonomy?.codeTask??Jt.codeTask,codeAccess:C.autonomy?.codeAccess??Jt.codeAccess},modelRouter:{enabled:b("MODEL_ROUTER_ENABLED","true")==="true",model:b("MODEL_ROUTER_MODEL","claude-haiku-4-5-20251001"),timeoutMs:parseInt(b("MODEL_ROUTER_TIMEOUT_MS","8000"),10)},sweeper:{intervalMs:parseInt(b("SWEEPER_INTERVAL_MS","300000"),10),threadTtlMs:parseInt(b("SWEEPER_THREAD_TTL_MS","86400000"),10),taskFileTtlMs:parseInt(b("SWEEPER_TASK_FILE_TTL_MS","604800000"),10),meetingSessionTtlMs:parseInt(b("SWEEPER_MEETING_TTL_MS","3600000"),10),cacheTtlMs:parseInt(b("SWEEPER_CACHE_TTL_MS","3600000"),10),retryMaxAttempts:parseInt(b("SWEEPER_RETRY_MAX_ATTEMPTS","3"),10),retryBaseDelayMs:parseInt(b("SWEEPER_RETRY_BASE_DELAY_MS","30000"),10)},retention:(()=>{let n=C.retention?.paths??{data:7,"agents/*/scratch":7,"agents/*/feeds":7,"agents/*/playwright":3,"agents/*/reports":0,logs:30},e={};for(let[r,i]of Object.entries(n)){if(typeof i!="number"||!Number.isFinite(i)||i<0)throw new Error(`Invalid retention.paths.${r}: must be a non-negative integer (got ${i})`);e[r]={days:i}}let t=Number(C.retention?.defaults?.days??7);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid retention.defaults.days: ${t}`);let s=parseInt(b("RETENTION_INTERVAL_MS",String(C.retention?.intervalMs??168*36e5)),10);if(!Number.isFinite(s)||s<=0)throw new Error(`Invalid retention.intervalMs: must be a positive integer (got ${s})`);return{enabled:!!(C.retention?.enabled??!1),intervalMs:s,defaultDays:t,paths:e}})(),memory:{hotBudgetTokens:parseInt(b("MEMORY_HOT_BUDGET_TOKENS",String(C.memory?.hotBudgetTokens??3e3)),10),sweepIntervalHours:parseFloat(b("MEMORY_SWEEP_INTERVAL_HOURS",String(C.memory?.sweepIntervalHours??6))),hotThreshold:parseFloat(b("MEMORY_HOT_THRESHOLD",String(C.memory?.hotThreshold??.6))),warmThreshold:parseFloat(b("MEMORY_WARM_THRESHOLD",String(C.memory?.warmThreshold??.3))),recencyHalfLifeDays:parseFloat(b("MEMORY_RECENCY_HALF_LIFE_DAYS",String(C.memory?.recencyHalfLifeDays??7))),coldSummaryMinRecords:parseInt(b("MEMORY_COLD_SUMMARY_MIN",String(C.memory?.coldSummaryMinRecords??5)),10),coldRetentionDays:parseInt(b("MEMORY_COLD_RETENTION_DAYS",String(C.memory?.coldRetentionDays??90)),10),purgeRetentionDays:parseInt(b("MEMORY_PURGE_RETENTION_DAYS",String(C.memory?.purgeRetentionDays??7)),10),reflectionMinTurns:parseInt(b("MEMORY_REFLECTION_MIN_TURNS",String(C.memory?.reflectionMinTurns??3)),10)},codeIndex:{enabled:C.codeIndex?.enabled===!0||process.env.CODE_INDEX_ENABLED==="true",scoreThreshold:parseFloat(b("CODE_INDEX_SCORE_THRESHOLD",String(C.codeIndex?.scoreThreshold??.65))),prefetchLimit:parseInt(b("CODE_INDEX_PREFETCH_LIMIT",String(C.codeIndex?.prefetchLimit??8)),10),sessionKnowledge:{enabled:(C.codeIndex?.sessionKnowledge?.enabled??!0)&&process.env.CODE_INDEX_SESSION_KNOWLEDGE!=="false"},repos:C.codeIndex?.repos??{}},events:{retentionDays:parseInt(b("EVENT_RETENTION_DAYS",String(C.events?.retentionDays??30)),10)},activity:{enabled:(C.activity?.enabled??!0)&&process.env.ACTIVITY_LOG_ENABLED!=="false",bufferSize:parseInt(b("ACTIVITY_BUFFER_SIZE",String(C.activity?.bufferSize??200)),10),flushIntervalMs:parseInt(b("ACTIVITY_FLUSH_INTERVAL_MS",String(C.activity?.flushIntervalMs??3e4)),10),retentionDays:parseInt(b("ACTIVITY_RETENTION_DAYS",String(C.activity?.retentionDays??90)),10)},autoDream:{enabled:C.autoDream?.enabled??!0,idleThresholdMinutes:parseInt(b("AUTODREAM_IDLE_THRESHOLD_MINUTES",String(C.autoDream?.idleThresholdMinutes??30)),10),cooldownMinutes:parseInt(b("AUTODREAM_COOLDOWN_MINUTES",String(C.autoDream?.cooldownMinutes??60)),10),similarityThreshold:parseFloat(b("AUTODREAM_SIMILARITY_THRESHOLD",String(C.autoDream?.similarityThreshold??.85))),patternMinCount:parseInt(b("AUTODREAM_PATTERN_MIN_COUNT",String(C.autoDream?.patternMinCount??3)),10),maxClustersPerRun:parseInt(b("AUTODREAM_MAX_CLUSTERS",String(C.autoDream?.maxClustersPerRun??20)),10),maxContradictionPairsPerRun:parseInt(b("AUTODREAM_MAX_CONTRADICTIONS",String(C.autoDream?.maxContradictionPairsPerRun??30)),10),maxPromotionsPerRun:parseInt(b("AUTODREAM_MAX_PROMOTIONS",String(C.autoDream?.maxPromotionsPerRun??10)),10),maxBudgetUsd:parseFloat(b("AUTODREAM_MAX_BUDGET_USD",String(C.autoDream?.maxBudgetUsd??.1)))},browser:{cdpEndpoint:b("BROWSER_CDP_ENDPOINT","")},tasksDir:{code:b("CODE_TASKS_DIR",`/tmp/${Fs}-code-tasks`),background:b("BG_TASKS_DIR",`/tmp/${Fs}-bg-tasks`)}}});function Vu(n){ka.has(n.id)&&Gu.warn("Archetype already registered \u2014 overwriting",{id:n.id}),ka.set(n.id,n),Gu.info("Registered archetype",{id:n.id})}function mr(n){return ka.get(n)}var Gu,ka,gr=j(()=>{"use strict";M();Gu=k("archetypes"),ka=new Map});import{readFileSync as b0}from"node:fs";import{resolve as dh}from"node:path";function v0(){let n=[dh(import.meta.dirname,"..","..","package.json"),dh(import.meta.dirname,"..","package.json")];for(let e of n)try{let t=JSON.parse(b0(e,"utf-8"));if(t?.name==="@keepur/hive"&&typeof t.hiveApi=="string")return t.hiveApi}catch{continue}return null}var _0,uh,_a,hh=j(()=>{"use strict";M();_0=k("api-version");uh=v0();uh||_0.warn("Could not read hiveApi from package.json; falling back to 1.0.0");_a=uh??"1.0.0"});var gh={};Ue(gh,{isHiveApiCompatible:()=>ph,loadPlugins:()=>va,normalizeManifest:()=>mh,registerPluginCommands:()=>I0,rescanPluginBrokenServers:()=>Ta,resolvePluginServerPath:()=>Ks});import{readFileSync as T0,existsSync as Sr}from"node:fs";import{resolve as dt,join as wr}from"node:path";function Ks(n,e,t){let s=e.replace(/\.ts$/,".js"),r=e.replace(/\.ts$/,".min.js"),i=[];t.distDir&&i.push(dt(t.distDir,`plugins/${n}/${s}`)),i.push(dt(t.hiveHome,"plugins","node_modules",n,"dist",r),dt(t.hiveHome,"plugins","node_modules",n,"dist",s),dt(t.hiveHome,"plugins",n,"dist",r),dt(t.hiveHome,"plugins",n,"dist",s));for(let o of i)if(Sr(o))return{path:o};return{reason:"no compiled entry found (expected one of .min.js or .js under dist/)",pathsChecked:i}}function va(n,e,t){let s=[];for(let r of n){let i=dt(e,"plugins","node_modules",r),o=dt(e,"plugins",r),a=wr(i,"plugin.yaml"),l=wr(o,"plugin.yaml"),c;if(Sr(a))c=i;else if(Sr(l))c=o;else{ut.warn("Plugin manifest not found, skipping",{plugin:r,tried:[a,l]});continue}let d=wr(c,"plugin.yaml"),u=(0,fh.parse)(T0(d,"utf-8")),h=mh(u);if(h.hiveApi&&!ph(h.hiveApi,_a)){ut.warn("Plugin declares incompatible hiveApi range, skipping",{plugin:r,requires:h.hiveApi,running:_a});continue}let p={};for(let[f,y]of Object.entries(h.mcpServers)){let w=Ks(r,y.entry,{hiveHome:e,distDir:t?.distDir});"reason"in w&&(p[f]=w,ut.error("Plugin MCP server entry not resolvable",{plugin:r,server:f,entry:y.entry,reason:w.reason,pathsChecked:w.pathsChecked}))}for(let f of h.agentSeeds){let y=wr(c,"agent-seeds",f);Sr(y)||ut.warn("Plugin agent seed not found",{plugin:r,seed:f,path:y})}s.push({name:r,dir:c,manifest:h,brokenServers:p});let m=Object.keys(p);ut.info("Plugin loaded",{plugin:r,mcpServers:Object.keys(h.mcpServers),seeds:h.agentSeeds,...m.length?{brokenServers:m}:{}})}return s}function Ta(n,e,t){let s={},r={};for(let i of n){let o=Object.keys(i.brokenServers);if(o.length!==0)for(let a of o){let l=i.manifest.mcpServers[a];if(!l){delete i.brokenServers[a];continue}"path"in Ks(i.name,l.entry,{hiveHome:e,distDir:t?.distDir})?(delete i.brokenServers[a],(s[i.name]??=[]).push(a)):(r[i.name]??=[]).push(a)}}return{rescued:s,stillBroken:r}}function ph(n,e){let t=n.trim();if(t===e)return!0;if(t.startsWith("^")){let s=t.slice(1).split(".").map(Number),r=e.split(".").map(Number);return!(s.length<1||r.length<1||s[0]!==r[0]||(r[1]??0)<(s[1]??0)||(r[1]??0)===(s[1]??0)&&(r[2]??0)<(s[2]??0))}return ut.warn("Unrecognized hiveApi range syntax, accepting",{range:n}),!0}function mh(n){return{name:n.name??"",description:n.description??"",hiveApi:n.hiveApi??n["hive-api"]??void 0,mcpServers:Object.fromEntries(Object.entries(n["mcp-servers"]??{}).map(([e,t])=>[e,{entry:t.entry,description:t.description,usage:t.usage,notFor:t["not-for"],env:t.env??[],secretEnv:t["secret-env"]??[],envMap:t["env-map"]??{},agentEnv:t["agent-env"]??{}}])),agentSeeds:n["agent-seeds"]??n["agents-templates"]??[],registerCommands:n["register-commands"]??void 0}}async function I0(n,e){for(let t of n)if(t.manifest.registerCommands)try{let r=await import(dt(t.dir,"dist",t.manifest.registerCommands));typeof r.registerCommands=="function"&&(r.registerCommands(e),ut.info("Plugin commands registered",{plugin:t.name}))}catch(s){ut.warn("Failed to load plugin commands",{plugin:t.name,error:String(s)})}}var fh,ut,kr=j(()=>{"use strict";fh=Ae(ga(),1);M();hh();ut=k("plugin-loader")});import{readFileSync as A0,writeFileSync as C0}from"node:fs";function E0(n){let e=n.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);if(!e)throw new Error("No YAML frontmatter found");let t=e[1],s=e[2],r={name:"",description:"",agents:[]},i=t.split(`
144
+ `),o=0;for(;o<i.length;){let a=i[o];if(a.trim()===""){o++;continue}let l=a.match(/^(\w[\w-]*):\s*(.*)/);if(!l){o++;continue}let c=l[1],d=l[2].trim();if(c==="name")r.name=vt(d);else if(c==="description")r.description=vt(d);else if(c==="workflow")r.workflow=vt(d);else if(c==="agents"){let u=d.match(/^\[([^\]]*)\]$/);if(u)r.agents=u[1].split(",").map(h=>vt(h.trim())).filter(h=>h.length>0);else if(d==="")for(r.agents=[];o+1<i.length&&i[o+1].match(/^\s+-\s+/);){o++;let h=i[o].replace(/^\s+-\s+/,"").trim();r.agents.push(vt(h))}else r.agents=[vt(d)]}else if(c==="origin")for(r.origin=yh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;else if(c==="author")for(r.author=yh(i,o);o+1<i.length&&i[o+1].match(/^\s+\S/);)o++;o++}return{frontmatter:r,body:s}}function yh(n,e){let t={},s=e+1;for(;s<n.length&&n[s].match(/^\s+\S/);){let r=n[s].match(/^\s+([\w][\w-]*):\s*(.*)/);if(r){let i=r[2].trim();i==="true"?t[r[1]]=!0:i==="false"?t[r[1]]=!1:t[r[1]]=vt(i)}s++}return t}function vt(n){return n.startsWith('"')&&n.endsWith('"')||n.startsWith("'")&&n.endsWith("'")?n.slice(1,-1).replace(/\\"/g,'"').replace(/\\\\/g,"\\"):n}function N0(n,e){let t=[];t.push(`name: ${br(n.name)}`),t.push(`description: ${br(n.description)}`);let s=n.agents.join(", ");return t.push(`agents: [${s}]`),n.workflow&&t.push(`workflow: ${br(n.workflow)}`),n.origin&&(t.push("origin:"),wh(t,n.origin)),n.author&&(t.push("author:"),wh(t,n.author)),`---
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=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(`
148
+ ${e}`}function wh(n,e){for(let[t,s]of Object.entries(e))s!==void 0&&n.push(` ${t}: ${br(String(s))}`)}function br(n){return n.includes(":")||n.includes("#")||n.includes('"')?`"${n.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`:n}function Sh(n){let e=A0(n,"utf-8");return E0(e)}function kh(n,e,t){C0(n,N0(e,t),"utf-8")}function bh(n){let e=n.match(/^(---\n)([\s\S]*?)(\n---\n?)([\s\S]*)$/);if(!e)return n;let t=e[1],s=e[2],r=e[3],i=e[4],o=s.split(`
149
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 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
-
154
- Direct tools available to you:
155
- ${u.join(`
156
- `)}`)}let a=t??[];if(a.length>0){let u=a.map(h=>Na(h,this.getServerCatalogEntry(h)));s.push(`## Available via subagents
157
-
158
- You have additional capabilities through delegation. If a task involves any of these domains, use the Agent tool \u2014 do NOT say you lack access:
159
- ${u.join(`
160
- `)}`)}let l=await this.memoryManager.getHotTierPrompt(this.agentConfig.id,p.memory.hotBudgetTokens);if(l)s.push(l);else{let u=`agents/${this.agentConfig.id}`,h=await this.memoryManager.read(`${u}/memory.md`);h&&s.push(`## Your Memory
161
- ${h}`);let g=(await this.memoryManager.list(u)).filter(f=>f.endsWith(".md")&&f!=="memory.md");g.length>0&&s.push(`## Available Memory Files
162
- You have ${g.length} reference file(s) in your memory directory:
163
- `+g.map(f=>`- ${u}/${f}`).join(`
164
- `)+"\n\nRead relevant files via the memory MCP server (`memory_read`) before starting tasks that may relate to them.")}let d=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return s.push(`**Current date/time**: ${d} (Pacific Time)`),s.join(`
150
+ `)+r+i}var Ia=j(()=>{"use strict"});import{createHash as x0}from"node:crypto";import{readdirSync as O0,readFileSync as M0,statSync as D0}from"node:fs";import{join as _h}from"node:path";function vh(n){let e=Th(n).sort(),t=x0("sha256");for(let s=0;s<e.length;s++){s>0&&t.update("\0");let r=_h(n,e[s]),i=M0(r,"utf-8");e[s]==="SKILL.md"?t.update(bh(i)):t.update(i)}return t.digest("hex")}function Th(n,e=""){let t=O0(n),s=[];for(let r of t){let i=_h(n,r),o=e?`${e}/${r}`:r;D0(i).isDirectory()?s.push(...Th(i,o)):s.push(o)}return s}var Ih=j(()=>{"use strict";Ia()});import{readdirSync as Ca,readFileSync as L0,statSync as Ea,existsSync as Tt}from"node:fs";import{join as xe,relative as P0,resolve as $0}from"node:path";function Na(n,e,t){let s=new Map,r=[],i=new Map;for(let o of t??[]){let a=xe(o,"skills");if(!Tt(a))continue;let l=o.split("/").pop()??"seed";Aa(a,`seed:${l}`,i,s,r,!1)}for(let o of e??[]){let a=xe(o.dir,"skills");Tt(a)&&Aa(a,o.name,i,s,r,!1)}if(Tt(n)?Aa(n,"customer",i,s,r,!0):be.debug("No customer skills directory found",{path:n}),r.length>0){for(let o of[...s.keys()])s.get(o).push(...r);s.set("__universal__",r)}return R0=B0(i,n),be.info("Skill index loaded",{workflows:i.size,agents:s.size-(s.has("__universal__")?1:0)}),s}function Ah(n,e,t){for(let[s,r]of e){let i=r.filter(o=>o.path!==n);i.length!==r.length&&(i.length===0?e.delete(s):e.set(s,i))}for(let s=t.length-1;s>=0;s--)t[s].path===n&&t.splice(s,1)}function Aa(n,e,t,s,r,i){let o;try{o=Ca(n).filter(a=>{try{return Ea(xe(n,a)).isDirectory()}catch{return!1}})}catch(a){be.warn("Failed to read skills directory",{source:e,path:n,error:String(a)});return}for(let a of o){let l=xe(n,a),c=xe(l,"skills");if(!Tt(c)){be.debug("Workflow missing skills/ subdirectory, skipping",{source:e,workflow:a});continue}let d=t.get(a);if(d)if(i&&d.source!=="customer")be.warn("Customer skill shadows plugin-bundled skill",{workflow:a,shadowed:d,customer:{source:e,path:l}}),Ah(d.path,s,r),t.set(a,{source:e,path:l});else if(i&&d.source==="customer"){be.error("Customer skill collision \u2014 both skipped",{workflow:a,first:d,second:{source:e,path:l}}),Ah(d.path,s,r),t.delete(a);continue}else{be.warn("Skill workflow collision \u2014 keeping first, skipping second",{workflow:a,kept:d,skipped:{source:e,path:l}});continue}else t.set(a,{source:e,path:l});let u={type:"local",path:l},h=new Set,p=!1,m;try{m=Ca(c).filter(f=>{try{return Ea(xe(c,f)).isDirectory()}catch{return!1}})}catch(f){be.warn("Failed to read workflow skills subdir",{source:e,workflow:a,error:String(f)});continue}for(let f of m){let y=xe(c,f,"SKILL.md");if(!Tt(y))continue;let w=U0(L0(y,"utf-8"));for(let S of w)S==="all"?p=!0:h.add(S)}if(p)r.push(u),be.debug("Workflow registered as universal",{source:e,workflow:a,skills:m.length});else if(h.size>0){for(let f of h){let y=s.get(f)??[];y.push(u),s.set(f,y)}be.debug("Workflow registered",{source:e,workflow:a,agents:[...h],skills:m.length})}}}function Ch(n,e){let t=n.get(e)??[],s=n.get("__universal__")??[];if(t.length>0&&s.length>0){let r=new Set(t.map(o=>o.path)),i=s.filter(o=>!r.has(o.path));return[...t,...i]}return t.length===0&&s.length>0?[...s]:t}function B0(n,e){let t=new Set,s=$0(e,"..");for(let[r,i]of n){if(i.source!=="customer")continue;let o=xe(i.path,"skills");if(!Tt(o))continue;let a;try{a=Ca(o).filter(l=>{try{return Ea(xe(o,l)).isDirectory()}catch{return!1}})}catch{continue}for(let l of a){let c=xe(o,l),d=xe(c,"SKILL.md");if(Tt(d))try{let{frontmatter:u,body:h}=Sh(d);if(!u.origin?.["base-content-hash"])continue;let p=vh(c);if(p!==u.origin["base-content-hash"]&&(t.add(c),be.warn("Registry-installed skill has been modified",{workflow:r,skill:l,source:u.origin.source,baseHash:u.origin["base-content-hash"],currentHash:p}),!u.origin.modified)){u.origin.modified=!0;try{kh(d,u,h),Rc(s,[P0(s,d)],`detect-modified: ${l} content hash changed`)}catch(m){be.error("Failed to persist modified flag to disk",{path:d,error:String(m)})}}}catch{}}}return t}function U0(n){let e=n.match(/^---\n([\s\S]*?)\n---/);if(!e)return[];let t=e[1],s=t.match(/^agents:\s*\n((?:\s+-\s+.+\n?)*)/m);if(s)return s[1].split(`
151
+ `).map(i=>i.replace(/^\s+-\s+/,"").trim()).filter(Boolean);let r=t.match(/^agents:\s*\[([^\]]*)\]/m);return r?r[1].split(",").map(i=>i.trim()).filter(Boolean):[]}var be,R0,xa=j(()=>{"use strict";M();Ih();Ia();xi();be=k("skill-loader"),R0=new Set});var It,_r=j(()=>{"use strict";It={clickup:{description:"Task management \u2014 tasks, lists, spaces, comments, custom fields",usage:"Creating and managing project tasks"},google:{description:"Email (Gmail), calendar, Google Drive files",usage:"Sending email, checking calendar events, reading Drive documents"},resend:{description:"Send outbound email with file attachments",usage:"Sending transactional or outreach email from your agent address",notFor:"Reading email \u2014 use google for inbox access"},"brave-search":{description:"Web search, news, local business lookup",usage:"Finding current information from the public web",notFor:"Internal data \u2014 use crm-search, code-search, or memory instead"},contacts:{description:"Contact lookups by name, email, or phone",usage:"Quick lookups of people in the contact directory",notFor:"Messaging another hive agent (use team) or CRM deal/company data (use a CRM plugin)"},team:{description:"Direct agent-to-agent messaging \u2014 peer hive agents, not Slack DMs",usage:"Sending a message or task to another agent in this hive",notFor:"Looking up people in the contact directory \u2014 use contacts instead",toolkitBlurb:"Direct messaging to peer hive agents (not Slack DMs)"},linear:{description:"Issue tracking and project management",usage:"Creating, searching, and updating engineering issues"},"github-issues":{description:"GitHub issue tracking \u2014 create, search, update, comment on issues",usage:"Managing GitHub issues for engineering work"},quo:{description:"Send and receive SMS messages via OpenPhone",usage:"Texting customers or team members"},voice:{description:"Make outbound phone calls via Vapi",usage:"Calling customers, scheduling appointments, following up by phone"},tasks:{description:"Task management \u2014 create, update, and track agent tasks",usage:"Managing your own task queue"},"code-search":{description:"Semantic search over codebase file index \u2014 find where functionality lives, file roles, exports",usage:"Finding code by what it does, not just by filename",notFor:"Broad web search \u2014 use brave-search instead"},"code-task":{description:"Spawn Claude Code CLI sessions for coding tasks",usage:"Delegating implementation, debugging, or code analysis work"},memory:{description:"Read and write your personal agent memory",usage:"Storing and retrieving facts across conversations. Auto-managed \u2014 don't over-save"},"structured-memory":{description:"Semantic + temporal memory tiers \u2014 recall, save, pin, forget",usage:"Use memory_recall to find prior facts; memory_save/_pin for durable notes",toolkitBlurb:"Semantic + temporal memory tiers (recall, save, pin)"},schedule:{description:"Self-service schedule management \u2014 view, add, update, remove your schedules",usage:"Managing your recurring or one-time scheduled tasks",toolkitBlurb:"Manage your scheduled tasks (recurring or one-time)"},"event-bus":{description:"Publish events to the cross-agent event bus",usage:"Notifying other agents about state changes or completed work"},workflow:{description:"Plan and task management \u2014 create plans, assign tasks, track dependencies",usage:"Coordinating multi-step work across agents and humans"},callback:{description:"Schedule future self-invocations",usage:"Reminding yourself to follow up on something later"},background:{description:"Spawn detached background processes",usage:"Running long-lived commands that outlive your current turn"},"conversation-search":{description:"Semantic search over past conversations",usage:"Finding what was discussed previously across threads"},browser:{description:"Browser automation via Playwright \u2014 navigate, click, fill forms, screenshot",usage:"Accessing web UIs that don't have APIs"},slack:{description:"Slack API \u2014 read channels, post messages, manage threads",usage:"Interacting with Slack channels and threads",toolkitBlurb:"Slack channels, messages, and threads"},recall:{description:"Meeting bot \u2014 join calls, get transcripts",usage:"Participating in or getting transcripts from video meetings"},admin:{description:"Agent management \u2014 list, view, update agent definitions",usage:"Viewing or modifying agent configurations"},keychain:{description:"Read secrets from macOS Keychain",usage:"Retrieving API keys or credentials stored in the system keychain"}}});function Eh(n=[]){let e=[],t=[],s=[];for(let i of Object.keys(It)){if(q0.has(i)){e.push(i);continue}let o=j0[i];!o||o()?e.push(i):t.push(i)}let r=g.instance?.id??"unknown";for(let i of n)for(let[o,a]of Object.entries(i.manifest.mcpServers)){let l=i.brokenServers[o];if(l){s.push({name:o,reason:l.reason});continue}let c=a.env??[],d=a.secretEnv??[],u=c.every(p=>!!process.env[p]),h=d.every(p=>!!process.env[p]||!!zt(r,p));u&&h?e.push(o):t.push(o)}return{instanceId:g.instance?.id??"unknown",servers:{configured:e,unconfigured:t,broken:s}}}var j0,q0,Nh=j(()=>{"use strict";Ne();pr();_r();j0={google:()=>Object.keys(g.google?.accounts??{}).length>0||!!g.google?.account,resend:()=>!!g.resend?.apiKey,"brave-search":()=>!!g.brave?.apiKey,linear:()=>!!g.linear?.apiKey,clickup:()=>!!g.clickup?.apiToken,"github-issues":()=>!!g.github?.repo,quo:()=>!!g.quo?.apiKey,recall:()=>!!g.recall?.apiKey,"code-task":()=>!0,"code-search":()=>!!g.codeIndex?.enabled,browser:()=>!!g.browser?.cdpEndpoint,tasks:()=>(g.taskLedger?.apiUrl??"")!=="http://localhost:3002"},q0=new Set(["memory","slack","contacts","callback","background","schedule","event-bus","conversation-search","keychain","admin"])});function Oa(n,e){let t=It[n];if(t)return t;for(let s of e){let r=s.manifest.mcpServers[n];if(r?.description)return{description:r.description,usage:r.usage,notFor:r.notFor}}return{description:n}}function K0(n){return n.toolkitBlurb??n.description}function Ma(n,e){return`- ${n} \u2014 ${K0(e)}`}function xh(n){let{coreServerNames:e,delegateServerNames:t,plugins:s,autoInjectedServers:r}=n,i=[],o=[],a=new Set;for(let d of e)r.has(d)&&(i.push(d),a.add(d));for(let d of e)a.has(d)||o.push(d);let l=[];l.push(`## Your toolkit
152
+
153
+ You have access to the following tools this session. Try them; don't guess at availability.`);let c=F0.map(d=>`- ${d.name} \u2014 ${d.blurb}`).join(`
154
+ `);if(l.push(`### Built-in (always available)
155
+ ${c}`),i.length>0){let d=i.map(u=>Ma(u,Oa(u,s))).join(`
156
+ `);l.push(`### Engine-provided (always available to every agent)
157
+ `+d)}if(o.length>0){let d=o.map(u=>Ma(u,Oa(u,s))).join(`
158
+ `);l.push(`### Capability MCPs (provisioned for your role)
159
+ `+d)}if(t.length>0){let d=t.map(u=>Ma(u,Oa(u,s))).join(`
160
+ `);l.push(`### Delegated capability MCPs (via Agent tool)
161
+ `+d)}return l.join(`
162
+
163
+ `)}var F0,Oh=j(()=>{"use strict";_r();F0=[{name:"Bash",blurb:"run shell commands"},{name:"Read / Write / Edit",blurb:"file I/O"},{name:"Glob / Grep",blurb:"file/content search"},{name:"WebFetch / WebSearch",blurb:"web access"},{name:"NotebookEdit",blurb:"Jupyter notebook editing"}]});var Lh={};Ue(Lh,{AgentRunner:()=>Ws,DIST_DIR:()=>Ke,ensurePluginNodeModulesLink:()=>Dh});import{query as H0}from"@anthropic-ai/claude-agent-sdk";import{resolve as Oe}from"node:path";import{existsSync as Hs,statSync as W0,mkdirSync as Mh,symlinkSync as G0,lstatSync as V0}from"node:fs";import{createRequire as Y0}from"node:module";import{readFile as J0}from"node:fs/promises";function z0(n){return JSON.stringify(Eh(n))}function Q0(n){let e=n;for(let t=0;t<15;t++){let s=Oe(e,"node_modules"),r=Oe(e,"package.json");if(Hs(s)&&Hs(r))return s;let i=Oe(e,"..");if(i===e)break;e=i}return null}function Dh(n){if(!Da)return;let e=Oe(n,"node_modules");try{V0(e);return}catch{}try{G0(Da,e,"dir"),R.info("Linked plugin node_modules to engine deps",{pluginDir:n,target:Da})}catch(t){R.warn("Failed to link plugin node_modules",{pluginDir:n,error:String(t)})}}function J(n){let e=X0[n];if(e){let t=Oe(Ke,"mcp",e);if(Hs(t))return t}return Oe(Ke,n)}var R,Ke,Da,X0,Ws,La=j(()=>{"use strict";gr();M();Ne();pr();ls();kr();xa();_r();Nh();Oh();R=k("agent-runner");Ke=Hs(Oe(import.meta.dirname,"mcp"))?import.meta.dirname:Oe(import.meta.dirname,"..");Da=Q0(Ke);X0={"memory/memory-mcp-server.js":"memory.min.js","memory/structured-memory-mcp-server.js":"structured-memory.min.js","keychain/keychain-mcp-server.js":"keychain.min.js","google/google-mcp-server.js":"google.min.js","quo/quo-mcp-server.js":"quo.min.js","voice/voice-mcp-server.js":"voice.min.js","contacts/contacts-mcp-server.js":"contacts.min.js","tasks/task-mcp-server.js":"task.min.js","resend/resend-mcp-server.js":"resend.min.js","linear/linear-mcp-server.js":"linear.min.js","github/github-issues-mcp-server.js":"github-issues.min.js","clickup/clickup-mcp-server.js":"clickup.min.js","recall/recall-mcp-server.js":"recall.min.js","background/background-task-mcp-server.js":"background-task.min.js","callback/callback-mcp-server.js":"callback.min.js","code-task/code-task-mcp-server.js":"code-task.min.js","search/conversation-search-mcp-server.js":"search-conversation.min.js","code-index/code-search-mcp-server.js":"code-search.min.js","events/event-bus-mcp-server.js":"event-bus.min.js","team/team-mcp-server.js":"team.min.js","workflow/workflow-mcp-server.js":"workflow.min.js","schedule/schedule-mcp-server.js":"schedule.min.js","admin/admin-mcp-server.js":"admin.min.js","slack/slack-mcp-server.js":"slack.min.js"};Ws=class n{static registryRef;agentConfig;memoryManager;plugins;skillIndex;activeQuery=null;eventSubscribersJson;prefetcher;_archetypeDef=void 0;constructor(e,t,s=[],r=new Map,i="{}",o){this.agentConfig=e,this.memoryManager=t,this.plugins=s,this.skillIndex=r,this.eventSubscribersJson=i,this.prefetcher=o}async buildSystemPrompt(e,t){let s=[];this.agentConfig.soul&&s.push(this.agentConfig.soul);let r=this.getArchetypeDef();if(r&&this.agentConfig.archetypeConfig)try{let c=r.systemPromptCard({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});c&&s.push(c)}catch(c){R.error("Archetype systemPromptCard threw \u2014 omitting card",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(c)})}s.push(this.agentConfig.systemPrompt);let i=await this.memoryManager.read("shared/constitution.md");i&&s.push(i),s.push(xh({coreServerNames:e,delegateServerNames:t??[],plugins:this.plugins,autoInjectedServers:n.autoInjectedServerNames()}));let o=await this.memoryManager.getHotTierPrompt(this.agentConfig.id,g.memory.hotBudgetTokens);if(o)s.push(o);else{let c=`agents/${this.agentConfig.id}`,d=await this.memoryManager.read(`${c}/memory.md`);d&&s.push(`## Your Memory
164
+ ${d}`);let h=(await this.memoryManager.list(c)).filter(p=>p.endsWith(".md")&&p!=="memory.md");h.length>0&&s.push(`## Available Memory Files
165
+ You have ${h.length} reference file(s) in your memory directory:
166
+ `+h.map(p=>`- ${c}/${p}`).join(`
167
+ `)+"\n\nRead relevant files via the memory MCP server (`memory_read`) before starting tasks that may relate to them.")}let l=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return s.push(`**Current date/time**: ${l} (Pacific Time)`),s.join(`
165
168
 
166
169
  ---
167
170
 
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}
171
+ `)}buildServerConfig(e,t){return this.buildAllServerConfigs(t)[e]}buildAllServerConfigs(e){let t={};if(g.slack.localMcpServer)t.slack={type:"stdio",command:"node",args:[J("slack/slack-mcp-server.js")],env:{HIVE_INTERNAL_URL:`http://127.0.0.1:${g.slackInternal.port}`,HIVE_INTERNAL_TOKEN:g.slackInternal.authToken,HIVE_AGENT_ID:this.agentConfig.id}};else{let c=g.slack.mcpToken;c&&(t.slack={type:"http",url:"https://mcp.slack.com/mcp",headers:{Authorization:`Bearer ${c}`}})}let s=[{id:"self",backing:"mongo"}],r=this.getArchetypeDef();if(r&&this.agentConfig.archetypeConfig)try{let c=r.memoryScopes({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig});for(let d of c)d.id!=="self"&&s.push(d)}catch(c){R.error("Archetype memoryScopes threw \u2014 using self-only",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(c)})}t.memory={type:"stdio",command:"node",args:[J("memory/memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,MEMORY_SCOPES_JSON:JSON.stringify(s)}},t["structured-memory"]={type:"stdio",command:"node",args:[J("memory/structured-memory-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,CHANNEL_ID:e?.channelId??"",THREAD_ID:e?.threadId??"",QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333",OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434"}},t.keychain={type:"stdio",command:"node",args:[J("keychain/keychain-mcp-server.js")],env:{KEYCHAIN_SERVICE:`hive/${g.instance.id}`}};let i=g.google.accounts[this.agentConfig.id]||g.google.account,o=g.google.client;if(t.google={type:"stdio",command:"node",args:[J("google/google-mcp-server.js")],env:{...i?{GOG_ACCOUNT:i}:{},...o?{GOG_CLIENT:o}:{},DRIVE_SHARED_FOLDER:g.google.sharedFolder,INSTANCE_ID:g.instance.id,PATH:process.env.PATH??""}},g.quo.apiKey&&(t.quo={type:"stdio",command:"node",args:[J("quo/quo-mcp-server.js")],env:{QUO_API_KEY:g.quo.apiKey,...g.quo.phoneNumberId?{QUO_PHONE_NUMBER_ID:g.quo.phoneNumberId}:{},QUO_LINES_JSON:JSON.stringify(g.quo.lines)}}),g.voice.enabled&&g.voice.apiKey){let c=Object.entries(g.voice.assistants).find(([d,u])=>u===this.agentConfig.id)?.[0]??"";t.voice={type:"stdio",command:"node",args:[J("voice/voice-mcp-server.js")],env:{VAPI_API_KEY:g.voice.apiKey,VAPI_PHONE_NUMBER_ID:g.voice.phoneNumberId,VAPI_ASSISTANT_ID:c,AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name}}}t.contacts={type:"stdio",command:"node",args:[J("contacts/contacts-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}};let a=g.taskLedger.agentKeys[this.agentConfig.id]??g.taskLedger.apiKey;if(a&&(t.tasks={type:"stdio",command:"node",args:[J("tasks/task-mcp-server.js")],env:{TASK_LEDGER_API_URL:g.taskLedger.apiUrl,TASK_LEDGER_API_KEY:a}}),g.brave.apiKey&&(t["brave-search"]={type:"stdio",command:"node",args:[Y0(import.meta.url).resolve("brave-search-mcp/dist/index.js")],env:{BRAVE_API_KEY:g.brave.apiKey}}),g.resend.apiKey){let c=this.agentConfig.name.toLowerCase(),d=g.resend.emailDomain,u=g.resend.businessName?` (${g.resend.businessName})`:"",h=d?`${this.agentConfig.name}${u} <${c}@${d}>`:g.resend.fromAddress;t.resend={type:"stdio",command:"node",args:[J("resend/resend-mcp-server.js")],env:{RESEND_API_KEY:g.resend.apiKey,RESEND_FROM_ADDRESS:h,RESEND_DEFAULT_CC:g.resend.defaultCc,RESEND_DEFAULT_BCC:g.resend.defaultBcc}}}if(g.linear.apiKey){let c={LINEAR_API_KEY:g.linear.apiKey};g.linear.teamId&&(c.LINEAR_TEAM_ID=g.linear.teamId),t.linear={type:"stdio",command:"node",args:[J("linear/linear-mcp-server.js")],env:c}}if(g.github.repo){let c={GITHUB_REPO:g.github.repo,PATH:process.env.PATH??""};g.github.token&&(c.GH_TOKEN=g.github.token),t["github-issues"]={type:"stdio",command:"node",args:[J("github/github-issues-mcp-server.js")],env:c}}if(g.clickup.apiToken&&(t.clickup={type:"stdio",command:"node",args:[J("clickup/clickup-mcp-server.js")],env:{CLICKUP_API_TOKEN:g.clickup.apiToken}}),g.recall.apiKey&&(t.recall={type:"stdio",command:"node",args:[J("recall/recall-mcp-server.js")],env:{RECALL_API_KEY:g.recall.apiKey,RECALL_API_REGION:g.recall.region,RECALL_WEBHOOK_SECRET:g.recall.webhookSecret,MEETING_MONITOR_API:`http://127.0.0.1:${g.recall.monitorPort}`,MEETING_MONITOR_PUBLIC_URL:g.recall.monitorPublicUrl,RECALL_AGENT_ID:this.agentConfig.id,RECALL_ADAPTER_ID:e?.adapterId??"",RECALL_CHANNEL_ID:e?.channelId??"",RECALL_CHANNEL_KIND:e?.channelKind??"internal",RECALL_CHANNEL_LABEL:e?.channelLabel??"",RECALL_THREAD_ID:e?.threadId??"",RECALL_SLACK_TS:e?.slackTs??"",RECALL_SLACK_THREAD_TS:e?.slackThreadTs??""}}),g.browser.cdpEndpoint){let c=xc(this.agentConfig.id,V);Mh(c,{recursive:!0}),t.browser={type:"stdio",command:"npx",args:["@playwright/mcp@latest","--cdp-endpoint",g.browser.cdpEndpoint,"--output-dir",c,"--user-data-dir",Oe(c,"user-data")],env:{PATH:process.env.PATH??"",HOME:process.env.HOME??""}}}t.background={type:"stdio",command:"node",args:[J("background/background-task-mcp-server.js")],env:{BG_TASK_API:`http://127.0.0.1:${g.background.port}`,BG_AUTH_TOKEN:g.background.authToken,BG_AGENT_ID:this.agentConfig.id,BG_ADAPTER_ID:e?.adapterId??"",BG_CHANNEL_ID:e?.channelId??"",BG_CHANNEL_KIND:e?.channelKind??"internal",BG_CHANNEL_LABEL:e?.channelLabel??"",BG_THREAD_ID:e?.threadId??"",BG_SLACK_TS:e?.slackTs??"",BG_SLACK_THREAD_TS:e?.slackThreadTs??""}},t.callback={type:"stdio",command:"node",args:[J("callback/callback-mcp-server.js")],env:{CB_AGENT_ID:this.agentConfig.id,CB_ADAPTER_ID:e?.adapterId??"",CB_CHANNEL_ID:e?.channelId??"",CB_CHANNEL_KIND:e?.channelKind??"internal",CB_CHANNEL_LABEL:e?.channelLabel??"",CB_THREAD_ID:e?.threadId??"",CB_SLACK_TS:e?.slackTs??"",CB_SLACK_THREAD_TS:e?.slackThreadTs??"",MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}},t["code-task"]={type:"stdio",command:"node",args:[J("code-task/code-task-mcp-server.js")],env:{CT_TASK_API:`http://127.0.0.1:${g.codeTask.port}`,CT_AUTH_TOKEN:g.codeTask.authToken,CT_AGENT_ID:this.agentConfig.id,CT_ADAPTER_ID:e?.adapterId??"",CT_CHANNEL_ID:e?.channelId??"",CT_CHANNEL_KIND:e?.channelKind??"internal",CT_CHANNEL_LABEL:e?.channelLabel??"",CT_THREAD_ID:e?.threadId??"",CT_SLACK_TS:e?.slackTs??"",CT_SLACK_THREAD_TS:e?.slackThreadTs??""}};let l={OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434",QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333"};process.env.KB_EMBED_MODEL&&(l.KB_EMBED_MODEL=process.env.KB_EMBED_MODEL),t["conversation-search"]={type:"stdio",command:"node",args:[J("search/conversation-search-mcp-server.js")],env:{...l,AGENT_ID:this.agentConfig.id,DEFAULT_AGENT:g.defaultAgent}},t["code-search"]={type:"stdio",command:"node",args:[J("code-index/code-search-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,QDRANT_URL:process.env.QDRANT_URL??"http://localhost:6333",OLLAMA_URL:process.env.OLLAMA_URL??"http://localhost:11434"}};for(let c of this.plugins)for(let[d,u]of Object.entries(c.manifest.mcpServers)){if(t[d]){R.warn("Plugin server name conflicts with core server, skipping",{plugin:c.name,server:d});continue}if(c.brokenServers[d])continue;let h=Ks(c.name,u.entry,{hiveHome:V,distDir:Ke});if("reason"in h){R.error("Plugin MCP server unresolvable at spawn time",{plugin:c.name,server:d,reason:h.reason,pathsChecked:h.pathsChecked});continue}let p=h.path;Dh(c.dir);let m=g.taskLedger.agentKeys[this.agentConfig.id]??g.taskLedger.apiKey,f={AGENT_ID:this.agentConfig.id,AGENT_NAME:this.agentConfig.name,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,TASK_LEDGER_API_URL:g.taskLedger.apiUrl,...m?{TASK_LEDGER_API_KEY:m}:{},PATH:process.env.PATH??"",HOME:process.env.HOME??""};for(let y of u.env??[])process.env[y]&&(f[y]=process.env[y]);for(let y of u.secretEnv??[]){let w=process.env[y]||zt(g.instance.id,y);w&&(f[y]=w)}for(let[y,w]of Object.entries(u.envMap??{}))f[w]&&(f[y]=f[w]);for(let[y,w]of Object.entries(u.agentEnv??{}))f[y]=n.resolveAgentEnvPath(this.agentConfig,w);t[d]={type:"stdio",command:"node",args:[p],env:f}}return t["event-bus"]={type:"stdio",command:"node",args:[J("events/event-bus-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}},n.registryRef||R.warn("registryRef not set \u2014 agents will get empty AGENT_IDS for team server"),t.team={type:"stdio",command:"node",args:[J("team/team-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,AGENT_IDS:JSON.stringify(n.registryRef?.getAll().map(c=>c.id)??[])}},g.workflow.enabled&&(t.workflow={type:"stdio",command:"node",args:[J("workflow/workflow-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,EVENT_SUBSCRIBERS:this.eventSubscribersJson}}),t.schedule={type:"stdio",command:"node",args:[J("schedule/schedule-mcp-server.js")],env:{AGENT_ID:this.agentConfig.id,MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName}},t.admin={type:"stdio",command:"node",args:[J("admin/admin-mcp-server.js")],env:{MONGODB_URI:g.mongo.uri,MONGODB_DB:g.mongo.dbName,AGENT_ID:this.agentConfig.id,INSTANCE_CAPABILITIES:z0(this.plugins)}},t}filterCoreServers(e){let t={...e},s=new Set(this.agentConfig.coreServers);s.has("memory")&&s.add("structured-memory"),s.add("schedule"),s.add("team"),s.add("slack"),g.workflow.enabled&&s.add("workflow");for(let r of Object.keys(t))s.has(r)||delete t[r];if(!this.agentConfig.autonomy.externalComms)for(let r of["resend","quo"])t[r]&&(R.debug("Autonomy: externalComms disabled \u2014 removing server",{server:r,agent:this.agentConfig.id}),delete t[r]);return this.agentConfig.autonomy.codeTask||t["code-task"]&&(R.debug("Autonomy: codeTask disabled \u2014 removing server",{server:"code-task",agent:this.agentConfig.id}),delete t["code-task"]),this.agentConfig.autonomy.codeAccess||t["code-search"]&&(R.debug("Autonomy: codeAccess disabled \u2014 removing server",{server:"code-search",agent:this.agentConfig.id}),delete t["code-search"]),t}static resolveAgentEnvPath(e,t){let s=t.split("."),r=e;for(let i of s){if(r==null||typeof r!="object")return"";r=r[i]}return r==null?"":String(r)}static autoInjectedServerNames(){let e=new Set(["schedule","team","slack"]);return g.workflow.enabled&&e.add("workflow"),e}static CONTEXT_DEPENDENT_SERVERS=new Set(["callback","background","code-task","recall","structured-memory","memory"]);buildDelegateAgents(e){let t=this.agentConfig.delegateServers;if(t.length===0)return{};let s={},r=new Set;this.agentConfig.autonomy.externalComms||(r.add("resend"),r.add("quo")),this.agentConfig.autonomy.codeTask||r.add("code-task"),this.agentConfig.autonomy.codeAccess||r.add("code-search");for(let i of t){if(r.has(i)){R.debug("Autonomy gate \u2014 skipping delegate server",{server:i,agent:this.agentConfig.id});continue}n.CONTEXT_DEPENDENT_SERVERS.has(i)&&R.warn("Context-dependent server in delegateServers \u2014 subagent won't have channel context",{agent:this.agentConfig.id,server:i});let o=e[i];if(!o){R.warn("Delegate server not found in configs, skipping",{agent:this.agentConfig.id,server:i});continue}let a=this.getServerCatalogEntry(i).description,l=this.agentConfig.delegatePrompts?.[i],c=l||`You are a tool specialist for ${i}. Execute the requested task using your available tools. Return results concisely. Do not add commentary or explanation beyond what was asked.`;s[i]={description:a,prompt:c,mcpServers:[{[i]:o}],model:"inherit",maxTurns:l?7:10,disallowedTools:["Agent"]},l&&R.info("Intent-aware delegate prompt loaded",{agent:this.agentConfig.id,server:i,promptLength:l.length})}return s}getServerCatalogEntry(e){if(It[e])return It[e];for(let t of this.plugins){let s=t.manifest.mcpServers[e];if(s?.description)return{description:s.description,usage:s.usage,notFor:s.notFor}}return{description:e}}buildSdkPlugins(){let e=this.agentConfig.plugins;if(!e?.length)return[];let t=[],s=Oe(Ke,"..","plugins","claude-code");for(let r of e){if(r.includes("/")||r.includes("\\")||r===".."||r.startsWith(".")){R.warn("Invalid plugin name, skipping",{plugin:r,agent:this.agentConfig.id});continue}let i=Oe(s,r);if(!Hs(i)){R.warn("Plugin not found, skipping",{plugin:r,expected:i,agent:this.agentConfig.id});continue}t.push({type:"local",path:i})}return t.length>0&&R.debug("Loaded plugins for agent",{agent:this.agentConfig.id,plugins:t.map(r=>r.path)}),t}buildNativeSkills(){return Ch(this.skillIndex,this.agentConfig.id)}getArchetypeDef(){return this._archetypeDef===void 0&&(this._archetypeDef=this.agentConfig.archetype?mr(this.agentConfig.archetype)??null:null,this.agentConfig.archetype&&!this._archetypeDef&&R.warn("Archetype referenced by agent not registered \u2014 running unstructured",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype})),this._archetypeDef}buildHooks(e){let t={PreCompact:this.buildPreCompactMatcher()},s=this.getArchetypeDef();if(s&&this.agentConfig.archetypeConfig)try{let r=s.preToolUseHooks({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:e});r.length>0&&(t.PreToolUse=r)}catch(r){R.error("Archetype preToolUseHooks threw \u2014 installing deny-all PreToolUse hook",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(r)}),t.PreToolUse=[{hooks:[async()=>({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Archetype hook initialization failed (${String(r)}). All tool calls blocked until the archetype is fixed.`}})]}]}return t}buildPreCompactMatcher(){let e=this.agentConfig.name,t=this.agentConfig.id,s=this.prefetcher;return[{hooks:[async(r,i,o)=>{R.info("PreCompact hook fired",{agent:t});let a=[`You are ${e} (agent ID: ${t}). When summarizing this conversation for compaction:`,"- Preserve your identity, role, and any behavioral instructions from your system prompt","- Keep all customer/contact names, deal details, and reference numbers","- Retain every decision made and commitment given \u2014 who decided what, and why","- Preserve active workflows: what's in progress, what's pending, next steps","- Keep tool call results that informed decisions (not raw API responses)","- Discard pleasantries, thinking-out-loud, and intermediate failed attempts"].join(`
172
+ `),l="";if(s&&r?.transcript_path)try{let d=await J0(r.transcript_path,"utf-8");if(d.length>0){let h=d.length>2e5?d.slice(-2e5):d;l=await s.getCompactionContext(h,t)}}catch(d){R.warn("Code context extraction failed during compaction \u2014 proceeding without",{agent:t,error:String(d)})}return{continue:!0,systemMessage:l?`${a}
170
173
 
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,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
- ${l}`});return{textContent:br(o.join(`
174
+ ${l}`:a}}]}]}async send(e,t,s,r,i,o){let a=i??this.agentConfig.model;R.info("Sending prompt to agent",{agent:this.agentConfig.id,model:a,modelOverride:!!i,resumeSession:t??"new",promptLength:e.length,streaming:!!s});let l=this.buildAllServerConfigs(r),c=this.filterCoreServers(l),d=this.buildDelegateAgents(l),u=await this.buildSystemPrompt(Object.keys(c),Object.keys(d)),h=[...this.buildSdkPlugins(),...this.buildNativeSkills()];Object.keys(d).length>0&&R.info("Delegate subagents configured",{agent:this.agentConfig.id,delegates:Object.keys(d)});let p={},m=this.getArchetypeDef();if(m&&this.agentConfig.archetypeConfig)try{p=m.sessionOptions({agentConfig:this.agentConfig,archetypeConfig:this.agentConfig.archetypeConfig,workItemContext:r})}catch(Y){R.error("Archetype sessionOptions threw \u2014 ignoring",{agent:this.agentConfig.id,archetype:this.agentConfig.archetype,error:String(Y)})}let f=typeof p.cwd=="string"?"archetype":"default",y=f==="archetype"?p.cwd:pn(this.agentConfig.id,V);if(f==="default")Mh(y,{recursive:!0});else{let Y;try{Y=W0(y)}catch(L){let P=`Archetype cwd unavailable at session start \u2014 refusing to run: ${y} (${String(L)})`;throw R.error(P,{agent:this.agentConfig.id}),new Error(P)}if(!Y.isDirectory()){let L=`Archetype cwd is not a directory: ${y}`;throw R.error(L,{agent:this.agentConfig.id}),new Error(L)}}let w=H0({prompt:e,options:{model:a,systemPrompt:u,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:o?.maxTurns??this.agentConfig.maxTurns,maxBudgetUsd:o?.budgetUsd??this.agentConfig.budgetUsd,cwd:y,settingSources:p.settingSources??[],includePartialMessages:!!s,...t?{resume:t}:{},...Object.keys(c).length>0?{mcpServers:c}:{},...Object.keys(d).length>0?{agents:d}:{},...h.length>0?{plugins:h}:{},hooks:this.buildHooks(r),...this.agentConfig.betas?.length?{betas:this.agentConfig.betas}:{},env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});this.activeQuery=w;let S="",_=t??"",v=0,I=0,N=!1,D;this._aborted=!1;let A=0,E=0,G=0,W=0,$=0,le=0,Ie,ge=[],ln=null,os=null,mt=o?.timeoutMs??this.agentConfig.timeoutMs??3e5,Ti=setTimeout(()=>{R.warn("Agent query timed out, aborting",{agent:this.agentConfig.id,timeoutMs:mt}),this.abort()},mt);try{for await(let Y of w){let L=Y;if(L.type==="system"&&L.subtype==="init"&&(_=L.session_id,R.debug("Session initialized",{sessionId:_})),L.type==="system"&&L.subtype==="compact_boundary"){let P=L.compact_metadata;le++,Ie=P?.pre_tokens,R.info("Context compacted",{agent:this.agentConfig.id,trigger:P?.trigger,preTokens:P?.pre_tokens,compactionNumber:le})}if(L.type==="system"&&L.subtype==="status"&&L.status==="compacting"&&R.info("Compaction in progress",{agent:this.agentConfig.id}),L.type==="stream_event"&&s){let P=L.event;P?.type==="content_block_delta"&&P?.delta?.type==="text_delta"&&(s(P.delta.text),N=!0)}if(L.type==="tool_progress"){let P=L;R.info("Tool in progress",{agent:this.agentConfig.id,tool:P.tool_name,elapsed:P.elapsed_time_seconds})}if(L.type==="assistant"){let P=L.message?.content;if(Array.isArray(P))for(let de of P)de.type==="text"?S=de.text:de.type==="tool_use"&&(os&&ge.length>0&&(ge[ge.length-1].endMs=Date.now()),os=de.name,ln=Date.now(),ge.push({tool:de.name,startMs:ln}),R.info("Tool call started",{agent:this.agentConfig.id,tool:de.name}));L.session_id&&(_=L.session_id)}if(L.type==="result"){let P=L;v=P.total_cost_usd,I=P.duration_ms,_=P.session_id;let de=P.usage;de&&(A=de.input_tokens??0,E=de.output_tokens??0,G=de.cache_read_input_tokens??0,W=de.cache_creation_input_tokens??0);let un=P.modelUsage;if(un)for(let Pt of Object.values(un))Pt.contextWindow&&Pt.contextWindow>$&&($=Pt.contextWindow);P.subtype==="success"?S=P.result||S:(D=P.subtype,"errors"in P&&Array.isArray(P.errors)&&(D=P.errors.join("; ")))}}}catch(Y){let L=String(Y);S&&v>0?R.warn("Agent process crashed after producing response \u2014 using response anyway",{agent:this.agentConfig.id,error:L,resultPreview:S.slice(0,200),costUsd:v,durationMs:I}):(D=L,R.error("Agent query failed",{agent:this.agentConfig.id,error:L,costUsd:v,durationMs:I}))}finally{clearTimeout(Ti),this.activeQuery=null}os&&ge.length>0&&(ge[ge.length-1].endMs=Date.now());let Qe={};for(let Y of ge){let L=(Y.endMs??Date.now())-Y.startMs,P=Y.tool.includes("__")?Y.tool.split("__")[1]:Y.tool;Qe[P]||(Qe[P]={count:0,totalMs:0}),Qe[P].count++,Qe[P].totalMs+=L}let dn=Object.entries(Qe).sort((Y,L)=>L[1].totalMs-Y[1].totalMs).map(([Y,L])=>`${Y}:${L.count}x/${(L.totalMs/1e3).toFixed(1)}s`).join(", "),Be=ge.reduce((Y,L)=>Y+((L.endMs??Date.now())-L.startMs),0),as=I-Be;return R.info("Agent response complete",{agent:this.agentConfig.id,sessionId:_,costUsd:v,durationMs:I,llmMs:as,toolMs:Be,toolCalls:ge.length,toolSummary:dn||"none",inputTokens:A,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:le,preCompactTokens:Ie,streamed:N,hasError:!!D}),{text:S,sessionId:_,costUsd:v,durationMs:I,llmMs:as,toolMs:Be,toolCalls:ge.length,toolSummary:dn||"none",streamed:N,inputTokens:A,outputTokens:E,cacheReadTokens:G,cacheCreationTokens:W,contextWindow:$,compactions:le,preCompactTokens:Ie,error:D,aborted:this._aborted}}_aborted=!1;get wasAborted(){return this._aborted}abort(){this.activeQuery&&(R.info("Aborting active query",{agent:this.agentConfig.id}),this._aborted=!0,this.activeQuery.close(),this.activeQuery=null)}}});import{writeFileSync as $a,mkdirSync as Z0}from"node:fs";import{join as Tr,extname as Ra}from"node:path";import{tmpdir as ek}from"node:os";function Rh(n){Pa=n}async function Bh(n,e){if(!Pa)return null;try{let t=n.toString("base64"),s=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${Ph}:generateContent?key=${Pa}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({contents:[{parts:[{inline_data:{mime_type:e,data:t}},{text:"Describe this image in detail. If it contains text, extract all of it. If it's a diagram, architecture drawing, or technical image, describe all labels, relationships, and structure. If it's a screenshot of messages or a conversation, transcribe everything. Be thorough."}]}]})});if(!s.ok){let o=await s.text();return ye.warn("Gemini vision error",{status:s.status,error:o.slice(0,200)}),null}let i=(await s.json()).candidates?.[0]?.content?.parts?.[0]?.text;return i&&ye.info("Image described via Gemini",{model:Ph,chars:i.length}),i||null}catch(t){return ye.warn("Gemini vision failed",{error:t.message}),null}}async function Uh(n,e,t){let s=Ra(e).slice(1).toLowerCase();if(tk.has(s)||t.startsWith("text/"))return{textContent:vr(n.toString("utf-8")),isImage:!1};if(s==="pdf"||t==="application/pdf")try{let r=await import("pdf-parse"),o=await(r.default??r)(n);return{textContent:vr(o.text),isImage:!1}}catch(r){return ye.warn("PDF parse failed",{name:e,error:r.message}),{textContent:"[PDF \u2014 could not extract text]",isImage:!1}}if(s==="docx"||t==="application/vnd.openxmlformats-officedocument.wordprocessingml.document")try{let i=await(await import("mammoth")).extractRawText({buffer:n});return{textContent:vr(i.value),isImage:!1}}catch(r){return ye.warn("DOCX parse failed",{name:e,error:r.message}),{textContent:"[DOCX \u2014 could not extract text]",isImage:!1}}if(s==="xlsx"||s==="xls"||t.includes("spreadsheet"))try{let r=await import("xlsx"),i=r.read(n,{type:"buffer"}),o=i.SheetNames.map(a=>{let l=r.utils.sheet_to_csv(i.Sheets[a]);return`--- Sheet: ${a} ---
175
+ ${l}`});return{textContent:vr(o.join(`
173
176
 
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?"":`
177
+ `)),isImage:!1}}catch(r){return ye.warn("XLSX parse failed",{name:e,error:r.message}),{textContent:"[Spreadsheet \u2014 could not extract content]",isImage:!1}}return null}async function jh(n,e){let t=n.url_private_download||n.url_private;if(!t)return ye.warn("No download URL for file",{id:n.id,name:n.name}),null;try{ye.info("Downloading file",{id:n.id,url:t.slice(0,80),mimetype:n.mimetype});let s=await fetch(t,{headers:{Authorization:`Bearer ${e}`},redirect:"manual"});if(s.status===302||s.status===301){let d=s.headers.get("location");d&&(ye.info("Following redirect",{id:n.id}),s=await fetch(d))}if(!s.ok)return ye.error("Failed to download file",{id:n.id,status:s.status}),null;let r=Buffer.from(await s.arrayBuffer());if(r.length<100&&r.length>0){let d=r.toString("utf-8").trim();if(d.includes("requested")&&d.includes("file")&&d.includes("not found"))return ye.error("Slack file error response",{id:n.id,name:n.name,errorText:d,bufferSize:r.length}),null}let i=n.name.replace(/[^a-zA-Z0-9._-]/g,"_"),o=Tr(Ir,`${n.id}-${i}`);$a(o,r);let a=Ra(n.name).slice(1).toLowerCase();if($h.has(a)||n.mimetype.startsWith("image/")){let d=await Bh(r,n.mimetype);return{name:n.name,mimetype:n.mimetype,size:n.size,localPath:o,textContent:d??"[Image \u2014 could not extract description]",isImage:!0}}let c=await Uh(r,n.name,n.mimetype);return c?{name:n.name,mimetype:n.mimetype,size:n.size,localPath:o,...c}:(ye.info("Unsupported file type",{name:n.name,ext:a,mimetype:n.mimetype}),{name:n.name,mimetype:n.mimetype,size:n.size,localPath:o,textContent:null,isImage:!1})}catch(s){return ye.error("File processing failed",{id:n.id,name:n.name,error:s.message}),null}}async function Gs(n,e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_"),r=Tr(Ir,`ws-${Date.now()}-${s}`);$a(r,n);let i=await Bh(n,t);return{name:e,mimetype:t,size:n.length,localPath:r,textContent:i??"[Image \u2014 could not extract description]",isImage:!0}}async function qh(n,e,t){let s=e.replace(/[^a-zA-Z0-9._-]/g,"_"),r=Tr(Ir,`team-${Date.now()}-${s}`);$a(r,n);let i=Ra(e).slice(1).toLowerCase();if($h.has(i)||t.startsWith("image/"))return Gs(n,e,t);let a=await Uh(n,e,t);return a?{name:e,mimetype:t,size:n.length,localPath:r,...a}:{name:e,mimetype:t,size:n.length,localPath:r,textContent:null,isImage:!1}}function Fh(n){return n.length===0?"":`
175
178
 
176
- `+r.map(t=>{let s=`\u{1F4CE} File: ${t.name} (${Rh(t.size)}, ${t.mimetype})`;return t.isImage?t.textContent?`${s}
179
+ `+n.map(t=>{let s=`\u{1F4CE} File: ${t.name} (${Kh(t.size)}, ${t.mimetype})`;return t.isImage?t.textContent?`${s}
177
180
  --- image description ---
178
181
  ${t.textContent}
179
182
  --- end image description ---`:`${s}
@@ -184,16 +187,16 @@ ${t.textContent}
184
187
  Saved at: ${t.localPath}
185
188
  (Content could not be extracted \u2014 file available for download)`}).join(`
186
189
 
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)+`
190
+ `)}function Kh(n){return n<1024?`${n} B`:n<1024*1024?`${(n/1024).toFixed(1)} KB`:`${(n/(1024*1024)).toFixed(1)} MB`}function vr(n,e=5e4){return n.length<=e?n:n.slice(0,e)+`
188
191
 
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:**
192
+ [... truncated at ${Kh(e)} \u2014 full file at local path]`}var ye,Ir,$h,Pa,Ph,tk,Vs=j(()=>{"use strict";M();ye=k("file-processor"),Ir=Tr(ek(),"hive-slack-files");Z0(Ir,{recursive:!0});$h=new Set(["png","jpg","jpeg","gif","webp","bmp","heic"]),Pa="",Ph=process.env.GEMINI_VISION_MODEL||"gemini-2.5-flash";tk=new Set(["csv","tsv","txt","text","md","markdown","json","xml","html","yaml","yml","log"])});async function He(n,e){let t=await fetch(`${n}/api/embed`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:ak,input:e})});if(!t.ok)throw new Error(`Ollama embed ${t.status}: ${await t.text()}`);return(await t.json()).embeddings[0]}var ak,Er=j(()=>{"use strict";ak=process.env.KB_EMBED_MODEL??"bge-large"});var Wa,aN,bf=j(()=>{"use strict";Wa="code_index",aN=Buffer.from("6ba7b8109dad11d180b400c04fd430c8","hex")});var _f={};Ue(_f,{CodeIndexPrefetcher:()=>Ga});import{QdrantClient as Mb}from"@qdrant/js-client-rest";var Ga,vf=j(()=>{"use strict";Er();bf();Ga=class{options;qdrant;connected=!1;scoreThreshold;prefetchLimit;constructor(e){this.options=e,this.scoreThreshold=e.scoreThreshold??.65,this.prefetchLimit=e.prefetchLimit??8}async ensureConnected(){this.connected||(this.qdrant=new Mb({url:this.options.qdrantUrl}),this.connected=!0)}async getContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],r;try{r=await He(this.options.ollamaUrl,e)}catch{return""}try{let o=(await this.qdrant.search(Wa,{vector:r,limit:this.prefetchLimit,with_payload:!0})).filter(a=>a.score>=this.scoreThreshold);if(o.length>0){let a=o.map(l=>{let c=l.payload;return`- **${c.repo}:${c.filePath}** \u2014 ${c.summary} (${c.role})`});s.push(`**Relevant files:**
190
193
  `+a.join(`
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:**
194
+ `))}}catch{}if(t)try{let o=(await this.qdrant.search("agent_memory",{vector:r,limit:15,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(a=>a.score>=this.scoreThreshold).filter(a=>typeof a.payload?.topic=="string"&&a.payload.topic.startsWith("code:"));if(o.length>0){let a=o.map(l=>l.payload?.mongoId).filter(Boolean);if(a.length>0){let l=this.options.db.collection("agent_memory"),{ObjectId:c}=await import("mongodb"),d=await l.find({_id:{$in:a.map(u=>new c(u))}}).toArray();if(d.length>0){let u=d.map(h=>`- ${String(h.topic??"").replace(/^code:/,"")}: ${String(h.content??"")}`);s.push(`**Previous session insights:**
192
195
  `+u.join(`
193
196
  `))}}}}catch{}return s.length===0?"":["## Codebase Context (auto-retrieved)",...s,"","_Results may be stale \u2014 verify by reading files._"].join(`
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 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
- [...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
+ `)}extractFilePaths(e){let t=/(?:^|\s|`|"|')((src|plugins|dist|docs|scripts|setup|skills|service|agents-templates|test)\/.{1,200}\.(ts|tsx|js|jsx|json|yaml|yml|md))\b/gm,s=new Set,r;for(;(r=t.exec(e))!==null;)s.add(r[1]);return[...s]}async getCompactionContext(e,t){try{await this.ensureConnected()}catch{return""}let s=[],r=[],i=new Set;try{let c=this.extractFilePaths(e);if(c.length>0){let u=await this.options.db.collection("code_index").find({filePath:{$in:c}}).project({repo:1,filePath:1,summary:1,role:1}).toArray();for(let h of u){let p=`${h.repo}:${h.filePath}`;i.has(p)||(i.add(p),s.push(`- ${p} \u2014 ${h.summary} [${h.role}]`))}}}catch{}try{let c=e.slice(-2e3),d=await He(this.options.ollamaUrl,c),u=await this.qdrant.search(Wa,{vector:d,limit:this.prefetchLimit,with_payload:!0});for(let h of u){if(h.score<this.scoreThreshold)continue;let p=h.payload,m=`${p.repo}:${p.filePath}`;i.has(m)||(i.add(m),s.push(`- ${m} \u2014 ${p.summary} [${p.role}]`))}if(t){let p=(await this.qdrant.search("agent_memory",{vector:d,limit:10,with_payload:!0,filter:{must:[{key:"agentId",match:{value:t}}]}})).filter(m=>m.score>=this.scoreThreshold).filter(m=>typeof m.payload?.topic=="string"&&m.payload.topic.startsWith("code:"));if(p.length>0){let m=p.map(f=>f.payload?.mongoId).filter(Boolean);if(m.length>0){let{ObjectId:f}=await import("mongodb"),w=await this.options.db.collection("agent_memory").find({_id:{$in:m.map(S=>new f(S))}}).toArray();for(let S of w){let _=String(S.topic??"").replace(/^code:/,""),v=String(S.content??"");r.push(`- ${_}: ${v}`)}}}}}catch{}if(s.length===0&&r.length===0)return"";let o=s.slice(0,10),a=[];o.length>0&&a.push("Files actively referenced in this conversation:",...o,"Preserve references to these files and any decisions made about them.");let l=r.slice(0,10);return l.length>0&&a.push("","Code insights from prior sessions:",...l,"Preserve these insights if relevant to the conversation."),a.join(`
198
+ `)}async close(){}}});var Tf={};Ue(Tf,{KnowledgeExtractor:()=>Va});import Db from"@anthropic-ai/sdk";var Lb,Va,If=j(()=>{"use strict";M();Lb=k("knowledge-extractor"),Va=class{memoryStore;memoryEmbedder;anthropic;constructor(e,t){this.memoryStore=e,this.memoryEmbedder=t,this.anthropic=new Db}async extract(e,t){if(!t?.result)return 0;let s=t.result.length>3e4?t.result.slice(0,3e4)+`
199
+ [...truncated]`:t.result,r=await this.anthropic.messages.create({model:"claude-haiku-4-5-20251001",max_tokens:4096,messages:[{role:"user",content:`Extract code insights from this completed coding session. For each source file the session read or modified, note:
197
200
  - filePath: the relative file path
198
201
  - repo: which repository this file belongs to, inferred from the working directory or file paths
199
202
  - insight: what was learned \u2014 what the file does, key patterns, gotchas, architectural decisions. Be specific and useful for a future session working on the same code.
@@ -202,48 +205,48 @@ ${t.textContent}
202
205
  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
206
 
204
207
  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 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:
208
+ ${s}`}]}),o=(r.content[0].type==="text"?r.content[0].text:"").match(/\[[\s\S]*\]/);if(!o)return 0;let a;try{a=JSON.parse(o[0])}catch{return 0}let l=0;for(let c of a){if(!c.filePath||!c.insight)continue;let d=`code:${c.repo??"unknown"}:${c.filePath}`;try{let u=this.memoryStore.getCollection(),h=await u.find({agentId:e,topic:d,pinned:{$ne:!0}}).toArray();for(let y of h)y.qdrantPointId&&await this.memoryEmbedder.remove(y.qdrantPointId).catch(()=>{});h.length>0&&await u.deleteMany({_id:{$in:h.map(y=>y._id)}});let p={content:c.insight,type:"fact",topic:d,importance:c.wasModified?"high":"medium"},m=crypto.randomUUID(),f=await this.memoryStore.save(e,p,m);await this.memoryEmbedder.upsert(m,c.insight,{agentId:e,mongoId:f._id.toString(),type:"fact",topic:d,tier:"hot",importance:p.importance,createdAt:Date.now()}),l++}catch(u){Lb.error("Failed to save insight",{topic:d,error:String(u)})}}return l}}});function Af(n,e){let t=[n,e].sort();return`dm:${t[0]}:${t[1]}`}var Cf=j(()=>{"use strict"});var Ef={};Ue(Ef,{TeamStore:()=>Ja});import{ObjectId as Pb}from"mongodb";var Ya,Ja,Nf=j(()=>{"use strict";M();Cf();Ya=k("team-store"),Ja=class{db;channels;messages;constructor(e){this.db=e}async init(){this.channels=this.db.collection("team_channels"),this.messages=this.db.collection("team_messages"),await this.channels.createIndex({type:1}),await this.channels.createIndex({members:1}),await this.messages.createIndex({channelId:1,createdAt:-1}),await this.messages.createIndex({threadId:1}),await this.messages.createIndex({createdAt:-1}),Ya.info("Team store connected",{db:this.db.databaseName})}async getChannel(e){return this.channels.findOne({_id:e,archived:{$ne:!0}})}async listChannels(e){let t={archived:{$ne:!0}};return e&&(t.members=e),this.channels.find(t).sort({updatedAt:-1}).toArray()}async createChannel(e){return await this.channels.insertOne(e),Ya.info("Channel created",{id:e._id,type:e.type}),e}async getOrCreateDm(e,t,s){let r=Af(e,t),i=await this.channels.findOne({_id:r});if(i)return i;let o={_id:r,type:"dm",name:s?`DM with ${s}`:`DM: ${e} & ${t}`,members:[e,t].sort(),createdBy:e,createdAt:new Date,updatedAt:new Date,archived:!1};return await this.channels.insertOne(o),Ya.info("DM created",{id:r,members:o.members}),o}async joinChannel(e,t){return(await this.channels.updateOne({_id:e,archived:{$ne:!0}},{$addToSet:{members:t},$set:{updatedAt:new Date}})).modifiedCount>0}async leaveChannel(e,t){return(await this.channels.updateOne({_id:e},{$pull:{members:t},$set:{updatedAt:new Date}})).modifiedCount>0}async archiveChannel(e){return(await this.channels.updateOne({_id:e},{$set:{archived:!0,updatedAt:new Date}})).modifiedCount>0}async renameChannel(e,t){return(await this.channels.updateOne({_id:e},{$set:{name:t,updatedAt:new Date}})).modifiedCount>0}async saveMessage(e){let t={...e,_id:new Pb().toHexString()};return await this.messages.insertOne(t),await this.channels.updateOne({_id:e.channelId},{$set:{updatedAt:new Date}}),t}async getHistory(e,t){let s=Math.min(t?.limit??50,100),r={channelId:e};t?.before&&(r._id={$lt:t.before}),t?.threadId&&(r.threadId=t.threadId);let i=await this.messages.find(r).sort({createdAt:-1}).limit(s+1).toArray(),o=i.length>s;return o&&i.pop(),{messages:i.reverse(),hasMore:o}}}});var xf={};Ue(xf,{CommandRegistry:()=>Qa});var za,Qa,Of=j(()=>{"use strict";M();za=k("command-registry"),Qa=class{teamStore;resolveAgent;commands=new Map;constructor(e,t){this.teamStore=e,this.resolveAgent=t,this.registerCoreCommands()}register(e){this.commands.has(e.def.name)&&za.warn("Command already registered, overwriting",{name:e.def.name}),this.commands.set(e.def.name,e),za.info("Command registered",{name:e.def.name,source:e.def.source})}get(e){return this.commands.get(e)}has(e){return this.commands.has(e)}list(){return[...this.commands.values()].map(e=>e.def)}async execute(e,t){let s=this.commands.get(e);if(!s)return{found:!1};try{return{found:!0,result:await s.execute(t)}}catch(r){return za.error("Command execution failed",{name:e,error:String(r)}),{found:!0,result:`Command failed: ${String(r)}`}}}registerCoreCommands(){this.register({def:{name:"help",source:"core",description:"List available commands"},execute:async()=>`Available commands:
206
209
  ${this.list().map(s=>` /${s.name} \u2014 ${s.description}`).join(`
207
210
  `)}`}),this.register({def:{name:"dm",source:"core",description:"Open or create a DM with an agent",args:[{name:"agent",required:!0,description:"Agent id or display name"}]},execute:async e=>{let t=e.args[0];if(!t)return"Usage: /dm <agent-id-or-name>";let s=this.resolveAgent(t);return s?`DM ready: ${(await this.teamStore.getOrCreateDm(e.senderId,s.id,e.senderName))._id}`:`Unknown agent: ${t}`}}),this.register({def:{name:"rename",source:"core",description:"Rename the current channel or thread",args:[{name:"name",required:!0,description:"New name"}]},execute:async e=>{let t=e.args.join(" ");return t?await this.teamStore.renameChannel(e.channelId,t)?`Renamed to "${t}"`:"Channel not found":"Usage: /rename <new name>"}}),this.register({def:{name:"members",source:"core",description:"List members of the current channel"},execute:async e=>{let t=await this.teamStore.getChannel(e.channelId);return t?`Members of ${t.name}:
208
211
  ${t.members.map(s=>` - ${s}`).join(`
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
212
+ `)}`:"Channel not found"}})}}});var Ve=T((SN,Lf)=>{"use strict";var Mf=["nodebuffer","arraybuffer","fragments"],Df=typeof Blob<"u";Df&&Mf.push("blob");Lf.exports={BINARY_TYPES:Mf,CLOSE_TIMEOUT:3e4,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Df,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var Zs=T((kN,di)=>{"use strict";var{EMPTY_BUFFER:$b}=Ve(),Xa=Buffer[Symbol.species];function Rb(n,e){if(n.length===0)return $b;if(n.length===1)return n[0];let t=Buffer.allocUnsafe(e),s=0;for(let r=0;r<n.length;r++){let i=n[r];t.set(i,s),s+=i.length}return s<e?new Xa(t.buffer,t.byteOffset,s):t}function Pf(n,e,t,s,r){for(let i=0;i<r;i++)t[s+i]=n[i]^e[i&3]}function $f(n,e){for(let t=0;t<n.length;t++)n[t]^=e[t&3]}function Bb(n){return n.length===n.buffer.byteLength?n.buffer:n.buffer.slice(n.byteOffset,n.byteOffset+n.length)}function Za(n){if(Za.readOnly=!0,Buffer.isBuffer(n))return n;let e;return n instanceof ArrayBuffer?e=new Xa(n):ArrayBuffer.isView(n)?e=new Xa(n.buffer,n.byteOffset,n.byteLength):(e=Buffer.from(n),Za.readOnly=!1),e}di.exports={concat:Rb,mask:Pf,toArrayBuffer:Bb,toBuffer:Za,unmask:$f};if(!process.env.WS_NO_BUFFER_UTIL)try{let n=H("bufferutil");di.exports.mask=function(e,t,s,r,i){i<48?Pf(e,t,s,r,i):n.mask(e,t,s,r,i)},di.exports.unmask=function(e,t){e.length<32?$f(e,t):n.unmask(e,t)}}catch{}});var Uf=T((bN,Bf)=>{"use strict";var Rf=Symbol("kDone"),ec=Symbol("kRun"),tc=class{constructor(e){this[Rf]=()=>{this.pending--,this[ec]()},this.concurrency=e||1/0,this.jobs=[],this.pending=0}add(e){this.jobs.push(e),this[ec]()}[ec](){if(this.pending!==this.concurrency&&this.jobs.length){let e=this.jobs.shift();this.pending++,e(this[Rf])}}};Bf.exports=tc});var es=T((_N,Kf)=>{"use strict";var en=H("zlib"),jf=Zs(),Ub=Uf(),{kStatusCode:qf}=Ve(),jb=Buffer[Symbol.species],qb=Buffer.from([0,0,255,255]),hi=Symbol("permessage-deflate"),Ye=Symbol("total-length"),Xt=Symbol("callback"),ft=Symbol("buffers"),Zt=Symbol("error"),ui,sc=class{constructor(e){if(this._options=e||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ui){let t=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ui=new Ub(t)}}static get extensionName(){return"permessage-deflate"}offer(){let e={};return this._options.serverNoContextTakeover&&(e.server_no_context_takeover=!0),this._options.clientNoContextTakeover&&(e.client_no_context_takeover=!0),this._options.serverMaxWindowBits&&(e.server_max_window_bits=this._options.serverMaxWindowBits),this._options.clientMaxWindowBits?e.client_max_window_bits=this._options.clientMaxWindowBits:this._options.clientMaxWindowBits==null&&(e.client_max_window_bits=!0),e}accept(e){return e=this.normalizeParams(e),this.params=this._isServer?this.acceptAsServer(e):this.acceptAsClient(e),this.params}cleanup(){if(this._inflate&&(this._inflate.close(),this._inflate=null),this._deflate){let e=this._deflate[Xt];this._deflate.close(),this._deflate=null,e&&e(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(e){let t=this._options,s=e.find(r=>!(t.serverNoContextTakeover===!1&&r.server_no_context_takeover||r.server_max_window_bits&&(t.serverMaxWindowBits===!1||typeof t.serverMaxWindowBits=="number"&&t.serverMaxWindowBits>r.server_max_window_bits)||typeof t.clientMaxWindowBits=="number"&&!r.client_max_window_bits));if(!s)throw new Error("None of the extension offers can be accepted");return t.serverNoContextTakeover&&(s.server_no_context_takeover=!0),t.clientNoContextTakeover&&(s.client_no_context_takeover=!0),typeof t.serverMaxWindowBits=="number"&&(s.server_max_window_bits=t.serverMaxWindowBits),typeof t.clientMaxWindowBits=="number"?s.client_max_window_bits=t.clientMaxWindowBits:(s.client_max_window_bits===!0||t.clientMaxWindowBits===!1)&&delete s.client_max_window_bits,s}acceptAsClient(e){let t=e[0];if(this._options.clientNoContextTakeover===!1&&t.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!t.client_max_window_bits)typeof this._options.clientMaxWindowBits=="number"&&(t.client_max_window_bits=this._options.clientMaxWindowBits);else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits=="number"&&t.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return t}normalizeParams(e){return e.forEach(t=>{Object.keys(t).forEach(s=>{let r=t[s];if(r.length>1)throw new Error(`Parameter "${s}" must have only a single value`);if(r=r[0],s==="client_max_window_bits"){if(r!==!0){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else if(s==="server_max_window_bits"){let i=+r;if(!Number.isInteger(i)||i<8||i>15)throw new TypeError(`Invalid value for parameter "${s}": ${r}`);r=i}else if(s==="client_no_context_takeover"||s==="server_no_context_takeover"){if(r!==!0)throw new TypeError(`Invalid value for parameter "${s}": ${r}`)}else throw new Error(`Unknown parameter "${s}"`);t[s]=r})}),e}decompress(e,t,s){ui.add(r=>{this._decompress(e,t,(i,o)=>{r(),s(i,o)})})}compress(e,t,s){ui.add(r=>{this._compress(e,t,(i,o)=>{r(),s(i,o)})})}_decompress(e,t,s){let r=this._isServer?"client":"server";if(!this._inflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[i];this._inflate=en.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[hi]=this,this._inflate[Ye]=0,this._inflate[ft]=[],this._inflate.on("error",Kb),this._inflate.on("data",Ff)}this._inflate[Xt]=s,this._inflate.write(e),t&&this._inflate.write(qb),this._inflate.flush(()=>{let i=this._inflate[Zt];if(i){this._inflate.close(),this._inflate=null,s(i);return}let o=jf.concat(this._inflate[ft],this._inflate[Ye]);this._inflate._readableState.endEmitted?(this._inflate.close(),this._inflate=null):(this._inflate[Ye]=0,this._inflate[ft]=[],t&&this.params[`${r}_no_context_takeover`]&&this._inflate.reset()),s(null,o)})}_compress(e,t,s){let r=this._isServer?"server":"client";if(!this._deflate){let i=`${r}_max_window_bits`,o=typeof this.params[i]!="number"?en.Z_DEFAULT_WINDOWBITS:this.params[i];this._deflate=en.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[Ye]=0,this._deflate[ft]=[],this._deflate.on("data",Fb)}this._deflate[Xt]=s,this._deflate.write(e),this._deflate.flush(en.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let i=jf.concat(this._deflate[ft],this._deflate[Ye]);t&&(i=new jb(i.buffer,i.byteOffset,i.length-4)),this._deflate[Xt]=null,this._deflate[Ye]=0,this._deflate[ft]=[],t&&this.params[`${r}_no_context_takeover`]&&this._deflate.reset(),s(null,i)})}};Kf.exports=sc;function Fb(n){this[ft].push(n),this[Ye]+=n.length}function Ff(n){if(this[Ye]+=n.length,this[hi]._maxPayload<1||this[Ye]<=this[hi]._maxPayload){this[ft].push(n);return}this[Zt]=new RangeError("Max payload size exceeded"),this[Zt].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[Zt][qf]=1009,this.removeListener("data",Ff),this.reset()}function Kb(n){if(this[hi]._inflate=null,this[Zt]){this[Xt](this[Zt]);return}n[qf]=1007,this[Xt](n)}});var ts=T((vN,fi)=>{"use strict";var{isUtf8:Hf}=H("buffer"),{hasBlob:Hb}=Ve(),Wb=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Gb(n){return n>=1e3&&n<=1014&&n!==1004&&n!==1005&&n!==1006||n>=3e3&&n<=4999}function nc(n){let e=n.length,t=0;for(;t<e;)if((n[t]&128)===0)t++;else if((n[t]&224)===192){if(t+1===e||(n[t+1]&192)!==128||(n[t]&254)===192)return!1;t+=2}else if((n[t]&240)===224){if(t+2>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||n[t]===224&&(n[t+1]&224)===128||n[t]===237&&(n[t+1]&224)===160)return!1;t+=3}else if((n[t]&248)===240){if(t+3>=e||(n[t+1]&192)!==128||(n[t+2]&192)!==128||(n[t+3]&192)!==128||n[t]===240&&(n[t+1]&240)===128||n[t]===244&&n[t+1]>143||n[t]>244)return!1;t+=4}else return!1;return!0}function Vb(n){return Hb&&typeof n=="object"&&typeof n.arrayBuffer=="function"&&typeof n.type=="string"&&typeof n.stream=="function"&&(n[Symbol.toStringTag]==="Blob"||n[Symbol.toStringTag]==="File")}fi.exports={isBlob:Vb,isValidStatusCode:Gb,isValidUTF8:nc,tokenChars:Wb};if(Hf)fi.exports.isValidUTF8=function(n){return n.length<24?nc(n):Hf(n)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let n=H("utf-8-validate");fi.exports.isValidUTF8=function(e){return e.length<32?nc(e):n(e)}}catch{}});var cc=T((TN,Qf)=>{"use strict";var{Writable:Yb}=H("stream"),Wf=es(),{BINARY_TYPES:Jb,EMPTY_BUFFER:Gf,kStatusCode:zb,kWebSocket:Qb}=Ve(),{concat:rc,toArrayBuffer:Xb,unmask:Zb}=Zs(),{isValidStatusCode:e_,isValidUTF8:Vf}=ts(),pi=Buffer[Symbol.species],_e=0,Yf=1,Jf=2,zf=3,ic=4,oc=5,mi=6,ac=class extends Yb{constructor(e={}){super(),this._allowSynchronousEvents=e.allowSynchronousEvents!==void 0?e.allowSynchronousEvents:!0,this._binaryType=e.binaryType||Jb[0],this._extensions=e.extensions||{},this._isServer=!!e.isServer,this._maxPayload=e.maxPayload|0,this._skipUTF8Validation=!!e.skipUTF8Validation,this[Qb]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=_e}_write(e,t,s){if(this._opcode===8&&this._state==_e)return s();this._bufferedBytes+=e.length,this._buffers.push(e),this.startLoop(s)}consume(e){if(this._bufferedBytes-=e,e===this._buffers[0].length)return this._buffers.shift();if(e<this._buffers[0].length){let s=this._buffers[0];return this._buffers[0]=new pi(s.buffer,s.byteOffset+e,s.length-e),new pi(s.buffer,s.byteOffset,e)}let t=Buffer.allocUnsafe(e);do{let s=this._buffers[0],r=t.length-e;e>=s.length?t.set(this._buffers.shift(),r):(t.set(new Uint8Array(s.buffer,s.byteOffset,e),r),this._buffers[0]=new pi(s.buffer,s.byteOffset+e,s.length-e)),e-=s.length}while(e>0);return t}startLoop(e){this._loop=!0;do switch(this._state){case _e:this.getInfo(e);break;case Yf:this.getPayloadLength16(e);break;case Jf:this.getPayloadLength64(e);break;case zf:this.getMask();break;case ic:this.getData(e);break;case oc:case mi:this._loop=!1;return}while(this._loop);this._errored||e()}getInfo(e){if(this._bufferedBytes<2){this._loop=!1;return}let t=this.consume(2);if((t[0]&48)!==0){let r=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");e(r);return}let s=(t[0]&64)===64;if(s&&!this._extensions[Wf.extensionName]){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._fin=(t[0]&128)===128,this._opcode=t[0]&15,this._payloadLength=t[1]&127,this._opcode===0){if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(!this._fragmented){let r=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}this._compressed=s}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let r=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");e(r);return}if(s){let r=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");e(r);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let r=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");e(r);return}}else{let r=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");e(r);return}if(!this._fin&&!this._fragmented&&(this._fragmented=this._opcode),this._masked=(t[1]&128)===128,this._isServer){if(!this._masked){let r=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");e(r);return}}else if(this._masked){let r=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");e(r);return}this._payloadLength===126?this._state=Yf:this._payloadLength===127?this._state=Jf:this.haveLength(e)}getPayloadLength16(e){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(e)}getPayloadLength64(e){if(this._bufferedBytes<8){this._loop=!1;return}let t=this.consume(8),s=t.readUInt32BE(0);if(s>Math.pow(2,21)-1){let r=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");e(r);return}this._payloadLength=s*Math.pow(2,32)+t.readUInt32BE(4),this.haveLength(e)}haveLength(e){if(this._payloadLength&&this._opcode<8&&(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0)){let t=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");e(t);return}this._masked?this._state=zf:this._state=ic}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=ic}getData(e){let t=Gf;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}t=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0&&Zb(t,this._mask)}if(this._opcode>7){this.controlMessage(t,e);return}if(this._compressed){this._state=oc,this.decompress(t,e);return}t.length&&(this._messageLength=this._totalPayloadLength,this._fragments.push(t)),this.dataMessage(e)}decompress(e,t){this._extensions[Wf.extensionName].decompress(e,this._fin,(r,i)=>{if(r)return t(r);if(i.length){if(this._messageLength+=i.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(o);return}this._fragments.push(i)}this.dataMessage(t),this._state===_e&&this.startLoop(t)})}dataMessage(e){if(!this._fin){this._state=_e;return}let t=this._messageLength,s=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let r;this._binaryType==="nodebuffer"?r=rc(s,t):this._binaryType==="arraybuffer"?r=Xb(rc(s,t)):this._binaryType==="blob"?r=new Blob(s):r=s,this._allowSynchronousEvents?(this.emit("message",r,!0),this._state=_e):(this._state=mi,setImmediate(()=>{this.emit("message",r,!0),this._state=_e,this.startLoop(e)}))}else{let r=rc(s,t);if(!this._skipUTF8Validation&&!Vf(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");e(i);return}this._state===oc||this._allowSynchronousEvents?(this.emit("message",r,!1),this._state=_e):(this._state=mi,setImmediate(()=>{this.emit("message",r,!1),this._state=_e,this.startLoop(e)}))}}controlMessage(e,t){if(this._opcode===8){if(e.length===0)this._loop=!1,this.emit("conclude",1005,Gf),this.end();else{let s=e.readUInt16BE(0);if(!e_(s)){let i=this.createError(RangeError,`invalid status code ${s}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");t(i);return}let r=new pi(e.buffer,e.byteOffset+2,e.length-2);if(!this._skipUTF8Validation&&!Vf(r)){let i=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(i);return}this._loop=!1,this.emit("conclude",s,r),this.end()}this._state=_e;return}this._allowSynchronousEvents?(this.emit(this._opcode===9?"ping":"pong",e),this._state=_e):(this._state=mi,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",e),this._state=_e,this.startLoop(t)}))}createError(e,t,s,r,i){this._loop=!1,this._errored=!0;let o=new e(s?`Invalid WebSocket frame: ${t}`:t);return Error.captureStackTrace(o,this.createError),o.code=i,o[zb]=r,o}};Qf.exports=ac});var uc=T((AN,ep)=>{"use strict";var{Duplex:IN}=H("stream"),{randomFillSync:t_}=H("crypto"),Xf=es(),{EMPTY_BUFFER:s_,kWebSocket:n_,NOOP:r_}=Ve(),{isBlob:ss,isValidStatusCode:i_}=ts(),{mask:Zf,toBuffer:xt}=Zs(),ve=Symbol("kByteLength"),o_=Buffer.alloc(4),gi=8*1024,Ot,ns=gi,De=0,a_=1,c_=2,lc=class n{constructor(e,t,s){this._extensions=t||{},s&&(this._generateMask=s,this._maskBuffer=Buffer.alloc(4)),this._socket=e,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=De,this.onerror=r_,this[n_]=void 0}static frame(e,t){let s,r=!1,i=2,o=!1;t.mask&&(s=t.maskBuffer||o_,t.generateMask?t.generateMask(s):(ns===gi&&(Ot===void 0&&(Ot=Buffer.alloc(gi)),t_(Ot,0,gi),ns=0),s[0]=Ot[ns++],s[1]=Ot[ns++],s[2]=Ot[ns++],s[3]=Ot[ns++]),o=(s[0]|s[1]|s[2]|s[3])===0,i=6);let a;typeof e=="string"?(!t.mask||o)&&t[ve]!==void 0?a=t[ve]:(e=Buffer.from(e),a=e.length):(a=e.length,r=t.mask&&t.readOnly&&!o);let l=a;a>=65536?(i+=8,l=127):a>125&&(i+=2,l=126);let c=Buffer.allocUnsafe(r?a+i:i);return c[0]=t.fin?t.opcode|128:t.opcode,t.rsv1&&(c[0]|=64),c[1]=l,l===126?c.writeUInt16BE(a,2):l===127&&(c[2]=c[3]=0,c.writeUIntBE(a,4,6)),t.mask?(c[1]|=128,c[i-4]=s[0],c[i-3]=s[1],c[i-2]=s[2],c[i-1]=s[3],o?[c,e]:r?(Zf(e,s,c,i,a),[c]):(Zf(e,s,e,0,a),[c,e])):[c,e]}close(e,t,s,r){let i;if(e===void 0)i=s_;else{if(typeof e!="number"||!i_(e))throw new TypeError("First argument must be a valid error code number");if(t===void 0||!t.length)i=Buffer.allocUnsafe(2),i.writeUInt16BE(e,0);else{let a=Buffer.byteLength(t);if(a>123)throw new RangeError("The message must not be greater than 123 bytes");i=Buffer.allocUnsafe(2+a),i.writeUInt16BE(e,0),typeof t=="string"?i.write(t,2):i.set(t,2)}}let o={[ve]:i.length,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};this._state!==De?this.enqueue([this.dispatch,i,!1,o,r]):this.sendFrame(n.frame(i,o),r)}ping(e,t,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):ss(e)?(r=e.size,i=!1):(e=xt(e),r=e.length,i=xt.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:9,readOnly:i,rsv1:!1};ss(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==De?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(n.frame(e,o),s)}pong(e,t,s){let r,i;if(typeof e=="string"?(r=Buffer.byteLength(e),i=!1):ss(e)?(r=e.size,i=!1):(e=xt(e),r=e.length,i=xt.readOnly),r>125)throw new RangeError("The data size must not be greater than 125 bytes");let o={[ve]:r,fin:!0,generateMask:this._generateMask,mask:t,maskBuffer:this._maskBuffer,opcode:10,readOnly:i,rsv1:!1};ss(e)?this._state!==De?this.enqueue([this.getBlobData,e,!1,o,s]):this.getBlobData(e,!1,o,s):this._state!==De?this.enqueue([this.dispatch,e,!1,o,s]):this.sendFrame(n.frame(e,o),s)}send(e,t,s){let r=this._extensions[Xf.extensionName],i=t.binary?2:1,o=t.compress,a,l;typeof e=="string"?(a=Buffer.byteLength(e),l=!1):ss(e)?(a=e.size,l=!1):(e=xt(e),a=e.length,l=xt.readOnly),this._firstFragment?(this._firstFragment=!1,o&&r&&r.params[r._isServer?"server_no_context_takeover":"client_no_context_takeover"]&&(o=a>=r._threshold),this._compress=o):(o=!1,i=0),t.fin&&(this._firstFragment=!0);let c={[ve]:a,fin:t.fin,generateMask:this._generateMask,mask:t.mask,maskBuffer:this._maskBuffer,opcode:i,readOnly:l,rsv1:o};ss(e)?this._state!==De?this.enqueue([this.getBlobData,e,this._compress,c,s]):this.getBlobData(e,this._compress,c,s):this._state!==De?this.enqueue([this.dispatch,e,this._compress,c,s]):this.dispatch(e,this._compress,c,s)}getBlobData(e,t,s,r){this._bufferedBytes+=s[ve],this._state=c_,e.arrayBuffer().then(i=>{if(this._socket.destroyed){let a=new Error("The socket was closed while the blob was being read");process.nextTick(dc,this,a,r);return}this._bufferedBytes-=s[ve];let o=xt(i);t?this.dispatch(o,t,s,r):(this._state=De,this.sendFrame(n.frame(o,s),r),this.dequeue())}).catch(i=>{process.nextTick(l_,this,i,r)})}dispatch(e,t,s,r){if(!t){this.sendFrame(n.frame(e,s),r);return}let i=this._extensions[Xf.extensionName];this._bufferedBytes+=s[ve],this._state=a_,i.compress(e,s.fin,(o,a)=>{if(this._socket.destroyed){let l=new Error("The socket was closed while data was being compressed");dc(this,l,r);return}this._bufferedBytes-=s[ve],this._state=De,s.readOnly=!1,this.sendFrame(n.frame(a,s),r),this.dequeue()})}dequeue(){for(;this._state===De&&this._queue.length;){let e=this._queue.shift();this._bufferedBytes-=e[3][ve],Reflect.apply(e[0],this,e.slice(1))}}enqueue(e){this._bufferedBytes+=e[3][ve],this._queue.push(e)}sendFrame(e,t){e.length===2?(this._socket.cork(),this._socket.write(e[0]),this._socket.write(e[1],t),this._socket.uncork()):this._socket.write(e[0],t)}};ep.exports=lc;function dc(n,e,t){typeof t=="function"&&t(e);for(let s=0;s<n._queue.length;s++){let r=n._queue[s],i=r[r.length-1];typeof i=="function"&&i(e)}}function l_(n,e,t){dc(n,e,t),n.onerror(e)}});var lp=T((CN,cp)=>{"use strict";var{kForOnEventAttribute:tn,kListener:hc}=Ve(),tp=Symbol("kCode"),sp=Symbol("kData"),np=Symbol("kError"),rp=Symbol("kMessage"),ip=Symbol("kReason"),rs=Symbol("kTarget"),op=Symbol("kType"),ap=Symbol("kWasClean"),Je=class{constructor(e){this[rs]=null,this[op]=e}get target(){return this[rs]}get type(){return this[op]}};Object.defineProperty(Je.prototype,"target",{enumerable:!0});Object.defineProperty(Je.prototype,"type",{enumerable:!0});var Mt=class extends Je{constructor(e,t={}){super(e),this[tp]=t.code===void 0?0:t.code,this[ip]=t.reason===void 0?"":t.reason,this[ap]=t.wasClean===void 0?!1:t.wasClean}get code(){return this[tp]}get reason(){return this[ip]}get wasClean(){return this[ap]}};Object.defineProperty(Mt.prototype,"code",{enumerable:!0});Object.defineProperty(Mt.prototype,"reason",{enumerable:!0});Object.defineProperty(Mt.prototype,"wasClean",{enumerable:!0});var is=class extends Je{constructor(e,t={}){super(e),this[np]=t.error===void 0?null:t.error,this[rp]=t.message===void 0?"":t.message}get error(){return this[np]}get message(){return this[rp]}};Object.defineProperty(is.prototype,"error",{enumerable:!0});Object.defineProperty(is.prototype,"message",{enumerable:!0});var sn=class extends Je{constructor(e,t={}){super(e),this[sp]=t.data===void 0?null:t.data}get data(){return this[sp]}};Object.defineProperty(sn.prototype,"data",{enumerable:!0});var d_={addEventListener(n,e,t={}){for(let r of this.listeners(n))if(!t[tn]&&r[hc]===e&&!r[tn])return;let s;if(n==="message")s=function(i,o){let a=new sn("message",{data:o?i:i.toString()});a[rs]=this,yi(e,this,a)};else if(n==="close")s=function(i,o){let a=new Mt("close",{code:i,reason:o.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});a[rs]=this,yi(e,this,a)};else if(n==="error")s=function(i){let o=new is("error",{error:i,message:i.message});o[rs]=this,yi(e,this,o)};else if(n==="open")s=function(){let i=new Je("open");i[rs]=this,yi(e,this,i)};else return;s[tn]=!!t[tn],s[hc]=e,t.once?this.once(n,s):this.on(n,s)},removeEventListener(n,e){for(let t of this.listeners(n))if(t[hc]===e&&!t[tn]){this.removeListener(n,t);break}}};cp.exports={CloseEvent:Mt,ErrorEvent:is,Event:Je,EventTarget:d_,MessageEvent:sn};function yi(n,e,t){typeof n=="object"&&n.handleEvent?n.handleEvent.call(n,t):n.call(e,t)}});var wi=T((EN,dp)=>{"use strict";var{tokenChars:nn}=ts();function $e(n,e,t){n[e]===void 0?n[e]=[t]:n[e].push(t)}function u_(n){let e=Object.create(null),t=Object.create(null),s=!1,r=!1,i=!1,o,a,l=-1,c=-1,d=-1,u=0;for(;u<n.length;u++)if(c=n.charCodeAt(u),o===void 0)if(d===-1&&nn[c]===1)l===-1&&(l=u);else if(u!==0&&(c===32||c===9))d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(l,d);c===44?($e(e,p,t),t=Object.create(null)):o=p,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);else if(a===void 0)if(d===-1&&nn[c]===1)l===-1&&(l=u);else if(c===32||c===9)d===-1&&l!==-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u),$e(t,n.slice(l,d),!0),c===44&&($e(e,o,t),t=Object.create(null),o=void 0),l=d=-1}else if(c===61&&l!==-1&&d===-1)a=n.slice(l,u),l=d=-1;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(r){if(nn[c]!==1)throw new SyntaxError(`Unexpected character at index ${u}`);l===-1?l=u:s||(s=!0),r=!1}else if(i)if(nn[c]===1)l===-1&&(l=u);else if(c===34&&l!==-1)i=!1,d=u;else if(c===92)r=!0;else throw new SyntaxError(`Unexpected character at index ${u}`);else if(c===34&&n.charCodeAt(u-1)===61)i=!0;else if(d===-1&&nn[c]===1)l===-1&&(l=u);else if(l!==-1&&(c===32||c===9))d===-1&&(d=u);else if(c===59||c===44){if(l===-1)throw new SyntaxError(`Unexpected character at index ${u}`);d===-1&&(d=u);let p=n.slice(l,d);s&&(p=p.replace(/\\/g,""),s=!1),$e(t,a,p),c===44&&($e(e,o,t),t=Object.create(null),o=void 0),a=void 0,l=d=-1}else throw new SyntaxError(`Unexpected character at index ${u}`);if(l===-1||i||c===32||c===9)throw new SyntaxError("Unexpected end of input");d===-1&&(d=u);let h=n.slice(l,d);return o===void 0?$e(e,h,t):(a===void 0?$e(t,h,!0):s?$e(t,a,h.replace(/\\/g,"")):$e(t,a,h),$e(e,o,t)),e}function h_(n){return Object.keys(n).map(e=>{let t=n[e];return Array.isArray(t)||(t=[t]),t.map(s=>[e].concat(Object.keys(s).map(r=>{let i=s[r];return Array.isArray(i)||(i=[i]),i.map(o=>o===!0?r:`${r}=${o}`).join("; ")})).join("; ")).join(", ")}).join(", ")}dp.exports={format:h_,parse:u_}});var _i=T((ON,_p)=>{"use strict";var f_=H("events"),p_=H("https"),m_=H("http"),fp=H("net"),g_=H("tls"),{randomBytes:y_,createHash:w_}=H("crypto"),{Duplex:NN,Readable:xN}=H("stream"),{URL:fc}=H("url"),pt=es(),S_=cc(),k_=uc(),{isBlob:b_}=ts(),{BINARY_TYPES:up,CLOSE_TIMEOUT:__,EMPTY_BUFFER:Si,GUID:v_,kForOnEventAttribute:pc,kListener:T_,kStatusCode:I_,kWebSocket:ie,NOOP:pp}=Ve(),{EventTarget:{addEventListener:A_,removeEventListener:C_}}=lp(),{format:E_,parse:N_}=wi(),{toBuffer:x_}=Zs(),mp=Symbol("kAborted"),mc=[8,13],ze=["CONNECTING","OPEN","CLOSING","CLOSED"],O_=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/,z=class n extends f_{constructor(e,t,s){super(),this._binaryType=up[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=Si,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=n.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,e!==null?(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,t===void 0?t=[]:Array.isArray(t)||(typeof t=="object"&&t!==null?(s=t,t=[]):t=[t]),gp(this,e,t,s)):(this._autoPong=s.autoPong,this._closeTimeout=s.closeTimeout,this._isServer=!0)}get binaryType(){return this._binaryType}set binaryType(e){up.includes(e)&&(this._binaryType=e,this._receiver&&(this._receiver._binaryType=e))}get bufferedAmount(){return this._socket?this._socket._writableState.length+this._sender._bufferedBytes:this._bufferedAmount}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(e,t,s){let r=new S_({allowSynchronousEvents:s.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:s.maxPayload,skipUTF8Validation:s.skipUTF8Validation}),i=new k_(e,this._extensions,s.generateMask);this._receiver=r,this._sender=i,this._socket=e,r[ie]=this,i[ie]=this,e[ie]=this,r.on("conclude",L_),r.on("drain",P_),r.on("error",$_),r.on("message",R_),r.on("ping",B_),r.on("pong",U_),i.onerror=j_,e.setTimeout&&e.setTimeout(0),e.setNoDelay&&e.setNoDelay(),t.length>0&&e.unshift(t),e.on("close",Sp),e.on("data",bi),e.on("end",kp),e.on("error",bp),this._readyState=n.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}this._extensions[pt.extensionName]&&this._extensions[pt.extensionName].cleanup(),this._receiver.removeAllListeners(),this._readyState=n.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(e,t){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===n.CLOSING){this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end();return}this._readyState=n.CLOSING,this._sender.close(e,t,!this._isServer,s=>{s||(this._closeFrameSent=!0,(this._closeFrameReceived||this._receiver._writableState.errorEmitted)&&this._socket.end())}),wp(this)}}pause(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!0,this._socket.pause())}ping(e,t,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=t=void 0):typeof t=="function"&&(s=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){gc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.ping(e||Si,t,s)}pong(e,t,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof e=="function"?(s=e,e=t=void 0):typeof t=="function"&&(s=t,t=void 0),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){gc(this,e,s);return}t===void 0&&(t=!this._isServer),this._sender.pong(e||Si,t,s)}resume(){this.readyState===n.CONNECTING||this.readyState===n.CLOSED||(this._paused=!1,this._receiver._writableState.needDrain||this._socket.resume())}send(e,t,s){if(this.readyState===n.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t=="function"&&(s=t,t={}),typeof e=="number"&&(e=e.toString()),this.readyState!==n.OPEN){gc(this,e,s);return}let r={binary:typeof e!="string",mask:!this._isServer,compress:!0,fin:!0,...t};this._extensions[pt.extensionName]||(r.compress=!1),this._sender.send(e||Si,r,s)}terminate(){if(this.readyState!==n.CLOSED){if(this.readyState===n.CONNECTING){Se(this,this._req,"WebSocket was closed before the connection was established");return}this._socket&&(this._readyState=n.CLOSING,this._socket.destroy())}}};Object.defineProperty(z,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(z.prototype,"CONNECTING",{enumerable:!0,value:ze.indexOf("CONNECTING")});Object.defineProperty(z,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(z.prototype,"OPEN",{enumerable:!0,value:ze.indexOf("OPEN")});Object.defineProperty(z,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(z.prototype,"CLOSING",{enumerable:!0,value:ze.indexOf("CLOSING")});Object.defineProperty(z,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});Object.defineProperty(z.prototype,"CLOSED",{enumerable:!0,value:ze.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach(n=>{Object.defineProperty(z.prototype,n,{enumerable:!0})});["open","error","close","message"].forEach(n=>{Object.defineProperty(z.prototype,`on${n}`,{enumerable:!0,get(){for(let e of this.listeners(n))if(e[pc])return e[T_];return null},set(e){for(let t of this.listeners(n))if(t[pc]){this.removeListener(n,t);break}typeof e=="function"&&this.addEventListener(n,e,{[pc]:!0})}})});z.prototype.addEventListener=A_;z.prototype.removeEventListener=C_;_p.exports=z;function gp(n,e,t,s){let r={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:__,protocolVersion:mc[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...s,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(n._autoPong=r.autoPong,n._closeTimeout=r.closeTimeout,!mc.includes(r.protocolVersion))throw new RangeError(`Unsupported protocol version: ${r.protocolVersion} (supported versions: ${mc.join(", ")})`);let i;if(e instanceof fc)i=e;else try{i=new fc(e)}catch{throw new SyntaxError(`Invalid URL: ${e}`)}i.protocol==="http:"?i.protocol="ws:":i.protocol==="https:"&&(i.protocol="wss:"),n._url=i.href;let o=i.protocol==="wss:",a=i.protocol==="ws+unix:",l;if(i.protocol!=="ws:"&&!o&&!a?l=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`:a&&!i.pathname?l="The URL's pathname is empty":i.hash&&(l="The URL contains a fragment identifier"),l){let f=new SyntaxError(l);if(n._redirects===0)throw f;ki(n,f);return}let c=o?443:80,d=y_(16).toString("base64"),u=o?p_.request:m_.request,h=new Set,p;if(r.createConnection=r.createConnection||(o?D_:M_),r.defaultPort=r.defaultPort||c,r.port=i.port||c,r.host=i.hostname.startsWith("[")?i.hostname.slice(1,-1):i.hostname,r.headers={...r.headers,"Sec-WebSocket-Version":r.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},r.path=i.pathname+i.search,r.timeout=r.handshakeTimeout,r.perMessageDeflate&&(p=new pt({...r.perMessageDeflate,isServer:!1,maxPayload:r.maxPayload}),r.headers["Sec-WebSocket-Extensions"]=E_({[pt.extensionName]:p.offer()})),t.length){for(let f of t){if(typeof f!="string"||!O_.test(f)||h.has(f))throw new SyntaxError("An invalid or duplicated subprotocol was specified");h.add(f)}r.headers["Sec-WebSocket-Protocol"]=t.join(",")}if(r.origin&&(r.protocolVersion<13?r.headers["Sec-WebSocket-Origin"]=r.origin:r.headers.Origin=r.origin),(i.username||i.password)&&(r.auth=`${i.username}:${i.password}`),a){let f=r.path.split(":");r.socketPath=f[0],r.path=f[1]}let m;if(r.followRedirects){if(n._redirects===0){n._originalIpc=a,n._originalSecure=o,n._originalHostOrSocketPath=a?r.socketPath:i.host;let f=s&&s.headers;if(s={...s,headers:{}},f)for(let[y,w]of Object.entries(f))s.headers[y.toLowerCase()]=w}else if(n.listenerCount("redirect")===0){let f=a?n._originalIpc?r.socketPath===n._originalHostOrSocketPath:!1:n._originalIpc?!1:i.host===n._originalHostOrSocketPath;(!f||n._originalSecure&&!o)&&(delete r.headers.authorization,delete r.headers.cookie,f||delete r.headers.host,r.auth=void 0)}r.auth&&!s.headers.authorization&&(s.headers.authorization="Basic "+Buffer.from(r.auth).toString("base64")),m=n._req=u(r),n._redirects&&n.emit("redirect",n.url,m)}else m=n._req=u(r);r.timeout&&m.on("timeout",()=>{Se(n,m,"Opening handshake has timed out")}),m.on("error",f=>{m===null||m[mp]||(m=n._req=null,ki(n,f))}),m.on("response",f=>{let y=f.headers.location,w=f.statusCode;if(y&&r.followRedirects&&w>=300&&w<400){if(++n._redirects>r.maxRedirects){Se(n,m,"Maximum redirects exceeded");return}m.abort();let S;try{S=new fc(y,e)}catch{let v=new SyntaxError(`Invalid URL: ${y}`);ki(n,v);return}gp(n,S,t,s)}else n.emit("unexpected-response",m,f)||Se(n,m,`Unexpected server response: ${f.statusCode}`)}),m.on("upgrade",(f,y,w)=>{if(n.emit("upgrade",f),n.readyState!==z.CONNECTING)return;m=n._req=null;let S=f.headers.upgrade;if(S===void 0||S.toLowerCase()!=="websocket"){Se(n,y,"Invalid Upgrade header");return}let _=w_("sha1").update(d+v_).digest("base64");if(f.headers["sec-websocket-accept"]!==_){Se(n,y,"Invalid Sec-WebSocket-Accept header");return}let v=f.headers["sec-websocket-protocol"],I;if(v!==void 0?h.size?h.has(v)||(I="Server sent an invalid subprotocol"):I="Server sent a subprotocol but none was requested":h.size&&(I="Server sent no subprotocol"),I){Se(n,y,I);return}v&&(n._protocol=v);let N=f.headers["sec-websocket-extensions"];if(N!==void 0){if(!p){Se(n,y,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let D;try{D=N_(N)}catch{Se(n,y,"Invalid Sec-WebSocket-Extensions header");return}let A=Object.keys(D);if(A.length!==1||A[0]!==pt.extensionName){Se(n,y,"Server indicated an extension that was not requested");return}try{p.accept(D[pt.extensionName])}catch{Se(n,y,"Invalid Sec-WebSocket-Extensions header");return}n._extensions[pt.extensionName]=p}n.setSocket(y,w,{allowSynchronousEvents:r.allowSynchronousEvents,generateMask:r.generateMask,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation})}),r.finishRequest?r.finishRequest(m,n):m.end()}function ki(n,e){n._readyState=z.CLOSING,n._errorEmitted=!0,n.emit("error",e),n.emitClose()}function M_(n){return n.path=n.socketPath,fp.connect(n)}function D_(n){return n.path=void 0,!n.servername&&n.servername!==""&&(n.servername=fp.isIP(n.host)?"":n.host),g_.connect(n)}function Se(n,e,t){n._readyState=z.CLOSING;let s=new Error(t);Error.captureStackTrace(s,Se),e.setHeader?(e[mp]=!0,e.abort(),e.socket&&!e.socket.destroyed&&e.socket.destroy(),process.nextTick(ki,n,s)):(e.destroy(s),e.once("error",n.emit.bind(n,"error")),e.once("close",n.emitClose.bind(n)))}function gc(n,e,t){if(e){let s=b_(e)?e.size:x_(e).length;n._socket?n._sender._bufferedBytes+=s:n._bufferedAmount+=s}if(t){let s=new Error(`WebSocket is not open: readyState ${n.readyState} (${ze[n.readyState]})`);process.nextTick(t,s)}}function L_(n,e){let t=this[ie];t._closeFrameReceived=!0,t._closeMessage=e,t._closeCode=n,t._socket[ie]!==void 0&&(t._socket.removeListener("data",bi),process.nextTick(yp,t._socket),n===1005?t.close():t.close(n,e))}function P_(){let n=this[ie];n.isPaused||n._socket.resume()}function $_(n){let e=this[ie];e._socket[ie]!==void 0&&(e._socket.removeListener("data",bi),process.nextTick(yp,e._socket),e.close(n[I_])),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n))}function hp(){this[ie].emitClose()}function R_(n,e){this[ie].emit("message",n,e)}function B_(n){let e=this[ie];e._autoPong&&e.pong(n,!this._isServer,pp),e.emit("ping",n)}function U_(n){this[ie].emit("pong",n)}function yp(n){n.resume()}function j_(n){let e=this[ie];e.readyState!==z.CLOSED&&(e.readyState===z.OPEN&&(e._readyState=z.CLOSING,wp(e)),this._socket.end(),e._errorEmitted||(e._errorEmitted=!0,e.emit("error",n)))}function wp(n){n._closeTimer=setTimeout(n._socket.destroy.bind(n._socket),n._closeTimeout)}function Sp(){let n=this[ie];if(this.removeListener("close",Sp),this.removeListener("data",bi),this.removeListener("end",kp),n._readyState=z.CLOSING,!this._readableState.endEmitted&&!n._closeFrameReceived&&!n._receiver._writableState.errorEmitted&&this._readableState.length!==0){let e=this.read(this._readableState.length);n._receiver.write(e)}n._receiver.end(),this[ie]=void 0,clearTimeout(n._closeTimer),n._receiver._writableState.finished||n._receiver._writableState.errorEmitted?n.emitClose():(n._receiver.on("error",hp),n._receiver.on("finish",hp))}function bi(n){this[ie]._receiver.write(n)||this.pause()}function kp(){let n=this[ie];n._readyState=z.CLOSING,n._receiver.end(),this.end()}function bp(){let n=this[ie];this.removeListener("error",bp),this.on("error",pp),n&&(n._readyState=z.CLOSING,this.destroy())}});var Ap=T((DN,Ip)=>{"use strict";var MN=_i(),{Duplex:q_}=H("stream");function vp(n){n.emit("close")}function F_(){!this.destroyed&&this._writableState.finished&&this.destroy()}function Tp(n){this.removeListener("error",Tp),this.destroy(),this.listenerCount("error")===0&&this.emit("error",n)}function K_(n,e){let t=!0,s=new q_({...e,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return n.on("message",function(i,o){let a=!o&&s._readableState.objectMode?i.toString():i;s.push(a)||n.pause()}),n.once("error",function(i){s.destroyed||(t=!1,s.destroy(i))}),n.once("close",function(){s.destroyed||s.push(null)}),s._destroy=function(r,i){if(n.readyState===n.CLOSED){i(r),process.nextTick(vp,s);return}let o=!1;n.once("error",function(l){o=!0,i(l)}),n.once("close",function(){o||i(r),process.nextTick(vp,s)}),t&&n.terminate()},s._final=function(r){if(n.readyState===n.CONNECTING){n.once("open",function(){s._final(r)});return}n._socket!==null&&(n._socket._writableState.finished?(r(),s._readableState.endEmitted&&s.destroy()):(n._socket.once("finish",function(){r()}),n.close()))},s._read=function(){n.isPaused&&n.resume()},s._write=function(r,i,o){if(n.readyState===n.CONNECTING){n.once("open",function(){s._write(r,i,o)});return}n.send(r,o)},s.on("end",F_),s.on("error",Tp),s}Ip.exports=K_});var yc=T((LN,Cp)=>{"use strict";var{tokenChars:H_}=ts();function W_(n){let e=new Set,t=-1,s=-1,r=0;for(r;r<n.length;r++){let o=n.charCodeAt(r);if(s===-1&&H_[o]===1)t===-1&&(t=r);else if(r!==0&&(o===32||o===9))s===-1&&t!==-1&&(s=r);else if(o===44){if(t===-1)throw new SyntaxError(`Unexpected character at index ${r}`);s===-1&&(s=r);let a=n.slice(t,s);if(e.has(a))throw new SyntaxError(`The "${a}" subprotocol is duplicated`);e.add(a),t=s=-1}else throw new SyntaxError(`Unexpected character at index ${r}`)}if(t===-1||s!==-1)throw new SyntaxError("Unexpected end of input");let i=n.slice(t,r);if(e.has(i))throw new SyntaxError(`The "${i}" subprotocol is duplicated`);return e.add(i),e}Cp.exports={parse:W_}});var Lp=T(($N,Dp)=>{"use strict";var G_=H("events"),vi=H("http"),{Duplex:PN}=H("stream"),{createHash:V_}=H("crypto"),Ep=wi(),Dt=es(),Y_=yc(),J_=_i(),{CLOSE_TIMEOUT:z_,GUID:Q_,kWebSocket:X_}=Ve(),Z_=/^[+/0-9A-Za-z]{22}==$/,Np=0,xp=1,Mp=2,wc=class extends G_{constructor(e,t){if(super(),e={allowSynchronousEvents:!0,autoPong:!0,maxPayload:100*1024*1024,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:z_,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:J_,...e},e.port==null&&!e.server&&!e.noServer||e.port!=null&&(e.server||e.noServer)||e.server&&e.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(e.port!=null?(this._server=vi.createServer((s,r)=>{let i=vi.STATUS_CODES[426];r.writeHead(426,{"Content-Length":i.length,"Content-Type":"text/plain"}),r.end(i)}),this._server.listen(e.port,e.host,e.backlog,t)):e.server&&(this._server=e.server),this._server){let s=this.emit.bind(this,"connection");this._removeListeners=ev(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(r,i,o)=>{this.handleUpgrade(r,i,o,s)}})}e.perMessageDeflate===!0&&(e.perMessageDeflate={}),e.clientTracking&&(this.clients=new Set,this._shouldEmitClose=!1),this.options=e,this._state=Np}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');return this._server?this._server.address():null}close(e){if(this._state===Mp){e&&this.once("close",()=>{e(new Error("The server is not running"))}),process.nextTick(rn,this);return}if(e&&this.once("close",e),this._state!==xp)if(this._state=xp,this.options.noServer||this.options.server)this._server&&(this._removeListeners(),this._removeListeners=this._server=null),this.clients?this.clients.size?this._shouldEmitClose=!0:process.nextTick(rn,this):process.nextTick(rn,this);else{let t=this._server;this._removeListeners(),this._removeListeners=this._server=null,t.close(()=>{rn(this)})}}shouldHandle(e){if(this.options.path){let t=e.url.indexOf("?");if((t!==-1?e.url.slice(0,t):e.url)!==this.options.path)return!1}return!0}handleUpgrade(e,t,s,r){t.on("error",Op);let i=e.headers["sec-websocket-key"],o=e.headers.upgrade,a=+e.headers["sec-websocket-version"];if(e.method!=="GET"){Lt(this,e,t,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){Lt(this,e,t,400,"Invalid Upgrade header");return}if(i===void 0||!Z_.test(i)){Lt(this,e,t,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){Lt(this,e,t,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(e)){on(t,400);return}let l=e.headers["sec-websocket-protocol"],c=new Set;if(l!==void 0)try{c=Y_.parse(l)}catch{Lt(this,e,t,400,"Invalid Sec-WebSocket-Protocol header");return}let d=e.headers["sec-websocket-extensions"],u={};if(this.options.perMessageDeflate&&d!==void 0){let h=new Dt({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let p=Ep.parse(d);p[Dt.extensionName]&&(h.accept(p[Dt.extensionName]),u[Dt.extensionName]=h)}catch{Lt(this,e,t,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let h={origin:e.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(e.socket.authorized||e.socket.encrypted),req:e};if(this.options.verifyClient.length===2){this.options.verifyClient(h,(p,m,f,y)=>{if(!p)return on(t,m||401,f,y);this.completeUpgrade(u,i,c,e,t,s,r)});return}if(!this.options.verifyClient(h))return on(t,401)}this.completeUpgrade(u,i,c,e,t,s,r)}completeUpgrade(e,t,s,r,i,o,a){if(!i.readable||!i.writable)return i.destroy();if(i[X_])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>Np)return on(i,503);let c=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${V_("sha1").update(t+Q_).digest("base64")}`],d=new this.options.WebSocket(null,void 0,this.options);if(s.size){let u=this.options.handleProtocols?this.options.handleProtocols(s,r):s.values().next().value;u&&(c.push(`Sec-WebSocket-Protocol: ${u}`),d._protocol=u)}if(e[Dt.extensionName]){let u=e[Dt.extensionName].params,h=Ep.format({[Dt.extensionName]:[u]});c.push(`Sec-WebSocket-Extensions: ${h}`),d._extensions=e}this.emit("headers",c,r),i.write(c.concat(`\r
210
213
  `).join(`\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
- `+Object.keys(s).map(n=>`${n}: ${s[n]}`).join(`\r
214
+ `)),i.removeListener("error",Op),d.setSocket(i,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients&&(this.clients.add(d),d.on("close",()=>{this.clients.delete(d),this._shouldEmitClose&&!this.clients.size&&process.nextTick(rn,this)})),a(d,r)}};Dp.exports=wc;function ev(n,e){for(let t of Object.keys(e))n.on(t,e[t]);return function(){for(let s of Object.keys(e))n.removeListener(s,e[s])}}function rn(n){n._state=Mp,n.emit("close")}function Op(){this.destroy()}function on(n,e,t,s){t=t||vi.STATUS_CODES[e],s={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(t),...s},n.once("finish",n.destroy),n.end(`HTTP/1.1 ${e} ${vi.STATUS_CODES[e]}\r
215
+ `+Object.keys(s).map(r=>`${r}: ${s[r]}`).join(`\r
213
216
  `)+`\r
214
217
  \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
218
+ `+t)}function Lt(n,e,t,s,r,i){if(n.listenerCount("wsClientError")){let o=new Error(r);Error.captureStackTrace(o,Lt),n.emit("wsClientError",o,t,e)}else on(t,s,r,i)}});var tv,sv,nv,rv,iv,ov,an,Sc,Pp=j(()=>{tv=Ae(Ap(),1),sv=Ae(wi(),1),nv=Ae(es(),1),rv=Ae(cc(),1),iv=Ae(uc(),1),ov=Ae(yc(),1),an=Ae(_i(),1),Sc=Ae(Lp(),1)});function $p(n){let e;try{e=JSON.parse(n)}catch{return null}if(typeof e!="object"||e===null)return null;let t=e;switch(t.type){case"message":return typeof t.text!="string"||typeof t.id!="string"?null:typeof t.channelId=="string"?{type:"message",channelId:t.channelId,text:t.text,threadId:typeof t.threadId=="string"?t.threadId:void 0,id:t.id}:{type:"message",text:t.text,id:t.id};case"image":return typeof t.data!="string"||typeof t.filename!="string"||typeof t.id!="string"?null:typeof t.channelId=="string"?{type:"image",channelId:t.channelId,data:t.data,filename:t.filename,id:t.id}:{type:"image",data:t.data,filename:t.filename,id:t.id};case"file":return typeof t.channelId=="string"&&typeof t.data=="string"&&typeof t.filename=="string"&&typeof t.mimetype=="string"&&typeof t.id=="string"?{type:"file",channelId:t.channelId,data:t.data,filename:t.filename,mimetype:t.mimetype,id:t.id}:null;case"ping":return{type:"ping"};case"join":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"join",channelId:t.channelId,id:t.id}:null;case"leave":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"leave",channelId:t.channelId,id:t.id}:null;case"command":return typeof t.channelId=="string"&&typeof t.name=="string"&&Array.isArray(t.args)&&typeof t.id=="string"?{type:"command",channelId:t.channelId,name:t.name,args:t.args.map(String),id:t.id}:null;case"command_list":return typeof t.id=="string"?{type:"command_list",id:t.id}:null;case"channel_list":return typeof t.id=="string"?{type:"channel_list",id:t.id}:null;case"history":return typeof t.channelId=="string"&&typeof t.id=="string"?{type:"history",channelId:t.channelId,before:typeof t.before=="string"?t.before:void 0,limit:typeof t.limit=="number"?t.limit:void 0,id:t.id}:null;case"agent_list":return typeof t.id=="string"?{type:"agent_list",id:t.id}:null;default:return null}}function Rp(n){return(n.type==="message"||n.type==="image"||n.type==="file")&&"channelId"in n}var Bp=j(()=>{"use strict"});var jp={};Ue(jp,{WsAdapter:()=>kc});import{createServer as av}from"node:http";import{randomUUID as cn}from"node:crypto";function Up(n){let e=n.split(".").pop()?.toLowerCase();return{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",webp:"image/webp",heic:"image/heic"}[e??""]??"image/jpeg"}var Te,kc,qp=j(()=>{"use strict";Pp();M();Bp();Vs();Te=k("ws-adapter"),kc=class{id="ws";kind="app";port;server;wss;connections=new Map;pendingMessages=new Map;onWorkItem;teamStore;commandRegistry;agentRegistry;agentManager;constructor(e,t){this.port=e,this.teamStore=t.teamStore,this.commandRegistry=t.commandRegistry,this.agentRegistry=t.agentRegistry,this.agentManager=t.agentManager}async start(e){this.onWorkItem=e,this.server=av(async(t,s)=>{if(s.setHeader("Access-Control-Allow-Origin","*"),s.setHeader("Access-Control-Allow-Methods","POST, GET, PUT, DELETE, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization"),t.method==="OPTIONS"){s.writeHead(204),s.end();return}let r=new URL(t.url??"/",`http://localhost:${this.port}`);if(t.method==="GET"&&r.pathname==="/health"){s.writeHead(200,{"Content-Type":"application/json"}),s.end(JSON.stringify({status:"ok",connections:this.connections.size}));return}s.writeHead(404),s.end("Not found")}),this.wss=new Sc.default({noServer:!0,maxPayload:10*1024*1024}),this.server.on("upgrade",(t,s,r)=>{let i=new URL(t.url??"/",`http://localhost:${this.port}`);if(i.searchParams.get("internal")!=="1"){s.write(`HTTP/1.1 404 Not Found\r
216
219
  \r
217
220
  `),s.destroy();return}let o=t.socket.remoteAddress??"";if(!(o==="127.0.0.1"||o==="::1"||o==="::ffff:127.0.0.1")){s.write(`HTTP/1.1 403 Forbidden\r
218
221
  \r
219
222
  `),s.destroy();return}let l=i.searchParams.get("deviceId"),c=i.searchParams.get("label")??i.searchParams.get("name"),d=i.searchParams.get("user")??void 0;if(!l||!c){s.write(`HTTP/1.1 400 Bad Request\r
220
223
  \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=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
224
+ `),s.destroy();return}let u=i.searchParams.get("origin")??void 0,h={_id:l,label:c,user:d,defaultAgentId:"",origin:u};this.wss.handleUpgrade(t,s,r,p=>{this.wss.emit("connection",p,t,h)})}),this.wss.on("connection",(t,s,r)=>{let i=r._id;Te.info("Device connected",{deviceId:i,label:r.label});let o=this.pendingMessages.get(i);if(o?.length){Te.info("Draining pending messages",{deviceId:i,count:o.length});for(let l of o)this.send(t,l);this.pendingMessages.delete(i)}let a=this.connections.get(i);a&&a.close(1e3,"Replaced by new connection"),this.connections.set(i,t),t.on("message",async l=>{try{let c=$p(l.toString());if(!c){this.send(t,{type:"error",message:"Invalid message format"});return}if(c.type==="ping")return;if(c.type==="command"){await this.handleCommand(t,c,r,i);return}if(c.type==="command_list"){await this.handleCommandList(t,c);return}if(c.type==="channel_list"){await this.handleChannelList(t,c,i);return}if(c.type==="history"){await this.handleHistory(t,c,i);return}if(c.type==="join"){await this.handleJoin(t,c,i);return}if(c.type==="leave"){await this.handleLeave(t,c,i);return}if(c.type==="agent_list"){let d=this.buildAgentList();this.send(t,{type:"agent_list",agents:d,id:c.id});return}if(Rp(c)){c.type==="message"?await this.handleTeamMessage(t,c,r,i):c.type==="image"?await this.handleTeamImage(t,c,r,i):c.type==="file"&&await this.handleTeamFile(t,c,r,i);return}if(c.type==="message"){this.send(t,{type:"ack",id:c.id});let d={id:c.id||cn(),text:c.text,source:{kind:"app",id:i,label:`app:${r.label}`,adapterId:"ws"},sender:i,senderName:r.label,threadId:`app:${i}`,timestamp:new Date,meta:{deviceId:i,defaultAgentId:r.defaultAgentId,origin:r.origin}};this.onWorkItem(d)}if(c.type==="image"){this.send(t,{type:"ack",id:c.id});let d=Buffer.from(c.data,"base64"),u=Up(c.filename);try{let h=await Gs(d,c.filename,u),p={id:c.id||cn(),text:`[Photo: ${c.filename}]`,source:{kind:"app",id:i,label:`app:${r.label}`,adapterId:"ws"},sender:i,senderName:r.label,threadId:`app:${i}`,timestamp:new Date,files:[h],meta:{deviceId:i,defaultAgentId:r.defaultAgentId,origin:r.origin}};this.onWorkItem(p)}catch(h){Te.error("Image processing failed",{deviceId:i,filename:c.filename,error:String(h)}),this.send(t,{type:"error",message:"Failed to process image"})}}}catch(c){Te.error("Message handling error",{deviceId:i,error:String(c)}),this.send(t,{type:"error",message:"Internal error"})}}),t.on("close",()=>{Te.info("Device disconnected",{deviceId:i}),this.connections.delete(i)}),t.on("error",l=>{Te.error("WebSocket error",{deviceId:i,error:String(l)})})}),await new Promise(t=>{this.server.listen(this.port,"127.0.0.1",()=>{Te.info("WebSocket server listening",{port:this.port,host:"127.0.0.1"}),t()})})}async deliver(e){let t=e.workItem.meta?.deviceId;if(!t){Te.warn("No deviceId in WorkResult, cannot deliver");return}let s=e.error?`Error: ${e.error}`:e.text,r=e.workItem.meta?.channelId,i=this.agentRegistry.get(e.agentId)?.name??e.agentId;r&&await this.teamStore.saveMessage({channelId:r,senderId:e.agentId,senderType:"agent",senderName:i,text:s,createdAt:new Date});let o={type:"message",text:s,agentId:e.agentId,agentName:i,replyTo:e.workItem.id,...r?{channelId:r}:{}},a=this.connections.get(t);if(a&&a.readyState===an.default.OPEN)this.send(a,o);else{Te.info("Device not connected, buffering message",{deviceId:t});let l=this.pendingMessages.get(t)??[];l.push(o),this.pendingMessages.set(t,l)}}async onProcessingStart(e,t){let s=e.meta?.deviceId;if(!s)return;let r=this.connections.get(s);r&&r.readyState===an.default.OPEN&&this.send(r,{type:"typing",agentId:t})}async onProcessingEnd(e,t){}async stop(){for(let[e,t]of this.connections)t.close(1001,"Server shutting down");this.connections.clear(),await new Promise(e=>{this.wss&&this.wss.close(()=>{}),this.server?this.server.close(()=>e()):e()}),Te.info("WebSocket adapter stopped")}get connectionCount(){return this.connections.size}async verifyChannelMembership(e,t,s){let r=await this.teamStore.getChannel(t);return r?r.members.includes(s)?r:(this.send(e,{type:"error",message:"Not a member of this channel"}),null):(this.send(e,{type:"error",message:"Channel not found"}),null)}buildAgentList(){return this.agentRegistry.getAll().map(e=>{let t=this.agentManager.getState(e.id);return{id:e.id,name:e.name,icon:e.icon,title:e.title??null,model:e.model,status:t?.status??"idle",tools:[...new Set([...e.coreServers,...e.delegateServers])].sort(),schedule:e.schedule.map(s=>({cron:s.cron,task:s.task})),channels:e.channels,messagesProcessed:t?.messagesProcessed??0,lastActivity:t?t.lastActivity.toISOString():null}})}async handleTeamMessage(e,t,s,r){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,r);if(!i)return;await this.teamStore.saveMessage({channelId:t.channelId,threadId:t.threadId,senderId:r,senderType:"person",senderName:s.label,text:t.text,createdAt:new Date});let o=i.type==="dm"?i.members.find(l=>l!==r):void 0,a={id:t.id||cn(),text:t.text,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:s.label,threadId:t.threadId??`team:${t.channelId}`,timestamp:new Date,meta:{deviceId:r,channelId:t.channelId,...s.user?{user:s.user}:{},...o?{targetAgentId:o}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(a)}async handleTeamImage(e,t,s,r){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,r);if(!i)return;let o=Buffer.from(t.data,"base64"),a=Up(t.filename);try{let l=await Gs(o,t.filename,a);await this.teamStore.saveMessage({channelId:t.channelId,senderId:r,senderType:"person",senderName:s.label,text:`[Photo: ${t.filename}]`,files:[{name:l.name,mimetype:l.mimetype,size:l.size,storageKey:l.localPath,isImage:!0}],createdAt:new Date});let c=i.type==="dm"?i.members.find(u=>u!==r):void 0,d={id:t.id||cn(),text:`[Photo: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[l],meta:{deviceId:r,channelId:t.channelId,...s.user?{user:s.user}:{},...c?{targetAgentId:c}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(d)}catch(l){Te.error("Team image processing failed",{deviceId:r,filename:t.filename,error:String(l)}),this.send(e,{type:"error",message:"Failed to process image"})}}async handleTeamFile(e,t,s,r){this.send(e,{type:"ack",id:t.id});let i=await this.verifyChannelMembership(e,t.channelId,r);if(!i)return;let o=Buffer.from(t.data,"base64");try{let a=t.mimetype.startsWith("image/")?await Gs(o,t.filename,t.mimetype):await qh(o,t.filename,t.mimetype);await this.teamStore.saveMessage({channelId:t.channelId,senderId:r,senderType:"person",senderName:s.label,text:`[File: ${t.filename}]`,files:[{name:a.name,mimetype:a.mimetype,size:a.size,storageKey:a.localPath,isImage:a.isImage}],createdAt:new Date});let l=i.type==="dm"?i.members.find(d=>d!==r):void 0,c={id:t.id||cn(),text:`[File: ${t.filename}]`,source:{kind:"team",id:t.channelId,label:`team:${i?.name??t.channelId}`,adapterId:"ws"},sender:r,senderName:s.label,threadId:`team:${t.channelId}`,timestamp:new Date,files:[a],meta:{deviceId:r,channelId:t.channelId,...s.user?{user:s.user}:{},...l?{targetAgentId:l}:{defaultAgentId:s.defaultAgentId}}};this.onWorkItem(c)}catch(a){Te.error("Team file processing failed",{deviceId:r,filename:t.filename,error:String(a)}),this.send(e,{type:"error",message:"Failed to process file"})}}async handleCommand(e,t,s,r){if(this.send(e,{type:"ack",id:t.id}),!this.commandRegistry.has(t.name)){this.send(e,{type:"error",message:`Unknown command: /${t.name}`});return}let{result:i}=await this.commandRegistry.execute(t.name,{channelId:t.channelId,senderId:r,senderName:s.label,args:t.args});i&&await this.teamStore.saveMessage({channelId:t.channelId,senderId:"system",senderType:"agent",senderName:"system",text:i,command:{name:t.name,args:t.args,result:i},createdAt:new Date}),this.send(e,{type:"message",text:i??"Done.",agentId:"system",agentName:"system",replyTo:t.id})}async handleCommandList(e,t){let s=this.commandRegistry.list();this.send(e,{type:"command_list",commands:s.map(r=>({name:r.name,description:r.description,args:r.args})),id:t.id})}async handleChannelList(e,t,s){let r=await this.teamStore.listChannels(s);this.send(e,{type:"channel_list",channels:r.map(i=>({id:i._id,type:i.type,name:i.name,members:i.members})),id:t.id})}async handleHistory(e,t,s){if(!await this.verifyChannelMembership(e,t.channelId,s))return;let{messages:r,hasMore:i}=await this.teamStore.getHistory(t.channelId,{before:t.before,limit:t.limit});this.send(e,{type:"history",channelId:t.channelId,messages:r.map(o=>({id:o._id??"",senderId:o.senderId,senderType:o.senderType,senderName:o.senderName,text:o.text,threadId:o.threadId,createdAt:o.createdAt.toISOString()})),hasMore:i,id:t.id})}async handleJoin(e,t,s){if(t.channelId.startsWith("dm:")){let i=await this.teamStore.getChannel(t.channelId);if(!i||!i.members.includes(s)){this.send(e,{type:"error",message:"Cannot join a DM you are not part of"});return}}await this.teamStore.joinChannel(t.channelId,s)?this.send(e,{type:"channel_event",channelId:t.channelId,event:"joined",detail:{memberId:s},id:t.id}):this.send(e,{type:"error",message:"Failed to join channel"})}async handleLeave(e,t,s){await this.teamStore.leaveChannel(t.channelId,s)?this.send(e,{type:"channel_event",channelId:t.channelId,event:"left",detail:{memberId:s},id:t.id}):this.send(e,{type:"error",message:"Failed to leave channel"})}send(e,t){e.readyState===an.default.OPEN&&e.send(JSON.stringify(t))}}});var Fp={};Ue(Fp,{startBeekeeperRegistration:()=>cv});function cv(n){let{beekeeperPort:e,wsPort:t}=n,s=n.intervalMs??3e4,r=`http://127.0.0.1:${e}/internal/register-capability`,i={name:n.capabilityName??"hive",localWsUrl:`ws://127.0.0.1:${t}`,healthUrl:`http://127.0.0.1:${t}/health`},o=JSON.stringify(i),a=async()=>{try{let c=await fetch(r,{method:"POST",headers:{"content-type":"application/json"},body:o});if(c.ok)bc.debug("Registered with beekeeper",{beekeeperPort:e,wsPort:t});else{let d=await c.text().catch(()=>"");bc.warn("Beekeeper registration failed",{status:c.status,body:d})}}catch(c){bc.warn("Beekeeper registration error",{error:String(c)})}};a();let l=setInterval(()=>{a()},s);return{stop:()=>clearInterval(l)}}var bc,Kp=j(()=>{"use strict";M();bc=k("beekeeper-client")});async function Hp(n,e,t){let s=[];n.soul&&s.push(n.soul),s.push(n.systemPrompt);let r=await e.read("shared/constitution.md");r&&s.push(r),s.push(`## Voice Call Mode
222
225
 
223
226
  You are currently on a live phone call. Keep responses conversational and concise \u2014 you are speaking out loud, not writing text. Avoid markdown, bullet points, or long lists. Speak naturally as a human would on the phone. Identify yourself at the start of the call.`),t?.goal&&s.push(`## Call Goal
224
227
 
225
228
  ${t.goal}`),t?.context&&s.push(`## Call Context
226
229
 
227
- ${t.context}`);let i=await e.getHotTierPrompt(r.id,p.memory.hotBudgetTokens);if(i)s.push(i);else{let l=`agents/${r.id}`,c=await e.read(`${l}/memory.md`);c&&s.push(`## Your Memory
230
+ ${t.context}`);let i=await e.getHotTierPrompt(n.id,g.memory.hotBudgetTokens);if(i)s.push(i);else{let l=`agents/${n.id}`,c=await e.read(`${l}/memory.md`);c&&s.push(`## Your Memory
228
231
  ${c}`)}let a=new Date().toLocaleString("en-US",{timeZone:"America/Los_Angeles",weekday:"long",year:"numeric",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0});return s.push(`**Current date/time**: ${a} (Pacific Time)`),s.join(`
229
232
 
230
233
  ---
231
234
 
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)}
235
+ `)}var Wp=j(()=>{"use strict";Ne()});function Gp(n,e){let t=[];for(let s of n)if(s.role!=="system")if(s.role==="user")t.push({role:"user",content:s.content??""});else if(s.role==="assistant")if(s.tool_calls&&s.tool_calls.length>0){let r=[];s.content&&r.push({type:"text",text:s.content});for(let i of s.tool_calls)r.push({type:"tool_use",id:i.id,name:i.function.name,input:lv(i.function.arguments)});t.push({role:"assistant",content:r})}else t.push({role:"assistant",content:s.content??""});else s.role==="tool"&&t.push({role:"user",content:[{type:"tool_result",tool_use_id:s.tool_call_id??"",content:s.content??""}]});return(t.length===0||t[0].role!=="user")&&t.unshift({role:"user",content:"[Call connected]"}),{system:e,messages:t}}function Vp(n){if(!(!n||n.length===0))return n.map(e=>({name:e.function.name,description:e.function.description??"",input_schema:e.function.parameters??{type:"object",properties:{}}}))}function Yp(n,e,t){let s={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,delta:{content:e},finish_reason:null}]};return`data: ${JSON.stringify(s)}
233
236
 
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)}
237
+ `}function _c(n,e,t="stop"){let s={id:n,object:"chat.completion.chunk",created:Math.floor(Date.now()/1e3),model:e,choices:[{index:0,delta:{},finish_reason:t}]};return`data: ${JSON.stringify(s)}
235
238
 
236
239
  data: [DONE]
237
240
 
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:
241
+ `}function Jp(n,e,t){return{id:n,object:"chat.completion",created:Math.floor(Date.now()/1e3),model:t,choices:[{index:0,message:{role:"assistant",content:e},finish_reason:"stop"}]}}function lv(n){if(!n)return{};try{return JSON.parse(n)}catch{return{}}}var zp=j(()=>{"use strict"});var Xp={};Ue(Xp,{VoiceAdapter:()=>vc});import{createServer as dv}from"node:http";import uv from"@anthropic-ai/sdk";import{randomUUID as Qp}from"node:crypto";function fv(n){return new Promise((e,t)=>{let s=[];n.on("data",r=>s.push(r)),n.on("end",()=>e(Buffer.concat(s).toString("utf-8"))),n.on("error",t)})}var Re,hv,vc,Zp=j(()=>{"use strict";M();Wp();zp();Ne();Re=k("voice-adapter"),hv=7200*1e3,vc=class{port;serverSecret;registry;memoryManager;httpServer;anthropic;sessions=new Map;sweepTimer;constructor(e,t,s,r){this.port=e,this.serverSecret=t,this.registry=s,this.memoryManager=r,this.anthropic=new uv}async start(){this.httpServer=dv((e,t)=>{this.handleRequest(e,t).catch(s=>{Re.error("Voice request handler error",{error:String(s)}),t.headersSent||(t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"})))})}),await new Promise(e=>{this.httpServer.listen(this.port,()=>e())}),this.sweepTimer=setInterval(()=>this.sweepStaleSessions(),1800*1e3),Re.info("Voice adapter started",{port:this.port})}stop(){this.sweepTimer&&clearInterval(this.sweepTimer),this.httpServer?.close(),Re.info("Voice adapter stopped")}sweepStaleSessions(){let e=Date.now(),t=0;for(let[s,r]of this.sessions)e-r.startedAt.getTime()>hv&&(this.sessions.delete(s),t++);t>0&&Re.info("Swept stale voice sessions",{count:t})}async handleRequest(e,t){if(!this.serverSecret){Re.error("Voice endpoint called but VAPI_SERVER_SECRET not configured \u2014 rejecting"),t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Server secret not configured"}));return}if((e.headers["x-vapi-secret"]??e.headers["server-secret"]??"")!==this.serverSecret){Re.warn("Voice request rejected \u2014 invalid server secret"),t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="GET"&&e.url==="/health"){t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"ok",activeCalls:this.sessions.size}));return}if(e.method!=="POST"||e.url!=="/v1/chat/completions"){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}));return}let r=await fv(e),i;try{i=JSON.parse(r)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON"}));return}let o=this.resolveAgentId(i);if(!o){Re.error("Could not resolve agent ID from Vapi request"),t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Cannot determine agent identity"}));return}let a=this.registry.get(o);if(!a){Re.error("Agent not found",{agentId:o}),t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:`Agent not found: ${o}`}));return}let l=i.call?.id??Qp();this.sessions.has(l)||(this.sessions.set(l,{callId:l,agentId:o,startedAt:new Date}),Re.info("Voice call session started",{callId:l,agentId:o}));let c=i.call?.metadata,d=await Hp(a,this.memoryManager,{goal:c?.goal,context:c?.context}),{system:u,messages:h}=Gp(i.messages,d),p=Vp(i.tools),m=a.model,f=`chatcmpl-${Qp()}`;if(i.stream===!1){let S=(await this.anthropic.messages.create({model:m,max_tokens:1024,system:u,messages:h,...p?{tools:p}:{}})).content.filter(_=>_.type==="text").map(_=>_.text).join("");t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(Jp(f,S,m)));return}t.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"});try{let y=this.anthropic.messages.stream({model:m,max_tokens:1024,system:u,messages:h,...p?{tools:p}:{}});for await(let w of y)if(w.type==="content_block_delta"){let S=w.delta;S.type==="text_delta"&&t.write(Yp(f,S.text??"",m))}t.writableEnded||t.write(_c(f,m))}catch(y){Re.error("Claude streaming error",{error:String(y),callId:l,agentId:o}),t.writableEnded||t.write(_c(f,m,"error"))}t.end()}resolveAgentId(e){let t=e.assistant?.metadata;if(t?.hive_agent_id)return t.hive_agent_id;let s=e.assistant?.id;if(s&&g.voice.assistants[s])return g.voice.assistants[s];let r=e.call?.metadata;if(r?.hive_agent_id)return r.hive_agent_id}}});ls();xi();import{existsSync as Tc,mkdirSync as pv,watch as mv}from"node:fs";import{resolve as em}from"node:path";import{MongoClient as gv}from"mongodb";M();import{existsSync as Bc,readFileSync as Uc,readdirSync as mm,statSync as xv,writeFileSync as Ov,mkdirSync as Mv}from"node:fs";import{resolve as jc,join as Lv}from"node:path";import{createHash as gm}from"node:crypto";var Oi=k("integrity");function qc(n,e){let t=jc(e,"installed-snapshot.json");if(!Bc(t))return Oi.warn("No installed-snapshot.json \u2014 skipping integrity check (first install?)"),{ok:!0,warnings:[]};let s=JSON.parse(Uc(t,"utf-8"));if(!Array.isArray(s))return{ok:!1,warnings:[`installed-snapshot.json is malformed (expected array, got ${typeof s})`]};let r=s,i=[];for(let o of r){let a=jc(n,o.path);if(!Bc(a)){i.push(`missing: ${o.path}`);continue}let l=Uc(a);gm("sha256").update(l).digest("hex")!==o.hash&&i.push(`modified: ${o.path}`)}if(i.length>0)throw Oi.error("Package integrity check FAILED \u2014 refusing to start",{drift:i}),new Error(`Package integrity check failed. ${i.length} file(s) have been modified or are missing:
239
242
  `+i.map(o=>` - ${o}`).join(`
240
243
  `)+`
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
244
+ Reinstall with: npm install @keepur/hive@<version>`);return{ok:!0,warnings:[]}}function Fc(n){let e=["skills","plugins","workflow","data","agents","logs",".hive",".hive-state",".env","hive.yaml","hive-","beekeeper.yaml",".hive-generated.json"];try{let t=mm(n),s=[];for(let r of t)e.some(i=>r.startsWith(i))||s.push(r);s.length>0&&Oi.warn("Unexpected files in instance directory",{files:s})}catch{}}M();import{existsSync as Mi,readFileSync as ym,writeFileSync as wm,mkdirSync as Sm}from"node:fs";import{resolve as Di}from"node:path";var Kc=k("upgrade-notice");function Hc(n,e){let t=Di(n,"upgrade-notice-emitted");if(Mi(t))return;let s=Di(n,"previous-snapshot.json");if(Mi(s))try{let r=JSON.parse(ym(s,"utf-8")),i=[];for(let l of r)if(typeof l.path=="string"&&l.path.startsWith("skills/")&&l.path.endsWith("SKILL.md")){let c=l.path.match(/^skills\/([^/]+)\//);c&&!Mi(Di(e,c[1]))&&i.push(c[1])}if(i.length===0)return;let o=[...new Set(i)],a=["","=".repeat(72),"Your previous version of hive shipped the following skills in its tarball:",...o.map(l=>` - ${l}`),"","These are no longer part of the hive core package. You can re-install any of","them from the default Keepur registry with:",""," hive skill add <name>","","Agent-authored skills you or your agents wrote on this hive are unaffected and","continue to work. This notice only appears once.","=".repeat(72),""].join(`
245
+ `);Kc.info(a),Sm(n,{recursive:!0}),wm(t,new Date().toISOString())}catch(r){Kc.warn("Failed to check upgrade notice",{error:String(r)})}}Ne();M();M();ya();var X={maxConcurrent:3,timeoutMs:3e5,budgetUsd:10,maxTurns:200,icon:"",keywords:[],passiveChannels:[],delegatePrompts:{},schedule:[],coreServers:["memory","structured-memory","keychain","event-bus","contacts"],delegateServers:[]};function Wu(n,e){return{id:n._id,name:n.name,aliases:n.aliases??[],model:n.model,channels:n.channels??[],homeBase:n.homeBase,catches:n.catches,passiveChannels:n.passiveChannels??X.passiveChannels,keywords:n.keywords??X.keywords,isDefault:n.isDefault??!1,schedule:n.schedule??X.schedule,budgetUsd:n.budgetUsd??X.budgetUsd,maxTurns:n.maxTurns??X.maxTurns,icon:n.icon??X.icon,slackBot:n.slackBot,coreServers:n.coreServers??[...X.coreServers],delegateServers:n.delegateServers??[...X.delegateServers],plugins:n.plugins,maxConcurrent:n.maxConcurrent??X.maxConcurrent,timeoutMs:n.timeoutMs??X.timeoutMs,betas:n.betas,metadata:n.metadata,disabled:n.disabled??!1,subscribe:n.subscribe??[],resourceTiers:n.resourceTiers,delegatePrompts:n.delegatePrompts??X.delegatePrompts,soul:n.soul??"",systemPrompt:n.systemPrompt??"",archetype:n.archetype,title:n.title,archetypeConfig:n.archetypeConfig,autonomy:Bu(e,n.autonomy)}}Ne();gr();gr();import{statSync as p0}from"node:fs";import{normalize as Yu,resolve as Ju}from"node:path";var zu=new Set(["linear","github","clickup"]);function Xu(n){if(!n||typeof n!="object")throw new Error("software-engineer archetypeConfig must be an object");let e=n;if(typeof e.workshop!="string"||!e.workshop.startsWith("/"))throw new Error("workshop must be an absolute path");let t=Yu(e.workshop);Qu(t,"workshop");let s=e.workspaces??[];if(!Array.isArray(s))throw new Error("workspaces must be an array");let r=new Set,i=s.map((o,a)=>{if(!o||typeof o!="object")throw new Error(`workspaces[${a}]: must be an object`);let l=o;if(typeof l.name!="string"||l.name.length===0)throw new Error(`workspaces[${a}]: name is required`);if(r.has(l.name))throw new Error(`workspaces[${a}]: duplicate workspace name "${l.name}"`);if(r.add(l.name),typeof l.path!="string"||!l.path.startsWith("/"))throw new Error(`workspaces[${a}] (${l.name}): path must be an absolute path`);let c=Yu(l.path);Qu(c,`workspaces[${a}] (${l.name})`);let d=Ju(c),u=Ju(t);if(!d.startsWith(u+"/"))throw new Error(`workspaces[${a}] (${l.name}): path must be inside workshop (${t}), got ${c}`);if(!l.tracker||typeof l.tracker!="object")throw new Error(`workspaces[${a}] (${l.name}): tracker is required`);let h=l.tracker;if(typeof h.type!="string"||!zu.has(h.type))throw new Error(`workspaces[${a}] (${l.name}): tracker.type must be one of: ${[...zu].join(", ")}`);return m0(h,a,l.name),{name:l.name,path:c,tracker:h,...l.primary===!0?{primary:!0}:{}}});return{workshop:t,workspaces:i}}function Qu(n,e){let t;try{t=p0(n)}catch{throw new Error(`${e}: path does not exist: ${n}`)}if(!t.isDirectory())throw new Error(`${e}: path is not a directory: ${n}`)}function m0(n,e,t){switch(n.type){case"linear":if(typeof n.project!="string"||n.project.length===0)throw new Error(`workspaces[${e}] (${t}): linear tracker requires project`);break;case"github":if(typeof n.repo!="string"||n.repo.length===0)throw new Error(`workspaces[${e}] (${t}): github tracker requires repo`);break;case"clickup":if(typeof n.list!="string"||n.list.length===0)throw new Error(`workspaces[${e}] (${t}): clickup tracker requires list`);break}}function Zu(n){let e=n.archetypeConfig,t=n.agentConfig.title||n.agentConfig.name,s=[];s.push(`# Software Engineer
243
246
 
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=d0(i.tracker),a=i.primary?" (primary)":"";n.push(`- **${i.name}**${a}: \`${i.path}\` \u2014 tracker: ${o}`)}}else n.push(`
246
- No workspaces configured yet. You have full agency over your entire workshop.`);return s.push(n.join(`
247
+ You are a software engineer. Your title is ${t}. Your discipline is owning codebases and shipping production code through disciplined delivery.`);let r=[`Your workshop is \`${e.workshop}\`. This is your working directory.`];if(e.workspaces.length>0){r.push(`
248
+ Workspaces:`);for(let i of e.workspaces){let o=g0(i.tracker),a=i.primary?" (primary)":"";r.push(`- **${i.name}**${a}: \`${i.path}\` \u2014 tracker: ${o}`)}}else r.push(`
249
+ No workspaces configured yet. You have full agency over your entire workshop.`);return s.push(r.join(`
247
250
  `)),e.workspaces.length>0&&s.push("## Workshop vs Workspace Policy\n\n**Workshop** (outside workspaces): You have full agency. Read, write, create, edit freely. This is your prototyping space, scratch area, and coordination point.\n\n**Workspaces**: Delegate-only. You MUST NOT directly edit, write, or create files inside a workspace. All code changes inside workspaces flow through `code_task`. This preserves the spec \u2192 plan \u2192 PR \u2192 CI discipline.\n\nIf you attempt to Edit or Write inside a workspace, the tool will be blocked with an error. This is intentional. Use `code_task` instead.\n\nInside workspaces, ALL execution \u2014 including git, npm, builds, test runs \u2014 flows through `code_task`. Your working directory is your workshop; treat all relative file paths accordingly. Reference workspace source only via absolute paths or through `code_task`."),s.push(`## Workflow: Ticket as Spec
248
251
 
249
252
  Every piece of work starts with a ticket. The ticket description IS the spec. Write ticket descriptions that a developer can implement from \u2014 problem statement, approach, and acceptance criteria.
@@ -269,7 +272,7 @@ A task is done when ALL of these are true:
269
272
  - **Always** verify PR + CI status before closing a ticket
270
273
  - **Always** file a ticket before delegating work`),s.join(`
271
274
 
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-7"};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.
275
+ `)}function g0(n){switch(n.type){case"linear":return`Linear (project: ${n.project})`;case"github":return`GitHub Issues (repo: ${n.repo})`;case"clickup":return`ClickUp (list: ${n.list})`;default:return n.type}}import{resolve as y0}from"node:path";import{normalize as eh,resolve as th}from"node:path";function ba(n){if(typeof n!="string"||!n.startsWith("/"))throw new Error(`claudeProjectSlug: path must be absolute, got ${String(n)}`);return n.replace(/\/+$/,"").replace(/[/_.]/g,"-").replace(/-+/g,"-")}function sh(n,e){let t=eh(th(n));return e.workspaces.find(s=>{let r=eh(th(s.path));return t===r||t.startsWith(r+"/")})}function nh(n){return ba(n.workshop)}function rh(n){return ba(n.path)}var w0=new Set(["Edit","Write","MultiEdit","NotebookEdit"]);function S0(n,e){return n==="NotebookEdit"?e.notebook_path??e.file_path:e.file_path}function ih(n){let e=n.archetypeConfig;return e.workspaces.length===0?[]:[{hooks:[async t=>{try{let s=t,r=s.tool_name??"";if(!w0.has(r))return{continue:!0};let i=S0(r,s.tool_input??{});if(typeof i!="string"||i.length===0)return{continue:!0};let o=y0(e.workshop,i),a=sh(o,e);return a?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`${r} blocked: \`${o}\` is inside workspace \`${a.name}\`. Code changes inside workspaces flow through \`code_task\`, not direct edits \u2014 this preserves the spec \u2192 plan \u2192 PR \u2192 CI discipline. If you're drafting a prototype, work inside the workshop outside any workspace. If you're ready to implement against a ticket, use \`code_task\` with the ticket ID.`}}:{continue:!0}}catch(s){return{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:`Software-engineer hook internal error: ${String(s)}. All file mutations blocked until the archetype is fixed.`}}}}]}]}import{homedir as k0}from"node:os";import{join as oh}from"node:path";function ah(n){let e=n.archetypeConfig,t=k0(),s=[];s.push({id:"workshop",backing:"filesystem",dir:oh(t,".claude/projects",nh(e),"memory")});for(let r of e.workspaces)s.push({id:`workspace:${r.name}`,backing:"filesystem",dir:oh(t,".claude/projects",rh(r),"memory")});return s}function ch(n){return{cwd:n.archetypeConfig.workshop,settingSources:["project"]}}Vu({id:"software-engineer",description:"Owns codebases and ships production code through disciplined delivery (ticket \u2192 spec \u2192 PR \u2192 CI \u2192 close).",whenToUse:"Pick this when the agent's core job is writing, reviewing, or shipping production code. For product strategists, marketers, or anyone where code is incidental, use a plain agent.",configSchema:{workshop:{type:"string",required:!0,description:"Absolute filesystem path \u2014 the engineer's bounded root directory (e.g. /Users/you/dev)."},workspaces:{type:"array",required:!1,description:"Registered codebases inside the workshop. Do NOT prompt for these at creation time \u2014 workspace registration is a separate admin flow. Start with an empty array."}},validateConfig:Xu,systemPromptCard:Zu,preToolUseHooks:ih,memoryScopes:ah,sessionOptions:ch});var pe=k("agent-registry"),lh=3e4,yr=class{agents=new Map;originToAgent=new Map;disabledAgents=[];agentDefs;changeStream=null;pollTimer=null;lastPollTime=new Date(0);onReload;constructor(e,t){this.agentDefs=e,this.onReload=t}async load(){let e=await this.agentDefs.find().toArray(),t=new Set(this.agents.keys()),s=new Set,r=[],i=[],o=[],a=[];for(let l of e){let c=Wu(l,g.autonomy);if(s.add(c.id),c.disabled){a.push(c),this.agents.has(c.id)&&(this.agents.delete(c.id),o.push(c.id),pe.info("Disabled agent removed from active map",{id:c.id}));continue}if(c.archetype){let d=mr(c.archetype);if(!d)pe.warn("Unknown archetype \u2014 loading agent as unstructured",{id:c.id,archetype:c.archetype}),c.archetype=void 0,c.archetypeConfig=void 0;else try{c.archetypeConfig=d.validateConfig(c.archetypeConfig)}catch(u){pe.error("Archetype config validation failed \u2014 agent will not load",{id:c.id,archetype:c.archetype,error:String(u)}),this.agents.has(c.id)&&(this.agents.delete(c.id),o.push(c.id),pe.warn("Evicted previously-loaded agent due to archetype validation failure",{id:c.id}));continue}}t.has(c.id)?i.push(c.id):r.push(c.id),this.agents.set(c.id,c),pe.info("Loaded agent",{id:c.id,name:c.name})}this.disabledAgents=a;for(let l of t)s.has(l)||(this.agents.delete(l),o.push(l),pe.info("Removed agent",{id:l}));return this.lastPollTime=new Date,this.rebuildOriginIndex(),{added:r,updated:i,removed:o}}async startWatching(){try{this.changeStream=this.agentDefs.watch([],{fullDocument:"updateLookup"}),this.changeStream.on("change",()=>{pe.info("Agent definition changed (change stream), triggering reload"),this.onReload?.()}),this.changeStream.on("error",e=>{pe.warn("Change stream error, falling back to polling",{error:String(e)}),this.changeStream=null,this.startPolling()}),pe.info("Agent registry watching via change stream")}catch{pe.info("Change stream not available, using polling fallback"),this.startPolling()}}startPolling(){this.pollTimer=setInterval(async()=>{try{let e=await this.agentDefs.countDocuments({updatedAt:{$gt:this.lastPollTime}});e>0&&(pe.info("Agent definitions changed (poll), triggering reload",{changed:e}),this.onReload?.())}catch(e){pe.error("Poll check failed",{error:String(e)})}},lh),pe.info("Agent registry watching via polling",{intervalMs:lh})}rebuildOriginIndex(){this.originToAgent.clear();let e=[...this.agents.values()].sort((t,s)=>t.id.localeCompare(s.id));for(let t of e)for(let s of t.catches??[]){if(this.originToAgent.has(s)){pe.error("Origin conflict \u2014 first sorted agent wins",{origin:s,winner:this.originToAgent.get(s),loser:t.id});continue}this.originToAgent.set(s,t.id)}}stopWatching(){this.changeStream&&(this.changeStream.close().catch(()=>{}),this.changeStream=null),this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=null)}get(e){return this.agents.get(e)}getAll(){return Array.from(this.agents.values())}async getAllDefinitions(){return this.agentDefs.find().toArray()}listIds(){return Array.from(this.agents.keys())}findByChannel(e){return this.getAll().find(t=>!t.disabled&&t.channels.includes(e))}findByOrigin(e){let t=this.originToAgent.get(e);return t?this.agents.get(t):void 0}isPassiveChannel(e){return this.getAll().some(t=>!t.disabled&&t.passiveChannels.includes(e))}findByKeyword(e){let t=e.toLowerCase();return this.getAll().find(s=>!s.disabled&&s.keywords.some(r=>{let i=r.toLowerCase().replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`\\b${i}\\b`).test(t)}))}findByName(e){return this.findAllByName(e)[0]}findAllByName(e){return this.getAll().filter(t=>{if(t.disabled)return!1;if(this.matchesName(t.name,e))return!0;if(t.name.includes(" ")){let s=t.name.split(" ")[0];if(this.matchesName(s,e))return!0}for(let s of t.aliases)if(this.matchesName(s,e))return!0;return!1})}matchesName(e,t){let s=e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(?:^|hey\\s+|@)${s}\\b|\\b${s}[,:]`,"i").test(t)}getDefault(){return this.getAll().find(e=>!e.disabled&&e.isDefault)}getDisabled(){return this.disabledAgents}getSubscriberMap(){let e={};for(let t of this.getAll())if(!t.disabled)for(let s of t.subscribe??[]){let r=s.includes(":")?s.split(":")[0]:s;e[r]||(e[r]=[]),e[r].includes(t.id)||e[r].push(t.id)}return e}};M();La();Vs();M();Ne();import{query as sk}from"@anthropic-ai/claude-agent-sdk";var Ys=k("model-router"),nk={haiku:{timeoutMs:12e4,maxTurns:20,budgetUsd:1},sonnet:{timeoutMs:3e5,maxTurns:50,budgetUsd:5},opus:{timeoutMs:6e5,maxTurns:200,budgetUsd:50}};function Ar(n,e){let t=nk[n],s=e?.[n];return s?{timeoutMs:s.timeoutMs??t.timeoutMs,maxTurns:s.maxTurns??t.maxTurns,budgetUsd:s.budgetUsd??t.budgetUsd}:{...t}}var ht={haiku:0,sonnet:1,opus:2},Cr={haiku:"claude-haiku-4-5-20251001",sonnet:"claude-sonnet-4-6",opus:"claude-opus-4-7"};function rk(n){return n.includes("opus")?"opus":n.includes("haiku")?"haiku":"sonnet"}var ik=`You are a model router. Your job is to classify the complexity of a user message and decide which AI model tier should handle it.
273
276
 
274
277
  Tiers:
275
278
  - **haiku**: Greetings, simple factual questions, acknowledgments, status checks, yes/no answers, brief lookups, routine updates. Fast and cheap.
@@ -282,33 +285,33 @@ Rules:
282
285
  - Look at the TASK complexity, not the message length.
283
286
  - Scheduled/cron tasks that say "execute your scheduled X task" are routine \u2192 haiku unless the task itself is complex.
284
287
 
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,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+`
288
+ Respond with ONLY a JSON object: { "tier": "haiku" | "sonnet" | "opus" }`;function ok(n){try{let s=JSON.parse(n);if(s.tier&&ht[s.tier]!==void 0)return s.tier}catch{}let e=n.indexOf("{"),t=n.lastIndexOf("}");if(e!==-1&&t>e)try{let s=JSON.parse(n.slice(e,t+1));if(s.tier&&ht[s.tier]!==void 0)return s.tier}catch{}return null}async function Hh(n,e,t){let s=rk(e),r=g.modelRouter.model;if(s==="haiku")return{tier:"haiku",model:Cr.haiku,costUsd:0,durationMs:0,resourceLimits:Ar("haiku",t)};let i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Ys.warn("Model router timed out",{timeoutMs:g.modelRouter.timeoutMs}),i.close())},g.modelRouter.timeoutMs);try{i=sk({prompt:n,options:{model:r,systemPrompt:ik,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let p=h;if(p.type==="assistant"){let m=p.message?.content;if(Array.isArray(m))for(let f of m)f.type==="text"&&(o=f.text)}if(p.type==="result"){let m=p;a=m.total_cost_usd,l=m.duration_ms,m.subtype==="success"&&m.result&&(o=m.result)}}}catch(h){Ys.warn("Model router query failed, defaulting to sonnet",{error:String(h)});let p=ht[s]>=ht.sonnet?"sonnet":s;return{tier:p,model:Cr[p],costUsd:0,durationMs:0,resourceLimits:Ar(p,t)}}finally{clearTimeout(c),i=null}let d=ok(o);if(!d){Ys.warn("Model router parse failed, defaulting to sonnet",{rawText:o.slice(0,200)});let h=ht[s]>=ht.sonnet?"sonnet":s;return{tier:h,model:Cr[h],costUsd:0,durationMs:0,resourceLimits:Ar(h,t)}}let u=d;return ht[d]>ht[s]&&(u=s,Ys.debug("Model router capped by ceiling",{requested:d,ceiling:s})),Ys.info("Model router decision",{tier:u,requested:d,ceiling:s,costUsd:a,durationMs:l,textPreview:n.slice(0,100)}),{tier:u,model:Cr[u],costUsd:a,durationMs:l,resourceLimits:Ar(u,t)}}Ne();kr();xa();ls();import{existsSync as Wh,readdirSync as lk,statSync as dk}from"node:fs";import{join as Gh}from"node:path";Er();import{QdrantClient as ck}from"@qdrant/js-client-rest";var Nr="conversations",xr=class{qdrantUrl;ollamaUrl;qdrant=null;collectionReady=!1;constructor(e,t){this.qdrantUrl=e??process.env.QDRANT_URL??"http://localhost:6333",this.ollamaUrl=t??process.env.OLLAMA_URL??"http://localhost:11434"}getClient(){return this.qdrant||(this.qdrant=new ck({url:this.qdrantUrl})),this.qdrant}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(r=>r.name===Nr)){let i=(await He(this.ollamaUrl,"test")).length;await e.createCollection(Nr,{vectors:{size:i,distance:"Cosine"}})}this.collectionReady=!0}async index(e){await this.ensureCollection();let t=this.getClient(),s=e.inbound+`
286
289
 
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+`
290
+ `+e.response,r=await He(this.ollamaUrl,s),i=crypto.randomUUID();await t.upsert(Nr,{points:[{id:i,vector:r,payload:{agentId:e.agentId,threadId:e.threadId,channelId:e.channelId,source:e.source,senderName:e.senderName,timestampUnix:e.timestampUnix,timestamp:e.timestamp,inbound:e.inbound,response:e.response}}]})}async search(e,t,s,r){await this.ensureCollection();let i=this.getClient(),o=await He(this.ollamaUrl,e),a=[{key:"agentId",match:{value:t}}];return r!==void 0&&a.push({key:"timestampUnix",range:{gte:r}}),(await i.search(Nr,{vector:o,limit:s,with_payload:!0,filter:{must:a}})).map(c=>({agentId:c.payload?.agentId,threadId:c.payload?.threadId,channelId:c.payload?.channelId,source:c.payload?.source,senderName:c.payload?.senderName,timestampUnix:c.payload?.timestampUnix,timestamp:c.payload?.timestamp,inbound:c.payload?.inbound,response:c.payload?.response,score:c.score}))}};var ae=k("agent-manager"),uk=new xr;function hk(n){if(!Wh(n))return[];try{return lk(n).map(e=>Gh(n,e)).filter(e=>{try{return dk(e).isDirectory()&&Wh(Gh(e,"skills"))}catch{return!1}})}catch{return[]}}var Or=class{states=new Map;queues=new Map;processing=new Set;activeRunners=new Map;activeThreads=new Map;registry;memoryManager;sessionStore;plugins;seedDirs;skillIndex;activityLogger;prefetcher;activeWorkItems=new Map;spawnWindow=new Map;constructor(e,t,s,r,i){this.registry=e,this.memoryManager=t,this.sessionStore=s,this.activityLogger=r,this.prefetcher=i,this.plugins=va(g.plugins,V,{distDir:Ke}),this.seedDirs=hk(Nc),this.skillIndex=Na(Xe,this.plugins,this.seedDirs)}getPlugins(){return this.plugins}getActiveWorkItems(e){return this.activeWorkItems.get(e)??[]}createRunner(e){let t=this.registry.get(e);if(!t)throw new Error(`Unknown agent: ${e}`);let s=JSON.stringify(this.registry.getSubscriberMap());return new Ws(t,this.memoryManager,this.plugins,this.skillIndex,s,this.prefetcher)}reloadSkills(){try{this.skillIndex=Na(Xe,this.plugins,this.seedDirs)}catch(e){ae.warn("Skill reload failed, retaining previous index",{error:String(e)})}}rescanPlugins(){let{rescued:e,stillBroken:t}=Ta(this.plugins,V,{distDir:Ke});Object.values(e).reduce((i,o)=>i+o.length,0)>0&&ae.info("Plugin MCP servers rescued after rescan",{rescued:e}),Object.values(t).reduce((i,o)=>i+o.length,0)>0&&ae.warn("Plugin MCP servers still unresolvable after rescan",{stillBroken:t})}recordSpawn(e){let t=Date.now(),s=6e4,r=(this.spawnWindow.get(e)??[]).filter(i=>t-i<s);if(r.push(t),this.spawnWindow.set(e,r),r.length>3&&ae.warn("Session spawn rate exceeded",{channelId:e,count:r.length,windowSec:60}),this.spawnWindow.size>200){let i=this.spawnWindow.keys().next().value;i&&this.spawnWindow.delete(i)}}ensureState(e){this.states.has(e)||this.states.set(e,{id:e,status:"idle",lastActivity:new Date,messagesProcessed:0,errorCount:0,activeThreadCount:0})}async sendMessage(e,t,s){this.ensureState(e);let r=t.threadId??t.id,i=`${e}:${r}`;return new Promise((o,a)=>{let l=this.queues.get(i)??[];l.push({message:t,onStream:s,resolve:o,reject:a}),this.queues.set(i,l),this.processThreadQueue(e,i).catch(c=>{ae.error("processThreadQueue failed unexpectedly",{agentId:e,threadKey:i,error:String(c)}),this.processing.delete(i);let d=this.activeThreads.get(e);d&&(d.delete(i),this.updateThreadCount(e),d.size===0&&this.updateStatus(e,"idle"));let u=this.queues.get(i);if(u){for(let h of u)h.reject(c instanceof Error?c:new Error(String(c)));this.queues.delete(i)}this.retryDeferredThreads(e)})})}async processThreadQueue(e,t){if(this.processing.has(t))return;let s=this.queues.get(t);if(!s||s.length===0)return;let r=this.registry.get(e),i=r?.maxConcurrent??3,o=this.activeThreads.get(e)??new Set;if(o.size>=i){ae.debug("Agent at concurrency limit, deferring",{agentId:e,threadKey:t,active:o.size,limit:i});return}this.processing.add(t),o.add(t),this.activeThreads.set(e,o),this.updateStatus(e,"processing"),this.updateThreadCount(e);let a=this.createRunner(e),l=this.activeRunners.get(e)??new Set;l.add(a),this.activeRunners.set(e,l);let c=0,d,u;for(;s.length>0;){let m=s.shift(),f=this.activeWorkItems.get(e)??[];f.push(m.message),this.activeWorkItems.set(e,f);try{let y=m.message.threadId??m.message.id,w=await this.sessionStore.get(e,y);w||this.recordSpawn(m.message.source.id);let S={adapterId:m.message.source.adapterId??m.message.source.kind,channelId:m.message.source.id,channelKind:m.message.source.kind,channelLabel:m.message.source.label,threadId:m.message.threadId??m.message.id,slackTs:m.message.meta?.slackTs??"",slackThreadTs:m.message.meta?.slackThreadTs??""},_=m.message.senderName??m.message.sender,v=m.message.source.kind==="team"?m.message.meta?.user:void 0,I;if(v)I=`[user:${v} via ${_} in #${m.message.source.label}]: ${m.message.text}`;else if(m.message.senderName){let W=m.message.meta?.slackThreadTs,$=m.message.meta?.slackTs,le=W??$,Ie=le?`, thread=${le}`:"";I=`[${_} in #${m.message.source.label}${Ie}]: ${m.message.text}`}else I=m.message.text;m.message.files?.length&&(I+=Fh(m.message.files));let N,D=0,A;if(g.modelRouter.enabled&&m.message.sender!=="system")try{let W=this.registry.get(e);if(W){let $=await Hh(m.message.text,W.model,W.resourceTiers);N=$.model!==W.model?$.model:void 0,D=$.costUsd,A=$.resourceLimits}}catch(W){ae.warn("Model router failed, using default",{agentId:e,error:String(W)})}let E=await a.send(I,w,m.onStream,S,N,A);E.costUsd+=D,E.sessionId&&!E.aborted&&this.sessionStore.set(e,y,E.sessionId,{inputTokens:E.inputTokens,outputTokens:E.outputTokens,cacheReadTokens:E.cacheReadTokens,cacheCreationTokens:E.cacheCreationTokens,contextWindow:E.contextWindow,compactions:E.compactions,preCompactTokens:E.preCompactTokens});let G=this.states.get(e);G.messagesProcessed++,G.lastActivity=new Date,G.currentSessionId=E.sessionId,E.error&&(G.errorCount++,w&&this.sessionStore.delete(e,y)),m.resolve(E),c++,d=m,u=E,E.text&&!E.error&&uk.index({agentId:e,threadId:y,channelId:m.message.source.id,source:m.message.source.kind,senderName:m.message.senderName??"unknown",timestampUnix:Math.floor(Date.now()/1e3),timestamp:new Date().toISOString(),inbound:I,response:E.text}).catch(W=>ae.warn("Conversation indexing failed",{agentId:e,error:String(W)})),this.activityLogger?.record({agentId:e,threadId:y,timestamp:new Date,sender:m.message.sender,senderName:m.message.senderName,channel:m.message.source.label,channelKind:m.message.source.kind,model:N??r?.model??"unknown",modelTier:void 0,costUsd:E.costUsd,durationMs:E.durationMs,inputTokens:E.inputTokens,outputTokens:E.outputTokens,contextWindow:E.contextWindow,toolCalls:E.toolCalls,toolSummary:E.toolSummary,compactions:E.compactions,streamed:E.streamed,error:E.error})}catch(y){let w=this.states.get(e);w&&(w.errorCount++,w.lastActivity=new Date),this.activityLogger?.record({agentId:e,threadId:m.message.threadId??m.message.id,timestamp:new Date,sender:m.message.sender,senderName:m.message.senderName,channel:m.message.source.label,channelKind:m.message.source.kind,model:r?.model??"unknown",costUsd:0,durationMs:0,inputTokens:0,outputTokens:0,contextWindow:0,toolCalls:0,toolSummary:"none",compactions:0,streamed:!1,error:String(y)}),m.reject(y instanceof Error?y:new Error(String(y)))}finally{let y=(this.activeWorkItems.get(e)??[]).filter(w=>w.id!==m.message.id);y.length===0?this.activeWorkItems.delete(e):this.activeWorkItems.set(e,y)}}let h=[...r?.coreServers??[],...r?.delegateServers??[]];if((h.includes("memory")||h.includes("structured-memory"))&&u&&d&&!u.error&&!u.aborted&&c>=g.memory.reflectionMinTurns&&d.message.sender!=="system")try{let m=["[System \u2014 end of conversation reflection]","This conversation is wrapping up. Review what was discussed:","- Were any new facts, decisions, or commitments made?","- Did anything contradict or update what you previously knew?","- Should any existing memories be updated or forgotten?","","If yes, use memory_save, memory_update, or memory_forget now.","If nothing worth saving, do nothing."].join(`
291
+ `),f=await a.send(m,u.sessionId);if(ae.info("Reflection completed",{agentId:e,threadKey:t,turnCount:c,costUsd:f.costUsd,toolCalls:f.toolCalls,toolSummary:f.toolSummary||void 0}),f.sessionId&&!f.aborted){let y=d.message.threadId??d.message.id;this.sessionStore.set(e,y,f.sessionId,{inputTokens:f.inputTokens,outputTokens:f.outputTokens,cacheReadTokens:f.cacheReadTokens,cacheCreationTokens:f.cacheCreationTokens,contextWindow:f.contextWindow,compactions:f.compactions,preCompactTokens:f.preCompactTokens})}}catch(m){ae.warn("Reflection failed, non-critical",{agentId:e,threadKey:t,error:String(m)})}l.delete(a),this.processing.delete(t),o.delete(t),this.queues.delete(t),this.updateThreadCount(e),o.size===0&&this.updateStatus(e,"idle"),this.retryDeferredThreads(e)}updateThreadCount(e){let t=this.states.get(e);t&&(t.activeThreadCount=this.activeThreads.get(e)?.size??0)}retryDeferredThreads(e){let t=`${e}:`;for(let[s,r]of this.queues)if(s.startsWith(t)&&r.length>0&&!this.processing.has(s)){this.processThreadQueue(e,s);break}}updateStatus(e,t){let s=this.states.get(e);s&&(s.status=t,ae.debug("Agent status changed",{agentId:e,status:t}))}getState(e){return this.states.get(e)}getAllStates(){return Array.from(this.states.values())}stopAgent(e){let t=this.activeRunners.get(e);if(t){for(let s of t)s.abort();t.clear()}this.activeRunners.delete(e),this.activeThreads.delete(e),this.updateStatus(e,"stopped")}stopAll(){for(let e of this.states.keys())this.stopAgent(e);ae.info("All agents stopped")}async findAgentForThread(e){return this.sessionStore.findAgentByThread(e)}async findAgentsForThread(e){return this.sessionStore.findAgentsByThread(e)}restartAgent(e){this.stopAgent(e),this.sessionStore.clearAgent(e),this.states.set(e,{id:e,status:"idle",lastActivity:new Date,messagesProcessed:0,errorCount:0,activeThreadCount:0}),ae.info("Agent restarted",{agentId:e})}sweep(){let e=0,t=[];for(let[r,i]of this.states)!this.registry.get(r)&&(i.status==="stopped"||i.status==="idle")&&(this.states.delete(r),this.activeRunners.delete(r),this.activeThreads.delete(r),e++,ae.info("Zombie agent state removed",{agentId:r}));for(let r of this.processing){let i=r.split(":")[0],o=this.activeRunners.get(i);if(!o||o.size===0){this.processing.delete(r);let a=this.activeThreads.get(i);a&&(a.delete(r),this.updateThreadCount(i),a.size===0&&this.updateStatus(i,"idle")),e++,ae.warn("Stuck processing flag cleared",{threadKey:r,agentId:i});let l=this.queues.get(r);l&&l.length>0&&this.processThreadQueue(i,r).catch(c=>{ae.error("Failed to restart stuck queue",{threadKey:r,error:String(c)})})}}let s=new Set;for(let r of this.queues.keys())s.add(r.split(":")[0]);for(let r of s)this.retryDeferredThreads(r);return{component:"agent-manager",pruned:e,retried:0,bytesFreed:0,errors:t}}};M();Vs();import{SocketModeClient as pk}from"@slack/socket-mode";import{WebClient as mk}from"@slack/web-api";M();var fk=k("outbound-ts-cache"),Mr=class{entries=new Map;ttlMs;maxSize;constructor(e={}){this.ttlMs=e.ttlMs??12e4,this.maxSize=e.maxSize??1e4}register(e,t){if(this.evictExpired(),this.entries.size>=this.maxSize){let s=this.entries.keys().next().value;s&&this.entries.delete(s)}this.entries.set(this.key(e,t),Date.now()+this.ttlMs)}has(e,t){let s=this.entries.get(this.key(e,t));return s===void 0?!1:s<=Date.now()?(this.entries.delete(this.key(e,t)),!1):!0}size(){return this.entries.size}key(e,t){return`${e}:${t}`}evictExpired(){let e=Date.now(),t=0;for(let[s,r]of this.entries)r<=e&&(this.entries.delete(s),t++);t>0&&fk.debug(`evicted ${t} expired entries`,{evicted:t})}};var K=k("slack-gateway"),Dr=class n{socket;web;messageHandler=null;threadStartedHandler=null;threadContextHandler=null;botUserId=null;botId=null;peerBotUserIds=new Set;peerBotIds=new Set;channelNameCache=new Map;channelIdCache=new Map;userNameCache=new Map;outboundTsCache=new Mr;integrationChannels=new Set;botToken;constructor(e,t){this.socket=new pk({appToken:e}),this.web=new mk(t),this.botToken=t}addIntegrationChannels(e){for(let t of e)this.integrationChannels.add(t)}addPeerBotIds(e,t){e&&this.peerBotUserIds.add(e),t&&this.peerBotIds.add(t),K.info("Peer bot IDs registered",{peerBotUserIds:[...this.peerBotUserIds],peerBotIds:[...this.peerBotIds]})}get resolvedBotUserId(){return this.botUserId}get resolvedBotId(){return this.botId}onMessage(e){this.messageHandler=e}onThreadStarted(e){this.threadStartedHandler=e}onThreadContextChanged(e){this.threadContextHandler=e}async start(){let e=await this.web.auth.test();this.botUserId=e.user_id,this.botId=e.bot_id??null,K.info("Bot identity resolved",{botUserId:this.botUserId,botId:this.botId}),this.socket.on("message",async({event:t,ack:s})=>{if(await s(),!t||(K.debug("Raw message event",{subtype:t.subtype,bot_id:t.bot_id,user:t.user,channel:t.channel,hasText:!!t.text,hasAttachments:!!t.attachments?.length,hasBlocks:!!t.blocks?.length}),t.user===this.botUserId)||this.peerBotUserIds.has(t.user)||t.bot_id&&t.bot_id===this.botId||t.bot_id&&this.peerBotIds.has(t.bot_id))return;if(t.ts&&t.channel&&this.outboundTsCache.has(t.channel,t.ts)){K.info("Outbound echo suppressed",{channel:t.channel,ts:t.ts});return}if(t.bot_id||t.subtype){let l=await this.resolveChannelName(t.channel);if(!this.integrationChannels.has(l)){K.info("Message filtered (subtype/bot in non-integration channel)",{channel:t.channel,channelName:l,user:t.user,subtype:t.subtype,bot_id:t.bot_id,hasText:!!t.text});return}K.info("Integration message accepted",{channelName:l,subtype:t.subtype,bot_id:t.bot_id})}let r=await this.resolveChannelName(t.channel),i=t.text??"";if(!i){let l=[...t.blocks??[]];for(let c of t.attachments??[])c.blocks&&l.push(...c.blocks),c.text&&(i+=c.text+`
289
292
  `);i||(i=l.filter(c=>c.type==="section"||c.type==="rich_text").map(c=>c.text?.text?c.text.text:c.elements?c.elements.map(d=>d.elements?.map(u=>u.text||"").join("")??"").join(`
290
293
  `):"").filter(Boolean).join(`
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(`
294
+ `)),i=i.trim()}let o=[];if(t.files?.length&&(K.info("Processing file attachments",{count:t.files.length,names:t.files.map(c=>c.name)}),o=(await Promise.all(t.files.map(c=>jh(c,this.botToken)))).filter(Boolean)),!i&&o.length===0){K.info("Skipping message with no extractable text or files",{channel:t.channel,channelName:r,user:t.user,subtype:t.subtype,hasBlocks:!!t.blocks?.length,hasAttachments:!!t.attachments?.length,blockTypes:t.blocks?.map(l=>l.type)});return}!i&&o.length>0&&(i=`[shared ${o.length} file${o.length>1?"s":""}]`),i=await this.resolveUserMentions(i);let a={text:i,channel:t.channel,channelName:r,user:t.user??t.bot_id??"unknown",ts:t.ts,threadTs:t.thread_ts,files:o.length>0?o:void 0};K.info("Message received",{channel:a.channel,channelName:r,user:a.user,textLength:a.text.length,fileCount:o.length}),this.messageHandler?.(a)}),this.socket.on("assistant_thread_started",async({event:t,ack:s})=>{await s(),K.info("Assistant thread started",{channel:t?.assistant_thread?.channel_id});let r=t?.assistant_thread;r&&this.threadStartedHandler?.({channel:r.channel_id,threadTs:r.thread_ts,context:r.context??{}})}),this.socket.on("assistant_thread_context_changed",async({event:t,ack:s})=>{await s(),K.info("Assistant thread context changed",{channel:t?.assistant_thread?.channel_id});let r=t?.assistant_thread;r&&this.threadContextHandler?.({channel:r.channel_id,threadTs:r.thread_ts,context:r.context??{}})}),this.socket.on("slack_event",async({ack:t,body:s})=>{await t();let r=s?.event;r&&K.debug("slack_event",{type:r.type,subtype:r.subtype,channel:r.channel})}),await this.socket.start(),K.info("Socket Mode connected")}async stop(){await this.socket.disconnect(),K.info("Socket Mode disconnected")}async setThreadStatus(e,t,s){try{await this.web.assistant.threads.setStatus({channel_id:e,thread_ts:t,status:s})}catch(r){K.warn("Failed to set thread status",{error:String(r)})}}async setSuggestedPrompts(e,t,s){try{await this.web.assistant.threads.setSuggestedPrompts({channel_id:e,thread_ts:t,prompts:s})}catch(r){K.warn("Failed to set suggested prompts",{error:String(r)})}}async setThreadTitle(e,t,s){try{await this.web.assistant.threads.setTitle({channel_id:e,thread_ts:t,title:s})}catch(r){K.warn("Failed to set thread title",{error:String(r)})}}async startStream(e,t){try{let s=await this.web.chat.startStream({channel:e,thread_ts:t});return s.channel&&s.ts?{channel:s.channel,ts:s.ts}:void 0}catch(s){K.warn("Failed to start stream",{error:String(s)});return}}async appendStream(e,t,s){try{await this.web.chat.appendStream({channel:e,ts:t,markdown_text:s})}catch(r){K.warn("Failed to append stream",{error:String(r)})}}async stopStream(e,t){try{await this.web.chat.stopStream({channel:e,ts:t})}catch(s){K.warn("Failed to stop stream",{error:String(s)})}}static SLACK_MAX_CHARS=3900;static SPLIT_MAX_CHARS=8e3;static SUMMARY_LENGTH=200;async postMessage(e,t,s,r){return t.length<=n.SLACK_MAX_CHARS?this.postSingle(e,t,s,r):t.length<=n.SPLIT_MAX_CHARS?this.postSplit(e,t,s,r):this.postAsFile(e,t,s,r)}async postSingle(e,t,s,r){if(r)try{let i={};r.icon&&(r.icon.startsWith(":")&&r.icon.endsWith(":")?i.icon_emoji=r.icon:i.icon_url=r.icon);let o=await this.web.chat.postMessage({channel:e,text:t,thread_ts:s,unfurl_links:!1,username:r.name,...i});return o.ok&&o.ts&&o.channel&&this.outboundTsCache.register(o.channel,o.ts),o.ts}catch(i){K.warn("Failed to post with identity, falling back to plain post",{error:String(i)})}try{let i=await this.web.chat.postMessage({channel:e,text:t,thread_ts:s,unfurl_links:!1});return i.ok&&i.ts&&i.channel&&this.outboundTsCache.register(i.channel,i.ts),i.ts}catch(i){K.error("Failed to post message",{channel:e,error:String(i)});return}}splitText(e){let t=n.SLACK_MAX_CHARS,s=[],r=e;for(;r.length>t;){let i=-1,o=r.lastIndexOf(`
292
295
 
293
- `,t);if(o>0&&(i=o+2),i===-1){let a=n.lastIndexOf(`
294
- `,t);a>0&&(i=a+1)}if(i===-1){let a=n.lastIndexOf(" ",t);a>0&&(i=a+1)}i===-1&&(i=t),s.push(n.slice(0,i).trimEnd()),n=n.slice(i).trimStart()}return n.length>0&&s.push(n),s}async postSplit(e,t,s,n){let i=this.splitText(t);K.info("Splitting oversized message",{channel:e,totalLength:t.length,chunks:i.length});let o;for(let a=0;a<i.length;a++){let l=a===0?i[a]:`_(cont.)_ ${i[a]}`,c=await this.postSingle(e,l,s,n);a===0&&(o=c)}return o}async postAsFile(e,t,s,n){let i=t.slice(0,r.SUMMARY_LENGTH),o=i,a=Math.max(i.lastIndexOf(". "),i.lastIndexOf(`.
296
+ `,t);if(o>0&&(i=o+2),i===-1){let a=r.lastIndexOf(`
297
+ `,t);a>0&&(i=a+1)}if(i===-1){let a=r.lastIndexOf(" ",t);a>0&&(i=a+1)}i===-1&&(i=t),s.push(r.slice(0,i).trimEnd()),r=r.slice(i).trimStart()}return r.length>0&&s.push(r),s}async postSplit(e,t,s,r){let i=this.splitText(t);K.info("Splitting oversized message",{channel:e,totalLength:t.length,chunks:i.length});let o;for(let a=0;a<i.length;a++){let l=a===0?i[a]:`_(cont.)_ ${i[a]}`,c=await this.postSingle(e,l,s,r);a===0&&(o=c)}return o}async postAsFile(e,t,s,r){let i=t.slice(0,n.SUMMARY_LENGTH),o=i,a=Math.max(i.lastIndexOf(". "),i.lastIndexOf(`.
295
298
  `),i.lastIndexOf(`?
296
299
  `),i.lastIndexOf("? "),i.lastIndexOf(`!
297
300
  `),i.lastIndexOf("! "));if(a>0)o=i.slice(0,a+1);else{let h=i.lastIndexOf(`
298
301
  `);h>0&&(o=i.slice(0,h))}o=`${o.trimEnd()}
299
302
 
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}
303
+ _(full response attached)_`;let l=r?.name??"hive",c=new Date().toISOString().replace(/[:.]/g,"-").slice(0,19),d=`${l.toLowerCase()}-${c}.md`,u=await this.postSingle(e,o,s,r);try{let h={content:t,filename:d,title:`${l} response`},p=s?{channel_id:e,thread_ts:s}:{channel_id:e};return await this.web.files.uploadV2({...h,...p}),K.info("Uploaded oversized message as file",{channel:e,filename:d,length:t.length}),u}catch(h){return K.warn("File upload failed, falling back to split",{channel:e,error:String(h)}),this.postSplit(e,t,s,r)}}async addReaction(e,t,s){try{await this.web.reactions.add({channel:e,name:s,timestamp:t})}catch(r){let i=String(r);i.includes("already_reacted")||K.warn("Failed to add reaction",{channel:e,ts:t,emoji:s,error:i})}}async removeReaction(e,t,s){try{await this.web.reactions.remove({channel:e,name:s,timestamp:t})}catch{}}async resolveUserName(e){let t=this.userNameCache.get(e);if(t)return t;try{let s=await this.web.users.info({user:e});return t=s.user?.profile?.display_name||s.user?.real_name||s.user?.name||e,this.userNameCache.set(e,t),t}catch{return this.userNameCache.set(e,e),e}}async resolveUserMentions(e){let t=/<@(U[A-Z0-9]+)>/g,s=[...e.matchAll(t)];if(s.length===0)return e;let r=e;for(let i of s){let o=i[1],a=this.userNameCache.get(o);if(!a)try{let l=await this.web.users.info({user:o});a=l.user?.profile?.display_name||l.user?.real_name||l.user?.name||o,this.userNameCache.set(o,a)}catch{this.userNameCache.set(o,o);continue}r=r.replace(i[0],`@${a}`)}return r}registerOutboundTs(e,t){this.outboundTsCache.register(e,t)}isOutboundEcho(e,t){return this.outboundTsCache.has(e,t)}async postAndRegister(e,t,s){try{let r=await this.postMessage(e,t,s);return r?{ok:!0,ts:r}:{ok:!1,error:"postMessage returned no ts"}}catch(r){return{ok:!1,error:r.message}}}async resolveChannelId(e){if(e.startsWith("C")||e.startsWith("D")||e.startsWith("G"))return e;let t=e.replace(/^#/,""),s=this.channelIdCache.get(t);if(s)return s;try{let r;do{let i=await this.web.conversations.list({limit:1e3,cursor:r,exclude_archived:!0,types:"public_channel,private_channel"});for(let o of i.channels??[])o.id&&o.name&&(this.channelNameCache.set(o.id,o.name),this.channelIdCache.set(o.name,o.id));r=i.response_metadata?.next_cursor||void 0}while(r)}catch(r){return K.warn("channel id resolve failed",{name:t,error:r.message}),null}return this.channelIdCache.get(t)??null}async resolveChannelName(e){let t=this.channelNameCache.get(e);if(t)return t;try{let r=(await this.web.conversations.info({channel:e})).channel?.name??e;return this.channelNameCache.set(e,r),r}catch{return this.channelNameCache.set(e,e),e}}async readChannel(e,t=50){try{return(await this.web.conversations.history({channel:e,limit:t})).messages}catch(s){K.warn("readChannel failed",{channel:e,error:s.message});return}}async listChannels(e){let t=[];try{let s;do{let r=await this.web.conversations.list({limit:1e3,cursor:s,exclude_archived:!0,types:"public_channel,private_channel"});for(let i of r.channels??[])i.id&&i.name&&(this.channelNameCache.set(i.id,i.name),this.channelIdCache.set(i.name,i.id),(!e||i.name.includes(e))&&t.push({id:i.id,name:i.name}));s=r.response_metadata?.next_cursor||void 0}while(s)}catch(s){K.warn("listChannels failed",{query:e,error:s.message})}return t}async readUser(e){try{return(await this.web.users.info({user:e})).user}catch(t){K.warn("readUser failed",{user:e,error:t.message});return}}sweep(){let e=this.channelNameCache.size+this.channelIdCache.size+this.userNameCache.size;return this.channelNameCache.clear(),this.channelIdCache.clear(),this.userNameCache.clear(),{component:"slack-gateway",pruned:e,retried:0,bytesFreed:0,errors:[]}}get client(){return this.web}};M();var gk=k("memory-manager"),Lr=class{db;collection;versions;_memoryStore;set memoryStore(e){this._memoryStore=e}constructor(e){this.db=e}async init(){this.collection=this.db.collection("memory"),this.versions=this.db.collection("memory_versions"),await this.collection.createIndex({path:1},{unique:!0}),await this.versions.createIndex({path:1,savedAt:-1}),gk.info("Memory manager connected to MongoDB",{db:this.db.databaseName})}async read(e){return(await this.collection.findOne({path:e}))?.content??null}async list(e){let t=e.endsWith("/")?e:e+"/";return(await this.collection.find({path:{$regex:`^${yk(t)}[^/]+$`}}).project({path:1}).toArray()).map(r=>r.path.slice(t.length))}async getHotTierPrompt(e,t){if(!this._memoryStore)return null;let s=await this._memoryStore.getHotTier(e);if(s.length===0)return null;let r={task:"Active Tasks",fact:"Key Facts",decision:"Recent Decisions",preference:"Preferences",interaction:"Recent Interactions",summary:"Summaries"},i={},o=[],a=0;for(let d of s){let h=`- [${d.updatedAt.toISOString().split("T")[0]}] ${d.content} (${d.importance})`,p=Math.ceil(h.length/4);if(a+p>t&&!d.pinned)break;if(a+=p,d.pinned)o.push(`- ${d.content} (${d.importance}, pinned)`);else{let m=d.type;i[m]||(i[m]=[]),i[m].push(h)}}let l=["## Your Memory"];for(let[d,u]of Object.entries(r))i[d]?.length&&l.push(`### ${u}
301
304
  ${i[d].join(`
302
305
  `)}`);o.length>0&&l.push(`### Pinned
303
306
  ${o.join(`
304
307
  `)}`);let c=await this._memoryStore.countNonHot(e);return c>0&&l.push(`---
305
308
  You have ${c} additional memories available via \`memory_recall\`. Use it to search for context before starting tasks.`),l.join(`
306
309
 
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}]
310
+ `)}async write(e,t,s){let r=await this.collection.findOne({path:e});r&&await this.versions.insertOne({path:e,content:r.content,savedAt:r.updatedAt,savedBy:r.updatedBy}),await this.collection.updateOne({path:e},{$set:{content:t,updatedAt:new Date,...s?{updatedBy:s}:{}}},{upsert:!0})}async commitAndPush(e){}async pull(){}async close(){}};function yk(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}M();Ne();var Q=k("scheduler"),Pr=class{heartbeatTimer=null;cronTimer=null;callbackTimer=null;eventTimer=null;teamTimer=null;agentManager;memoryManager;healthReporter;registry;cronJobs=[];db=null;callbackCollection=null;eventsCollection=null;onDispatch;constructor(e,t,s,r,i){this.agentManager=e,this.memoryManager=t,this.healthReporter=s,this.registry=r,this.onDispatch=i;for(let o of r.getAll())for(let a of o.schedule)this.cronJobs.push({agentId:o.id,cron:a.cron,task:a.task,lastRun:null})}async connectDb(e){this.db=e,this.callbackCollection=this.db.collection("agent_callbacks"),this.eventsCollection=this.db.collection("agent_events"),await this.callbackCollection.createIndex({status:1,dueAt:1}),await this.eventsCollection.createIndex({hasPending:1,createdAt:1}),await this.eventsCollection.createIndex({sourceAgentId:1,createdAt:-1}),await this.eventsCollection.createIndex({domain:1,createdAt:-1}),await this.eventsCollection.createIndex({createdAt:1},{expireAfterSeconds:g.events.retentionDays*86400}),await this.db.collection("team_pending_requests").createIndex({status:1,createdAt:-1}),await this.db.collection("team_pending_requests").createIndex({createdAt:1},{expireAfterSeconds:3600}),Q.info("Callback store connected",{db:e.databaseName})}async reloadSchedules(){this.cronJobs=[];for(let e of this.registry.getAll())for(let t of e.schedule)this.cronJobs.push({agentId:e.id,cron:t.cron,task:t.task,lastRun:null});Q.info("Schedules reloaded",{jobs:this.cronJobs.length})}start(){this.heartbeatTimer=setInterval(async()=>{try{await this.memoryManager.pull(),await this.healthReporter.writeToMemory()}catch(e){Q.error("Heartbeat failed",{error:String(e)})}},g.scheduler.heartbeatIntervalMs),this.cronTimer=setInterval(()=>{this.checkCronJobs()},6e4),this.callbackCollection&&(this.callbackTimer=setInterval(()=>{this.checkCallbacks().catch(e=>{Q.error("Callback check failed",{error:String(e)})})},3e4)),this.eventsCollection&&(this.eventTimer=setInterval(()=>{this.checkEvents().catch(e=>{Q.error("Event check failed",{error:String(e)})})},3e4)),this.db&&(this.teamTimer=setInterval(()=>{this.fireTeamRequests().catch(e=>Q.error("Team request check failed",{error:String(e)}))},5e3)),Q.info("Scheduler started",{heartbeatMs:g.scheduler.heartbeatIntervalMs,cronJobs:this.cronJobs.length,callbacksEnabled:!!this.callbackCollection,eventsEnabled:!!this.eventsCollection})}stop(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.cronTimer&&(clearInterval(this.cronTimer),this.cronTimer=null),this.callbackTimer&&(clearInterval(this.callbackTimer),this.callbackTimer=null),this.eventTimer&&(clearInterval(this.eventTimer),this.eventTimer=null),this.teamTimer&&(clearInterval(this.teamTimer),this.teamTimer=null),Q.info("Scheduler stopped")}checkCronJobs(){let e=new Date;for(let t of this.cronJobs)if(wk(t.cron,e)){if(t.lastRun&&Sk(t.lastRun,e))continue;t.lastRun=e;let s=this.registry.get(t.agentId);if(s?.disabled){Q.debug("Skipping scheduled task \u2014 agent disabled",{agentId:t.agentId,task:t.task});continue}Q.info("Triggering scheduled task",{agentId:t.agentId,task:t.task});let r=s?.homeBase??s?.channels?.[0];if(!r){Q.error("Cannot dispatch scheduled task \u2014 agent has no homeBase or channels",{agentId:t.agentId,task:t.task});continue}let i={id:`sched:${t.agentId}:${t.task}:${Date.now()}`,text:`[Scheduled task: ${t.task}] Execute your scheduled "${t.task}" task now.`,source:{kind:"slack",id:r,label:r},sender:"system",threadId:`scheduler:${t.agentId}:${t.task}:${Date.now()}`,timestamp:e,meta:{targetAgentId:t.agentId}};this.onDispatch?this.onDispatch(i):this.agentManager.sendMessage(t.agentId,i).catch(o=>{Q.error("Scheduled task failed",{agentId:t.agentId,task:t.task,error:String(o)})})}}async checkCallbacks(){if(!this.callbackCollection)return;let e=new Date,t=this.callbackCollection.find({status:"pending",dueAt:{$lte:e}});for await(let s of t){if((await this.callbackCollection.updateOne({_id:s._id,status:"pending"},{$set:{status:"fired",firedAt:e}})).modifiedCount===0)continue;Q.info("Firing callback",{agentId:s.agentId,callbackId:s._id.toString(),contextPreview:s.context.slice(0,80)});let i=this.registry.get(s.agentId);if(!i){Q.warn("Callback agent not found, skipping",{agentId:s.agentId});continue}if(i.disabled){Q.info("Callback agent disabled, skipping",{agentId:s.agentId});continue}let o={id:`callback:${s._id.toString()}`,text:`[Scheduled callback] ${s.context}`,source:{kind:s.source.channelKind||"slack",id:s.source.channelId,label:s.source.channelLabel,adapterId:s.source.adapterId},sender:"system",threadId:s.source.threadId||void 0,timestamp:e,meta:{slackTs:s.source.slackTs,slackThreadTs:s.source.slackThreadTs,targetAgentId:s.agentId}};this.onDispatch?this.onDispatch(o):this.agentManager.sendMessage(s.agentId,o).catch(a=>{Q.error("Callback dispatch failed",{agentId:s.agentId,callbackId:s._id.toString(),error:String(a)})})}}async checkEvents(){if(!this.eventsCollection)return;let e=this.eventsCollection.find({hasPending:!0});for await(let t of e){let s=t.deliveries.filter(r=>r.status==="pending");for(let r of s){let i=new Date;if((await this.eventsCollection.updateOne({_id:t._id,deliveries:{$elemMatch:{agentId:r.agentId,status:"pending"}}},{$set:{"deliveries.$.status":"fired","deliveries.$.firedAt":i}})).modifiedCount===0)continue;await this.eventsCollection.updateOne({_id:t._id,"deliveries.status":{$ne:"pending"}},{$set:{hasPending:!1}});let a=this.registry.get(r.agentId);if(!a){Q.warn("Event target agent not found, skipping",{agentId:r.agentId,eventType:t.type});continue}if(a.disabled){Q.info("Event target agent disabled, skipping",{agentId:r.agentId,eventType:t.type});continue}let l=t._id.toHexString(),d=this.registry.get(t.sourceAgentId)?.name??t.sourceAgentId;Q.info("Dispatching event",{eventType:t.type,eventId:l,targetAgent:r.agentId,sourceAgent:t.sourceAgentId});let u=a.homeBase??`agent-${r.agentId}`,h={id:`event:${l}:${r.agentId}`,text:`[Event: ${t.type} from ${d}]
308
311
 
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
- `];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"),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
+ ${JSON.stringify(t.payload)}`,source:{kind:"internal",id:u,label:u},sender:"system",threadId:`event:${l}:${r.agentId}:${i.getTime()}`,timestamp:i,meta:{targetAgentId:r.agentId,eventType:t.type,eventDomain:t.domain,eventId:l}};this.onDispatch?this.onDispatch(h):this.agentManager.sendMessage(r.agentId,h).catch(p=>{Q.error("Event dispatch failed",{agentId:r.agentId,eventType:t.type,eventId:l,error:String(p)})})}}}async fireTeamRequests(){if(!this.db)return;let e=await this.db.collection("team_pending_requests").find({status:"pending"}).toArray();for(let t of e){if(!await this.db.collection("team_pending_requests").findOneAndUpdate({_id:t._id,status:"pending"},{$set:{status:"fired",firedAt:new Date}}))continue;let r={id:`team-${String(t._id)}`,text:t.text,source:{kind:"internal",id:t.channelId,label:`internal:${t.fromAgentId}\u2192${t.targetAgentId}`},sender:t.fromAgentId,senderName:t.fromAgentId,threadId:`internal:${t.channelId}:${t.threadId}`,timestamp:new Date,meta:{targetAgentId:t.targetAgentId,teamRequestId:String(t._id),teamRequestType:t.type}};try{if(t.type==="fire_and_forget")this.onDispatch?this.onDispatch(r):this.agentManager.sendMessage(t.targetAgentId,r).catch(i=>Q.error("Fire-and-forget team message failed",{target:t.targetAgentId,error:String(i)}));else if(t.type==="request_response"){let i=await this.agentManager.sendMessage(t.targetAgentId,r);await this.db.collection("team_messages").insertOne({channelId:t.channelId,threadId:t.threadId,senderId:t.targetAgentId,senderType:"agent",senderName:t.targetAgentId,text:i.text,createdAt:new Date}),await this.db.collection("team_pending_requests").updateOne({_id:t._id},{$set:{status:"completed",response:i.text}})}}catch(i){Q.error("Team request dispatch failed",{requestId:String(t._id),target:t.targetAgentId,error:String(i)}),await this.db.collection("team_pending_requests").updateOne({_id:t._id},{$set:{status:"failed",error:String(i)}})}}}};function wk(n,e){let t=n.split(/\s+/);if(t.length!==5)return!1;let[s,r,i,o,a]=t,l=e.getMinutes(),c=e.getHours(),d=e.getDate(),u=e.getMonth()+1,h=e.getDay();return Js(s,l)&&Js(r,c)&&Js(i,d)&&Js(o,u)&&Js(a,h)}function Js(n,e){if(n==="*")return!0;if(n.includes("-")){let[t,s]=n.split("-").map(Number);return e>=t&&e<=s}if(n.includes(","))return n.split(",").map(Number).includes(e);if(n.startsWith("*/")){let t=Number(n.slice(2));return e%t===0}return Number(n)===e}function Sk(n,e){return n.getFullYear()===e.getFullYear()&&n.getMonth()===e.getMonth()&&n.getDate()===e.getDate()&&n.getHours()===e.getHours()&&n.getMinutes()===e.getMinutes()}M();var kk=k("health-reporter"),$r=class{agentManager;memoryManager;registry;constructor(e,t,s){this.agentManager=e,this.memoryManager=t,this.registry=s}generateReport(){let e={};for(let t of this.agentManager.getAllStates())e[t.id]={status:t.status,lastActivity:t.lastActivity.toISOString(),messagesProcessed:t.messagesProcessed,errorCount:t.errorCount,sessionId:t.currentSessionId,activeThreads:t.activeThreadCount??0};return{lastUpdated:new Date().toISOString(),agents:e}}formatForSlack(){let e=this.generateReport();if(Object.keys(e.agents).length===0)return"No agents are currently registered.";let s=[`*Hive Status* \u2014 ${new Date().toLocaleString()}
313
+ `];for(let[r,i]of Object.entries(e.agents)){let l=this.registry?.get(r)?.disabled?":no_entry_sign:":i.status==="idle"?":white_circle:":i.status==="processing"?":large_blue_circle:":i.status==="error"?":red_circle:":":black_circle:",c=i.activeThreads>0?` (${i.activeThreads} threads)`:"";s.push(`${l} *${r}*${c}`),s.push(` Messages: ${i.messagesProcessed} | Errors: ${i.errorCount}`),s.push(` Last active: ${new Date(i.lastActivity).toLocaleString()}`)}return s.join(`
314
+ `)}async writeToMemory(){let e=this.generateReport();await this.memoryManager.write("status/health.json",JSON.stringify(e,null,2)),await this.memoryManager.commitAndPush("heartbeat: update agent status"),kk.info("Health report written to memory")}};M();import{LinearClient as bk}from"@linear/sdk";var me=k("linear-client"),Rr=class{client;defaultTeamId;constructor(e,t){this.client=new bk({apiKey:e}),this.defaultTeamId=t}async listTeams(){try{return(await this.client.teams()).nodes.map(t=>({id:t.id,name:t.name,key:t.key}))}catch(e){return me.error("Failed to list teams",{error:String(e)}),[]}}async createIssue(e,t){try{let s=t?.teamId??this.defaultTeamId;if(!s)return me.error("Cannot create issue: no teamId provided and no default set"),null;let i=await(await this.client.createIssue({teamId:s,title:e,description:t?.description,priority:t?.priority,stateId:t?.stateId,labelIds:t?.labelIds})).issue;return i?(me.info("Issue created",{identifier:i.identifier,title:e}),{identifier:i.identifier,id:i.id,url:i.url}):(me.error("Issue creation returned no issue",{title:e}),null)}catch(s){return me.error("Failed to create issue",{error:String(s),title:e}),null}}async updateIssue(e,t){try{return await this.client.updateIssue(e,t),me.info("Issue updated",{issueId:e,...t}),!0}catch(s){return me.error("Failed to update issue",{error:String(s),issueId:e}),!1}}async addComment(e,t){try{let r=await(await this.client.createComment({issueId:e,body:t})).comment;return me.info("Comment added",{issueId:e,commentId:r?.id}),r?.id??null}catch(s){return me.error("Failed to add comment",{error:String(s),issueId:e}),null}}async listIssues(e){try{let t=e?.teamId??this.defaultTeamId,s={};t&&(s.team={id:{eq:t}}),e?.stateType&&(s.state={type:{eq:e.stateType}}),e?.assigneeEmail&&(s.assignee={email:{eq:e.assigneeEmail}});let r=await this.client.issues({filter:s,first:e?.limit??50,orderBy:"updatedAt"}),i=[];for(let o of r.nodes){let a=await o.state,l=await o.assignee;i.push({identifier:o.identifier,id:o.id,title:o.title,state:a?.name??"Unknown",priority:o.priority,url:o.url,assignee:l?{id:l.id,name:l.name,email:l.email}:void 0})}return i}catch(t){return me.error("Failed to list issues",{error:String(t)}),[]}}async searchIssues(e,t,s){try{let r=s??this.defaultTeamId,o=(await this.client.searchIssues(e,{first:t??10})).nodes,a=[];for(let l of o){if(r&&(await l.team)?.id!==r)continue;let c=await l.state,d=await l.assignee;a.push({identifier:l.identifier,id:l.id,title:l.title,state:c?.name??"Unknown",priority:l.priority,url:l.url,assignee:d?{id:d.id,name:d.name,email:d.email}:void 0})}return a}catch(r){return me.error("Failed to search issues",{error:String(r),term:e}),[]}}async getWorkflowStates(e){try{let t=e??this.defaultTeamId,s={};return t&&(s.team={id:{eq:t}}),(await this.client.workflowStates({filter:s})).nodes.map(i=>({id:i.id,name:i.name,type:i.type}))}catch(t){return me.error("Failed to get workflow states",{error:String(t)}),[]}}async searchUsers(e,t){try{return(await this.client.users({filter:{or:[{name:{containsIgnoreCase:e}},{displayName:{containsIgnoreCase:e}},{email:{containsIgnoreCase:e}}]},first:t??10})).nodes.map(r=>({id:r.id,name:r.name,displayName:r.displayName,email:r.email,active:r.active}))}catch(s){return me.error("Failed to search users",{error:String(s),query:e}),[]}}async findIssueByIdentifier(e){try{let t=await this.client.issue(e),s=await t.state,r=await t.assignee;return{identifier:t.identifier,id:t.id,title:t.title,state:s?.name??"Unknown",priority:t.priority,url:t.url,description:t.description??void 0,assignee:r?{id:r.id,name:r.name,email:r.email}:void 0}}catch(t){return me.error("Failed to find issue",{error:String(t),identifier:e}),null}}};M();var Ba=k("session-store"),Br=class{db;collection;constructor(e){this.db=e}async init(){this.collection=this.db.collection("sessions"),await this.collection.createIndex({updatedAt:1},{expireAfterSeconds:10080*60}),await this.collection.createIndex({agentId:1}),await this.collection.createIndex({threadId:1});let e=await this.collection.countDocuments();Ba.info("Session store connected",{count:e})}async withRetry(e,t,s){try{return await e()}catch(r){return Ba.error("MongoDB operation failed, using fallback",{label:s,error:String(r?.message??r)}),t}}async get(e,t){return this.withRetry(async()=>{let s=await this.collection.findOne({_id:`${e}:${t}`});if(s)return s.sessionId;if(t.startsWith("slack:")){let r=t.split(":").pop();return(await this.collection.findOne({_id:`${e}:${r}`}))?.sessionId}},void 0,`get(${e}:${t})`)}async set(e,t,s,r){await this.withRetry(async()=>{let i=new Date,o={$set:{agentId:e,threadId:t,sessionId:s,updatedAt:i},$setOnInsert:{createdAt:i,compactions:0}};r?(o.$set.inputTokens=r.inputTokens,o.$set.outputTokens=r.outputTokens,o.$set.cacheReadTokens=r.cacheReadTokens,o.$set.cacheCreationTokens=r.cacheCreationTokens,o.$set.contextWindow=r.contextWindow,r.compactions>0&&(o.$inc={compactions:r.compactions},o.$set.lastCompactedAt=i,r.preCompactTokens!==void 0&&(o.$set.preCompactTokens=r.preCompactTokens),delete o.$setOnInsert.compactions)):Object.assign(o.$setOnInsert,{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheCreationTokens:0,contextWindow:0}),await this.collection.updateOne({_id:`${e}:${t}`},o,{upsert:!0})},void 0,`set(${e}:${t})`)}async delete(e,t){await this.withRetry(async()=>{await this.collection.deleteOne({_id:`${e}:${t}`})},void 0,`delete(${e}:${t})`)}async clearAgent(e){await this.withRetry(async()=>{let t=await this.collection.deleteMany({agentId:e});t.deletedCount>0&&Ba.info("Cleared agent sessions",{agentId:e,deleted:t.deletedCount})},void 0,`clearAgent(${e})`)}async findAgentByThread(e){return this.withRetry(async()=>(await this.collection.findOne({threadId:e},{sort:{updatedAt:-1},projection:{agentId:1}}))?.agentId,void 0,`findAgentByThread(${e})`)}async findAgentsByThread(e){return this.withRetry(async()=>{let t=await this.collection.find({threadId:e},{projection:{agentId:1},sort:{updatedAt:-1}}).toArray();return[...new Set(t.map(s=>s.agentId))]},[],`findAgentsByThread(${e})`)}async close(){}};M();M();Ne();import{query as _k}from"@anthropic-ai/claude-agent-sdk";var Ur=k("meeting-classifier"),vk=`You are a meeting facilitator. Given a message and a list of meeting participants, decide which participants should respond.
312
315
 
313
316
  Rules:
314
317
  - If someone is addressed by name, they MUST be in the respond list.
@@ -318,34 +321,34 @@ Rules:
318
321
  - If the message is a general question to the room, pick 2-3 most relevant.
319
322
  - For "what does everyone think?" style questions, include all participants.
320
323
 
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
- ${r.map(n=>`- ${n.agentId} (${n.name}${n.title?`, ${n.title}`:""}): ${n.role}`).join(`
324
+ Respond with ONLY a JSON object: { "respond": ["agent-id-1", "agent-id-2"] }`;function Tk(n,e){let t=o=>{try{let a=JSON.parse(o);if(Array.isArray(a.respond))return a.respond.filter(l=>e.has(l))}catch{}return null},s=t(n);if(s)return s;let r=n.indexOf("{"),i=n.lastIndexOf("}");if(r!==-1&&i>r){let o=t(n.slice(r,i+1));if(o)return o}return null}function Ik(n,e){let s=`Participants:
325
+ ${n.map(r=>`- ${r.agentId} (${r.name}${r.title?`, ${r.title}`:""}): ${r.role}`).join(`
323
326
  `)}`;return e&&(s+=`
324
327
 
325
328
  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=`${Sk(e,t)}
329
+ ${e}`),s}async function Ua(n,e,t){let s=new Set(e.map(u=>u.agentId));if(e.length===0)return{respondAgentIds:[],costUsd:0,durationMs:0};if(e.length===1)return{respondAgentIds:[e[0].agentId],costUsd:0,durationMs:0};let r=g.modelRouter.model,i=null,o="",a=0,l=0,c=setTimeout(()=>{i&&(Ur.warn("Meeting classifier timed out",{timeoutMs:g.modelRouter.timeoutMs}),i.close())},g.modelRouter.timeoutMs);try{let u=`${Ik(e,t)}
327
330
 
328
331
  Message:
329
- ${r}`;i=gk({prompt:u,options:{model:n,systemPrompt:yk,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,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
- `);n={...e,text:`${l}
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
- `)[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(`
333
- `)}let l=await $a(e.text,i,a);q.info("Conference classifier result",{channel:e.source.label,threadId:t,roster:[...s],selected:l.respondAgentIds,costUsd:l.costUsd});let c=this.buildMeetingPreamble(e.source.label,i);return l.respondAgentIds.map(d=>({agentId:d,conferenceMode:!0,conferenceHumanTs:e.meta?.slackTs,conferenceRound:0,threadContext:o,meetingPreamble:c}))}formatThreadContext(e,t,s){if(e.length===0)return"";let n=s.map(l=>l.name).join(", "),i=`[Meeting thread in #${t} \u2014 participants: ${n}]`,o=e;if(e.length>105){let l=e.slice(0,5),c=e.slice(-100);o=[...l,...c]}let a=o.map(l=>{let c=this.formatTimeAgo(l.timestamp);return`${l.author} (${c}): ${l.text}`}).join(`
332
+ ${n}`;i=_k({prompt:u,options:{model:r,systemPrompt:vk,permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:.01,persistSession:!1,disallowedTools:["Bash","Read","Write","Edit","Glob","Grep","Agent","WebFetch","WebSearch","NotebookEdit"],env:{...process.env,...g.anthropic.apiKey?{ANTHROPIC_API_KEY:g.anthropic.apiKey}:{},CLAUDE_AGENT_SDK_CLIENT_APP:"hive/0.1.0",CLAUDECODE:void 0}}});for await(let h of i){let p=h;if(p.type==="assistant"){let m=p.message?.content;if(Array.isArray(m))for(let f of m)f.type==="text"&&(o=f.text)}if(p.type==="result"){let m=p;a=m.total_cost_usd,l=m.duration_ms,m.subtype==="success"&&m.result&&(o=m.result)}}}catch(u){return Ur.warn("Meeting classifier query failed, selecting all roster members",{error:String(u)}),{respondAgentIds:[...s],costUsd:0,durationMs:0}}finally{clearTimeout(c),i=null}let d=Tk(o,s);return d?(Ur.info("Meeting classifier decision",{respond:d,rosterSize:e.length,costUsd:a,durationMs:l}),{respondAgentIds:d,costUsd:a,durationMs:l}):(Ur.warn("Meeting classifier parse failed, selecting all roster members",{rawText:o.slice(0,200)}),{respondAgentIds:[...s],costUsd:a,durationMs:l})}var q=k("dispatcher"),Ak=80,Ck=[/^status\??$/i,/^how.{0,20}(everyone|agents?|doing|running)/i,/^health\??$/i,/^system status/i],Vh=[/^no response (requested|needed|required|necessary)\.?$/i,/^\(no response\)$/i,/^n\/a\.?$/i],jr=class n{adapters=new Map;registry;agentManager;healthReporter;defaultAgentId;threadAgentMap=new Map;threadParticipants=new Map;threadAgentLastSeen=new Map;recentMessageIds=new Map;auditAdapter;auditChannelIds;fallbackAuditChannelId;taskLedger;retryQueue;teamStore;slackAdapter;meetingRosters=new Map;meetingReactionTracker=new Map;static DEDUP_TTL_MS=6e4;constructor(e,t,s,r,i){this.registry=e,this.agentManager=t,this.healthReporter=s,this.defaultAgentId=r,this.taskLedger=i}registerAdapter(e){this.adapters.set(e.id,e)}setRetryQueue(e){this.retryQueue=e}setTeamStore(e){this.teamStore=e}setAuditChannel(e,t,s){this.auditAdapter=e,this.auditChannelIds=t,this.fallbackAuditChannelId=s}setSlackAdapter(e){this.slackAdapter=e}async dispatch(e){if(this.recentMessageIds.has(e.id)){q.debug("Duplicate message skipped",{id:e.id,source:e.source.adapterId});return}this.recentMessageIds.set(e.id,Date.now()),this.pruneDedup();let t=e.text.trim();if(t.length<=Ak&&Ck.some(d=>d.test(t))){q.info("Status query intercepted",{source:e.source.kind,text:t});let d=this.healthReporter.formatForSlack(),u=this.adapters.get(e.source.adapterId??e.source.kind);if(u)try{await u.deliver({text:d,agentId:"system",workItem:e,costUsd:0,durationMs:0})}catch(h){q.warn("Status delivery failed, queuing for retry",{error:String(h)}),this.retryQueue?.enqueue({text:d,agentId:"system",workItem:e,costUsd:0,durationMs:0},u)}return}let s=await this.resolveAgents(e);if(s.length===0){q.warn("No agent found for work item",{source:e.source.kind,label:e.source.label,text:e.text.slice(0,50)});return}let r=s.filter(({agentId:d})=>this.registry.get(d)?.disabled?(q.info("Message dropped \u2014 agent is disabled",{agentId:d,source:e.source.kind}),!1):!0);if(r.length===0)return;if(r.some(d=>d.conferenceMode)){let d=e.threadId??e.id;this.threadAgentLastSeen.set(d,Date.now()),q.info("Conference fan-out",{agents:r.map(u=>u.agentId)}),await Promise.all(r.map(u=>this.dispatchToAgent(e,u)));return}if(r.length>1){let d=e.threadId??e.id;this.threadParticipants.has(d)||this.threadParticipants.set(d,new Set(r.map(u=>u.agentId))),this.threadAgentLastSeen.set(d,Date.now()),q.info("Multi-agent fan-out",{agents:r.map(u=>u.agentId)}),await Promise.all(r.map(u=>this.dispatchToAgent(e,u)));return}let{agentId:o}=r[0],a=e.threadId??e.id;this.threadAgentMap.set(a,o),this.threadAgentLastSeen.set(a,Date.now());let l=this.taskLedger?.shouldTrack(e)??!1;l&&this.taskLedger.onDispatch(e,o).catch(d=>q.warn("Task ledger dispatch failed",{error:String(d)}));let c=this.adapters.get(e.source.adapterId??e.source.kind);await c?.onProcessingStart?.(e,o);try{let d=await this.agentManager.sendMessage(o,e),u=d.text.trim();if(Vh.some(p=>p.test(u)))q.info("Non-response suppressed",{agentId:o,source:e.source.kind,text:u,costUsd:d.costUsd,durationMs:d.durationMs});else{let p={text:d.text||"_No response._",agentId:o,workItem:e,costUsd:d.costUsd,durationMs:d.durationMs,error:d.error};if(c)try{await c.deliver(p)}catch(m){q.warn("Agent response delivery failed, queuing for retry",{error:String(m)}),this.retryQueue?.enqueue(p,c)}l&&this.taskLedger.onComplete(p).catch(m=>q.warn("Task ledger complete failed",{error:String(m)})),this.auditAdapter&&e.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(p),q.info("Work item dispatched",{agentId:o,source:e.source.kind,costUsd:d.costUsd,durationMs:d.durationMs,llmMs:d.llmMs,toolMs:d.toolMs,toolCalls:d.toolCalls,toolSummary:d.toolSummary})}}catch(d){let u={text:`Something went wrong: ${String(d)}`,agentId:o,workItem:e,costUsd:0,durationMs:0,error:String(d)};if(c)try{await c.deliver(u)}catch(h){q.warn("Error delivery failed, queuing for retry",{error:String(h)}),this.retryQueue?.enqueue(u,c)}q.error("Dispatch failed",{agentId:o,error:String(d)})}finally{await c?.onProcessingEnd?.(e,o)}}pruneDedup(){let e=Date.now()-n.DEDUP_TTL_MS;for(let[t,s]of this.recentMessageIds)s<e&&this.recentMessageIds.delete(t)}async resolveAgents(e){let t=e.meta?.targetAgentId;if(t&&this.registry.get(t))return[{agentId:t}];if(e.source.kind==="team")return this.resolveFromTeam(e);let s=e.meta?.origin;if(s){let a=this.registry.findByOrigin(s);return a?[{agentId:a.id}]:(q.warn("Origin not routed",{origin:s,deviceId:e.meta?.deviceId,text:e.text.slice(0,50)}),[])}if(e.source.kind==="slack"&&e.source.label.startsWith("conf-"))return this.resolveConferenceAgents(e);let r=this.registry.findByChannel(e.source.label);if(r)return[{agentId:r.id}];if(e.threadId){let a=this.registry.findAllByName(e.text),l=new Set(a.map(h=>h.id)),c=this.threadParticipants.get(e.threadId);if(c){for(let h of l)c.add(h);return this.threadAgentLastSeen.set(e.threadId,Date.now()),[...c].map(h=>({agentId:h}))}let d=this.threadAgentMap.get(e.threadId);if(d){let h=a.some(p=>p.id!==d);if(l.size>0&&h){let p=new Set([d,...l]);return this.threadParticipants.set(e.threadId,p),this.threadAgentMap.delete(e.threadId),this.threadAgentLastSeen.set(e.threadId,Date.now()),q.info("Thread transitioned to multi-agent",{threadId:e.threadId,participants:[...p]}),[...p].map(m=>({agentId:m}))}return this.threadAgentLastSeen.set(e.threadId,Date.now()),[{agentId:d}]}let u=await this.agentManager.findAgentsForThread(e.threadId);if(u.length>0){let h=u.filter(p=>this.registry.get(p));if(h.length>1){let p=new Set(h);return this.threadParticipants.set(e.threadId,p),this.threadAgentLastSeen.set(e.threadId,Date.now()),[...p].map(m=>({agentId:m}))}if(h.length===1)return this.threadAgentMap.set(e.threadId,h[0]),this.threadAgentLastSeen.set(e.threadId,Date.now()),[{agentId:h[0]}]}}let i=this.registry.findAllByName(e.text);if(i.length>0)return i.map(a=>({agentId:a.id}));let o=e.meta?.defaultAgentId;return o&&this.registry.get(o)?[{agentId:o}]:this.isDirectMessage(e)&&this.registry.get(this.defaultAgentId)?(q.info("DM routed to default agent",{agentId:this.defaultAgentId,channel:e.source.id}),[{agentId:this.defaultAgentId}]):(q.debug("No agent matched \u2014 dropping",{channel:e.source.label}),[])}isDirectMessage(e){return!!(e.source.kind==="slack"&&e.source.id.startsWith("D")||e.meta?.channelType==="im"||e.source.kind==="team"&&typeof e.source.id=="string"&&e.source.id.startsWith("dm:"))}async resolveFromTeam(e){let t=e.meta?.channelId;if(!t||!this.teamStore){let o=e.meta?.defaultAgentId;return o&&this.registry.get(o)?[{agentId:o}]:[]}let s=await this.teamStore.getChannel(t);if(!s)return q.warn("Team channel not found",{channelId:t}),[];if(s.type==="dm"){let o=s.members.find(a=>a!==e.sender);return o&&this.registry.get(o)?[{agentId:o}]:(q.warn("DM agent not found in registry",{channelId:t,members:s.members}),[])}let r=this.registry.findAllByName(e.text);if(r.length>0){let o=new Set(s.members),a=r.filter(l=>o.has(l.id));if(a.length>0)return a.map(l=>({agentId:l.id}))}let i=s.members.filter(o=>this.registry.get(o));return i.length>0?[{agentId:i[0]}]:(q.warn("No agent members in Team channel",{channelId:t}),[])}async dispatchToAgent(e,t){let{agentId:s}=t,r=e;if(t.conferenceMode){let l=[t.meetingPreamble,"",t.threadContext,"","---","[New message]:"].filter(Boolean).join(`
333
+ `);r={...e,text:`${l}
334
+ ${e.text}`,meta:{...e.meta,conferenceMode:!0,conferenceHumanTs:t.conferenceHumanTs,conferenceRound:t.conferenceRound}}}let i=r.threadId??r.id;this.threadAgentLastSeen.set(i,Date.now());let o=this.taskLedger?.shouldTrack(r)??!1;o&&this.taskLedger.onDispatch(r,s).catch(l=>q.warn("Task ledger dispatch failed",{error:String(l)}));let a=this.adapters.get(r.source.adapterId??r.source.kind);try{let l=await this.agentManager.sendMessage(s,r),c=l.text.trim(),d=Vh.some(u=>u.test(c));if(d)q.info("Non-response suppressed (fan-out)",{agentId:s});else{let u={text:l.text||"_No response._",agentId:s,workItem:r,costUsd:l.costUsd,durationMs:l.durationMs,error:l.error};if(a)try{await a.deliver(u)}catch{this.retryQueue?.enqueue(u,a)}t.conferenceMode&&t.conferenceRound===0&&!d&&this.triggerConferenceReactions(l.text,e,s,t.conferenceHumanTs).catch(h=>q.warn("Conference reaction trigger failed",{error:String(h)})),o&&this.taskLedger.onComplete(u).catch(h=>q.warn("Task ledger complete failed",{error:String(h)})),this.auditAdapter&&r.source.kind!==this.auditAdapter.kind&&await this.postAuditLog(u),q.info("Fan-out dispatch complete",{agentId:s,costUsd:l.costUsd,durationMs:l.durationMs})}}catch(l){let c={text:`Something went wrong: ${String(l)}`,agentId:s,workItem:r,costUsd:0,durationMs:0,error:String(l)};if(a)try{await a.deliver(c)}catch{this.retryQueue?.enqueue(c,a)}q.error("Fan-out dispatch failed",{agentId:s,error:String(l)})}}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.threadAgentLastSeen)i<t&&(this.threadAgentMap.delete(r),this.threadParticipants.delete(r),this.meetingRosters.delete(r),this.meetingReactionTracker.delete(r),this.threadAgentLastSeen.delete(r),s++);return{component:"dispatcher",pruned:s,retried:0,bytesFreed:0,errors:[]}}async resolveConferenceAgents(e){let t=e.threadId??e.id,s=this.meetingRosters.get(t)??new Set,r=this.registry.findAllByName(e.text);for(let d of r)s.add(d.id);if(this.meetingRosters.set(t,s),this.threadAgentLastSeen.set(t,Date.now()),s.size===0)return q.debug("Conference channel \u2014 no roster yet",{channel:e.source.label,threadId:t}),[];let i=[];for(let d of s){let u=this.registry.get(d);!u||u.disabled||i.push({agentId:u.id,name:u.name,title:u.title,role:u.soul.split(`
335
+ `)[0]})}if(i.length===0)return[];let o="",a="";if(this.slackAdapter){let d=e.source.id,u=e.meta?.slackThreadTs??e.meta?.slackTs??t,h=await this.slackAdapter.fetchThreadHistory(d,u);o=this.formatThreadContext(h,e.source.label,i),a=h.slice(-5).map(p=>`${p.author}: ${p.text.slice(0,200)}`).join(`
336
+ `)}let l=await Ua(e.text,i,a);q.info("Conference classifier result",{channel:e.source.label,threadId:t,roster:[...s],selected:l.respondAgentIds,costUsd:l.costUsd});let c=this.buildMeetingPreamble(e.source.label,i);return l.respondAgentIds.map(d=>({agentId:d,conferenceMode:!0,conferenceHumanTs:e.meta?.slackTs,conferenceRound:0,threadContext:o,meetingPreamble:c}))}formatThreadContext(e,t,s){if(e.length===0)return"";let r=s.map(l=>l.name).join(", "),i=`[Meeting thread in #${t} \u2014 participants: ${r}]`,o=e;if(e.length>105){let l=e.slice(0,5),c=e.slice(-100);o=[...l,...c]}let a=o.map(l=>{let c=this.formatTimeAgo(l.timestamp);return`${l.author} (${c}): ${l.text}`}).join(`
334
337
  `);return`${i}
335
338
 
336
- ${a}`}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);if(t<60)return`${t}s ago`;let s=Math.floor(t/60);return s<60?`${s} min ago`:`${Math.floor(s/60)}h ago`}buildMeetingPreamble(e,t){let s=t.map(n=>n.name).join(", ");return`You are in a meeting in #${e} with ${s}.
339
+ ${a}`}formatTimeAgo(e){let t=Math.floor((Date.now()-e.getTime())/1e3);if(t<60)return`${t}s ago`;let s=Math.floor(t/60);return s<60?`${s} min ago`:`${Math.floor(s/60)}h ago`}buildMeetingPreamble(e,t){let s=t.map(r=>r.name).join(", ");return`You are in a meeting in #${e} with ${s}.
337
340
 
338
341
  Meeting rules:
339
342
  - Be concise \u2014 others are also responding.
340
343
  - Build on what's been said. Don't repeat points already made.
341
344
  - If you have nothing meaningful to add, respond with "No response needed."
342
345
  - Stay in your lane \u2014 don't cover someone else's domain unless asked.
343
- - Address others by name when responding to their points.`}async triggerConferenceReactions(e,t,s,n){let i=t.threadId??t.id,o=this.meetingRosters.get(i);if(!o)return;this.meetingReactionTracker.has(i)||this.meetingReactionTracker.set(i,new Map);let a=this.meetingReactionTracker.get(i),l=a.get(n)??new Set;a.set(n,l);let c=[];for(let f of o){if(f===s||l.has(f))continue;let y=this.registry.get(f);!y||y.disabled||(l.add(f),c.push({agentId:y.id,name:y.name,title:y.title,role:y.soul.split(`
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
- `)[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
+ - Address others by name when responding to their points.`}async triggerConferenceReactions(e,t,s,r){let i=t.threadId??t.id,o=this.meetingRosters.get(i);if(!o)return;this.meetingReactionTracker.has(i)||this.meetingReactionTracker.set(i,new Map);let a=this.meetingReactionTracker.get(i),l=a.get(r)??new Set;a.set(r,l);let c=[];for(let f of o){if(f===s||l.has(f))continue;let y=this.registry.get(f);!y||y.disabled||(l.add(f),c.push({agentId:y.id,name:y.name,title:y.title,role:y.soul.split(`
347
+ `)[0]}))}if(c.length===0)return;let d=await Ua(e,c),u=new Set(d.respondAgentIds);for(let f of c)u.has(f.agentId)||l.delete(f.agentId);if(d.respondAgentIds.length===0)return;q.info("Conference depth-1 reactions",{threadId:i,respondingAgent:s,peers:d.respondAgentIds});let h="",p="";if(this.slackAdapter){let f=t.source.id,y=t.meta?.slackThreadTs??t.meta?.slackTs??i,w=await this.slackAdapter.fetchThreadHistory(f,y),S=[];for(let _ of o){let v=this.registry.get(_);!v||v.disabled||S.push({agentId:v.id,name:v.name,title:v.title,role:v.soul.split(`
348
+ `)[0]})}h=this.formatThreadContext(w,t.source.label,S),p=this.buildMeetingPreamble(t.source.label,S)}let m=d.respondAgentIds.map(f=>{let y={agentId:f,conferenceMode:!0,conferenceHumanTs:r,conferenceRound:1,threadContext:h,meetingPreamble:p};return this.dispatchToAgent(t,y)});await Promise.all(m)}async postAuditLog(e){if(!this.auditAdapter||!this.auditChannelIds)return;let t=this.registry.get(e.agentId),s=t?.name??e.agentId,r=t?.homeBase,i=(r?this.auditChannelIds.get(r):void 0)??this.fallbackAuditChannelId;if(!i){q.warn("No audit channel resolved for agent",{agentId:e.agentId,homeBase:r});return}if(e.workItem.source.kind==="slack"&&e.workItem.source.id===i)return;let o=e.workItem.source.kind==="sms"?":phone:":e.workItem.source.kind==="imessage"?":speech_balloon:":e.workItem.source.kind==="app"?":iphone:":":incoming_envelope:",a=e.workItem.senderName??e.workItem.sender,l=e.text.length>300?e.text.slice(0,300)+"...":e.text,c={id:`audit:${e.workItem.id}`,text:`${o} *${s}* handled ${e.workItem.source.kind} from ${a}:
346
349
  > ${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 _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(`
350
+ _($${e.costUsd.toFixed(3)} \xB7 ${(e.durationMs/1e3).toFixed(1)}s)_`,source:{kind:"internal",id:i,label:"audit"},sender:"system",timestamp:new Date,meta:{slackThreadTs:e.workItem.meta?.slackThreadTs,slackTs:e.workItem.meta?.slackTs}};await this.auditAdapter.deliver({text:c.text,agentId:"system",workItem:c,costUsd:0,durationMs:0})}};M();function Ek(n){let e=n;return e=e.replace(/^#{1,6}\s+(.+)$/gm,"*$1*"),e=e.replace(/\*{3}(.+?)\*{3}/g,"*_$1_*"),e=e.replace(/\*{2}(.+?)\*{2}/g,"*$1*"),e=e.replace(/__(.+?)__/g,"*$1*"),e=e.replace(/\[([^\]]+)\]\(([^)]+)\)/g,"<$2|$1>"),e=e.replace(/~~(.+?)~~/g,"~$1~"),e=e.replace(/^[-*_]{3,}$/gm,"\u2014\u2014\u2014"),e}function Yh(n){return n?Ek(n.trim()):"_No response._"}function Jh(n){return`Something went wrong: ${n}`}var At=k("slack-adapter"),Nk=[{title:"Daily briefing",message:"What's on my plate today?"},{title:"Open tasks",message:"Show me all open tasks from Linear"},{title:"System status",message:"How's everyone doing?"},{title:"Quick note",message:"I need to remember something..."}],qr=class{id;kind="slack";gateway;registry;excludeChannels;defaultAgentId;botLabel;threadContextMap=new Map;threadContextLastSeen=new Map;constructor(e,t,s=[],r="slack",i,o){this.id=r,this.gateway=e,this.registry=t,this.excludeChannels=new Set(s),this.defaultAgentId=i,this.botLabel=o}async start(e){let t=this.registry.getAll().filter(s=>!s.slackBot||s.slackBot===this.botLabel).flatMap(s=>s.channels).filter(s=>!this.excludeChannels.has(s));this.gateway.addIntegrationChannels(t),this.gateway.onMessage(async s=>{if(this.excludeChannels.has(s.channelName)){At.debug("Ignoring message from excluded channel",{channel:s.channelName});return}let r=this.registry.findByChannel(s.channelName);if(r&&r.slackBot&&r.slackBot!==this.botLabel){At.debug("Ignoring message from other bot's channel",{channel:s.channelName,owner:r.id,botLabel:this.botLabel});return}let i=s.user.startsWith("U")?await this.gateway.resolveUserName(s.user):void 0,o={id:s.ts,text:s.text,source:{kind:"slack",id:s.channel,label:s.channelName,adapterId:this.id},sender:s.user,senderName:i,threadId:`slack:${s.channel}:${s.threadTs??s.ts}`,timestamp:new Date,meta:{slackTs:s.ts,slackThreadTs:s.threadTs,defaultAgentId:this.defaultAgentId},files:s.files};e(o)}),this.gateway.onThreadStarted(async s=>{At.info("Setting up new assistant thread",{channel:s.channel}),await this.gateway.setThreadStatus(s.channel,s.threadTs,"Getting ready..."),await this.gateway.setSuggestedPrompts(s.channel,s.threadTs,Nk),await this.gateway.setThreadStatus(s.channel,s.threadTs,""),s.context.channelId&&(this.threadContextMap.set(s.threadTs,s.context.channelId),this.threadContextLastSeen.set(s.threadTs,Date.now()))}),this.gateway.onThreadContextChanged(async s=>{s.context.channelId&&(this.threadContextMap.set(s.threadTs,s.context.channelId),this.threadContextLastSeen.set(s.threadTs,Date.now()),At.info("Thread context updated",{threadTs:s.threadTs,channelId:s.context.channelId}))}),await this.gateway.start(),At.info("Slack adapter started")}async deliver(e){let t=e.workItem.source.id,s=e.workItem.meta?.slackThreadTs??e.workItem.meta?.slackTs,r=this.registry.get(e.agentId),o=e.workItem.sender?.startsWith("B")||e.workItem.sender==="integration"?void 0:s,a=e.error?Jh(e.error):Yh(e.text);r&&(a=`${r.icon?`${r.icon} `:""}*${r.name}*: ${a}`);let l=r?{name:r.name,icon:r.icon}:void 0;await this.gateway.postMessage(t,a,o,l)}async onProcessingStart(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",r=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&r&&await this.gateway.setThreadStatus(e.source.id,r,"Thinking...")}async onProcessingEnd(e,t){let s=e.sender?.startsWith("B")||e.sender==="integration",r=e.meta?.slackThreadTs??e.meta?.slackTs;!s&&r&&await this.gateway.setThreadStatus(e.source.id,r,"")}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.threadContextLastSeen)i<t&&(this.threadContextMap.delete(r),this.threadContextLastSeen.delete(r),s++);return{component:`slack-adapter:${this.id}`,pruned:s,retried:0,bytesFreed:0,errors:[]}}async stop(){await this.gateway.stop(),At.info("Slack adapter stopped")}get client(){return this.gateway.client}async fetchThreadHistory(e,t){try{let s=await this.gateway.client.conversations.replies({channel:e,ts:t,limit:200}),r=[],i=new Map;for(let o of s.messages??[]){if(!o.text&&!o.blocks)continue;let a="Unknown",l=!1,c=o;if(o.bot_id||c.subtype==="bot_message"){let d=o.text?.match(/^\S+\s\*([^*]+)\*:/);a=d?d[1]:c.username??"Agent",l=!0}else if(o.user){let d=i.get(o.user);if(d)a=d;else{try{let u=await this.gateway.client.users.info({user:o.user});a=u.user?.real_name??u.user?.name??o.user}catch{a=o.user}i.set(o.user,a)}}r.push({author:a,text:o.text??"",timestamp:new Date(parseFloat(o.ts??"0")*1e3),isBot:l})}return r}catch(s){return At.warn("Failed to fetch thread history",{channelId:e,threadTs:t,error:String(s)}),[]}}};M();var We=k("sms-adapter"),zh="https://api.openphone.com/v1",Fr=class{id="sms";kind="sms";apiKey;lines;interval=null;constructor(e,t){this.apiKey=e,this.lines=t.map(s=>({id:s.id,label:s.label,number:s.number,routeLabel:s.slackChannel??s.label,lastSeen:new Date().toISOString()}))}async start(e){if(this.lines.length===0){We.warn("SMS adapter has no lines to watch");return}this.poll(e),this.interval=setInterval(()=>this.poll(e),3e4),We.info("SMS adapter started",{lines:this.lines.map(t=>t.label)})}async deliver(e){if(e.error){We.warn("Skipping SMS delivery due to error",{error:e.error});return}let t=e.workItem.sender,s=e.workItem.source.id;try{let r=await fetch(`${zh}/messages`,{method:"POST",headers:{Authorization:this.apiKey,"Content-Type":"application/json"},body:JSON.stringify({from:s,to:[t],content:e.text})});r.ok?We.info("SMS reply sent",{to:t,from:s}):We.error("Failed to send SMS reply",{status:r.status,body:await r.text(),to:t})}catch(r){We.error("SMS delivery error",{error:String(r),to:t})}}async stop(){this.interval&&(clearInterval(this.interval),this.interval=null),We.info("SMS adapter stopped")}async quoApi(e,t={}){let s=new URL(`${zh}${e}`);for(let[i,o]of Object.entries(t))o&&s.searchParams.append(i,o);let r=await fetch(s.toString(),{headers:{Authorization:this.apiKey}});if(!r.ok)throw new Error(`Quo API ${r.status}: ${await r.text()}`);return r.json()}async poll(e){for(let t of this.lines)try{let r=(await this.quoApi("/conversations",{"phoneNumbers[]":t.id,updatedAfter:t.lastSeen,maxResults:"20"})).data??[];if(r.length===0)continue;for(let i of r){let o=i.participants?.[0];if(!o)continue;let l=((await this.quoApi("/messages",{phoneNumberId:t.id,"participants[]":o,maxResults:"10",createdAfter:t.lastSeen})).data??[]).filter(c=>c.direction==="incoming").reverse();for(let c of l){if(!c.text)continue;let d=`SMS from ${c.from} \u2192 ${t.label}:
351
+ ${c.text}`,u={id:c.id,text:d,source:{kind:"sms",id:t.id,label:t.routeLabel},sender:c.from,threadId:`sms:${t.id}:${c.from}`,timestamp:new Date,meta:{quoMessageId:c.id,lineNumber:t.number}};We.info("SMS received",{from:c.from,line:t.label,textLength:c.text.length}),e(u)}}t.lastSeen=new Date().toISOString()}catch(s){We.error("SMS poll failed",{line:t.label,error:String(s)})}}};M();import{execFileSync as Bk}from"node:child_process";import{readFileSync as Uk,writeFileSync as jk,existsSync as Xh,mkdirSync as qk}from"node:fs";import{resolve as Zh}from"node:path";M();import xk from"better-sqlite3";var Qh=k("imessage-db"),Ok=978307200,Mk=43;function Dk(n){let e=n/1e9+Ok;return new Date(e*1e3)}function Lk(n){try{let e=Buffer.from("NS.string"),t=n.indexOf(e);if(t===-1){let o=Buffer.from("NS.data");t=n.indexOf(o)}if(t===-1){let o=Buffer.from("streamtyped"),a=n.indexOf(o);return a===-1?null:Pk(n,a+o.length)}for(t+=e.length;t<n.length&&n[t]<32&&n[t]!==10;)t++;let s=t,r=t;for(;r<n.length;){let o=n[r];if(o===0||o===6&&r>s+1)break;r++}if(r<=s)return null;let i=n.subarray(s,r).toString("utf-8").trim();return i.length>0?i:null}catch(e){return Qh.warn("Failed to extract text from attributedBody",{error:String(e)}),null}}function Pk(n,e){let t=e,s=-1,r=0;for(;t<n.length-1;)if($k(n[t])){let o=t,a=0;for(;t<n.length&&Rk(n[t]);)a++,t++;a>r&&a>4&&(s=o,r=a)}else t++;if(s===-1)return null;let i=n.subarray(s,s+r).toString("utf-8").trim();return i.length>0?i:null}function $k(n){return n>=32&&n<=126||n>=192}function Rk(n){return n>=32&&n<=126||n===10||n===13||n===9||n>=128}var Kr=class{db;constructor(e){let t=e??`${process.env.HOME}/Library/Messages/chat.db`;this.db=new xk(t,{readonly:!0})}getNewMessages(e){let t=this.db.prepare(`
349
352
  SELECT m.ROWID AS rowId, m.text, m.attributedBody, m.is_from_me AS isFromMe,
350
353
  m.date, m.service, h.id AS sender, h.ROWID AS handleRowId
351
354
  FROM message m
@@ -357,46 +360,46 @@ ${c.text}`,u={id:c.id,text:d,source:{kind:"sms",id:t.id,label:t.routeLabel},send
357
360
  AND m.is_empty = 0
358
361
  AND (c.style IS NULL OR c.style != ?)
359
362
  ORDER BY m.ROWID ASC
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)+`
363
+ `).all(e,Mk),s=[];for(let r of t){let i=r.text;if(!i&&r.attributedBody&&(i=Lk(r.attributedBody),!i)){Qh.warn("Could not extract text from attributedBody, skipping",{rowId:r.rowId});continue}i&&s.push({rowId:r.rowId,text:i,sender:r.sender,handleRowId:r.handleRowId,service:r.service,date:Dk(r.date)})}return s}getMaxRowId(){return this.db.prepare("SELECT MAX(ROWID) AS maxId FROM message").get().maxId??0}close(){this.db.close()}};var ne=k("imessage-adapter"),Hr=class{id="imessage";kind="imessage";config;mongoDb;gateway;db;threadsCollection;contactsCollection;slackChannelId;interval=null;lastSeenRowId=0;lastMessageAt=0;lastColdPoll=0;stateFilePath;constructor(e,t,s,r){this.config=e,this.mongoDb=t,this.gateway=s,this.stateFilePath=Zh(`/tmp/${r}-imessage-state.json`)}async start(e){this.threadsCollection=this.mongoDb.collection("imessage_threads"),this.contactsCollection=this.mongoDb.collection("contacts");try{let s=((await this.gateway.client.conversations.list({types:"public_channel",limit:200})).channels??[]).find(r=>r.name===this.config.slackChannel);s?.id?(this.slackChannelId=s.id,ne.info("Slack mirror channel resolved",{channel:this.config.slackChannel,id:s.id})):ne.warn("Slack mirror channel not found",{channel:this.config.slackChannel})}catch(t){ne.warn("Failed to resolve Slack mirror channel",{error:String(t)})}try{this.db=new Kr}catch(t){ne.error("Failed to open chat.db \u2014 check Full Disk Access for node",{error:String(t)});return}this.loadState(),this.lastSeenRowId===0&&(this.lastSeenRowId=this.db.getMaxRowId(),this.saveState(),ne.info("First run \u2014 initialized lastSeenRowId",{lastSeenRowId:this.lastSeenRowId})),this.interval=setInterval(()=>this.poll(e),this.config.hotIntervalMs),this.poll(e),ne.info("iMessage adapter started",{lastSeenRowId:this.lastSeenRowId,hotIntervalMs:this.config.hotIntervalMs,coldIntervalMs:this.config.coldIntervalMs})}async deliver(e){if(e.error){ne.warn("Skipping iMessage delivery due to error",{error:e.error});return}let t=e.workItem.sender;try{this.sendViaAppleScript(t,e.text),ne.info("iMessage reply sent",{to:t})}catch(s){ne.warn("iMessage send failed, retrying",{error:String(s),to:t});try{await Fk(500),this.sendViaAppleScript(t,e.text),ne.info("iMessage reply sent on retry",{to:t})}catch(r){ne.error("iMessage delivery failed after retry",{error:String(r),to:t});return}}await this.mirrorToSlack(t,e.text,e.agentId,!0)}async stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.db?.close(),ne.info("iMessage adapter stopped")}async poll(e){let t=Date.now(),s=t-this.lastMessageAt<this.config.hotWindowMs;if(!(!s&&t-this.lastColdPoll<this.config.coldIntervalMs)&&(s||(this.lastColdPoll=t),!!this.db))try{let r=this.db.getNewMessages(this.lastSeenRowId);if(r.length===0)return;for(let i of r){this.lastSeenRowId=i.rowId,this.lastMessageAt=t;let o={id:`imsg-${i.rowId}`,text:i.text,source:{kind:"imessage",id:"imessage",label:"imessage"},sender:i.sender,threadId:`imessage:${i.sender}`,timestamp:i.date,meta:{messageRowId:i.rowId,service:i.service}};ne.info("iMessage received",{from:i.sender,service:i.service,textLength:i.text.length}),await this.mirrorToSlack(i.sender,i.text,void 0,!1),e(o)}this.saveState()}catch(r){ne.error("iMessage poll failed",{error:String(r)})}}sendViaAppleScript(e,t){let s=t.replace(/\\/g,"\\\\").replace(/"/g,'\\"');Bk("osascript",["-e",'tell application "Messages"',"-e","set targetService to 1st account whose service type = iMessage","-e",`set targetBuddy to participant "${e}" of targetService`,"-e",`send "${s}" to targetBuddy`,"-e","end tell"])}async mirrorToSlack(e,t,s,r){if(!(!this.slackChannelId||!this.threadsCollection))try{let i=await this.threadsCollection.findOne({handleId:e}),o;if(i)o=i.slackThreadTs;else{let l=await this.resolveContactName(e),c=`:speech_balloon: iMessage conversation with ${l}`,d=await this.gateway.postMessage(this.slackChannelId,c);if(!d){ne.warn("Failed to create Slack mirror thread",{handleId:e});return}o=d,await this.threadsCollection.insertOne({handleId:e,slackThreadTs:o,displayName:l,createdAt:new Date})}let a=r?s?`*${s}*: `:"*Agent*: ":`*${e}*: `;await this.gateway.postMessage(this.slackChannelId,`${a}${t}`,o)}catch(i){ne.warn("Slack mirror failed",{error:String(i),handleId:e})}}async resolveContactName(e){if(!this.contactsCollection)return e;try{let t=await this.contactsCollection.findOne({$or:[{phones:e},{emails:e}]});if(t?.displayName)return`${t.displayName} (${e})`;if(t?.name)return`${t.name} (${e})`}catch{}return e}loadState(){try{if(Xh(this.stateFilePath)){let e=JSON.parse(Uk(this.stateFilePath,"utf-8"));this.lastSeenRowId=e.lastSeenRowId??0,ne.info("Restored iMessage state",{lastSeenRowId:this.lastSeenRowId})}}catch(e){ne.warn("Failed to load iMessage state, starting fresh",{error:String(e)})}}saveState(){try{let e=Zh(this.stateFilePath,"..");Xh(e)||qk(e,{recursive:!0}),jk(this.stateFilePath,JSON.stringify({lastSeenRowId:this.lastSeenRowId}))}catch(e){ne.warn("Failed to save iMessage state",{error:String(e)})}}};function Fk(n){return new Promise(e=>setTimeout(e,n))}M();var Qt=k("task-client"),Wr=class{apiUrl;apiKey;constructor(e,t){this.apiUrl=e,this.apiKey=t}get isConfigured(){return this.apiKey.length>0}async api(e,t,s){let r=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":this.apiKey,...s?{"Content-Type":"application/json"}:{}},...s?{body:JSON.stringify(s)}:{}});if(!r.ok)throw new Error(`Task API ${r.status}: ${await r.text()}`);return r.json()}async createTask(e){try{let t=await this.api("POST","/tasks",e);return Qt.info("Task created",{taskId:t._id,name:e.name}),t}catch(t){return Qt.error("Failed to create task",{error:String(t),name:e.name}),null}}async updateTask(e,t){try{return await this.api("PUT",`/tasks/${e}`,t),Qt.info("Task updated",{taskId:e,...t}),!0}catch(s){return Qt.error("Failed to update task",{error:String(s),taskId:e}),!1}}async addComment(e,t){try{return await this.api("POST",`/tasks/${e}/comments`,{content:t}),Qt.info("Comment added",{taskId:e}),!0}catch(s){return Qt.error("Failed to add comment",{error:String(s),taskId:e}),!1}}};M();var zs=k("task-ledger"),Gr=class{threadTaskMap=new Map;threadTaskLastSeen=new Map;apiUrl;agentKeys;fallbackKey;constructor(e,t,s){this.apiUrl=e,this.agentKeys=t,this.fallbackKey=s}get isConfigured(){return Object.keys(this.agentKeys).length>0||this.fallbackKey.length>0}shouldTrack(e){return e.source.kind!=="slack"&&e.source.kind!=="sms"}async onDispatch(e,t){let s=this.getApiKey(t);if(!s)return;let r=e.threadId??e.id,i=this.threadTaskMap.get(r);if(i){this.threadTaskLastSeen.set(r,Date.now()),await this.addComment(i,s,this.formatIncomingComment(e));return}let o=await this.createTask(s,e);o&&(this.threadTaskMap.set(r,o),this.threadTaskLastSeen.set(r,Date.now()))}async onComplete(e){let t=this.getApiKey(e.agentId);if(!t)return;let s=e.workItem.threadId??e.workItem.id,r=this.threadTaskMap.get(s);if(r&&this.threadTaskLastSeen.set(s,Date.now()),!r)return;let i=this.formatCompletionComment(e);await this.addComment(r,t,i),e.error||await this.updateTask(r,t,{state:"DONE"})}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.threadTaskLastSeen)i<t&&(this.threadTaskMap.delete(r),this.threadTaskLastSeen.delete(r),s++);return{component:"task-ledger",pruned:s,retried:0,bytesFreed:0,errors:[]}}getApiKey(e){let t=this.agentKeys[e]??this.fallbackKey;return t||(zs.debug("No task ledger API key for agent",{agentId:e}),null)}async createTask(e,t){try{let s=await this.api("POST","/tasks",e,{name:this.taskName(t),type:this.taskType(t),description:this.taskDescription(t)});return zs.info("Task created",{taskId:s.taskId,source:t.source.kind}),s.taskId}catch(s){return zs.error("Failed to create task",{error:String(s),source:t.source.kind}),null}}async addComment(e,t,s){try{await this.api("POST",`/tasks/${e}/comments`,t,{content:s})}catch(r){zs.error("Failed to add comment",{error:String(r),taskId:e})}}async updateTask(e,t,s){try{await this.api("PUT",`/tasks/${e}`,t,s)}catch(r){zs.error("Failed to update task",{error:String(r),taskId:e})}}async api(e,t,s,r){let i=await fetch(`${this.apiUrl}/api/v1${t}`,{method:e,headers:{"x-api-key":s,...r?{"Content-Type":"application/json"}:{}},...r?{body:JSON.stringify(r)}:{}});if(!i.ok)throw new Error(`Task API ${i.status}: ${await i.text()}`);return i.json()}taskName(e){let t=e.text,s=t.match(/\[Scheduled task: (.+?)\]/);if(s)return`[Scheduled] ${s[1]}`;let r=t.match(/Command: `(.+?)`/);if(r)return`[Background] ${r[1].slice(0,80)}`;let i=t.match(/\[Meeting (?:transcript update|ended) — (.+?)\]/);return i?`[Meeting] ${i[1]}`:e.source.kind==="email"?`[Email] ${t.slice(0,80)}`:`[${e.source.kind}] ${t.slice(0,80)}`}taskType(e){return e.source.kind==="email"?"FOLLOW_UP":e.text.includes("[Meeting ended")?"ACTION_ITEM":"AGENT"}taskDescription(e){let t=[`**Source:** ${e.source.kind} / ${e.source.label}`,`**Sender:** ${e.senderName??e.sender}`,`**Time:** ${e.timestamp.toISOString()}`];e.threadId&&t.push(`**Thread:** ${e.threadId}`);let s=5e3,r=e.text.length>s?e.text.slice(0,s)+`
361
364
 
362
- ... (truncated)`:e.text;return t.push("","---","",n),t.join(`
365
+ ... (truncated)`:e.text;return t.push("","---","",r),t.join(`
363
366
  `)}formatIncomingComment(e){return`**Follow-up message** (${e.source.kind})
364
367
 
365
368
  ${e.text.slice(0,5e3)}`}formatCompletionComment(e){let t=[`**Agent response** ($${e.costUsd.toFixed(3)} \xB7 ${(e.durationMs/1e3).toFixed(1)}s)`];e.error&&t.push(`
366
- **Error:** ${e.error}`);let s=5e3,n=e.text.length>s?e.text.slice(0,s)+`
369
+ **Error:** ${e.error}`);let s=5e3,r=e.text.length>s?e.text.slice(0,s)+`
367
370
 
368
- ... (truncated)`:e.text;return t.push("",n),t.join(`
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
+ ... (truncated)`:e.text;return t.push("",r),t.join(`
372
+ `)}};M();import{createServer as Kk}from"node:http";import{spawn as Hk}from"node:child_process";import{mkdir as Wk,readFile as ef,writeFile as Gk,readdir as Vk,stat as Yk,unlink as Jk}from"node:fs/promises";import{openSync as zk,closeSync as Qk}from"node:fs";import{randomUUID as Xk}from"node:crypto";var we=k("bg-task-manager"),ja=100,Zk=5e3,Vr=class{port;authToken;tasksDir;tasks=new Map;onComplete;server=null;orphanPollers=new Map;constructor(e,t,s,r){this.port=e,this.authToken=t,this.tasksDir=s,this.onComplete=r}async start(){await Wk(this.tasksDir,{recursive:!0}),this.server=Kk((e,t)=>{this.handleRequest(e,t).catch(s=>{we.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),we.info("Background task manager started",{port:this.port})}async scanOrphans(){let e;try{e=await Vk(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".json")),s=0,r=0;for(let i of t)try{let o=await ef(`${this.tasksDir}/${i}`,"utf-8"),a=JSON.parse(o);this.tasks.set(a.id,a),a.status==="running"&&a.pid&&(this.isProcessAlive(a.pid)?(this.pollOrphan(a.id,a.pid),r++):(a.status="orphaned",a.completedAt=new Date().toISOString(),await this.writeMeta(a),this.fireCompletion(a),s++))}catch(o){we.warn("Failed to read orphan task file",{file:i,error:String(o)})}(s>0||r>0)&&we.info("Orphan scan complete",{orphaned:s,recovered:r,total:t.length})}async stop(){for(let[,t]of this.orphanPollers)clearInterval(t);this.orphanPollers.clear();let e=[...this.tasks.values()].filter(t=>t.status==="running"&&t.pid);if(e.length>0){we.info("Sending SIGTERM to running background tasks",{count:e.length});for(let t of e)this.killProcess(t.pid,"SIGTERM");await this.sleep(Zk);for(let t of e)t.pid&&this.isProcessAlive(t.pid)&&(we.warn("Background task did not exit after SIGTERM, sending SIGKILL",{id:t.id,pid:t.pid}),this.killProcess(t.pid,"SIGKILL"))}this.server&&(this.server.close(),this.server=null),we.info("Background task manager stopped",{killed:e.length})}killProcess(e,t){try{process.kill(e,t)}catch(s){s.code!=="ESRCH"&&we.warn("Failed to send signal to process",{pid:e,signal:t,error:String(s)})}}sleep(e){return new Promise(t=>setTimeout(t,e))}async handleRequest(e,t){let s=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="POST"&&s.pathname==="/tasks"){let o=await this.readBody(e),a=JSON.parse(o),l=await this.spawnTask(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:l.id,status:"running"}));return}let i=s.pathname.match(/^\/tasks\/([a-f0-9-]+)$/);if(e.method==="GET"&&i){let o=i[1],a=await this.taskStatus(o);if(!a){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Task not found"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(a));return}if(e.method==="GET"&&s.pathname==="/tasks"){let o=s.searchParams.get("agentId")??void 0,a=await this.listTasks(o);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({tasks:a}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}async spawnTask(e){let t=Xk(),s=`${this.tasksDir}/${t}.log`,r=`${this.tasksDir}/${t}.json`,i=e.cwd??process.env.HOME??"/tmp",o=zk(s,"a"),a=Hk(e.command,e.args??[],{cwd:i,detached:!0,stdio:["ignore",o,o]});Qk(o);let l={id:t,command:e.command+(e.args?.length?" "+e.args.join(" "):""),cwd:i,status:"running",exitCode:null,startedAt:new Date().toISOString(),completedAt:null,logPath:s,metaPath:r,context:e.context,pid:a.pid??null};return this.tasks.set(t,l),a.on("exit",c=>this.handleExit(t,c)),a.on("error",c=>{we.error("Background task process error",{id:t,error:String(c)}),this.handleExit(t,1)}),this.writeMeta(l).catch(()=>{}),we.info("Background task spawned",{id:t,command:e.command,cwd:i,pid:a.pid,agentId:e.context.agentId}),l}async handleExit(e,t){let s=this.tasks.get(e);!s||s.status!=="running"||(s.exitCode=t??1,s.status=s.exitCode===0?"completed":"failed",s.completedAt=new Date().toISOString(),await this.writeMeta(s),this.fireCompletion(s))}fireCompletion(e){let t=new Date(e.startedAt).getTime(),r=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-t)/1e3).toFixed(1);this.tailLog(e.logPath,ja).then(i=>{let o=e.status==="completed"?"completed":e.status==="failed"?"failed":"orphaned",a={id:`bg:${e.id}:done:${Date.now()}`,text:[`[Background task ${o}] Task \`${e.id}\` finished with exit code ${e.exitCode??"unknown"}.`,`Command: \`${e.command}\``,`Duration: ${r}s`,`Output (last ${ja} lines):`,"```",i||"(no output)","```"].join(`
373
+ `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,bgTaskId:e.id}};we.info("Background task completed, dispatching notification",{id:e.id,status:e.status,exitCode:e.exitCode,durationSec:r,agentId:e.context.agentId}),this.onComplete(a)}).catch(i=>{we.error("Failed to fire completion notification",{id:e.id,error:String(i)})})}async taskStatus(e){let t=this.tasks.get(e);if(!t)return null;let s=await this.tailLog(t.logPath,ja);return{id:t.id,status:t.status,exitCode:t.exitCode,startedAt:t.startedAt,completedAt:t.completedAt,command:t.command,output:s}}async listTasks(e){let t=[];for(let s of this.tasks.values())e&&s.context.agentId!==e||t.push({id:s.id,status:s.status,exitCode:s.exitCode,startedAt:s.startedAt,completedAt:s.completedAt,command:s.command});return t}async writeMeta(e){try{await Gk(e.metaPath,JSON.stringify(e,null,2),"utf-8")}catch(t){we.error("Failed to write task metadata",{id:e.id,error:String(t)})}}async tailLog(e,t){try{return(await ef(e,"utf-8")).split(`
371
374
  `).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 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+`
375
+ `).trim()}catch{return""}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}pollOrphan(e,t){let s=setInterval(()=>{if(!this.isProcessAlive(t)){clearInterval(s),this.orphanPollers.delete(e);let r=this.tasks.get(e);r&&r.status==="running"&&(r.status="orphaned",r.completedAt=new Date().toISOString(),this.writeMeta(r).then(()=>this.fireCompletion(r)))}},5e3);this.orphanPollers.set(e,s)}async sweep(e){let t=Date.now()-e,s=0,r=0,i=[];for(let[o,a]of this.tasks)if(!(a.status==="running"||!a.completedAt||new Date(a.completedAt).getTime()>t)){for(let c of[a.metaPath,a.logPath])try{let d=await Yk(c);r+=d.size,await Jk(c)}catch(d){d.code!=="ENOENT"&&i.push(`Failed to delete ${c}: ${String(d)}`)}this.tasks.delete(o),s++}return{component:"bg-task-manager",pruned:s,retried:0,bytesFreed:r,errors:i}}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();import{createServer as nb}from"node:http";import{spawn as rb}from"node:child_process";import{mkdir as ib,readFile as Yr,writeFile as ob,readdir as ab,stat as cb,unlink as lb,open as db}from"node:fs/promises";import{openSync as rf,closeSync as of}from"node:fs";import{randomUUID as ub}from"node:crypto";function tf(n){let e=n.trim();if(!e)return null;try{let t=JSON.parse(e);return t.type!=="result"?null:{sessionId:t.session_id??null,result:t.result??"",subtype:t.subtype??"unknown",costUsd:t.total_cost_usd??0,durationMs:t.duration_ms??0,numTurns:t.num_turns??0,isError:t.is_error===!0}}catch{return null}}var eb=/\*{0,2}Status:?\*{0,2}\s+(NEEDS_CONTEXT|BLOCKED)/i,tb=/\*{0,2}Question:?\*{0,2}\s+(.+?)(?:\n\n|\n\*{0,2}(?:Context|Status|Files|What)|$)/is,sb=/\*{0,2}Context:?\*{0,2}\s+(.+?)(?:\n\n\*{0,2}(?:Status|Question|Files|To respond)|$)/is;function sf(n){if(!n)return null;let e=eb.exec(n);if(!e)return null;let t=e[1].toUpperCase(),r=tb.exec(n)?.[1]?.trim()??"",o=sb.exec(n)?.[1]?.trim()??"";return{status:t,question:r,context:o}}function nf(n,e,t){return t||e?.subtype==="error_max_turns"||e?.subtype==="error_max_budget_usd"?"needs_input":n===0&&e?.subtype==="success"||n===0&&!e?"completed":"failed"}var ee=k("code-task-manager"),Qs=2e3,qa=100,af=5e3,Jr=class{port;authToken;pluginDirs;maxConcurrent;tasksDir;cliBin;options;tasks=new Map;onComplete;server=null;orphanPollers=new Map;reapTimers=new Set;constructor(e,t,s,r,i,o,a){this.port=e,this.authToken=t,this.pluginDirs=s,this.maxConcurrent=r,this.tasksDir=i,this.onComplete=o,this.options=a??{},this.cliBin=this.options.cliBin??"claude"}async start(){await ib(this.tasksDir,{recursive:!0}),this.server=nb((e,t)=>{this.handleRequest(e,t).catch(s=>{ee.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),ee.info("Code task manager started",{port:this.port})}async scanOrphans(){let e;try{e=await ab(this.tasksDir)}catch{return}let t=e.filter(i=>i.endsWith(".meta.json")),s=0,r=0;for(let i of t)try{let o=await Yr(`${this.tasksDir}/${i}`,"utf-8"),a=JSON.parse(o);this.tasks.set(a.id,a),a.status==="running"&&a.pid&&(this.isProcessAlive(a.pid)?(this.pollOrphan(a.id,a.pid),r++):(a.status="orphaned",a.completedAt=new Date().toISOString(),await this.writeMeta(a),this.fireCompletion(a),s++))}catch(o){ee.warn("Failed to read orphan task file",{file:i,error:String(o)})}(s>0||r>0)&&ee.info("Orphan scan complete",{orphaned:s,recovered:r,total:t.length})}async stop(){for(let[,t]of this.orphanPollers)clearInterval(t);this.orphanPollers.clear();for(let t of this.reapTimers)clearTimeout(t);this.reapTimers.clear();let e=[...this.tasks.values()].filter(t=>t.status==="running"&&t.pid);if(e.length>0){ee.info("Sending SIGTERM to running code tasks",{count:e.length});for(let t of e)this.killProcess(t.pid,"SIGTERM");await this.sleep(af);for(let t of e)t.pid&&this.isProcessAlive(t.pid)&&(ee.warn("Code task did not exit after SIGTERM, sending SIGKILL",{id:t.id,pid:t.pid}),this.killProcess(t.pid,"SIGKILL"))}this.server&&(this.server.close(),this.server=null),ee.info("Code task manager stopped",{killed:e.length})}async reapStale(){let e=this.options.maxLifetimeMs??288e5,t=this.options.staleGraceMs??1800*1e3,s=Date.now(),r=0,i=0;for(let o of this.tasks.values()){if(o.status!=="running"||!o.pid)continue;let a=s-new Date(o.startedAt).getTime();if(a<e)continue;if(await this.isFileRecentlyModified(o.stderrPath,t)){ee.info("Stale code task spared \u2014 stderr still active",{id:o.id,pid:o.pid,ageHours:(a/36e5).toFixed(1)}),i++;continue}ee.warn("Reaping stale code task",{id:o.id,pid:o.pid,ageHours:(a/36e5).toFixed(1)}),this.killProcess(o.pid,"SIGTERM"),o.status="orphaned";let c=setTimeout(()=>{this.reapTimers.delete(c),o.pid&&this.isProcessAlive(o.pid)&&(ee.warn("Stale code task did not exit after SIGTERM, sending SIGKILL",{id:o.id,pid:o.pid}),this.killProcess(o.pid,"SIGKILL"))},af);this.reapTimers.add(c),r++}return(r>0||i>0)&&ee.info("Stale reap complete",{reaped:r,spared:i}),{reaped:r,spared:i}}async handleRequest(e,t){let s=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}if(e.method==="POST"&&s.pathname==="/tasks"){let a;try{a=JSON.parse(await this.readBody(e))}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON body"}));return}try{let l=await this.spawnTask(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:l.id,status:"running"}))}catch(l){let c=String(l instanceof Error?l.message:l),d=c.includes("concurrency")?429:400;t.writeHead(d,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:c}))}return}let i=s.pathname.match(/^\/tasks\/([a-f0-9-]+)\/respond$/);if(e.method==="POST"&&i){let a=i[1],l;try{l=JSON.parse(await this.readBody(e))}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Invalid JSON body"}));return}try{let c=await this.resumeTask(a,l.response,l.context);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({id:c.id,status:"running",resumedFrom:a}))}catch(c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:String(c instanceof Error?c.message:c)}))}return}let o=s.pathname.match(/^\/tasks\/([a-f0-9-]+)$/);if(e.method==="GET"&&o){let a=o[1],l=await this.taskStatus(a);if(!l){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Task not found"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(l));return}if(e.method==="GET"&&s.pathname==="/tasks"){let a=s.searchParams.get("agentId")??void 0,l=this.listTasks(a);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({tasks:l}));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}async spawnTask(e){if([...this.tasks.values()].filter(S=>S.status==="running").length>=this.maxConcurrent)throw new Error(`Max concurrency reached (${this.maxConcurrent} running). Wait for a task to finish or increase the limit.`);let s=ub(),r=`${this.tasksDir}/${s}.stdout.json`,i=`${this.tasksDir}/${s}.stderr.log`,o=`${this.tasksDir}/${s}.meta.json`,a=e.cwd,l=e.model??"",c=e.maxTurns??100,d=e.maxBudget??5,u=e.prompt;if(this.options?.prefetcher)try{let S=await this.options.prefetcher.getContext(e.prompt,e.context.agentId);S&&(u=S+`
373
376
 
374
377
  ---
375
378
 
376
379
  `+e.prompt)}catch(S){ee.warn(`Prefetch failed for task, proceeding without context: ${S}`)}let h=e.sessionId?u:u+`
377
380
 
378
381
  ---
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
- `)}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
- `)}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
- `)}let a="";try{a=(await Gr(e.stderrPath,"utf-8")).split(`
383
- `).slice(-Ba).join(`
384
- `).trim()}catch{a="(no stderr output)"}let l=t?.result?t.result.slice(-Xs):"";return[`[Code task ${e.status}] Task \`${e.id}\` exited with code ${e.exitCode??"unknown"}.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",l?`Result:
382
+ IMPORTANT: After completing implementation, you MUST run /quality-gate before reporting done. This includes test creation, lint, typecheck, and build verification. Do not claim completion without quality-gate passing.`,p=this.buildArgs({prompt:h,maxTurns:c,maxBudget:d,model:l,sessionId:e.sessionId}),m=rf(r,"w"),f=rf(i,"w"),y=rb(this.cliBin,p,{cwd:a,detached:!0,stdio:["ignore",m,f],env:process.env});y.on("exit",S=>this.handleExit(s,S)),y.on("error",S=>{ee.error("Code task process error",{id:s,error:String(S)}),this.handleExit(s,1)}),of(m),of(f);let w={id:s,prompt:e.prompt.slice(0,500),cwd:a,model:l,maxTurns:c,maxBudget:d,status:"running",exitCode:null,startedAt:new Date().toISOString(),completedAt:null,stdoutPath:r,stderrPath:i,metaPath:o,context:e.context,pid:y.pid??null,sessionId:e.sessionId??null,costUsd:0,numTurns:0,escalation:null,parentTaskId:e.parentTaskId??null};return this.tasks.set(s,w),await this.writeMeta(w),ee.info("Code task spawned",{id:s,cwd:a,model:l||"(default)",maxTurns:c,maxBudget:d,pid:y.pid,agentId:e.context.agentId,parentTaskId:e.parentTaskId??null}),w}buildArgs(e){let t=[];e.sessionId?t.push("--resume",e.sessionId,"-p",e.prompt):t.push("-p",e.prompt);for(let s of this.pluginDirs)t.push("--plugin-dir",s);return t.push("--output-format","json","--dangerously-skip-permissions"),t.push("--max-turns",String(e.maxTurns)),t.push("--max-budget-usd",String(e.maxBudget)),e.model&&t.push("--model",e.model),t}async resumeTask(e,t,s){let r=this.tasks.get(e);if(!r)throw new Error(`Task ${e} not found`);if(r.status!=="needs_input")throw new Error(`Task ${e} is ${r.status}, not needs_input`);if(!r.sessionId)throw new Error(`Task ${e} has no session ID for resume`);return r.status="running",this.spawnTask({prompt:t,cwd:r.cwd,model:r.model,maxTurns:r.maxTurns,maxBudget:r.maxBudget,sessionId:r.sessionId,context:s??r.context,parentTaskId:e})}async handleExit(e,t){let s=this.tasks.get(e);if(!s||s.status!=="running")return;s.exitCode=t??1,s.completedAt=new Date().toISOString();let r=null;try{let o=await Yr(s.stdoutPath,"utf-8");r=tf(o)}catch{}r&&(s.sessionId=r.sessionId,s.costUsd=r.costUsd,s.numTurns=r.numTurns);let i=r?sf(r.result):null;s.escalation=i,s.status=nf(s.exitCode,r,i),await this.writeMeta(s),this.fireCompletion(s,r)}fireCompletion(e,t){let s=new Date(e.startedAt).getTime(),i=(((e.completedAt?new Date(e.completedAt).getTime():Date.now())-s)/1e3).toFixed(1);(async()=>{if(e.status==="needs_input"&&e.escalation){let c=[`[Code task needs input] Task \`${e.id}\` is waiting for a decision.`,""];return e.escalation.status==="BLOCKED"?c.push(`**BLOCKED**: ${e.escalation.question||"No details provided."}`):c.push(`**Needs context**: ${e.escalation.question||"No details provided."}`),e.escalation.context&&c.push("",`Context: ${e.escalation.context}`),c.push("",`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",`To respond: \`code_respond({ id: "${e.id}", response: "your answer" })\``),c.join(`
383
+ `)}if(e.status==="needs_input"&&t?.subtype){let c=t.subtype==="error_max_turns"?`Hit max turns limit (${e.maxTurns})`:`Hit budget limit ($${e.maxBudget})`;return[`[Code task limit reached] Task \`${e.id}\` \u2014 ${c}.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"","The session can be resumed with additional budget/turns via `code_respond`.","",`Result (last ${Qs} chars):`,"```",(t.result||"(no output)").slice(-Qs),"```"].join(`
384
+ `)}if(e.status==="completed"){let c=t?.result||"(no output)";return[`[Code task completed] Task \`${e.id}\` finished successfully.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",`Result (last ${Qs} chars):`,"```",c.slice(-Qs),"```"].join(`
385
+ `)}let a="";try{a=(await Yr(e.stderrPath,"utf-8")).split(`
386
+ `).slice(-qa).join(`
387
+ `).trim()}catch{a="(no stderr output)"}let l=t?.result?t.result.slice(-Qs):"";return[`[Code task ${e.status}] Task \`${e.id}\` exited with code ${e.exitCode??"unknown"}.`,`Duration: ${i}s | Cost: $${e.costUsd.toFixed(2)} | Turns: ${e.numTurns}`,"",l?`Result:
385
388
  \`\`\`
386
389
  ${l}
387
390
  \`\`\`
388
- `:"",`Stderr (last ${Ba} lines):`,"```",a||"(empty)","```"].filter(Boolean).join(`
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
- `).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 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
- `),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
- `),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 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(`
391
+ `:"",`Stderr (last ${qa} lines):`,"```",a||"(empty)","```"].filter(Boolean).join(`
392
+ `)})().then(a=>{let l={id:`ct:${e.id}:done:${Date.now()}`,text:a,source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,codeTaskId:e.id}};ee.info("Code task completed, dispatching notification",{id:e.id,status:e.status,exitCode:e.exitCode,costUsd:e.costUsd,numTurns:e.numTurns,durationSec:i,agentId:e.context.agentId,hasEscalation:!!e.escalation}),this.onComplete(l),this.options?.knowledgeExtractor&&e.status==="completed"&&t&&this.options.knowledgeExtractor.extract(e.context.agentId,t).then(c=>{c>0&&ee.info(`Extracted ${c} code insights from task ${e.id}`)}).catch(c=>{ee.warn(`Knowledge extraction failed for task ${e.id}: ${c}`)})}).catch(a=>{ee.error("Failed to fire completion notification",{id:e.id,error:String(a)})})}async taskStatus(e){let t=this.tasks.get(e);if(!t)return null;let s="";try{s=(await Yr(t.stderrPath,"utf-8")).split(`
393
+ `).slice(-qa).join(`
394
+ `).trim()}catch{}return{id:t.id,status:t.status,exitCode:t.exitCode,startedAt:t.startedAt,completedAt:t.completedAt,cwd:t.cwd,model:t.model,costUsd:t.costUsd,numTurns:t.numTurns,sessionId:t.sessionId,escalation:t.escalation,parentTaskId:t.parentTaskId,stderrTail:s}}listTasks(e){let t=[];for(let s of this.tasks.values())e&&s.context.agentId!==e||t.push({id:s.id,status:s.status,exitCode:s.exitCode,startedAt:s.startedAt,completedAt:s.completedAt,costUsd:s.costUsd,numTurns:s.numTurns,cwd:s.cwd,prompt:s.prompt});return t}async sweep(e){let t=Date.now()-e,s=0,r=0,i=[];for(let[o,a]of this.tasks)if(!(a.status==="running"||!a.completedAt||new Date(a.completedAt).getTime()>t)){for(let c of[a.metaPath,a.stdoutPath,a.stderrPath])try{let d=await cb(c);r+=d.size,await lb(c)}catch(d){d.code!=="ENOENT"&&i.push(`Failed to delete ${c}: ${String(d)}`)}this.tasks.delete(o),s++}return{component:"code-task-manager",pruned:s,retried:0,bytesFreed:r,errors:i}}async writeMeta(e){try{await ob(e.metaPath,JSON.stringify(e,null,2),"utf-8")}catch(t){ee.error("Failed to write task metadata",{id:e.id,error:String(t)})}}isProcessAlive(e){try{return process.kill(e,0),!0}catch{return!1}}pollOrphan(e,t){let s=setInterval(()=>{if(!this.isProcessAlive(t)){clearInterval(s),this.orphanPollers.delete(e);let r=this.tasks.get(e);r&&r.status==="running"&&(r.status="orphaned",r.completedAt=new Date().toISOString(),this.writeMeta(r).then(()=>this.fireCompletion(r)))}},5e3);this.orphanPollers.set(e,s)}killProcess(e,t){try{process.kill(e,t)}catch(s){s.code!=="ESRCH"&&ee.warn("Failed to send signal to process",{pid:e,signal:t,error:String(s)})}}async isFileRecentlyModified(e,t){try{let s=await db(e,"r"),r=await s.stat();return await s.close(),Date.now()-r.mtimeMs<t}catch{return!1}}sleep(e){return new Promise(t=>setTimeout(t,e))}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();import{createServer as hb}from"node:http";import{randomUUID as fb}from"node:crypto";var re=k("meeting-monitor"),pb=1e4,mb=15e3,gb=2,yb=new Set(["done","fatal","call_ended","media_expired","recording_permission_denied"]),zr=class{port;webhookSecret;onUpdate;server=null;sessions=new Map;sessionsByBotId=new Map;constructor(e,t,s){this.port=e,this.webhookSecret=t,this.onUpdate=s}async start(){this.server=hb((e,t)=>{this.handleRequest(e,t).catch(s=>{re.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),re.info("Meeting monitor started",{port:this.port}),this.webhookSecret||re.error("Webhook verification disabled \u2014 RECALL_WEBHOOK_SECRET not set. All webhook requests will be rejected.")}stop(){for(let e of this.sessions.values())e.pollTimer&&(clearInterval(e.pollTimer),e.pollTimer=null);this.server&&(this.server.close(),this.server=null),re.info("Meeting monitor stopped")}async handleRequest(e,t){let s=new URL(e.url??"/",`http://127.0.0.1:${this.port}`);if(e.method==="POST"&&s.pathname==="/meetings/start"){let i=await this.readBody(e),o=JSON.parse(i),a=this.createSession(o);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({sessionId:a.id}));return}let r=s.pathname.match(/^\/meetings\/([a-f0-9-]+)\/stop$/);if(e.method==="POST"&&r){let i=r[1],o=this.sessions.get(i);if(!o){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Session not found"}));return}o.pollTimer&&(clearInterval(o.pollTimer),o.pollTimer=null),o.status="ended",o.endedAt=Date.now(),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({status:"stopped"}));return}if(e.method==="POST"&&s.pathname.startsWith("/webhook/transcript")){if(!this.webhookSecret){t.writeHead(403,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Webhook verification not configured"}));return}if(s.pathname!==`/webhook/transcript/${this.webhookSecret}`){t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}));return}let i=await this.readBody(e);this.handleTranscriptWebhook(i),t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0}));return}if(e.method==="GET"&&s.pathname==="/meetings"){let i=[];for(let o of this.sessions.values())i.push({id:o.id,botId:o.botId,botName:o.botName,meetingUrl:o.meetingUrl,status:o.status,pollCount:o.pollCount,lastSegmentIndex:o.lastSegmentIndex,pendingSegments:o.pendingSegments.length});t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify(i));return}t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}handleTranscriptWebhook(e){try{let t=JSON.parse(e),s=t.event,r=t.data?.bot?.id;if(!r){re.warn("Webhook missing bot ID",{event:s});return}let i=this.sessionsByBotId.get(r);if(!i){re.warn("Webhook for unknown bot",{botId:r,event:s});return}let o=this.sessions.get(i);if(!o||o.status!=="monitoring")return;let a=t.data?.data;if(!a)return;let l=a.participant?.id??0,c=a.participant?.name??"Unknown",d=Array.isArray(a.words)?a.words.map(u=>u.text).join(" "):"";if(!d)return;o.idlePollCount=0,s==="transcript.partial_data"?o.activePartials.set(l,{speaker:c,text:d}):s==="transcript.data"&&(o.pendingSegments.push({speaker:c,text:d}),o.activePartials.delete(l),o.lastSegmentIndex++),re.debug("Webhook transcript",{sessionId:i,botId:r,event:s,speaker:c,wordCount:d.split(" ").length})}catch(t){re.error("Webhook parse error",{error:String(t)})}}createSession(e){let t=fb(),s={id:t,botId:e.botId,botName:e.botName,meetingUrl:e.meetingUrl,apiKey:e.apiKey,region:e.region,context:e.context,lastSegmentIndex:0,pendingSegments:[],activePartials:new Map,lastDispatchTime:Date.now(),idlePollCount:0,pollTimer:null,pollCount:0,status:"monitoring",endedAt:null};return this.sessions.set(t,s),this.sessionsByBotId.set(e.botId,t),s.pollTimer=setInterval(()=>{this.pollSession(t).catch(r=>{re.error("Poll session error",{sessionId:t,botId:s.botId,error:String(r)})})},pb),re.info("Meeting session created",{sessionId:t,botId:e.botId,botName:e.botName,meetingUrl:e.meetingUrl,agentId:e.context.agentId}),s}async pollSession(e){let t=this.sessions.get(e);if(!t||t.status!=="monitoring")return;t.pollCount++;let s=t.pendingSegments.length>0||t.activePartials.size>0;(Date.now()-t.lastDispatchTime>=mb&&s||t.idlePollCount>=gb&&s)&&this.dispatchBatch(t),t.pollCount%3===0&&await this.checkBotStatus(t)}async checkBotStatus(e){try{let t=`https://${e.region}.recall.ai/api/v1/bot/${e.botId}/`,s=await fetch(t,{headers:{Authorization:`Token ${e.apiKey}`},signal:AbortSignal.timeout(15e3)});if(!s.ok){re.warn("Bot status check failed",{sessionId:e.id,botId:e.botId,status:s.status});return}let r=await s.json(),i=r.status_changes;if(Array.isArray(i)&&i.length>0){let o=i[i.length-1].code;if(yb.has(o)){re.info("Meeting reached terminal status",{sessionId:e.id,botId:e.botId,statusCode:o});let a=await this.fetchFullTranscript(e,r);this.dispatchEnd(e,a);return}}}catch(t){re.error("Bot status check error",{sessionId:e.id,botId:e.botId,error:String(t)})}}async fetchFullTranscript(e,t){let i=(Array.isArray(t.recordings)?t.recordings:[])[0]?.media_shortcuts?.transcript?.data?.download_url;if(!i)return re.warn("No transcript download URL available",{sessionId:e.id,botId:e.botId}),[...e.pendingSegments];try{let o=await fetch(i,{signal:AbortSignal.timeout(3e4)});if(!o.ok)return re.warn("Transcript download failed",{sessionId:e.id,status:o.status}),[...e.pendingSegments];let a=await o.json();return(Array.isArray(a)?a:Array.isArray(a.results)?a.results:[]).map(c=>({speaker:c.speaker??c.participant?.name??"Unknown",text:Array.isArray(c.words)?c.words.map(d=>d.text).join(" "):typeof c.text=="string"?c.text:""}))}catch(o){return re.error("Transcript download error",{sessionId:e.id,error:String(o)}),[...e.pendingSegments]}}dispatchBatch(e){let t=e.pendingSegments.splice(0,e.pendingSegments.length);for(let r of e.activePartials.values())t.push({speaker:r.speaker,text:`${r.text} [still speaking...]`});if(e.activePartials.clear(),e.lastDispatchTime=Date.now(),t.length===0)return;let s={id:`meeting:${e.botId}:${Date.now()}`,text:[`[Meeting transcript update \u2014 ${e.botName}]`,`Bot ID: ${e.botId}`,"","New transcript:",...t.map(r=>`[${r.speaker}]: ${r.text}`),"","---",`You are participating in this meeting. Use recall_send_chat with bot_id "${e.botId}" if you have relevant input. Otherwise respond "No response needed."`].join(`
395
+ `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,meetingBotId:e.botId}};re.info("Dispatching transcript batch",{sessionId:e.id,botId:e.botId,segmentCount:t.length}),this.onUpdate(s)}dispatchEnd(e,t){let s={id:`meeting:${e.botId}:${Date.now()}`,text:[`[Meeting ended \u2014 ${e.botName}]`,`Bot ID: ${e.botId}`,"","Full transcript:",...t.map(r=>`[${r.speaker}]: ${r.text}`),"","---","Meeting has ended. Produce a summary: key decisions made, action items with owners, and open questions."].join(`
396
+ `),source:{kind:e.context.channelKind||"internal",id:e.context.channelId,label:e.context.channelLabel,adapterId:e.context.adapterId},sender:"system",threadId:e.context.threadId,timestamp:new Date,meta:{slackTs:e.context.slackTs,slackThreadTs:e.context.slackThreadTs,meetingBotId:e.botId}};re.info("Dispatching meeting end",{sessionId:e.id,botId:e.botId,totalSegments:t.length}),this.onUpdate(s),e.pollTimer&&(clearInterval(e.pollTimer),e.pollTimer=null),e.status="ended",e.endedAt=Date.now()}sweep(e){let t=Date.now()-e,s=0;for(let[r,i]of this.sessions)i.endedAt!==null&&(i.endedAt>t||(i.pollTimer&&(clearInterval(i.pollTimer),i.pollTimer=null),this.sessionsByBotId.delete(i.botId),this.sessions.delete(r),s++));return{component:"meeting-monitor",pruned:s,retried:0,bytesFreed:0,errors:[]}}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();var Qr=k("retry-queue"),Xr=class{entries=[];config;constructor(e){this.config=e}enqueue(e,t){this.entries.push({result:e,adapter:t,attempts:0,nextRetryAt:Date.now()+this.config.baseDelayMs,createdAt:Date.now()}),Qr.info("Delivery queued for retry",{agentId:e.agentId,adapterId:t.id,queueSize:this.entries.length})}async processRetries(){let e=Date.now(),t={pending:0,retried:0,dropped:0,errors:[]},s=[];for(let r of this.entries){if(r.nextRetryAt>e){s.push(r),t.pending++;continue}r.attempts++;try{await r.adapter.deliver(r.result),t.retried++,Qr.info("Retry delivery succeeded",{agentId:r.result.agentId,adapterId:r.adapter.id,attempt:r.attempts})}catch(i){if(r.attempts>=this.config.maxAttempts){t.dropped++;let o=`Dropped after ${r.attempts} attempts: ${String(i)}`;t.errors.push(o),Qr.error("Retry delivery exhausted",{agentId:r.result.agentId,adapterId:r.adapter.id,attempts:r.attempts,error:String(i)})}else r.nextRetryAt=e+this.config.baseDelayMs*Math.pow(2,r.attempts),s.push(r),t.pending++,Qr.warn("Retry delivery failed, will retry",{agentId:r.result.agentId,adapterId:r.adapter.id,attempt:r.attempts,nextRetryAt:new Date(r.nextRetryAt).toISOString(),error:String(i)})}}return this.entries=s,t}get size(){return this.entries.length}};M();var Ge=k("sweeper"),Zr=class n{config;targets;taskClient;taskId;timer=null;sweepCount=0;gatewayCycleCounter=0;memoryCycleCounter=0;memorySweepEvery;lastDreamAt=0;static GATEWAY_SWEEP_EVERY=12;constructor(e,t,s){this.config=e,this.targets=t,this.taskClient=s;let r=e.memorySweepIntervalHours??6;this.memorySweepEvery=Math.round(r*36e5/e.intervalMs)}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>{Ge.error("Sweep cycle failed",{error:String(e)})})},this.config.intervalMs),Ge.info("Sweeper started",{intervalMs:this.config.intervalMs}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),Ge.info("Sweeper stopped")}async sweep(){let e=Date.now();this.sweepCount++,this.gatewayCycleCounter++;let t=[];try{t.push(this.targets.dispatcher.sweep(this.config.threadTtlMs))}catch(d){t.push({component:"dispatcher",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}for(let d of this.targets.slackAdapters)try{t.push(d.sweep(this.config.threadTtlMs))}catch(u){t.push({component:`slack-adapter:${d.id}`,pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}if(this.targets.taskLedger)try{t.push(this.targets.taskLedger.sweep(this.config.threadTtlMs))}catch(d){t.push({component:"task-ledger",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}try{t.push(await this.targets.bgTaskManager.sweep(this.config.taskFileTtlMs))}catch(d){t.push({component:"bg-task-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.codeTaskManager){try{t.push(await this.targets.codeTaskManager.sweep(this.config.taskFileTtlMs))}catch(d){t.push({component:"code-task-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}try{let{reaped:d,spared:u}=await this.targets.codeTaskManager.reapStale();(d>0||u>0)&&t.push({component:"code-task-reaper",pruned:d,retried:0,bytesFreed:0,errors:u>0?[`${u} task(s) spared \u2014 still active past TTL`]:[]})}catch(d){t.push({component:"code-task-reaper",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}}if(this.targets.meetingMonitor)try{t.push(this.targets.meetingMonitor.sweep(this.config.meetingSessionTtlMs))}catch(d){t.push({component:"meeting-monitor",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.gatewayCycleCounter>=n.GATEWAY_SWEEP_EVERY){this.gatewayCycleCounter=0;for(let d of this.targets.slackGateways)try{t.push(d.sweep())}catch(u){t.push({component:"slack-gateway",pruned:0,retried:0,bytesFreed:0,errors:[String(u)]})}}try{t.push(this.targets.agentManager.sweep())}catch(d){t.push({component:"agent-manager",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.retryQueue)try{let d=await this.targets.retryQueue.processRetries();t.push({component:"retry-queue",pruned:d.dropped,retried:d.retried,bytesFreed:0,errors:d.errors})}catch(d){t.push({component:"retry-queue",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}if(this.targets.memoryLifecycle&&(this.memoryCycleCounter++,this.memoryCycleCounter>=this.memorySweepEvery)){this.memoryCycleCounter=0;try{t.push(await this.targets.memoryLifecycle.sweep())}catch(d){t.push({component:"memory-lifecycle",pruned:0,retried:0,bytesFreed:0,errors:[String(d)]})}}if(this.targets.memoryLifecycle&&this.config.dreamConfig?.enabled){let d=this.config.dreamConfig,u=d.cooldownMinutes*60*1e3,h=Date.now(),p=h-this.lastDreamAt>u,m=this.memoryCycleCounter===0,f=!1;if(p&&!m){let y=d.idleThresholdMinutes*60*1e3,w=this.targets.agentManager.getAllStates();f=w.length>0&&w.every(S=>S.status==="idle"&&h-S.lastActivity.getTime()>y)}if(p&&(m||f)){let y=m?"post-sweep":"idle";Ge.info("autoDream triggered",{trigger:y});try{let w=await this.targets.memoryLifecycle.dream();this.lastDreamAt=Date.now(),(w.merged+w.contradictions+w.promoted>0||w.errors.length>0)&&t.push({component:"autodream",pruned:w.merged+w.contradictions,retried:w.promoted,bytesFreed:0,errors:w.errors})}catch(w){t.push({component:"autodream",pruned:0,retried:0,bytesFreed:0,errors:[String(w)]})}}}let s=Date.now()-e,r=t.reduce((d,u)=>d+u.pruned,0),i=t.reduce((d,u)=>d+u.retried,0),o=t.reduce((d,u)=>d+u.bytesFreed,0),a=t.flatMap(d=>d.errors),l=r===0&&i===0&&o===0&&a.length===0;return(l?Ge.debug.bind(Ge):Ge.info.bind(Ge))("Sweep cycle complete",{cycle:this.sweepCount,durationMs:s,pruned:r,retried:i,bytesFreed:o,errors:a.length,components:t.map(d=>`${d.component}:${d.pruned}p/${d.retried}r`).join(" ")}),this.taskClient?.isConfigured&&!l&&await this.reportToTaskLedger(s,r,i,o,a),t}async reportToTaskLedger(e,t,s,r,i){try{if(!this.taskId){let a=await this.taskClient.createTask({name:"[Sweeper] Periodic maintenance",type:"AGENT",description:"Long-running system health task. Each comment is a sweep cycle report."});a&&(this.taskId=a._id)}if(!this.taskId)return;let o=[`**Sweep #${this.sweepCount}** (${e}ms)`,`Pruned: ${t} | Retried: ${s} | Freed: ${this.formatBytes(r)}`,i.length>0?`Errors: ${i.join(", ")}`:null].filter(Boolean).join(`
397
+ `);await this.taskClient.addComment(this.taskId,o),i.length>0&&await this.taskClient.updateTask(this.taskId,{state:"NEEDS_ATTENTION"})}catch(o){Ge.warn("Failed to report to task ledger",{error:String(o)})}}formatBytes(e){if(e===0)return"0 B";let t=["B","KB","MB","GB"],s=Math.floor(Math.log(e)/Math.log(1024));return`${(e/Math.pow(1024,s)).toFixed(1)} ${t[s]}`}};M();import{readdirSync as lf,readFileSync as wb,rmSync as Sb,statSync as kb,existsSync as ei}from"node:fs";import{resolve as Fa,join as df,sep as cf}from"node:path";var Xs=k("retention"),ti=class{config;deps;timer=null;constructor(e,t){this.config=e,this.deps=t}start(){this.timer||(this.timer=setInterval(()=>{this.sweep().catch(e=>Xs.error("Retention sweep failed",{error:String(e)}))},this.config.intervalMs),Xs.info("Retention sweeper started",{intervalMs:this.config.intervalMs,enabled:this.config.enabled,rules:Object.keys(this.config.paths).length}))}stop(){this.timer&&(clearInterval(this.timer),this.timer=null),Xs.info("Retention sweeper stopped")}async sweep(){let e=new Date,t=[],s=[],r=[];for(let[o,a]of Object.entries(this.config.paths))if(a.days!==0)for(let l of bb(this.deps.hiveHome,o))try{_b(l,o,a.days,e,t)}catch(c){r.push({path:l,error:String(c)})}if(this.config.enabled)for(let o of t)try{Sb(o.path,{recursive:!0,force:!0}),s.push(o)}catch(a){r.push({path:o.path,error:String(a)})}let i={sweptAt:e,dryRun:!this.config.enabled,candidates:t,deleted:s,errors:r};try{await this.deps.report(Tb(i))}catch(o){Xs.warn("Retention report delivery failed",{error:String(o)})}return i}};function bb(n,e){let t=e.split("/"),s=t.indexOf("*");if(s===-1){let a=Fa(n,e);return ei(a)?[a]:[]}if(t.indexOf("*",s+1)!==-1)throw new Error(`Retention rules support at most one '*' segment: ${e}`);let r=t.slice(0,s).join(cf),i=t.slice(s+1).join(cf),o=Fa(n,r);return ei(o)?lf(o,{withFileTypes:!0}).filter(a=>a.isDirectory()).map(a=>Fa(o,a.name,i)).filter(a=>ei(a)):[]}function _b(n,e,t,s,r){let i=vb(n)??t;if(i===0)return;let o=s.getTime()-i*864e5,a=lf(n,{withFileTypes:!0});for(let l of a){if(l.name===".retention-days")continue;let c=df(n,l.name),d;try{d=kb(c)}catch{continue}d.mtimeMs<=o&&r.push({path:c,rule:e,days:i,mtime:d.mtime,ageDays:(s.getTime()-d.mtimeMs)/864e5})}}function vb(n){let e=df(n,".retention-days");if(!ei(e))return null;let t=wb(e,"utf-8").trim(),s=Number(t);return!Number.isFinite(s)||s<0||!Number.isInteger(s)?(Xs.warn("Invalid .retention-days override \u2014 ignoring",{path:e,raw:t}),null):s}function Tb(n){let e=n.dryRun?"would delete":"deleted",t=[`*Retention sweep* (${n.dryRun?"dry-run":"enforced"}) @ ${n.sweptAt.toISOString()}`,`${n.candidates.length} candidates \xB7 ${e} ${n.dryRun?n.candidates.length:n.deleted.length} \xB7 ${n.errors.length} errors`],s=n.candidates.slice(0,10);if(s.length){t.push("```");for(let r of s)t.push(`${r.path} (age ${r.ageDays.toFixed(1)}d, rule ${r.rule}@${r.days}d)`);n.candidates.length>s.length&&t.push(`\u2026 and ${n.candidates.length-s.length} more`),t.push("```")}return n.errors.length&&t.push(`Errors: ${n.errors.slice(0,3).map(r=>`${r.path}: ${r.error}`).join(" | ")}`),t.join(`
398
+ `)}Vs();M();var Ib=k("memory-store"),si=class{db;collection;constructor(e){this.db=e}async init(){this.collection=this.db.collection("agent_memory"),await this.collection.createIndex({agentId:1,tier:1}),await this.collection.createIndex({agentId:1,topic:1}),await this.collection.createIndex({agentId:1,updatedAt:1}),await this.collection.createIndex({agentId:1,type:1}),await this.collection.createIndex({agentId:1,purged:1,purgedAt:1}),Ib.info("Memory store initialized",{db:this.db.databaseName})}getCollection(){return this.collection}async save(e,t,s,r,i){let o=new Date,a={agentId:e,content:t.content,type:t.type,topic:t.topic,importance:t.importance,tier:"hot",createdAt:o,updatedAt:o,lastAccessedAt:o,accessCount:0,sourceChannel:r,sourceThread:i,pinned:!1,summarized:!1,qdrantPointId:s},l=await this.collection.insertOne(a);return a._id=l.insertedId,a}async getById(e){return this.collection.findOne({_id:e,purged:{$ne:!0}})}async update(e,t,s,r){let i={content:t,updatedAt:new Date};return s&&(i.importance=s),r&&(i.qdrantPointId=r),await this.collection.findOneAndUpdate({_id:e},{$set:i},{returnDocument:"after"})}async pin(e){return(await this.collection.updateOne({_id:e},{$set:{pinned:!0,tier:"hot"}})).modifiedCount>0}async unpin(e){return(await this.collection.updateOne({_id:e},{$set:{pinned:!1}})).modifiedCount>0}async delete(e){return this.collection.findOneAndDelete({_id:e})}async touchAccess(e){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{lastAccessedAt:new Date},$inc:{accessCount:1}})}async getHotTier(e){let t={critical:4,high:3,medium:2,low:1};return(await this.collection.find({agentId:e,tier:"hot",purged:{$ne:!0},supersededBy:{$exists:!1}}).toArray()).sort((r,i)=>{if(r.pinned!==i.pinned)return r.pinned?-1:1;let o=(t[i.importance]??0)-(t[r.importance]??0);return o!==0?o:i.updatedAt.getTime()-r.updatedAt.getTime()})}async getHotTierWithStats(e){let t=await this.getHotTier(e),s=Date.now();return t.map(r=>({...r,ageDays:Math.floor((s-r.createdAt.getTime())/(1e3*60*60*24)),daysSinceAccess:Math.floor((s-r.lastAccessedAt.getTime())/(1e3*60*60*24))}))}async getByIds(e){return e.length===0?[]:this.collection.find({_id:{$in:e},purged:{$ne:!0}}).toArray()}async countNonHot(e){return this.collection.countDocuments({agentId:e,tier:{$ne:"hot"},purged:{$ne:!0}})}async getAllNonPinned(e){return this.collection.find({agentId:e,pinned:!1,purged:{$ne:!0},supersededBy:{$exists:!1}}).toArray()}async getByTiersForAgent(e,t){return this.collection.find({agentId:e,tier:{$in:t},purged:{$ne:!0},summarized:!1,supersededBy:{$exists:!1}}).toArray()}async getFactsAndDecisionsByTopic(e){let t=await this.collection.find({agentId:e,type:{$in:["fact","decision"]},purged:{$ne:!0},supersededBy:{$exists:!1},needsReview:{$ne:!0}}).toArray(),s=new Map;for(let r of t){let i=s.get(r.topic)??[];i.push(r),s.set(r.topic,i)}return s}async getInteractionsByTopic(e){let t=await this.collection.find({agentId:e,type:"interaction",tier:{$in:["hot","warm"]},purged:{$ne:!0},supersededBy:{$exists:!1},summarized:!1}).toArray(),s=new Map;for(let r of t){let i=s.get(r.topic)??[];i.push(r),s.set(r.topic,i)}return s}async markSuperseded(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{supersededBy:t,tier:"cold"}})}async flagForReview(e){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{needsReview:!0}})}async getAllForAgent(e){return this.collection.find({agentId:e}).toArray()}async setTier(e,t){await this.collection.updateOne({_id:e},{$set:{tier:t}})}async setTierBulk(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{tier:t}})}async getColdByTopic(e,t){return this.collection.find({agentId:e,tier:"cold",topic:t,summarized:!1,purged:{$ne:!0}}).sort({createdAt:1}).toArray()}async getColdTopics(e){return await this.collection.distinct("topic",{agentId:e,tier:"cold",summarized:!1,purged:{$ne:!0}})}async markSummarized(e,t){e.length!==0&&await this.collection.updateMany({_id:{$in:e}},{$set:{summarized:!0,summaryGroup:t,summarizedAt:new Date}})}async deleteSummarizedOlderThan(e,t){return(await this.collection.deleteMany({agentId:e,summarized:!0,summarizedAt:{$lt:t}})).deletedCount}async purge(e,t){if(!(t.topic!==void 0||t.type!==void 0||t.importance!==void 0||t.tier!==void 0||t.olderThan!==void 0))throw new Error("purge() requires at least one filter");let r={agentId:e,pinned:!1,purged:{$ne:!0}};return t.topic!==void 0&&(r.topic=t.topic),t.type!==void 0&&(r.type=t.type),t.importance!==void 0&&(r.importance=t.importance),t.tier!==void 0&&(r.tier=t.tier),t.olderThan!==void 0&&(r.updatedAt={$lt:t.olderThan}),(await this.collection.updateMany(r,{$set:{purged:!0,purgedAt:new Date}})).modifiedCount}async deletePurgedOlderThan(e,t){let s=await this.collection.find({agentId:e,purged:!0,purgedAt:{$lt:t}}).toArray();if(s.length===0)return[];let r=s.map(i=>i._id);return await this.collection.deleteMany({_id:{$in:r}}),s}async getAgentIds(){return this.collection.distinct("agentId")}async close(){}};M();Er();import{QdrantClient as Ab}from"@qdrant/js-client-rest";var uf=k("memory-embedder"),Ct="agent_memory",ni=class{qdrantUrl;ollamaUrl;qdrant=null;collectionReady=!1;constructor(e=process.env.QDRANT_URL??"http://localhost:6333",t=process.env.OLLAMA_URL??"http://localhost:11434"){this.qdrantUrl=e,this.ollamaUrl=t}getClient(){return this.qdrant||(this.qdrant=new Ab({url:this.qdrantUrl})),this.qdrant}async embed(e){return He(this.ollamaUrl,e)}async ensureCollection(){if(this.collectionReady)return;let e=this.getClient(),{collections:t}=await e.getCollections();if(!t.some(r=>r.name===Ct)){let r=await this.embed("test");await e.createCollection(Ct,{vectors:{size:r.length,distance:"Cosine"}}),uf.info("Created Qdrant collection",{collection:Ct,vectorSize:r.length})}this.collectionReady=!0}async upsert(e,t,s){await this.ensureCollection();let r=await this.embed(t);await this.getClient().upsert(Ct,{points:[{id:e,vector:r,payload:s}]})}async remove(e){await this.ensureCollection(),await this.getClient().delete(Ct,{points:[e]})}async search(e,t,s){await this.ensureCollection();let r=await this.embed(e),i=s?.limit??10,o=[{key:"agentId",match:{value:t}}];return s?.type&&o.push({key:"type",match:{value:s.type}}),s?.topic&&o.push({key:"topic",match:{value:s.topic}}),s?.tier&&o.push({key:"tier",match:{value:s.tier}}),s?.importance&&o.push({key:"importance",match:{value:s.importance}}),(await this.getClient().search(Ct,{vector:r,limit:i,with_payload:!0,filter:{must:o}})).map(l=>({mongoId:l.payload?.mongoId,score:l.score}))}async findSimilar(e,t,s,r=10){await this.ensureCollection();let i;try{i=await this.getClient().query(Ct,{query:{recommend:{positive:[e]}},filter:{must:[{key:"agentId",match:{value:t}}]},limit:r,with_payload:!0,score_threshold:s})}catch(o){if(String(o).includes("Not Found")||String(o).includes("does not exists"))return uf.warn("findSimilar skipped orphan point",{pointId:e,agentId:t}),[];throw o}return i.points.map(o=>({mongoId:o.payload?.mongoId,score:o.score??0,pointId:typeof o.id=="string"?o.id:String(o.id)}))}};M();import{ObjectId as Cb}from"mongodb";import{query as ri}from"@anthropic-ai/claude-agent-sdk";var hf={critical:1,high:.75,medium:.5,low:.25},ff={decision:1,fact:.8,preference:.8,summary:.6,task:.5,interaction:.3};var Me=k("memory-lifecycle"),ii=class{store;embedder;config;dreamConfig;getActiveAgentIds;constructor(e,t,s,r,i){this.store=e,this.embedder=t,this.config=s,this.dreamConfig=r,this.getActiveAgentIds=i}async filterActiveAgents(e){if(!this.getActiveAgentIds)return e;let t=await this.getActiveAgentIds(),s=e.filter(i=>t.has(i)),r=e.length-s.length;return r>0&&Me.debug("Skipped retired agents",{skipped:r,retiredIds:e.filter(i=>!t.has(i))}),s}computeScore(e,t){let s=hf[e.importance]??.5,r=ff[e.type]??.5,i=Date.now()-e.updatedAt.getTime(),o=this.config.recencyHalfLifeDays*24*60*60*1e3,a=Math.exp(-.693*i/o),l=t>0?Math.min(e.accessCount/t,1):e.accessCount>0?1:0;return s*.4+a*.3+l*.2+r*.1}estimateTokens(e){return Math.ceil(e.length/4)}async sweep(){let e=Date.now(),t=0,s=0,r=0,i=0,o=0,a=[];try{let c=await this.store.getAgentIds(),d=await this.filterActiveAgents(c);for(let u of d)try{let h=await this.sweepAgent(u);t+=h.promoted,s+=h.demoted,r+=h.summarized,i+=h.cleaned,o+=h.purged}catch(h){a.push(`${u}: ${h}`),Me.error("Memory lifecycle sweep failed for agent",{agentId:u,error:String(h)})}}catch(c){a.push(`global: ${c}`)}return t+s+r+i+o>0&&Me.info("Memory lifecycle sweep complete",{durationMs:Date.now()-e,promoted:t,demoted:s,summarized:r,cleaned:i,purged:o,errors:a.length}),{component:"memory-lifecycle",pruned:s+i+o,retried:t,bytesFreed:0,errors:a}}async sweepAgent(e){let t=0,s=0,r=await this.store.getAllNonPinned(e),i=0,o=0;if(r.length>0){let d=r.map(w=>w.accessCount).sort((w,S)=>w-S),u=d[Math.floor(d.length/2)]??0,h=r.map(w=>({record:w,score:this.computeScore(w,u)})),p=[];for(let{record:w,score:S}of h){let _;S>=this.config.hotThreshold?_="hot":S>=this.config.warmThreshold?_="warm":_="cold",_!==w.tier&&(p.push({id:w._id,newTier:_}),_==="hot"&&w.tier!=="hot"&&t++,_!=="hot"&&w.tier==="hot"&&s++)}for(let w of["hot","warm","cold"]){let S=p.filter(_=>_.newTier===w).map(_=>_.id);await this.store.setTierBulk(S,w)}let m=await this.store.getHotTier(e),f=0,y=[];for(let w of m){let S=this.estimateTokens(w.content);w.pinned||(f+=S,f>this.config.hotBudgetTokens&&y.push(w._id))}y.length>0&&(await this.store.setTierBulk(y,"warm"),s+=y.length);try{i=await this.summarizeCold(e)}catch(w){Me.warn("Cold summarization failed",{agentId:e,error:String(w)})}}let a=new Date(Date.now()-this.config.coldRetentionDays*24*60*60*1e3);o=await this.store.deleteSummarizedOlderThan(e,a);let l=new Date(Date.now()-this.config.purgeRetentionDays*24*60*60*1e3),c=0;try{let d=await this.store.deletePurgedOlderThan(e,l);if(c=d.length,d.length>0){let u=d.map(h=>h.qdrantPointId).filter(Boolean);for(let h of u)await this.embedder.remove(h);Me.info("Hard-deleted purged records",{agentId:e,count:d.length})}}catch(d){Me.warn("Purge hard-delete phase failed",{agentId:e,error:String(d)})}return{promoted:t,demoted:s,summarized:i,cleaned:o,purged:c}}async dream(){if(!this.dreamConfig?.enabled)return{merged:0,contradictions:0,promoted:0,flaggedForReview:0,errors:[]};let e=Date.now(),t=0,s=0,r=0,i=0,o=[];try{let l=await this.store.getAgentIds(),c=await this.filterActiveAgents(l);for(let d of c)try{let u=await this.mergeDuplicates(d);t+=u.merged;let h=await this.detectContradictions(d);s+=h.resolved,i+=h.flagged;let p=await this.promotePatterns(d);r+=p.promoted}catch(u){o.push(`${d}: ${u}`),Me.error("autoDream failed for agent",{agentId:d,error:String(u)})}}catch(l){o.push(`global: ${l}`)}return t+s+r+i>0&&Me.info("autoDream complete",{durationMs:Date.now()-e,merged:t,contradictions:s,promoted:r,flaggedForReview:i,errors:o.length}),{merged:t,contradictions:s,promoted:r,flaggedForReview:i,errors:o}}async mergeDuplicates(e){let t=this.dreamConfig,s=await this.store.getByTiersForAgent(e,["hot","warm"]);if(s.length<2)return{merged:0};let r=new Set,i=0,o=0;for(let a of s){if(o>=t.maxClustersPerRun)break;if(r.has(a.qdrantPointId))continue;let c=(await this.embedder.findSimilar(a.qdrantPointId,e,t.similarityThreshold,10)).filter(I=>!r.has(I.pointId));if(c.length===0)continue;r.add(a.qdrantPointId);for(let I of c)r.add(I.pointId);let d=c.map(I=>new Cb(I.mongoId)),u=await this.store.getByIds(d),h=[a,...u],m=["Merge the following duplicate or overlapping memories into a single consolidated record.","Preserve all unique details. Discard exact duplicates. Be concise.","",h.map(I=>`- [${I.type}/${I.importance}] ${I.content}`).join(`
396
399
  `)].join(`
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
- `),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(`
400
+ `),f=ri({prompt:m,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),y="";for await(let I of f){let N=I;if(N.type==="result"){let D=N;D.subtype==="success"&&D.result&&(y=D.result)}}if(!y)continue;let w=this.highestImportance(h),S=crypto.randomUUID(),_=await this.store.save(e,{content:y,type:a.type,topic:a.topic,importance:w},S);await this.embedder.upsert(S,y,{agentId:e,mongoId:_._id.toString(),type:a.type,topic:a.topic,tier:"hot",importance:w,createdAt:Math.floor(Date.now()/1e3)});let v=h.map(I=>I._id);await this.store.markSuperseded(v,_._id),i+=h.length,o++}return i>0&&Me.info("autoDream: duplicates merged",{agentId:e,merged:i,clusters:o}),{merged:i}}highestImportance(e){let t=["critical","high","medium","low"];for(let s of t)if(e.some(r=>r.importance===s))return s;return"medium"}async detectContradictions(e){let t=this.dreamConfig,s=await this.store.getFactsAndDecisionsByTopic(e),r=0,i=0,o=0,a=new Set;for(let[l,c]of s){if(o>=t.maxContradictionPairsPerRun)break;if(!(c.length<2)){for(let d=0;d<c.length-1;d++)if(!a.has(c[d]._id.toString())){for(let u=d+1;u<c.length&&!(o>=t.maxContradictionPairsPerRun);u++){if(a.has(c[u]._id.toString()))continue;let h=c[d],p=c[u],m=["Do these two memories contradict each other?","",`Memory A (${h.type}, created ${h.createdAt.toISOString()}):`,h.content,"",`Memory B (${p.type}, created ${p.createdAt.toISOString()}):`,p.content,"","Reply with exactly one of:",`- "NO" if they don't contradict`,'- "A_WINS" if Memory A is more current/accurate','- "B_WINS" if Memory B is more current/accurate',`- "UNCLEAR" if they contradict but you can't determine which is correct`].join(`
401
+ `),f=ri({prompt:m,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),y="";for await(let w of f){let S=w;if(S.type==="result"){let _=S;_.subtype==="success"&&_.result&&(y=_.result.trim().toUpperCase())}}o++,y.includes("A_WINS")?(await this.store.markSuperseded([p._id],h._id),a.add(p._id.toString()),r++):y.includes("B_WINS")?(await this.store.markSuperseded([h._id],p._id),a.add(h._id.toString()),r++):y.includes("UNCLEAR")&&(await this.store.flagForReview([h._id,p._id]),a.add(h._id.toString()),a.add(p._id.toString()),i+=2)}if(o>=t.maxContradictionPairsPerRun)break}}}return(r>0||i>0)&&Me.info("autoDream: contradictions processed",{agentId:e,resolved:r,flagged:i,pairsChecked:o}),{resolved:r,flagged:i}}async promotePatterns(e){let t=this.dreamConfig,s=await this.store.getInteractionsByTopic(e),r=0;for(let[i,o]of s){if(r>=t.maxPromotionsPerRun)break;let a=new Set(o.map(w=>w.sourceThread).filter(Boolean));if(a.size<t.patternMinCount)continue;let d=o.sort((w,S)=>S.createdAt.getTime()-w.createdAt.getTime()).slice(0,10).map(w=>`- [${w.importance}] ${w.content}`).join(`
399
402
  `),u=[`These ${o.length} interactions across ${a.size} conversations share topic "${i}".`,"Generate a single fact that captures the recurring pattern or insight.","Be concise \u2014 one to three sentences.","",d].join(`
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
- `),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 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)});
403
+ `),h=ri({prompt:u,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),p="";for await(let w of h){let S=w;if(S.type==="result"){let _=S;_.subtype==="success"&&_.result&&(p=_.result)}}if(!p)continue;let m=crypto.randomUUID(),f=await this.store.save(e,{content:p,type:"fact",topic:i,importance:"medium"},m);await this.embedder.upsert(m,p,{agentId:e,mongoId:f._id.toString(),type:"fact",topic:i,tier:"hot",importance:"medium",createdAt:Math.floor(Date.now()/1e3)});let y=o.map(w=>w._id);await this.store.markSuperseded(y,f._id),r++}return r>0&&Me.info("autoDream: patterns promoted",{agentId:e,promoted:r}),{promoted:r}}async summarizeCold(e){let t=await this.store.getColdTopics(e),s=0;for(let r of t){let i=await this.store.getColdByTopic(e,r);if(i.length<this.config.coldSummaryMinRecords)continue;let o=i.map(h=>`- [${h.type}/${h.importance}] ${h.content}`).join(`
404
+ `),a=[`Summarize the following memory entries for agent ${e} about topic "${r}".`,"Preserve key facts, decisions, and outcomes. Discard routine interactions.","Be concise \u2014 aim for 2-5 sentences.","",o].join(`
405
+ `),l=ri({prompt:a,options:{model:"claude-haiku-4-5-20251001",permissionMode:"bypassPermissions",allowDangerouslySkipPermissions:!0,maxTurns:1,maxBudgetUsd:this.dreamConfig?.maxBudgetUsd??.1,persistSession:!1}}),c="";for await(let h of l){let p=h;if(p.type==="result"){let m=p;m.subtype==="success"&&m.result&&(c=m.result)}}if(!c)continue;let d=crypto.randomUUID(),u=await this.store.save(e,{content:c,type:"summary",topic:r,importance:"medium"},d);await this.store.setTier(u._id,"warm"),await this.embedder.upsert(d,c,{agentId:e,mongoId:u._id.toString(),type:"summary",topic:r,tier:"warm",importance:"medium",createdAt:Math.floor(Date.now()/1e3)}),await this.store.markSummarized(i.map(h=>h._id),u._id),s+=i.length}return s}};M();import{createServer as Eb}from"node:http";var pf=k("admin-api"),oi=class{server;port;token;agentDefs;agentVersions;onReload;constructor(e,t,s,r,i){this.port=e,this.token=t,this.agentDefs=s,this.agentVersions=r,this.onReload=i,this.server=Eb((o,a)=>this.handleRequest(o,a))}async start(){return new Promise(e=>{this.server.listen(this.port,()=>{pf.info("Admin API started",{port:this.port}),e()})})}stop(){this.server.close()}async handleRequest(e,t){let s=e.headers.authorization;if(!s||s!==`Bearer ${this.token}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Unauthorized"}));return}let r=new URL(e.url??"/",`http://localhost:${this.port}`),i=r.pathname,o=e.method??"GET";try{if(i==="/admin/agents"&&o==="GET")return await this.listAgents(t);if(i==="/admin/agents"&&o==="POST")return await this.createAgent(e,t);let a=i.match(/^\/admin\/agents\/([^/]+)$/);if(a){let u=decodeURIComponent(a[1]);if(o==="GET")return await this.getAgent(u,t);if(o==="PATCH")return await this.updateAgent(u,e,t);if(o==="DELETE")return await this.deleteAgent(u,t)}let l=i.match(/^\/admin\/agents\/([^/]+)\/(enable|disable)$/);if(l&&o==="POST"){let u=decodeURIComponent(l[1]),h=l[2];return await this.toggleAgent(u,h,t)}let c=i.match(/^\/admin\/agents\/([^/]+)\/history$/);if(c&&o==="GET"){let u=decodeURIComponent(c[1]),h=parseInt(r.searchParams.get("limit")??"10",10);return await this.agentHistory(u,h,t)}let d=i.match(/^\/admin\/agents\/([^/]+)\/rollback$/);if(d&&o==="POST"){let u=decodeURIComponent(d[1]);return await this.rollbackAgent(u,e,t)}if(i==="/admin/servers"&&o==="GET")return await this.listServers(t);t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Not found"}))}catch(a){pf.error("Admin API error",{error:String(a),path:i,method:o}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({error:"Internal server error"}))}}async readBody(e){return new Promise((t,s)=>{let r=[];e.on("data",i=>r.push(i)),e.on("end",()=>{try{t(JSON.parse(Buffer.concat(r).toString()))}catch{s(new Error("Invalid JSON"))}}),e.on("error",s)})}json(e,t,s){e.writeHead(t,{"Content-Type":"application/json"}),e.end(JSON.stringify(s))}async saveVersion(e,t){let s=await this.agentDefs.findOne({_id:e});s&&await this.agentVersions.insertOne({agentId:e,snapshot:s,changedFields:t,createdAt:new Date})}async listAgents(e){let t=await this.agentDefs.find().toArray();this.json(e,200,t)}async getAgent(e,t){let s=await this.agentDefs.findOne({_id:e});if(!s)return this.json(t,404,{error:"Agent not found"});this.json(t,200,s)}async createAgent(e,t){let s=await this.readBody(e);if(!s._id||!s.name||!s.model)return this.json(t,400,{error:"Required: _id, name, model"});if(await this.agentDefs.findOne({_id:s._id}))return this.json(t,409,{error:"Agent already exists"});let i=new Date,o={_id:s._id,name:s.name,model:s.model,icon:s.icon??X.icon,channels:s.channels??[],passiveChannels:s.passiveChannels??X.passiveChannels,keywords:s.keywords??X.keywords,isDefault:s.isDefault??!1,coreServers:s.coreServers??[],delegateServers:s.delegateServers??[],delegatePrompts:s.delegatePrompts??X.delegatePrompts,plugins:s.plugins,metadata:s.metadata,soul:s.soul??"",systemPrompt:s.systemPrompt??"",schedule:s.schedule??X.schedule,subscribe:s.subscribe,budgetUsd:s.budgetUsd??X.budgetUsd,maxTurns:s.maxTurns??X.maxTurns,maxConcurrent:s.maxConcurrent??X.maxConcurrent,timeoutMs:s.timeoutMs??X.timeoutMs,disabled:s.disabled??!1,slackBot:s.slackBot,createdAt:i,updatedAt:i,updatedBy:"admin-api"};await this.agentDefs.insertOne(o),this.onReload(),this.json(t,201,o)}async updateAgent(e,t,s){let r=await this.readBody(t);if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found"});delete r._id,delete r.createdAt;let o=Object.keys(r);await this.saveVersion(e,o),await this.agentDefs.updateOne({_id:e},{$set:{...r,updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload();let a=await this.agentDefs.findOne({_id:e});this.json(s,200,a)}async deleteAgent(e,t){if(!await this.agentDefs.findOne({_id:e}))return this.json(t,404,{error:"Agent not found"});await this.saveVersion(e,["_deleted"]),await this.agentDefs.deleteOne({_id:e}),this.onReload(),this.json(t,200,{deleted:e})}async toggleAgent(e,t,s){if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found"});await this.saveVersion(e,["disabled"]),await this.agentDefs.updateOne({_id:e},{$set:{disabled:t==="disable",updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload(),this.json(s,200,{[t+"d"]:e})}async agentHistory(e,t,s){let r=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).limit(t).toArray();this.json(s,200,r)}async rollbackAgent(e,t,s){let i=(await this.readBody(t)).version_index??0;if(typeof i!="number"||i<0||!Number.isInteger(i))return this.json(s,400,{error:"version_index must be a non-negative integer"});let o=await this.agentVersions.find({agentId:e}).sort({createdAt:-1}).skip(i).limit(1).toArray();if(o.length===0)return this.json(s,404,{error:"No version found at that index"});if(!await this.agentDefs.findOne({_id:e}))return this.json(s,404,{error:"Agent not found \u2014 cannot rollback a deleted agent"});await this.saveVersion(e,["_rollback"]);let{_id:l,...c}=o[0].snapshot;await this.agentDefs.updateOne({_id:e},{$set:{...c,updatedAt:new Date,updatedBy:"admin-api"}}),this.onReload();let d=await this.agentDefs.findOne({_id:e});this.json(s,200,d)}async listServers(e){this.json(e,200,{message:"Server registry \u2014 use agent_definitions.coreServers/delegateServers fields"})}};M();var Et=k("activity-logger"),ai=class{db;collection;buffer=[];flushTimer=null;config;connected=!1;constructor(e,t){this.db=e,this.config=t}async connect(){if(!this.config.enabled){Et.info("Activity log disabled");return}this.collection=this.db.collection("activity_log"),await this.collection.createIndex({agentId:1,timestamp:-1}),await this.collection.createIndex({timestamp:1},{expireAfterSeconds:this.config.retentionDays*24*60*60}),this.connected=!0,this.flushTimer=setInterval(()=>{this.flush().catch(t=>Et.warn("Periodic flush failed",{error:String(t)}))},this.config.flushIntervalMs);let e=await this.collection.estimatedDocumentCount();Et.info("Activity log connected",{records:e,retentionDays:this.config.retentionDays})}record(e){!this.config.enabled||!this.connected||(this.buffer.push(e),this.buffer.length>=this.config.bufferSize&&this.flush().catch(t=>Et.warn("Buffer-full flush failed",{error:String(t)})))}async flush(){if(this.buffer.length===0)return;let e=this.buffer.splice(0);try{await this.collection.insertMany(e,{ordered:!1})}catch(t){Et.warn("Bulk write failed, retrying once",{count:e.length,error:String(t)});try{await this.collection.insertMany(e,{ordered:!1})}catch(s){Et.error("Bulk write failed after retry, dropping batch",{count:e.length,error:String(s)})}}}async stop(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=null),this.buffer.length>0&&(Et.info("Draining activity buffer on shutdown",{count:this.buffer.length}),await this.flush()),this.connected=!1}};M();var mf={id:"001-backfill-home-base",async run(n,e){let t=n.collection("agent_definitions"),s=t.find({homeBase:{$exists:!1}}),r=0,i=0;for await(let o of s){let a=o.channels?.find(l=>l.startsWith("agent-"))??o.channels?.[0];if(!a){e.warn("Cannot backfill homeBase \u2014 no channels",{agentId:o._id}),i++;continue}await t.updateOne({_id:o._id},{$set:{homeBase:a}}),r++}e.info("Backfill complete",{migration:"001-backfill-home-base",updated:r,skipped:i})}};var ci=k("migrations"),Nb=[mf];async function gf(n,e=Nb){let t=n.collection("migrations");for(let s of e){if(await t.findOne({_id:s.id})){ci.debug("Migration already applied, skipping",{id:s.id});continue}ci.info("Running migration",{id:s.id}),await s.run(n,ci),await t.insertOne({_id:s.id,ranAt:new Date}),ci.info("Migration applied",{id:s.id})}}M();var Nt=k("first-boot"),yf="hive/first-boot-greeting-sent",wf="chief-of-staff";async function Sf(n,e,t,s){let r;try{r=await n.read(yf)}catch(d){Nt.warn("First-boot flag read failed \u2014 skipping check this startup",{error:String(d)});return}if(r){Nt.debug("First-boot greeting already sent \u2014 skipping");return}let i=e.get(wf),o=i?.homeBase??i?.channels?.[0];if(!o){Nt.warn("First-boot: CoS agent has no homeBase or channels \u2014 skipping, will retry next startup");return}let a=s.get(o);if(!a){Nt.warn("First-boot: could not resolve channel ID for CoS home channel",{channelName:o});return}try{await n.write(yf,"true","system")}catch(d){Nt.error("First-boot: flag write failed \u2014 aborting greeting dispatch",{error:String(d)});return}let l=Date.now(),c={id:`system:first-boot:${l}`,text:"First boot detected. Greet the owner and offer onboarding.",source:{kind:"slack",id:a,label:o,adapterId:"slack"},sender:"system",threadId:`first-boot:${l}`,timestamp:new Date,meta:{targetAgentId:wf,systemTrigger:"first-boot"}};Nt.info("First-boot: dispatching CoS greeting",{channel:o,channelId:a}),t.dispatch(c).catch(d=>{Nt.error("First-boot greeting dispatch failed",{error:String(d)})})}M();import{createServer as xb}from"node:http";var Ka=k("slack-internal-api"),li=class{port;authToken;gateway;agentManager;server=null;constructor(e){this.port=e.port,this.authToken=e.authToken,this.gateway=e.gateway,this.agentManager=e.agentManager}async start(){this.server=xb((e,t)=>{this.handleRequest(e,t).catch(s=>{Ka.error("HTTP handler error",{error:String(s)}),t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"Internal server error"}))})}),await new Promise(e=>{this.server.listen(this.port,"127.0.0.1",()=>e())}),Ka.info("Slack internal API started",{port:this.port})}async stop(){this.server&&(this.server.close(),this.server=null),Ka.info("Slack internal API stopped")}async handleRequest(e,t){if(e.method!=="POST"){t.writeHead(405,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"method not allowed"}));return}if(e.headers.authorization!==`Bearer ${this.authToken}`){t.writeHead(401,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"unauthorized"}));return}let r=new URL(e.url??"/",`http://127.0.0.1:${this.port}`),i=await this.readBody(e),o;try{o=JSON.parse(i)}catch{t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"invalid JSON body"}));return}switch(r.pathname){case"/internal/slack/send":return this.handleSend(o,t);case"/internal/slack/read":return this.handleRead(o,t);case"/internal/slack/channels":return this.handleChannels(o,t);case"/internal/slack/users":return this.handleUsers(o,t);case"/internal/slack/search":t.writeHead(501,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"search deferred pending tool-parity audit"}));return;default:t.writeHead(404,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"not found"}))}}async handleSend(e,t){let{agent_id:s,channel:r,text:i,thread_ts:o,blocks:a,force_root:l}=e;if(typeof r!="string"||!r){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"channel is required"}));return}if(typeof i!="string"||!i){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"text is required"}));return}let c=await this.gateway.resolveChannelId(r);if(!c){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:`unknown channel: ${r}`}));return}let d=o;if(!d&&!l&&typeof s=="string"&&s){let m=this.agentManager.getActiveWorkItems(s).filter(f=>f.source.id===c);if(m.length>0){let f=m[m.length-1];d=f.meta?.slackThreadTs??f.meta?.slackTs}}let u=await this.gateway.postAndRegister(c,i,d),h=u.ok?{ok:!0,ts:u.ts,channel:c}:{ok:!1,error:u.error};t.writeHead(u.ok?200:500,{"Content-Type":"application/json"}),t.end(JSON.stringify(h))}async handleRead(e,t){let{channel:s,limit:r}=e;if(typeof s!="string"||!s){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"channel is required"}));return}let i=await this.gateway.readChannel(s,typeof r=="number"?r:void 0);if(i===void 0){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"failed to read channel history"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,messages:i}))}async handleChannels(e,t){let{query:s}=e,r=await this.gateway.listChannels(typeof s=="string"?s:void 0);t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,channels:r}))}async handleUsers(e,t){let{user:s}=e;if(typeof s!="string"||!s){t.writeHead(400,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"user is required"}));return}let r=await this.gateway.readUser(s);if(r===void 0){t.writeHead(500,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!1,error:"failed to look up user"}));return}t.writeHead(200,{"Content-Type":"application/json"}),t.end(JSON.stringify({ok:!0,user:r}))}readBody(e){return new Promise((t,s)=>{let r="";e.on("data",i=>{r+=i.toString()}),e.on("end",()=>t(r)),e.on("error",s)})}};M();var Ha=k("slack-scope-preflight"),Ob=["chat:write","chat:write.customize","channels:history","channels:read","users:read"];async function kf(n,e=Ob){let t=await fetch("https://slack.com/api/auth.test",{method:"POST",headers:{Authorization:`Bearer ${n}`}}),s=await t.json();if(!s.ok){Ha.warn("Slack auth.test failed \u2014 skipping scope preflight",{error:s.error??"unknown"});return}let i=(t.headers.get("x-oauth-scopes")??"").split(",").map(a=>a.trim()).filter(Boolean),o=e.filter(a=>!i.includes(a));if(o.length>0){Ha.warn("Slack bot token missing recommended scopes \u2014 some features may degrade silently",{missing:o,required:[...e],note:"Identity-mode posts fall back to plain bot identity if chat:write.customize is missing. Grant the scope and reinstall the app to enable it."});return}Ha.info("Slack scope preflight passed",{required:[...e]})}var x=k("index");function tm(n){for(let e of n)for(let t of[pn(e),Oc(e),Mc(e)])try{pv(t,{recursive:!0})}catch(s){x.warn("Failed to provision agent dir",{agentId:e,dir:t,err:s})}}async function yv(){x.info("Hive starting up",{instance:g.instance.id,portBase:g.instance.portBase}),Tc(em(V,"dist","index.js"))&&Tc(em(cs,"dist","index.js"))&&(x.error("Conflicting engine layouts detected \u2014 both <hiveHome>/dist/ and <hiveHome>/.hive/dist/ exist. Remove the old <hiveHome>/dist/ before starting 0.2.0.",{hiveHome:V,engineDir:cs}),process.exit(1)),qc(V,hn),Fc(V),$c(V),Hc(hn,Xe),g.gemini.apiKey&&(Rh(g.gemini.apiKey),x.info("Gemini vision enabled",{model:g.gemini.visionModel}));let n=new gv(g.mongo.uri,{heartbeatFrequencyMS:3e4,serverSelectionTimeoutMS:1e4,socketTimeoutMS:3e4,maxIdleTimeMS:3e5,retryWrites:!0,retryReads:!0});await n.connect();let e=n.db(g.mongo.dbName),t=e.collection("agent_definitions");await t.createIndex({channels:1}),await t.createIndex({disabled:1}),await gf(e);let s,r,i,o=null,a,l=async()=>{if(!r||!i)return;x.info("Hot-reloading agent registry...");let O=await s.load();if(O.added.length&&x.info("New agents online",{agents:O.added}),O.updated.length&&x.info("Agents updated",{agents:O.updated}),tm(s.listIds()),O.removed.length){x.info("Agents removed",{agents:O.removed});for(let ue of O.removed)r.stopAgent(ue)}let B=s.getDisabled();for(let ue of B)r.stopAgent(ue.id);B.length&&x.info("Disabled agents stopped",{agents:B.map(ue=>ue.id)}),await i.reloadSchedules(),r.reloadSkills(),r.rescanPlugins()};s=new yr(t,()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),await s.load(),x.info("Agent registry loaded",{agents:s.listIds()}),tm(s.listIds());let c=new Lr(e);await c.init();let d=new si(e);await d.init(),c.memoryStore=d;let u=new ni,h=new ii(d,u,{hotBudgetTokens:g.memory.hotBudgetTokens,sweepIntervalHours:g.memory.sweepIntervalHours,hotThreshold:g.memory.hotThreshold,warmThreshold:g.memory.warmThreshold,recencyHalfLifeDays:g.memory.recencyHalfLifeDays,coldSummaryMinRecords:g.memory.coldSummaryMinRecords,coldRetentionDays:g.memory.coldRetentionDays,purgeRetentionDays:g.memory.purgeRetentionDays},g.autoDream,async()=>new Set(s.listIds()));x.info("Structured memory lifecycle enabled");let p=new Br(e);await p.init();let m;if(g.activity.enabled&&(m=new ai(e,g.activity),await m.connect()),g.linear.apiKey){let O=new Rr(g.linear.apiKey,g.linear.teamId||void 0);x.info("Linear client configured")}let f=new Wr(g.taskLedger.apiUrl,g.taskLedger.apiKey);f.isConfigured&&x.info("Task ledger client configured",{apiUrl:g.taskLedger.apiUrl});let y=new Gr(g.taskLedger.apiUrl,g.taskLedger.agentKeys,g.taskLedger.apiKey);y.isConfigured&&x.info("Task ledger auto-tracking enabled",{apiUrl:g.taskLedger.apiUrl,agents:Object.keys(g.taskLedger.agentKeys)});let w,S;if(g.codeIndex.enabled){let{CodeIndexPrefetcher:O}=await Promise.resolve().then(()=>(vf(),_f)),{KnowledgeExtractor:B}=await Promise.resolve().then(()=>(If(),Tf));w=new O({db:e,qdrantUrl:process.env.QDRANT_URL??"http://localhost:6333",ollamaUrl:process.env.OLLAMA_URL??"http://localhost:11434",scoreThreshold:g.codeIndex.scoreThreshold,prefetchLimit:g.codeIndex.prefetchLimit}),g.codeIndex.sessionKnowledge.enabled&&(S=new B(d,u)),x.info("Code index integration enabled",{prefetch:!0,sessionKnowledge:S!==void 0})}r=new Or(s,c,p,m,w);let _=new $r(r,c,s),v=new jr(s,r,_,g.defaultAgent,y.isConfigured?y:void 0),I=new Vr(g.background.port,g.background.authToken,g.tasksDir.background,O=>v.dispatch(O).catch(B=>{x.error("Background task completion dispatch failed",{error:String(B)})}));await I.start(),await I.scanOrphans(),x.info("Background task manager started",{port:g.background.port});let N=new Jr(g.codeTask.port,g.codeTask.authToken,g.codeTask.pluginDirs,g.codeTask.maxConcurrent,g.tasksDir.code,O=>v.dispatch(O).catch(B=>{x.error("Code task completion dispatch failed",{error:String(B)})}),{prefetcher:w,knowledgeExtractor:S,maxLifetimeMs:g.codeTask.maxLifetimeMs,staleGraceMs:g.codeTask.staleGraceMs});await N.start(),await N.scanOrphans(),x.info("Code task manager started",{port:g.codeTask.port});let D;g.recall.apiKey&&(D=new zr(g.recall.monitorPort,g.recall.webhookSecret,O=>v.dispatch(O).catch(B=>{x.error("Meeting monitor dispatch failed",{error:String(B)})})),await D.start(),x.info("Meeting monitor started",{port:g.recall.monitorPort}),g.recall.apiKey&&!g.recall.webhookSecret&&x.error("Real-time transcript delivery disabled \u2014 RECALL_WEBHOOK_SECRET not set")),Tc(Xe)&&(mv(Xe,{recursive:!0},()=>{o&&clearTimeout(o),o=setTimeout(()=>l(),500)}),x.info("Skills hot-reload enabled",{watched:Xe})),process.on("SIGUSR1",()=>l()),x.info("Hot-reload enabled",{signal:"SIGUSR1"});let A=g.sms.lines.map(O=>O.slackChannel).filter(Boolean),E=new Dr(g.slack.appToken,g.slack.botToken),G=new qr(E,s,A,"slack");v.registerAdapter(G),v.setSlackAdapter(G),await G.start(O=>{v.dispatch(O).catch(B=>{x.error("Slack dispatch failed",{error:String(B),source:O.source.label})})}),x.info("Slack adapter connected");let W=new Map;try{let O;do{let ue=await E.client.conversations.list({types:"public_channel,private_channel",limit:1e3,cursor:O});for(let $t of ue.channels??[])$t.name&&$t.id&&W.set($t.name,$t.id);O=ue.response_metadata?.next_cursor||void 0}while(O);let B=g.slack.auditChannel;a=B?W.get(B):void 0,v.setAuditChannel(G,W,a),x.info("Audit channel configured",{channels:W.size,fallback:B||null,fallbackResolved:!!a})}catch(O){x.warn("Failed to configure audit channel",{error:String(O)})}let $=null;g.slack.localMcpServer&&(await kf(g.slack.botToken),$=new li({port:g.slackInternal.port,authToken:g.slackInternal.authToken,gateway:E,agentManager:r}),await $.start(),x.info("Slack internal API started",{port:g.slackInternal.port}));let le=new Fr(g.quo.apiKey,g.sms.lines);v.registerAdapter(le),g.quo.apiKey&&g.sms.lines.length>0&&(await le.start(O=>{v.dispatch(O).catch(B=>{x.error("SMS dispatch failed",{error:String(B),source:O.source.label})})}),x.info("SMS adapter started",{lines:g.sms.lines.length}));let Ie;g.imessage.enabled&&(Ie=new Hr(g.imessage,e,E,g.instance.id),v.registerAdapter(Ie),await Ie.start(O=>{v.dispatch(O).catch(B=>{x.error("iMessage dispatch failed",{error:String(B)})})}),x.info("iMessage adapter started"));let{AgentRunner:ge}=await Promise.resolve().then(()=>(La(),Lh));ge.registryRef=s;let{TeamStore:ln}=await Promise.resolve().then(()=>(Nf(),Ef)),{CommandRegistry:os}=await Promise.resolve().then(()=>(Of(),xf)),mt=new ln(e);await mt.init();let Ti=O=>{let B=s.getAll(),ue=B.find(Ai=>Ai.id===O);if(ue)return{id:ue.id,name:ue.name};let $t=O.toLowerCase(),Ii=B.find(Ai=>Ai.name.toLowerCase()===$t);return Ii?{id:Ii.id,name:Ii.name}:null},Qe=new os(mt,Ti);v.setTeamStore(mt),x.info("Team layer initialized");let{registerPluginCommands:dn}=await Promise.resolve().then(()=>(kr(),gh));await dn(r.getPlugins(),Qe);let Be;if(g.ws.enabled){let{WsAdapter:O}=await Promise.resolve().then(()=>(qp(),jp));Be=new O(g.ws.port,{teamStore:mt,commandRegistry:Qe,agentRegistry:s,agentManager:r}),v.registerAdapter(Be),await Be.start(B=>{v.dispatch(B).catch(ue=>{x.error("WS dispatch failed",{error:String(ue),source:B.source.label})})}),x.info("WebSocket adapter started",{port:g.ws.port})}let as;if(g.ws.enabled){let{startBeekeeperRegistration:O}=await Promise.resolve().then(()=>(Kp(),Fp)),B=`hive-${g.instance.id}`;as=O({beekeeperPort:g.beekeeper.port,wsPort:g.ws.port,capabilityName:B}),x.info("Beekeeper registration loop started",{beekeeperPort:g.beekeeper.port,wsPort:g.ws.port,capabilityName:B})}let Y;if(g.voice.enabled&&g.voice.serverSecret){let{VoiceAdapter:O}=await Promise.resolve().then(()=>(Zp(),Xp));Y=new O(g.voice.port,g.voice.serverSecret,s,c),await Y.start(),x.info("Voice adapter started",{port:g.voice.port})}i=new Pr(r,c,_,s,O=>{v.dispatch(O).catch(B=>{x.error("Callback dispatch failed",{error:String(B)})})}),await i.connectDb(e),i.start(),x.info("Scheduler started"),await s.startWatching();let L;g.adminApi.token&&(L=new oi(g.adminApi.port,g.adminApi.token,t,e.collection("agent_definition_versions"),()=>l()),await L.start(),x.info("Admin API started",{port:g.adminApi.port}));let P=new Xr({maxAttempts:g.sweeper.retryMaxAttempts,baseDelayMs:g.sweeper.retryBaseDelayMs});v.setRetryQueue(P);let de=[G],un=[E],Pt=new Zr({intervalMs:g.sweeper.intervalMs,threadTtlMs:g.sweeper.threadTtlMs,taskFileTtlMs:g.sweeper.taskFileTtlMs,meetingSessionTtlMs:g.sweeper.meetingSessionTtlMs,cacheTtlMs:g.sweeper.cacheTtlMs,memorySweepIntervalHours:g.memory.sweepIntervalHours,dreamConfig:g.autoDream},{dispatcher:v,slackAdapters:de,bgTaskManager:I,codeTaskManager:N,meetingMonitor:D,taskLedger:y.isConfigured?y:void 0,slackGateways:un,agentManager:r,retryQueue:P,memoryLifecycle:h},f.isConfigured?f:void 0);Pt.start(),x.info("Sweeper started",{intervalMs:g.sweeper.intervalMs});let Ic=new ti(g.retention,{hiveHome:V,report:async O=>{a?await E.postMessage(a,O).catch(B=>x.warn("Retention report: Slack post failed",{error:String(B)})):x.info("Retention report (no audit channel configured)",{text:O})}});Ic.start(),x.info("Retention sweeper started",{enabled:g.retention.enabled,intervalMs:g.retention.intervalMs});let Ac=async O=>{x.info("Shutdown signal received",{signal:O}),Pt.stop(),Ic.stop(),L?.stop(),s.stopWatching(),await le.stop(),$&&await $.stop(),Ie&&await Ie.stop(),as?.stop(),Be&&await Be.stop(),Y?.stop(),i.stop(),await I.stop(),await N.stop(),await w?.close(),D?.stop(),r.stopAll(),m&&await m.stop(),await p.close(),await d.close(),await G.stop(),await n.close(),x.info("Hive shut down cleanly"),process.exit(0)};process.on("SIGTERM",()=>Ac("SIGTERM")),process.on("SIGINT",()=>Ac("SIGINT")),x.info("Hive is running"),Sf(c,s,v,W).catch(O=>{x.error("First-boot check failed",{error:String(O)})})}process.on("unhandledRejection",n=>{x.error("Unhandled promise rejection",{error:String(n),stack:n instanceof Error?n.stack:void 0})});yv().catch(n=>{x.error("Fatal startup error",{error:String(n)}),process.exit(1)});