everclaw 0.3.19 → 0.3.20
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/agent/subagent-worker.js +72 -81
- package/index.js +213 -401
- package/package.json +1 -1
- package/agent/tools/chrome-session/daemon-worker.js +0 -54
package/agent/subagent-worker.js
CHANGED
|
@@ -1,67 +1,58 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{createRequire as i6}from"node:module";var c6=Object.create;var{getPrototypeOf:d6,defineProperty:w$,getOwnPropertyNames:l6}=Object;var p6=Object.prototype.hasOwnProperty;var HJ=(J,_,$)=>{$=J!=null?c6(d6(J)):{};let X=_||!J||!J.__esModule?w$($,"default",{value:J,enumerable:!0}):$;for(let A of l6(J))if(!p6.call(X,A))w$(X,A,{get:()=>J[A],enumerable:!0});return X};var D=(J,_)=>()=>(_||J((_={exports:{}}).exports,_),_.exports);var x=i6(import.meta.url);var I$=D((yK,n6)=>{n6.exports={name:"dotenv",version:"16.6.1",description:"Loads environment variables from .env file",main:"lib/main.js",types:"lib/main.d.ts",exports:{".":{types:"./lib/main.d.ts",require:"./lib/main.js",default:"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},scripts:{"dts-check":"tsc --project tests/types/tsconfig.json",lint:"standard",pretest:"npm run lint && npm run dts-check",test:"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",prerelease:"npm test",release:"standard-version"},repository:{type:"git",url:"git://github.com/motdotla/dotenv.git"},homepage:"https://github.com/motdotla/dotenv#readme",funding:"https://dotenvx.com",keywords:["dotenv","env",".env","environment","variables","config","settings"],readmeFilename:"README.md",license:"BSD-2-Clause",devDependencies:{"@types/node":"^18.11.3",decache:"^4.6.2",sinon:"^14.0.1",standard:"^17.0.0","standard-version":"^9.5.0",tap:"^19.2.0",typescript:"^4.8.4"},engines:{node:">=12"},browser:{fs:!1}}});var b$=D((LK,yJ)=>{var _1=x("fs"),__=x("path"),r6=x("os"),o6=x("crypto"),a6=I$(),$1=a6.version,s6=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function t6(J){let _={},$=J.toString();$=$.replace(/\r\n?/mg,`
|
|
3
|
-
`);
|
|
4
|
-
`),G=G.replace(/\\r/g,"\r");_[A]=G}return _}function e6(J){J=J||{};let _=h$(J);J.path=_;let $=m.configDotenv(J);if(!$.parsed){let K=new Error(`MISSING_DATA: Cannot parse ${_} for an unknown reason`);throw K.code="MISSING_DATA",K}let X=v$(J).split(","),A=X.length,G;for(let K=0;K<A;K++)try{let Q=X[K].trim(),N=_8($,Q);G=m.decrypt(N.ciphertext,N.key);break}catch(Q){if(K+1>=A)throw Q}return m.parse(G)}function J8(J){console.log(`[dotenv@${$1}][WARN] ${J}`)}function F0(J){console.log(`[dotenv@${$1}][DEBUG] ${J}`)}function D$(J){console.log(`[dotenv@${$1}] ${J}`)}function v$(J){if(J&&J.DOTENV_KEY&&J.DOTENV_KEY.length>0)return J.DOTENV_KEY;if(process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0)return process.env.DOTENV_KEY;return""}function _8(J,_){let $;try{$=new URL(_)}catch(Q){if(Q.code==="ERR_INVALID_URL"){let N=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 N.code="INVALID_DOTENV_KEY",N}throw Q}let X=$.password;if(!X){let Q=new Error("INVALID_DOTENV_KEY: Missing key part");throw Q.code="INVALID_DOTENV_KEY",Q}let A=$.searchParams.get("environment");if(!A){let Q=new Error("INVALID_DOTENV_KEY: Missing environment part");throw Q.code="INVALID_DOTENV_KEY",Q}let G=`DOTENV_VAULT_${A.toUpperCase()}`,K=J.parsed[G];if(!K){let Q=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${G} in your .env.vault file.`);throw Q.code="NOT_FOUND_DOTENV_ENVIRONMENT",Q}return{ciphertext:K,key:X}}function h$(J){let _=null;if(J&&J.path&&J.path.length>0)if(Array.isArray(J.path)){for(let $ of J.path)if(_1.existsSync($))_=$.endsWith(".vault")?$:`${$}.vault`}else _=J.path.endsWith(".vault")?J.path:`${J.path}.vault`;else _=__.resolve(process.cwd(),".env.vault");if(_1.existsSync(_))return _;return null}function x$(J){return J[0]==="~"?__.join(r6.homedir(),J.slice(1)):J}function $8(J){let _=Boolean(J&&J.debug),$=J&&"quiet"in J?J.quiet:!0;if(_||!$)D$("Loading env from encrypted .env.vault");let X=m._parseVault(J),A=process.env;if(J&&J.processEnv!=null)A=J.processEnv;return m.populate(A,X,J),{parsed:X}}function X8(J){let _=__.resolve(process.cwd(),".env"),$="utf8",X=Boolean(J&&J.debug),A=J&&"quiet"in J?J.quiet:!0;if(J&&J.encoding)$=J.encoding;else if(X)F0("No encoding is specified. UTF-8 is used by default");let G=[_];if(J&&J.path)if(!Array.isArray(J.path))G=[x$(J.path)];else{G=[];for(let R of J.path)G.push(x$(R))}let K,Q={};for(let R of G)try{let Y=m.parse(_1.readFileSync(R,{encoding:$}));m.populate(Q,Y,J)}catch(Y){if(X)F0(`Failed to load ${R} ${Y.message}`);K=Y}let N=process.env;if(J&&J.processEnv!=null)N=J.processEnv;if(m.populate(N,Q,J),X||!A){let R=Object.keys(Q).length,Y=[];for(let H of G)try{let q=__.relative(process.cwd(),H);Y.push(q)}catch(q){if(X)F0(`Failed to load ${H} ${q.message}`);K=q}D$(`injecting env (${R}) from ${Y.join(",")}`)}if(K)return{parsed:Q,error:K};else return{parsed:Q}}function A8(J){if(v$(J).length===0)return m.configDotenv(J);let _=h$(J);if(!_)return J8(`You set DOTENV_KEY but you are missing a .env.vault file at ${_}. Did you forget to build it?`),m.configDotenv(J);return m._configVault(J)}function G8(J,_){let $=Buffer.from(_.slice(-64),"hex"),X=Buffer.from(J,"base64"),A=X.subarray(0,12),G=X.subarray(-16);X=X.subarray(12,-16);try{let K=o6.createDecipheriv("aes-256-gcm",$,A);return K.setAuthTag(G),`${K.update(X)}${K.final()}`}catch(K){let Q=K instanceof RangeError,N=K.message==="Invalid key length",R=K.message==="Unsupported state or unable to authenticate data";if(Q||N){let Y=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw Y.code="INVALID_DOTENV_KEY",Y}else if(R){let Y=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw Y.code="DECRYPTION_FAILED",Y}else throw K}}function K8(J,_,$={}){let X=Boolean($&&$.debug),A=Boolean($&&$.override);if(typeof _!=="object"){let G=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw G.code="OBJECT_REQUIRED",G}for(let G of Object.keys(_))if(Object.prototype.hasOwnProperty.call(J,G)){if(A===!0)J[G]=_[G];if(X)if(A===!0)F0(`"${G}" is already defined and WAS overwritten`);else F0(`"${G}" is already defined and was NOT overwritten`)}else J[G]=_[G]}var m={configDotenv:X8,_configVault:$8,_parseVault:e6,config:A8,decrypt:G8,parse:t6,populate:K8};LK.configDotenv=m.configDotenv;LK._configVault=m._configVault;LK._parseVault=m._parseVault;LK.config=m.config;LK.decrypt=m.decrypt;LK.parse=m.parse;LK.populate=m.populate;yJ.exports=m});var g$=D((BK,f$)=>{var DJ={};if(process.env.DOTENV_CONFIG_ENCODING!=null)DJ.encoding=process.env.DOTENV_CONFIG_ENCODING;if(process.env.DOTENV_CONFIG_PATH!=null)DJ.path=process.env.DOTENV_CONFIG_PATH;if(process.env.DOTENV_CONFIG_QUIET!=null)DJ.quiet=process.env.DOTENV_CONFIG_QUIET;if(process.env.DOTENV_CONFIG_DEBUG!=null)DJ.debug=process.env.DOTENV_CONFIG_DEBUG;if(process.env.DOTENV_CONFIG_OVERRIDE!=null)DJ.override=process.env.DOTENV_CONFIG_OVERRIDE;if(process.env.DOTENV_CONFIG_DOTENV_KEY!=null)DJ.DOTENV_KEY=process.env.DOTENV_CONFIG_DOTENV_KEY;f$.exports=DJ});var m$=D((UK,k$)=>{var y8=/^dotenv_config_(encoding|path|quiet|debug|override|DOTENV_KEY)=(.+)$/;k$.exports=function J(_){let $=_.reduce(function(X,A){let G=A.match(y8);if(G)X[G[1]]=G[2];return X},{});if(!("quiet"in $))$.quiet="true";return $}});var u$=D(()=>{(function(){b$().config(Object.assign({},g$(),m$()(process.argv)))})()});var n4=D((i4)=>{Object.defineProperty(i4,"__esModule",{value:!0});class TJ extends Error{}class uX extends TJ{constructor(J){super(`Invalid DateTime: ${J.toMessage()}`)}}class cX extends TJ{constructor(J){super(`Invalid Interval: ${J.toMessage()}`)}}class dX extends TJ{constructor(J){super(`Invalid Duration: ${J.toMessage()}`)}}class kJ extends TJ{}class W1 extends TJ{constructor(J){super(`Invalid unit ${J}`)}}class p extends TJ{}class BJ extends TJ{constructor(){super("Zone is an abstract class")}}var L="numeric",QJ="short",a="long",L_={year:L,month:L,day:L},lX={year:L,month:QJ,day:L},W8={year:L,month:QJ,day:L,weekday:QJ},pX={year:L,month:a,day:L},iX={year:L,month:a,day:L,weekday:a},nX={hour:L,minute:L},rX={hour:L,minute:L,second:L},oX={hour:L,minute:L,second:L,timeZoneName:QJ},aX={hour:L,minute:L,second:L,timeZoneName:a},sX={hour:L,minute:L,hourCycle:"h23"},tX={hour:L,minute:L,second:L,hourCycle:"h23"},eX={hour:L,minute:L,second:L,hourCycle:"h23",timeZoneName:QJ},J4={hour:L,minute:L,second:L,hourCycle:"h23",timeZoneName:a},_4={year:L,month:L,day:L,hour:L,minute:L},$4={year:L,month:L,day:L,hour:L,minute:L,second:L},X4={year:L,month:QJ,day:L,hour:L,minute:L},A4={year:L,month:QJ,day:L,hour:L,minute:L,second:L},w8={year:L,month:QJ,day:L,weekday:QJ,hour:L,minute:L},G4={year:L,month:a,day:L,hour:L,minute:L,timeZoneName:QJ},K4={year:L,month:a,day:L,hour:L,minute:L,second:L,timeZoneName:QJ},Q4={year:L,month:a,day:L,weekday:a,hour:L,minute:L,timeZoneName:a},N4={year:L,month:a,day:L,weekday:a,hour:L,minute:L,second:L,timeZoneName:a};class uJ{get type(){throw new BJ}get name(){throw new BJ}get ianaName(){return this.name}get isUniversal(){throw new BJ}offsetName(J,_){throw new BJ}formatOffset(J,_){throw new BJ}offset(J){throw new BJ}equals(J){throw new BJ}get isValid(){throw new BJ}}var R1=null;class b0 extends uJ{static get instance(){if(R1===null)R1=new b0;return R1}get type(){return"system"}get name(){return new Intl.DateTimeFormat().resolvedOptions().timeZone}get isUniversal(){return!1}offsetName(J,{format:_,locale:$}){return j4(J,_,$)}formatOffset(J,_){return v0(this.offset(J),_)}offset(J){return-new Date(J).getTimezoneOffset()}equals(J){return J.type==="system"}get isValid(){return!0}}var Z1=new Map;function I8(J){let _=Z1.get(J);if(_===void 0)_=new Intl.DateTimeFormat("en-US",{hour12:!1,timeZone:J,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",era:"short"}),Z1.set(J,_);return _}var x8={year:0,month:1,day:2,era:3,hour:4,minute:5,second:6};function D8(J,_){let $=J.format(_).replace(/\u200E/g,""),X=/(\d+)\/(\d+)\/(\d+) (AD|BC),? (\d+):(\d+):(\d+)/.exec($),[,A,G,K,Q,N,R,Y]=X;return[K,A,G,Q,N,R,Y]}function v8(J,_){let $=J.formatToParts(_),X=[];for(let A=0;A<$.length;A++){let{type:G,value:K}=$[A],Q=x8[G];if(G==="era")X[Q]=K;else if(!z(Q))X[Q]=parseInt(K,10)}return X}var Y1=new Map;class qJ extends uJ{static create(J){let _=Y1.get(J);if(_===void 0)Y1.set(J,_=new qJ(J));return _}static resetCache(){Y1.clear(),Z1.clear()}static isValidSpecifier(J){return this.isValidZone(J)}static isValidZone(J){if(!J)return!1;try{return new Intl.DateTimeFormat("en-US",{timeZone:J}).format(),!0}catch(_){return!1}}constructor(J){super();this.zoneName=J,this.valid=qJ.isValidZone(J)}get type(){return"iana"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(J,{format:_,locale:$}){return j4(J,_,$,this.name)}formatOffset(J,_){return v0(this.offset(J),_)}offset(J){if(!this.valid)return NaN;let _=new Date(J);if(isNaN(_))return NaN;let $=I8(this.name),[X,A,G,K,Q,N,R]=$.formatToParts?v8($,_):D8($,_);if(K==="BC")X=-Math.abs(X)+1;let H=z_({year:X,month:A,day:G,hour:Q===24?0:Q,minute:N,second:R,millisecond:0}),q=+_,V=q%1000;return q-=V>=0?V:1000+V,(H-q)/60000}equals(J){return J.type==="iana"&&J.name===this.name}get isValid(){return this.valid}}var HX={};function h8(J,_={}){let $=JSON.stringify([J,_]),X=HX[$];if(!X)X=new Intl.ListFormat(J,_),HX[$]=X;return X}var M1=new Map;function z1(J,_={}){let $=JSON.stringify([J,_]),X=M1.get($);if(X===void 0)X=new Intl.DateTimeFormat(J,_),M1.set($,X);return X}var E1=new Map;function b8(J,_={}){let $=JSON.stringify([J,_]),X=E1.get($);if(X===void 0)X=new Intl.NumberFormat(J,_),E1.set($,X);return X}var j1=new Map;function f8(J,_={}){let{base:$,...X}=_,A=JSON.stringify([J,X]),G=j1.get(A);if(G===void 0)G=new Intl.RelativeTimeFormat(J,_),j1.set(A,G);return G}var I0=null;function g8(){if(I0)return I0;else return I0=new Intl.DateTimeFormat().resolvedOptions().locale,I0}var C1=new Map;function R4(J){let _=C1.get(J);if(_===void 0)_=new Intl.DateTimeFormat(J).resolvedOptions(),C1.set(J,_);return _}var O1=new Map;function k8(J){let _=O1.get(J);if(!_){let $=new Intl.Locale(J);if(_="getWeekInfo"in $?$.getWeekInfo():$.weekInfo,!("minimalDays"in _))_={...V4,..._};O1.set(J,_)}return _}function m8(J){let _=J.indexOf("-x-");if(_!==-1)J=J.substring(0,_);let $=J.indexOf("-u-");if($===-1)return[J];else{let X,A;try{X=z1(J).resolvedOptions(),A=J}catch(Q){let N=J.substring(0,$);X=z1(N).resolvedOptions(),A=N}let{numberingSystem:G,calendar:K}=X;return[A,G,K]}}function u8(J,_,$){if($||_){if(!J.includes("-u-"))J+="-u";if($)J+=`-ca-${$}`;if(_)J+=`-nu-${_}`;return J}else return J}function c8(J){let _=[];for(let $=1;$<=12;$++){let X=E.utc(2009,$,1);_.push(J(X))}return _}function d8(J){let _=[];for(let $=1;$<=7;$++){let X=E.utc(2016,11,13+$);_.push(J(X))}return _}function N_(J,_,$,X){let A=J.listingMode();if(A==="error")return null;else if(A==="en")return $(_);else return X(_)}function l8(J){if(J.numberingSystem&&J.numberingSystem!=="latn")return!1;else return J.numberingSystem==="latn"||!J.locale||J.locale.startsWith("en")||R4(J.locale).numberingSystem==="latn"}class Y4{constructor(J,_,$){this.padTo=$.padTo||0,this.floor=$.floor||!1;let{padTo:X,floor:A,...G}=$;if(!_||Object.keys(G).length>0){let K={useGrouping:!1,...$};if($.padTo>0)K.minimumIntegerDigits=$.padTo;this.inf=b8(J,K)}}format(J){if(this.inf){let _=this.floor?Math.floor(J):J;return this.inf.format(_)}else{let _=this.floor?Math.floor(J):h1(J,3);return f(_,this.padTo)}}}class H4{constructor(J,_,$){this.opts=$,this.originalZone=void 0;let X=void 0;if(this.opts.timeZone)this.dt=J;else if(J.zone.type==="fixed"){let G=-1*(J.offset/60),K=G>=0?`Etc/GMT+${G}`:`Etc/GMT${G}`;if(J.offset!==0&&qJ.create(K).valid)X=K,this.dt=J;else X="UTC",this.dt=J.offset===0?J:J.setZone("UTC").plus({minutes:J.offset}),this.originalZone=J.zone}else if(J.zone.type==="system")this.dt=J;else if(J.zone.type==="iana")this.dt=J,X=J.zone.name;else X="UTC",this.dt=J.setZone("UTC").plus({minutes:J.offset}),this.originalZone=J.zone;let A={...this.opts};A.timeZone=A.timeZone||X,this.dtf=z1(_,A)}format(){if(this.originalZone)return this.formatToParts().map(({value:J})=>J).join("");return this.dtf.format(this.dt.toJSDate())}formatToParts(){let J=this.dtf.formatToParts(this.dt.toJSDate());if(this.originalZone)return J.map((_)=>{if(_.type==="timeZoneName"){let $=this.originalZone.offsetName(this.dt.ts,{locale:this.dt.locale,format:this.opts.timeZoneName});return{..._,value:$}}else return _});return J}resolvedOptions(){return this.dtf.resolvedOptions()}}class q4{constructor(J,_,$){if(this.opts={style:"long",...$},!_&&z4())this.rtf=f8(J,$)}format(J,_){if(this.rtf)return this.rtf.format(J,_);else return H2(_,J,this.opts.numeric,this.opts.style!=="long")}formatToParts(J,_){if(this.rtf)return this.rtf.formatToParts(J,_);else return[]}}var V4={firstDay:1,minimalDays:4,weekend:[6,7]};class W{static fromOpts(J){return W.create(J.locale,J.numberingSystem,J.outputCalendar,J.weekSettings,J.defaultToEN)}static create(J,_,$,X,A=!1){let G=J||v.defaultLocale,K=G||(A?"en-US":g8()),Q=_||v.defaultNumberingSystem,N=$||v.defaultOutputCalendar,R=T1(X)||v.defaultWeekSettings;return new W(K,Q,N,R,G)}static resetCache(){I0=null,M1.clear(),E1.clear(),j1.clear(),C1.clear(),O1.clear()}static fromObject({locale:J,numberingSystem:_,outputCalendar:$,weekSettings:X}={}){return W.create(J,_,$,X)}constructor(J,_,$,X,A){let[G,K,Q]=m8(J);this.locale=G,this.numberingSystem=_||K||null,this.outputCalendar=$||Q||null,this.weekSettings=X,this.intl=u8(this.locale,this.numberingSystem,this.outputCalendar),this.weekdaysCache={format:{},standalone:{}},this.monthsCache={format:{},standalone:{}},this.meridiemCache=null,this.eraCache={},this.specifiedLocale=A,this.fastNumbersCached=null}get fastNumbers(){if(this.fastNumbersCached==null)this.fastNumbersCached=l8(this);return this.fastNumbersCached}listingMode(){let J=this.isEnglish(),_=(this.numberingSystem===null||this.numberingSystem==="latn")&&(this.outputCalendar===null||this.outputCalendar==="gregory");return J&&_?"en":"intl"}clone(J){if(!J||Object.getOwnPropertyNames(J).length===0)return this;else return W.create(J.locale||this.specifiedLocale,J.numberingSystem||this.numberingSystem,J.outputCalendar||this.outputCalendar,T1(J.weekSettings)||this.weekSettings,J.defaultToEN||!1)}redefaultToEN(J={}){return this.clone({...J,defaultToEN:!0})}redefaultToSystem(J={}){return this.clone({...J,defaultToEN:!1})}months(J,_=!1){return N_(this,J,F4,()=>{let $=this.intl==="ja"||this.intl.startsWith("ja-");_&=!$;let X=_?{month:J,day:"numeric"}:{month:J},A=_?"format":"standalone";if(!this.monthsCache[A][J]){let G=!$?(K)=>this.extract(K,X,"month"):(K)=>this.dtFormatter(K,X).format();this.monthsCache[A][J]=c8(G)}return this.monthsCache[A][J]})}weekdays(J,_=!1){return N_(this,J,P4,()=>{let $=_?{weekday:J,year:"numeric",month:"long",day:"numeric"}:{weekday:J},X=_?"format":"standalone";if(!this.weekdaysCache[X][J])this.weekdaysCache[X][J]=d8((A)=>this.extract(A,$,"weekday"));return this.weekdaysCache[X][J]})}meridiems(){return N_(this,void 0,()=>W4,()=>{if(!this.meridiemCache){let J={hour:"numeric",hourCycle:"h12"};this.meridiemCache=[E.utc(2016,11,13,9),E.utc(2016,11,13,19)].map((_)=>this.extract(_,J,"dayperiod"))}return this.meridiemCache})}eras(J){return N_(this,J,w4,()=>{let _={era:J};if(!this.eraCache[J])this.eraCache[J]=[E.utc(-40,1,1),E.utc(2017,1,1)].map(($)=>this.extract($,_,"era"));return this.eraCache[J]})}extract(J,_,$){let X=this.dtFormatter(J,_),A=X.formatToParts(),G=A.find((K)=>K.type.toLowerCase()===$);return G?G.value:null}numberFormatter(J={}){return new Y4(this.intl,J.forceSimple||this.fastNumbers,J)}dtFormatter(J,_={}){return new H4(J,this.intl,_)}relFormatter(J={}){return new q4(this.intl,this.isEnglish(),J)}listFormatter(J={}){return h8(this.intl,J)}isEnglish(){return this.locale==="en"||this.locale.toLowerCase()==="en-us"||R4(this.intl).locale.startsWith("en-us")}getWeekSettings(){if(this.weekSettings)return this.weekSettings;else if(!E4())return V4;else return k8(this.locale)}getStartOfWeek(){return this.getWeekSettings().firstDay}getMinDaysInFirstWeek(){return this.getWeekSettings().minimalDays}getWeekendDays(){return this.getWeekSettings().weekend}equals(J){return this.locale===J.locale&&this.numberingSystem===J.numberingSystem&&this.outputCalendar===J.outputCalendar}toString(){return`Locale(${this.locale}, ${this.numberingSystem}, ${this.outputCalendar})`}}var H1=null;class n extends uJ{static get utcInstance(){if(H1===null)H1=new n(0);return H1}static instance(J){return J===0?n.utcInstance:new n(J)}static parseSpecifier(J){if(J){let _=J.match(/^utc(?:([+-]\d{1,2})(?::(\d{2}))?)?$/i);if(_)return new n(E_(_[1],_[2]))}return null}constructor(J){super();this.fixed=J}get type(){return"fixed"}get name(){return this.fixed===0?"UTC":`UTC${v0(this.fixed,"narrow")}`}get ianaName(){if(this.fixed===0)return"Etc/UTC";else return`Etc/GMT${v0(-this.fixed,"narrow")}`}offsetName(){return this.name}formatOffset(J,_){return v0(this.fixed,_)}get isUniversal(){return!0}offset(){return this.fixed}equals(J){return J.type==="fixed"&&J.fixed===this.fixed}get isValid(){return!0}}class w1 extends uJ{constructor(J){super();this.zoneName=J}get type(){return"invalid"}get name(){return this.zoneName}get isUniversal(){return!1}offsetName(){return null}formatOffset(){return""}offset(){return NaN}equals(){return!1}get isValid(){return!1}}function OJ(J,_){if(z(J)||J===null)return _;else if(J instanceof uJ)return J;else if(a8(J)){let $=J.toLowerCase();if($==="default")return _;else if($==="local"||$==="system")return b0.instance;else if($==="utc"||$==="gmt")return n.utcInstance;else return n.parseSpecifier($)||qJ.create(J)}else if(FJ(J))return n.instance(J);else if(typeof J==="object"&&"offset"in J&&typeof J.offset==="function")return J;else return new w1(J)}var I1={arab:"[٠-٩]",arabext:"[۰-۹]",bali:"[᭐-᭙]",beng:"[০-৯]",deva:"[०-९]",fullwide:"[0-9]",gujr:"[૦-૯]",hanidec:"[〇|一|二|三|四|五|六|七|八|九]",khmr:"[០-៩]",knda:"[೦-೯]",laoo:"[໐-໙]",limb:"[᥆-᥏]",mlym:"[൦-൯]",mong:"[᠐-᠙]",mymr:"[၀-၉]",orya:"[୦-୯]",tamldec:"[௦-௯]",telu:"[౦-౯]",thai:"[๐-๙]",tibt:"[༠-༩]",latn:"\\d"},qX={arab:[1632,1641],arabext:[1776,1785],bali:[6992,7001],beng:[2534,2543],deva:[2406,2415],fullwide:[65296,65303],gujr:[2790,2799],khmr:[6112,6121],knda:[3302,3311],laoo:[3792,3801],limb:[6470,6479],mlym:[3430,3439],mong:[6160,6169],mymr:[4160,4169],orya:[2918,2927],tamldec:[3046,3055],telu:[3174,3183],thai:[3664,3673],tibt:[3872,3881]},p8=I1.hanidec.replace(/[\[|\]]/g,"").split("");function i8(J){let _=parseInt(J,10);if(isNaN(_)){_="";for(let $=0;$<J.length;$++){let X=J.charCodeAt($);if(J[$].search(I1.hanidec)!==-1)_+=p8.indexOf(J[$]);else for(let A in qX){let[G,K]=qX[A];if(X>=G&&X<=K)_+=X-G}}return parseInt(_,10)}else return _}var F1=new Map;function n8(){F1.clear()}function GJ({numberingSystem:J},_=""){let $=J||"latn",X=F1.get($);if(X===void 0)X=new Map,F1.set($,X);let A=X.get(_);if(A===void 0)A=new RegExp(`${I1[$]}${_}`),X.set(_,A);return A}var VX=()=>Date.now(),yX="system",LX=null,BX=null,UX=null,ZX=60,MX,zX=null;class v{static get now(){return VX}static set now(J){VX=J}static set defaultZone(J){yX=J}static get defaultZone(){return OJ(yX,b0.instance)}static get defaultLocale(){return LX}static set defaultLocale(J){LX=J}static get defaultNumberingSystem(){return BX}static set defaultNumberingSystem(J){BX=J}static get defaultOutputCalendar(){return UX}static set defaultOutputCalendar(J){UX=J}static get defaultWeekSettings(){return zX}static set defaultWeekSettings(J){zX=T1(J)}static get twoDigitCutoffYear(){return ZX}static set twoDigitCutoffYear(J){ZX=J%100}static get throwOnInvalid(){return MX}static set throwOnInvalid(J){MX=J}static resetCaches(){W.resetCache(),qJ.resetCache(),E.resetCache(),n8()}}class e{constructor(J,_){this.reason=J,this.explanation=_}toMessage(){if(this.explanation)return`${this.reason}: ${this.explanation}`;else return this.reason}}var y4=[0,31,59,90,120,151,181,212,243,273,304,334],L4=[0,31,60,91,121,152,182,213,244,274,305,335];function JJ(J,_){return new e("unit out of range",`you specified ${_} (of type ${typeof _}) as a ${J}, which is invalid`)}function x1(J,_,$){let X=new Date(Date.UTC(J,_-1,$));if(J<100&&J>=0)X.setUTCFullYear(X.getUTCFullYear()-1900);let A=X.getUTCDay();return A===0?7:A}function B4(J,_,$){return $+(f0(J)?L4:y4)[_-1]}function U4(J,_){let $=f0(J)?L4:y4,X=$.findIndex((G)=>G<_),A=_-$[X];return{month:X+1,day:A}}function D1(J,_){return(J-_+7)%7+1}function B_(J,_=4,$=1){let{year:X,month:A,day:G}=J,K=B4(X,A,G),Q=D1(x1(X,A,G),$),N=Math.floor((K-Q+14-_)/7),R;if(N<1)R=X-1,N=h0(R,_,$);else if(N>h0(X,_,$))R=X+1,N=1;else R=X;return{weekYear:R,weekNumber:N,weekday:Q,...j_(J)}}function EX(J,_=4,$=1){let{weekYear:X,weekNumber:A,weekday:G}=J,K=D1(x1(X,1,_),$),Q=Q0(X),N=A*7+G-K-7+_,R;if(N<1)R=X-1,N+=Q0(R);else if(N>Q)R=X+1,N-=Q0(X);else R=X;let{month:Y,day:H}=U4(R,N);return{year:R,month:Y,day:H,...j_(J)}}function q1(J){let{year:_,month:$,day:X}=J,A=B4(_,$,X);return{year:_,ordinal:A,...j_(J)}}function jX(J){let{year:_,ordinal:$}=J,{month:X,day:A}=U4(_,$);return{year:_,month:X,day:A,...j_(J)}}function CX(J,_){if(!z(J.localWeekday)||!z(J.localWeekNumber)||!z(J.localWeekYear)){if(!z(J.weekday)||!z(J.weekNumber)||!z(J.weekYear))throw new kJ("Cannot mix locale-based week fields with ISO-based week fields");if(!z(J.localWeekday))J.weekday=J.localWeekday;if(!z(J.localWeekNumber))J.weekNumber=J.localWeekNumber;if(!z(J.localWeekYear))J.weekYear=J.localWeekYear;return delete J.localWeekday,delete J.localWeekNumber,delete J.localWeekYear,{minDaysInFirstWeek:_.getMinDaysInFirstWeek(),startOfWeek:_.getStartOfWeek()}}else return{minDaysInFirstWeek:4,startOfWeek:1}}function r8(J,_=4,$=1){let X=M_(J.weekYear),A=_J(J.weekNumber,1,h0(J.weekYear,_,$)),G=_J(J.weekday,1,7);if(!X)return JJ("weekYear",J.weekYear);else if(!A)return JJ("week",J.weekNumber);else if(!G)return JJ("weekday",J.weekday);else return!1}function o8(J){let _=M_(J.year),$=_J(J.ordinal,1,Q0(J.year));if(!_)return JJ("year",J.year);else if(!$)return JJ("ordinal",J.ordinal);else return!1}function Z4(J){let _=M_(J.year),$=_J(J.month,1,12),X=_J(J.day,1,U_(J.year,J.month));if(!_)return JJ("year",J.year);else if(!$)return JJ("month",J.month);else if(!X)return JJ("day",J.day);else return!1}function M4(J){let{hour:_,minute:$,second:X,millisecond:A}=J,G=_J(_,0,23)||_===24&&$===0&&X===0&&A===0,K=_J($,0,59),Q=_J(X,0,59),N=_J(A,0,999);if(!G)return JJ("hour",_);else if(!K)return JJ("minute",$);else if(!Q)return JJ("second",X);else if(!N)return JJ("millisecond",A);else return!1}function z(J){return typeof J==="undefined"}function FJ(J){return typeof J==="number"}function M_(J){return typeof J==="number"&&J%1===0}function a8(J){return typeof J==="string"}function s8(J){return Object.prototype.toString.call(J)==="[object Date]"}function z4(){try{return typeof Intl!=="undefined"&&!!Intl.RelativeTimeFormat}catch(J){return!1}}function E4(){try{return typeof Intl!=="undefined"&&!!Intl.Locale&&(("weekInfo"in Intl.Locale.prototype)||("getWeekInfo"in Intl.Locale.prototype))}catch(J){return!1}}function t8(J){return Array.isArray(J)?J:[J]}function OX(J,_,$){if(J.length===0)return;return J.reduce((X,A)=>{let G=[_(A),A];if(!X)return G;else if($(X[0],G[0])===X[0])return X;else return G},null)[1]}function e8(J,_){return _.reduce(($,X)=>{return $[X]=J[X],$},{})}function R0(J,_){return Object.prototype.hasOwnProperty.call(J,_)}function T1(J){if(J==null)return null;else if(typeof J!=="object")throw new p("Week settings must be an object");else{if(!_J(J.firstDay,1,7)||!_J(J.minimalDays,1,7)||!Array.isArray(J.weekend)||J.weekend.some((_)=>!_J(_,1,7)))throw new p("Invalid week settings");return{firstDay:J.firstDay,minimalDays:J.minimalDays,weekend:Array.from(J.weekend)}}}function _J(J,_,$){return M_(J)&&J>=_&&J<=$}function J2(J,_){return J-_*Math.floor(J/_)}function f(J,_=2){let $=J<0,X;if($)X="-"+(""+-J).padStart(_,"0");else X=(""+J).padStart(_,"0");return X}function CJ(J){if(z(J)||J===null||J==="")return;else return parseInt(J,10)}function fJ(J){if(z(J)||J===null||J==="")return;else return parseFloat(J)}function v1(J){if(z(J)||J===null||J==="")return;else{let _=parseFloat("0."+J)*1000;return Math.floor(_)}}function h1(J,_,$="round"){let X=10**_;switch($){case"expand":return J>0?Math.ceil(J*X)/X:Math.floor(J*X)/X;case"trunc":return Math.trunc(J*X)/X;case"round":return Math.round(J*X)/X;case"floor":return Math.floor(J*X)/X;case"ceil":return Math.ceil(J*X)/X;default:throw new RangeError(`Value rounding ${$} is out of range`)}}function f0(J){return J%4===0&&(J%100!==0||J%400===0)}function Q0(J){return f0(J)?366:365}function U_(J,_){let $=J2(_-1,12)+1,X=J+(_-$)/12;if($===2)return f0(X)?29:28;else return[31,null,31,30,31,30,31,31,30,31,30,31][$-1]}function z_(J){let _=Date.UTC(J.year,J.month-1,J.day,J.hour,J.minute,J.second,J.millisecond);if(J.year<100&&J.year>=0)_=new Date(_),_.setUTCFullYear(J.year,J.month-1,J.day);return+_}function FX(J,_,$){return-D1(x1(J,1,_),$)+_-1}function h0(J,_=4,$=1){let X=FX(J,_,$),A=FX(J+1,_,$);return(Q0(J)-X+A)/7}function S1(J){if(J>99)return J;else return J>v.twoDigitCutoffYear?1900+J:2000+J}function j4(J,_,$,X=null){let A=new Date(J),G={hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"};if(X)G.timeZone=X;let K={timeZoneName:_,...G},Q=new Intl.DateTimeFormat($,K).formatToParts(A).find((N)=>N.type.toLowerCase()==="timezonename");return Q?Q.value:null}function E_(J,_){let $=parseInt(J,10);if(Number.isNaN($))$=0;let X=parseInt(_,10)||0,A=$<0||Object.is($,-0)?-X:X;return $*60+A}function C4(J){let _=Number(J);if(typeof J==="boolean"||J===""||!Number.isFinite(_))throw new p(`Invalid unit value ${J}`);return _}function Z_(J,_){let $={};for(let X in J)if(R0(J,X)){let A=J[X];if(A===void 0||A===null)continue;$[_(X)]=C4(A)}return $}function v0(J,_){let $=Math.trunc(Math.abs(J/60)),X=Math.trunc(Math.abs(J%60)),A=J>=0?"+":"-";switch(_){case"short":return`${A}${f($,2)}:${f(X,2)}`;case"narrow":return`${A}${$}${X>0?`:${X}`:""}`;case"techie":return`${A}${f($,2)}${f(X,2)}`;default:throw new RangeError(`Value format ${_} is out of range for property format`)}}function j_(J){return e8(J,["hour","minute","second","millisecond"])}var _2=["January","February","March","April","May","June","July","August","September","October","November","December"],O4=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],$2=["J","F","M","A","M","J","J","A","S","O","N","D"];function F4(J){switch(J){case"narrow":return[...$2];case"short":return[...O4];case"long":return[..._2];case"numeric":return["1","2","3","4","5","6","7","8","9","10","11","12"];case"2-digit":return["01","02","03","04","05","06","07","08","09","10","11","12"];default:return null}}var T4=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],S4=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"],X2=["M","T","W","T","F","S","S"];function P4(J){switch(J){case"narrow":return[...X2];case"short":return[...S4];case"long":return[...T4];case"numeric":return["1","2","3","4","5","6","7"];default:return null}}var W4=["AM","PM"],A2=["Before Christ","Anno Domini"],G2=["BC","AD"],K2=["B","A"];function w4(J){switch(J){case"narrow":return[...K2];case"short":return[...G2];case"long":return[...A2];default:return null}}function Q2(J){return W4[J.hour<12?0:1]}function N2(J,_){return P4(_)[J.weekday-1]}function R2(J,_){return F4(_)[J.month-1]}function Y2(J,_){return w4(_)[J.year<0?0:1]}function H2(J,_,$="always",X=!1){let A={years:["year","yr."],quarters:["quarter","qtr."],months:["month","mo."],weeks:["week","wk."],days:["day","day","days"],hours:["hour","hr."],minutes:["minute","min."],seconds:["second","sec."]},G=["hours","minutes","seconds"].indexOf(J)===-1;if($==="auto"&&G){let H=J==="days";switch(_){case 1:return H?"tomorrow":`next ${A[J][0]}`;case-1:return H?"yesterday":`last ${A[J][0]}`;case 0:return H?"today":`this ${A[J][0]}`}}let K=Object.is(_,-0)||_<0,Q=Math.abs(_),N=Q===1,R=A[J],Y=X?N?R[1]:R[2]||R[1]:N?A[J][0]:J;return K?`${Q} ${Y} ago`:`in ${Q} ${Y}`}function TX(J,_){let $="";for(let X of J)if(X.literal)$+=X.val;else $+=_(X.val);return $}var q2={D:L_,DD:lX,DDD:pX,DDDD:iX,t:nX,tt:rX,ttt:oX,tttt:aX,T:sX,TT:tX,TTT:eX,TTTT:J4,f:_4,ff:X4,fff:G4,ffff:Q4,F:$4,FF:A4,FFF:K4,FFFF:N4};class i{static create(J,_={}){return new i(J,_)}static parseFormat(J){let _=null,$="",X=!1,A=[];for(let G=0;G<J.length;G++){let K=J.charAt(G);if(K==="'"){if($.length>0||X)A.push({literal:X||/^\s+$/.test($),val:$===""?"'":$});_=null,$="",X=!X}else if(X)$+=K;else if(K===_)$+=K;else{if($.length>0)A.push({literal:/^\s+$/.test($),val:$});$=K,_=K}}if($.length>0)A.push({literal:X||/^\s+$/.test($),val:$});return A}static macroTokenToFormatOpts(J){return q2[J]}constructor(J,_){this.opts=_,this.loc=J,this.systemLoc=null}formatWithSystemDefault(J,_){if(this.systemLoc===null)this.systemLoc=this.loc.redefaultToSystem();return this.systemLoc.dtFormatter(J,{...this.opts,..._}).format()}dtFormatter(J,_={}){return this.loc.dtFormatter(J,{...this.opts,..._})}formatDateTime(J,_){return this.dtFormatter(J,_).format()}formatDateTimeParts(J,_){return this.dtFormatter(J,_).formatToParts()}formatInterval(J,_){return this.dtFormatter(J.start,_).dtf.formatRange(J.start.toJSDate(),J.end.toJSDate())}resolvedOptions(J,_){return this.dtFormatter(J,_).resolvedOptions()}num(J,_=0,$=void 0){if(this.opts.forceSimple)return f(J,_);let X={...this.opts};if(_>0)X.padTo=_;if($)X.signDisplay=$;return this.loc.numberFormatter(X).format(J)}formatDateTimeFromString(J,_){let $=this.loc.listingMode()==="en",X=this.loc.outputCalendar&&this.loc.outputCalendar!=="gregory",A=(q,V)=>this.loc.extract(J,q,V),G=(q)=>{if(J.isOffsetFixed&&J.offset===0&&q.allowZ)return"Z";return J.isValid?J.zone.formatOffset(J.ts,q.format):""},K=()=>$?Q2(J):A({hour:"numeric",hourCycle:"h12"},"dayperiod"),Q=(q,V)=>$?R2(J,q):A(V?{month:q}:{month:q,day:"numeric"},"month"),N=(q,V)=>$?N2(J,q):A(V?{weekday:q}:{weekday:q,month:"long",day:"numeric"},"weekday"),R=(q)=>{let V=i.macroTokenToFormatOpts(q);if(V)return this.formatWithSystemDefault(J,V);else return q},Y=(q)=>$?Y2(J,q):A({era:q},"era"),H=(q)=>{switch(q){case"S":return this.num(J.millisecond);case"u":case"SSS":return this.num(J.millisecond,3);case"s":return this.num(J.second);case"ss":return this.num(J.second,2);case"uu":return this.num(Math.floor(J.millisecond/10),2);case"uuu":return this.num(Math.floor(J.millisecond/100));case"m":return this.num(J.minute);case"mm":return this.num(J.minute,2);case"h":return this.num(J.hour%12===0?12:J.hour%12);case"hh":return this.num(J.hour%12===0?12:J.hour%12,2);case"H":return this.num(J.hour);case"HH":return this.num(J.hour,2);case"Z":return G({format:"narrow",allowZ:this.opts.allowZ});case"ZZ":return G({format:"short",allowZ:this.opts.allowZ});case"ZZZ":return G({format:"techie",allowZ:this.opts.allowZ});case"ZZZZ":return J.zone.offsetName(J.ts,{format:"short",locale:this.loc.locale});case"ZZZZZ":return J.zone.offsetName(J.ts,{format:"long",locale:this.loc.locale});case"z":return J.zoneName;case"a":return K();case"d":return X?A({day:"numeric"},"day"):this.num(J.day);case"dd":return X?A({day:"2-digit"},"day"):this.num(J.day,2);case"c":return this.num(J.weekday);case"ccc":return N("short",!0);case"cccc":return N("long",!0);case"ccccc":return N("narrow",!0);case"E":return this.num(J.weekday);case"EEE":return N("short",!1);case"EEEE":return N("long",!1);case"EEEEE":return N("narrow",!1);case"L":return X?A({month:"numeric",day:"numeric"},"month"):this.num(J.month);case"LL":return X?A({month:"2-digit",day:"numeric"},"month"):this.num(J.month,2);case"LLL":return Q("short",!0);case"LLLL":return Q("long",!0);case"LLLLL":return Q("narrow",!0);case"M":return X?A({month:"numeric"},"month"):this.num(J.month);case"MM":return X?A({month:"2-digit"},"month"):this.num(J.month,2);case"MMM":return Q("short",!1);case"MMMM":return Q("long",!1);case"MMMMM":return Q("narrow",!1);case"y":return X?A({year:"numeric"},"year"):this.num(J.year);case"yy":return X?A({year:"2-digit"},"year"):this.num(J.year.toString().slice(-2),2);case"yyyy":return X?A({year:"numeric"},"year"):this.num(J.year,4);case"yyyyyy":return X?A({year:"numeric"},"year"):this.num(J.year,6);case"G":return Y("short");case"GG":return Y("long");case"GGGGG":return Y("narrow");case"kk":return this.num(J.weekYear.toString().slice(-2),2);case"kkkk":return this.num(J.weekYear,4);case"W":return this.num(J.weekNumber);case"WW":return this.num(J.weekNumber,2);case"n":return this.num(J.localWeekNumber);case"nn":return this.num(J.localWeekNumber,2);case"ii":return this.num(J.localWeekYear.toString().slice(-2),2);case"iiii":return this.num(J.localWeekYear,4);case"o":return this.num(J.ordinal);case"ooo":return this.num(J.ordinal,3);case"q":return this.num(J.quarter);case"qq":return this.num(J.quarter,2);case"X":return this.num(Math.floor(J.ts/1000));case"x":return this.num(J.ts);default:return R(q)}};return TX(i.parseFormat(_),H)}formatDurationFromString(J,_){let $=this.opts.signMode==="negativeLargestOnly"?-1:1,X=(R)=>{switch(R[0]){case"S":return"milliseconds";case"s":return"seconds";case"m":return"minutes";case"h":return"hours";case"d":return"days";case"w":return"weeks";case"M":return"months";case"y":return"years";default:return null}},A=(R,Y)=>(H)=>{let q=X(H);if(q){let V=Y.isNegativeDuration&&q!==Y.largestUnit?$:1,y;if(this.opts.signMode==="negativeLargestOnly"&&q!==Y.largestUnit)y="never";else if(this.opts.signMode==="all")y="always";else y="auto";return this.num(R.get(q)*V,H.length,y)}else return H},G=i.parseFormat(_),K=G.reduce((R,{literal:Y,val:H})=>Y?R:R.concat(H),[]),Q=J.shiftTo(...K.map(X).filter((R)=>R)),N={isNegativeDuration:Q<0,largestUnit:Object.keys(Q.values)[0]};return TX(G,A(Q,N))}}var I4=/[A-Za-z_+-]{1,256}(?::?\/[A-Za-z0-9_+-]{1,256}(?:\/[A-Za-z0-9_+-]{1,256})?)?/;function Y0(...J){let _=J.reduce(($,X)=>$+X.source,"");return RegExp(`^${_}$`)}function H0(...J){return(_)=>J.reduce(([$,X,A],G)=>{let[K,Q,N]=G(_,A);return[{...$,...K},Q||X,N]},[{},null,1]).slice(0,2)}function q0(J,..._){if(J==null)return[null,null];for(let[$,X]of _){let A=$.exec(J);if(A)return X(A)}return[null,null]}function x4(...J){return(_,$)=>{let X={},A;for(A=0;A<J.length;A++)X[J[A]]=CJ(_[$+A]);return[X,null,$+A]}}var D4=/(?:([Zz])|([+-]\d\d)(?::?(\d\d))?)/,V2=`(?:${D4.source}?(?:\\[(${I4.source})\\])?)?`,b1=/(\d\d)(?::?(\d\d)(?::?(\d\d)(?:[.,](\d{1,30}))?)?)?/,v4=RegExp(`${b1.source}${V2}`),f1=RegExp(`(?:[Tt]${v4.source})?`),y2=/([+-]\d{6}|\d{4})(?:-?(\d\d)(?:-?(\d\d))?)?/,L2=/(\d{4})-?W(\d\d)(?:-?(\d))?/,B2=/(\d{4})-?(\d{3})/,U2=x4("weekYear","weekNumber","weekDay"),Z2=x4("year","ordinal"),M2=/(\d{4})-(\d\d)-(\d\d)/,h4=RegExp(`${b1.source} ?(?:${D4.source}|(${I4.source}))?`),z2=RegExp(`(?: ${h4.source})?`);function N0(J,_,$){let X=J[_];return z(X)?$:CJ(X)}function E2(J,_){return[{year:N0(J,_),month:N0(J,_+1,1),day:N0(J,_+2,1)},null,_+3]}function V0(J,_){return[{hours:N0(J,_,0),minutes:N0(J,_+1,0),seconds:N0(J,_+2,0),milliseconds:v1(J[_+3])},null,_+4]}function g0(J,_){let $=!J[_]&&!J[_+1],X=E_(J[_+1],J[_+2]),A=$?null:n.instance(X);return[{},A,_+3]}function k0(J,_){let $=J[_]?qJ.create(J[_]):null;return[{},$,_+1]}var j2=RegExp(`^T?${b1.source}$`),C2=/^-?P(?:(?:(-?\d{1,20}(?:\.\d{1,20})?)Y)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20}(?:\.\d{1,20})?)W)?(?:(-?\d{1,20}(?:\.\d{1,20})?)D)?(?:T(?:(-?\d{1,20}(?:\.\d{1,20})?)H)?(?:(-?\d{1,20}(?:\.\d{1,20})?)M)?(?:(-?\d{1,20})(?:[.,](-?\d{1,20}))?S)?)?)$/;function O2(J){let[_,$,X,A,G,K,Q,N,R]=J,Y=_[0]==="-",H=N&&N[0]==="-",q=(V,y=!1)=>V!==void 0&&(y||V&&Y)?-V:V;return[{years:q(fJ($)),months:q(fJ(X)),weeks:q(fJ(A)),days:q(fJ(G)),hours:q(fJ(K)),minutes:q(fJ(Q)),seconds:q(fJ(N),N==="-0"),milliseconds:q(v1(R),H)}]}var F2={GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function g1(J,_,$,X,A,G,K){let Q={year:_.length===2?S1(CJ(_)):CJ(_),month:O4.indexOf($)+1,day:CJ(X),hour:CJ(A),minute:CJ(G)};if(K)Q.second=CJ(K);if(J)Q.weekday=J.length>3?T4.indexOf(J)+1:S4.indexOf(J)+1;return Q}var T2=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|(?:([+-]\d\d)(\d\d)))$/;function S2(J){let[,_,$,X,A,G,K,Q,N,R,Y,H]=J,q=g1(_,A,X,$,G,K,Q),V;if(N)V=F2[N];else if(R)V=0;else V=E_(Y,H);return[q,new n(V)]}function P2(J){return J.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").trim()}var W2=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d\d) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d\d):(\d\d):(\d\d) GMT$/,w2=/^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d\d)-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d\d) (\d\d):(\d\d):(\d\d) GMT$/,I2=/^(Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( \d|\d\d) (\d\d):(\d\d):(\d\d) (\d{4})$/;function SX(J){let[,_,$,X,A,G,K,Q]=J;return[g1(_,A,X,$,G,K,Q),n.utcInstance]}function x2(J){let[,_,$,X,A,G,K,Q]=J;return[g1(_,Q,$,X,A,G,K),n.utcInstance]}var D2=Y0(y2,f1),v2=Y0(L2,f1),h2=Y0(B2,f1),b2=Y0(v4),b4=H0(E2,V0,g0,k0),f2=H0(U2,V0,g0,k0),g2=H0(Z2,V0,g0,k0),k2=H0(V0,g0,k0);function m2(J){return q0(J,[D2,b4],[v2,f2],[h2,g2],[b2,k2])}function u2(J){return q0(P2(J),[T2,S2])}function c2(J){return q0(J,[W2,SX],[w2,SX],[I2,x2])}function d2(J){return q0(J,[C2,O2])}var l2=H0(V0);function p2(J){return q0(J,[j2,l2])}var i2=Y0(M2,z2),n2=Y0(h4),r2=H0(V0,g0,k0);function o2(J){return q0(J,[i2,b4],[n2,r2])}var PX="Invalid Duration",f4={weeks:{days:7,hours:168,minutes:10080,seconds:604800,milliseconds:604800000},days:{hours:24,minutes:1440,seconds:86400,milliseconds:86400000},hours:{minutes:60,seconds:3600,milliseconds:3600000},minutes:{seconds:60,milliseconds:60000},seconds:{milliseconds:1000}},a2={years:{quarters:4,months:12,weeks:52,days:365,hours:8760,minutes:525600,seconds:31536000,milliseconds:31536000000},quarters:{months:3,weeks:13,days:91,hours:2184,minutes:131040,seconds:7862400,milliseconds:7862400000},months:{weeks:4,days:30,hours:720,minutes:43200,seconds:2592000,milliseconds:2592000000},...f4},t=365.2425,X0=30.436875,s2={years:{quarters:4,months:12,weeks:t/7,days:t,hours:t*24,minutes:t*24*60,seconds:t*24*60*60,milliseconds:t*24*60*60*1000},quarters:{months:3,weeks:t/28,days:t/4,hours:t*24/4,minutes:t*24*60/4,seconds:t*24*60*60/4,milliseconds:t*24*60*60*1000/4},months:{weeks:X0/7,days:X0,hours:X0*24,minutes:X0*24*60,seconds:X0*24*60*60,milliseconds:X0*24*60*60*1000},...f4},mJ=["years","quarters","months","weeks","days","hours","minutes","seconds","milliseconds"],t2=mJ.slice(0).reverse();function LJ(J,_,$=!1){let X={values:$?_.values:{...J.values,..._.values||{}},loc:J.loc.clone(_.loc),conversionAccuracy:_.conversionAccuracy||J.conversionAccuracy,matrix:_.matrix||J.matrix};return new F(X)}function g4(J,_){var $;let X=($=_.milliseconds)!=null?$:0;for(let A of t2.slice(1))if(_[A])X+=_[A]*J[A].milliseconds;return X}function WX(J,_){let $=g4(J,_)<0?-1:1;mJ.reduceRight((X,A)=>{if(!z(_[A])){if(X){let G=_[X]*$,K=J[A][X],Q=Math.floor(G/K);_[A]+=Q*$,_[X]-=Q*K*$}return A}else return X},null),mJ.reduce((X,A)=>{if(!z(_[A])){if(X){let G=_[X]%1;_[X]-=G,_[A]+=G*J[X][A]}return A}else return X},null)}function wX(J){let _={};for(let[$,X]of Object.entries(J))if(X!==0)_[$]=X;return _}class F{constructor(J){let _=J.conversionAccuracy==="longterm"||!1,$=_?s2:a2;if(J.matrix)$=J.matrix;this.values=J.values,this.loc=J.loc||W.create(),this.conversionAccuracy=_?"longterm":"casual",this.invalid=J.invalid||null,this.matrix=$,this.isLuxonDuration=!0}static fromMillis(J,_){return F.fromObject({milliseconds:J},_)}static fromObject(J,_={}){if(J==null||typeof J!=="object")throw new p(`Duration.fromObject: argument expected to be an object, got ${J===null?"null":typeof J}`);return new F({values:Z_(J,F.normalizeUnit),loc:W.fromObject(_),conversionAccuracy:_.conversionAccuracy,matrix:_.matrix})}static fromDurationLike(J){if(FJ(J))return F.fromMillis(J);else if(F.isDuration(J))return J;else if(typeof J==="object")return F.fromObject(J);else throw new p(`Unknown duration argument ${J} of type ${typeof J}`)}static fromISO(J,_){let[$]=d2(J);if($)return F.fromObject($,_);else return F.invalid("unparsable",`the input "${J}" can't be parsed as ISO 8601`)}static fromISOTime(J,_){let[$]=p2(J);if($)return F.fromObject($,_);else return F.invalid("unparsable",`the input "${J}" can't be parsed as ISO 8601`)}static invalid(J,_=null){if(!J)throw new p("need to specify a reason the Duration is invalid");let $=J instanceof e?J:new e(J,_);if(v.throwOnInvalid)throw new dX($);else return new F({invalid:$})}static normalizeUnit(J){let _={year:"years",years:"years",quarter:"quarters",quarters:"quarters",month:"months",months:"months",week:"weeks",weeks:"weeks",day:"days",days:"days",hour:"hours",hours:"hours",minute:"minutes",minutes:"minutes",second:"seconds",seconds:"seconds",millisecond:"milliseconds",milliseconds:"milliseconds"}[J?J.toLowerCase():J];if(!_)throw new W1(J);return _}static isDuration(J){return J&&J.isLuxonDuration||!1}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}toFormat(J,_={}){let $={..._,floor:_.round!==!1&&_.floor!==!1};return this.isValid?i.create(this.loc,$).formatDurationFromString(this,J):PX}toHuman(J={}){if(!this.isValid)return PX;let _=J.showZeros!==!1,$=mJ.map((X)=>{let A=this.values[X];if(z(A)||A===0&&!_)return null;return this.loc.numberFormatter({style:"unit",unitDisplay:"long",...J,unit:X.slice(0,-1)}).format(A)}).filter((X)=>X);return this.loc.listFormatter({type:"conjunction",style:J.listStyle||"narrow",...J}).format($)}toObject(){if(!this.isValid)return{};return{...this.values}}toISO(){if(!this.isValid)return null;let J="P";if(this.years!==0)J+=this.years+"Y";if(this.months!==0||this.quarters!==0)J+=this.months+this.quarters*3+"M";if(this.weeks!==0)J+=this.weeks+"W";if(this.days!==0)J+=this.days+"D";if(this.hours!==0||this.minutes!==0||this.seconds!==0||this.milliseconds!==0)J+="T";if(this.hours!==0)J+=this.hours+"H";if(this.minutes!==0)J+=this.minutes+"M";if(this.seconds!==0||this.milliseconds!==0)J+=h1(this.seconds+this.milliseconds/1000,3)+"S";if(J==="P")J+="T0S";return J}toISOTime(J={}){if(!this.isValid)return null;let _=this.toMillis();if(_<0||_>=86400000)return null;return J={suppressMilliseconds:!1,suppressSeconds:!1,includePrefix:!1,format:"extended",...J,includeOffset:!1},E.fromMillis(_,{zone:"UTC"}).toISOTime(J)}toJSON(){return this.toISO()}toString(){return this.toISO()}[Symbol.for("nodejs.util.inspect.custom")](){if(this.isValid)return`Duration { values: ${JSON.stringify(this.values)} }`;else return`Duration { Invalid, reason: ${this.invalidReason} }`}toMillis(){if(!this.isValid)return NaN;return g4(this.matrix,this.values)}valueOf(){return this.toMillis()}plus(J){if(!this.isValid)return this;let _=F.fromDurationLike(J),$={};for(let X of mJ)if(R0(_.values,X)||R0(this.values,X))$[X]=_.get(X)+this.get(X);return LJ(this,{values:$},!0)}minus(J){if(!this.isValid)return this;let _=F.fromDurationLike(J);return this.plus(_.negate())}mapUnits(J){if(!this.isValid)return this;let _={};for(let $ of Object.keys(this.values))_[$]=C4(J(this.values[$],$));return LJ(this,{values:_},!0)}get(J){return this[F.normalizeUnit(J)]}set(J){if(!this.isValid)return this;let _={...this.values,...Z_(J,F.normalizeUnit)};return LJ(this,{values:_})}reconfigure({locale:J,numberingSystem:_,conversionAccuracy:$,matrix:X}={}){let G={loc:this.loc.clone({locale:J,numberingSystem:_}),matrix:X,conversionAccuracy:$};return LJ(this,G)}as(J){return this.isValid?this.shiftTo(J).get(J):NaN}normalize(){if(!this.isValid)return this;let J=this.toObject();return WX(this.matrix,J),LJ(this,{values:J},!0)}rescale(){if(!this.isValid)return this;let J=wX(this.normalize().shiftToAll().toObject());return LJ(this,{values:J},!0)}shiftTo(...J){if(!this.isValid)return this;if(J.length===0)return this;J=J.map((G)=>F.normalizeUnit(G));let _={},$={},X=this.toObject(),A;for(let G of mJ)if(J.indexOf(G)>=0){A=G;let K=0;for(let N in $)K+=this.matrix[N][G]*$[N],$[N]=0;if(FJ(X[G]))K+=X[G];let Q=Math.trunc(K);_[G]=Q,$[G]=(K*1000-Q*1000)/1000}else if(FJ(X[G]))$[G]=X[G];for(let G in $)if($[G]!==0)_[A]+=G===A?$[G]:$[G]/this.matrix[A][G];return WX(this.matrix,_),LJ(this,{values:_},!0)}shiftToAll(){if(!this.isValid)return this;return this.shiftTo("years","months","weeks","days","hours","minutes","seconds","milliseconds")}negate(){if(!this.isValid)return this;let J={};for(let _ of Object.keys(this.values))J[_]=this.values[_]===0?0:-this.values[_];return LJ(this,{values:J},!0)}removeZeros(){if(!this.isValid)return this;let J=wX(this.values);return LJ(this,{values:J},!0)}get years(){return this.isValid?this.values.years||0:NaN}get quarters(){return this.isValid?this.values.quarters||0:NaN}get months(){return this.isValid?this.values.months||0:NaN}get weeks(){return this.isValid?this.values.weeks||0:NaN}get days(){return this.isValid?this.values.days||0:NaN}get hours(){return this.isValid?this.values.hours||0:NaN}get minutes(){return this.isValid?this.values.minutes||0:NaN}get seconds(){return this.isValid?this.values.seconds||0:NaN}get milliseconds(){return this.isValid?this.values.milliseconds||0:NaN}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}equals(J){if(!this.isValid||!J.isValid)return!1;if(!this.loc.equals(J.loc))return!1;function _($,X){if($===void 0||$===0)return X===void 0||X===0;return $===X}for(let $ of mJ)if(!_(this.values[$],J.values[$]))return!1;return!0}}var A0="Invalid Interval";function e2(J,_){if(!J||!J.isValid)return h.invalid("missing or invalid start");else if(!_||!_.isValid)return h.invalid("missing or invalid end");else if(_<J)return h.invalid("end before start",`The end of an interval must be after its start, but you had start=${J.toISO()} and end=${_.toISO()}`);else return null}class h{constructor(J){this.s=J.start,this.e=J.end,this.invalid=J.invalid||null,this.isLuxonInterval=!0}static invalid(J,_=null){if(!J)throw new p("need to specify a reason the Interval is invalid");let $=J instanceof e?J:new e(J,_);if(v.throwOnInvalid)throw new cX($);else return new h({invalid:$})}static fromDateTimes(J,_){let $=w0(J),X=w0(_),A=e2($,X);if(A==null)return new h({start:$,end:X});else return A}static after(J,_){let $=F.fromDurationLike(_),X=w0(J);return h.fromDateTimes(X,X.plus($))}static before(J,_){let $=F.fromDurationLike(_),X=w0(J);return h.fromDateTimes(X.minus($),X)}static fromISO(J,_){let[$,X]=(J||"").split("/",2);if($&&X){let A,G;try{A=E.fromISO($,_),G=A.isValid}catch(N){G=!1}let K,Q;try{K=E.fromISO(X,_),Q=K.isValid}catch(N){Q=!1}if(G&&Q)return h.fromDateTimes(A,K);if(G){let N=F.fromISO(X,_);if(N.isValid)return h.after(A,N)}else if(Q){let N=F.fromISO($,_);if(N.isValid)return h.before(K,N)}}return h.invalid("unparsable",`the input "${J}" can't be parsed as ISO 8601`)}static isInterval(J){return J&&J.isLuxonInterval||!1}get start(){return this.isValid?this.s:null}get end(){return this.isValid?this.e:null}get lastDateTime(){return this.isValid?this.e?this.e.minus(1):null:null}get isValid(){return this.invalidReason===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}length(J="milliseconds"){return this.isValid?this.toDuration(...[J]).get(J):NaN}count(J="milliseconds",_){if(!this.isValid)return NaN;let $=this.start.startOf(J,_),X;if(_!=null&&_.useLocaleWeeks)X=this.end.reconfigure({locale:$.locale});else X=this.end;return X=X.startOf(J,_),Math.floor(X.diff($,J).get(J))+(X.valueOf()!==this.end.valueOf())}hasSame(J){return this.isValid?this.isEmpty()||this.e.minus(1).hasSame(this.s,J):!1}isEmpty(){return this.s.valueOf()===this.e.valueOf()}isAfter(J){if(!this.isValid)return!1;return this.s>J}isBefore(J){if(!this.isValid)return!1;return this.e<=J}contains(J){if(!this.isValid)return!1;return this.s<=J&&this.e>J}set({start:J,end:_}={}){if(!this.isValid)return this;return h.fromDateTimes(J||this.s,_||this.e)}splitAt(...J){if(!this.isValid)return[];let _=J.map(w0).filter((G)=>this.contains(G)).sort((G,K)=>G.toMillis()-K.toMillis()),$=[],{s:X}=this,A=0;while(X<this.e){let G=_[A]||this.e,K=+G>+this.e?this.e:G;$.push(h.fromDateTimes(X,K)),X=K,A+=1}return $}splitBy(J){let _=F.fromDurationLike(J);if(!this.isValid||!_.isValid||_.as("milliseconds")===0)return[];let{s:$}=this,X=1,A,G=[];while($<this.e){let K=this.start.plus(_.mapUnits((Q)=>Q*X));A=+K>+this.e?this.e:K,G.push(h.fromDateTimes($,A)),$=A,X+=1}return G}divideEqually(J){if(!this.isValid)return[];return this.splitBy(this.length()/J).slice(0,J)}overlaps(J){return this.e>J.s&&this.s<J.e}abutsStart(J){if(!this.isValid)return!1;return+this.e===+J.s}abutsEnd(J){if(!this.isValid)return!1;return+J.e===+this.s}engulfs(J){if(!this.isValid)return!1;return this.s<=J.s&&this.e>=J.e}equals(J){if(!this.isValid||!J.isValid)return!1;return this.s.equals(J.s)&&this.e.equals(J.e)}intersection(J){if(!this.isValid)return this;let _=this.s>J.s?this.s:J.s,$=this.e<J.e?this.e:J.e;if(_>=$)return null;else return h.fromDateTimes(_,$)}union(J){if(!this.isValid)return this;let _=this.s<J.s?this.s:J.s,$=this.e>J.e?this.e:J.e;return h.fromDateTimes(_,$)}static merge(J){let[_,$]=J.sort((X,A)=>X.s-A.s).reduce(([X,A],G)=>{if(!A)return[X,G];else if(A.overlaps(G)||A.abutsStart(G))return[X,A.union(G)];else return[X.concat([A]),G]},[[],null]);if($)_.push($);return _}static xor(J){let _=null,$=0,X=[],A=J.map((Q)=>[{time:Q.s,type:"s"},{time:Q.e,type:"e"}]),G=Array.prototype.concat(...A),K=G.sort((Q,N)=>Q.time-N.time);for(let Q of K)if($+=Q.type==="s"?1:-1,$===1)_=Q.time;else{if(_&&+_!==+Q.time)X.push(h.fromDateTimes(_,Q.time));_=null}return h.merge(X)}difference(...J){return h.xor([this].concat(J)).map((_)=>this.intersection(_)).filter((_)=>_&&!_.isEmpty())}toString(){if(!this.isValid)return A0;return`[${this.s.toISO()} – ${this.e.toISO()})`}[Symbol.for("nodejs.util.inspect.custom")](){if(this.isValid)return`Interval { start: ${this.s.toISO()}, end: ${this.e.toISO()} }`;else return`Interval { Invalid, reason: ${this.invalidReason} }`}toLocaleString(J=L_,_={}){return this.isValid?i.create(this.s.loc.clone(_),J).formatInterval(this):A0}toISO(J){if(!this.isValid)return A0;return`${this.s.toISO(J)}/${this.e.toISO(J)}`}toISODate(){if(!this.isValid)return A0;return`${this.s.toISODate()}/${this.e.toISODate()}`}toISOTime(J){if(!this.isValid)return A0;return`${this.s.toISOTime(J)}/${this.e.toISOTime(J)}`}toFormat(J,{separator:_=" – "}={}){if(!this.isValid)return A0;return`${this.s.toFormat(J)}${_}${this.e.toFormat(J)}`}toDuration(J,_){if(!this.isValid)return F.invalid(this.invalidReason);return this.e.diff(this.s,J,_)}mapEndpoints(J){return h.fromDateTimes(J(this.s),J(this.e))}}class K0{static hasDST(J=v.defaultZone){let _=E.now().setZone(J).set({month:12});return!J.isUniversal&&_.offset!==_.set({month:6}).offset}static isValidIANAZone(J){return qJ.isValidZone(J)}static normalizeZone(J){return OJ(J,v.defaultZone)}static getStartOfWeek({locale:J=null,locObj:_=null}={}){return(_||W.create(J)).getStartOfWeek()}static getMinimumDaysInFirstWeek({locale:J=null,locObj:_=null}={}){return(_||W.create(J)).getMinDaysInFirstWeek()}static getWeekendWeekdays({locale:J=null,locObj:_=null}={}){return(_||W.create(J)).getWeekendDays().slice()}static months(J="long",{locale:_=null,numberingSystem:$=null,locObj:X=null,outputCalendar:A="gregory"}={}){return(X||W.create(_,$,A)).months(J)}static monthsFormat(J="long",{locale:_=null,numberingSystem:$=null,locObj:X=null,outputCalendar:A="gregory"}={}){return(X||W.create(_,$,A)).months(J,!0)}static weekdays(J="long",{locale:_=null,numberingSystem:$=null,locObj:X=null}={}){return(X||W.create(_,$,null)).weekdays(J)}static weekdaysFormat(J="long",{locale:_=null,numberingSystem:$=null,locObj:X=null}={}){return(X||W.create(_,$,null)).weekdays(J,!0)}static meridiems({locale:J=null}={}){return W.create(J).meridiems()}static eras(J="short",{locale:_=null}={}){return W.create(_,null,"gregory").eras(J)}static features(){return{relative:z4(),localeWeek:E4()}}}function IX(J,_){let $=(A)=>A.toUTC(0,{keepLocalTime:!0}).startOf("day").valueOf(),X=$(_)-$(J);return Math.floor(F.fromMillis(X).as("days"))}function JA(J,_,$){let X=[["years",(N,R)=>R.year-N.year],["quarters",(N,R)=>R.quarter-N.quarter+(R.year-N.year)*4],["months",(N,R)=>R.month-N.month+(R.year-N.year)*12],["weeks",(N,R)=>{let Y=IX(N,R);return(Y-Y%7)/7}],["days",IX]],A={},G=J,K,Q;for(let[N,R]of X)if($.indexOf(N)>=0)if(K=N,A[N]=R(J,_),Q=G.plus(A),Q>_){if(A[N]--,J=G.plus(A),J>_)Q=J,A[N]--,J=G.plus(A)}else J=Q;return[J,A,Q,K]}function _A(J,_,$,X){let[A,G,K,Q]=JA(J,_,$),N=_-A,R=$.filter((H)=>["hours","minutes","seconds","milliseconds"].indexOf(H)>=0);if(R.length===0){if(K<_)K=A.plus({[Q]:1});if(K!==A)G[Q]=(G[Q]||0)+N/(K-A)}let Y=F.fromObject(G,X);if(R.length>0)return F.fromMillis(N,X).shiftTo(...R).plus(Y);else return Y}var $A="missing Intl.DateTimeFormat.formatToParts support";function T(J,_=($)=>$){return{regex:J,deser:([$])=>_(i8($))}}var XA=String.fromCharCode(160),k4=`[ ${XA}]`,m4=new RegExp(k4,"g");function AA(J){return J.replace(/\./g,"\\.?").replace(m4,k4)}function xX(J){return J.replace(/\./g,"").replace(m4," ").toLowerCase()}function KJ(J,_){if(J===null)return null;else return{regex:RegExp(J.map(AA).join("|")),deser:([$])=>J.findIndex((X)=>xX($)===xX(X))+_}}function DX(J,_){return{regex:J,deser:([,$,X])=>E_($,X),groups:_}}function R_(J){return{regex:J,deser:([_])=>_}}function GA(J){return J.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g,"\\$&")}function KA(J,_){let $=GJ(_),X=GJ(_,"{2}"),A=GJ(_,"{3}"),G=GJ(_,"{4}"),K=GJ(_,"{6}"),Q=GJ(_,"{1,2}"),N=GJ(_,"{1,3}"),R=GJ(_,"{1,6}"),Y=GJ(_,"{1,9}"),H=GJ(_,"{2,4}"),q=GJ(_,"{4,6}"),V=(M)=>({regex:RegExp(GA(M.val)),deser:([Z])=>Z,literal:!0}),B=((M)=>{if(J.literal)return V(M);switch(M.val){case"G":return KJ(_.eras("short"),0);case"GG":return KJ(_.eras("long"),0);case"y":return T(R);case"yy":return T(H,S1);case"yyyy":return T(G);case"yyyyy":return T(q);case"yyyyyy":return T(K);case"M":return T(Q);case"MM":return T(X);case"MMM":return KJ(_.months("short",!0),1);case"MMMM":return KJ(_.months("long",!0),1);case"L":return T(Q);case"LL":return T(X);case"LLL":return KJ(_.months("short",!1),1);case"LLLL":return KJ(_.months("long",!1),1);case"d":return T(Q);case"dd":return T(X);case"o":return T(N);case"ooo":return T(A);case"HH":return T(X);case"H":return T(Q);case"hh":return T(X);case"h":return T(Q);case"mm":return T(X);case"m":return T(Q);case"q":return T(Q);case"qq":return T(X);case"s":return T(Q);case"ss":return T(X);case"S":return T(N);case"SSS":return T(A);case"u":return R_(Y);case"uu":return R_(Q);case"uuu":return T($);case"a":return KJ(_.meridiems(),0);case"kkkk":return T(G);case"kk":return T(H,S1);case"W":return T(Q);case"WW":return T(X);case"E":case"c":return T($);case"EEE":return KJ(_.weekdays("short",!1),1);case"EEEE":return KJ(_.weekdays("long",!1),1);case"ccc":return KJ(_.weekdays("short",!0),1);case"cccc":return KJ(_.weekdays("long",!0),1);case"Z":case"ZZ":return DX(new RegExp(`([+-]${Q.source})(?::(${X.source}))?`),2);case"ZZZ":return DX(new RegExp(`([+-]${Q.source})(${X.source})?`),2);case"z":return R_(/[a-z_+-/]{1,256}?/i);case" ":return R_(/[^\S\n\r]/);default:return V(M)}})(J)||{invalidReason:$A};return B.token=J,B}var QA={year:{"2-digit":"yy",numeric:"yyyyy"},month:{numeric:"M","2-digit":"MM",short:"MMM",long:"MMMM"},day:{numeric:"d","2-digit":"dd"},weekday:{short:"EEE",long:"EEEE"},dayperiod:"a",dayPeriod:"a",hour12:{numeric:"h","2-digit":"hh"},hour24:{numeric:"H","2-digit":"HH"},minute:{numeric:"m","2-digit":"mm"},second:{numeric:"s","2-digit":"ss"},timeZoneName:{long:"ZZZZZ",short:"ZZZ"}};function NA(J,_,$){let{type:X,value:A}=J;if(X==="literal"){let N=/^\s+$/.test(A);return{literal:!N,val:N?" ":A}}let G=_[X],K=X;if(X==="hour")if(_.hour12!=null)K=_.hour12?"hour12":"hour24";else if(_.hourCycle!=null)if(_.hourCycle==="h11"||_.hourCycle==="h12")K="hour12";else K="hour24";else K=$.hour12?"hour12":"hour24";let Q=QA[K];if(typeof Q==="object")Q=Q[G];if(Q)return{literal:!1,val:Q};return}function RA(J){return[`^${J.map(($)=>$.regex).reduce(($,X)=>`${$}(${X.source})`,"")}$`,J]}function YA(J,_,$){let X=J.match(_);if(X){let A={},G=1;for(let K in $)if(R0($,K)){let Q=$[K],N=Q.groups?Q.groups+1:1;if(!Q.literal&&Q.token)A[Q.token.val[0]]=Q.deser(X.slice(G,G+N));G+=N}return[X,A]}else return[X,{}]}function HA(J){let _=(G)=>{switch(G){case"S":return"millisecond";case"s":return"second";case"m":return"minute";case"h":case"H":return"hour";case"d":return"day";case"o":return"ordinal";case"L":case"M":return"month";case"y":return"year";case"E":case"c":return"weekday";case"W":return"weekNumber";case"k":return"weekYear";case"q":return"quarter";default:return null}},$=null,X;if(!z(J.z))$=qJ.create(J.z);if(!z(J.Z)){if(!$)$=new n(J.Z);X=J.Z}if(!z(J.q))J.M=(J.q-1)*3+1;if(!z(J.h)){if(J.h<12&&J.a===1)J.h+=12;else if(J.h===12&&J.a===0)J.h=0}if(J.G===0&&J.y)J.y=-J.y;if(!z(J.u))J.S=v1(J.u);return[Object.keys(J).reduce((G,K)=>{let Q=_(K);if(Q)G[Q]=J[K];return G},{}),$,X]}var V1=null;function qA(){if(!V1)V1=E.fromMillis(1555555555555);return V1}function VA(J,_){if(J.literal)return J;let $=i.macroTokenToFormatOpts(J.val),X=d4($,_);if(X==null||X.includes(void 0))return J;return X}function u4(J,_){return Array.prototype.concat(...J.map(($)=>VA($,_)))}class k1{constructor(J,_){if(this.locale=J,this.format=_,this.tokens=u4(i.parseFormat(_),J),this.units=this.tokens.map(($)=>KA($,J)),this.disqualifyingUnit=this.units.find(($)=>$.invalidReason),!this.disqualifyingUnit){let[$,X]=RA(this.units);this.regex=RegExp($,"i"),this.handlers=X}}explainFromTokens(J){if(!this.isValid)return{input:J,tokens:this.tokens,invalidReason:this.invalidReason};else{let[_,$]=YA(J,this.regex,this.handlers),[X,A,G]=$?HA($):[null,null,void 0];if(R0($,"a")&&R0($,"H"))throw new kJ("Can't include meridiem when specifying 24-hour format");return{input:J,tokens:this.tokens,regex:this.regex,rawMatches:_,matches:$,result:X,zone:A,specificOffset:G}}}get isValid(){return!this.disqualifyingUnit}get invalidReason(){return this.disqualifyingUnit?this.disqualifyingUnit.invalidReason:null}}function c4(J,_,$){return new k1(J,$).explainFromTokens(_)}function yA(J,_,$){let{result:X,zone:A,specificOffset:G,invalidReason:K}=c4(J,_,$);return[X,A,G,K]}function d4(J,_){if(!J)return null;let X=i.create(_,J).dtFormatter(qA()),A=X.formatToParts(),G=X.resolvedOptions();return A.map((K)=>NA(K,J,G))}var y1="Invalid DateTime",vX=8640000000000000;function x0(J){return new e("unsupported zone",`the zone "${J.name}" is not supported`)}function L1(J){if(J.weekData===null)J.weekData=B_(J.c);return J.weekData}function B1(J){if(J.localWeekData===null)J.localWeekData=B_(J.c,J.loc.getMinDaysInFirstWeek(),J.loc.getStartOfWeek());return J.localWeekData}function gJ(J,_){let $={ts:J.ts,zone:J.zone,c:J.c,o:J.o,loc:J.loc,invalid:J.invalid};return new E({...$,..._,old:$})}function l4(J,_,$){let X=J-_*60*1000,A=$.offset(X);if(_===A)return[X,_];X-=(A-_)*60*1000;let G=$.offset(X);if(A===G)return[X,A];return[J-Math.min(A,G)*60*1000,Math.max(A,G)]}function Y_(J,_){J+=_*60*1000;let $=new Date(J);return{year:$.getUTCFullYear(),month:$.getUTCMonth()+1,day:$.getUTCDate(),hour:$.getUTCHours(),minute:$.getUTCMinutes(),second:$.getUTCSeconds(),millisecond:$.getUTCMilliseconds()}}function q_(J,_,$){return l4(z_(J),_,$)}function hX(J,_){let $=J.o,X=J.c.year+Math.trunc(_.years),A=J.c.month+Math.trunc(_.months)+Math.trunc(_.quarters)*3,G={...J.c,year:X,month:A,day:Math.min(J.c.day,U_(X,A))+Math.trunc(_.days)+Math.trunc(_.weeks)*7},K=F.fromObject({years:_.years-Math.trunc(_.years),quarters:_.quarters-Math.trunc(_.quarters),months:_.months-Math.trunc(_.months),weeks:_.weeks-Math.trunc(_.weeks),days:_.days-Math.trunc(_.days),hours:_.hours,minutes:_.minutes,seconds:_.seconds,milliseconds:_.milliseconds}).as("milliseconds"),Q=z_(G),[N,R]=l4(Q,$,J.zone);if(K!==0)N+=K,R=J.zone.offset(N);return{ts:N,o:R}}function G0(J,_,$,X,A,G){let{setZone:K,zone:Q}=$;if(J&&Object.keys(J).length!==0||_){let N=_||Q,R=E.fromObject(J,{...$,zone:N,specificOffset:G});return K?R:R.setZone(Q)}else return E.invalid(new e("unparsable",`the input "${A}" can't be parsed as ${X}`))}function H_(J,_,$=!0){return J.isValid?i.create(W.create("en-US"),{allowZ:$,forceSimple:!0}).formatDateTimeFromString(J,_):null}function U1(J,_,$){let X=J.c.year>9999||J.c.year<0,A="";if(X&&J.c.year>=0)A+="+";if(A+=f(J.c.year,X?6:4),$==="year")return A;if(_){if(A+="-",A+=f(J.c.month),$==="month")return A;A+="-"}else if(A+=f(J.c.month),$==="month")return A;return A+=f(J.c.day),A}function bX(J,_,$,X,A,G,K){let Q=!$||J.c.millisecond!==0||J.c.second!==0,N="";switch(K){case"day":case"month":case"year":break;default:if(N+=f(J.c.hour),K==="hour")break;if(_){if(N+=":",N+=f(J.c.minute),K==="minute")break;if(Q)N+=":",N+=f(J.c.second)}else{if(N+=f(J.c.minute),K==="minute")break;if(Q)N+=f(J.c.second)}if(K==="second")break;if(Q&&(!X||J.c.millisecond!==0))N+=".",N+=f(J.c.millisecond,3)}if(A)if(J.isOffsetFixed&&J.offset===0&&!G)N+="Z";else if(J.o<0)N+="-",N+=f(Math.trunc(-J.o/60)),N+=":",N+=f(Math.trunc(-J.o%60));else N+="+",N+=f(Math.trunc(J.o/60)),N+=":",N+=f(Math.trunc(J.o%60));if(G)N+="["+J.zone.ianaName+"]";return N}var p4={month:1,day:1,hour:0,minute:0,second:0,millisecond:0},LA={weekNumber:1,weekday:1,hour:0,minute:0,second:0,millisecond:0},BA={ordinal:1,hour:0,minute:0,second:0,millisecond:0},V_=["year","month","day","hour","minute","second","millisecond"],UA=["weekYear","weekNumber","weekday","hour","minute","second","millisecond"],ZA=["year","ordinal","hour","minute","second","millisecond"];function y_(J){let _={year:"year",years:"year",month:"month",months:"month",day:"day",days:"day",hour:"hour",hours:"hour",minute:"minute",minutes:"minute",quarter:"quarter",quarters:"quarter",second:"second",seconds:"second",millisecond:"millisecond",milliseconds:"millisecond",weekday:"weekday",weekdays:"weekday",weeknumber:"weekNumber",weeksnumber:"weekNumber",weeknumbers:"weekNumber",weekyear:"weekYear",weekyears:"weekYear",ordinal:"ordinal"}[J.toLowerCase()];if(!_)throw new W1(J);return _}function fX(J){switch(J.toLowerCase()){case"localweekday":case"localweekdays":return"localWeekday";case"localweeknumber":case"localweeknumbers":return"localWeekNumber";case"localweekyear":case"localweekyears":return"localWeekYear";default:return y_(J)}}function MA(J){if(D0===void 0)D0=v.now();if(J.type!=="iana")return J.offset(D0);let _=J.name,$=P1.get(_);if($===void 0)$=J.offset(D0),P1.set(_,$);return $}function gX(J,_){let $=OJ(_.zone,v.defaultZone);if(!$.isValid)return E.invalid(x0($));let X=W.fromObject(_),A,G;if(!z(J.year)){for(let N of V_)if(z(J[N]))J[N]=p4[N];let K=Z4(J)||M4(J);if(K)return E.invalid(K);let Q=MA($);[A,G]=q_(J,Q,$)}else A=v.now();return new E({ts:A,zone:$,loc:X,o:G})}function kX(J,_,$){let X=z($.round)?!0:$.round,A=z($.rounding)?"trunc":$.rounding,G=(Q,N)=>{return Q=h1(Q,X||$.calendary?0:2,$.calendary?"round":A),_.loc.clone($).relFormatter($).format(Q,N)},K=(Q)=>{if($.calendary)if(!_.hasSame(J,Q))return _.startOf(Q).diff(J.startOf(Q),Q).get(Q);else return 0;else return _.diff(J,Q).get(Q)};if($.unit)return G(K($.unit),$.unit);for(let Q of $.units){let N=K(Q);if(Math.abs(N)>=1)return G(N,Q)}return G(J>_?-0:0,$.units[$.units.length-1])}function mX(J){let _={},$;if(J.length>0&&typeof J[J.length-1]==="object")_=J[J.length-1],$=Array.from(J).slice(0,J.length-1);else $=Array.from(J);return[_,$]}var D0,P1=new Map;class E{constructor(J){let _=J.zone||v.defaultZone,$=J.invalid||(Number.isNaN(J.ts)?new e("invalid input"):null)||(!_.isValid?x0(_):null);this.ts=z(J.ts)?v.now():J.ts;let X=null,A=null;if(!$)if(J.old&&J.old.ts===this.ts&&J.old.zone.equals(_))[X,A]=[J.old.c,J.old.o];else{let K=FJ(J.o)&&!J.old?J.o:_.offset(this.ts);X=Y_(this.ts,K),$=Number.isNaN(X.year)?new e("invalid input"):null,X=$?null:X,A=$?null:K}this._zone=_,this.loc=J.loc||W.create(),this.invalid=$,this.weekData=null,this.localWeekData=null,this.c=X,this.o=A,this.isLuxonDateTime=!0}static now(){return new E({})}static local(){let[J,_]=mX(arguments),[$,X,A,G,K,Q,N]=_;return gX({year:$,month:X,day:A,hour:G,minute:K,second:Q,millisecond:N},J)}static utc(){let[J,_]=mX(arguments),[$,X,A,G,K,Q,N]=_;return J.zone=n.utcInstance,gX({year:$,month:X,day:A,hour:G,minute:K,second:Q,millisecond:N},J)}static fromJSDate(J,_={}){let $=s8(J)?J.valueOf():NaN;if(Number.isNaN($))return E.invalid("invalid input");let X=OJ(_.zone,v.defaultZone);if(!X.isValid)return E.invalid(x0(X));return new E({ts:$,zone:X,loc:W.fromObject(_)})}static fromMillis(J,_={}){if(!FJ(J))throw new p(`fromMillis requires a numerical input, but received a ${typeof J} with value ${J}`);else if(J<-vX||J>vX)return E.invalid("Timestamp out of range");else return new E({ts:J,zone:OJ(_.zone,v.defaultZone),loc:W.fromObject(_)})}static fromSeconds(J,_={}){if(!FJ(J))throw new p("fromSeconds requires a numerical input");else return new E({ts:J*1000,zone:OJ(_.zone,v.defaultZone),loc:W.fromObject(_)})}static fromObject(J,_={}){J=J||{};let $=OJ(_.zone,v.defaultZone);if(!$.isValid)return E.invalid(x0($));let X=W.fromObject(_),A=Z_(J,fX),{minDaysInFirstWeek:G,startOfWeek:K}=CX(A,X),Q=v.now(),N=!z(_.specificOffset)?_.specificOffset:$.offset(Q),R=!z(A.ordinal),Y=!z(A.year),H=!z(A.month)||!z(A.day),q=Y||H,V=A.weekYear||A.weekNumber;if((q||R)&&V)throw new kJ("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(H&&R)throw new kJ("Can't mix ordinal dates with month/day");let y=V||A.weekday&&!q,B,M,Z=Y_(Q,N);if(y)B=UA,M=LA,Z=B_(Z,G,K);else if(R)B=ZA,M=BA,Z=q1(Z);else B=V_,M=p4;let O=!1;for(let k of B){let AJ=A[k];if(!z(AJ))O=!0;else if(O)A[k]=M[k];else A[k]=Z[k]}let I=y?r8(A,G,K):R?o8(A):Z4(A),P=I||M4(A);if(P)return E.invalid(P);let g=y?EX(A,G,K):R?jX(A):A,[tJ,w]=q_(g,N,$),o=new E({ts:tJ,zone:$,o:w,loc:X});if(A.weekday&&q&&J.weekday!==o.weekday)return E.invalid("mismatched weekday",`you can't specify both a weekday of ${A.weekday} and a date of ${o.toISO()}`);if(!o.isValid)return E.invalid(o.invalid);return o}static fromISO(J,_={}){let[$,X]=m2(J);return G0($,X,_,"ISO 8601",J)}static fromRFC2822(J,_={}){let[$,X]=u2(J);return G0($,X,_,"RFC 2822",J)}static fromHTTP(J,_={}){let[$,X]=c2(J);return G0($,X,_,"HTTP",_)}static fromFormat(J,_,$={}){if(z(J)||z(_))throw new p("fromFormat requires an input string and a format");let{locale:X=null,numberingSystem:A=null}=$,G=W.fromOpts({locale:X,numberingSystem:A,defaultToEN:!0}),[K,Q,N,R]=yA(G,J,_);if(R)return E.invalid(R);else return G0(K,Q,$,`format ${_}`,J,N)}static fromString(J,_,$={}){return E.fromFormat(J,_,$)}static fromSQL(J,_={}){let[$,X]=o2(J);return G0($,X,_,"SQL",J)}static invalid(J,_=null){if(!J)throw new p("need to specify a reason the DateTime is invalid");let $=J instanceof e?J:new e(J,_);if(v.throwOnInvalid)throw new uX($);else return new E({invalid:$})}static isDateTime(J){return J&&J.isLuxonDateTime||!1}static parseFormatForOpts(J,_={}){let $=d4(J,W.fromObject(_));return!$?null:$.map((X)=>X?X.val:null).join("")}static expandFormat(J,_={}){return u4(i.parseFormat(J),W.fromObject(_)).map((X)=>X.val).join("")}static resetCache(){D0=void 0,P1.clear()}get(J){return this[J]}get isValid(){return this.invalid===null}get invalidReason(){return this.invalid?this.invalid.reason:null}get invalidExplanation(){return this.invalid?this.invalid.explanation:null}get locale(){return this.isValid?this.loc.locale:null}get numberingSystem(){return this.isValid?this.loc.numberingSystem:null}get outputCalendar(){return this.isValid?this.loc.outputCalendar:null}get zone(){return this._zone}get zoneName(){return this.isValid?this.zone.name:null}get year(){return this.isValid?this.c.year:NaN}get quarter(){return this.isValid?Math.ceil(this.c.month/3):NaN}get month(){return this.isValid?this.c.month:NaN}get day(){return this.isValid?this.c.day:NaN}get hour(){return this.isValid?this.c.hour:NaN}get minute(){return this.isValid?this.c.minute:NaN}get second(){return this.isValid?this.c.second:NaN}get millisecond(){return this.isValid?this.c.millisecond:NaN}get weekYear(){return this.isValid?L1(this).weekYear:NaN}get weekNumber(){return this.isValid?L1(this).weekNumber:NaN}get weekday(){return this.isValid?L1(this).weekday:NaN}get isWeekend(){return this.isValid&&this.loc.getWeekendDays().includes(this.weekday)}get localWeekday(){return this.isValid?B1(this).weekday:NaN}get localWeekNumber(){return this.isValid?B1(this).weekNumber:NaN}get localWeekYear(){return this.isValid?B1(this).weekYear:NaN}get ordinal(){return this.isValid?q1(this.c).ordinal:NaN}get monthShort(){return this.isValid?K0.months("short",{locObj:this.loc})[this.month-1]:null}get monthLong(){return this.isValid?K0.months("long",{locObj:this.loc})[this.month-1]:null}get weekdayShort(){return this.isValid?K0.weekdays("short",{locObj:this.loc})[this.weekday-1]:null}get weekdayLong(){return this.isValid?K0.weekdays("long",{locObj:this.loc})[this.weekday-1]:null}get offset(){return this.isValid?+this.o:NaN}get offsetNameShort(){if(this.isValid)return this.zone.offsetName(this.ts,{format:"short",locale:this.locale});else return null}get offsetNameLong(){if(this.isValid)return this.zone.offsetName(this.ts,{format:"long",locale:this.locale});else return null}get isOffsetFixed(){return this.isValid?this.zone.isUniversal:null}get isInDST(){if(this.isOffsetFixed)return!1;else return this.offset>this.set({month:1,day:1}).offset||this.offset>this.set({month:5}).offset}getPossibleOffsets(){if(!this.isValid||this.isOffsetFixed)return[this];let J=86400000,_=60000,$=z_(this.c),X=this.zone.offset($-J),A=this.zone.offset($+J),G=this.zone.offset($-X*_),K=this.zone.offset($-A*_);if(G===K)return[this];let Q=$-G*_,N=$-K*_,R=Y_(Q,G),Y=Y_(N,K);if(R.hour===Y.hour&&R.minute===Y.minute&&R.second===Y.second&&R.millisecond===Y.millisecond)return[gJ(this,{ts:Q}),gJ(this,{ts:N})];return[this]}get isInLeapYear(){return f0(this.year)}get daysInMonth(){return U_(this.year,this.month)}get daysInYear(){return this.isValid?Q0(this.year):NaN}get weeksInWeekYear(){return this.isValid?h0(this.weekYear):NaN}get weeksInLocalWeekYear(){return this.isValid?h0(this.localWeekYear,this.loc.getMinDaysInFirstWeek(),this.loc.getStartOfWeek()):NaN}resolvedLocaleOptions(J={}){let{locale:_,numberingSystem:$,calendar:X}=i.create(this.loc.clone(J),J).resolvedOptions(this);return{locale:_,numberingSystem:$,outputCalendar:X}}toUTC(J=0,_={}){return this.setZone(n.instance(J),_)}toLocal(){return this.setZone(v.defaultZone)}setZone(J,{keepLocalTime:_=!1,keepCalendarTime:$=!1}={}){if(J=OJ(J,v.defaultZone),J.equals(this.zone))return this;else if(!J.isValid)return E.invalid(x0(J));else{let X=this.ts;if(_||$){let A=J.offset(this.ts),G=this.toObject();[X]=q_(G,A,J)}return gJ(this,{ts:X,zone:J})}}reconfigure({locale:J,numberingSystem:_,outputCalendar:$}={}){let X=this.loc.clone({locale:J,numberingSystem:_,outputCalendar:$});return gJ(this,{loc:X})}setLocale(J){return this.reconfigure({locale:J})}set(J){if(!this.isValid)return this;let _=Z_(J,fX),{minDaysInFirstWeek:$,startOfWeek:X}=CX(_,this.loc),A=!z(_.weekYear)||!z(_.weekNumber)||!z(_.weekday),G=!z(_.ordinal),K=!z(_.year),Q=!z(_.month)||!z(_.day),N=K||Q,R=_.weekYear||_.weekNumber;if((N||G)&&R)throw new kJ("Can't mix weekYear/weekNumber units with year/month/day or ordinals");if(Q&&G)throw new kJ("Can't mix ordinal dates with month/day");let Y;if(A)Y=EX({...B_(this.c,$,X),..._},$,X);else if(!z(_.ordinal))Y=jX({...q1(this.c),..._});else if(Y={...this.toObject(),..._},z(_.day))Y.day=Math.min(U_(Y.year,Y.month),Y.day);let[H,q]=q_(Y,this.o,this.zone);return gJ(this,{ts:H,o:q})}plus(J){if(!this.isValid)return this;let _=F.fromDurationLike(J);return gJ(this,hX(this,_))}minus(J){if(!this.isValid)return this;let _=F.fromDurationLike(J).negate();return gJ(this,hX(this,_))}startOf(J,{useLocaleWeeks:_=!1}={}){if(!this.isValid)return this;let $={},X=F.normalizeUnit(J);switch(X){case"years":$.month=1;case"quarters":case"months":$.day=1;case"weeks":case"days":$.hour=0;case"hours":$.minute=0;case"minutes":$.second=0;case"seconds":$.millisecond=0;break}if(X==="weeks")if(_){let A=this.loc.getStartOfWeek(),{weekday:G}=this;if(G<A)$.weekNumber=this.weekNumber-1;$.weekday=A}else $.weekday=1;if(X==="quarters"){let A=Math.ceil(this.month/3);$.month=(A-1)*3+1}return this.set($)}endOf(J,_){return this.isValid?this.plus({[J]:1}).startOf(J,_).minus(1):this}toFormat(J,_={}){return this.isValid?i.create(this.loc.redefaultToEN(_)).formatDateTimeFromString(this,J):y1}toLocaleString(J=L_,_={}){return this.isValid?i.create(this.loc.clone(_),J).formatDateTime(this):y1}toLocaleParts(J={}){return this.isValid?i.create(this.loc.clone(J),J).formatDateTimeParts(this):[]}toISO({format:J="extended",suppressSeconds:_=!1,suppressMilliseconds:$=!1,includeOffset:X=!0,extendedZone:A=!1,precision:G="milliseconds"}={}){if(!this.isValid)return null;G=y_(G);let K=J==="extended",Q=U1(this,K,G);if(V_.indexOf(G)>=3)Q+="T";return Q+=bX(this,K,_,$,X,A,G),Q}toISODate({format:J="extended",precision:_="day"}={}){if(!this.isValid)return null;return U1(this,J==="extended",y_(_))}toISOWeekDate(){return H_(this,"kkkk-'W'WW-c")}toISOTime({suppressMilliseconds:J=!1,suppressSeconds:_=!1,includeOffset:$=!0,includePrefix:X=!1,extendedZone:A=!1,format:G="extended",precision:K="milliseconds"}={}){if(!this.isValid)return null;return K=y_(K),(X&&V_.indexOf(K)>=3?"T":"")+bX(this,G==="extended",_,J,$,A,K)}toRFC2822(){return H_(this,"EEE, dd LLL yyyy HH:mm:ss ZZZ",!1)}toHTTP(){return H_(this.toUTC(),"EEE, dd LLL yyyy HH:mm:ss 'GMT'")}toSQLDate(){if(!this.isValid)return null;return U1(this,!0)}toSQLTime({includeOffset:J=!0,includeZone:_=!1,includeOffsetSpace:$=!0}={}){let X="HH:mm:ss.SSS";if(_||J){if($)X+=" ";if(_)X+="z";else if(J)X+="ZZ"}return H_(this,X,!0)}toSQL(J={}){if(!this.isValid)return null;return`${this.toSQLDate()} ${this.toSQLTime(J)}`}toString(){return this.isValid?this.toISO():y1}[Symbol.for("nodejs.util.inspect.custom")](){if(this.isValid)return`DateTime { ts: ${this.toISO()}, zone: ${this.zone.name}, locale: ${this.locale} }`;else return`DateTime { Invalid, reason: ${this.invalidReason} }`}valueOf(){return this.toMillis()}toMillis(){return this.isValid?this.ts:NaN}toSeconds(){return this.isValid?this.ts/1000:NaN}toUnixInteger(){return this.isValid?Math.floor(this.ts/1000):NaN}toJSON(){return this.toISO()}toBSON(){return this.toJSDate()}toObject(J={}){if(!this.isValid)return{};let _={...this.c};if(J.includeConfig)_.outputCalendar=this.outputCalendar,_.numberingSystem=this.loc.numberingSystem,_.locale=this.loc.locale;return _}toJSDate(){return new Date(this.isValid?this.ts:NaN)}diff(J,_="milliseconds",$={}){if(!this.isValid||!J.isValid)return F.invalid("created by diffing an invalid DateTime");let X={locale:this.locale,numberingSystem:this.numberingSystem,...$},A=t8(_).map(F.normalizeUnit),G=J.valueOf()>this.valueOf(),K=G?this:J,Q=G?J:this,N=_A(K,Q,A,X);return G?N.negate():N}diffNow(J="milliseconds",_={}){return this.diff(E.now(),J,_)}until(J){return this.isValid?h.fromDateTimes(this,J):this}hasSame(J,_,$){if(!this.isValid)return!1;let X=J.valueOf(),A=this.setZone(J.zone,{keepLocalTime:!0});return A.startOf(_,$)<=X&&X<=A.endOf(_,$)}equals(J){return this.isValid&&J.isValid&&this.valueOf()===J.valueOf()&&this.zone.equals(J.zone)&&this.loc.equals(J.loc)}toRelative(J={}){if(!this.isValid)return null;let _=J.base||E.fromObject({},{zone:this.zone}),$=J.padding?this<_?-J.padding:J.padding:0,X=["years","months","days","hours","minutes","seconds"],A=J.unit;if(Array.isArray(J.unit))X=J.unit,A=void 0;return kX(_,this.plus($),{...J,numeric:"always",units:X,unit:A})}toRelativeCalendar(J={}){if(!this.isValid)return null;return kX(J.base||E.fromObject({},{zone:this.zone}),this,{...J,numeric:"auto",units:["years","months","days"],calendary:!0})}static min(...J){if(!J.every(E.isDateTime))throw new p("min requires all arguments be DateTimes");return OX(J,(_)=>_.valueOf(),Math.min)}static max(...J){if(!J.every(E.isDateTime))throw new p("max requires all arguments be DateTimes");return OX(J,(_)=>_.valueOf(),Math.max)}static fromFormatExplain(J,_,$={}){let{locale:X=null,numberingSystem:A=null}=$,G=W.fromOpts({locale:X,numberingSystem:A,defaultToEN:!0});return c4(G,J,_)}static fromStringExplain(J,_,$={}){return E.fromFormatExplain(J,_,$)}static buildFormatParser(J,_={}){let{locale:$=null,numberingSystem:X=null}=_,A=W.fromOpts({locale:$,numberingSystem:X,defaultToEN:!0});return new k1(A,J)}static fromFormatParser(J,_,$={}){if(z(J)||z(_))throw new p("fromFormatParser requires an input string and a format parser");let{locale:X=null,numberingSystem:A=null}=$,G=W.fromOpts({locale:X,numberingSystem:A,defaultToEN:!0});if(!G.equals(_.locale))throw new p(`fromFormatParser called with a locale of ${G}, but the format parser was created for ${_.locale}`);let{result:K,zone:Q,specificOffset:N,invalidReason:R}=_.explainFromTokens(J);if(R)return E.invalid(R);else return G0(K,Q,$,`format ${_.format}`,J,N)}static get DATE_SHORT(){return L_}static get DATE_MED(){return lX}static get DATE_MED_WITH_WEEKDAY(){return W8}static get DATE_FULL(){return pX}static get DATE_HUGE(){return iX}static get TIME_SIMPLE(){return nX}static get TIME_WITH_SECONDS(){return rX}static get TIME_WITH_SHORT_OFFSET(){return oX}static get TIME_WITH_LONG_OFFSET(){return aX}static get TIME_24_SIMPLE(){return sX}static get TIME_24_WITH_SECONDS(){return tX}static get TIME_24_WITH_SHORT_OFFSET(){return eX}static get TIME_24_WITH_LONG_OFFSET(){return J4}static get DATETIME_SHORT(){return _4}static get DATETIME_SHORT_WITH_SECONDS(){return $4}static get DATETIME_MED(){return X4}static get DATETIME_MED_WITH_SECONDS(){return A4}static get DATETIME_MED_WITH_WEEKDAY(){return w8}static get DATETIME_FULL(){return G4}static get DATETIME_FULL_WITH_SECONDS(){return K4}static get DATETIME_HUGE(){return Q4}static get DATETIME_HUGE_WITH_SECONDS(){return N4}}function w0(J){if(E.isDateTime(J))return J;else if(J&&J.valueOf&&FJ(J.valueOf()))return E.fromJSDate(J);else if(J&&typeof J==="object")return E.fromObject(J);else throw new p(`Unknown datetime argument: ${J}, of type ${typeof J}`)}var zA="3.7.2";i4.DateTime=E;i4.Duration=F;i4.FixedOffsetZone=n;i4.IANAZone=qJ;i4.Info=K0;i4.Interval=h;i4.InvalidZone=w1;i4.Settings=v;i4.SystemZone=b0;i4.VERSION=zA;i4.Zone=uJ});var o4=D((LQ,r4)=>{var cJ=n4();j.prototype.addYear=function(){this._date=this._date.plus({years:1})};j.prototype.addMonth=function(){this._date=this._date.plus({months:1}).startOf("month")};j.prototype.addDay=function(){this._date=this._date.plus({days:1}).startOf("day")};j.prototype.addHour=function(){var J=this._date;if(this._date=this._date.plus({hours:1}).startOf("hour"),this._date<=J)this._date=this._date.plus({hours:1})};j.prototype.addMinute=function(){var J=this._date;if(this._date=this._date.plus({minutes:1}).startOf("minute"),this._date<J)this._date=this._date.plus({hours:1})};j.prototype.addSecond=function(){var J=this._date;if(this._date=this._date.plus({seconds:1}).startOf("second"),this._date<J)this._date=this._date.plus({hours:1})};j.prototype.subtractYear=function(){this._date=this._date.minus({years:1})};j.prototype.subtractMonth=function(){this._date=this._date.minus({months:1}).endOf("month").startOf("second")};j.prototype.subtractDay=function(){this._date=this._date.minus({days:1}).endOf("day").startOf("second")};j.prototype.subtractHour=function(){var J=this._date;if(this._date=this._date.minus({hours:1}).endOf("hour").startOf("second"),this._date>=J)this._date=this._date.minus({hours:1})};j.prototype.subtractMinute=function(){var J=this._date;if(this._date=this._date.minus({minutes:1}).endOf("minute").startOf("second"),this._date>J)this._date=this._date.minus({hours:1})};j.prototype.subtractSecond=function(){var J=this._date;if(this._date=this._date.minus({seconds:1}).startOf("second"),this._date>J)this._date=this._date.minus({hours:1})};j.prototype.getDate=function(){return this._date.day};j.prototype.getFullYear=function(){return this._date.year};j.prototype.getDay=function(){var J=this._date.weekday;return J==7?0:J};j.prototype.getMonth=function(){return this._date.month-1};j.prototype.getHours=function(){return this._date.hour};j.prototype.getMinutes=function(){return this._date.minute};j.prototype.getSeconds=function(){return this._date.second};j.prototype.getMilliseconds=function(){return this._date.millisecond};j.prototype.getTime=function(){return this._date.valueOf()};j.prototype.getUTCDate=function(){return this._getUTC().day};j.prototype.getUTCFullYear=function(){return this._getUTC().year};j.prototype.getUTCDay=function(){var J=this._getUTC().weekday;return J==7?0:J};j.prototype.getUTCMonth=function(){return this._getUTC().month-1};j.prototype.getUTCHours=function(){return this._getUTC().hour};j.prototype.getUTCMinutes=function(){return this._getUTC().minute};j.prototype.getUTCSeconds=function(){return this._getUTC().second};j.prototype.toISOString=function(){return this._date.toUTC().toISO()};j.prototype.toJSON=function(){return this._date.toJSON()};j.prototype.setDate=function(J){this._date=this._date.set({day:J})};j.prototype.setFullYear=function(J){this._date=this._date.set({year:J})};j.prototype.setDay=function(J){this._date=this._date.set({weekday:J})};j.prototype.setMonth=function(J){this._date=this._date.set({month:J+1})};j.prototype.setHours=function(J){this._date=this._date.set({hour:J})};j.prototype.setMinutes=function(J){this._date=this._date.set({minute:J})};j.prototype.setSeconds=function(J){this._date=this._date.set({second:J})};j.prototype.setMilliseconds=function(J){this._date=this._date.set({millisecond:J})};j.prototype._getUTC=function(){return this._date.toUTC()};j.prototype.toString=function(){return this.toDate().toString()};j.prototype.toDate=function(){return this._date.toJSDate()};j.prototype.isLastDayOfMonth=function(){var J=this._date.plus({days:1}).startOf("day");return this._date.month!==J.month};j.prototype.isLastWeekdayOfMonth=function(){var J=this._date.plus({days:7}).startOf("day");return this._date.month!==J.month};function j(J,_){var $={zone:_};if(!J)this._date=cJ.DateTime.local();else if(J instanceof j)this._date=J._date;else if(J instanceof Date)this._date=cJ.DateTime.fromJSDate(J,$);else if(typeof J==="number")this._date=cJ.DateTime.fromMillis(J,$);else if(typeof J==="string")this._date=cJ.DateTime.fromISO(J,$),this._date.isValid||(this._date=cJ.DateTime.fromRFC2822(J,$)),this._date.isValid||(this._date=cJ.DateTime.fromSQL(J,$)),this._date.isValid||(this._date=cJ.DateTime.fromFormat(J,"EEE, d MMM yyyy HH:mm:ss",$));if(!this._date||!this._date.isValid)throw new Error("CronDate: unhandled timestamp: "+JSON.stringify(J));if(_&&_!==this._date.zoneName)this._date=this._date.setZone(_)}r4.exports=j});var t4=D((BQ,s4)=>{function dJ(J){return{start:J,count:1}}function a4(J,_){J.end=_,J.step=_-J.start,J.count=2}function m1(J,_,$){if(_)if(_.count===2)J.push(dJ(_.start)),J.push(dJ(_.end));else J.push(_);if($)J.push($)}function xA(J){var _=[],$=void 0;for(var X=0;X<J.length;X++){var A=J[X];if(typeof A!=="number")m1(_,$,dJ(A)),$=void 0;else if(!$)$=dJ(A);else if($.count===1)a4($,A);else if($.step===A-$.end)$.count++,$.end=A;else if($.count===2)_.push(dJ($.start)),$=dJ($.end),a4($,A);else m1(_,$),$=dJ(A)}return m1(_,$),_}s4.exports=xA});var J5=D((UQ,e4)=>{var DA=t4();function vA(J,_,$){var X=DA(J);if(X.length===1){var A=X[0],G=A.step;if(G===1&&A.start===_&&A.end===$)return"*";if(G!==1&&A.start===_&&A.end===$-G+1)return"*/"+G}var K=[];for(var Q=0,N=X.length;Q<N;++Q){var R=X[Q];if(R.count===1){K.push(R.start);continue}var G=R.step;if(R.step===1){K.push(R.start+"-"+R.end);continue}var Y=R.start==0?R.count-1:R.count;if(R.step*Y>R.end)K=K.concat(Array.from({length:R.end-R.start+1}).map(function(q,V){var y=R.start+V;if((y-R.start)%R.step===0)return y;return null}).filter(function(q){return q!=null}));else if(R.end===$-R.step+1)K.push(R.start+"/"+R.step);else K.push(R.start+"-"+R.end+"/"+R.step)}return K.join(",")}e4.exports=vA});var X5=D((ZQ,$5)=>{var lJ=o4(),hA=J5(),_5=1e4;function U(J,_){this._options=_,this._utc=_.utc||!1,this._tz=this._utc?"UTC":_.tz,this._currentDate=new lJ(_.currentDate,this._tz),this._startDate=_.startDate?new lJ(_.startDate,this._tz):null,this._endDate=_.endDate?new lJ(_.endDate,this._tz):null,this._isIterator=_.iterator||!1,this._hasIterated=!1,this._nthDayOfWeek=_.nthDayOfWeek||0,this.fields=U._freezeFields(J)}U.map=["second","minute","hour","dayOfMonth","month","dayOfWeek"];U.predefined={"@yearly":"0 0 1 1 *","@monthly":"0 0 1 * *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *"};U.constraints=[{min:0,max:59,chars:[]},{min:0,max:59,chars:[]},{min:0,max:23,chars:[]},{min:1,max:31,chars:["L"]},{min:1,max:12,chars:[]},{min:0,max:7,chars:["L"]}];U.daysInMonth=[31,29,31,30,31,30,31,31,30,31,30,31];U.aliases={month:{jan:1,feb:2,mar:3,apr:4,may:5,jun:6,jul:7,aug:8,sep:9,oct:10,nov:11,dec:12},dayOfWeek:{sun:0,mon:1,tue:2,wed:3,thu:4,fri:5,sat:6}};U.parseDefaults=["0","*","*","*","*","*"];U.standardValidCharacters=/^[,*\d/-]+$/;U.dayOfWeekValidCharacters=/^[?,*\dL#/-]+$/;U.dayOfMonthValidCharacters=/^[?,*\dL/-]+$/;U.validCharacters={second:U.standardValidCharacters,minute:U.standardValidCharacters,hour:U.standardValidCharacters,dayOfMonth:U.dayOfMonthValidCharacters,month:U.standardValidCharacters,dayOfWeek:U.dayOfWeekValidCharacters};U._isValidConstraintChar=function J(_,$){if(typeof $!=="string")return!1;return _.chars.some(function(X){return $.indexOf(X)>-1})};U._parseField=function J(_,$,X){switch(_){case"month":case"dayOfWeek":var A=U.aliases[_];$=$.replace(/[a-z]{3}/gi,function(N){if(N=N.toLowerCase(),typeof A[N]!=="undefined")return A[N];else throw new Error('Validation error, cannot resolve alias "'+N+'"')});break}if(!U.validCharacters[_].test($))throw new Error("Invalid characters, got value: "+$);if($.indexOf("*")!==-1)$=$.replace(/\*/g,X.min+"-"+X.max);else if($.indexOf("?")!==-1)$=$.replace(/\?/g,X.min+"-"+X.max);function G(N){var R=[];function Y(y){if(y instanceof Array)for(var B=0,M=y.length;B<M;B++){var Z=y[B];if(U._isValidConstraintChar(X,Z)){R.push(Z);continue}if(typeof Z!=="number"||Number.isNaN(Z)||Z<X.min||Z>X.max)throw new Error("Constraint error, got value "+Z+" expected range "+X.min+"-"+X.max);R.push(Z)}else{if(U._isValidConstraintChar(X,y)){R.push(y);return}var O=+y;if(Number.isNaN(O)||O<X.min||O>X.max)throw new Error("Constraint error, got value "+y+" expected range "+X.min+"-"+X.max);if(_==="dayOfWeek")O=O%7;R.push(O)}}var H=N.split(",");if(!H.every(function(y){return y.length>0}))throw new Error("Invalid list value format");if(H.length>1)for(var q=0,V=H.length;q<V;q++)Y(K(H[q]));else Y(K(N));return R.sort(U._sortCompareFn),R}function K(N){var R=1,Y=N.split("/");if(Y.length>2)throw new Error("Invalid repeat: "+N);if(Y.length>1){if(Y[0]==+Y[0])Y=[Y[0]+"-"+X.max,Y[1]];return Q(Y[0],Y[Y.length-1])}return Q(N,R)}function Q(N,R){var Y=[],H=N.split("-");if(H.length>1){if(H.length<2)return+N;if(!H[0].length){if(!H[1].length)throw new Error("Invalid range: "+N);return+N}var q=+H[0],V=+H[1];if(Number.isNaN(q)||Number.isNaN(V)||q<X.min||V>X.max)throw new Error("Constraint error, got range "+q+"-"+V+" expected range "+X.min+"-"+X.max);else if(q>V)throw new Error("Invalid range: "+N);var y=+R;if(Number.isNaN(y)||y<=0)throw new Error("Constraint error, cannot repeat at every "+y+" time.");if(_==="dayOfWeek"&&V%7===0)Y.push(0);for(var B=q,M=V;B<=M;B++){var Z=Y.indexOf(B)!==-1;if(!Z&&y>0&&y%R===0)y=1,Y.push(B);else y++}return Y}return Number.isNaN(+N)?N:+N}return G($)};U._sortCompareFn=function(J,_){var $=typeof J==="number",X=typeof _==="number";if($&&X)return J-_;if(!$&&X)return 1;if($&&!X)return-1;return J.localeCompare(_)};U._handleMaxDaysInMonth=function(J){if(J.month.length===1){var _=U.daysInMonth[J.month[0]-1];if(J.dayOfMonth[0]>_)throw new Error("Invalid explicit day of month definition");return J.dayOfMonth.filter(function($){return $==="L"?!0:$<=_}).sort(U._sortCompareFn)}};U._freezeFields=function(J){for(var _=0,$=U.map.length;_<$;++_){var X=U.map[_],A=J[X];J[X]=Object.freeze(A)}return Object.freeze(J)};U.prototype._applyTimezoneShift=function(J,_,$){if($==="Month"||$==="Day"){var X=J.getTime();J[_+$]();var A=J.getTime();if(X===A){if(J.getMinutes()===0&&J.getSeconds()===0)J.addHour();else if(J.getMinutes()===59&&J.getSeconds()===59)J.subtractHour()}}else{var G=J.getHours();J[_+$]();var K=J.getHours(),Q=K-G;if(Q===2){if(this.fields.hour.length!==24)this._dstStart=K}else if(Q===0&&J.getMinutes()===0&&J.getSeconds()===0){if(this.fields.hour.length!==24)this._dstEnd=K}}};U.prototype._findSchedule=function J(_){function $(Z,O){for(var I=0,P=O.length;I<P;I++)if(O[I]>=Z)return O[I]===Z;return O[0]===Z}function X(Z,O){if(O<6){if(Z.getDate()<8&&O===1)return!0;var I=Z.getDate()%7?1:0,P=Z.getDate()-Z.getDate()%7,g=Math.floor(P/7)+I;return g===O}return!1}function A(Z){return Z.length>0&&Z.some(function(O){return typeof O==="string"&&O.indexOf("L")>=0})}_=_||!1;var G=_?"subtract":"add",K=new lJ(this._currentDate,this._tz),Q=this._startDate,N=this._endDate,R=K.getTime(),Y=0;function H(Z){return Z.some(function(O){if(!A([O]))return!1;var I=Number.parseInt(O[0])%7;if(Number.isNaN(I))throw new Error("Invalid last weekday of the month expression: "+O);return K.getDay()===I&&K.isLastWeekdayOfMonth()})}while(Y<_5){if(Y++,_){if(Q&&K.getTime()-Q.getTime()<0)throw new Error("Out of the timespan range")}else if(N&&N.getTime()-K.getTime()<0)throw new Error("Out of the timespan range");var q=$(K.getDate(),this.fields.dayOfMonth);if(A(this.fields.dayOfMonth))q=q||K.isLastDayOfMonth();var V=$(K.getDay(),this.fields.dayOfWeek);if(A(this.fields.dayOfWeek))V=V||H(this.fields.dayOfWeek);var y=this.fields.dayOfMonth.length>=U.daysInMonth[K.getMonth()],B=this.fields.dayOfWeek.length===U.constraints[5].max-U.constraints[5].min+1,M=K.getHours();if(!q&&(!V||B)){this._applyTimezoneShift(K,G,"Day");continue}if(!y&&B&&!q){this._applyTimezoneShift(K,G,"Day");continue}if(y&&!B&&!V){this._applyTimezoneShift(K,G,"Day");continue}if(this._nthDayOfWeek>0&&!X(K,this._nthDayOfWeek)){this._applyTimezoneShift(K,G,"Day");continue}if(!$(K.getMonth()+1,this.fields.month)){this._applyTimezoneShift(K,G,"Month");continue}if(!$(M,this.fields.hour)){if(this._dstStart!==M){this._dstStart=null,this._applyTimezoneShift(K,G,"Hour");continue}else if(!$(M-1,this.fields.hour)){K[G+"Hour"]();continue}}else if(this._dstEnd===M){if(!_){this._dstEnd=null,this._applyTimezoneShift(K,"add","Hour");continue}}if(!$(K.getMinutes(),this.fields.minute)){this._applyTimezoneShift(K,G,"Minute");continue}if(!$(K.getSeconds(),this.fields.second)){this._applyTimezoneShift(K,G,"Second");continue}if(R===K.getTime()){if(G==="add"||K.getMilliseconds()===0)this._applyTimezoneShift(K,G,"Second");else K.setMilliseconds(0);continue}break}if(Y>=_5)throw new Error("Invalid expression, loop limit exceeded");return this._currentDate=new lJ(K,this._tz),this._hasIterated=!0,K};U.prototype.next=function J(){var _=this._findSchedule();if(this._isIterator)return{value:_,done:!this.hasNext()};return _};U.prototype.prev=function J(){var _=this._findSchedule(!0);if(this._isIterator)return{value:_,done:!this.hasPrev()};return _};U.prototype.hasNext=function(){var J=this._currentDate,_=this._hasIterated;try{return this._findSchedule(),!0}catch($){return!1}finally{this._currentDate=J,this._hasIterated=_}};U.prototype.hasPrev=function(){var J=this._currentDate,_=this._hasIterated;try{return this._findSchedule(!0),!0}catch($){return!1}finally{this._currentDate=J,this._hasIterated=_}};U.prototype.iterate=function J(_,$){var X=[];if(_>=0)for(var A=0,G=_;A<G;A++)try{var K=this.next();if(X.push(K),$)$(K,A)}catch(Q){break}else for(var A=0,G=_;A>G;A--)try{var K=this.prev();if(X.push(K),$)$(K,A)}catch(R){break}return X};U.prototype.reset=function J(_){this._currentDate=new lJ(_||this._options.currentDate)};U.prototype.stringify=function J(_){var $=[];for(var X=_?0:1,A=U.map.length;X<A;++X){var G=U.map[X],K=this.fields[G],Q=U.constraints[X];if(G==="dayOfMonth"&&this.fields.month.length===1)Q={min:1,max:U.daysInMonth[this.fields.month[0]-1]};else if(G==="dayOfWeek")Q={min:0,max:6},K=K[K.length-1]===7?K.slice(0,-1):K;$.push(hA(K,Q.min,Q.max))}return $.join(" ")};U.parse=function J(_,$){var X=this;if(typeof $==="function")$={};function A(G,K){if(!K)K={};if(typeof K.currentDate==="undefined")K.currentDate=new lJ(void 0,X._tz);if(U.predefined[G])G=U.predefined[G];var Q=[],N=(G+"").trim().split(/\s+/);if(N.length>6)throw new Error("Invalid cron expression");var R=U.map.length-N.length;for(var Y=0,H=U.map.length;Y<H;++Y){var q=U.map[Y],V=N[N.length>H?Y:Y-R];if(Y<R||!V)Q.push(U._parseField(q,U.parseDefaults[Y],U.constraints[Y]));else{var y=q==="dayOfWeek"?O(V):V;Q.push(U._parseField(q,y,U.constraints[Y]))}}var B={};for(var Y=0,H=U.map.length;Y<H;Y++){var M=U.map[Y];B[M]=Q[Y]}var Z=U._handleMaxDaysInMonth(B);return B.dayOfMonth=Z||B.dayOfMonth,new U(B,K);function O(I){var P=I.split("#");if(P.length>1){var g=+P[P.length-1];if(/,/.test(I))throw new Error("Constraint error, invalid dayOfWeek `#` and `,` special characters are incompatible");if(/\//.test(I))throw new Error("Constraint error, invalid dayOfWeek `#` and `/` special characters are incompatible");if(/-/.test(I))throw new Error("Constraint error, invalid dayOfWeek `#` and `-` special characters are incompatible");if(P.length>2||Number.isNaN(g)||(g<1||g>5))throw new Error("Constraint error, invalid dayOfWeek occurrence number (#)");return K.nthDayOfWeek=g,P[0]}return I}}return A(_,$)};U.fieldsToExpression=function J(_,$){function X(q,V,y){if(!V)throw new Error("Validation error, Field "+q+" is missing");if(V.length===0)throw new Error("Validation error, Field "+q+" contains no values");for(var B=0,M=V.length;B<M;B++){var Z=V[B];if(U._isValidConstraintChar(y,Z))continue;if(typeof Z!=="number"||Number.isNaN(Z)||Z<y.min||Z>y.max)throw new Error("Constraint error, got value "+Z+" expected range "+y.min+"-"+y.max)}}var A={};for(var G=0,K=U.map.length;G<K;++G){var Q=U.map[G],N=_[Q];X(Q,N,U.constraints[G]);var R=[],Y=-1;while(++Y<N.length)R[Y]=N[Y];if(N=R.sort(U._sortCompareFn).filter(function(q,V,y){return!V||q!==y[V-1]}),N.length!==R.length)throw new Error("Validation error, Field "+Q+" contains duplicate values");A[Q]=N}var H=U._handleMaxDaysInMonth(A);return A.dayOfMonth=H||A.dayOfMonth,new U(A,$||{})};$5.exports=U});var G5=D((MQ,A5)=>{var C_=X5();function SJ(){}SJ._parseEntry=function J(_){var $=_.split(" ");if($.length===6)return{interval:C_.parse(_)};else if($.length>6)return{interval:C_.parse($.slice(0,6).join(" ")),command:$.slice(6,$.length)};else throw new Error("Invalid entry: "+_)};SJ.parseExpression=function J(_,$){return C_.parse(_,$)};SJ.fieldsToExpression=function J(_,$){return C_.fieldsToExpression(_,$)};SJ.parseString=function J(_){var $=_.split(`
|
|
5
|
-
`),X={variables:{},expressions:[],errors:{}};for(var A=0,G=$.length;A<G;A++){var K=$[A],Q=null,N=K.trim();if(N.length>0)if(N.match(/^#/))continue;else if(Q=N.match(/^(.*)=(.*)$/))X.variables[Q[1]]=Q[2];else{var R=null;try{R=SJ._parseEntry("0 "+N),X.expressions.push(R.interval)}catch(Y){X.errors[N]=Y}}}return X};SJ.parseFile=function J(_,$){x("fs").readFile(_,function(X,A){if(X){$(X);return}return $(null,SJ.parseString(A.toString()))})};A5.exports=SJ});var ZJ=D((w9,O5)=>{var j5=["nodebuffer","arraybuffer","fragments"],C5=typeof Blob!=="undefined";if(C5)j5.push("blob");O5.exports={BINARY_TYPES:j5,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:C5,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var d0=D((I9,I_)=>{var{EMPTY_BUFFER:rA}=ZJ(),$$=Buffer[Symbol.species];function oA(J,_){if(J.length===0)return rA;if(J.length===1)return J[0];let $=Buffer.allocUnsafe(_),X=0;for(let A=0;A<J.length;A++){let G=J[A];$.set(G,X),X+=G.length}if(X<_)return new $$($.buffer,$.byteOffset,X);return $}function F5(J,_,$,X,A){for(let G=0;G<A;G++)$[X+G]=J[G]^_[G&3]}function T5(J,_){for(let $=0;$<J.length;$++)J[$]^=_[$&3]}function aA(J){if(J.length===J.buffer.byteLength)return J.buffer;return J.buffer.slice(J.byteOffset,J.byteOffset+J.length)}function X$(J){if(X$.readOnly=!0,Buffer.isBuffer(J))return J;let _;if(J instanceof ArrayBuffer)_=new $$(J);else if(ArrayBuffer.isView(J))_=new $$(J.buffer,J.byteOffset,J.byteLength);else _=Buffer.from(J),X$.readOnly=!1;return _}I_.exports={concat:oA,mask:F5,toArrayBuffer:aA,toBuffer:X$,unmask:T5};if(!process.env.WS_NO_BUFFER_UTIL)try{let J=(()=>{throw new Error("Cannot require module "+"bufferutil");})();I_.exports.mask=function(_,$,X,A,G){if(G<48)F5(_,$,X,A,G);else J.mask(_,$,X,A,G)},I_.exports.unmask=function(_,$){if(_.length<32)T5(_,$);else J.unmask(_,$)}}catch(J){}});var w5=D((x9,W5)=>{var S5=Symbol("kDone"),A$=Symbol("kRun");class P5{constructor(J){this[S5]=()=>{this.pending--,this[A$]()},this.concurrency=J||1/0,this.jobs=[],this.pending=0}add(J){this.jobs.push(J),this[A$]()}[A$](){if(this.pending===this.concurrency)return;if(this.jobs.length){let J=this.jobs.shift();this.pending++,J(this[S5])}}}W5.exports=P5});var Z0=D((D9,h5)=>{var l0=x("zlib"),I5=d0(),sA=w5(),{kStatusCode:x5}=ZJ(),tA=Buffer[Symbol.species],eA=Buffer.from([0,0,255,255]),D_=Symbol("permessage-deflate"),MJ=Symbol("total-length"),B0=Symbol("callback"),PJ=Symbol("buffers"),U0=Symbol("error"),x_;class D5{constructor(J){if(this._options=J||{},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,!x_){let _=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;x_=new sA(_)}}static get extensionName(){return"permessage-deflate"}offer(){let J={};if(this._options.serverNoContextTakeover)J.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)J.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)J.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)J.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)J.client_max_window_bits=!0;return J}accept(J){return J=this.normalizeParams(J),this.params=this._isServer?this.acceptAsServer(J):this.acceptAsClient(J),this.params}cleanup(){if(this._inflate)this._inflate.close(),this._inflate=null;if(this._deflate){let J=this._deflate[B0];if(this._deflate.close(),this._deflate=null,J)J(new Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(J){let _=this._options,$=J.find((X)=>{if(_.serverNoContextTakeover===!1&&X.server_no_context_takeover||X.server_max_window_bits&&(_.serverMaxWindowBits===!1||typeof _.serverMaxWindowBits==="number"&&_.serverMaxWindowBits>X.server_max_window_bits)||typeof _.clientMaxWindowBits==="number"&&!X.client_max_window_bits)return!1;return!0});if(!$)throw new Error("None of the extension offers can be accepted");if(_.serverNoContextTakeover)$.server_no_context_takeover=!0;if(_.clientNoContextTakeover)$.client_no_context_takeover=!0;if(typeof _.serverMaxWindowBits==="number")$.server_max_window_bits=_.serverMaxWindowBits;if(typeof _.clientMaxWindowBits==="number")$.client_max_window_bits=_.clientMaxWindowBits;else if($.client_max_window_bits===!0||_.clientMaxWindowBits===!1)delete $.client_max_window_bits;return $}acceptAsClient(J){let _=J[0];if(this._options.clientNoContextTakeover===!1&&_.client_no_context_takeover)throw new Error('Unexpected parameter "client_no_context_takeover"');if(!_.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")_.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&_.client_max_window_bits>this._options.clientMaxWindowBits)throw new Error('Unexpected or invalid parameter "client_max_window_bits"');return _}normalizeParams(J){return J.forEach((_)=>{Object.keys(_).forEach(($)=>{let X=_[$];if(X.length>1)throw new Error(`Parameter "${$}" must have only a single value`);if(X=X[0],$==="client_max_window_bits"){if(X!==!0){let A=+X;if(!Number.isInteger(A)||A<8||A>15)throw new TypeError(`Invalid value for parameter "${$}": ${X}`);X=A}else if(!this._isServer)throw new TypeError(`Invalid value for parameter "${$}": ${X}`)}else if($==="server_max_window_bits"){let A=+X;if(!Number.isInteger(A)||A<8||A>15)throw new TypeError(`Invalid value for parameter "${$}": ${X}`);X=A}else if($==="client_no_context_takeover"||$==="server_no_context_takeover"){if(X!==!0)throw new TypeError(`Invalid value for parameter "${$}": ${X}`)}else throw new Error(`Unknown parameter "${$}"`);_[$]=X})}),J}decompress(J,_,$){x_.add((X)=>{this._decompress(J,_,(A,G)=>{X(),$(A,G)})})}compress(J,_,$){x_.add((X)=>{this._compress(J,_,(A,G)=>{X(),$(A,G)})})}_decompress(J,_,$){let X=this._isServer?"client":"server";if(!this._inflate){let A=`${X}_max_window_bits`,G=typeof this.params[A]!=="number"?l0.Z_DEFAULT_WINDOWBITS:this.params[A];this._inflate=l0.createInflateRaw({...this._options.zlibInflateOptions,windowBits:G}),this._inflate[D_]=this,this._inflate[MJ]=0,this._inflate[PJ]=[],this._inflate.on("error",_7),this._inflate.on("data",v5)}if(this._inflate[B0]=$,this._inflate.write(J),_)this._inflate.write(eA);this._inflate.flush(()=>{let A=this._inflate[U0];if(A){this._inflate.close(),this._inflate=null,$(A);return}let G=I5.concat(this._inflate[PJ],this._inflate[MJ]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[MJ]=0,this._inflate[PJ]=[],_&&this.params[`${X}_no_context_takeover`])this._inflate.reset();$(null,G)})}_compress(J,_,$){let X=this._isServer?"server":"client";if(!this._deflate){let A=`${X}_max_window_bits`,G=typeof this.params[A]!=="number"?l0.Z_DEFAULT_WINDOWBITS:this.params[A];this._deflate=l0.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:G}),this._deflate[MJ]=0,this._deflate[PJ]=[],this._deflate.on("data",J7)}this._deflate[B0]=$,this._deflate.write(J),this._deflate.flush(l0.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let A=I5.concat(this._deflate[PJ],this._deflate[MJ]);if(_)A=new tA(A.buffer,A.byteOffset,A.length-4);if(this._deflate[B0]=null,this._deflate[MJ]=0,this._deflate[PJ]=[],_&&this.params[`${X}_no_context_takeover`])this._deflate.reset();$(null,A)})}}h5.exports=D5;function J7(J){this[PJ].push(J),this[MJ]+=J.length}function v5(J){if(this[MJ]+=J.length,this[D_]._maxPayload<1||this[MJ]<=this[D_]._maxPayload){this[PJ].push(J);return}this[U0]=new RangeError("Max payload size exceeded"),this[U0].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[U0][x5]=1009,this.removeListener("data",v5),this.reset()}function _7(J){if(this[D_]._inflate=null,this[U0]){this[B0](this[U0]);return}J[x5]=1007,this[B0](J)}});var M0=D((v9,v_)=>{var{isUtf8:b5}=x("buffer"),{hasBlob:$7}=ZJ(),X7=[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 A7(J){return J>=1000&&J<=1014&&J!==1004&&J!==1005&&J!==1006||J>=3000&&J<=4999}function G$(J){let _=J.length,$=0;while($<_)if((J[$]&128)===0)$++;else if((J[$]&224)===192){if($+1===_||(J[$+1]&192)!==128||(J[$]&254)===192)return!1;$+=2}else if((J[$]&240)===224){if($+2>=_||(J[$+1]&192)!==128||(J[$+2]&192)!==128||J[$]===224&&(J[$+1]&224)===128||J[$]===237&&(J[$+1]&224)===160)return!1;$+=3}else if((J[$]&248)===240){if($+3>=_||(J[$+1]&192)!==128||(J[$+2]&192)!==128||(J[$+3]&192)!==128||J[$]===240&&(J[$+1]&240)===128||J[$]===244&&J[$+1]>143||J[$]>244)return!1;$+=4}else return!1;return!0}function G7(J){return $7&&typeof J==="object"&&typeof J.arrayBuffer==="function"&&typeof J.type==="string"&&typeof J.stream==="function"&&(J[Symbol.toStringTag]==="Blob"||J[Symbol.toStringTag]==="File")}v_.exports={isBlob:G7,isValidStatusCode:A7,isValidUTF8:G$,tokenChars:X7};if(b5)v_.exports.isValidUTF8=function(J){return J.length<24?G$(J):b5(J)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let J=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();v_.exports.isValidUTF8=function(_){return _.length<32?G$(_):J(_)}}catch(J){}});var Q$=D((h9,u5)=>{var{Writable:K7}=x("stream"),f5=Z0(),{BINARY_TYPES:Q7,EMPTY_BUFFER:g5,kStatusCode:N7,kWebSocket:R7}=ZJ(),{concat:K$,toArrayBuffer:Y7,unmask:H7}=d0(),{isValidStatusCode:q7,isValidUTF8:k5}=M0(),h_=Buffer[Symbol.species];class m5 extends K7{constructor(J={}){super();this._allowSynchronousEvents=J.allowSynchronousEvents!==void 0?J.allowSynchronousEvents:!0,this._binaryType=J.binaryType||Q7[0],this._extensions=J.extensions||{},this._isServer=!!J.isServer,this._maxPayload=J.maxPayload|0,this._skipUTF8Validation=!!J.skipUTF8Validation,this[R7]=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=0}_write(J,_,$){if(this._opcode===8&&this._state==0)return $();this._bufferedBytes+=J.length,this._buffers.push(J),this.startLoop($)}consume(J){if(this._bufferedBytes-=J,J===this._buffers[0].length)return this._buffers.shift();if(J<this._buffers[0].length){let $=this._buffers[0];return this._buffers[0]=new h_($.buffer,$.byteOffset+J,$.length-J),new h_($.buffer,$.byteOffset,J)}let _=Buffer.allocUnsafe(J);do{let $=this._buffers[0],X=_.length-J;if(J>=$.length)_.set(this._buffers.shift(),X);else _.set(new Uint8Array($.buffer,$.byteOffset,J),X),this._buffers[0]=new h_($.buffer,$.byteOffset+J,$.length-J);J-=$.length}while(J>0);return _}startLoop(J){this._loop=!0;do switch(this._state){case 0:this.getInfo(J);break;case 1:this.getPayloadLength16(J);break;case 2:this.getPayloadLength64(J);break;case 3:this.getMask();break;case 4:this.getData(J);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)J()}getInfo(J){if(this._bufferedBytes<2){this._loop=!1;return}let _=this.consume(2);if((_[0]&48)!==0){let X=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");J(X);return}let $=(_[0]&64)===64;if($&&!this._extensions[f5.extensionName]){let X=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");J(X);return}if(this._fin=(_[0]&128)===128,this._opcode=_[0]&15,this._payloadLength=_[1]&127,this._opcode===0){if($){let X=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");J(X);return}if(!this._fragmented){let X=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");J(X);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let X=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");J(X);return}this._compressed=$}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let X=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");J(X);return}if($){let X=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");J(X);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let X=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");J(X);return}}else{let X=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");J(X);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(_[1]&128)===128,this._isServer){if(!this._masked){let X=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");J(X);return}}else if(this._masked){let X=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");J(X);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else this.haveLength(J)}getPayloadLength16(J){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(J)}getPayloadLength64(J){if(this._bufferedBytes<8){this._loop=!1;return}let _=this.consume(8),$=_.readUInt32BE(0);if($>Math.pow(2,21)-1){let X=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");J(X);return}this._payloadLength=$*Math.pow(2,32)+_.readUInt32BE(4),this.haveLength(J)}haveLength(J){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let _=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");J(_);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(J){let _=g5;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(_=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)H7(_,this._mask)}if(this._opcode>7){this.controlMessage(_,J);return}if(this._compressed){this._state=5,this.decompress(_,J);return}if(_.length)this._messageLength=this._totalPayloadLength,this._fragments.push(_);this.dataMessage(J)}decompress(J,_){this._extensions[f5.extensionName].decompress(J,this._fin,(X,A)=>{if(X)return _(X);if(A.length){if(this._messageLength+=A.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let G=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");_(G);return}this._fragments.push(A)}if(this.dataMessage(_),this._state===0)this.startLoop(_)})}dataMessage(J){if(!this._fin){this._state=0;return}let _=this._messageLength,$=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._fragments=[],this._opcode===2){let X;if(this._binaryType==="nodebuffer")X=K$($,_);else if(this._binaryType==="arraybuffer")X=Y7(K$($,_));else if(this._binaryType==="blob")X=new Blob($);else X=$;if(this._allowSynchronousEvents)this.emit("message",X,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",X,!0),this._state=0,this.startLoop(J)})}else{let X=K$($,_);if(!this._skipUTF8Validation&&!k5(X)){let A=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");J(A);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",X,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",X,!1),this._state=0,this.startLoop(J)})}}controlMessage(J,_){if(this._opcode===8){if(J.length===0)this._loop=!1,this.emit("conclude",1005,g5),this.end();else{let $=J.readUInt16BE(0);if(!q7($)){let A=this.createError(RangeError,`invalid status code ${$}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");_(A);return}let X=new h_(J.buffer,J.byteOffset+2,J.length-2);if(!this._skipUTF8Validation&&!k5(X)){let A=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");_(A);return}this._loop=!1,this.emit("conclude",$,X),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",J),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",J),this._state=0,this.startLoop(_)})}createError(J,_,$,X,A){this._loop=!1,this._errored=!0;let G=new J($?`Invalid WebSocket frame: ${_}`:_);return Error.captureStackTrace(G,this.createError),G.code=A,G[N7]=X,G}}u5.exports=m5});var R$=D((f9,l5)=>{var{Duplex:b9}=x("stream"),{randomFillSync:V7}=x("crypto"),c5=Z0(),{EMPTY_BUFFER:y7,kWebSocket:L7,NOOP:B7}=ZJ(),{isBlob:z0,isValidStatusCode:U7}=M0(),{mask:d5,toBuffer:pJ}=d0(),XJ=Symbol("kByteLength"),Z7=Buffer.alloc(4),iJ,E0=8192,YJ=0,M7=1,z7=2;class WJ{constructor(J,_,$){if(this._extensions=_||{},$)this._generateMask=$,this._maskBuffer=Buffer.alloc(4);this._socket=J,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=YJ,this.onerror=B7,this[L7]=void 0}static frame(J,_){let $,X=!1,A=2,G=!1;if(_.mask){if($=_.maskBuffer||Z7,_.generateMask)_.generateMask($);else{if(E0===8192){if(iJ===void 0)iJ=Buffer.alloc(8192);V7(iJ,0,8192),E0=0}$[0]=iJ[E0++],$[1]=iJ[E0++],$[2]=iJ[E0++],$[3]=iJ[E0++]}G=($[0]|$[1]|$[2]|$[3])===0,A=6}let K;if(typeof J==="string")if((!_.mask||G)&&_[XJ]!==void 0)K=_[XJ];else J=Buffer.from(J),K=J.length;else K=J.length,X=_.mask&&_.readOnly&&!G;let Q=K;if(K>=65536)A+=8,Q=127;else if(K>125)A+=2,Q=126;let N=Buffer.allocUnsafe(X?K+A:A);if(N[0]=_.fin?_.opcode|128:_.opcode,_.rsv1)N[0]|=64;if(N[1]=Q,Q===126)N.writeUInt16BE(K,2);else if(Q===127)N[2]=N[3]=0,N.writeUIntBE(K,4,6);if(!_.mask)return[N,J];if(N[1]|=128,N[A-4]=$[0],N[A-3]=$[1],N[A-2]=$[2],N[A-1]=$[3],G)return[N,J];if(X)return d5(J,$,N,A,K),[N];return d5(J,$,J,0,K),[N,J]}close(J,_,$,X){let A;if(J===void 0)A=y7;else if(typeof J!=="number"||!U7(J))throw new TypeError("First argument must be a valid error code number");else if(_===void 0||!_.length)A=Buffer.allocUnsafe(2),A.writeUInt16BE(J,0);else{let K=Buffer.byteLength(_);if(K>123)throw new RangeError("The message must not be greater than 123 bytes");if(A=Buffer.allocUnsafe(2+K),A.writeUInt16BE(J,0),typeof _==="string")A.write(_,2);else A.set(_,2)}let G={[XJ]:A.length,fin:!0,generateMask:this._generateMask,mask:$,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==YJ)this.enqueue([this.dispatch,A,!1,G,X]);else this.sendFrame(WJ.frame(A,G),X)}ping(J,_,$){let X,A;if(typeof J==="string")X=Buffer.byteLength(J),A=!1;else if(z0(J))X=J.size,A=!1;else J=pJ(J),X=J.length,A=pJ.readOnly;if(X>125)throw new RangeError("The data size must not be greater than 125 bytes");let G={[XJ]:X,fin:!0,generateMask:this._generateMask,mask:_,maskBuffer:this._maskBuffer,opcode:9,readOnly:A,rsv1:!1};if(z0(J))if(this._state!==YJ)this.enqueue([this.getBlobData,J,!1,G,$]);else this.getBlobData(J,!1,G,$);else if(this._state!==YJ)this.enqueue([this.dispatch,J,!1,G,$]);else this.sendFrame(WJ.frame(J,G),$)}pong(J,_,$){let X,A;if(typeof J==="string")X=Buffer.byteLength(J),A=!1;else if(z0(J))X=J.size,A=!1;else J=pJ(J),X=J.length,A=pJ.readOnly;if(X>125)throw new RangeError("The data size must not be greater than 125 bytes");let G={[XJ]:X,fin:!0,generateMask:this._generateMask,mask:_,maskBuffer:this._maskBuffer,opcode:10,readOnly:A,rsv1:!1};if(z0(J))if(this._state!==YJ)this.enqueue([this.getBlobData,J,!1,G,$]);else this.getBlobData(J,!1,G,$);else if(this._state!==YJ)this.enqueue([this.dispatch,J,!1,G,$]);else this.sendFrame(WJ.frame(J,G),$)}send(J,_,$){let X=this._extensions[c5.extensionName],A=_.binary?2:1,G=_.compress,K,Q;if(typeof J==="string")K=Buffer.byteLength(J),Q=!1;else if(z0(J))K=J.size,Q=!1;else J=pJ(J),K=J.length,Q=pJ.readOnly;if(this._firstFragment){if(this._firstFragment=!1,G&&X&&X.params[X._isServer?"server_no_context_takeover":"client_no_context_takeover"])G=K>=X._threshold;this._compress=G}else G=!1,A=0;if(_.fin)this._firstFragment=!0;let N={[XJ]:K,fin:_.fin,generateMask:this._generateMask,mask:_.mask,maskBuffer:this._maskBuffer,opcode:A,readOnly:Q,rsv1:G};if(z0(J))if(this._state!==YJ)this.enqueue([this.getBlobData,J,this._compress,N,$]);else this.getBlobData(J,this._compress,N,$);else if(this._state!==YJ)this.enqueue([this.dispatch,J,this._compress,N,$]);else this.dispatch(J,this._compress,N,$)}getBlobData(J,_,$,X){this._bufferedBytes+=$[XJ],this._state=z7,J.arrayBuffer().then((A)=>{if(this._socket.destroyed){let K=new Error("The socket was closed while the blob was being read");process.nextTick(N$,this,K,X);return}this._bufferedBytes-=$[XJ];let G=pJ(A);if(!_)this._state=YJ,this.sendFrame(WJ.frame(G,$),X),this.dequeue();else this.dispatch(G,_,$,X)}).catch((A)=>{process.nextTick(E7,this,A,X)})}dispatch(J,_,$,X){if(!_){this.sendFrame(WJ.frame(J,$),X);return}let A=this._extensions[c5.extensionName];this._bufferedBytes+=$[XJ],this._state=M7,A.compress(J,$.fin,(G,K)=>{if(this._socket.destroyed){let Q=new Error("The socket was closed while data was being compressed");N$(this,Q,X);return}this._bufferedBytes-=$[XJ],this._state=YJ,$.readOnly=!1,this.sendFrame(WJ.frame(K,$),X),this.dequeue()})}dequeue(){while(this._state===YJ&&this._queue.length){let J=this._queue.shift();this._bufferedBytes-=J[3][XJ],Reflect.apply(J[0],this,J.slice(1))}}enqueue(J){this._bufferedBytes+=J[3][XJ],this._queue.push(J)}sendFrame(J,_){if(J.length===2)this._socket.cork(),this._socket.write(J[0]),this._socket.write(J[1],_),this._socket.uncork();else this._socket.write(J[0],_)}}l5.exports=WJ;function N$(J,_,$){if(typeof $==="function")$(_);for(let X=0;X<J._queue.length;X++){let A=J._queue[X],G=A[A.length-1];if(typeof G==="function")G(_)}}function E7(J,_,$){N$(J,_,$),J.onerror(_)}});var e5=D((g9,t5)=>{var{kForOnEventAttribute:p0,kListener:Y$}=ZJ(),p5=Symbol("kCode"),i5=Symbol("kData"),n5=Symbol("kError"),r5=Symbol("kMessage"),o5=Symbol("kReason"),j0=Symbol("kTarget"),a5=Symbol("kType"),s5=Symbol("kWasClean");class wJ{constructor(J){this[j0]=null,this[a5]=J}get target(){return this[j0]}get type(){return this[a5]}}Object.defineProperty(wJ.prototype,"target",{enumerable:!0});Object.defineProperty(wJ.prototype,"type",{enumerable:!0});class C0 extends wJ{constructor(J,_={}){super(J);this[p5]=_.code===void 0?0:_.code,this[o5]=_.reason===void 0?"":_.reason,this[s5]=_.wasClean===void 0?!1:_.wasClean}get code(){return this[p5]}get reason(){return this[o5]}get wasClean(){return this[s5]}}Object.defineProperty(C0.prototype,"code",{enumerable:!0});Object.defineProperty(C0.prototype,"reason",{enumerable:!0});Object.defineProperty(C0.prototype,"wasClean",{enumerable:!0});class i0 extends wJ{constructor(J,_={}){super(J);this[n5]=_.error===void 0?null:_.error,this[r5]=_.message===void 0?"":_.message}get error(){return this[n5]}get message(){return this[r5]}}Object.defineProperty(i0.prototype,"error",{enumerable:!0});Object.defineProperty(i0.prototype,"message",{enumerable:!0});class f_ extends wJ{constructor(J,_={}){super(J);this[i5]=_.data===void 0?null:_.data}get data(){return this[i5]}}Object.defineProperty(f_.prototype,"data",{enumerable:!0});var j7={addEventListener(J,_,$={}){for(let A of this.listeners(J))if(!$[p0]&&A[Y$]===_&&!A[p0])return;let X;if(J==="message")X=function A(G,K){let Q=new f_("message",{data:K?G:G.toString()});Q[j0]=this,b_(_,this,Q)};else if(J==="close")X=function A(G,K){let Q=new C0("close",{code:G,reason:K.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});Q[j0]=this,b_(_,this,Q)};else if(J==="error")X=function A(G){let K=new i0("error",{error:G,message:G.message});K[j0]=this,b_(_,this,K)};else if(J==="open")X=function A(){let G=new wJ("open");G[j0]=this,b_(_,this,G)};else return;if(X[p0]=!!$[p0],X[Y$]=_,$.once)this.once(J,X);else this.on(J,X)},removeEventListener(J,_){for(let $ of this.listeners(J))if($[Y$]===_&&!$[p0]){this.removeListener(J,$);break}}};t5.exports={CloseEvent:C0,ErrorEvent:i0,Event:wJ,EventTarget:j7,MessageEvent:f_};function b_(J,_,$){if(typeof J==="object"&&J.handleEvent)J.handleEvent.call(J,$);else J.call(_,$)}});var g_=D((k9,J6)=>{var{tokenChars:n0}=M0();function VJ(J,_,$){if(J[_]===void 0)J[_]=[$];else J[_].push($)}function C7(J){let _=Object.create(null),$=Object.create(null),X=!1,A=!1,G=!1,K,Q,N=-1,R=-1,Y=-1,H=0;for(;H<J.length;H++)if(R=J.charCodeAt(H),K===void 0)if(Y===-1&&n0[R]===1){if(N===-1)N=H}else if(H!==0&&(R===32||R===9)){if(Y===-1&&N!==-1)Y=H}else if(R===59||R===44){if(N===-1)throw new SyntaxError(`Unexpected character at index ${H}`);if(Y===-1)Y=H;let V=J.slice(N,Y);if(R===44)VJ(_,V,$),$=Object.create(null);else K=V;N=Y=-1}else throw new SyntaxError(`Unexpected character at index ${H}`);else if(Q===void 0)if(Y===-1&&n0[R]===1){if(N===-1)N=H}else if(R===32||R===9){if(Y===-1&&N!==-1)Y=H}else if(R===59||R===44){if(N===-1)throw new SyntaxError(`Unexpected character at index ${H}`);if(Y===-1)Y=H;if(VJ($,J.slice(N,Y),!0),R===44)VJ(_,K,$),$=Object.create(null),K=void 0;N=Y=-1}else if(R===61&&N!==-1&&Y===-1)Q=J.slice(N,H),N=Y=-1;else throw new SyntaxError(`Unexpected character at index ${H}`);else if(A){if(n0[R]!==1)throw new SyntaxError(`Unexpected character at index ${H}`);if(N===-1)N=H;else if(!X)X=!0;A=!1}else if(G)if(n0[R]===1){if(N===-1)N=H}else if(R===34&&N!==-1)G=!1,Y=H;else if(R===92)A=!0;else throw new SyntaxError(`Unexpected character at index ${H}`);else if(R===34&&J.charCodeAt(H-1)===61)G=!0;else if(Y===-1&&n0[R]===1){if(N===-1)N=H}else if(N!==-1&&(R===32||R===9)){if(Y===-1)Y=H}else if(R===59||R===44){if(N===-1)throw new SyntaxError(`Unexpected character at index ${H}`);if(Y===-1)Y=H;let V=J.slice(N,Y);if(X)V=V.replace(/\\/g,""),X=!1;if(VJ($,Q,V),R===44)VJ(_,K,$),$=Object.create(null),K=void 0;Q=void 0,N=Y=-1}else throw new SyntaxError(`Unexpected character at index ${H}`);if(N===-1||G||R===32||R===9)throw new SyntaxError("Unexpected end of input");if(Y===-1)Y=H;let q=J.slice(N,Y);if(K===void 0)VJ(_,q,$);else{if(Q===void 0)VJ($,q,!0);else if(X)VJ($,Q,q.replace(/\\/g,""));else VJ($,Q,q);VJ(_,K,$)}return _}function O7(J){return Object.keys(J).map((_)=>{let $=J[_];if(!Array.isArray($))$=[$];return $.map((X)=>{return[_].concat(Object.keys(X).map((A)=>{let G=X[A];if(!Array.isArray(G))G=[G];return G.map((K)=>K===!0?A:`${A}=${K}`).join("; ")})).join("; ")}).join(", ")}).join(", ")}J6.exports={format:O7,parse:C7}});var c_=D((c9,q6)=>{var F7=x("events"),T7=x("https"),S7=x("http"),X6=x("net"),P7=x("tls"),{randomBytes:W7,createHash:w7}=x("crypto"),{Duplex:m9,Readable:u9}=x("stream"),{URL:H$}=x("url"),IJ=Z0(),I7=Q$(),x7=R$(),{isBlob:D7}=M0(),{BINARY_TYPES:_6,CLOSE_TIMEOUT:v7,EMPTY_BUFFER:k_,GUID:h7,kForOnEventAttribute:q$,kListener:b7,kStatusCode:f7,kWebSocket:c,NOOP:A6}=ZJ(),{EventTarget:{addEventListener:g7,removeEventListener:k7}}=e5(),{format:m7,parse:u7}=g_(),{toBuffer:c7}=d0(),G6=Symbol("kAborted"),V$=[8,13],zJ=["CONNECTING","OPEN","CLOSING","CLOSED"],d7=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class C extends F7{constructor(J,_,$){super();if(this._binaryType=_6[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=k_,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=C.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,J!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,_===void 0)_=[];else if(!Array.isArray(_))if(typeof _==="object"&&_!==null)$=_,_=[];else _=[_];K6(this,J,_,$)}else this._autoPong=$.autoPong,this._closeTimeout=$.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(J){if(!_6.includes(J))return;if(this._binaryType=J,this._receiver)this._receiver._binaryType=J}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}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(J,_,$){let X=new I7({allowSynchronousEvents:$.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxPayload:$.maxPayload,skipUTF8Validation:$.skipUTF8Validation}),A=new x7(J,this._extensions,$.generateMask);if(this._receiver=X,this._sender=A,this._socket=J,X[c]=this,A[c]=this,J[c]=this,X.on("conclude",i7),X.on("drain",n7),X.on("error",r7),X.on("message",o7),X.on("ping",a7),X.on("pong",s7),A.onerror=t7,J.setTimeout)J.setTimeout(0);if(J.setNoDelay)J.setNoDelay();if(_.length>0)J.unshift(_);J.on("close",R6),J.on("data",u_),J.on("end",Y6),J.on("error",H6),this._readyState=C.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=C.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[IJ.extensionName])this._extensions[IJ.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=C.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(J,_){if(this.readyState===C.CLOSED)return;if(this.readyState===C.CONNECTING){s(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===C.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=C.CLOSING,this._sender.close(J,_,!this._isServer,($)=>{if($)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),N6(this)}pause(){if(this.readyState===C.CONNECTING||this.readyState===C.CLOSED)return;this._paused=!0,this._socket.pause()}ping(J,_,$){if(this.readyState===C.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof J==="function")$=J,J=_=void 0;else if(typeof _==="function")$=_,_=void 0;if(typeof J==="number")J=J.toString();if(this.readyState!==C.OPEN){y$(this,J,$);return}if(_===void 0)_=!this._isServer;this._sender.ping(J||k_,_,$)}pong(J,_,$){if(this.readyState===C.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof J==="function")$=J,J=_=void 0;else if(typeof _==="function")$=_,_=void 0;if(typeof J==="number")J=J.toString();if(this.readyState!==C.OPEN){y$(this,J,$);return}if(_===void 0)_=!this._isServer;this._sender.pong(J||k_,_,$)}resume(){if(this.readyState===C.CONNECTING||this.readyState===C.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(J,_,$){if(this.readyState===C.CONNECTING)throw new Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof _==="function")$=_,_={};if(typeof J==="number")J=J.toString();if(this.readyState!==C.OPEN){y$(this,J,$);return}let X={binary:typeof J!=="string",mask:!this._isServer,compress:!0,fin:!0,..._};if(!this._extensions[IJ.extensionName])X.compress=!1;this._sender.send(J||k_,X,$)}terminate(){if(this.readyState===C.CLOSED)return;if(this.readyState===C.CONNECTING){s(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=C.CLOSING,this._socket.destroy()}}Object.defineProperty(C,"CONNECTING",{enumerable:!0,value:zJ.indexOf("CONNECTING")});Object.defineProperty(C.prototype,"CONNECTING",{enumerable:!0,value:zJ.indexOf("CONNECTING")});Object.defineProperty(C,"OPEN",{enumerable:!0,value:zJ.indexOf("OPEN")});Object.defineProperty(C.prototype,"OPEN",{enumerable:!0,value:zJ.indexOf("OPEN")});Object.defineProperty(C,"CLOSING",{enumerable:!0,value:zJ.indexOf("CLOSING")});Object.defineProperty(C.prototype,"CLOSING",{enumerable:!0,value:zJ.indexOf("CLOSING")});Object.defineProperty(C,"CLOSED",{enumerable:!0,value:zJ.indexOf("CLOSED")});Object.defineProperty(C.prototype,"CLOSED",{enumerable:!0,value:zJ.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((J)=>{Object.defineProperty(C.prototype,J,{enumerable:!0})});["open","error","close","message"].forEach((J)=>{Object.defineProperty(C.prototype,`on${J}`,{enumerable:!0,get(){for(let _ of this.listeners(J))if(_[q$])return _[b7];return null},set(_){for(let $ of this.listeners(J))if($[q$]){this.removeListener(J,$);break}if(typeof _!=="function")return;this.addEventListener(J,_,{[q$]:!0})}})});C.prototype.addEventListener=g7;C.prototype.removeEventListener=k7;q6.exports=C;function K6(J,_,$,X){let A={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:v7,protocolVersion:V$[1],maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...X,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(J._autoPong=A.autoPong,J._closeTimeout=A.closeTimeout,!V$.includes(A.protocolVersion))throw new RangeError(`Unsupported protocol version: ${A.protocolVersion} (supported versions: ${V$.join(", ")})`);let G;if(_ instanceof H$)G=_;else try{G=new H$(_)}catch{throw new SyntaxError(`Invalid URL: ${_}`)}if(G.protocol==="http:")G.protocol="ws:";else if(G.protocol==="https:")G.protocol="wss:";J._url=G.href;let K=G.protocol==="wss:",Q=G.protocol==="ws+unix:",N;if(G.protocol!=="ws:"&&!K&&!Q)N=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(Q&&!G.pathname)N="The URL's pathname is empty";else if(G.hash)N="The URL contains a fragment identifier";if(N){let B=new SyntaxError(N);if(J._redirects===0)throw B;else{m_(J,B);return}}let R=K?443:80,Y=W7(16).toString("base64"),H=K?T7.request:S7.request,q=new Set,V;if(A.createConnection=A.createConnection||(K?p7:l7),A.defaultPort=A.defaultPort||R,A.port=G.port||R,A.host=G.hostname.startsWith("[")?G.hostname.slice(1,-1):G.hostname,A.headers={...A.headers,"Sec-WebSocket-Version":A.protocolVersion,"Sec-WebSocket-Key":Y,Connection:"Upgrade",Upgrade:"websocket"},A.path=G.pathname+G.search,A.timeout=A.handshakeTimeout,A.perMessageDeflate)V=new IJ({...A.perMessageDeflate,isServer:!1,maxPayload:A.maxPayload}),A.headers["Sec-WebSocket-Extensions"]=m7({[IJ.extensionName]:V.offer()});if($.length){for(let B of $){if(typeof B!=="string"||!d7.test(B)||q.has(B))throw new SyntaxError("An invalid or duplicated subprotocol was specified");q.add(B)}A.headers["Sec-WebSocket-Protocol"]=$.join(",")}if(A.origin)if(A.protocolVersion<13)A.headers["Sec-WebSocket-Origin"]=A.origin;else A.headers.Origin=A.origin;if(G.username||G.password)A.auth=`${G.username}:${G.password}`;if(Q){let B=A.path.split(":");A.socketPath=B[0],A.path=B[1]}let y;if(A.followRedirects){if(J._redirects===0){J._originalIpc=Q,J._originalSecure=K,J._originalHostOrSocketPath=Q?A.socketPath:G.host;let B=X&&X.headers;if(X={...X,headers:{}},B)for(let[M,Z]of Object.entries(B))X.headers[M.toLowerCase()]=Z}else if(J.listenerCount("redirect")===0){let B=Q?J._originalIpc?A.socketPath===J._originalHostOrSocketPath:!1:J._originalIpc?!1:G.host===J._originalHostOrSocketPath;if(!B||J._originalSecure&&!K){if(delete A.headers.authorization,delete A.headers.cookie,!B)delete A.headers.host;A.auth=void 0}}if(A.auth&&!X.headers.authorization)X.headers.authorization="Basic "+Buffer.from(A.auth).toString("base64");if(y=J._req=H(A),J._redirects)J.emit("redirect",J.url,y)}else y=J._req=H(A);if(A.timeout)y.on("timeout",()=>{s(J,y,"Opening handshake has timed out")});if(y.on("error",(B)=>{if(y===null||y[G6])return;y=J._req=null,m_(J,B)}),y.on("response",(B)=>{let M=B.headers.location,Z=B.statusCode;if(M&&A.followRedirects&&Z>=300&&Z<400){if(++J._redirects>A.maxRedirects){s(J,y,"Maximum redirects exceeded");return}y.abort();let O;try{O=new H$(M,_)}catch(I){let P=new SyntaxError(`Invalid URL: ${M}`);m_(J,P);return}K6(J,O,$,X)}else if(!J.emit("unexpected-response",y,B))s(J,y,`Unexpected server response: ${B.statusCode}`)}),y.on("upgrade",(B,M,Z)=>{if(J.emit("upgrade",B),J.readyState!==C.CONNECTING)return;y=J._req=null;let O=B.headers.upgrade;if(O===void 0||O.toLowerCase()!=="websocket"){s(J,M,"Invalid Upgrade header");return}let I=w7("sha1").update(Y+h7).digest("base64");if(B.headers["sec-websocket-accept"]!==I){s(J,M,"Invalid Sec-WebSocket-Accept header");return}let P=B.headers["sec-websocket-protocol"],g;if(P!==void 0){if(!q.size)g="Server sent a subprotocol but none was requested";else if(!q.has(P))g="Server sent an invalid subprotocol"}else if(q.size)g="Server sent no subprotocol";if(g){s(J,M,g);return}if(P)J._protocol=P;let tJ=B.headers["sec-websocket-extensions"];if(tJ!==void 0){if(!V){s(J,M,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let w;try{w=u7(tJ)}catch(k){s(J,M,"Invalid Sec-WebSocket-Extensions header");return}let o=Object.keys(w);if(o.length!==1||o[0]!==IJ.extensionName){s(J,M,"Server indicated an extension that was not requested");return}try{V.accept(w[IJ.extensionName])}catch(k){s(J,M,"Invalid Sec-WebSocket-Extensions header");return}J._extensions[IJ.extensionName]=V}J.setSocket(M,Z,{allowSynchronousEvents:A.allowSynchronousEvents,generateMask:A.generateMask,maxPayload:A.maxPayload,skipUTF8Validation:A.skipUTF8Validation})}),A.finishRequest)A.finishRequest(y,J);else y.end()}function m_(J,_){J._readyState=C.CLOSING,J._errorEmitted=!0,J.emit("error",_),J.emitClose()}function l7(J){return J.path=J.socketPath,X6.connect(J)}function p7(J){if(J.path=void 0,!J.servername&&J.servername!=="")J.servername=X6.isIP(J.host)?"":J.host;return P7.connect(J)}function s(J,_,$){J._readyState=C.CLOSING;let X=new Error($);if(Error.captureStackTrace(X,s),_.setHeader){if(_[G6]=!0,_.abort(),_.socket&&!_.socket.destroyed)_.socket.destroy();process.nextTick(m_,J,X)}else _.destroy(X),_.once("error",J.emit.bind(J,"error")),_.once("close",J.emitClose.bind(J))}function y$(J,_,$){if(_){let X=D7(_)?_.size:c7(_).length;if(J._socket)J._sender._bufferedBytes+=X;else J._bufferedAmount+=X}if($){let X=new Error(`WebSocket is not open: readyState ${J.readyState} (${zJ[J.readyState]})`);process.nextTick($,X)}}function i7(J,_){let $=this[c];if($._closeFrameReceived=!0,$._closeMessage=_,$._closeCode=J,$._socket[c]===void 0)return;if($._socket.removeListener("data",u_),process.nextTick(Q6,$._socket),J===1005)$.close();else $.close(J,_)}function n7(){let J=this[c];if(!J.isPaused)J._socket.resume()}function r7(J){let _=this[c];if(_._socket[c]!==void 0)_._socket.removeListener("data",u_),process.nextTick(Q6,_._socket),_.close(J[f7]);if(!_._errorEmitted)_._errorEmitted=!0,_.emit("error",J)}function $6(){this[c].emitClose()}function o7(J,_){this[c].emit("message",J,_)}function a7(J){let _=this[c];if(_._autoPong)_.pong(J,!this._isServer,A6);_.emit("ping",J)}function s7(J){this[c].emit("pong",J)}function Q6(J){J.resume()}function t7(J){let _=this[c];if(_.readyState===C.CLOSED)return;if(_.readyState===C.OPEN)_._readyState=C.CLOSING,N6(_);if(this._socket.end(),!_._errorEmitted)_._errorEmitted=!0,_.emit("error",J)}function N6(J){J._closeTimer=setTimeout(J._socket.destroy.bind(J._socket),J._closeTimeout)}function R6(){let J=this[c];if(this.removeListener("close",R6),this.removeListener("data",u_),this.removeListener("end",Y6),J._readyState=C.CLOSING,!this._readableState.endEmitted&&!J._closeFrameReceived&&!J._receiver._writableState.errorEmitted&&this._readableState.length!==0){let _=this.read(this._readableState.length);J._receiver.write(_)}if(J._receiver.end(),this[c]=void 0,clearTimeout(J._closeTimer),J._receiver._writableState.finished||J._receiver._writableState.errorEmitted)J.emitClose();else J._receiver.on("error",$6),J._receiver.on("finish",$6)}function u_(J){if(!this[c]._receiver.write(J))this.pause()}function Y6(){let J=this[c];J._readyState=C.CLOSING,J._receiver.end(),this.end()}function H6(){let J=this[c];if(this.removeListener("error",H6),this.on("error",A6),J)J._readyState=C.CLOSING,this.destroy()}});var B6=D((l9,L6)=>{var d9=c_(),{Duplex:e7}=x("stream");function V6(J){J.emit("close")}function JG(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function y6(J){if(this.removeListener("error",y6),this.destroy(),this.listenerCount("error")===0)this.emit("error",J)}function _G(J,_){let $=!0,X=new e7({..._,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return J.on("message",function A(G,K){let Q=!K&&X._readableState.objectMode?G.toString():G;if(!X.push(Q))J.pause()}),J.once("error",function A(G){if(X.destroyed)return;$=!1,X.destroy(G)}),J.once("close",function A(){if(X.destroyed)return;X.push(null)}),X._destroy=function(A,G){if(J.readyState===J.CLOSED){G(A),process.nextTick(V6,X);return}let K=!1;if(J.once("error",function Q(N){K=!0,G(N)}),J.once("close",function Q(){if(!K)G(A);process.nextTick(V6,X)}),$)J.terminate()},X._final=function(A){if(J.readyState===J.CONNECTING){J.once("open",function G(){X._final(A)});return}if(J._socket===null)return;if(J._socket._writableState.finished){if(A(),X._readableState.endEmitted)X.destroy()}else J._socket.once("finish",function G(){A()}),J.close()},X._read=function(){if(J.isPaused)J.resume()},X._write=function(A,G,K){if(J.readyState===J.CONNECTING){J.once("open",function Q(){X._write(A,G,K)});return}J.send(A,K)},X.on("end",JG),X.on("error",y6),X}L6.exports=_G});var L$=D((p9,U6)=>{var{tokenChars:$G}=M0();function XG(J){let _=new Set,$=-1,X=-1,A=0;for(A;A<J.length;A++){let K=J.charCodeAt(A);if(X===-1&&$G[K]===1){if($===-1)$=A}else if(A!==0&&(K===32||K===9)){if(X===-1&&$!==-1)X=A}else if(K===44){if($===-1)throw new SyntaxError(`Unexpected character at index ${A}`);if(X===-1)X=A;let Q=J.slice($,X);if(_.has(Q))throw new SyntaxError(`The "${Q}" subprotocol is duplicated`);_.add(Q),$=X=-1}else throw new SyntaxError(`Unexpected character at index ${A}`)}if($===-1||X!==-1)throw new SyntaxError("Unexpected end of input");let G=J.slice($,A);if(_.has(G))throw new SyntaxError(`The "${G}" subprotocol is duplicated`);return _.add(G),_}U6.exports={parse:XG}});var j6=D((n9,E6)=>{var AG=x("events"),d_=x("http"),{Duplex:i9}=x("stream"),{createHash:GG}=x("crypto"),Z6=g_(),nJ=Z0(),KG=L$(),QG=c_(),{CLOSE_TIMEOUT:NG,GUID:RG,kWebSocket:YG}=ZJ(),HG=/^[+/0-9A-Za-z]{22}==$/;class z6 extends AG{constructor(J,_){super();if(J={allowSynchronousEvents:!0,autoPong:!0,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:NG,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:QG,...J},J.port==null&&!J.server&&!J.noServer||J.port!=null&&(J.server||J.noServer)||J.server&&J.noServer)throw new TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(J.port!=null)this._server=d_.createServer(($,X)=>{let A=d_.STATUS_CODES[426];X.writeHead(426,{"Content-Length":A.length,"Content-Type":"text/plain"}),X.end(A)}),this._server.listen(J.port,J.host,J.backlog,_);else if(J.server)this._server=J.server;if(this._server){let $=this.emit.bind(this,"connection");this._removeListeners=qG(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(X,A,G)=>{this.handleUpgrade(X,A,G,$)}})}if(J.perMessageDeflate===!0)J.perMessageDeflate={};if(J.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=J,this._state=0}address(){if(this.options.noServer)throw new Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(J){if(this._state===2){if(J)this.once("close",()=>{J(new Error("The server is not running"))});process.nextTick(r0,this);return}if(J)this.once("close",J);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick(r0,this);else this._shouldEmitClose=!0;else process.nextTick(r0,this)}else{let _=this._server;this._removeListeners(),this._removeListeners=this._server=null,_.close(()=>{r0(this)})}}shouldHandle(J){if(this.options.path){let _=J.url.indexOf("?");if((_!==-1?J.url.slice(0,_):J.url)!==this.options.path)return!1}return!0}handleUpgrade(J,_,$,X){_.on("error",M6);let A=J.headers["sec-websocket-key"],G=J.headers.upgrade,K=+J.headers["sec-websocket-version"];if(J.method!=="GET"){rJ(this,J,_,405,"Invalid HTTP method");return}if(G===void 0||G.toLowerCase()!=="websocket"){rJ(this,J,_,400,"Invalid Upgrade header");return}if(A===void 0||!HG.test(A)){rJ(this,J,_,400,"Missing or invalid Sec-WebSocket-Key header");return}if(K!==13&&K!==8){rJ(this,J,_,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(J)){o0(_,400);return}let Q=J.headers["sec-websocket-protocol"],N=new Set;if(Q!==void 0)try{N=KG.parse(Q)}catch(H){rJ(this,J,_,400,"Invalid Sec-WebSocket-Protocol header");return}let R=J.headers["sec-websocket-extensions"],Y={};if(this.options.perMessageDeflate&&R!==void 0){let H=new nJ({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let q=Z6.parse(R);if(q[nJ.extensionName])H.accept(q[nJ.extensionName]),Y[nJ.extensionName]=H}catch(q){rJ(this,J,_,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let H={origin:J.headers[`${K===8?"sec-websocket-origin":"origin"}`],secure:!!(J.socket.authorized||J.socket.encrypted),req:J};if(this.options.verifyClient.length===2){this.options.verifyClient(H,(q,V,y,B)=>{if(!q)return o0(_,V||401,y,B);this.completeUpgrade(Y,A,N,J,_,$,X)});return}if(!this.options.verifyClient(H))return o0(_,401)}this.completeUpgrade(Y,A,N,J,_,$,X)}completeUpgrade(J,_,$,X,A,G,K){if(!A.readable||!A.writable)return A.destroy();if(A[YG])throw new Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return o0(A,503);let N=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${GG("sha1").update(_+RG).digest("base64")}`],R=new this.options.WebSocket(null,void 0,this.options);if($.size){let Y=this.options.handleProtocols?this.options.handleProtocols($,X):$.values().next().value;if(Y)N.push(`Sec-WebSocket-Protocol: ${Y}`),R._protocol=Y}if(J[nJ.extensionName]){let Y=J[nJ.extensionName].params,H=Z6.format({[nJ.extensionName]:[Y]});N.push(`Sec-WebSocket-Extensions: ${H}`),R._extensions=J}if(this.emit("headers",N,X),A.write(N.concat(`\r
|
|
6
|
-
`).
|
|
7
|
-
`)),
|
|
8
|
-
|
|
9
|
-
`)
|
|
10
|
-
\r
|
|
11
|
-
`+$)}function rJ(J,_,$,X,A,G){if(J.listenerCount("wsClientError")){let K=new Error(A);Error.captureStackTrace(K,rJ),J.emit("wsClientError",K,$,_)}else o0($,X,A,G)}});var q3=HJ(u$(),1);import XX from"node:fs";import l$ from"node:fs";import p$ from"node:os";import vJ from"node:path";import{fileURLToPath as Z8}from"node:url";import L8 from"node:fs";import c$ from"node:path";import B8 from"node:os";function d$(){if(typeof globalThis.Bun==="undefined")return!1;try{return String(import.meta.url).includes("/$bunfs/")}catch{return!1}}function U8(){return c$.join(B8.homedir(),".everclaw","cache","embedded","0.3.0")}function X1(){if(!d$())return null;let J=U8();return L8.existsSync(c$.join(J,".extracted"))?J:null}var G1=".everclaw",T0="~/.everclaw/config.json",i$=vJ.join("~",G1,"workspace");function n$(J=p$.homedir()){return vJ.join(J,G1,"workspace")}function r$(J=p$.homedir()){return vJ.join(J,G1,"config.json")}function M8(){let J=X1();if(J)return J;let _=Z8(import.meta.url),$=vJ.dirname(_);if(_.endsWith("/index.js")||_.endsWith("\\index.js"))return $;return vJ.resolve($,"..")}var A1=null;function o$(){if(A1===null)A1=M8();return A1}function a$(...J){let _=vJ.resolve(o$(),...J);if(!l$.existsSync(_))throw new Error(`Runtime asset not found: ${_}`);return _}function $_(...J){let _=vJ.resolve(o$(),...J);return l$.existsSync(_)?_:null}var z8=[{spec:{name:"zai",keywords:["zai"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://api.z.ai/api/coding/paas/v4"},models:["glm-5-turbo"]},{spec:{name:"openrouter",displayName:"OpenRouter",keywords:["openrouter"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://openrouter.ai/api/v1",detectByKeyPrefix:"sk-or-",detectByBaseKeyword:"openrouter"},models:["anthropic/claude-opus-4-1","anthropic/claude-sonnet-4","openai/gpt-4.1","google/gemini-2.5-pro"]},{spec:{name:"aihubmix",displayName:"AIHubMix",keywords:["aihubmix"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://aihubmix.com/v1",detectByBaseKeyword:"aihubmix"},models:[]},{spec:{name:"siliconflow",displayName:"SiliconFlow",keywords:["siliconflow"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://api.siliconflow.cn/v1",detectByBaseKeyword:"siliconflow"},models:["openai/deepseek-ai/DeepSeek-R1"]},{spec:{name:"volcengine",displayName:"VolcEngine",keywords:["volcengine","volces","ark"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://ark.cn-beijing.volces.com/api/v3",detectByBaseKeyword:"volces"},models:["volcengine/deepseek-r1-250120"]},{spec:{name:"anthropic",displayName:"Anthropic",keywords:["anthropic","claude"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["anthropic/claude-opus-4-5","anthropic/claude-sonnet-4"]},{spec:{name:"openai",displayName:"OpenAI",keywords:["openai","gpt"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["gpt-5.2","gpt-5.2-pro","gpt-5.3-codex","gpt-5.2-codex","gpt-5.1","gpt-5.1-codex","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"]},{spec:{name:"openai_codex",displayName:"OpenAI Codex",keywords:["openai-codex","codex"],isOauth:!0,isGateway:!1,isLocal:!1,defaultApiBase:"https://chatgpt.com/backend-api"},models:[]},{spec:{name:"github_copilot",displayName:"GitHub Copilot",keywords:["github_copilot","copilot"],isOauth:!0,isGateway:!1,isLocal:!1,defaultApiBase:""},models:[]},{spec:{name:"deepseek",displayName:"DeepSeek",keywords:["deepseek"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["deepseek/deepseek-chat","deepseek/deepseek-reasoner"]},{spec:{name:"gemini",displayName:"Google Gemini",keywords:["gemini"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["gemini/gemini-3-flash-preview","gemini/gemini-2.5-pro","gemini/gemini-2.5-flash"]},{spec:{name:"zhipu",displayName:"Zhipu AI",keywords:["zhipu","glm","zai"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["zai/glm-4.5"]},{spec:{name:"dashscope",displayName:"DashScope",keywords:["qwen","dashscope"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["dashscope/qwen-max"]},{spec:{name:"moonshot",displayName:"Moonshot AI",keywords:["moonshot","kimi"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:"https://api.moonshot.ai/v1"},models:["moonshot/kimi-k2.5"]},{spec:{name:"minimax",displayName:"MiniMax",keywords:["minimax"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:"https://api.minimax.io/v1"},models:["minimax/MiniMax-M2.1"]},{spec:{name:"vllm",displayName:"vLLM",keywords:["vllm"],isOauth:!1,isGateway:!1,isLocal:!0,defaultApiBase:""},models:["hosted_vllm/llama-3.1-8b-instruct"]},{spec:{name:"groq",displayName:"Groq",keywords:["groq"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["openai/gpt-oss-120b","openai/gpt-oss-20b","meta-llama/llama-4-maverick-17b-128e-instruct","groq/compound","groq/compound-mini"]},{spec:{name:"ollama",displayName:"Ollama",keywords:["ollama"],isOauth:!1,isGateway:!1,isLocal:!0,defaultApiBase:"http://localhost:11434/v1"},models:["ollama/llama3.3","ollama/qwen2.5","ollama/deepseek-r1"]}];function K1(){return z8.map((J)=>J.spec)}var S0=K1(),E8=Object.fromEntries(K1().map((J)=>[J.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),X_="custom:",P0={agents:{defaults:{workspace:i$,model:"gpt-4.1",provider:"auto",maxTokens:8192,temperature:0.1,maxToolIterations:40,memoryWindow:100}},subagents:[{id:"researcher",name:"Researcher",task:"Research the given topic thoroughly and provide detailed findings.",createdAt:0},{id:"advisor",name:"Advisor",task:"Analyze the current conversation context and provide exactly 3 concise suggestion options for the user's next logical message. Reply with a JSON array of 3 strings.",createdAt:0}],channels:{sendProgress:!0,sendToolHints:!1,telegram:{enabled:!1,token:"",allowFrom:[],proxy:null,replyToMessage:!1,debounce:{enabled:!0,quietMs:500,maxWaitMs:3000},groups:{requireMention:!0,allowedGroupIds:null},commands:{native:!0,custom:[]}},discord:{enabled:!1,token:"",allowFrom:[],gatewayUrl:"wss://gateway.discord.gg/?v=10&encoding=json",intents:37377,debounce:{enabled:!0,quietMs:500,maxWaitMs:3000}}},providers:E8,customLlmProviders:[],customAcpProviders:[],gateway:{host:"127.0.0.1",port:6767,dashboard:{enabled:!0},heartbeat:{enabled:!0,intervalS:1800}},tools:{web:{search:{apiKey:"",maxResults:5}},exec:{timeout:60,pathAppend:""},restrictToWorkspace:!1,mcpServers:{},chromeSession:{enabled:!1,debugPort:9222,minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8,stealth:{enabled:!1,cursorMovement:!0,humanizedTyping:!0,interStepDelay:[300,1500]}},browserRelay:{enabled:!1,authToken:"",extensionPath:""},rtk:{enabled:!0,autoInstall:!0,ultraCompact:!1,version:"latest"}},security:{enabled:!1,auth:{enabled:!1,pinHash:"",sessionTtlS:3600,lockOnIdle:!1,idleTimeoutS:900},toolGuard:{enabled:!1,guardedTools:null,deniedTools:[],rules:[],failOpen:!0},skillScanner:{enabled:!1,scanOnLoad:!1,blockUnsafe:!0,maxFileCount:1000,maxFileSizeBytes:5242880},inputSanitizer:{enabled:!1,maxInputLength:50000,stripHtmlTags:!1,blockPromptInjection:!1}},logging:{enabled:!0,level:"info",retentionHours:4,maxFileSizeMb:10,purgeIntervalMs:600000},compaction:{enabled:!0,microCompactThresholdRatio:0.6,autoCompactThresholdRatio:0.8,keepRecentMessages:10,maxConsecutiveFailures:3}};function eJ(J){return J.toLowerCase().replace(/[\s-]+/g,"_")}function s$(J){return`${X_}${eJ(J)}`}function t$(J,_){let $=eJ(_.startsWith(X_)?_.slice(X_.length):_);return J.customLlmProviders.find((X)=>eJ(X.name)===$)??null}function j8(J,_){if(!_.includes("/"))return null;let X=_.split("/",1)[0];if(!X)return null;return t$(J,X)}function hJ(J){return!!J&&J.startsWith(X_)}function J0(J,_,$){let X=(_??J.agents.defaults.provider).trim();if(X&&X!=="auto"&&!J.providers[X])return t$(J,X);let A=j8(J,$??J.agents.defaults.model);if(A)return A;let G=J.customLlmProviders.filter((K)=>K.name.trim()&&K.baseUrl.trim());return G.length===1?G[0]??null:null}function A_(J,_){let $=J.agents.defaults.provider;if($!=="auto"){if(J.providers[$])return $;let Q=J0(J,$,_);return Q?s$(Q.name):null}let X=(_??J.agents.defaults.model).toLowerCase(),A=eJ(X),G=X.includes("/")?X.split("/",1)[0]:"";for(let Q of S0){let N=J.providers[Q.name];if(G&&eJ(G)===Q.name&&(Q.isOauth||N?.apiKey))return Q.name}for(let Q of S0){let N=J.providers[Q.name];if(Q.keywords.some((R)=>X.includes(R)||A.includes(eJ(R)))&&(Q.isOauth||N?.apiKey))return Q.name}for(let Q of S0){if(Q.isOauth)continue;if(J.providers[Q.name]?.apiKey)return Q.name}let K=J0(J,$,_);if(K)return s$(K.name);return null}function e$(J,_){let $=A_(J,_);if($&&hJ($)){let X=J0(J,$,_);return X?{apiKey:X.apiKey,apiBase:X.baseUrl,extraHeaders:X.extraHeaders}:null}return $?J.providers[$]??null:null}function G_(J,_){let $=A_(J,_);if(!$)return null;if(hJ($))return J0(J,$,_)?.baseUrl??null;let X=J.providers[$];if(X?.apiBase)return X.apiBase;let A=S0.find((G)=>G.name===$);return A?.isGateway?A.defaultApiBase:null}import C8 from"node:fs";import O8 from"node:path";import JX from"node:os";function _X(J){return C8.mkdirSync(J,{recursive:!0}),J}function $X(J){let _=J?J.replace(/^~(?=$|[\\/])/,JX.homedir()):n$(JX.homedir());return _X(O8.resolve(_))}function T8(){return r$()}function AX(J,_){if(!_||typeof _!=="object")return J;let $=Array.isArray(J)?[...J]:{...J};for(let[X,A]of Object.entries(_))if(A&&typeof A==="object"&&!Array.isArray(A)&&$[X]&&typeof $[X]==="object"&&!Array.isArray($[X]))$[X]=AX($[X],A);else $[X]=A;return $}function GX(J){let _=J??T8();if(!XX.existsSync(_))return structuredClone(P0);try{let $=XX.readFileSync(_,"utf8"),X=JSON.parse($),A=AX(structuredClone(P0),X),G=["advisor"];for(let K of G)if(!A.subagents.find((Q)=>Q.id===K)){let Q=P0.subagents.find((N)=>N.id===K);if(Q)A.subagents.push(structuredClone(Q))}return A}catch($){return console.warn(`Warning: Failed to load config from ${_}: ${String($)}`),structuredClone(P0)}}function W0(J){return J.map((_)=>{let $=_.content;if(typeof $==="string"&&$.length===0){if(_.role==="assistant"&&_.tool_calls)return{..._,content:null};return{..._,content:"(empty)"}}if(Array.isArray($)){let X=$.filter((A)=>!(typeof A==="object"&&A&&["text","input_text","output_text"].includes(A.type)&&!A.text));if(X.length!==$.length){if(X.length>0)return{..._,content:X};if(_.role==="assistant"&&_.tool_calls)return{..._,content:null};return{..._,content:"(empty)"}}}return _})}function Q1(){let J=new Error("Operation aborted");return J.name="AbortError",J}function l(J){return J instanceof Error&&J.name==="AbortError"}function u(J){if(J?.aborted)throw Q1()}function KX(J){return J.trim().toLowerCase().replace(/[\s-]+/g,"_")}function QX(J){if(typeof J!=="string")return J&&typeof J==="object"?J:{};try{return JSON.parse(J)}catch{return{}}}class N1{apiKey;apiBase;defaultModel;options;constructor(J,_,$,X={}){this.apiKey=J;this.apiBase=_;this.defaultModel=$;this.options=X}getDefaultModel(){return this.defaultModel}get requestFormat(){return this.options.apiFormat??"v1/chat/completions"}resolveModel(J){let _=J.trim();if(!_.includes("/"))return _;let $=_.split("/",2),X=$[0],A=$[1];if(!X||!A)return _;return new Set(["custom",KX(this.options.providerLabel??"")]).has(KX(X))?A:_}buildHeaders(){let J={"Content-Type":"application/json",...this.options.extraHeaders??{}};if(this.apiKey.trim())J.Authorization=`Bearer ${this.apiKey}`;return J}async readJson(J){try{return await J.json()}catch{return{}}}async chatCompletions(J){let _=await fetch(`${this.apiBase.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({model:this.resolveModel(J.model??this.defaultModel),messages:W0(J.messages),tools:J.tools,tool_choice:J.tools?.length?J.toolChoice??"auto":void 0,max_tokens:Math.max(1,J.maxTokens??4096),temperature:J.temperature??0.7,...J.reasoning?{reasoning_effort:"medium"}:{},...J.imageOutput?{include_image_output:!0}:{}}),...J.signal?{signal:J.signal}:{}}),$=await this.readJson(_);if(!_.ok)return{content:`Error calling LLM: ${$?.error?.message??JSON.stringify($)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let X=$.choices?.[0];if(!X?.message)return{content:`Error calling LLM: ${JSON.stringify($)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let A=(X.message.tool_calls??[]).map((G)=>({id:G.id,name:G.function.name,arguments:QX(G.function.arguments)}));return{content:X.message.content??null,toolCalls:A,finishReason:X.finish_reason??"stop",usage:{prompt_tokens:$.usage?.prompt_tokens??0,completion_tokens:$.usage?.completion_tokens??0,total_tokens:$.usage?.total_tokens??0},reasoningContent:X.message.reasoning_content??null}}toResponsesInput(J){let _=[];for(let $ of W0(J)){let X=String($.role??"");if(X==="tool"){_.push({type:"function_call_output",call_id:String($.tool_call_id??""),output:typeof $.content==="string"?$.content:JSON.stringify($.content??null)});continue}if(X==="assistant"&&Array.isArray($.tool_calls))for(let A of $.tool_calls)_.push({type:"function_call",call_id:String(A.id??""),name:String(A.name??""),arguments:typeof A.arguments==="string"?A.arguments:JSON.stringify(A.arguments??{})});if(X==="system"||X==="user"||X==="assistant")_.push({role:X,content:$.content??""})}return _}async responses(J){let _=await fetch(`${this.apiBase.replace(/\/$/,"")}/responses`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({model:this.resolveModel(J.model??this.defaultModel),input:this.toResponsesInput(J.messages),tools:J.tools,tool_choice:J.tools?.length?J.toolChoice??"auto":void 0,max_output_tokens:Math.max(1,J.maxTokens??4096),temperature:J.temperature??0.7,...J.reasoning?{reasoning:{effort:"medium"}}:{},...J.imageOutput?{include_image_output:!0}:{}}),...J.signal?{signal:J.signal}:{}}),$=await this.readJson(_);if(!_.ok)return{content:`Error calling LLM: ${$?.error?.message??JSON.stringify($)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let X=Array.isArray($.output)?$.output:[],A=X.filter((K)=>K?.type==="function_call").map((K)=>({id:String(K.call_id??K.id??""),name:String(K.name??""),arguments:QX(K.arguments)}));return{content:X.filter((K)=>K?.type==="message").flatMap((K)=>Array.isArray(K?.content)?K.content:[]).filter((K)=>K?.type==="output_text").map((K)=>String(K.text??"")).join(`
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
${
|
|
17
|
-
|
|
18
|
-
`)}
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
${
|
|
22
|
-
|
|
23
|
-
Exit code: ${N.exitCode}`:"",q=N.status==="failed"&&N.signal?`
|
|
24
|
-
Signal: ${N.signal}`:"",V=`${R}${Y}${H}${q}`.trim();if(V)return V.length>1e4?`${V.slice(0,1e4)}
|
|
25
|
-
... (truncated, ${V.length-1e4} more chars)`:V;if(N.status==="failed")return N.errorMessage?`Error executing command: ${N.errorMessage}`:"Error executing command";return"(no output)"}}var V5={general:{name:"general",description:"General-purpose subagent with full tool access",systemPromptSuffix:"Complete the assigned task using all available tools."},researcher:{name:"researcher",description:"Read-only researcher — no file modifications",systemPromptSuffix:"Research and report findings. Do NOT modify any files.",allowedTools:["read_file","list_files","search","web_search","web_fetch","session.info","session.search"]},coder:{name:"coder",description:"Code modification specialist",systemPromptSuffix:"Implement the requested code changes.",deniedTools:["web_search","web_fetch"]}};function y5(J){return V5[J]}function L5(){return Object.values(V5)}class s1 extends S{manager;name="spawn";description="Spawn a subagent to handle a task in the background.";parameters={type:"object",properties:{task:{type:"string",description:"The task for the subagent to complete"},label:{type:"string",description:"Optional short label"},model:{type:"string",description:"Optional model override (e.g. 'anthropic/claude-sonnet-4'). Falls back to subagent config or global default if omitted."},provider:{type:"string",description:"Optional provider override (e.g. 'openai'). Falls back to subagent config or global default if omitted."},context:{type:"string",enum:["fresh","fork"],description:"Context mode: 'fresh' (default) starts with minimal context, 'fork' inherits parent conversation for prompt cache reuse."},type:{type:"string",description:`Agent type defining available tools and behavior. Available types: ${L5().map((J)=>`'${J.name}'`).join(", ")}. Defaults to 'general'.`}},required:["task"]};originChannel="cli";originChatId="direct";sessionKey="cli:direct";parentSystemPrompt;constructor(J){super();this.manager=J}setContext(J,_,$=`${J}:${_}`,X){this.originChannel=J,this.originChatId=_,this.sessionKey=$,this.parentSystemPrompt=X}async execute(J,_){let $=J.context??"fresh",X=J.type??"general",A={task:String(J.task??""),label:J.label!=null?String(J.label):null,originChannel:this.originChannel,originChatId:this.originChatId,sessionKey:this.sessionKey,contextMode:$,agentType:X};if(J.model!=null)A.model=String(J.model);if(J.provider!=null)A.providerName=String(J.provider);if($==="fork"&&this.parentSystemPrompt)A.parentSystemPrompt=this.parentSystemPrompt;return this.manager.spawn(A)}}class t1 extends S{name="session.search";description="Search the current session's message history for content matching the query.";parameters={type:"object",properties:{query:{type:"string",description:"The search query to match against message content"},limit:{type:"integer",description:"Maximum number of results to return",minimum:1,maximum:100}},required:["query"]};sessionManager=null;sessionKey="cli:direct";constructor(){super()}setSessionManager(J){this.sessionManager=J}setContext(J){this.sessionKey=J}async execute(J,_){if(!this.sessionManager)return"Error: Session manager not available";let $=String(J.query??""),X=typeof J.limit==="number"?Math.min(Math.max(1,Math.floor(J.limit)),100):10;if(!$)return"Error: Query cannot be empty";let G=this.sessionManager.getOrCreate(this.sessionKey).search($,X);return JSON.stringify(G,null,2)}}import z5 from"node:fs";import w_ from"node:path";import E5 from"node:os";import m0 from"node:fs";import S_ from"node:path";var uA={"gpt-4.1":1047576,"gpt-4.1-mini":1047576,"gpt-4.1-nano":1047576,"gpt-4o":128000,"gpt-4o-mini":128000,"gpt-4-turbo":128000,"gpt-4":8192,"gpt-3.5-turbo":16385,"claude-sonnet-4":200000,"claude-sonnet-4-20250514":200000,"claude-3-5-sonnet":200000,"claude-3-5-sonnet-20241022":200000,"claude-3-5-haiku":200000,"claude-3-opus":200000,"claude-3-sonnet":200000,"claude-3-haiku":200000,"gemini-2.5-pro":1e6,"gemini-2.0-flash":1e6,"gemini-1.5-pro":1e6,"gemini-1.5-flash":1e6,"deepseek-chat":64000,"deepseek-reasoner":64000,"grok-2":131072,"grok-2-mini":131072};function T_(J){if(!J)return 0;let _=typeof J==="string"?J:JSON.stringify(J);return Math.ceil(_.length/4)}function B5(J,_){if(_){let X=_.providers?.[_.agents.defaults.provider]?.models?.find((A)=>A.id.toLowerCase()===J.toLowerCase())?.capabilities;if(X?.contextWindow)return X.contextWindow;for(let A of _.customLlmProviders??[]){let G=A.models.find((K)=>K.id.toLowerCase()===J.toLowerCase());if(G?.capabilities?.contextWindow)return G.capabilities.contextWindow}}let $=J.toLowerCase();for(let[X,A]of Object.entries(uA))if(X.toLowerCase()===$||$.includes(X.toLowerCase()))return A;return 128000}var U5=1000,cA=250,P_=`
|
|
26
|
-
... (truncated for archival)`;function Z5(J){return Math.max(0,Math.floor(J*4))}function dA(J,_){if(_<=0)return"";let $=Z5(_);if(J.length<=$)return J;let X=Math.max(0,$-P_.length);return`${P_}${J.slice(-X)}`}function lA(J,_){if(_<=0||J.length===0)return{text:"",omittedLines:J.length};let $=Z5(_),X=[],A=0,G=0;for(let K=J.length-1;K>=0;K--){let Q=J[K],N=X.length?1:0,R=$-A-N;if(R<=0){G=K+1;break}if(Q.length<=R){X.unshift(Q),A+=Q.length+N;continue}let Y=Math.max(0,R-P_.length);X.unshift(`${P_}${Q.slice(-Y)}`),A=$,G=K;break}return{text:X.join(`
|
|
27
|
-
`),omittedLines:G}}var pA=[{type:"function",function:{name:"save_memory",description:"Save the memory consolidation result to persistent storage.",parameters:{type:"object",properties:{history_entry:{type:"string"},memory_update:{type:"string"}},required:["history_entry","memory_update"]}}}];function iA(J){let _=J.match(/```(?:json)?\s*([\s\S]*?)```/i);if(_?.[1])return _[1].trim();let $=J.indexOf("{"),X=J.lastIndexOf("}");if($===-1||X===-1||X<$)return null;return J.slice($,X+1).trim()}function nA(J){if(!J)return null;let _=iA(J.trim());if(!_)return null;try{let $=JSON.parse(_);if(!$||typeof $!=="object"||Array.isArray($))return null;let X=$;if(X.history_entry==null&&X.memory_update==null)return null;return X}catch{return null}}class W_{memoryDir;memoryFile;historyFile;constructor(J,_){let $=S_.join(J,"memory");this.memoryDir=_?S_.join($,_):$,m0.mkdirSync(this.memoryDir,{recursive:!0}),this.memoryFile=S_.join(this.memoryDir,"MEMORY.md"),this.historyFile=S_.join(this.memoryDir,"HISTORY.md")}readLongTerm(){return m0.existsSync(this.memoryFile)?m0.readFileSync(this.memoryFile,"utf8"):""}writeLongTerm(J){m0.writeFileSync(this.memoryFile,J,"utf8")}appendHistory(J){m0.appendFileSync(this.historyFile,`${J.trim()}
|
|
28
|
-
|
|
29
|
-
`,"utf8")}getMemoryContext(){let J=this.readLongTerm();return J?`## Long-term Memory
|
|
30
|
-
${J}`:""}async consolidate(J,_,$,X){let A=X?.archiveAll??!1,G=X?.memoryWindow??50,K=[],Q=0;if(A)K=J.messages,Q=0;else{if(Q=Math.floor(G/2),J.messages.length<=Q)return!0;if(J.messages.length-J.lastConsolidated<=0)return!0;if(K=J.messages.slice(J.lastConsolidated,J.messages.length-Q),!K.length)return!0}let N=[],R=[];for(let w of K)if(w._type==="anchor")N.push(w);else R.push(w);let Y=[];for(let w of N)Y.push(`[ANCHOR] ${w.name}: ${w.summary??"(no summary)"}`);for(let w of R){if(!w.content&&!w._full_content)continue;let o=Array.isArray(w.tools_used)&&w.tools_used.length?` [tools: ${w.tools_used.join(", ")}]`:"",k=w._full_content??w.content;Y.push(`[${String(w.timestamp??"?").slice(0,16)}] ${String(w.role).toUpperCase()}${o}: ${String(k)}`)}let H=this.readLongTerm(),q=Y.join(`
|
|
31
|
-
`),V=H||"(empty)",y="## Conversation to Process",B=q,M=T_(`Process this conversation and call the save_memory tool with your consolidation.
|
|
2
|
+
import"dotenv/config";import wt from"node:fs";import Un from"node:path";import ir from"node:fs";import ut from"node:os";import J from"node:path";import{fileURLToPath as ar}from"node:url";var He=".everclaw",K="~/.everclaw/config.json",dt=J.join("~",He,"workspace");function mt(s=ut.homedir()){return J.join(s,He,"workspace")}function gt(s=ut.homedir()){return J.join(s,He,"config.json")}function lr(){let s=ar(import.meta.url),t=J.dirname(s);return s.endsWith("/index.js")||s.endsWith("\\index.js")?t:J.resolve(t,"..")}var cr=lr();function pt(...s){let t=J.resolve(cr,...s);if(!ir.existsSync(t))throw new Error(`Runtime asset not found: ${t}`);return t}var ur=[{spec:{name:"zai",keywords:["zai"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://api.z.ai/api/coding/paas/v4"},models:["glm-5-turbo"]},{spec:{name:"openrouter",displayName:"OpenRouter",keywords:["openrouter"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://openrouter.ai/api/v1",detectByKeyPrefix:"sk-or-",detectByBaseKeyword:"openrouter"},models:["anthropic/claude-opus-4-1","anthropic/claude-sonnet-4","openai/gpt-4.1","google/gemini-2.5-pro"]},{spec:{name:"aihubmix",displayName:"AIHubMix",keywords:["aihubmix"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://aihubmix.com/v1",detectByBaseKeyword:"aihubmix"},models:[]},{spec:{name:"siliconflow",displayName:"SiliconFlow",keywords:["siliconflow"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://api.siliconflow.cn/v1",detectByBaseKeyword:"siliconflow"},models:["openai/deepseek-ai/DeepSeek-R1"]},{spec:{name:"volcengine",displayName:"VolcEngine",keywords:["volcengine","volces","ark"],isOauth:!1,isGateway:!0,isLocal:!1,defaultApiBase:"https://ark.cn-beijing.volces.com/api/v3",detectByBaseKeyword:"volces"},models:["volcengine/deepseek-r1-250120"]},{spec:{name:"anthropic",displayName:"Anthropic",keywords:["anthropic","claude"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["anthropic/claude-opus-4-5","anthropic/claude-sonnet-4"]},{spec:{name:"openai",displayName:"OpenAI",keywords:["openai","gpt"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["gpt-5.2","gpt-5.2-pro","gpt-5.3-codex","gpt-5.2-codex","gpt-5.1","gpt-5.1-codex","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini"]},{spec:{name:"openai_codex",displayName:"OpenAI Codex",keywords:["openai-codex","codex"],isOauth:!0,isGateway:!1,isLocal:!1,defaultApiBase:"https://chatgpt.com/backend-api"},models:[]},{spec:{name:"github_copilot",displayName:"GitHub Copilot",keywords:["github_copilot","copilot"],isOauth:!0,isGateway:!1,isLocal:!1,defaultApiBase:""},models:[]},{spec:{name:"deepseek",displayName:"DeepSeek",keywords:["deepseek"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["deepseek/deepseek-chat","deepseek/deepseek-reasoner"]},{spec:{name:"gemini",displayName:"Google Gemini",keywords:["gemini"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["gemini/gemini-3-flash-preview","gemini/gemini-2.5-pro","gemini/gemini-2.5-flash"]},{spec:{name:"zhipu",displayName:"Zhipu AI",keywords:["zhipu","glm","zai"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["zai/glm-4.5"]},{spec:{name:"dashscope",displayName:"DashScope",keywords:["qwen","dashscope"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["dashscope/qwen-max"]},{spec:{name:"moonshot",displayName:"Moonshot AI",keywords:["moonshot","kimi"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:"https://api.moonshot.ai/v1"},models:["moonshot/kimi-k2.5"]},{spec:{name:"minimax",displayName:"MiniMax",keywords:["minimax"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:"https://api.minimax.io/v1"},models:["minimax/MiniMax-M2.1"]},{spec:{name:"vllm",displayName:"vLLM",keywords:["vllm"],isOauth:!1,isGateway:!1,isLocal:!0,defaultApiBase:""},models:["hosted_vllm/llama-3.1-8b-instruct"]},{spec:{name:"groq",displayName:"Groq",keywords:["groq"],isOauth:!1,isGateway:!1,isLocal:!1,defaultApiBase:""},models:["openai/gpt-oss-120b","openai/gpt-oss-20b","meta-llama/llama-4-maverick-17b-128e-instruct","groq/compound","groq/compound-mini"]},{spec:{name:"ollama",displayName:"Ollama",keywords:["ollama"],isOauth:!1,isGateway:!1,isLocal:!0,defaultApiBase:"http://localhost:11434/v1"},models:["ollama/llama3.3","ollama/qwen2.5","ollama/deepseek-r1"]}];function Ve(){return ur.map(s=>s.spec)}var H=Ve(),dr=Object.fromEntries(Ve().map(s=>[s.name,{apiKey:"",apiBase:null,extraHeaders:null,models:[]}])),ae="custom:",V={agents:{defaults:{workspace:dt,model:"gpt-4.1",provider:"auto",maxTokens:8192,temperature:.1,maxToolIterations:40,memoryWindow:100}},subagents:[{id:"researcher",name:"Researcher",task:"Research the given topic thoroughly and provide detailed findings.",createdAt:0},{id:"advisor",name:"Advisor",task:"Analyze the current conversation context and provide exactly 3 concise suggestion options for the user's next logical message. Reply with a JSON array of 3 strings.",createdAt:0}],channels:{sendProgress:!0,sendToolHints:!1,telegram:{enabled:!1,token:"",allowFrom:[],proxy:null,replyToMessage:!1,debounce:{enabled:!0,quietMs:500,maxWaitMs:3e3},groups:{requireMention:!0,allowedGroupIds:null},commands:{native:!0,custom:[]}},discord:{enabled:!1,token:"",allowFrom:[],gatewayUrl:"wss://gateway.discord.gg/?v=10&encoding=json",intents:37377,debounce:{enabled:!0,quietMs:500,maxWaitMs:3e3}}},providers:dr,customLlmProviders:[],customAcpProviders:[],gateway:{host:"127.0.0.1",port:6767,dashboard:{enabled:!0},heartbeat:{enabled:!0,intervalS:1800}},tools:{web:{search:{apiKey:"",maxResults:5}},exec:{timeout:60,pathAppend:""},restrictToWorkspace:!1,mcpServers:{},chromeSession:{enabled:!1,debugPort:9222,minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8,stealth:{enabled:!1,cursorMovement:!0,humanizedTyping:!0,interStepDelay:[300,1500]}},browserRelay:{enabled:!1,authToken:"",extensionPath:""},rtk:{enabled:!0,autoInstall:!0,ultraCompact:!1,version:"latest"}},security:{enabled:!1,auth:{enabled:!1,pinHash:"",sessionTtlS:3600,lockOnIdle:!1,idleTimeoutS:900},toolGuard:{enabled:!1,guardedTools:null,deniedTools:[],rules:[],failOpen:!0},skillScanner:{enabled:!1,scanOnLoad:!1,blockUnsafe:!0,maxFileCount:1e3,maxFileSizeBytes:5242880},inputSanitizer:{enabled:!1,maxInputLength:5e4,stripHtmlTags:!1,blockPromptInjection:!1}},logging:{enabled:!0,level:"info",retentionHours:4,maxFileSizeMb:10,purgeIntervalMs:6e5},compaction:{enabled:!0,microCompactThresholdRatio:.6,autoCompactThresholdRatio:.8,keepRecentMessages:10,maxConsecutiveFailures:3}};function U(s){return s.toLowerCase().replace(/[\s-]+/g,"_")}function ft(s){return`${ae}${U(s)}`}function ht(s,t){let e=U(t.startsWith(ae)?t.slice(ae.length):t);return s.customLlmProviders.find(r=>U(r.name)===e)??null}function mr(s,t){if(!t.includes("/"))return null;let r=t.split("/",1)[0];return r?ht(s,r):null}function N(s){return!!s&&s.startsWith(ae)}function q(s,t,e){let r=(t??s.agents.defaults.provider).trim();if(r&&r!=="auto"&&!s.providers[r])return ht(s,r);let n=mr(s,e??s.agents.defaults.model);if(n)return n;let o=s.customLlmProviders.filter(i=>i.name.trim()&&i.baseUrl.trim());return o.length===1?o[0]??null:null}function le(s,t){let e=s.agents.defaults.provider;if(e!=="auto"){if(s.providers[e])return e;let a=q(s,e,t);return a?ft(a.name):null}let r=(t??s.agents.defaults.model).toLowerCase(),n=U(r),o=r.includes("/")?r.split("/",1)[0]:"";for(let a of H){let l=s.providers[a.name];if(o&&U(o)===a.name&&(a.isOauth||l?.apiKey))return a.name}for(let a of H){let l=s.providers[a.name];if(a.keywords.some(c=>r.includes(c)||n.includes(U(c)))&&(a.isOauth||l?.apiKey))return a.name}for(let a of H){if(a.isOauth)continue;if(s.providers[a.name]?.apiKey)return a.name}let i=q(s,e,t);return i?ft(i.name):null}function yt(s,t){let e=le(s,t);if(e&&N(e)){let r=q(s,e,t);return r?{apiKey:r.apiKey,apiBase:r.baseUrl,extraHeaders:r.extraHeaders}:null}return e?s.providers[e]??null:null}function ce(s,t){let e=le(s,t);if(!e)return null;if(N(e))return q(s,e,t)?.baseUrl??null;let r=s.providers[e];if(r?.apiBase)return r.apiBase;let n=H.find(o=>o.name===e);return n?.isGateway?n.defaultApiBase:null}import gr from"node:fs";import pr from"node:path";import bt from"node:os";function vt(s){return gr.mkdirSync(s,{recursive:!0}),s}function St(s){let t=s?s.replace(/^~(?=$|[\\/])/,bt.homedir()):mt(bt.homedir());return vt(pr.resolve(t))}function hr(){return gt()}function xt(s,t){if(!t||typeof t!="object")return s;let e=Array.isArray(s)?[...s]:{...s};for(let[r,n]of Object.entries(t))n&&typeof n=="object"&&!Array.isArray(n)&&e[r]&&typeof e[r]=="object"&&!Array.isArray(e[r])?e[r]=xt(e[r],n):e[r]=n;return e}function kt(s){let t=s??hr();if(!wt.existsSync(t))return structuredClone(V);try{let e=wt.readFileSync(t,"utf8"),r=JSON.parse(e),n=xt(structuredClone(V),r),o=["advisor"];for(let i of o)if(!n.subagents.find(a=>a.id===i)){let a=V.subagents.find(l=>l.id===i);a&&n.subagents.push(structuredClone(a))}return n}catch(e){return console.warn(`Warning: Failed to load config from ${t}: ${String(e)}`),structuredClone(V)}}function z(s){return s.map(t=>{let e=t.content;if(typeof e=="string"&&e.length===0)return t.role==="assistant"&&t.tool_calls?{...t,content:null}:{...t,content:"(empty)"};if(Array.isArray(e)){let r=e.filter(n=>!(typeof n=="object"&&n&&["text","input_text","output_text"].includes(n.type)&&!n.text));if(r.length!==e.length)return r.length>0?{...t,content:r}:t.role==="assistant"&&t.tool_calls?{...t,content:null}:{...t,content:"(empty)"}}return t})}function ze(){let s=new Error("Operation aborted");return s.name="AbortError",s}function k(s){return s instanceof Error&&s.name==="AbortError"}function v(s){if(s?.aborted)throw ze()}function Ct(s){return s.trim().toLowerCase().replace(/[\s-]+/g,"_")}function Tt(s){if(typeof s!="string")return s&&typeof s=="object"?s:{};try{return JSON.parse(s)}catch{return{}}}var ue=class{constructor(t,e,r,n={}){this.apiKey=t;this.apiBase=e;this.defaultModel=r;this.options=n}apiKey;apiBase;defaultModel;options;getDefaultModel(){return this.defaultModel}get requestFormat(){return this.options.apiFormat??"v1/chat/completions"}resolveModel(t){let e=t.trim();if(!e.includes("/"))return e;let r=e.split("/",2),n=r[0],o=r[1];return!n||!o?e:new Set(["custom",Ct(this.options.providerLabel??"")]).has(Ct(n))?o:e}buildHeaders(){let t={"Content-Type":"application/json",...this.options.extraHeaders??{}};return this.apiKey.trim()&&(t.Authorization=`Bearer ${this.apiKey}`),t}async readJson(t){try{return await t.json()}catch{return{}}}async chatCompletions(t){let e=await fetch(`${this.apiBase.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({model:this.resolveModel(t.model??this.defaultModel),messages:z(t.messages),tools:t.tools,tool_choice:t.tools?.length?t.toolChoice??"auto":void 0,max_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7,...t.reasoning?{reasoning_effort:"medium"}:{},...t.imageOutput?{include_image_output:!0}:{}}),...t.signal?{signal:t.signal}:{}}),r=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${r?.error?.message??JSON.stringify(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let n=r.choices?.[0];if(!n?.message)return{content:`Error calling LLM: ${JSON.stringify(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=(n.message.tool_calls??[]).map(i=>({id:i.id,name:i.function.name,arguments:Tt(i.function.arguments)}));return{content:n.message.content??null,toolCalls:o,finishReason:n.finish_reason??"stop",usage:{prompt_tokens:r.usage?.prompt_tokens??0,completion_tokens:r.usage?.completion_tokens??0,total_tokens:r.usage?.total_tokens??0},reasoningContent:n.message.reasoning_content??null}}toResponsesInput(t){let e=[];for(let r of z(t)){let n=String(r.role??"");if(n==="tool"){e.push({type:"function_call_output",call_id:String(r.tool_call_id??""),output:typeof r.content=="string"?r.content:JSON.stringify(r.content??null)});continue}if(n==="assistant"&&Array.isArray(r.tool_calls))for(let o of r.tool_calls)e.push({type:"function_call",call_id:String(o.id??""),name:String(o.name??""),arguments:typeof o.arguments=="string"?o.arguments:JSON.stringify(o.arguments??{})});(n==="system"||n==="user"||n==="assistant")&&e.push({role:n,content:r.content??""})}return e}async responses(t){let e=await fetch(`${this.apiBase.replace(/\/$/,"")}/responses`,{method:"POST",headers:this.buildHeaders(),body:JSON.stringify({model:this.resolveModel(t.model??this.defaultModel),input:this.toResponsesInput(t.messages),tools:t.tools,tool_choice:t.tools?.length?t.toolChoice??"auto":void 0,max_output_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7,...t.reasoning?{reasoning:{effort:"medium"}}:{},...t.imageOutput?{include_image_output:!0}:{}}),...t.signal?{signal:t.signal}:{}}),r=await this.readJson(e);if(!e.ok)return{content:`Error calling LLM: ${r?.error?.message??JSON.stringify(r)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let n=Array.isArray(r.output)?r.output:[],o=n.filter(a=>a?.type==="function_call").map(a=>({id:String(a.call_id??a.id??""),name:String(a.name??""),arguments:Tt(a.arguments)}));return{content:n.filter(a=>a?.type==="message").flatMap(a=>Array.isArray(a?.content)?a.content:[]).filter(a=>a?.type==="output_text").map(a=>String(a.text??"")).join(`
|
|
3
|
+
`).trim()||null,toolCalls:o,finishReason:o.length?"tool_calls":r.status??"stop",usage:{prompt_tokens:r.usage?.input_tokens??0,completion_tokens:r.usage?.output_tokens??0,total_tokens:r.usage?.total_tokens??0},reasoningContent:null}}async chat(t){try{return v(t.signal),this.requestFormat==="v1/responses"?await this.responses(t):await this.chatCompletions(t)}catch(e){if(k(e))throw e;return{content:`Error calling LLM: ${String(e)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};import{nanoid as yr}from"nanoid";var de=class s{constructor(t,e,r){this.apiKey=t;this.apiBase=e;this.defaultModel=r}apiKey;apiBase;defaultModel;static DEFAULT_BASE="https://generativelanguage.googleapis.com/v1beta";getDefaultModel(){return this.defaultModel}resolveModel(t){let e=t.trim();if(e.includes("/")){let r=e.split("/",2),n=r[0],o=r[1];if(!n||!o)return e;let i=n.toLowerCase();(i==="gemini"||i==="google")&&(e=o)}return e.startsWith("models/")?e.slice(7):e}asText(t){if(typeof t=="string")return t;if(t==null)return"";try{return JSON.stringify(t)}catch{return String(t)}}parseToolArgs(t){if(t&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t=="string")try{let e=JSON.parse(t);if(e&&typeof e=="object"&&!Array.isArray(e))return e}catch{}return{}}toGemini(t){let e=[],r=[];for(let i of t.messages){let a=String(i.role??"");if(a==="system"){let l=this.asText(i.content).trim();l&&e.push(l);continue}if(a==="user"){let l=this.asText(i.content).trim();if(!l)continue;r.push({role:"user",parts:[{text:l}]});continue}if(a==="assistant"||a==="model"){let l=[],c=this.asText(i.content).trim();c&&l.push({text:c});let u=Array.isArray(i.tool_calls)?i.tool_calls:[];for(let d of u){let m=d.function;m?.name&&l.push({functionCall:{name:m.name,args:this.parseToolArgs(m.arguments)}})}l.length&&r.push({role:"model",parts:l});continue}if(a==="tool"){let l=typeof i.name=="string"?i.name:"";if(!l)continue;let c=this.asText(i.content);r.push({role:"user",parts:[{functionResponse:{name:l,response:{result:c}}}]})}}r.length||r.push({role:"user",parts:[{text:"Hello"}]});let n={contents:r,generationConfig:{temperature:t.temperature??.1,maxOutputTokens:Math.max(1,t.maxTokens??4096),...t.reasoning?{thinkingConfig:{thinkingBudget:Math.max(1,t.maxTokens??4096)}}:{}}};e.length&&(n.systemInstruction={parts:[{text:e.join(`
|
|
4
|
+
|
|
5
|
+
`)}]});let o=(t.tools??[]).map(i=>i).filter(i=>i.type==="function"&&i.function?.name).map(i=>({name:i.function.name,description:i.function?.description??"",parameters:i.function?.parameters??{type:"object",properties:{}}}));return o.length&&(n.tools=[{functionDeclarations:o}],n.toolConfig=t.toolChoice==="required"?{functionCallingConfig:{mode:"ANY",allowedFunctionNames:o.map(i=>i.name)}}:{functionCallingConfig:{mode:"AUTO"}}),t.imageOutput&&(n.responseModalities=["TEXT","IMAGE"]),n}async chat(t){try{v(t.signal);let e=this.resolveModel(t.model??this.defaultModel),n=`${(this.apiBase??s.DEFAULT_BASE).replace(/\/$/,"")}/models/${encodeURIComponent(e)}:generateContent`,o=this.toGemini(t),i=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json","x-goog-api-key":this.apiKey},body:JSON.stringify(o),...t.signal?{signal:t.signal}:{}}),a=await i.json();if(!i.ok)return{content:`Error calling LLM: ${a?.error?.message??JSON.stringify(a)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let l=a?.candidates?.[0],c=l?.content?.parts??[],u=c.filter(f=>typeof f?.text=="string").map(f=>String(f.text)),d=c.filter(f=>f?.functionCall?.name).map(f=>({id:yr(9),name:String(f.functionCall.name),arguments:this.parseToolArgs(f.functionCall.args)})),m={};a?.usageMetadata&&(m.prompt_tokens=Number(a.usageMetadata.promptTokenCount??0),m.completion_tokens=Number(a.usageMetadata.candidatesTokenCount??0),m.total_tokens=Number(a.usageMetadata.totalTokenCount??0));let p=String(l?.finishReason??"STOP").toLowerCase();return{content:u.length?u.join(`
|
|
6
|
+
`):null,toolCalls:d,finishReason:p,usage:m,reasoningContent:null}}catch(e){if(k(e))throw e;return{content:`Error calling LLM: ${String(e)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};import{nanoid as br}from"nanoid";var me=class s{constructor(t,e,r,n){this.apiKey=t;this.apiBase=e;this.defaultModel=r;this.providerName=n}apiKey;apiBase;defaultModel;providerName;static DEFAULT_BASE_BY_PROVIDER={openrouter:"https://openrouter.ai/api/v1",openai:"https://api.openai.com/v1",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",moonshot:"https://api.moonshot.ai/v1",minimax:"https://api.minimax.io/v1",dashscope:"https://dashscope.aliyuncs.com/compatible-mode/v1",zhipu:"https://open.bigmodel.cn/api/paas/v4",siliconflow:"https://api.siliconflow.cn/v1",volcengine:"https://ark.cn-beijing.volces.com/api/v3",vllm:"http://localhost:8000/v1",ollama:"http://localhost:11434/v1",zai:"https://api.z.ai/api/coding/paas/v4"};static UNSUPPORTED_PROVIDERS=new Set(["anthropic","gemini","openai_codex","github_copilot"]);getDefaultModel(){return this.defaultModel}resolveModel(t){let e=r=>r.toLowerCase().replace(/-/g,"_");if(t.includes("/")){let r=t.split("/",2),n=r[0],o=r[1];if(!n||!o)return t;if(e(n)==="github_copilot")return`github_copilot/${o}`;if(e(n)==="openai_codex")return`openai_codex/${o}`;if(e(n)==="groq")return o==="compound"||o==="compound-mini"?`groq/${o}`:o;if(e(n)==="ollama")return o}return t}async chat(t){let r={model:this.resolveModel(t.model??this.defaultModel),messages:z(t.messages),max_tokens:Math.max(1,t.maxTokens??4096),temperature:t.temperature??.7};t.tools?.length&&(r.tools=t.tools,r.tool_choice=t.toolChoice??"auto"),t.reasoning&&(r.reasoning_effort="medium"),t.imageOutput&&(r.include_image_output=!0);try{v(t.signal);let n=(this.providerName??"").trim();if(n&&s.UNSUPPORTED_PROVIDERS.has(n))return{content:`Error calling LLM: provider '${n}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let o=this.apiBase??(n?s.DEFAULT_BASE_BY_PROVIDER[n]:void 0)??(this.apiKey?.startsWith("sk-or-")?s.DEFAULT_BASE_BY_PROVIDER.openrouter:void 0);if(!o)return{content:`Error calling LLM: api_base not configured. Set provider/api_base in ${K} or run everclaw onboard.`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let i={"Content-Type":"application/json"};this.apiKey&&(i.Authorization=`Bearer ${this.apiKey}`);let a=await fetch(`${o.replace(/\/$/,"")}/chat/completions`,{method:"POST",headers:i,body:JSON.stringify(r),...t.signal?{signal:t.signal}:{}}),l=await a.json();if(!a.ok){let d=l?.error?.code??"",m=l?.error?.message??JSON.stringify(l);return d==="model_not_found"?{content:`Error calling LLM: ${m}
|
|
7
|
+
${n==="groq"?"Try a Groq-supported model like llama-3.3-70b-versatile or openai/gpt-oss-120b. You can run `everclaw doctor`.":"Check your model id and provider access. You can run `everclaw doctor`."}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}:{content:`Error calling LLM: ${m}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}let c=l.choices?.[0]?.message?l.choices[0]:null;if(!c)return{content:`Error calling LLM: ${JSON.stringify(l)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null};let u=(c.message.tool_calls??[]).map(d=>({id:br(9),name:d.function.name,arguments:typeof d.function.arguments=="string"?JSON.parse(d.function.arguments||"{}"):d.function.arguments}));return{content:c.message.content??null,toolCalls:u,finishReason:c.finish_reason??"stop",usage:l.usage??{},reasoningContent:c.message.reasoning_content??null}}catch(n){if(k(n))throw n;return{content:`Error calling LLM: ${String(n)}`,toolCalls:[],finishReason:"error",usage:{},reasoningContent:null}}}};function At(s){let t=s.agents.defaults.model,e=le(s,t),r=yt(s,t),n=e&&N(e)?q(s,e,t):null,o=new Set(["openai_codex","github_copilot"]),i=new Set(["anthropic"]);if(!e)throw new Error("No provider could be resolved from config. Run `everclaw onboard` and set provider/model/API key.");if(N(e)&&!n)throw new Error(`Custom provider '${e}' could not be found. Check ${K}.`);if(i.has(e))throw new Error(`Provider '${e}' is not supported in this TypeScript port yet. Use openrouter/openai/deepseek/groq/custom.`);if(!o.has(e)&&e!=="vllm"&&e!=="custom"&&!N(e)&&!(r?.apiKey||"").trim())throw new Error(`No API key configured for provider '${e}'. Run 'everclaw onboard' or edit ${K}.`);return e==="custom"||N(e)?new ue(r?.apiKey||n?.apiKey||"no-key",ce(s,t)||n?.baseUrl||"http://localhost:8000/v1",t,{providerLabel:n?.name??e,apiFormat:n?.apiFormat,extraHeaders:n?.extraHeaders??r?.extraHeaders??null}):e==="gemini"?new de(r?.apiKey||"",ce(s,t),t):new me(r?.apiKey??null,ce(s,t),t,e)}import{randomUUID as Fi}from"node:crypto";import bn from"node:path";import{randomUUID as Ao}from"node:crypto";import Ro from"cron-parser";function Ye(s){return s??"builtin"}function vr(){return{beforeAgentTurn:[],afterAgentTurn:[],beforeOutbound:[],afterOutbound:[],beforeScheduledJob:[],afterScheduledJob:[],shutdown:[]}}function ge(s,t,e,r){let n=Ye(e.source),o=t.get(r.name);if(o)throw new Error(`${s} '${r.name}' from extension '${e.name}' conflicts with extension '${o.extension}'`);t.set(r.name,{extension:e.name,source:n,contribution:r})}function Sr(s,t,e){let r=(n,o)=>{let i=n.find(a=>a.contribution.name===o.name);if(i)throw new Error(`lifecycle '${o.slot}:${o.name}' from extension '${t.name}' conflicts with extension '${i.extension}'`);n.push({extension:t.name,source:Ye(t.source),contribution:o})};switch(e.slot){case"beforeAgentTurn":r(s.beforeAgentTurn,e);return;case"afterAgentTurn":r(s.afterAgentTurn,e);return;case"beforeOutbound":r(s.beforeOutbound,e);return;case"afterOutbound":r(s.afterOutbound,e);return;case"beforeScheduledJob":r(s.beforeScheduledJob,e);return;case"afterScheduledJob":r(s.afterScheduledJob,e);return;case"shutdown":r(s.shutdown,e);return}}function R(s){return{...s,source:"builtin"}}var Xe=class{extensions=new Map;register(t){if(this.extensions.has(t.name))throw new Error(`Extension '${t.name}' is already registered`);return this.extensions.set(t.name,{...t,source:Ye(t.source)}),this}list(){return[...this.extensions.values()]}compose(){let t=new Map,e=new Map,r=new Map,n=new Map,o=vr();for(let i of this.extensions.values()){for(let a of i.tools??[])ge("tool",t,i,a);for(let a of i.channels??[])ge("channel",e,i,a);for(let a of i.jobs??[])ge("job",r,i,a);for(let a of i.commands??[])ge("command",n,i,a);for(let a of i.lifecycle??[])Sr(o,i,a)}return{extensions:this.list(),tools:t,channels:e,jobs:r,commands:n,lifecycle:{beforeAgentTurn:o.beforeAgentTurn,afterAgentTurn:o.afterAgentTurn,beforeOutbound:o.beforeOutbound,afterOutbound:o.afterOutbound,beforeScheduledJob:o.beforeScheduledJob,afterScheduledJob:o.afterScheduledJob,shutdown:o.shutdown}}}};function Et(s){let t=new Xe;for(let e of s)t.register(e);return t.compose()}import yo from"node:path";import{createRequire as wr}from"node:module";var wo=wr(import.meta.url);import $o from"node:fs";import No from"node:path";var g=class s{static typeMap={string:t=>typeof t=="string",integer:t=>Number.isInteger(t),number:t=>typeof t=="number"&&Number.isFinite(t),boolean:t=>typeof t=="boolean",array:t=>Array.isArray(t),object:t=>!!t&&typeof t=="object"&&!Array.isArray(t)};validateParams(t){let e=this.parameters??{};if(e.type!=="object")throw new Error(`Schema must be object type, got ${String(e.type)}`);return this.validateValue(t,{...e,type:"object"},"parameter")}validateValue(t,e,r){let n=e.type,o=[];if(n&&s.typeMap[n]&&!s.typeMap[n](t))return[`${r} should be ${n}`];if(e.enum&&!e.enum.includes(t)&&o.push(`${r} must be one of ${JSON.stringify(e.enum)}`),(n==="integer"||n==="number")&&typeof t=="number"&&(typeof e.minimum=="number"&&t<e.minimum&&o.push(`${r} must be >= ${e.minimum}`),typeof e.maximum=="number"&&t>e.maximum&&o.push(`${r} must be <= ${e.maximum}`)),n==="string"&&typeof t=="string"&&(typeof e.minLength=="number"&&t.length<e.minLength&&o.push(`${r} must be at least ${e.minLength} chars`),typeof e.maxLength=="number"&&t.length>e.maxLength&&o.push(`${r} must be at most ${e.maxLength} chars`)),n==="object"&&t&&typeof t=="object"&&!Array.isArray(t)){let i=t,a=e.properties??{};for(let l of e.required??[])l in i||o.push(`missing required ${r==="parameter"?l:`${r}.${l}`}`);for(let[l,c]of Object.entries(i))a[l]&&o.push(...this.validateValue(c,a[l],r==="parameter"?l:`${r}.${l}`))}return n==="array"&&Array.isArray(t)&&e.items&&typeof e.items=="object"&&t.forEach((i,a)=>o.push(...this.validateValue(i,e.items,`${r}[${a}]`))),o}toSchema(){return{type:"function",function:{name:this.name,description:this.description,parameters:this.parameters}}}};var pe=class extends g{constructor(e){super();this.cron=e}cron;name="cron";description="Schedule reminders and recurring tasks. Actions: add, list, remove.";parameters={type:"object",properties:{action:{type:"string",enum:["add","list","remove"]},message:{type:"string"},every_seconds:{type:"integer"},cron_expr:{type:"string"},tz:{type:"string"},at:{type:"string"},job_id:{type:"string"}},required:["action"]};channel="";chatId="";setContext(e,r){this.channel=e,this.chatId=r}async execute(e,r){let n=String(e.action??"");return n==="add"?this.addJob(e):n==="list"?this.listJobs():n==="remove"?this.removeJob(String(e.job_id??"")):`Unknown action: ${n}`}addJob(e){let r=String(e.message??"");if(!r)return"Error: message is required for add";if(!this.channel||!this.chatId)return"Error: no session context (channel/chat_id)";let n=e.every_seconds!=null?Number(e.every_seconds):null,o=e.cron_expr!=null?String(e.cron_expr):null,i=e.tz!=null?String(e.tz):null,a=e.at!=null?String(e.at):null,l,c=!1;if(n)l={kind:"every",everyMs:n*1e3};else if(o){let u={kind:"cron",expr:o};i&&(u.tz=i),l=u}else if(a){let u=new Date(a);if(Number.isNaN(u.getTime()))return"Error: invalid ISO datetime in at";l={kind:"at",atMs:u.getTime()},c=!0}else return"Error: either every_seconds, cron_expr, or at is required";try{let u=this.cron.addJob({name:r.slice(0,30),schedule:l,message:r,deliver:!0,channel:this.channel,to:this.chatId,deleteAfterRun:c});return`Created job '${u.name}' (id: ${u.id})`}catch(u){return`Error: ${String(u).replace(/^Error:\s*/,"")}`}}listJobs(){let e=this.cron.listJobs();return e.length?`Scheduled jobs:
|
|
8
|
+
${e.map(r=>`- ${r.name} (id: ${r.id}, ${r.schedule.kind})`).join(`
|
|
9
|
+
`)}`:"No scheduled jobs."}removeJob(e){return e?this.cron.removeJob(e)?`Removed job ${e}`:`Job ${e} not found`:"Error: job_id is required for remove"}};import A from"node:fs";import W from"node:path";import M from"node:fs";import C from"node:path";function Rt(s){let t=C.resolve(s);for(;t!=="/"&&t!==".";)try{return M.lstatSync(t),t}catch{let e=C.dirname(t);if(e===t)break;t=e}return t||"/"}function Mt(s,t){let e=C.resolve(s),r=C.resolve(t),n=r.endsWith(C.sep)?r.slice(0,-1):r,o=e===n||e.startsWith(n+C.sep);if(!M.existsSync(n))return o;try{let i=n;try{i=M.realpathSync.native(n)}catch{}if(M.existsSync(e)){let c=M.realpathSync.native(e);return c===i||c.startsWith(i+C.sep)}let a=Rt(e);if(a===i||a===n)return!0;if(a!=="/")try{let c=M.realpathSync.native(a);if(c===i||c.startsWith(i+C.sep))return!0;if(!o)return!1}catch{return o}let l=e;for(;l!=="/"&&l!==".";){let c=C.dirname(l);if(c===l)break;try{if(M.lstatSync(c).isSymbolicLink()){let d=M.realpathSync.native(c);if(d!==i&&!d.startsWith(i+C.sep))return!1}}catch{}l=c}return o}catch{return!1}}function _t(s,t){let e=C.resolve(s),r=C.resolve(t);if(!Mt(s,t))throw new Error(`Path '${s}' is outside allowed workspace '${t}'`);let n=C.dirname(e),o=Rt(n),i=r;try{M.existsSync(r)&&(i=M.realpathSync.native(r))}catch{}if(o!=="/"&&o!==i)try{let a=M.realpathSync.native(o);if(a!==i&&!a.startsWith(i+C.sep))throw new Error(`Path '${s}' would be created outside workspace via symlinked parent directory`)}catch(a){throw a instanceof Error&&a.message.includes("symlinked parent")?a:new Error(`Could not validate path '${s}' is within workspace`)}}function Lt(s,t){if(!Mt(s,t))throw new Error(`Path '${s}' is outside allowed workspace '${t}'`)}function ve(s,t,e,r=!1){let n=s.startsWith("~")?W.join(process.env.USERPROFILE||process.env.HOME||"",s.slice(1)):s,o=W.isAbsolute(n)?n:t?W.join(t,n):n,i=W.resolve(o);if(e)try{r?_t(i,e):Lt(i,e)}catch(a){throw new Error(a instanceof Error?a.message:`Path ${s} validation failed`)}return i}var fe=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="read_file";description="Read the contents of a file at the given path.";parameters={type:"object",properties:{path:{type:"string",description:"The file path to read"}},required:["path"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir);return A.existsSync(n)?A.statSync(n).isFile()?A.readFileSync(n,"utf8"):`Error: Not a file: ${String(e.path)}`:`Error: File not found: ${String(e.path)}`}catch(n){return`Error reading file: ${String(n)}`}}},he=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="write_file";description="Write content to a file at the given path. Creates parent directories if needed.";parameters={type:"object",properties:{path:{type:"string"},content:{type:"string"}},required:["path","content"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir,!0);A.mkdirSync(W.dirname(n),{recursive:!0});let o=String(e.content??"");return A.writeFileSync(n,o,"utf8"),`Successfully wrote ${o.length} bytes to ${n}`}catch(n){return`Error writing file: ${String(n)}`}}},ye=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="edit_file";description="Edit a file by replacing old_text with new_text. The old_text must exist exactly in the file.";parameters={type:"object",properties:{path:{type:"string"},old_text:{type:"string"},new_text:{type:"string"}},required:["path","old_text","new_text"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir,!0);if(!A.existsSync(n))return`Error: File not found: ${String(e.path)}`;let o=A.readFileSync(n,"utf8"),i=String(e.old_text??""),a=String(e.new_text??"");return o.includes(i)?o.split(i).length-1>1?`Warning: old_text appears ${o.split(i).length-1} times. Please provide more context to make it unique.`:(A.writeFileSync(n,o.replace(i,a),"utf8"),`Successfully edited ${n}`):`Error: old_text not found in ${String(e.path)}. Verify the file content.`}catch(n){return`Error editing file: ${String(n)}`}}},be=class extends g{constructor(e,r){super();this.workspace=e;this.allowedDir=r}workspace;allowedDir;name="list_dir";description="List the contents of a directory.";parameters={type:"object",properties:{path:{type:"string"}},required:["path"]};async execute(e,r){try{let n=ve(String(e.path),this.workspace,this.allowedDir);if(!A.existsSync(n))return`Error: Directory not found: ${String(e.path)}`;if(!A.statSync(n).isDirectory())return`Error: Not a directory: ${String(e.path)}`;let o=A.readdirSync(n).sort().map(i=>{let a=W.join(n,i);return`${A.statSync(a).isDirectory()?"[DIR]":"[FILE]"} ${i}`});return o.length?o.join(`
|
|
10
|
+
`):`Directory ${String(e.path)} is empty`}catch(n){return`Error listing directory: ${String(n)}`}}};var Se=class extends g{constructor(e){super();this.sendCallback=e}sendCallback;name="message";description="Send a message to the user. Use this when you want to communicate something.";parameters={type:"object",properties:{content:{type:"string",description:"The message content to send"},channel:{type:"string",description:"Optional target channel"},chat_id:{type:"string",description:"Optional target chat/user ID"},media:{type:"array",items:{type:"string"},description:"Optional file attachments"}},required:["content"]};defaultChannel="";defaultChatId="";defaultMessageId=null;setContext(e,r,n){this.defaultChannel=e,this.defaultChatId=r,this.defaultMessageId=n??null}setSendCallback(e){this.sendCallback=e}async execute(e,r){let n=String(e.content??""),o=String(e.channel??this.defaultChannel),i=String(e.chat_id??this.defaultChatId),a=String(e.message_id??this.defaultMessageId??""),l=Array.isArray(e.media)?e.media:[];if(!o||!i)return"Error: No target channel/chat specified";if(!this.sendCallback)return"Error: Message sending not configured";try{await this.sendCallback({channel:o,chatId:i,content:n,media:l,metadata:{message_id:a}});let c=o===this.defaultChannel&&i===this.defaultChatId,u=`Message sent to ${o}:${i}${l.length?` with ${l.length} attachments`:""}`;return c?`__TERMINAL__${u}`:u}catch(c){return`Error sending message: ${String(c)}`}}};import Qe from"node:path";import{spawn as Pt}from"node:child_process";var kr={"agent-turn":{target:"agent-turn",mode:"in-process",risk:"safe",cleanup:"none",observation:"basic",reason:"Normal agent turns stay in-process unless a later surface explicitly routes them through isolation."},"tool.exec":{target:"tool.exec",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Shell execution already crosses the local OS boundary and needs explicit launch, timeout, output capture, and cleanup semantics."},subagent:{target:"subagent",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Spawned subagents are a high-risk local execution path that later Wave D routing can move onto this process boundary."},"scheduled-job":{target:"scheduled-job",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Scheduled jobs can run unattended and should share the same local-process isolation contract when routed in later Wave D work."},"background-job":{target:"background-job",mode:"local-process",risk:"risky-local",cleanup:"terminate-process",observation:"stdio",reason:"Long-running background work needs the same local process cleanup and attribution boundary as other risky execution paths."}};function Ze(s){return{...kr[s]}}var D=class{async run(t){let e=Math.max(1,t.maxCaptureBytes??1048576),r=typeof t.timeoutMs=="number"&&Number.isFinite(t.timeoutMs)&&t.timeoutMs>0?t.timeoutMs:null,n=this.launch(t);if(n instanceof Error)return{status:"failed",pid:null,stdout:"",stderr:"",exitCode:null,signal:null,failureAttribution:"spawn_error",cleanupTriggered:!1,cleanupReason:null,errorMessage:n.message};let{child:o,spawnError:i}=n;t.stdinText!=null?o.stdin?.end(t.stdinText,"utf8"):o.stdin?.end();let a="",l="",c=!1,u=null,d=!1,m=(S,L)=>{let B=typeof S=="string"?S:S.toString("utf8"),_=e-Buffer.byteLength(L);return _<=0?L:L+B.slice(0,_)};o.stdout?.on("data",S=>{a=m(S,a)}),o.stderr?.on("data",S=>{l=m(S,l)});let p=null,f=S=>{c||(c=!0,u=S,d=S==="timeout",this.killChild(o,"SIGTERM"),p=setTimeout(()=>this.killChild(o,"SIGKILL"),250),p.unref?.())},b=()=>f("abort");t.signal?.aborted?b():t.signal?.addEventListener("abort",b,{once:!0});let T=r!=null?setTimeout(()=>f("timeout"),r):null;T?.unref?.();let x=await new Promise(S=>{let L=!1,B=_=>{L||(L=!0,S(_))};o.once("error",_=>{i.current=_,B({code:null,signal:null})}),o.once("close",(_,ie)=>B({code:_,signal:ie}))});return T&&clearTimeout(T),p&&clearTimeout(p),t.signal?.removeEventListener("abort",b),u==="abort"?{status:"aborted",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:"aborted",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:d?{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:"timeout",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:i.current?{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:"spawn_error",cleanupTriggered:c,cleanupReason:u,errorMessage:i.current.message}:x.code===0?{status:"ok",pid:o.pid??null,stdout:a,stderr:l,exitCode:0,signal:x.signal,failureAttribution:"none",cleanupTriggered:c,cleanupReason:u,errorMessage:null}:{status:"failed",pid:o.pid??null,stdout:a,stderr:l,exitCode:x.code,signal:x.signal,failureAttribution:x.signal?"signal":"exit_code",cleanupTriggered:c,cleanupReason:u,errorMessage:null}}launch(t){try{return{child:t.command.kind==="shell"?Pt(t.command.command,{cwd:t.cwd,env:t.env,shell:!0,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}):Pt(t.command.file,t.command.args??[],{cwd:t.cwd,env:t.env,detached:process.platform!=="win32",stdio:["pipe","pipe","pipe"]}),spawnError:{current:null}}}catch(e){return e instanceof Error?e:new Error(String(e))}}killChild(t,e){try{if(process.platform!=="win32"&&typeof t.pid=="number"){process.kill(-t.pid,e);return}}catch{}try{t.kill(e)}catch{}}};var we=class extends g{constructor(e=60,r,n=!1,o="",i=new D,a,l=!1){super();this.timeout=e;this.workingDir=r;this.restrictToWorkspace=n;this.pathAppend=o;this.runner=i;this.rtkService=a;this.rtkUltraCompact=l}timeout;workingDir;restrictToWorkspace;pathAppend;runner;rtkService;rtkUltraCompact;name="exec";description="Execute a shell command and return its output. Use with caution.";parameters={type:"object",properties:{command:{type:"string",description:"The shell command to execute"},working_dir:{type:"string",description:"Optional working directory for the command"}},required:["command"]};guard(e,r){let n=e.toLowerCase();if([/\brm\s+-[rf]{1,2}\b/,/\bdel\s+\/[fq]\b/,/\brmdir\s+\/s\b/,/(?:^|[;&|]\s*)format\b/,/\b(mkfs|diskpart)\b/,/\bdd\s+if=/,/>\s*\/dev\/sd/,/\b(shutdown|reboot|poweroff)\b/,/:\(\)\s*\{.*\};\s*:/].some(i=>i.test(n)))return"Error: Command blocked by safety guard (dangerous pattern detected)";if(this.restrictToWorkspace){if(e.includes("../")||e.includes("..\\"))return"Error: Command blocked by safety guard (path traversal detected)";let i=e.match(/[A-Za-z]:\\[^\s"']+/g)??[];for(let a of i){let l=Qe.resolve(a),c=Qe.resolve(r);if(!l.startsWith(c))return"Error: Command blocked by safety guard (path outside working dir)"}}return null}async execute(e,r){let n=String(e.command??""),o=String(e.working_dir??this.workingDir??process.cwd()),i=this.guard(n,o);if(i)return i;v(r?.signal);let a=Ze("tool.exec"),l={...process.env};if(this.pathAppend&&(l.PATH=`${l.PATH??""}${Qe.delimiter}${this.pathAppend}`),a.mode!=="local-process")return"Error: exec tool requires local-process isolation";let c={command:{kind:"shell",command:n},cwd:o,env:l,timeoutMs:this.timeout*1e3,maxCaptureBytes:1024*1024};r?.signal&&(c.signal=r.signal);let u=await this.runner.run(c);if(u.status==="aborted")throw ze();if(u.failureAttribution==="timeout")return`Error: Command timed out after ${this.timeout} seconds`;let d=u.stdout?`${u.stdout}${u.status==="failed"?`
|
|
11
|
+
`:""}`:"";if(this.rtkService?.getRuntime().available&&d)try{let T=await this.rtkService.compress({command:n,stdout:d,stderr:u.stderr,exitCode:u.exitCode,ultraCompact:this.rtkUltraCompact});T.compressed&&(d=T.stdout)}catch{}let m=u.stderr.trim()?`STDERR:
|
|
12
|
+
${u.stderr}
|
|
13
|
+
`:"",p=u.status==="failed"&&typeof u.exitCode=="number"?`
|
|
14
|
+
Exit code: ${u.exitCode}`:"",f=u.status==="failed"&&u.signal?`
|
|
15
|
+
Signal: ${u.signal}`:"",b=`${d}${m}${p}${f}`.trim();return b?b.length>1e4?`${b.slice(0,1e4)}
|
|
16
|
+
... (truncated, ${b.length-1e4} more chars)`:b:u.status==="failed"?u.errorMessage?`Error executing command: ${u.errorMessage}`:"Error executing command":"(no output)"}};var Cr={general:{name:"general",description:"General-purpose subagent with full tool access",systemPromptSuffix:"Complete the assigned task using all available tools."},researcher:{name:"researcher",description:"Read-only researcher \u2014 no file modifications",systemPromptSuffix:"Research and report findings. Do NOT modify any files.",allowedTools:["read_file","list_files","search","web_search","web_fetch","session.info","session.search"]},coder:{name:"coder",description:"Code modification specialist",systemPromptSuffix:"Implement the requested code changes.",deniedTools:["web_search","web_fetch"]}};function Ot(){return Object.values(Cr)}var xe=class extends g{constructor(e){super();this.manager=e}manager;name="spawn";description="Spawn a subagent to handle a task in the background.";parameters={type:"object",properties:{task:{type:"string",description:"The task for the subagent to complete"},label:{type:"string",description:"Optional short label"},model:{type:"string",description:"Optional model override (e.g. 'anthropic/claude-sonnet-4'). Falls back to subagent config or global default if omitted."},provider:{type:"string",description:"Optional provider override (e.g. 'openai'). Falls back to subagent config or global default if omitted."},context:{type:"string",enum:["fresh","fork"],description:"Context mode: 'fresh' (default) starts with minimal context, 'fork' inherits parent conversation for prompt cache reuse."},type:{type:"string",description:`Agent type defining available tools and behavior. Available types: ${Ot().map(e=>`'${e.name}'`).join(", ")}. Defaults to 'general'.`}},required:["task"]};originChannel="cli";originChatId="direct";sessionKey="cli:direct";parentSystemPrompt;setContext(e,r,n=`${e}:${r}`,o){this.originChannel=e,this.originChatId=r,this.sessionKey=n,this.parentSystemPrompt=o}async execute(e,r){let n=e.context??"fresh",o=e.type??"general",i={task:String(e.task??""),label:e.label!=null?String(e.label):null,originChannel:this.originChannel,originChatId:this.originChatId,sessionKey:this.sessionKey,contextMode:n,agentType:o};return e.model!=null&&(i.model=String(e.model)),e.provider!=null&&(i.providerName=String(e.provider)),n==="fork"&&this.parentSystemPrompt&&(i.parentSystemPrompt=this.parentSystemPrompt),this.manager.spawn(i)}};var ke=class extends g{name="session.search";description="Search the current session's message history for content matching the query.";parameters={type:"object",properties:{query:{type:"string",description:"The search query to match against message content"},limit:{type:"integer",description:"Maximum number of results to return",minimum:1,maximum:100}},required:["query"]};sessionManager=null;sessionKey="cli:direct";constructor(){super()}setSessionManager(t){this.sessionManager=t}setContext(t){this.sessionKey=t}async execute(t,e){if(!this.sessionManager)return"Error: Session manager not available";let r=String(t.query??""),n=typeof t.limit=="number"?Math.min(Math.max(1,Math.floor(t.limit)),100):10;if(!r)return"Error: Query cannot be empty";let i=this.sessionManager.getOrCreate(this.sessionKey).search(r,n);return JSON.stringify(i,null,2)}};import jt from"node:fs";import Re from"node:path";import Bt from"node:os";import X from"node:fs";import Te from"node:path";var Tr={"gpt-4.1":1047576,"gpt-4.1-mini":1047576,"gpt-4.1-nano":1047576,"gpt-4o":128e3,"gpt-4o-mini":128e3,"gpt-4-turbo":128e3,"gpt-4":8192,"gpt-3.5-turbo":16385,"claude-sonnet-4":2e5,"claude-sonnet-4-20250514":2e5,"claude-3-5-sonnet":2e5,"claude-3-5-sonnet-20241022":2e5,"claude-3-5-haiku":2e5,"claude-3-opus":2e5,"claude-3-sonnet":2e5,"claude-3-haiku":2e5,"gemini-2.5-pro":1e6,"gemini-2.0-flash":1e6,"gemini-1.5-pro":1e6,"gemini-1.5-flash":1e6,"deepseek-chat":64e3,"deepseek-reasoner":64e3,"grok-2":131072,"grok-2-mini":131072},Ar=128e3;function Ce(s){if(!s)return 0;let t=typeof s=="string"?s:JSON.stringify(s);return Math.ceil(t.length/4)}function $t(s,t){if(t){let r=t.providers?.[t.agents.defaults.provider]?.models?.find(n=>n.id.toLowerCase()===s.toLowerCase())?.capabilities;if(r?.contextWindow)return r.contextWindow;for(let n of t.customLlmProviders??[]){let o=n.models.find(i=>i.id.toLowerCase()===s.toLowerCase());if(o?.capabilities?.contextWindow)return o.capabilities.contextWindow}}let e=s.toLowerCase();for(let[r,n]of Object.entries(Tr))if(r.toLowerCase()===e||e.includes(r.toLowerCase()))return n;return Ar}var It=1e3,Er=250,Ae=`
|
|
17
|
+
... (truncated for archival)`;function Nt(s){return Math.max(0,Math.floor(s*4))}function Rr(s,t){if(t<=0)return"";let e=Nt(t);if(s.length<=e)return s;let r=Math.max(0,e-Ae.length);return`${Ae}${s.slice(-r)}`}function Mr(s,t){if(t<=0||s.length===0)return{text:"",omittedLines:s.length};let e=Nt(t),r=[],n=0,o=0;for(let i=s.length-1;i>=0;i--){let a=s[i],l=r.length?1:0,c=e-n-l;if(c<=0){o=i+1;break}if(a.length<=c){r.unshift(a),n+=a.length+l;continue}let u=Math.max(0,c-Ae.length);r.unshift(`${Ae}${a.slice(-u)}`),n=e,o=i;break}return{text:r.join(`
|
|
18
|
+
`),omittedLines:o}}var _r=[{type:"function",function:{name:"save_memory",description:"Save the memory consolidation result to persistent storage.",parameters:{type:"object",properties:{history_entry:{type:"string"},memory_update:{type:"string"}},required:["history_entry","memory_update"]}}}];function Lr(s){let t=s.trim(),e=t.match(/^```(?:json)?\s*([\s\S]*?)```$/i);if(e?.[1])return e[1].trim();if(t.startsWith("{")&&t.endsWith("}"))return t;let r=t.indexOf("{"),n=t.lastIndexOf("}");return r!==-1&&n>r?t.slice(r,n+1).trim():null}function Pr(s){if(!s)return null;let t=Lr(s.trim());if(!t)return null;try{let e=JSON.parse(t);if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e;return r.history_entry==null&&r.memory_update==null?null:r}catch{return null}}var Y=class{memoryDir;memoryFile;historyFile;constructor(t,e){let r=Te.join(t,"memory");this.memoryDir=e?Te.join(r,e):r,X.mkdirSync(this.memoryDir,{recursive:!0}),this.memoryFile=Te.join(this.memoryDir,"MEMORY.md"),this.historyFile=Te.join(this.memoryDir,"HISTORY.md")}readLongTerm(){return X.existsSync(this.memoryFile)?X.readFileSync(this.memoryFile,"utf8"):""}writeLongTerm(t){X.writeFileSync(this.memoryFile,t,"utf8")}appendHistory(t){X.appendFileSync(this.historyFile,`${t.trim()}
|
|
19
|
+
|
|
20
|
+
`,"utf8")}getMemoryContext(){let t=this.readLongTerm();return t?`## Long-term Memory
|
|
21
|
+
${t}`:""}async consolidate(t,e,r,n){let o=n?.archiveAll??!1,i=n?.memoryWindow??50,a=[],l=0;if(o)a=t.messages,l=0;else if(l=Math.floor(i/2),t.messages.length<=l||t.messages.length-t.lastConsolidated<=0||(a=t.messages.slice(t.lastConsolidated,t.messages.length-l),!a.length))return!0;let c=[],u=[];for(let h of a)h._type==="anchor"?c.push(h):u.push(h);let d=[];for(let h of c)d.push(`[ANCHOR] ${h.name}: ${h.summary??"(no summary)"}`);for(let h of u){if(!h.content&&!h._full_content)continue;let F=Array.isArray(h.tools_used)&&h.tools_used.length?` [tools: ${h.tools_used.join(", ")}]`:"",E=h._full_content??h.content;d.push(`[${String(h.timestamp??"?").slice(0,16)}] ${String(h.role).toUpperCase()}${F}: ${String(E)}`)}let m=this.readLongTerm(),p=d.join(`
|
|
22
|
+
`),f=m||"(empty)",b="## Conversation to Process",T=p,x=Ce(`Process this conversation and call the save_memory tool with your consolidation.
|
|
32
23
|
|
|
33
24
|
## Current Long-term Memory
|
|
34
25
|
|
|
35
26
|
|
|
36
27
|
## Conversation to Process
|
|
37
|
-
`),
|
|
28
|
+
`),S=Ce(m||"(empty)"),L=Ce(p),B=x+S+L,_=Math.max(1,n?.contextWindow??$t(r)),ie=Math.floor(_*.9);if(B>ie){let h=Math.max(1,ie-x),F=Math.min(S,Math.max(Er,Math.floor(h*.3))),E=Math.min(S,Math.max(0,h-It),F),I=Math.max(It,h-E);if(E<S&&(f=Rr(f,E)),I<L){let $=Mr(d,I);T=$.text,b=$.text!==p?`## Conversation to Process (truncated, most recent ${d.length-$.omittedLines} entries)`:"## Conversation to Process"}}let sr=`Process this conversation and call the save_memory tool with your consolidation. If tool calling is unavailable, respond with JSON only containing string fields named history_entry and memory_update.
|
|
38
29
|
|
|
39
30
|
## Current Long-term Memory
|
|
40
|
-
${
|
|
31
|
+
${f}
|
|
41
32
|
|
|
42
|
-
${
|
|
43
|
-
${
|
|
33
|
+
${b}
|
|
34
|
+
${T}`;try{let h=async P=>{let ct=await e.chat({model:r,messages:[{role:"system",content:"You are a memory consolidation agent. Call the save_memory tool. If tool calling is unavailable, respond with JSON only containing string fields named history_entry and memory_update."},{role:"user",content:sr}],...P?{tools:_r,toolChoice:"required"}:{}});return ct.toolCalls[0]?.arguments??Pr(ct.content)},F=n?.toolCallingEnabled!==!1,E=await h(F);if(!E&&F&&(E=await h(!1)),!E)return!1;let I=E.history_entry,$=E.memory_update;if(I!=null&&this.appendHistory(typeof I=="string"?I:JSON.stringify(I)),$!=null){let P=typeof $=="string"?$:JSON.stringify($);P!==m&&this.writeLongTerm(P)}let at=o?0:t.messages.length-l,lt=t.messages.slice(0,at),Ke=-1;for(let P=lt.length-1;P>=0;P--)if(lt[P]?._type==="anchor"){Ke=P;break}return Ke!==-1?t.lastConsolidated=Ke+1:t.lastConsolidated=at,!0}catch{return!1}}};import Z from"node:fs";import Q from"node:path";var Dt=/^[a-z0-9][a-z0-9-]*$/;var Ee=class{workspaceSkills;userSkills;builtinSkills;scannerConfig;scanner;constructor(t,e,r,n,o){this.workspaceSkills=Q.join(t,"skills"),this.userSkills=e??null,this.builtinSkills=r??pt("skills"),this.scannerConfig=n??null,this.scanner=o??null}listSkills(t=!0){return(t?this.getResolvedSkills().filter(r=>r.status==="available"):this.getResolvedSkills()).map(({name:r,path:n,source:o})=>({name:r,path:n,source:o}))}listResolvedSkills(){return this.getResolvedSkills().map(({content:t,metadata:e,runtimeMeta:r,...n})=>n)}loadSkill(t){let e=this.getSkillByName(t);return e?.status==="available"?e.content:null}loadSkillsForContext(t){let e=[];for(let r of t){let n=this.getSkillByName(r);if(!n){e.push(this.renderLoadFailure(r,`Skill '${r}' is not installed. ${this.getAvailableSkillsHint()}`));continue}if(n.status!=="available"){let o=n.status==="malformed"?`Skill '${r}' is malformed: ${n.reason}.`:n.status==="blocked"?`Skill '${r}' is blocked by security scanner: ${n.reason}.`:`Skill '${r}' is unavailable: ${n.reason}.`;e.push(this.renderLoadFailure(r,o));continue}e.push(`### Skill: ${r}
|
|
44
35
|
|
|
45
|
-
${this.stripFrontmatter(
|
|
36
|
+
${this.stripFrontmatter(n.content)}`)}return e.join(`
|
|
46
37
|
|
|
47
38
|
---
|
|
48
39
|
|
|
49
|
-
`)}buildSkillsSummary(){let
|
|
50
|
-
`)}getAlwaysSkills(){return this.getResolvedSkills().filter(
|
|
51
|
-
`)||
|
|
52
|
-
`)))return{frontmatter:null,error:"missing YAML frontmatter"};let
|
|
40
|
+
`)}buildSkillsSummary(){let t=this.getResolvedSkills();if(!t.length)return"";let e=n=>n.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">"),r=["<skills>"];for(let n of t)r.push(` <skill available="${n.status==="available"}" source="${e(n.source)}">`),r.push(` <name>${e(n.name)}</name>`),r.push(` <description>${e(n.description)}</description>`),r.push(` <location>${e(n.path)}</location>`),r.push(` <status>${e(n.status)}</status>`),n.reason&&r.push(` <reason>${e(n.reason)}</reason>`),r.push(" </skill>");return r.push("</skills>"),r.join(`
|
|
41
|
+
`)}getAlwaysSkills(){return this.getResolvedSkills().filter(t=>t.status==="available"&&t.always).map(t=>t.name)}getSkillMetadata(t){return this.getSkillByName(t)?.metadata??null}stripFrontmatter(t){let e=t.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);return e?t.slice(e[0].length).trim():t}getResolvedSkills(){let t=new Map;for(let{root:e,source:r}of this.getSkillRoots()){if(!Z.existsSync(e))continue;let n=Z.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name));for(let o of n){if(t.has(o.name))continue;let i=Q.join(e,o.name,"SKILL.md");Z.existsSync(i)&&t.set(o.name,this.readSkill(o.name,i,r))}}return[...t.values()].sort((e,r)=>e.name.localeCompare(r.name))}getSkillByName(t){return this.getResolvedSkills().find(e=>e.name===t)??null}getSkillRoots(){let t=[{root:this.workspaceSkills,source:"workspace"}];return this.userSkills&&t.push({root:this.userSkills,source:"user"}),t.push({root:this.builtinSkills,source:"builtin"}),t}readSkill(t,e,r){let n=Z.readFileSync(e,"utf8"),o=this.parseSkill(t,n);if(o.errors.length)return{name:t,path:e,source:r,content:n,metadata:o.metadata,runtimeMeta:{},description:o.description,status:"malformed",reason:o.errors.join("; "),always:!1};let i=this.getRequirementErrors(o.runtimeMeta),a=this.runSecurityScan(e,t);if(a&&!a.isSafe&&this.scannerConfig?.blockUnsafe)return{name:t,path:e,source:r,content:n,metadata:o.metadata,runtimeMeta:o.runtimeMeta,description:o.description,status:"blocked",reason:this.formatBlockedReason(a),always:o.always};if(a&&a.findings.length>0){let l=a.findings.map(c=>`[${c.severity}] ${c.title} (${c.category})`);console.warn(`SkillScanner: skill '${t}' has ${a.findings.length} finding(s): ${l.join("; ")}`)}return{name:t,path:e,source:r,content:n,metadata:o.metadata,runtimeMeta:o.runtimeMeta,description:o.description,status:i.length?"unavailable":"available",reason:i.length?i.join("; "):null,always:o.always}}runSecurityScan(t,e){if(!this.scannerConfig?.enabled||!this.scannerConfig.scanOnLoad||!this.scanner)return null;let r=Q.dirname(t);return this.scanner.scanSkill(r,e,{maxFileCount:this.scannerConfig.maxFileCount,maxFileSizeBytes:this.scannerConfig.maxFileSizeBytes})}formatBlockedReason(t){let e=t.findings.filter(n=>n.severity==="CRITICAL");return e.length===0?"Security scan failed":`Blocked by security scanner: ${e.map(n=>`[${n.severity}] ${n.title} (${n.category})`).join("; ")}`}parseSkill(t,e){let r=this.extractFrontmatter(e);if(!r.frontmatter)return{metadata:null,runtimeMeta:{},description:t,always:!1,errors:[r.error??"missing YAML frontmatter"]};let n=this.parseFrontmatter(r.frontmatter),o=n.metadata,i=typeof o.description=="string"&&o.description.trim()?o.description.trim():t,a=[...n.errors],l=typeof o.name=="string"?o.name.trim():"";l?l!==t?a.push(`frontmatter name '${l}' does not match directory '${t}'`):Dt.test(l)||a.push(`frontmatter name '${l}' must match ${Dt}`):a.push("missing required frontmatter field 'name'"),typeof o.description=="string"&&o.description.trim()||a.push("missing required frontmatter field 'description'");let c=this.parseRuntimeMetadata(o.metadata);a.push(...c.errors);let u=o.always;return u!==void 0&&typeof u!="boolean"&&a.push("frontmatter field 'always' must be a boolean"),{metadata:o,runtimeMeta:c.runtimeMeta,description:i,always:u??c.runtimeMeta.always??!1,errors:a}}extractFrontmatter(t){if(!(t.startsWith(`---
|
|
42
|
+
`)||t.startsWith(`---\r
|
|
43
|
+
`)))return{frontmatter:null,error:"missing YAML frontmatter"};let e=t.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/);return e?{frontmatter:e[1]??null,error:null}:{frontmatter:null,error:"unterminated YAML frontmatter"}}parseFrontmatter(t){let e={},r=[];for(let n of t.split(/\r?\n/)){let o=n.trim();if(!o)continue;let i=o.indexOf(":");if(i<=0){r.push(`invalid frontmatter line '${o}'`);continue}let a=o.slice(0,i).trim(),l=o.slice(i+1).trim();e[a]=this.parseFrontmatterValue(l)}return{metadata:e,errors:r}}parseFrontmatterValue(t){let e=t.replace(/^['"]|['"]$/g,"");return e==="true"?!0:e==="false"?!1:e}parseRuntimeMetadata(t){if(t===void 0||t==="")return{runtimeMeta:{},errors:[]};if(typeof t!="string")return{runtimeMeta:{},errors:["frontmatter field 'metadata' must be a JSON object string"]};let e;try{e=JSON.parse(t)}catch{return{runtimeMeta:{},errors:["frontmatter field 'metadata' must contain valid JSON"]}}if(!this.isRecord(e))return{runtimeMeta:{},errors:["frontmatter field 'metadata' must decode to an object"]};let r=e.everclaw??e.openclaw??{};if(!this.isRecord(r))return{runtimeMeta:{},errors:["skill metadata for 'everclaw'/'openclaw' must be an object"]};let n=[],o={};if(r.always!==void 0&&(typeof r.always!="boolean"?n.push("skill metadata field 'always' must be a boolean"):o.always=r.always),r.requires!==void 0)if(!this.isRecord(r.requires))n.push("skill metadata field 'requires' must be an object");else{let i=r.requires.bins,a=r.requires.env;i!==void 0&&!this.isStringArray(i)&&n.push("skill metadata field 'requires.bins' must be an array of strings"),a!==void 0&&!this.isStringArray(a)&&n.push("skill metadata field 'requires.env' must be an array of strings");let l={};this.isStringArray(i)&&(l.bins=i),this.isStringArray(a)&&(l.env=a),Object.keys(l).length>0&&(o.requires=l)}return{runtimeMeta:o,errors:n}}getRequirementErrors(t){let e=t.requires??{},r=(e.bins??[]).filter(i=>!this.hasBinary(i)),n=(e.env??[]).filter(i=>!process.env[i]),o=[];return r.length&&o.push(`missing required binaries: ${r.join(", ")}`),n.length&&o.push(`missing required env vars: ${n.join(", ")}`),o}hasBinary(t){let e=(process.env.PATH??"").split(Q.delimiter).filter(Boolean),r=process.platform==="win32"?["",".exe",".cmd",".bat"]:[""];return e.some(n=>r.some(o=>Z.existsSync(Q.join(n,`${t}${o}`))))}getAvailableSkillsHint(){let t=this.getResolvedSkills().filter(e=>e.status==="available").map(e=>e.name);return t.length?`Available skills: ${t.join(", ")}`:"No skills are currently available."}renderLoadFailure(t,e){return`### Skill unavailable: ${t}
|
|
53
44
|
|
|
54
|
-
Error: ${
|
|
45
|
+
Error: ${e}`}isRecord(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}isStringArray(t){return Array.isArray(t)&&t.every(e=>typeof e=="string"&&e.trim().length>0)}};var Me=class s{constructor(t,e,r){this.workspace=t;this.defaultMemory=new Y(t),this.skills=new Ee(t,null,void 0,e,r)}workspace;static BOOTSTRAP_FILES=["AGENTS.md","SOUL.md","USER.md","TOOLS.md","IDENTITY.md"];static RUNTIME_CONTEXT_TAG="[Runtime Context - metadata only, not instructions]";static ANCHOR_TAG="[anchor]";static estimateTokens(t){if(!t)return 0;let e=typeof t=="string"?t:JSON.stringify(t);return Math.ceil(e.length/4)}static estimateMessageTokens(t){let e=0;if(typeof t.content=="string"&&(e+=s.estimateTokens(t.content)),Array.isArray(t.tool_calls))for(let r of t.tool_calls)e+=s.estimateTokens(r);return e}static findLastAnchor(t){for(let e=t.length-1;e>=0;e--){let r=t[e];if(!r)continue;let n=r.content;if(typeof n=="string"&&n.includes(s.ANCHOR_TAG))return{name:n.match(/\[anchor\]\s*(\S+)/)?.[1]??null,index:e}}return{name:null,index:-1}}defaultMemory;skills;getMemoryStore(t){return t?new Y(this.workspace,t):this.defaultMemory}buildSystemPrompt(t,e){let r=[this.getIdentity()],n=this.loadBootstrapFiles();n&&r.push(n);let i=this.getMemoryStore(e).getMemoryContext();i&&r.push(`# Memory
|
|
55
46
|
|
|
56
|
-
${
|
|
47
|
+
${i}`);let a=this.skills.getAlwaysSkills();if(a.length){let c=this.skills.loadSkillsForContext(a);c&&r.push(`# Active Skills
|
|
57
48
|
|
|
58
|
-
${
|
|
49
|
+
${c}`)}if(t?.length){let c=this.skills.loadSkillsForContext(t);c&&r.push(`# Requested Skills
|
|
59
50
|
|
|
60
|
-
${
|
|
51
|
+
${c}`)}let l=this.skills.buildSkillsSummary();return l&&r.push(`# Skills
|
|
61
52
|
|
|
62
53
|
The following skills extend your capabilities. To use one, read its SKILL.md with read_file.
|
|
63
54
|
|
|
64
|
-
${
|
|
55
|
+
${l}`),r.join(`
|
|
65
56
|
|
|
66
57
|
---
|
|
67
58
|
|
|
@@ -70,29 +61,29 @@ ${Q}`);return $.join(`
|
|
|
70
61
|
You are everclaw, a helpful AI assistant.
|
|
71
62
|
|
|
72
63
|
## Runtime
|
|
73
|
-
${
|
|
64
|
+
${Bt.platform()} ${Bt.arch()}, Node ${process.version}
|
|
74
65
|
|
|
75
66
|
## Workspace
|
|
76
67
|
Your workspace is at: ${this.workspace}
|
|
77
|
-
- Long-term memory: ${
|
|
78
|
-
- History log: ${
|
|
79
|
-
- Custom skills: ${
|
|
68
|
+
- Long-term memory: ${Re.join(this.workspace,"memory","MEMORY.md")}
|
|
69
|
+
- History log: ${Re.join(this.workspace,"memory","HISTORY.md")}
|
|
70
|
+
- Custom skills: ${Re.join(this.workspace,"skills","{skill-name}","SKILL.md")}
|
|
80
71
|
|
|
81
72
|
## Guidelines
|
|
82
73
|
- State intent before tool calls, but never claim results before receiving them.
|
|
83
74
|
- Before modifying a file, read it first.
|
|
84
|
-
- Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let
|
|
75
|
+
- Ask for clarification when the request is ambiguous.`}loadBootstrapFiles(){let t=[];for(let e of s.BOOTSTRAP_FILES){let r=Re.join(this.workspace,e);jt.existsSync(r)&&t.push(`## ${e}
|
|
85
76
|
|
|
86
|
-
${
|
|
77
|
+
${jt.readFileSync(r,"utf8")}`)}return t.join(`
|
|
87
78
|
|
|
88
|
-
`)}static buildRuntimeContext(
|
|
89
|
-
${
|
|
90
|
-
`)}`}buildMessages(
|
|
91
|
-
`)}return`[${
|
|
92
|
-
Status: ${
|
|
93
|
-
`),
|
|
94
|
-
`),
|
|
95
|
-
`;return new Promise((
|
|
79
|
+
`)}static buildRuntimeContext(t,e,r){let o=[`Current Time: ${new Date().toISOString()}`];return t&&e&&(o.push(`Channel: ${t}`),o.push(`Chat ID: ${e}`)),r?.chat_type&&o.push(`Chat Type: ${r.chat_type}`),r?.bot_mentioned&&o.push("Bot Mentioned: yes"),`${s.RUNTIME_CONTEXT_TAG}
|
|
80
|
+
${o.join(`
|
|
81
|
+
`)}`}buildMessages(t){return[{role:"system",content:this.buildSystemPrompt(t.skillNames,t.memoryNamespace)},...t.history,{role:"user",content:s.buildRuntimeContext(t.channel,t.chatId,t.metadata)},{role:"user",content:t.currentMessage}]}addToolResult(t,e,r,n){return t.push({role:"tool",tool_call_id:e,name:r,content:n}),t}addAssistantMessage(t,e,r,n){let o={role:"assistant",content:e};return r?.length&&(o.tool_calls=r),n!=null&&(o.reasoning_content=n),t.push(o),t}buildNotificationContext(t){let e=t.status==="completed"?"\u2713":"\u2717";if(t.kind==="cron_completed"||t.kind==="subagent_completed"||t.kind==="subagent_failed"){let r=[`[${e}] ${t.kind==="cron_completed"?"Cron Job":"Subagent"}: ${t.label}`,`Task: ${t.originalTask}`,`Status: ${t.status}`];t.result&&r.push(`Result: ${t.result}`),t.error&&r.push(`Error: ${t.error}`);let n=t.kind==="cron_completed"?"cron job":"subagent";return r.push("",`The ${n} has finished. Acknowledge this result briefly and continue with any follow-up work if needed.`),r.join(`
|
|
82
|
+
`)}return`[${e}] Task: ${t.label}
|
|
83
|
+
Status: ${t.status}`}};var _e=class extends g{name="session.info";description="Returns information about the current session: message count, token estimate, last anchor name, and messages since last anchor.";parameters={type:"object",properties:{},required:[]};sessionManager=null;sessionKey="cli:direct";setSessionManager(t){this.sessionManager=t}setContext(t){this.sessionKey=t}async execute(t){if(!this.sessionManager)return"Error: Session manager not available";let e=this.sessionManager.getOrCreate(this.sessionKey),r=e.getHistory(1e3),n=0;for(let l of r)n+=Me.estimateMessageTokens(l);let o=e.getLastAnchor(),i=e.getMessagesSinceLastAnchor().length,a={messageCount:e.messages.length,tokenEstimate:n,lastAnchor:o?.name??null,messagesSinceAnchor:i};return JSON.stringify(a,null,2)}};var Le=class extends g{name="session.anchor";description="Create a named anchor in the session. Messages before the anchor become eligible for summarization. Anchors survive consolidation.";parameters={type:"object",properties:{name:{type:"string",description:"The name of the anchor"},summary:{type:"string",description:"Optional summary describing what happened before this anchor"}},required:["name"]};sessionManager=null;sessionKey="cli:direct";setSessionManager(t){this.sessionManager=t}setContext(t){this.sessionKey=t}async execute(t){if(!this.sessionManager)return"Error: Session manager not available";let e=String(t.name??"");if(!e)return"Error: Anchor name is required";let r=t.summary!=null?String(t.summary):void 0,o=this.sessionManager.getOrCreate(this.sessionKey).anchor(e,r);return JSON.stringify({success:!0,anchor:{name:o.name,summary:o.summary,timestamp:o.timestamp}},null,2)}};import{readFileSync as Or,existsSync as $r}from"node:fs";import{join as y}from"node:path";import Ir from"node:http";import{homedir as Nr}from"node:os";import Dr from"node:net";import Jt from"ws";var jr={existsSync:$r,readFileSync:Or},Ft=jr;var Br=Ir,Ut=Br;var Fr=1;var Jr="/tmp/chrome-debug-profile";function Ur(s){let t=s??process.platform,e=Nr(),r=y(Jr,"DevToolsActivePort");switch(t){case"darwin":return[r,y(e,"Library/Application Support/Google/Chrome/DevToolsActivePort"),y(e,"Library/Application Support/Chromium/DevToolsActivePort"),y(e,"Library/Application Support/BraveSoftware/Brave-Browser/DevToolsActivePort"),y(e,"Library/Application Support/Microsoft Edge/DevToolsActivePort"),y(e,"Library/Application Support/Vivaldi/DevToolsActivePort")];case"linux":{let n=process.env.XDG_CONFIG_HOME||y(e,".config");return[r,y(n,"google-chrome","DevToolsActivePort"),y(n,"chromium","DevToolsActivePort"),y(n,"BraveSoftware","Brave-Browser","DevToolsActivePort"),y(n,"microsoft-edge","DevToolsActivePort"),y(n,"vivaldi","DevToolsActivePort"),y(e,".config","google-chrome","DevToolsActivePort"),y(e,".config","chromium","DevToolsActivePort"),y(e,"snap","chromium","common","chromium","DevToolsActivePort"),y(e,".var","app","com.google.Chrome","config","google-chrome","DevToolsActivePort"),y(e,".var","app","org.chromium.Chromium","config","chromium","DevToolsActivePort")]}case"win32":{let n=process.env.LOCALAPPDATA||y(e,"AppData","Local");return[r,y(n,"Google","Chrome","User Data","DevToolsActivePort"),y(n,"Chromium","User Data","DevToolsActivePort"),y(n,"BraveSoftware","Brave-Browser","User Data","DevToolsActivePort"),y(n,"Microsoft","Edge","User Data","DevToolsActivePort"),y(n,"Vivaldi","User Data","DevToolsActivePort")]}default:return[]}}function Oe(s){return $e(s)?.port}function $e(s){let t=Ur(s);for(let e of t)try{if(!Ft.existsSync(e))continue;let n=Ft.readFileSync(e,"utf-8").split(`
|
|
84
|
+
`),o=n[0]?.trim(),i=n[1]?.trim()||void 0;if(o){let a=parseInt(o,10);if(a>0&&a<=65535)return{port:a,browserWsPath:i}}}catch{}}function qr(s=9222){return new Promise(t=>{let e=`http://127.0.0.1:${s}/json/version`,r=Ut.get(e,{timeout:5e3},n=>{if(n.statusCode!==200){n.resume(),t(void 0);return}let o=[];n.on("data",i=>o.push(i)),n.on("end",()=>{try{let i=Buffer.concat(o).toString("utf-8"),a=JSON.parse(i);t(a)}catch{t(void 0)}}),n.on("error",()=>t(void 0))});r.on("timeout",()=>{r.destroy(),t(void 0)}),r.on("error",()=>t(void 0))})}function Wr(s,t="127.0.0.1"){return new Promise(e=>{let r=new Dr.Socket;r.setTimeout(2e3),r.once("connect",()=>{r.destroy(),e(!0)}),r.once("timeout",()=>{r.destroy(),e(!1)}),r.once("error",()=>{e(!1)}),r.connect(s,t)})}function Gr(s){return new Promise(t=>{try{let e=new Jt(s),r=setTimeout(()=>{e.close(),t(!1)},3e3);e.on("open",()=>{clearTimeout(r),e.close(),t(!0)}),e.on("error",()=>{clearTimeout(r),t(!1)})}catch{t(!1)}})}async function qt(s=9222){let t=$e(),e=t?.port??s;if(await Wr(e)){for(let n=0;n<2;n++){try{let o=await qr(e);if(o)return{port:e,versionInfo:o}}catch{}n<1&&await new Promise(o=>setTimeout(o,500))}if(t?.browserWsPath){let n=`ws://127.0.0.1:${e}${t.browserWsPath}`;if(await Gr(n))return{port:e,versionInfo:{Browser:"Chrome","Protocol-Version":"1.3","User-Agent":"","V8-Version":"","WebKit-Version":"",webSocketDebuggerUrl:n}}}return new Promise(n=>{let o=Ut.get(`http://127.0.0.1:${e}/json/version`,{timeout:3e3},i=>{i.resume(),i.statusCode===404||i.statusCode===403?n({port:e,versionInfo:{},pendingApproval:!0}):n(void 0)});o.on("error",()=>n(void 0)),o.on("timeout",()=>{o.destroy(),n(void 0)})})}}async function ee(s){let e=$e()?.browserWsPath;if(!e)return[];let r=await Pe.connect(`ws://127.0.0.1:${s}${e}`);try{return((await r.send("Target.getTargets")).targetInfos??[]).map(i=>({id:i.targetId,type:i.type,title:i.title,url:i.url,webSocketDebuggerUrl:i.webSocketDebuggerUrl??`ws://127.0.0.1:${s}/devtools/page/${i.targetId}`}))}finally{r.close()}}async function Wt(s,t){let r=$e()?.browserWsPath;if(!r)throw new Error("No browser WebSocket path found in DevToolsActivePort");let n=await Pe.connect(`ws://127.0.0.1:${s}${r}`);try{let i=(await n.send("Target.createTarget",{url:t})).targetId;if(!i)throw new Error("Target.createTarget returned no targetId");return{id:i,type:"page",title:"",url:t,webSocketDebuggerUrl:`ws://127.0.0.1:${s}/devtools/page/${i}`}}finally{n.close()}}var Pe=class s{ws;nextId=1;pending=new Map;eventListeners=new Map;closed=!1;constructor(t){this.ws=t}static connect(t){return new Promise((e,r)=>{let n=new Jt(t);n.on("open",()=>{let o=new s(n);s.attachHandlers(o,n),e(o)}),n.on("error",(...o)=>{let i=o[0];r(new Error(`Failed to connect to CDP: ${i.message}`))})})}static fromWebSocket(t){let e=new s(t);return s.attachHandlers(e,t),e}static attachHandlers(t,e){e.on("message",r=>{let n=typeof r=="string"?r:Buffer.from(r).toString("utf-8");t.handleMessage(n)}),e.on("close",()=>{t.closed=!0;for(let[,r]of t.pending)r.reject(new Error("WebSocket closed"));t.pending.clear()}),e.on("error",(...r)=>{let n=r[0];for(let[,o]of t.pending)o.reject(n);t.pending.clear()})}async send(t,e){if(this.closed||this.ws.readyState!==Fr)throw new Error("WebSocket is closed");let r=this.nextId++,n=JSON.stringify({id:r,method:t,params:e??{}});return new Promise((o,i)=>{this.pending.set(r,{resolve:o,reject:i}),this.ws.send(n)})}onEvent(t,e){return this.eventListeners.has(t)||this.eventListeners.set(t,new Set),this.eventListeners.get(t).add(e),()=>{this.eventListeners.get(t)?.delete(e)}}waitForEvent(t,e=1e4){return new Promise((r,n)=>{let o=setTimeout(()=>{i(),n(new Error(`Timeout waiting for event '${t}' after ${e}ms`))},e),i=this.onEvent(t,a=>{clearTimeout(o),i(),r(a)})})}close(){if(!this.closed){this.closed=!0;try{this.ws.close()}catch{}}}handleMessage(t){let e;try{e=JSON.parse(t)}catch{return}if("id"in e&&typeof e.id=="number"){let r=e,n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(`CDP error ${r.error.code}: ${r.error.message}`)):n.resolve(r.result??{}));return}if("method"in e&&typeof e.method=="string"){let r=e,n=this.eventListeners.get(r.method);if(n)for(let o of n)try{o(r.params??{})}catch{}}}};import{spawn as Kr}from"node:child_process";import{createConnection as Hr}from"node:net";import{tmpdir as Vr}from"node:os";import{join as Kt,dirname as zr}from"node:path";import{unlink as Xr,unlinkSync as Yr,mkdirSync as Zr,existsSync as Ie}from"node:fs";import j from"node:fs";function et(s){let t="electron"in process.versions,e=s;try{e=j.realpathSync(s)}catch{}let r,n;if(e.endsWith(".js")){if(!j.existsSync(e))throw new Error(`No executable found: ${e} does not exist.`);r=e,n=!1}else if(e.endsWith(".ts")){if(!j.existsSync(e))throw new Error(`No executable found: ${e} does not exist.`);r=e,n=!0}else{let a=e+".js",l=e+".ts";if(j.existsSync(a)){try{r=j.realpathSync(a)}catch{r=a}n=!1}else if(j.existsSync(l)){try{r=j.realpathSync(l)}catch{r=l}n=!0}else throw new Error(`No executable found: neither ${a} nor ${l} exists.`)}let o=process.execPath,i=n?["--import","tsx",r]:[r];return t?{file:o,args:i,env:{...process.env,ELECTRON_RUN_AS_NODE:"1"}}:{file:o,args:i,env:process.env}}var Qr=null,en=null,tn=null,rn=!1;function te(){return en??process.platform}function nn(){return Qr??Kr}function on(){return tn??Hr}function sn(s,t){let e=te(),r=t??Vr(),n=s.replace(/[^a-zA-Z0-9]/g,"_").slice(0,32);return e==="win32"?`\\\\.\\pipe\\airclaw-daemon-${n}`:Kt(r,`airclaw-daemon-${n}.sock`)}function Gt(s,t){let e=s.split(`
|
|
85
|
+
`),r=e.pop()??"";for(let n of e){let o=n.trim();if(o)try{let i=JSON.parse(o);t(i)}catch{}}return r}var Ne=class s{static instance=null;daemons=new Map;constructor(){}static getInstance(){return s.instance||(s.instance=new s),s.instance}async getOrCreateDaemon(t,e,r){if(this.daemons.has(t))return;let n=sn(t,r?.socketDir),o=r?.idleTimeoutMs??12e5;if(te()==="win32"||Ie(n)){let p={targetId:t,child:null,socketPath:n,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};this.daemons.set(t,p);try{await this.connectToDaemon(t);return}catch{if(this.daemons.delete(t),te()!=="win32"&&Ie(n))try{Yr(n)}catch{}}}let i=zr(n);if(!Ie(i)&&te()!=="win32")try{Zr(i,{recursive:!0})}catch{}let a={targetId:t,child:null,socketPath:n,clientSocket:null,commandId:1,pendingCommands:new Map,ndjsonBuffer:""};if(this.daemons.set(t,a),rn)return;let l=Kt(import.meta.dirname,"daemon-worker"),{file:c,args:u,env:d}=et(l),m=nn()(c,[...u,"--target",t,"--ws-url",e,"--socket",n,"--idle-timeout",String(o)],{stdio:["ignore","pipe","pipe"],detached:!1,env:d});a.child=m,m.on("exit",()=>{this.cleanupDaemon(t)}),m.on("error",()=>{this.cleanupDaemon(t)}),await new Promise((p,f)=>{let b=setTimeout(()=>{f(new Error("Daemon startup timeout"))},1e4),T=x=>{x.toString("utf8").includes("READY")&&(clearTimeout(b),m.stdout?.off("data",T),p())};m.stdout?.on("data",T)}),await this.connectToDaemon(t)}async connectToDaemon(t){let e=this.daemons.get(t);if(!e)throw new Error(`No daemon for target ${t}`);return new Promise((r,n)=>{let o=on()(e.socketPath);o.on("connect",()=>{e.clientSocket=o,o.on("data",i=>{e.ndjsonBuffer=Gt(e.ndjsonBuffer+i.toString("utf8"),a=>{let l=e.pendingCommands.get(a.id);l&&(e.pendingCommands.delete(a.id),l.resolve(a))})}),o.on("close",()=>{e.clientSocket=null;for(let[,i]of e.pendingCommands)i.reject(new Error("Daemon socket closed"));e.pendingCommands.clear()}),o.on("error",()=>{}),r()}),o.on("error",i=>{n(new Error(`Failed to connect to daemon: ${i.message}`))}),setTimeout(()=>{e.clientSocket||(o.destroy(),n(new Error("Daemon connection timeout")))},5e3)})}async sendCommand(t,e,r={}){let n=this.daemons.get(t);if(!n)throw new Error(`No daemon for target ${t}`);if(!n.clientSocket)throw new Error(`Daemon socket not connected for ${t}`);let o=n.commandId++,a=JSON.stringify({id:o,cmd:e,args:r})+`
|
|
86
|
+
`;return new Promise((l,c)=>{n.pendingCommands.set(o,{resolve:l,reject:c});try{n.clientSocket.write(a)}catch(u){n.pendingCommands.delete(o),c(u)}setTimeout(()=>{n.pendingCommands.has(o)&&(n.pendingCommands.delete(o),c(new Error(`Command ${o} timed out`)))},3e4)})}hasDaemon(t){return this.daemons.has(t)}getSocketPath(t){return this.daemons.get(t)?.socketPath}stopDaemon(t){let e=this.daemons.get(t);e&&(e.clientSocket&&e.clientSocket.destroy(),e.child&&e.child.kill("SIGTERM"),this.cleanupDaemon(t))}stopAll(){for(let t of this.daemons.keys())this.stopDaemon(t)}getActiveTargets(){return Array.from(this.daemons.keys())}__setClientSocket(t,e){let r=this.daemons.get(t);r&&(r.clientSocket=e,e&&(e.on("data",n=>{r.ndjsonBuffer=Gt(r.ndjsonBuffer+n.toString("utf8"),o=>{let i=r.pendingCommands.get(o.id);i&&(r.pendingCommands.delete(o.id),i.resolve(o))})}),e.on("close",()=>{r.clientSocket=null;for(let[,n]of r.pendingCommands)n.reject(new Error("Daemon socket closed"));r.pendingCommands.clear()})))}cleanupDaemon(t){let e=this.daemons.get(t);if(e){e.clientSocket&&e.clientSocket.destroy(),e.child&&e.child.kill("SIGTERM");for(let[,r]of e.pendingCommands)r.reject(new Error("Daemon stopped"));te()!=="win32"&&Ie(e.socketPath)&&Xr(e.socketPath,()=>{}),this.daemons.delete(t)}}};import{writeFileSync as an,mkdirSync as ln,existsSync as cn}from"node:fs";import{dirname as un,join as De}from"node:path";import{tmpdir as dn}from"node:os";var tt={minChromeVersion:136,daemonIdleTimeoutS:1200,targetPrefixLength:8},re=class extends g{name="chrome_session";description=`Interact with Chrome browser via Chrome DevTools Protocol (CDP).
|
|
96
87
|
|
|
97
88
|
Core Commands:
|
|
98
89
|
- status: Check Chrome connectivity, version, and remote debugging status
|
|
@@ -127,19 +118,19 @@ Examples:
|
|
|
127
118
|
- chrome_session clickxy --target "ABC123" --x 100 --y 200
|
|
128
119
|
- chrome_session type --target "ABC123" --text "Hello World"
|
|
129
120
|
- chrome_session loadall --target "ABC123" --selector "button.load-more" --interval 500
|
|
130
|
-
- chrome_session evalraw --target "ABC123" --method "Page.getTitle" --params '{}'`;parameters={type:"object",properties:{command:{type:"string",description:"The command to execute",enum:["status","list","open","stop","snap","shot","eval","html","nav","net","click","clickxy","type","loadall","evalraw"]},target:{type:"string",description:"Target ID prefix (required for page interaction commands)"},url:{type:"string",description:"URL to open (for 'open' and 'nav' commands)"},path:{type:"string",description:"File path to save screenshot (for 'shot' command)"},selector:{type:"string",description:"CSS selector for element-specific operations (for 'shot', 'html', 'click', 'loadall' commands)"},expression:{type:"string",description:"JavaScript expression to evaluate (for 'eval' command)"},depth:{type:"number",description:"Maximum depth for accessibility tree (for 'snap' command)"},timeout:{type:"number",description:"Timeout in milliseconds (for 'nav' command)"},outer:{type:"boolean",description:"Return outer HTML (default true, for 'html' command)"},x:{type:"number",description:"X coordinate in CSS pixels (for 'clickxy' command)"},y:{type:"number",description:"Y coordinate in CSS pixels (for 'clickxy' command)"},text:{type:"string",description:"Text to type at focused element (for 'type' command)"},interval:{type:"number",description:"Interval in milliseconds between clicks (for 'loadall' command, default 500)"},method:{type:"string",description:"CDP method name (for 'evalraw' command)"},params:{type:"object",description:"CDP method parameters as JSON object (for 'evalraw' command)"}},required:["command"]};config;daemonManager;commands;workspace;restrictToWorkspace;constructor(J={},_,$=!1){super();this.config={minChromeVersion:J.minChromeVersion??Z$.minChromeVersion,daemonIdleTimeoutS:J.daemonIdleTimeoutS??Z$.daemonIdleTimeoutS,targetPrefixLength:J.targetPrefixLength??Z$.targetPrefixLength,...J.stealth?{stealth:J.stealth}:{}},this.workspace=_,this.restrictToWorkspace=$,this.daemonManager=sJ.getInstance(),this.commands=new Map([["status",this.handleStatus.bind(this)],["list",this.handleList.bind(this)],["open",this.handleOpen.bind(this)],["stop",this.handleStop.bind(this)],["snap",this.handleSnap.bind(this)],["shot",this.handleShot.bind(this)],["eval",this.handleEval.bind(this)],["html",this.handleHtml.bind(this)],["nav",this.handleNav.bind(this)],["net",this.handleNet.bind(this)],["click",this.handleClick.bind(this)],["clickxy",this.handleClickxy.bind(this)],["type",this.handleType.bind(this)],["loadall",this.handleLoadall.bind(this)],["evalraw",this.handleEvalraw.bind(this)]])}async execute(J,_){let $=J.command;if(!$)return this.formatError("Missing required 'command' parameter. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw");let X=this.commands.get($);if(!X)return this.formatError(`Unknown command '${$}'. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw`);try{return await X(J,_)}catch(A){let G=A instanceof Error?A.message:String(A);return this.formatError(`Command '${$}' failed: ${G}`)}}async handleStatus(){let J=this.config,_=await T6();if(!_)return this.formatResult({available:!1,reason:"Chrome remote debugging not detected",hint:"Enable remote debugging in Chrome at chrome://inspect/#remote-debugging or launch Chrome with --remote-debugging-port=9222"});if(_.pendingApproval)return this.formatResult({available:!1,pendingApproval:!0,reason:`Chrome is listening on port ${_.port} but remote debugging approval may be required`,hint:"Look for a remote debugging approval prompt in Chrome, or quit Chrome and relaunch with: open -a 'Google Chrome' --args --remote-debugging-port=9222",port:_.port});let{port:$,versionInfo:X}=_,A=X.Browser.match(/(\w+)\/(\d+)/),G=A?.[1]??"Chrome",K=A?parseInt(A[2],10):0;if(K>0&&K<J.minChromeVersion)return this.formatResult({available:!1,reason:`Chrome version ${K} is below minimum required version ${J.minChromeVersion}`,hint:`Update Chrome to version ${J.minChromeVersion} or higher`,version:X.Browser,port:$,browser:G});return this.formatResult({available:!0,version:X.Browser,protocolVersion:X["Protocol-Version"],userAgent:X["User-Agent"],webSocketDebuggerUrl:X.webSocketDebuggerUrl,port:$,browser:G})}async handleList(){let J=l_();if(!J)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let _;try{let G=await fetch(`http://127.0.0.1:${J}/json/list`);if(G.ok)_=await G.json();else _=await a0(J)}catch{_=await a0(J)}let $=_.filter((G)=>G.type==="page"&&!G.url.startsWith("chrome://"));if($.length===0)return this.formatResult({tabs:[],message:"No open tabs found"});let X=this.config.targetPrefixLength,A=$.map((G)=>({id:G.id.slice(0,X),fullId:G.id,title:G.title,url:G.url}));return this.formatResult({tabs:A,count:A.length})}async handleOpen(J){let _=l_();if(!_)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let $=J.url??"about:blank",X=this.config.targetPrefixLength;try{let A=await fetch(`http://127.0.0.1:${_}/json/new?${$}`,{method:"PUT"});if(A.ok){let G=await A.json();return this.formatResult({success:!0,id:G.id.slice(0,X),fullId:G.id,url:G.url,message:`Opened new tab: ${G.url}`})}}catch{}try{let A=await S6(_,$);return this.formatResult({success:!0,id:A.id.slice(0,X),fullId:A.id,url:A.url,message:`Opened new tab: ${A.url}`})}catch(A){return this.formatError(`Cannot open tab via HTTP or WebSocket on port ${_}: ${A instanceof Error?A.message:String(A)}. Run 'chrome_session status' for details.`)}}async handleStop(J){let _=J.target;if(_){let A=this.daemonManager.getActiveTargets().find((G)=>G.toUpperCase().startsWith(_.toUpperCase()));if(!A)return this.formatError(`No daemon found for target prefix '${_}'`);return this.daemonManager.stopDaemon(A),this.formatResult({success:!0,target:A.slice(0,this.config.targetPrefixLength),message:`Stopped daemon for target ${A.slice(0,this.config.targetPrefixLength)}`})}let $=this.daemonManager.getActiveTargets().length;if($===0)return this.formatResult({success:!0,message:"No active daemons to stop"});return this.daemonManager.stopAll(),this.formatResult({success:!0,message:`Stopped ${$} daemon(s)`})}async handleSnap(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X={};if(J.depth!==void 0)X.depth=J.depth;let A=await this.sendDaemonCommand(_,$,"snap",X);if(!A.ok)return this.formatError(A.error??"Failed to get accessibility tree");return this.formatResult({tree:A.result?.tree,nodeCount:A.result?.nodeCount})}async handleShot(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.path,A=this.resolveScreenshotPath(X),G={};if(A)G.path=A;if(J.selector)G.selector=J.selector;let K=await this.sendDaemonCommand(_,$,"shot",G);if(!K.ok)return this.formatError(K.error??"Failed to capture screenshot");if(A&&K.result?.data)this.saveScreenshot(A,K.result.data);return this.formatResult({path:A,dpr:K.result?.dpr,viewport:K.result?.viewport,message:A?`Screenshot saved to ${A}`:"Screenshot captured (base64 data in 'data' field)",data:A?void 0:K.result?.data})}async handleEval(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.expression;if(!X)return this.formatError("Missing required 'expression' parameter");let A=await this.sendDaemonCommand(_,$,"eval",{expression:X,awaitPromise:!0});if(!A.ok)return this.formatError(A.error??"JavaScript evaluation failed");return this.formatResult({ok:!0,result:A.result?.result,type:A.result?.type,subtype:A.result?.subtype})}async handleHtml(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X={};if(J.selector)X.selector=J.selector;if(J.outer!==void 0)X.outer=J.outer;let A=await this.sendDaemonCommand(_,$,"html",X);if(!A.ok)return this.formatError(A.error??"Failed to get HTML");return this.formatResult({html:A.result?.html,selector:A.result?.selector})}async handleNav(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.url;if(!X)return this.formatError("Missing required 'url' parameter");let A={url:X};if(J.timeout!==void 0)A.timeout=J.timeout;let G=await this.sendDaemonCommand(_,$,"nav",A);if(!G.ok)return this.formatError(G.error??"Navigation failed");return this.formatResult({ok:!0,url:G.result?.url,frameId:G.result?.frameId,loaderId:G.result?.loaderId,message:G.result?.message})}async handleNet(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=await this.sendDaemonCommand(_,$,"net",{});if(!X.ok)return this.formatError(X.error??"Failed to get network timing");return this.formatResult({entries:X.result?.entries,count:X.result?.count})}async handleClick(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.selector;if(!X)return this.formatError("Missing required 'selector' parameter");let A=await this.sendDaemonCommand(_,$,"click",{selector:X});if(!A.ok)return this.formatError(A.error??"Click failed");return this.formatResult({ok:!0,selector:X,tag:A.result?.tag,text:A.result?.text,message:A.result?.message})}async handleClickxy(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.x,A=J.y;if(typeof X!=="number"||typeof A!=="number")return this.formatError("Missing required 'x' and 'y' parameters");let G=await this.sendDaemonCommand(_,$,"clickxy",{x:X,y:A});if(!G.ok)return this.formatError(G.error??"Click at coordinates failed");return this.formatResult({ok:!0,x:X,y:A,message:`Clicked at (${X}, ${A})`})}async handleType(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.text;if(!X)return this.formatError("Missing required 'text' parameter");let A=await this.sendDaemonCommand(_,$,"type",{text:X});if(!A.ok)return this.formatError(A.error??"Type failed");return this.formatResult({ok:!0,text:X,message:`Typed ${X.length} character(s)`})}async handleLoadall(J,_){let{targetId:$,wsUrl:X}=await this.resolveTarget(J.target),A=J.selector,G=J.interval??500;if(!A)return this.formatError("Missing required 'selector' parameter");let K=await this.sendDaemonCommand($,X,"loadall",{selector:A,interval:G,timeout:300000});if(!K.ok)return this.formatError(K.error??"Loadall failed");return this.formatResult({ok:!0,selector:A,clickCount:K.result?.clickCount,timedOut:K.result?.timedOut,message:K.result?.message})}async handleEvalraw(J){let{targetId:_,wsUrl:$}=await this.resolveTarget(J.target),X=J.method,A=J.params??{};if(!X)return this.formatError("Missing required 'method' parameter");let G=await this.sendDaemonCommand(_,$,"evalraw",{method:X,params:A});if(!G.ok)return this.formatError(G.error??"Raw CDP command failed");return this.formatResult({ok:!0,method:X,result:G.result?.result})}async resolveTarget(J){if(!J)throw new Error("Missing required 'target' parameter. Use 'chrome_session list' to see available targets.");let _=l_();if(!_)throw new Error("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let $;try{let Q=await fetch(`http://127.0.0.1:${_}/json/list`);if(Q.ok)$=await Q.json();else $=await a0(_)}catch{$=await a0(_)}let X=$.filter((Q)=>Q.type==="page"&&!Q.url.startsWith("chrome://")),A=J.toUpperCase(),G=X.filter((Q)=>Q.id.toUpperCase().startsWith(A));if(G.length===0)throw new Error(`No target found matching prefix '${J}'`);if(G.length>1){let Q=G.map((N)=>N.id.slice(0,this.config.targetPrefixLength)).join(", ");throw new Error(`Ambiguous prefix '${J}' matches ${G.length} targets: ${Q}`)}let K=G[0];return{targetId:K.id,wsUrl:K.webSocketDebuggerUrl}}async sendDaemonCommand(J,_,$,X){if(await this.daemonManager.getOrCreateDaemon(J,_,{idleTimeoutMs:this.config.daemonIdleTimeoutS*1000}),this.config.stealth?.enabled)await this.daemonManager.sendCommand(J,"setStealthConfig",{stealth:this.config.stealth});return this.daemonManager.sendCommand(J,$,X)}resolveScreenshotPath(J){if(!J)return;let _;if(J.startsWith("/"))_=J;else if(J.startsWith("./")||J.startsWith("../"))if(this.restrictToWorkspace&&this.workspace)_=n_(this.workspace,J);else _=n_(process.cwd(),J);else if(this.restrictToWorkspace&&this.workspace)_=n_(this.workspace,J);else _=n_(tG(),`airclaw-screenshot-${Date.now()}.png`);if(this.restrictToWorkspace&&this.workspace){if(!_.startsWith(this.workspace))throw new Error(`Screenshot path '${J}' is outside workspace (restrictToWorkspace is enabled)`)}return _}saveScreenshot(J,_){let $=sG(J);if(!aG($))oG($,{recursive:!0});let X=Buffer.from(_,"base64");rG(J,X)}formatResult(J){return JSON.stringify(J,null,2)}formatError(J){return JSON.stringify({error:J},null,2)}}class o_ extends S{relay;name="chrome_relay";description="Control Chrome browser through the relay extension. Commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach.";parameters={type:"object",properties:{command:{type:"string",enum:["list_tabs","navigate","click","type","screenshot","read","evaluate","attach","detach"],description:"The command to execute"},tabId:{type:"number",description:"Tab ID for tab-specific commands"},url:{type:"string",description:"URL to navigate to"},selector:{type:"string",description:"CSS selector for click command"},text:{type:"string",description:"Text to type"},expression:{type:"string",description:"JavaScript expression to evaluate"},format:{type:"string",description:"Screenshot format (png or jpeg)"}},required:["command"]};constructor(J){super();this.relay=J}async execute(J){let _=String(J.command??"");try{switch(_){case"list_tabs":{let $=await this.relay.listTabs();return JSON.stringify($,null,2)}case"navigate":{let $=Number(J.tabId),X=String(J.url??"");if(!$)return"Error: tabId is required";if(!X)return"Error: url is required";return await this.relay.navigate($,X),`Navigated tab ${$} to ${X}`}case"click":{let $=Number(J.tabId),X=String(J.selector??"");if(!$)return"Error: tabId is required";if(!X)return"Error: selector is required";return await this.relay.click($,X),`Clicked "${X}" in tab ${$}`}case"type":{let $=Number(J.tabId),X=String(J.text??""),A=J.selector?String(J.selector):void 0;if(!$)return"Error: tabId is required";if(!X)return"Error: text is required";return await this.relay.type($,X,A),`Typed "${X}" in tab ${$}${A?` (selector: ${A})`:""}`}case"screenshot":{let $=Number(J.tabId),X=String(J.format??"png");if(!$)return"Error: tabId is required";return`Screenshot captured: ${(await this.relay.screenshot($,X)).slice(0,100)}...`}case"read":{let $=Number(J.tabId);if(!$)return"Error: tabId is required";let X=await this.relay.evaluate($,"document.body.innerText");return JSON.stringify(X,null,2)}case"evaluate":{let $=Number(J.tabId),X=String(J.expression??"");if(!$)return"Error: tabId is required";if(!X)return"Error: expression is required";let A=await this.relay.evaluate($,X);return JSON.stringify(A,null,2)}case"attach":{let $=Number(J.tabId);if(!$)return"Error: tabId is required";return await this.relay.attachTab($),`Attached to tab ${$}`}case"detach":{let $=Number(J.tabId);if(!$)return"Error: tabId is required";return await this.relay.detachTab($),`Detached from tab ${$}`}default:return`Unknown command: ${_}. Available commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach`}}catch($){return`Error: ${$ instanceof Error?$.message:String($)}`}}}import d from"node:fs";import t0 from"node:path";import{randomUUID as eG}from"node:crypto";var JK="automations",_K="index.json";function $K(J){return J.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)}function M$(J){return t0.join(J,JK)}function w6(J){return t0.join(M$(J),_K)}function a_(J,_){return t0.join(M$(J),_)}function z$(J,_){return t0.join(a_(J,_),"rule.json")}function E$(J,_){return t0.join(a_(J,_),"script.js")}function j$(J){let _=M$(J);if(!d.existsSync(_))d.mkdirSync(_,{recursive:!0})}function s_(J){j$(J);let _=w6(J);if(!d.existsSync(_))return{rules:[]};try{let $=d.readFileSync(_,"utf-8"),X=JSON.parse($),A=!1;for(let G of X.rules){if(G.stepCount===void 0){let K=O0(J,G.id);G.stepCount=K?.steps?.length||0,A=!0}if(G.toolType===void 0){let K=O0(J,G.id);if(K?.toolType)G.toolType=K.toolType,A=!0}}if(A)t_(J,X);return X}catch{return{rules:[]}}}function t_(J,_){j$(J);let $=w6(J),X=`${$}.tmp`;d.writeFileSync(X,JSON.stringify(_,null,2)),d.renameSync(X,$)}function I6(J){return s_(J).rules}function O0(J,_){let $=z$(J,_);if(!d.existsSync($))return null;try{let X=d.readFileSync($,"utf-8"),A=JSON.parse(X),G=E$(J,_);if(d.existsSync(G))A.scriptContent=d.readFileSync(G,"utf-8");return A}catch{return null}}function x6(J,_){j$(J);let $=$K(_.name)||eG().slice(0,8),X=Date.now(),A={id:$,name:_.name,description:_.description,createdAt:X,updatedAt:X,enabled:!0,stepCount:_.steps.length,steps:_.steps,scriptPath:`automations/${$}/script.js`,tags:_.tags||[],source:_.source||"manual",..._.toolType?{toolType:_.toolType}:{},..._.variables?{variables:_.variables}:{}},G=a_(J,$);if(!d.existsSync(G))d.mkdirSync(G,{recursive:!0});let K=z$(J,$);d.writeFileSync(K,JSON.stringify(A,null,2));let Q=h6(A),N=E$(J,$);d.writeFileSync(N,Q);let R=s_(J),Y={id:A.id,name:A.name,description:A.description,enabled:A.enabled,updatedAt:A.updatedAt,stepCount:A.steps.length};if(_.toolType)Y.toolType=_.toolType;return R.rules.push(Y),t_(J,R),A}function D6(J,_,$){let X=O0(J,_);if(!X)return null;let A=Date.now(),G={...X,...$,id:X.id,createdAt:X.createdAt,updatedAt:A,stepCount:($.steps||X.steps).length},K=z$(J,_);if(d.writeFileSync(K,JSON.stringify(G,null,2)),$.steps){let R=h6(G),Y=E$(J,_);d.writeFileSync(Y,R)}let Q=s_(J),N=Q.rules.findIndex((R)=>R.id===_);if(N>=0){let R={id:G.id,name:G.name,description:G.description,enabled:G.enabled,updatedAt:G.updatedAt,stepCount:G.steps.length};if(G.toolType)R.toolType=G.toolType;Q.rules[N]=R,t_(J,Q)}return G}function v6(J,_){let $=a_(J,_);if(!d.existsSync($))return!1;d.rmSync($,{recursive:!0,force:!0});let X=s_(J),A=X.rules.length;if(X.rules=X.rules.filter((G)=>G.id!==_),X.rules.length!==A)return t_(J,X),!0;return!1}function h6(J){let _=new Date().toISOString();return`// Automation: ${J.name}
|
|
131
|
-
// Tool: ${
|
|
132
|
-
// Generated: ${
|
|
133
|
-
// Description: ${
|
|
121
|
+
- chrome_session evalraw --target "ABC123" --method "Page.getTitle" --params '{}'`;parameters={type:"object",properties:{command:{type:"string",description:"The command to execute",enum:["status","list","open","stop","snap","shot","eval","html","nav","net","click","clickxy","type","loadall","evalraw"]},target:{type:"string",description:"Target ID prefix (required for page interaction commands)"},url:{type:"string",description:"URL to open (for 'open' and 'nav' commands)"},path:{type:"string",description:"File path to save screenshot (for 'shot' command)"},selector:{type:"string",description:"CSS selector for element-specific operations (for 'shot', 'html', 'click', 'loadall' commands)"},expression:{type:"string",description:"JavaScript expression to evaluate (for 'eval' command)"},depth:{type:"number",description:"Maximum depth for accessibility tree (for 'snap' command)"},timeout:{type:"number",description:"Timeout in milliseconds (for 'nav' command)"},outer:{type:"boolean",description:"Return outer HTML (default true, for 'html' command)"},x:{type:"number",description:"X coordinate in CSS pixels (for 'clickxy' command)"},y:{type:"number",description:"Y coordinate in CSS pixels (for 'clickxy' command)"},text:{type:"string",description:"Text to type at focused element (for 'type' command)"},interval:{type:"number",description:"Interval in milliseconds between clicks (for 'loadall' command, default 500)"},method:{type:"string",description:"CDP method name (for 'evalraw' command)"},params:{type:"object",description:"CDP method parameters as JSON object (for 'evalraw' command)"}},required:["command"]};config;daemonManager;commands;workspace;restrictToWorkspace;constructor(t={},e,r=!1){super(),this.config={minChromeVersion:t.minChromeVersion??tt.minChromeVersion,daemonIdleTimeoutS:t.daemonIdleTimeoutS??tt.daemonIdleTimeoutS,targetPrefixLength:t.targetPrefixLength??tt.targetPrefixLength,...t.stealth?{stealth:t.stealth}:{}},this.workspace=e,this.restrictToWorkspace=r,this.daemonManager=Ne.getInstance(),this.commands=new Map([["status",this.handleStatus.bind(this)],["list",this.handleList.bind(this)],["open",this.handleOpen.bind(this)],["stop",this.handleStop.bind(this)],["snap",this.handleSnap.bind(this)],["shot",this.handleShot.bind(this)],["eval",this.handleEval.bind(this)],["html",this.handleHtml.bind(this)],["nav",this.handleNav.bind(this)],["net",this.handleNet.bind(this)],["click",this.handleClick.bind(this)],["clickxy",this.handleClickxy.bind(this)],["type",this.handleType.bind(this)],["loadall",this.handleLoadall.bind(this)],["evalraw",this.handleEvalraw.bind(this)]])}async execute(t,e){let r=t.command;if(!r)return this.formatError("Missing required 'command' parameter. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw");let n=this.commands.get(r);if(!n)return this.formatError(`Unknown command '${r}'. Available commands: status, list, open, stop, snap, shot, eval, html, nav, net, click, clickxy, type, loadall, evalraw`);try{return await n(t,e)}catch(o){let i=o instanceof Error?o.message:String(o);return this.formatError(`Command '${r}' failed: ${i}`)}}async handleStatus(){let t=this.config,e=await qt();if(!e)return this.formatResult({available:!1,reason:"Chrome remote debugging not detected",hint:"Enable remote debugging in Chrome at chrome://inspect/#remote-debugging or launch Chrome with --remote-debugging-port=9222"});if(e.pendingApproval)return this.formatResult({available:!1,pendingApproval:!0,reason:`Chrome is listening on port ${e.port} but remote debugging approval may be required`,hint:"Look for a remote debugging approval prompt in Chrome, or quit Chrome and relaunch with: open -a 'Google Chrome' --args --remote-debugging-port=9222",port:e.port});let{port:r,versionInfo:n}=e,o=n.Browser.match(/(\w+)\/(\d+)/),i=o?.[1]??"Chrome",a=o?parseInt(o[2],10):0;return a>0&&a<t.minChromeVersion?this.formatResult({available:!1,reason:`Chrome version ${a} is below minimum required version ${t.minChromeVersion}`,hint:`Update Chrome to version ${t.minChromeVersion} or higher`,version:n.Browser,port:r,browser:i}):this.formatResult({available:!0,version:n.Browser,protocolVersion:n["Protocol-Version"],userAgent:n["User-Agent"],webSocketDebuggerUrl:n.webSocketDebuggerUrl,port:r,browser:i})}async handleList(){let t=Oe();if(!t)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let e;try{let i=await fetch(`http://127.0.0.1:${t}/json/list`);i.ok?e=await i.json():e=await ee(t)}catch{e=await ee(t)}let r=e.filter(i=>i.type==="page"&&!i.url.startsWith("chrome://"));if(r.length===0)return this.formatResult({tabs:[],message:"No open tabs found"});let n=this.config.targetPrefixLength,o=r.map(i=>({id:i.id.slice(0,n),fullId:i.id,title:i.title,url:i.url}));return this.formatResult({tabs:o,count:o.length})}async handleOpen(t){let e=Oe();if(!e)return this.formatError("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let r=t.url??"about:blank",n=this.config.targetPrefixLength;try{let o=await fetch(`http://127.0.0.1:${e}/json/new?${r}`,{method:"PUT"});if(o.ok){let i=await o.json();return this.formatResult({success:!0,id:i.id.slice(0,n),fullId:i.id,url:i.url,message:`Opened new tab: ${i.url}`})}}catch{}try{let o=await Wt(e,r);return this.formatResult({success:!0,id:o.id.slice(0,n),fullId:o.id,url:o.url,message:`Opened new tab: ${o.url}`})}catch(o){return this.formatError(`Cannot open tab via HTTP or WebSocket on port ${e}: ${o instanceof Error?o.message:String(o)}. Run 'chrome_session status' for details.`)}}async handleStop(t){let e=t.target;if(e){let o=this.daemonManager.getActiveTargets().find(i=>i.toUpperCase().startsWith(e.toUpperCase()));return o?(this.daemonManager.stopDaemon(o),this.formatResult({success:!0,target:o.slice(0,this.config.targetPrefixLength),message:`Stopped daemon for target ${o.slice(0,this.config.targetPrefixLength)}`})):this.formatError(`No daemon found for target prefix '${e}'`)}let r=this.daemonManager.getActiveTargets().length;return r===0?this.formatResult({success:!0,message:"No active daemons to stop"}):(this.daemonManager.stopAll(),this.formatResult({success:!0,message:`Stopped ${r} daemon(s)`}))}async handleSnap(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n={};t.depth!==void 0&&(n.depth=t.depth);let o=await this.sendDaemonCommand(e,r,"snap",n);return o.ok?this.formatResult({tree:o.result?.tree,nodeCount:o.result?.nodeCount}):this.formatError(o.error??"Failed to get accessibility tree")}async handleShot(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.path,o=this.resolveScreenshotPath(n),i={};o&&(i.path=o),t.selector&&(i.selector=t.selector);let a=await this.sendDaemonCommand(e,r,"shot",i);return a.ok?(o&&a.result?.data&&this.saveScreenshot(o,a.result.data),this.formatResult({path:o,dpr:a.result?.dpr,viewport:a.result?.viewport,message:o?`Screenshot saved to ${o}`:"Screenshot captured (base64 data in 'data' field)",data:o?void 0:a.result?.data})):this.formatError(a.error??"Failed to capture screenshot")}async handleEval(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.expression;if(!n)return this.formatError("Missing required 'expression' parameter");let o=await this.sendDaemonCommand(e,r,"eval",{expression:n,awaitPromise:!0});return o.ok?this.formatResult({ok:!0,result:o.result?.result,type:o.result?.type,subtype:o.result?.subtype}):this.formatError(o.error??"JavaScript evaluation failed")}async handleHtml(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n={};t.selector&&(n.selector=t.selector),t.outer!==void 0&&(n.outer=t.outer);let o=await this.sendDaemonCommand(e,r,"html",n);return o.ok?this.formatResult({html:o.result?.html,selector:o.result?.selector}):this.formatError(o.error??"Failed to get HTML")}async handleNav(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.url;if(!n)return this.formatError("Missing required 'url' parameter");let o={url:n};t.timeout!==void 0&&(o.timeout=t.timeout);let i=await this.sendDaemonCommand(e,r,"nav",o);return i.ok?this.formatResult({ok:!0,url:i.result?.url,frameId:i.result?.frameId,loaderId:i.result?.loaderId,message:i.result?.message}):this.formatError(i.error??"Navigation failed")}async handleNet(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=await this.sendDaemonCommand(e,r,"net",{});return n.ok?this.formatResult({entries:n.result?.entries,count:n.result?.count}):this.formatError(n.error??"Failed to get network timing")}async handleClick(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.selector;if(!n)return this.formatError("Missing required 'selector' parameter");let o=await this.sendDaemonCommand(e,r,"click",{selector:n});return o.ok?this.formatResult({ok:!0,selector:n,tag:o.result?.tag,text:o.result?.text,message:o.result?.message}):this.formatError(o.error??"Click failed")}async handleClickxy(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.x,o=t.y;if(typeof n!="number"||typeof o!="number")return this.formatError("Missing required 'x' and 'y' parameters");let i=await this.sendDaemonCommand(e,r,"clickxy",{x:n,y:o});return i.ok?this.formatResult({ok:!0,x:n,y:o,message:`Clicked at (${n}, ${o})`}):this.formatError(i.error??"Click at coordinates failed")}async handleType(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.text;if(!n)return this.formatError("Missing required 'text' parameter");let o=await this.sendDaemonCommand(e,r,"type",{text:n});return o.ok?this.formatResult({ok:!0,text:n,message:`Typed ${n.length} character(s)`}):this.formatError(o.error??"Type failed")}async handleLoadall(t,e){let{targetId:r,wsUrl:n}=await this.resolveTarget(t.target),o=t.selector,i=t.interval??500;if(!o)return this.formatError("Missing required 'selector' parameter");let a=await this.sendDaemonCommand(r,n,"loadall",{selector:o,interval:i,timeout:3e5});return a.ok?this.formatResult({ok:!0,selector:o,clickCount:a.result?.clickCount,timedOut:a.result?.timedOut,message:a.result?.message}):this.formatError(a.error??"Loadall failed")}async handleEvalraw(t){let{targetId:e,wsUrl:r}=await this.resolveTarget(t.target),n=t.method,o=t.params??{};if(!n)return this.formatError("Missing required 'method' parameter");let i=await this.sendDaemonCommand(e,r,"evalraw",{method:n,params:o});return i.ok?this.formatResult({ok:!0,method:n,result:i.result?.result}):this.formatError(i.error??"Raw CDP command failed")}async resolveTarget(t){if(!t)throw new Error("Missing required 'target' parameter. Use 'chrome_session list' to see available targets.");let e=Oe();if(!e)throw new Error("Chrome remote debugging not detected. Run 'chrome_session status' for details.");let r;try{let l=await fetch(`http://127.0.0.1:${e}/json/list`);l.ok?r=await l.json():r=await ee(e)}catch{r=await ee(e)}let n=r.filter(l=>l.type==="page"&&!l.url.startsWith("chrome://")),o=t.toUpperCase(),i=n.filter(l=>l.id.toUpperCase().startsWith(o));if(i.length===0)throw new Error(`No target found matching prefix '${t}'`);if(i.length>1){let l=i.map(c=>c.id.slice(0,this.config.targetPrefixLength)).join(", ");throw new Error(`Ambiguous prefix '${t}' matches ${i.length} targets: ${l}`)}let a=i[0];return{targetId:a.id,wsUrl:a.webSocketDebuggerUrl}}async sendDaemonCommand(t,e,r,n){return await this.daemonManager.getOrCreateDaemon(t,e,{idleTimeoutMs:this.config.daemonIdleTimeoutS*1e3}),this.config.stealth?.enabled&&await this.daemonManager.sendCommand(t,"setStealthConfig",{stealth:this.config.stealth}),this.daemonManager.sendCommand(t,r,n)}resolveScreenshotPath(t){if(!t)return;let e;if(t.startsWith("/")?e=t:t.startsWith("./")||t.startsWith("../")?this.restrictToWorkspace&&this.workspace?e=De(this.workspace,t):e=De(process.cwd(),t):this.restrictToWorkspace&&this.workspace?e=De(this.workspace,t):e=De(dn(),`airclaw-screenshot-${Date.now()}.png`),this.restrictToWorkspace&&this.workspace&&!e.startsWith(this.workspace))throw new Error(`Screenshot path '${t}' is outside workspace (restrictToWorkspace is enabled)`);return e}saveScreenshot(t,e){let r=un(t);cn(r)||ln(r,{recursive:!0});let n=Buffer.from(e,"base64");an(t,n)}formatResult(t){return JSON.stringify(t,null,2)}formatError(t){return JSON.stringify({error:t},null,2)}};var ne=class extends g{constructor(e){super();this.relay=e}relay;name="chrome_relay";description="Control Chrome browser through the relay extension. Commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach.";parameters={type:"object",properties:{command:{type:"string",enum:["list_tabs","navigate","click","type","screenshot","read","evaluate","attach","detach"],description:"The command to execute"},tabId:{type:"number",description:"Tab ID for tab-specific commands"},url:{type:"string",description:"URL to navigate to"},selector:{type:"string",description:"CSS selector for click command"},text:{type:"string",description:"Text to type"},expression:{type:"string",description:"JavaScript expression to evaluate"},format:{type:"string",description:"Screenshot format (png or jpeg)"}},required:["command"]};async execute(e){let r=String(e.command??"");try{switch(r){case"list_tabs":{let n=await this.relay.listTabs();return JSON.stringify(n,null,2)}case"navigate":{let n=Number(e.tabId),o=String(e.url??"");return n?o?(await this.relay.navigate(n,o),`Navigated tab ${n} to ${o}`):"Error: url is required":"Error: tabId is required"}case"click":{let n=Number(e.tabId),o=String(e.selector??"");return n?o?(await this.relay.click(n,o),`Clicked "${o}" in tab ${n}`):"Error: selector is required":"Error: tabId is required"}case"type":{let n=Number(e.tabId),o=String(e.text??""),i=e.selector?String(e.selector):void 0;return n?o?(await this.relay.type(n,o,i),`Typed "${o}" in tab ${n}${i?` (selector: ${i})`:""}`):"Error: text is required":"Error: tabId is required"}case"screenshot":{let n=Number(e.tabId),o=String(e.format??"png");return n?`Screenshot captured: ${(await this.relay.screenshot(n,o)).slice(0,100)}...`:"Error: tabId is required"}case"read":{let n=Number(e.tabId);if(!n)return"Error: tabId is required";let o=await this.relay.evaluate(n,"document.body.innerText");return JSON.stringify(o,null,2)}case"evaluate":{let n=Number(e.tabId),o=String(e.expression??"");if(!n)return"Error: tabId is required";if(!o)return"Error: expression is required";let i=await this.relay.evaluate(n,o);return JSON.stringify(i,null,2)}case"attach":{let n=Number(e.tabId);return n?(await this.relay.attachTab(n),`Attached to tab ${n}`):"Error: tabId is required"}case"detach":{let n=Number(e.tabId);return n?(await this.relay.detachTab(n),`Detached from tab ${n}`):"Error: tabId is required"}default:return`Unknown command: ${r}. Available commands: list_tabs, navigate, click, type, screenshot, read, evaluate, attach, detach`}}catch(n){return`Error: ${n instanceof Error?n.message:String(n)}`}}};import w from"node:fs";import oe from"node:path";import{randomUUID as mn}from"node:crypto";var gn="automations",pn="index.json";function fn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,50)}function rt(s){return oe.join(s,gn)}function Ht(s){return oe.join(rt(s),pn)}function je(s,t){return oe.join(rt(s),t)}function nt(s,t){return oe.join(je(s,t),"rule.json")}function ot(s,t){return oe.join(je(s,t),"script.js")}function st(s){let t=rt(s);w.existsSync(t)||w.mkdirSync(t,{recursive:!0})}function Be(s){st(s);let t=Ht(s);if(!w.existsSync(t))return{rules:[]};try{let e=w.readFileSync(t,"utf-8"),r=JSON.parse(e),n=!1;for(let o of r.rules){if(o.stepCount===void 0){let i=G(s,o.id);o.stepCount=i?.steps?.length||0,n=!0}if(o.toolType===void 0){let i=G(s,o.id);i?.toolType&&(o.toolType=i.toolType,n=!0)}}return n&&Fe(s,r),r}catch{return{rules:[]}}}function Fe(s,t){st(s);let e=Ht(s),r=`${e}.tmp`;w.writeFileSync(r,JSON.stringify(t,null,2)),w.renameSync(r,e)}function Vt(s){return Be(s).rules}function G(s,t){let e=nt(s,t);if(!w.existsSync(e))return null;try{let r=w.readFileSync(e,"utf-8"),n=JSON.parse(r),o=ot(s,t);return w.existsSync(o)&&(n.scriptContent=w.readFileSync(o,"utf-8")),n}catch{return null}}function zt(s,t){st(s);let e=fn(t.name)||mn().slice(0,8),r=Date.now(),n={id:e,name:t.name,description:t.description,createdAt:r,updatedAt:r,enabled:!0,stepCount:t.steps.length,steps:t.steps,scriptPath:`automations/${e}/script.js`,tags:t.tags||[],source:t.source||"manual",...t.toolType?{toolType:t.toolType}:{},...t.variables?{variables:t.variables}:{}},o=je(s,e);w.existsSync(o)||w.mkdirSync(o,{recursive:!0});let i=nt(s,e);w.writeFileSync(i,JSON.stringify(n,null,2));let a=Zt(n),l=ot(s,e);w.writeFileSync(l,a);let c=Be(s),u={id:n.id,name:n.name,description:n.description,enabled:n.enabled,updatedAt:n.updatedAt,stepCount:n.steps.length};return t.toolType&&(u.toolType=t.toolType),c.rules.push(u),Fe(s,c),n}function Xt(s,t,e){let r=G(s,t);if(!r)return null;let n=Date.now(),o={...r,...e,id:r.id,createdAt:r.createdAt,updatedAt:n,stepCount:(e.steps||r.steps).length},i=nt(s,t);if(w.writeFileSync(i,JSON.stringify(o,null,2)),e.steps){let c=Zt(o),u=ot(s,t);w.writeFileSync(u,c)}let a=Be(s),l=a.rules.findIndex(c=>c.id===t);if(l>=0){let c={id:o.id,name:o.name,description:o.description,enabled:o.enabled,updatedAt:o.updatedAt,stepCount:o.steps.length};o.toolType&&(c.toolType=o.toolType),a.rules[l]=c,Fe(s,a)}return o}function Yt(s,t){let e=je(s,t);if(!w.existsSync(e))return!1;w.rmSync(e,{recursive:!0,force:!0});let r=Be(s),n=r.rules.length;return r.rules=r.rules.filter(o=>o.id!==t),r.rules.length!==n?(Fe(s,r),!0):!1}function Zt(s){let t=new Date().toISOString();return`// Automation: ${s.name}
|
|
122
|
+
// Tool: ${s.toolType??"auto-detect"}
|
|
123
|
+
// Generated: ${t}
|
|
124
|
+
// Description: ${s.description}
|
|
134
125
|
//
|
|
135
126
|
// Steps:
|
|
136
|
-
${
|
|
127
|
+
${s.steps.map(e=>`// ${e.order}. ${e.description}`).join(`
|
|
137
128
|
`)}
|
|
138
129
|
//
|
|
139
130
|
// Usage: node script.js [--port=6767]
|
|
140
131
|
|
|
141
132
|
const PORT = process.argv.find(a => a.startsWith('--port='))?.split('=')[1] ?? '6767';
|
|
142
|
-
const URL = \`http://127.0.0.1:\${PORT}/api/automations/${
|
|
133
|
+
const URL = \`http://127.0.0.1:\${PORT}/api/automations/${s.id}/run\`;
|
|
143
134
|
|
|
144
135
|
fetch(URL, { method: 'POST' })
|
|
145
136
|
.then(r => r.json())
|
|
@@ -148,38 +139,38 @@ fetch(URL, { method: 'POST' })
|
|
|
148
139
|
else console.error('Failed:', r.error);
|
|
149
140
|
})
|
|
150
141
|
.catch(e => console.error('Could not reach everclaw:', e.message));
|
|
151
|
-
`}var
|
|
152
|
-
`)}}return
|
|
153
|
-
`)}async resolveTabContext(){if(!this.browserTool)return{};let
|
|
154
|
-
`);return{kind:"error",content:`Security: Tool call blocked. The tool '${
|
|
142
|
+
`}var Qt={chrome_session:{navigate:"nav",click:"click",type:"type",screenshot:"shot",read:"snap",eval:"eval"},chrome_relay:{navigate:"navigate",click:"click",type:"type",screenshot:"screenshot",read:"read",eval:"evaluate"}},se=s=>new Promise(t=>setTimeout(t,s)),Je=class extends g{constructor(e,r,n){super();this.browserTool=r;this.stealthConfig=n;this.workspace=St(e)}browserTool;stealthConfig;name="automation";description="Manage browser automation workflows. Commands: list, get, save, delete, run.";parameters={type:"object",properties:{command:{type:"string",enum:["list","get","save","delete","run"],description:"The command to execute"},id:{type:"string",description:"Automation ID (for get, delete, run)"},name:{type:"string",description:"Automation name (for save)"},description:{type:"string",description:"Brief description (for save)"},steps:{type:"array",items:{type:"object",properties:{order:{type:"number"},action:{type:"string"},target:{type:"string"},value:{type:"string"},description:{type:"string"},optional:{type:"boolean"},assert:{type:"object",properties:{check:{type:"string",enum:["selector_exists","selector_text","url_contains","eval_truthy"]},value:{type:"string"},expected:{type:"string"},timeoutMs:{type:"number"}}},retries:{type:"number"},retryDelayMs:{type:"number"}}},description:"Automation steps (for save)"},tags:{type:"array",items:{type:"string"},description:"Optional tags (for save)"},enabled:{type:"boolean",description:"Enable/disable (for save)"},variables:{type:"object",description:'Variable overrides for run command (e.g., {"USERNAME": "user"})'}},required:["command"]};workspace;async execute(e,r){let n=String(e.command??"");try{switch(n){case"list":{let o=Vt(this.workspace);return JSON.stringify(o,null,2)}case"get":{let o=String(e.id??"");if(!o)return"Error: id is required for get command";let i=G(this.workspace,o);return i?JSON.stringify(i,null,2):`Error: Automation '${o}' not found`}case"save":{let o=e.id?String(e.id):void 0,i=String(e.name??"Untitled Automation"),a=String(e.description??""),l=e.steps||[],c=e.tags||[];if(l.length===0)return"Error: At least one step is required";let u=this.browserTool?.name,d;if(o){let m={name:i,description:a,steps:l,tags:c};return u&&(m.toolType=u),d=Xt(this.workspace,o,m),d?`Updated automation '${d.name}' (${d.id})`:`Error: Automation '${o}' not found for update`}else{let m={name:i,description:a,steps:l,tags:c,source:"conversation"};return u&&(m.toolType=u),d=zt(this.workspace,m),`Created automation '${d.name}' (${d.id})`}}case"delete":{let o=String(e.id??"");return o?Yt(this.workspace,o)?`Deleted automation '${o}'`:`Error: Automation '${o}' not found or could not be deleted`:"Error: id is required for delete command"}case"run":{let o=String(e.id??"");if(!o)return"Error: id is required for run command";let i=G(this.workspace,o);if(!i)return`Error: Automation '${o}' not found`;if(!i.enabled)return`Error: Automation '${i.name}' is disabled`;let a=e.variables;return this.executeAutomation(i,r?.signal,a)}default:return`Unknown command: ${n}. Available commands: list, get, save, delete, run`}}catch(o){return`Error: ${o instanceof Error?o.message:String(o)}`}}async executeAutomation(e,r,n){if(!this.browserTool)return"Error: No browser tool available. Enable chrome_session or chrome_relay to run automations.";if(e.toolType&&e.toolType!==this.browserTool.name)return`Error: Automation '${e.name}' requires ${e.toolType} but ${this.browserTool.name} is active. Change browser tool or update the automation.`;let o=[];o.push(`Running automation: ${e.name}`),o.push(`Tool: ${this.browserTool.name}`),o.push(`Steps: ${e.steps.length}`);let i=await this.resolveTabContext();if(!i.tabId&&!i.target)return"Error: Could not resolve tab context. Open a browser tab first.";let a=[...e.steps].sort((l,c)=>l.order-c.order);for(let l of a){if(r?.aborted){o.push(`Aborted at step ${l.order}`);break}l.stealth?.preDelay&&await se(l.stealth.preDelay),o.push(`[Step ${l.order}] ${l.description}`);try{let c=this.resolveStep(l,e.variables,n),u=await this.executeStepWithRetries(c,r,i),d=this.maskSensitiveValues(u,e.variables);if(o.push(` -> ${d.slice(0,200)}${d.length>200?"...":""}`),this.stealthConfig?.enabled){let[m,p]=this.stealthConfig.interStepDelay;await se(m+Math.random()*(p-m))}}catch(c){let u=c instanceof Error?c.message:String(c);if(l.optional)o.push(` -> Optional step failed (continuing): ${u}`);else return o.push(` -> FAILED: ${u}`),o.push(`Automation '${e.name}' stopped due to error.`),o.join(`
|
|
143
|
+
`)}}return o.push(`Automation '${e.name}' completed successfully.`),o.join(`
|
|
144
|
+
`)}async resolveTabContext(){if(!this.browserTool)return{};let e=this.browserTool.name;if(e==="chrome_relay"){try{let r=await this.browserTool.execute({command:"list_tabs"}),n=JSON.parse(r);if(Array.isArray(n)&&n.length>0)return{tabId:(n.find(i=>i.active)||n[0]).id}}catch{}return{}}if(e==="chrome_session"){try{let r=await this.browserTool.execute({command:"list"}),n=JSON.parse(r);if(n.tabs&&Array.isArray(n.tabs)&&n.tabs.length>0)return{target:n.tabs[0].id}}catch{}return{}}return{}}resolveStep(e,r,n){let o=l=>l&&l.replace(/\$\{(\w+)\}/g,(c,u)=>{if(n&&n[u]!==void 0)return n[u];if(r&&r[u]?.defaultValue!==void 0)return r[u].defaultValue;if(r&&r[u]?.required)throw new Error(`Required variable '${u}' not provided`);return`\${${u}}`}),i=o(e.target),a=o(e.value);return{...e,...i!==void 0?{target:i}:{},...a!==void 0?{value:a}:{}}}maskSensitiveValues(e,r){if(!r)return e;let n=e;for(let[o,i]of Object.entries(r))i.sensitive&&(n=n.replaceAll(`\${${o}}`,`[REDACTED:${o}]`));return n}async executeStepWithRetries(e,r,n){let o=1+(e.retries??0),i=e.retryDelayMs??1e3,a;for(let l=1;l<=o;l++)try{let c=await this.executeStepOnce(e,r,n);return e.assert&&await this.pollAssertion(e.assert,r,n),c}catch(c){a=c instanceof Error?c:new Error(String(c)),l<o&&await se(i)}throw a??new Error("Unknown error")}async executeStepOnce(e,r,n){if(!this.browserTool)throw new Error("No browser tool available");let o=this.browserTool.name,i=Qt[o];if(!i)throw new Error(`Unsupported browser tool: ${o}`);let a=i[e.action];if(!a)throw new Error(`Action '${e.action}' not supported by ${o}`);let l={command:a};switch(o==="chrome_relay"&&n.tabId&&(l.tabId=n.tabId),o==="chrome_session"&&n.target&&(l.target=n.target),e.action){case"navigate":l.url=e.value??e.target??"";break;case"click":l.selector=e.target??"";break;case"type":l.text=e.value??"",e.stealth?.typingSpeed&&(l.typingSpeed=e.stealth.typingSpeed);break;case"read":break;case"screenshot":e.target&&(l.selector=e.target);break;case"eval":l.expression=e.value??"";break;case"wait":let c=parseInt(e.value??"1000",10);return await se(c),`Waited ${c}ms`;default:throw new Error(`Unknown action: ${e.action}`)}return this.browserTool.execute(l,r?{signal:r}:void 0)}toExpression(e){switch(e.check){case"selector_exists":return`!!document.querySelector(${JSON.stringify(e.value)})`;case"selector_text":return`(document.querySelector(${JSON.stringify(e.value)})?.textContent?.trim() ?? "") === ${JSON.stringify(e.expected??"")}`;case"url_contains":return`window.location.href.includes(${JSON.stringify(e.value)})`;case"eval_truthy":return`!!(${e.value})`}}isAssertionPassing(e,r){try{let n=JSON.parse(e);if(r==="chrome_session"){let o=n.result;return o&&typeof o.value=="boolean"?o.value:o&&typeof o.value=="string"?o.value.length>0:o&&typeof o.value=="number"?o.value!==0:n.result===!0}return r==="chrome_relay"?n===!0:!1}catch{return!1}}async pollAssertion(e,r,n){if(!this.browserTool)throw new Error("No browser tool available");let o=e.timeoutMs??5e3,i=500,a=this.toExpression(e),l=Date.now();do{if(r?.aborted)throw new Error("Aborted during assertion");try{let c=this.browserTool.name,d=Qt[c]?.eval;if(!d)throw new Error(`Evaluation not supported by ${c}`);let m={command:d,expression:a};c==="chrome_relay"&&n.tabId&&(m.tabId=n.tabId),c==="chrome_session"&&n.target&&(m.target=n.target);let p=await this.browserTool.execute(m);if(this.isAssertionPassing(p,c))return}catch{}if(Date.now()-l>=o)break;await se(i)}while(Date.now()-l<o);throw new Error(`Assertion failed after ${o}ms: ${e.check} (${e.value})`)}};var Ue=class s{tools=new Map;guardEngine=null;register(t){this.tools.set(t.name,t)}unregister(t){return this.tools.delete(t)}clear(){this.tools.clear()}get(t){return this.tools.get(t)}getDefinitions(){return[...this.tools.values()].map(t=>t.toSchema())}get toolNames(){return[...this.tools.keys()]}setGuardEngine(t){this.guardEngine=t}getGuardEngine(){return this.guardEngine}filterByNames(t){let e=new s;e.guardEngine=this.guardEngine;for(let r of t){let n=this.tools.get(r);n&&e.register(n)}return e}excludeByNames(t){let e=new Set(t),r=new s;r.guardEngine=this.guardEngine;for(let[n,o]of this.tools)e.has(n)||r.register(o);return r}async execute(t,e,r){let n=this.tools.get(t);if(!n)return{kind:"error",content:`Error: Tool '${t}' not found. Available: ${this.toolNames.join(", ")}`,retryable:!1};try{if(v(r?.signal),this.guardEngine){let a=this.guardEngine.guard(t,e);if(a&&!a.isSafe){let l=a.findings.map(c=>` - [${c.severity}] ${c.title}: ${c.description}`).join(`
|
|
145
|
+
`);return{kind:"error",content:`Security: Tool call blocked. The tool '${t}' was denied by the security guard.
|
|
155
146
|
|
|
156
147
|
Findings:
|
|
157
|
-
${
|
|
148
|
+
${l}`,retryable:!1}}}let o=n.validateParams(e);if(o.length)return{kind:"error",content:`Error: Invalid parameters for tool '${t}': ${o.join("; ")}
|
|
158
149
|
|
|
159
|
-
[Analyze the error above and try a different approach.]`,retryable:!0};let
|
|
150
|
+
[Analyze the error above and try a different approach.]`,retryable:!0};let i=await n.execute(e,r);return v(r?.signal),i.startsWith("__TERMINAL__")?{kind:"terminal",content:i.slice(12)}:{kind:"ok",content:i}}catch(o){if(k(o))throw o;return{kind:"error",content:`Error executing ${t}: ${String(o)}
|
|
160
151
|
|
|
161
|
-
[Analyze the error above and try a different approach.]`,retryable:!0}}}}function
|
|
152
|
+
[Analyze the error above and try a different approach.]`,retryable:!0}}}};function er(s){return s.replace(/<script[\s\S]*?<\/script>/gi,"").replace(/<style[\s\S]*?<\/style>/gi,"").replace(/<[^>]+>/g,"").trim()}function hn(s){return s.replace(/[ \t]+/g," ").replace(/\n{3,}/g,`
|
|
162
153
|
|
|
163
|
-
`).trim()}function
|
|
164
|
-
`)}catch(
|
|
154
|
+
`).trim()}function yn(s){try{let t=new URL(s);return["http:","https:"].includes(t.protocol)?t.hostname?[!0,""]:[!1,"Missing domain"]:[!1,`Only http/https allowed, got '${t.protocol.replace(":","")}'`]}catch(t){return[!1,String(t)]}}var qe=class extends g{constructor(e,r=5){super();this.apiKey=e;this.maxResults=r}apiKey;maxResults;name="web_search";description="Search the web. Returns titles, URLs, and snippets.";parameters={type:"object",properties:{query:{type:"string",description:"Search query"},count:{type:"integer",minimum:1,maximum:10,description:"Results (1-10)"}},required:["query"]};async execute(e,r){let n=String(e.query??""),o=Math.min(Math.max(Number(e.count??this.maxResults),1),10),i=this.apiKey||process.env.BRAVE_API_KEY||"";if(!i)return"Error: Brave Search API key not configured. Set tools.web.search.apiKey or BRAVE_API_KEY.";try{v(r?.signal);let a=new URL("https://api.search.brave.com/res/v1/web/search");a.searchParams.set("q",n),a.searchParams.set("count",String(o));let l=await fetch(a,{headers:{Accept:"application/json","X-Subscription-Token":i},...r?.signal?{signal:r.signal}:{}});if(!l.ok)return`Error: ${l.status} ${l.statusText}`;let u=(await l.json()).web?.results??[];if(!u.length)return`No results for: ${n}`;let d=[`Results for: ${n}`,""];return u.slice(0,o).forEach((m,p)=>{d.push(`${p+1}. ${m.title??""}`),d.push(` ${m.url??""}`),m.description&&d.push(` ${m.description}`)}),d.join(`
|
|
155
|
+
`)}catch(a){if(k(a))throw a;return`Error: ${String(a)}`}}},We=class extends g{constructor(e=5e4){super();this.maxChars=e}maxChars;name="web_fetch";description="Fetch URL and extract readable content (HTML to markdown/text).";parameters={type:"object",properties:{url:{type:"string",description:"URL to fetch"},extractMode:{type:"string",enum:["markdown","text"]},maxChars:{type:"integer",minimum:100}},required:["url"]};async execute(e,r){let n=String(e.url??""),o=String(e.extractMode??"markdown"),i=Number(e.maxChars??this.maxChars),[a,l]=yn(n);if(!a)return JSON.stringify({error:`URL validation failed: ${l}`,url:n});try{v(r?.signal);let c=await fetch(n,{redirect:"follow",headers:{"User-Agent":"Mozilla/5.0"},...r?.signal?{signal:r.signal}:{}}),u=c.headers.get("content-type")||"",d="",m="raw";if(u.includes("application/json"))d=JSON.stringify(await c.json(),null,2),m="json";else{let b=await c.text();u.includes("text/html")||/^\s*<!doctype|^\s*<html/i.test(b.slice(0,256))?(d=o==="text"?er(b):hn(er(b)),m="html"):d=b}let p=d.length>i,f=p?d.slice(0,i):d;return JSON.stringify({url:n,finalUrl:c.url,status:c.status,extractor:m,truncated:p,length:f.length,text:f})}catch(c){if(k(c))throw c;return JSON.stringify({error:String(c),url:n})}}};function O(s){return bn.resolve(s.workspace)}function Ge(s){let t=O(s);return s.restrictToWorkspace?t:void 0}function vn(s){let t=[R({name:"builtin-filesystem-tools",tools:[{name:"read_file",create:e=>new fe(O(e),Ge(e))},{name:"write_file",create:e=>new he(O(e),Ge(e))},{name:"edit_file",create:e=>new ye(O(e),Ge(e))},{name:"list_dir",create:e=>new be(O(e),Ge(e))}]}),R({name:"builtin-shell-tools",tools:[{name:"exec",create:e=>new we(e.execConfig?.timeout??60,O(e),!!e.restrictToWorkspace,e.execConfig?.pathAppend??"",new D,e.rtkService,e.rtkConfig?.ultraCompact??!1)}]}),R({name:"builtin-web-tools",tools:[{name:"web_search",create:e=>new qe(e.braveApiKey??null)},{name:"web_fetch",create:()=>new We}]})];return s.bus&&t.push(R({name:"builtin-messaging-tools",tools:[{name:"message",create:e=>{if(!e.bus)throw new Error("Builtin message tool requires a message bus");let r=new Se(async n=>{e.turn?.isCurrent&&!e.turn.isCurrent()||await e.bus.publishOutbound(n)});return e.turn&&r.setContext(e.turn.channel,e.turn.chatId,e.turn.messageId),r}}]})),s.subagents&&t.push(R({name:"builtin-subagent-tools",tools:[{name:"spawn",create:e=>{if(!e.subagents)throw new Error("Builtin spawn tool requires a subagent manager");let r=new xe(e.subagents);return e.turn&&r.setContext(e.turn.channel,e.turn.chatId,e.turn.sessionKey,e.turn.systemPrompt),r}}]})),s.cronService&&t.push(R({name:"builtin-scheduler-tools",tools:[{name:"cron",create:e=>{if(!e.cronService)throw new Error("Builtin cron tool requires a cron service");let r=new pe(e.cronService);return e.turn&&r.setContext(e.turn.channel,e.turn.chatId),r}}]})),s.sessionManager&&t.push(R({name:"builtin-session-tools",tools:[{name:"session.info",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.info tool requires a session manager");let r=new _e;return r.setSessionManager(e.sessionManager),e.turn&&r.setContext(e.turn.sessionKey),r}},{name:"session.anchor",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.anchor tool requires a session manager");let r=new Le;return r.setSessionManager(e.sessionManager),e.turn&&r.setContext(e.turn.sessionKey),r}},{name:"session.search",create:e=>{if(!e.sessionManager)throw new Error("Builtin session.search tool requires a session manager");let r=new ke;return r.setSessionManager(e.sessionManager),e.turn&&r.setContext(e.turn.sessionKey),r}}]})),s.chromeSessionConfig?.enabled&&t.push(R({name:"builtin-chrome-session-tools",tools:[{name:"chrome_session",create:e=>new re(e.chromeSessionConfig,O(e),!!e.restrictToWorkspace)}]})),s.browserRelay&&t.push(R({name:"builtin-browser-relay-tools",tools:[{name:"chrome_relay",create:e=>{if(!e.browserRelay)throw new Error("Builtin chrome_relay tool requires a browser relay server");return new ne(e.browserRelay)}}]})),t.push(R({name:"builtin-automation-tools",tools:[{name:"automation",create:e=>{let r=e.browserRelay?new ne(e.browserRelay):e.chromeSessionConfig?.enabled?new re(e.chromeSessionConfig,O(e),!!e.restrictToWorkspace):void 0;return new Je(O(e),r,e.chromeSessionConfig?.stealth)}}]})),t}function Sn(s){return Et(vn(s))}function tr(s){let t=new Ue,e=Sn(s);for(let r of e.tools.values())t.register(r.contribution.create(s));return t}var nr="EVERCLAW_SUBAGENT_RESULT ";function rr(s,t){let e=new Date().toLocaleString(),r=t??"You are operating as a subagent spawned by the main agent to complete a specific task. Stay focused and concise. Complete the assigned task and report your findings.";return s?`${s}
|
|
165
156
|
|
|
166
157
|
---
|
|
167
158
|
|
|
168
159
|
# Subagent Mode
|
|
169
160
|
|
|
170
|
-
Current Time: ${
|
|
161
|
+
Current Time: ${e}
|
|
171
162
|
|
|
172
|
-
${
|
|
163
|
+
${r}`:`# Subagent
|
|
173
164
|
|
|
174
|
-
Current Time: ${
|
|
165
|
+
Current Time: ${e}
|
|
175
166
|
|
|
176
|
-
${
|
|
167
|
+
${r}`}async function or(s){let t=tr({workspace:s.workspace,restrictToWorkspace:s.restrictToWorkspace,braveApiKey:s.braveApiKey,execConfig:s.execConfig}),e=s.definition;e?.allowedTools&&e.allowedTools.length>0?t=t.filterByNames(e.allowedTools):e?.deniedTools&&e.deniedTools.length>0&&(t=t.excludeByNames(e.deniedTools));let r=e?.systemPromptSuffix,n;if(s.contextMode==="fork"&&s.existingMessages?.length){let i=r?`# Subagent Mode
|
|
177
168
|
|
|
178
|
-
${
|
|
169
|
+
${r}`:`# Subagent Mode
|
|
179
170
|
|
|
180
|
-
You are operating as a subagent spawned by the main agent to complete a specific task. Stay focused and concise. Complete the assigned task and report your findings.`;
|
|
171
|
+
You are operating as a subagent spawned by the main agent to complete a specific task. Stay focused and concise. Complete the assigned task and report your findings.`;n=s.existingMessages.map((a,l)=>l===0&&a.role==="system"&&typeof a.content=="string"?{...a,content:`${a.content}
|
|
181
172
|
|
|
182
173
|
---
|
|
183
174
|
|
|
184
|
-
${
|
|
185
|
-
`)}async function
|
|
175
|
+
${i}`}:a),n.push({role:"user",content:s.task})}else s.contextMode==="inherit-system"&&s.parentSystemPrompt?n=[{role:"system",content:rr(s.parentSystemPrompt,r)},{role:"user",content:s.task}]:n=s.existingMessages?[...s.existingMessages,{role:"user",content:s.task}]:[{role:"system",content:rr(void 0,r)},{role:"user",content:s.task}];let o="Task completed but no final response was generated.";for(let i=0;i<15;i++){v(s.signal);let a=await s.provider.chat({messages:n,tools:t.getDefinitions(),model:s.model,temperature:s.temperature,maxTokens:s.maxTokens,...s.signal?{signal:s.signal}:{}});if(v(s.signal),a.toolCalls.length){n.push({role:"assistant",content:a.content??"",tool_calls:a.toolCalls.map(l=>({id:l.id,type:"function",function:{name:l.name,arguments:JSON.stringify(l.arguments)}}))});for(let l of a.toolCalls){v(s.signal);let c=await t.execute(l.name,l.arguments,s.signal?{signal:s.signal}:{});v(s.signal);let u=typeof c=="object"&&"kind"in c?c.content??String(c):String(c);n.push({role:"tool",tool_call_id:l.id,name:l.name,content:u})}continue}o=a.content??o;break}return o}async function wn(){let s=[];for await(let t of process.stdin)s.push(typeof t=="string"?t:t.toString("utf8"));return s.join("")}function it(s){process.stdout.write(`${nr}${JSON.stringify(s)}
|
|
176
|
+
`)}async function xn(){let s=new AbortController,t=()=>s.abort();process.once("SIGTERM",t),process.once("SIGINT",t);try{let e=(await wn()).trim();if(!e)throw new Error("Missing subagent payload.");let r=JSON.parse(e),n=kt();r.providerName&&(n.agents.defaults.provider=r.providerName),r.model&&(n.agents.defaults.model=r.model);let o=At(n),i=await or({...r,provider:o,signal:s.signal});it({status:"completed",finalResult:i})}catch(e){if(s.signal.aborted||k(e)){it({status:"aborted",errorMessage:null,failureAttribution:"aborted"});return}let r=e instanceof Error?e.message:String(e);console.error(e instanceof Error&&e.stack?e.stack:r),it({status:"failed",errorMessage:r,failureAttribution:"exception"}),process.exitCode=1}finally{process.removeListener("SIGTERM",t),process.removeListener("SIGINT",t)}}xn();
|